diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/main/java/net/vidageek/crawler/PageCrawler.java b/src/main/java/net/vidageek/crawler/PageCrawler.java index eb45910..d782b10 100644 --- a/src/main/java/net/vidageek/crawler/PageCrawler.java +++ b/src/main/java/net/vidageek/crawler/PageCrawler.java @@ -1,64 +1,64 @@ /** * */ package net.vidageek.crawler; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author jonasabreu * */ public class PageCrawler { private final String beginUrl; private final Downloader downloader; public PageCrawler(final String beginUrl) { this(beginUrl, new WebDownloader()); } public PageCrawler(final String beginUrl, final Downloader downloader) { this.downloader = downloader; if (beginUrl == null) { throw new IllegalArgumentException("beginUrl cannot be null"); } if (beginUrl.trim().length() == 0) { throw new IllegalArgumentException("beginUrl cannot be empty"); } if (!beginUrl.startsWith("http://")) { throw new IllegalArgumentException("beginUrl must start with http://"); } this.beginUrl = beginUrl; } private void craw(final PageVisitor visitor, final Set<String> visitedUrls) { if (visitor == null) { throw new NullPointerException("visitor cannot be null"); } if (!visitedUrls.contains(beginUrl)) { visitedUrls.add(beginUrl); Page page = new Page(beginUrl, downloader); visitor.visit(page); List<String> links = page.getLinks(); for (String link : links) { if (visitor.followUrl(link)) { - new PageCrawler(link, downloader).craw(visitor); + new PageCrawler(link, downloader).craw(visitor, visitedUrls); } } } } public void craw(final PageVisitor visitor) { craw(visitor, new HashSet<String>()); } }
true
true
private void craw(final PageVisitor visitor, final Set<String> visitedUrls) { if (visitor == null) { throw new NullPointerException("visitor cannot be null"); } if (!visitedUrls.contains(beginUrl)) { visitedUrls.add(beginUrl); Page page = new Page(beginUrl, downloader); visitor.visit(page); List<String> links = page.getLinks(); for (String link : links) { if (visitor.followUrl(link)) { new PageCrawler(link, downloader).craw(visitor); } } } }
private void craw(final PageVisitor visitor, final Set<String> visitedUrls) { if (visitor == null) { throw new NullPointerException("visitor cannot be null"); } if (!visitedUrls.contains(beginUrl)) { visitedUrls.add(beginUrl); Page page = new Page(beginUrl, downloader); visitor.visit(page); List<String> links = page.getLinks(); for (String link : links) { if (visitor.followUrl(link)) { new PageCrawler(link, downloader).craw(visitor, visitedUrls); } } } }
diff --git a/tools/dotnet-tools-commons/src/main/java/org/sonar/dotnet/tools/commons/visualstudio/ModelFactory.java b/tools/dotnet-tools-commons/src/main/java/org/sonar/dotnet/tools/commons/visualstudio/ModelFactory.java index cc4a60442..e34e57805 100644 --- a/tools/dotnet-tools-commons/src/main/java/org/sonar/dotnet/tools/commons/visualstudio/ModelFactory.java +++ b/tools/dotnet-tools-commons/src/main/java/org/sonar/dotnet/tools/commons/visualstudio/ModelFactory.java @@ -1,607 +1,608 @@ /* * .NET tools :: Commons * Copyright (C) 2010 Jose Chillan, Alexandre Victoor and SonarSource * [email protected] * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ /* * Created on Apr 16, 2009 */ package org.sonar.dotnet.tools.commons.visualstudio; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.utils.WildcardPattern; import org.sonar.dotnet.tools.commons.DotNetToolsException; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * Utility classes for the parsing of a Visual Studio project * * @author Fabrice BELLINGARD * @author Jose CHILLAN Aug 14, 2009 */ public final class ModelFactory { private static final Logger LOG = LoggerFactory.getLogger(ModelFactory.class); /** * Pattern used to define if a project is a test project or not */ private static String testProjectNamePattern = "*.Tests"; /** * Pattern used to define if a project is an integ test project or not */ private static String integTestProjectNamePattern = null; private ModelFactory() { } /** * Sets the pattern used to define if a project is a test project or not * * @param testProjectNamePattern * the pattern */ public static void setTestProjectNamePattern(String testProjectNamePattern) { ModelFactory.testProjectNamePattern = testProjectNamePattern; } public static void setIntegTestProjectNamePattern(String testProjectNamePattern) { ModelFactory.integTestProjectNamePattern = testProjectNamePattern; } /** * Checks, whether the child directory is a subdirectory of the base directory. * * @param base * the base directory. * @param child * the suspected child directory. * @return true, if the child is a subdirectory of the base directory. * @throws IOException * if an IOError occured during the test. */ public static boolean isSubDirectory(File base, File child) { try { File baseFile = base.getCanonicalFile(); File childFile = child.getCanonicalFile(); File parentFile = childFile; // Checks recursively if "base" is one of the parent of "child" while (parentFile != null) { if (baseFile.equals(parentFile)) { return true; } parentFile = parentFile.getParentFile(); } } catch (IOException ex) { // This is false if (LOG.isDebugEnabled()) { LOG.debug(child + " is not in " + base, ex); } } return false; } /** * @param visualStudioProject * @param integTestProjectPatterns */ protected static void assessTestProject(VisualStudioProject visualStudioProject, String testProjectPatterns, String integTestProjectPatterns) { String assemblyName = visualStudioProject.getAssemblyName(); boolean testFlag = nameMatchPatterns(assemblyName, testProjectPatterns); boolean integTestFlag = nameMatchPatterns(assemblyName, integTestProjectPatterns); if (testFlag) { visualStudioProject.setUnitTest(true); if (StringUtils.isEmpty(integTestProjectPatterns)) { visualStudioProject.setIntegTest(true); } } if (integTestFlag) { visualStudioProject.setIntegTest(true); } if (testFlag || integTestFlag) { LOG.info("The project '{}' has been qualified as a test project.", visualStudioProject.getName()); } } private static boolean nameMatchPatterns(String assemblyName, String testProjectPatterns) { if (StringUtils.isEmpty(testProjectPatterns)) { return false; } String[] patterns = StringUtils.split(testProjectPatterns, ";"); boolean testFlag = false; for (int i = 0; i < patterns.length; i++) { if (WildcardPattern.create(patterns[i]).match(assemblyName)) { testFlag = true; break; } } return testFlag; } /** * Gets the solution from its folder and name. * * @param baseDirectory * the directory containing the solution * @param solutionName * the solution name * @return the generated solution * @throws IOException * @throws DotNetToolsException */ public static VisualStudioSolution getSolution(File baseDirectory, String solutionName) throws IOException, DotNetToolsException { File solutionFile = new File(baseDirectory, solutionName); return getSolution(solutionFile); } /** * @param solutionFile * the solution file * @return a new visual studio solution * @throws IOException * @throws DotNetToolsException */ public static VisualStudioSolution getSolution(File solutionFile) throws IOException, DotNetToolsException { String solutionContent = FileUtils.readFileToString(solutionFile); List<String> buildConfigurations = getBuildConfigurations(solutionContent); List<VisualStudioProject> projects = getProjects(solutionFile, solutionContent, buildConfigurations); VisualStudioSolution solution = new VisualStudioSolution(solutionFile, projects); solution.setBuildConfigurations(buildConfigurations); solution.setName(solutionFile.getName()); return solution; } private static List<String> getBuildConfigurations(String solutionContent) { // A pattern to extract the build configurations from a visual studio solution String confExtractExp = "(\tGlobalSection\\(SolutionConfigurationPlatforms\\).*?^\tEndGlobalSection$)"; Pattern confExtractPattern = Pattern.compile(confExtractExp, Pattern.MULTILINE + Pattern.DOTALL); List<String> buildConfigurations = new ArrayList<String>(); // Extracts all the projects from the solution Matcher blockMatcher = confExtractPattern.matcher(solutionContent); if (blockMatcher.find()) { String buildConfigurationBlock = blockMatcher.group(1); String buildConfExtractExp = " = (.*)\\|"; Pattern buildConfExtractPattern = Pattern.compile(buildConfExtractExp); Matcher buildConfMatcher = buildConfExtractPattern.matcher(buildConfigurationBlock); while (buildConfMatcher.find()) { String buildConfiguration = buildConfMatcher.group(1); buildConfigurations.add(buildConfiguration); } } return buildConfigurations; } /** * Gets all the projects in a solution. * * @param solutionFile * the solution file * @param solutionContent * the text content of the solution file * @return a list of projects * @throws IOException * @throws DotNetToolsException */ private static List<VisualStudioProject> getProjects(File solutionFile, String solutionContent, List<String> buildConfigurations) throws IOException, DotNetToolsException { File baseDirectory = solutionFile.getParentFile(); // A pattern to extract the projects from a visual studion solution String projectExtractExp = "(Project.*?^EndProject$)"; Pattern projectExtractPattern = Pattern.compile(projectExtractExp, Pattern.MULTILINE + Pattern.DOTALL); List<String> projectDefinitions = new ArrayList<String>(); // Extracts all the projects from the solution Matcher globalMatcher = projectExtractPattern.matcher(solutionContent); while (globalMatcher.find()) { String projectDefinition = globalMatcher.group(1); projectDefinitions.add(projectDefinition); } // This pattern extracts the projects from a Visual Studio solution String normalProjectExp = "\\s*Project\\([^\\)]*\\)\\s*=\\s*\"([^\"]*)\"\\s*,\\s*\"([^\"]*?\\.csproj)\""; String webProjectExp = "\\s*Project\\([^\\)]*\\)\\s*=\\s*\"([^\"]*).*?ProjectSection\\(WebsiteProperties\\).*?" + "Debug\\.AspNetCompiler\\.PhysicalPath\\s*=\\s*\"([^\"]*)"; Pattern projectPattern = Pattern.compile(normalProjectExp); Pattern webPattern = Pattern.compile(webProjectExp, Pattern.MULTILINE + Pattern.DOTALL); List<VisualStudioProject> result = new ArrayList<VisualStudioProject>(); for (String projectDefinition : projectDefinitions) { // Looks for project files Matcher matcher = projectPattern.matcher(projectDefinition); if (matcher.find()) { String projectName = matcher.group(1); String projectPath = StringUtils.replace(matcher.group(2), "\\", File.separatorChar + ""); File projectFile = new File(baseDirectory, projectPath); if (!projectFile.exists()) { throw new FileNotFoundException("Could not find the project file: " + projectFile); } VisualStudioProject project = getProject(projectFile, projectName, buildConfigurations); result.add(project); } else { // Searches the web project Matcher webMatcher = webPattern.matcher(projectDefinition); if (webMatcher.find()) { String projectName = webMatcher.group(1); String projectPath = webMatcher.group(2); if (projectPath.endsWith("\\")) { projectPath = StringUtils.chop(projectPath); } File projectRoot = new File(baseDirectory, projectPath); VisualStudioProject project = getWebProject(baseDirectory, projectRoot, projectName, projectDefinition); result.add(project); } } } return result; } /** * Creates a project from its file * * @param projectFile * the project file * @return the visual project if possible to define * @throws DotNetToolsException * @throws FileNotFoundException */ public static VisualStudioProject getProject(File projectFile) throws FileNotFoundException, DotNetToolsException { String projectName = projectFile.getName(); return getProject(projectFile, projectName, null); } /** * Generates a list of projects from the path of the visual studio projects files (.csproj) * * @param projectFile * the project file * @param projectName * the name of the project * @throws DotNetToolsException * @throws FileNotFoundException * if the file was not found */ public static VisualStudioProject getProject(File projectFile, String projectName, List<String> buildConfigurations) throws FileNotFoundException, DotNetToolsException { VisualStudioProject project = new VisualStudioProject(); project.setProjectFile(projectFile); project.setName(projectName); File projectDir = projectFile.getParentFile(); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // This is a workaround to avoid Xerces class-loading issues - ClassLoader savedClassloader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(xpath.getClass().getClassLoader()); + // TODO Godin: this code seems useless and prevents successful execution of tests under JDK 1.5, however we should verify that it can be safely removed + // ClassLoader savedClassloader = Thread.currentThread().getContextClassLoader(); + // Thread.currentThread().setContextClassLoader(xpath.getClass().getClassLoader()); try { // We define the namespace prefix for Visual Studio xpath.setNamespaceContext(new VisualStudioNamespaceContext()); if (buildConfigurations != null) { Map<String, File> buildConfOutputDirMap = new HashMap<String, File>(); for (String config : buildConfigurations) { XPathExpression configOutputExpression = xpath.compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'" + config + "')]/vst:OutputPath"); String configOutput = extractProjectProperty(configOutputExpression, projectFile); buildConfOutputDirMap.put(config, new File(projectDir, configOutput)); } project.setBuildConfOutputDirMap(buildConfOutputDirMap); } XPathExpression projectTypeExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:OutputType"); XPathExpression assemblyNameExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:AssemblyName"); XPathExpression rootNamespaceExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:RootNamespace"); XPathExpression debugOutputExpression = xpath.compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'Debug')]/vst:OutputPath"); XPathExpression releaseOutputExpression = xpath .compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'Release')]/vst:OutputPath"); XPathExpression silverlightExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:SilverlightApplication"); XPathExpression projectGuidExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:ProjectGuid"); // Extracts the properties of a Visual Studio Project String typeStr = extractProjectProperty(projectTypeExpression, projectFile); String silverlightStr = extractProjectProperty(silverlightExpression, projectFile); String assemblyName = extractProjectProperty(assemblyNameExpression, projectFile); String rootNamespace = extractProjectProperty(rootNamespaceExpression, projectFile); String debugOutput = extractProjectProperty(debugOutputExpression, projectFile); String releaseOutput = extractProjectProperty(releaseOutputExpression, projectFile); String projectGuid = extractProjectProperty(projectGuidExpression, projectFile); // because the GUID starts with { and ends with }, remove these characters projectGuid = projectGuid.substring(1, projectGuid.length() - 2); // Assess if the artifact is a library or an executable ArtifactType type = ArtifactType.LIBRARY; if (StringUtils.containsIgnoreCase(typeStr, "exe")) { type = ArtifactType.EXECUTABLE; } // The project is populated project.setProjectGuid(UUID.fromString(projectGuid)); project.setProjectFile(projectFile); project.setType(type); project.setDirectory(projectDir); project.setAssemblyName(assemblyName); project.setRootNamespace(rootNamespace); project.setDebugOutputDir(new File(projectDir, debugOutput)); project.setReleaseOutputDir(new File(projectDir, releaseOutput)); if (StringUtils.isNotEmpty(silverlightStr)) { project.setSilverlightProject(true); } // ??? - Thread.currentThread().setContextClassLoader(savedClassloader); + //Thread.currentThread().setContextClassLoader(savedClassloader); // Get all source files to find the assembly version // [assembly: AssemblyVersion("1.0.0.0")] Collection<SourceFile> sourceFiles = project.getSourceFiles(); project.setAssemblyVersion(findAssemblyVersion(sourceFiles)); assessTestProject(project, testProjectNamePattern, integTestProjectNamePattern); return project; } catch (XPathExpressionException xpee) { throw new DotNetToolsException("Error while processing the project " + projectFile, xpee); } finally { // Replaces the class loader after usage - Thread.currentThread().setContextClassLoader(savedClassloader); + // Thread.currentThread().setContextClassLoader(savedClassloader); } } protected static String findAssemblyVersion(Collection<SourceFile> sourceFiles) { String version = null; // first parse: in general, it's in the "Properties\AssemblyInfo.cs" for (SourceFile file : sourceFiles) { if ("assemblyinfo.cs".equalsIgnoreCase(file.getName())) { version = tryToGetVersion(file); if (version != null) { break; } } } // second parse: try to read all files for (SourceFile file : sourceFiles) { version = tryToGetVersion(file); if (version != null) { break; } } return version; } private static String tryToGetVersion(SourceFile file) { String content; try { content = org.apache.commons.io.FileUtils.readFileToString(file.getFile(), "UTF-8"); if (content.startsWith("\uFEFF") || content.startsWith("\uFFFE")) { content = content.substring(1); } Pattern p = Pattern.compile("^[^/]*\\[assembly:\\sAssemblyVersion\\(\"([^\"]*)\"\\)\\].*$", Pattern.MULTILINE); Matcher m = p.matcher(content); if (m.find()) { return m.group(1); } } catch (IOException e) { LOG.warn("Not able to read the file " + file.getFile().getAbsolutePath() + " to find project version", e); } return null; } public static VisualStudioProject getWebProject(File solutionRoot, File projectRoot, String projectName, String definition) throws FileNotFoundException { // We define the namespace prefix for Visual Studio VisualStudioProject project = new VisualStudioWebProject(); project.setName(projectName); // Extracts the properties of a Visual Studio Project String assemblyName = projectName; String rootNamespace = ""; String debugOutput = extractSolutionProperty("Debug.AspNetCompiler.TargetPath", definition); String releaseOutput = extractSolutionProperty("Release.AspNetCompiler.TargetPath", definition); // The project is populated project.setDirectory(projectRoot); project.setAssemblyName(assemblyName); project.setRootNamespace(rootNamespace); project.setDebugOutputDir(new File(solutionRoot, debugOutput)); project.setReleaseOutputDir(new File(solutionRoot, releaseOutput)); return project; } /** * Reads a property from a project * * @param string * @param definition * @return */ public static String extractSolutionProperty(String name, String definition) { String regexp = name + "\\s*=\\s*\"([^\"]*)"; Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(definition); if (matcher.find()) { return matcher.group(1); } return null; } /** * Gets the relative paths of all the files in a project, as they are defined in the .csproj file. * * @param project * the project file * @return a list of the project files */ public static List<String> getFilesPath(File project) { List<String> result = new ArrayList<String>(); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // We define the namespace prefix for Visual Studio xpath.setNamespaceContext(new VisualStudioNamespaceContext()); try { XPathExpression filesExpression = xpath.compile("/vst:Project/vst:ItemGroup/vst:Compile"); InputSource inputSource = new InputSource(new FileInputStream(project)); NodeList nodes = (NodeList) filesExpression.evaluate(inputSource, XPathConstants.NODESET); int countNodes = nodes.getLength(); for (int idxNode = 0; idxNode < countNodes; idxNode++) { Element compileElement = (Element) nodes.item(idxNode); // We filter the files String filePath = compileElement.getAttribute("Include"); if ((filePath != null) && filePath.endsWith(".cs")) { // fix tests on unix system // but should not be necessary // on windows build machines filePath = StringUtils.replace(filePath, "\\", File.separatorChar + ""); result.add(filePath); } } } catch (XPathExpressionException exception) { // Should not happen LOG.debug("xpath error", exception); } catch (FileNotFoundException exception) { // Should not happen LOG.debug("project file not found", exception); } return result; } /** * Extracts a string project data. * * @param expression * @param projectFile * @return * @throws DotNetToolsException * @throws FileNotFoundException */ private static String extractProjectProperty(XPathExpression expression, File projectFile) throws DotNetToolsException { try { FileInputStream file = new FileInputStream(projectFile); InputSource source = new InputSource(file); return expression.evaluate(source); } catch (Exception e) { throw new DotNetToolsException("Could not evaluate the expression " + expression + " on project " + projectFile, e); } } /** * A Namespace context specialized for the handling of csproj files * * @author Jose CHILLAN Sep 1, 2009 */ private static class VisualStudioNamespaceContext implements NamespaceContext { /** * Gets the namespace URI. * * @param prefix * @return */ public String getNamespaceURI(String prefix) { if (prefix == null) { throw new IllegalStateException("Null prefix"); } final String result; if ("vst".equals(prefix)) { result = "http://schemas.microsoft.com/developer/msbuild/2003"; } else if ("xml".equals(prefix)) { result = XMLConstants.XML_NS_URI; } else { result = XMLConstants.NULL_NS_URI; } return result; } // This method isn't necessary for XPath processing. public String getPrefix(String uri) { throw new UnsupportedOperationException(); } // This method isn't necessary for XPath processing either. public Iterator<?> getPrefixes(String uri) { throw new UnsupportedOperationException(); } } /** * Checks a file existence in a directory. * * @param basedir * the directory containing the file * @param fileName * the file name * @return <code>null</code> if the file doesn't exist, the file if it is found */ public static File checkFileExistence(File basedir, String fileName) { File checkedFile = new File(basedir, fileName); if (checkedFile.exists()) { return checkedFile; } return null; } }
false
true
public static VisualStudioProject getProject(File projectFile, String projectName, List<String> buildConfigurations) throws FileNotFoundException, DotNetToolsException { VisualStudioProject project = new VisualStudioProject(); project.setProjectFile(projectFile); project.setName(projectName); File projectDir = projectFile.getParentFile(); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // This is a workaround to avoid Xerces class-loading issues ClassLoader savedClassloader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(xpath.getClass().getClassLoader()); try { // We define the namespace prefix for Visual Studio xpath.setNamespaceContext(new VisualStudioNamespaceContext()); if (buildConfigurations != null) { Map<String, File> buildConfOutputDirMap = new HashMap<String, File>(); for (String config : buildConfigurations) { XPathExpression configOutputExpression = xpath.compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'" + config + "')]/vst:OutputPath"); String configOutput = extractProjectProperty(configOutputExpression, projectFile); buildConfOutputDirMap.put(config, new File(projectDir, configOutput)); } project.setBuildConfOutputDirMap(buildConfOutputDirMap); } XPathExpression projectTypeExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:OutputType"); XPathExpression assemblyNameExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:AssemblyName"); XPathExpression rootNamespaceExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:RootNamespace"); XPathExpression debugOutputExpression = xpath.compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'Debug')]/vst:OutputPath"); XPathExpression releaseOutputExpression = xpath .compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'Release')]/vst:OutputPath"); XPathExpression silverlightExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:SilverlightApplication"); XPathExpression projectGuidExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:ProjectGuid"); // Extracts the properties of a Visual Studio Project String typeStr = extractProjectProperty(projectTypeExpression, projectFile); String silverlightStr = extractProjectProperty(silverlightExpression, projectFile); String assemblyName = extractProjectProperty(assemblyNameExpression, projectFile); String rootNamespace = extractProjectProperty(rootNamespaceExpression, projectFile); String debugOutput = extractProjectProperty(debugOutputExpression, projectFile); String releaseOutput = extractProjectProperty(releaseOutputExpression, projectFile); String projectGuid = extractProjectProperty(projectGuidExpression, projectFile); // because the GUID starts with { and ends with }, remove these characters projectGuid = projectGuid.substring(1, projectGuid.length() - 2); // Assess if the artifact is a library or an executable ArtifactType type = ArtifactType.LIBRARY; if (StringUtils.containsIgnoreCase(typeStr, "exe")) { type = ArtifactType.EXECUTABLE; } // The project is populated project.setProjectGuid(UUID.fromString(projectGuid)); project.setProjectFile(projectFile); project.setType(type); project.setDirectory(projectDir); project.setAssemblyName(assemblyName); project.setRootNamespace(rootNamespace); project.setDebugOutputDir(new File(projectDir, debugOutput)); project.setReleaseOutputDir(new File(projectDir, releaseOutput)); if (StringUtils.isNotEmpty(silverlightStr)) { project.setSilverlightProject(true); } // ??? Thread.currentThread().setContextClassLoader(savedClassloader); // Get all source files to find the assembly version // [assembly: AssemblyVersion("1.0.0.0")] Collection<SourceFile> sourceFiles = project.getSourceFiles(); project.setAssemblyVersion(findAssemblyVersion(sourceFiles)); assessTestProject(project, testProjectNamePattern, integTestProjectNamePattern); return project; } catch (XPathExpressionException xpee) { throw new DotNetToolsException("Error while processing the project " + projectFile, xpee); } finally { // Replaces the class loader after usage Thread.currentThread().setContextClassLoader(savedClassloader); } }
public static VisualStudioProject getProject(File projectFile, String projectName, List<String> buildConfigurations) throws FileNotFoundException, DotNetToolsException { VisualStudioProject project = new VisualStudioProject(); project.setProjectFile(projectFile); project.setName(projectName); File projectDir = projectFile.getParentFile(); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // This is a workaround to avoid Xerces class-loading issues // TODO Godin: this code seems useless and prevents successful execution of tests under JDK 1.5, however we should verify that it can be safely removed // ClassLoader savedClassloader = Thread.currentThread().getContextClassLoader(); // Thread.currentThread().setContextClassLoader(xpath.getClass().getClassLoader()); try { // We define the namespace prefix for Visual Studio xpath.setNamespaceContext(new VisualStudioNamespaceContext()); if (buildConfigurations != null) { Map<String, File> buildConfOutputDirMap = new HashMap<String, File>(); for (String config : buildConfigurations) { XPathExpression configOutputExpression = xpath.compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'" + config + "')]/vst:OutputPath"); String configOutput = extractProjectProperty(configOutputExpression, projectFile); buildConfOutputDirMap.put(config, new File(projectDir, configOutput)); } project.setBuildConfOutputDirMap(buildConfOutputDirMap); } XPathExpression projectTypeExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:OutputType"); XPathExpression assemblyNameExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:AssemblyName"); XPathExpression rootNamespaceExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:RootNamespace"); XPathExpression debugOutputExpression = xpath.compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'Debug')]/vst:OutputPath"); XPathExpression releaseOutputExpression = xpath .compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'Release')]/vst:OutputPath"); XPathExpression silverlightExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:SilverlightApplication"); XPathExpression projectGuidExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:ProjectGuid"); // Extracts the properties of a Visual Studio Project String typeStr = extractProjectProperty(projectTypeExpression, projectFile); String silverlightStr = extractProjectProperty(silverlightExpression, projectFile); String assemblyName = extractProjectProperty(assemblyNameExpression, projectFile); String rootNamespace = extractProjectProperty(rootNamespaceExpression, projectFile); String debugOutput = extractProjectProperty(debugOutputExpression, projectFile); String releaseOutput = extractProjectProperty(releaseOutputExpression, projectFile); String projectGuid = extractProjectProperty(projectGuidExpression, projectFile); // because the GUID starts with { and ends with }, remove these characters projectGuid = projectGuid.substring(1, projectGuid.length() - 2); // Assess if the artifact is a library or an executable ArtifactType type = ArtifactType.LIBRARY; if (StringUtils.containsIgnoreCase(typeStr, "exe")) { type = ArtifactType.EXECUTABLE; } // The project is populated project.setProjectGuid(UUID.fromString(projectGuid)); project.setProjectFile(projectFile); project.setType(type); project.setDirectory(projectDir); project.setAssemblyName(assemblyName); project.setRootNamespace(rootNamespace); project.setDebugOutputDir(new File(projectDir, debugOutput)); project.setReleaseOutputDir(new File(projectDir, releaseOutput)); if (StringUtils.isNotEmpty(silverlightStr)) { project.setSilverlightProject(true); } // ??? //Thread.currentThread().setContextClassLoader(savedClassloader); // Get all source files to find the assembly version // [assembly: AssemblyVersion("1.0.0.0")] Collection<SourceFile> sourceFiles = project.getSourceFiles(); project.setAssemblyVersion(findAssemblyVersion(sourceFiles)); assessTestProject(project, testProjectNamePattern, integTestProjectNamePattern); return project; } catch (XPathExpressionException xpee) { throw new DotNetToolsException("Error while processing the project " + projectFile, xpee); } finally { // Replaces the class loader after usage // Thread.currentThread().setContextClassLoader(savedClassloader); } }
diff --git a/dist-tools/dist-tool-plugin/src/main/java/org/apache/maven/dist/tools/DistCheckSourceReleaseMojo.java b/dist-tools/dist-tool-plugin/src/main/java/org/apache/maven/dist/tools/DistCheckSourceReleaseMojo.java index 6113f0d41..89ae17e81 100644 --- a/dist-tools/dist-tool-plugin/src/main/java/org/apache/maven/dist/tools/DistCheckSourceReleaseMojo.java +++ b/dist-tools/dist-tool-plugin/src/main/java/org/apache/maven/dist/tools/DistCheckSourceReleaseMojo.java @@ -1,428 +1,428 @@ package org.apache.maven.dist.tools; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Locale; import org.apache.maven.doxia.markup.HtmlMarkup; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.doxia.sink.SinkEventAttributeSet; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.reporting.MavenReportException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * * Check presence of source-release.zip in dist repo and central repo * * @author skygo */ @Mojo( name = "check-source-release", requiresProject = false ) public class DistCheckSourceReleaseMojo extends AbstractDistCheckMojo { //Artifact metadata retrieval done y hands. private static final String DIST_AREA = "http://www.apache.org/dist/maven"; private static final String DIST_SVNPUBSUB = "https://dist.apache.org/repos/dist/release/maven"; @Override public String getOutputName() { return "dist-tool-checksourcerelease"; } @Override public String getName( Locale locale ) { return "Disttool> Source Release"; } @Override public String getDescription( Locale locale ) { return "Verification of source release"; } class DistCheckSourceRelease extends AbstractCheckResult { private List<String> central; private List<String> dist; private List<String> older; public DistCheckSourceRelease( ConfigurationLineInfo r, String version ) { super( r, version ); } private void setMissingDistSourceRelease( List<String> checkRepos ) { dist = checkRepos; } private void setMissingCentralSourceRelease( List<String> checkRepos ) { central = checkRepos; } private void setOlderSourceRelease( List<String> checkRepos ) { older = checkRepos; } } private final List<DistCheckSourceRelease> results = new LinkedList<>(); private void reportLine( Sink sink, DistCheckSourceRelease csr ) { ConfigurationLineInfo cli = csr.getConfigurationLine(); sink.tableRow(); sink.tableCell(); // shorten groupid sink.rawText( csr.getConfigurationLine().getGroupId().replaceAll( "org.apache.maven", "o.a.m" ) ); sink.tableCell_(); sink.tableCell(); sink.rawText( csr.getConfigurationLine().getArtifactId() ); sink.tableCell_(); sink.tableCell(); sink.link( cli.getMetadataFileURL( repoBaseUrl ) ); sink.rawText( csr.getVersion() ); sink.link_(); sink.tableCell_(); sink.tableCell(); sink.rawText( csr.getConfigurationLine().getReleaseFromMetadata() ); sink.tableCell_(); sink.tableCell(); sink.link( cli.getBaseURL( repoBaseUrl, "" ) ); sink.text( "artifact" ); sink.link_(); sink.text( "/" ); sink.link( cli.getVersionnedFolderURL( repoBaseUrl, csr.getVersion() ) ); sink.text( csr.getVersion() ); sink.link_(); sink.text( "/source-release" ); if ( csr.central.isEmpty() ) { iconSuccess( sink ); } else { iconWarning( sink ); } for ( String missing : csr.central ) { sink.lineBreak(); iconError( sink ); sink.rawText( missing ); } sink.tableCell_(); // dist sink.tableCell(); sink.link( cli.getDist() ); sink.text( cli.getDist().substring( DIST_AREA.length() ) ); sink.link_(); sink.text( "source-release" ); if ( csr.dist.isEmpty() ) { iconSuccess( sink ); } else { iconWarning( sink ); } StringBuilder cliMissing = new StringBuilder(); for ( String missing : csr.dist ) { sink.lineBreak(); iconError( sink ); sink.rawText( missing ); cliMissing.append( "\nwget -O " ).append( cli.getVersionnedFolderURL( repoBaseUrl, csr.getVersion() ) ). append( "/" ).append( missing ); - cliMissing.append( "\nsvn co " ).append( missing ); + cliMissing.append( "\nsvn ci " ).append( missing ); } if ( !cliMissing.toString().isEmpty() ) { sink.lineBreak(); SinkEventAttributeSet atts = new SinkEventAttributeSet(); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_START ) }, atts ); sink.text( cliMissing.toString() ); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_END ) }, null ); } sink.tableCell_(); //older sink.tableCell(); sink.link( cli.getDist() ); sink.text( cli.getDist().substring( DIST_AREA.length() ) ); sink.link_(); sink.text( "source-release" ); if ( csr.dist.isEmpty() ) { iconSuccess( sink ); } else { iconWarning( sink ); } StringBuilder cliOlder = new StringBuilder(); for ( String missing : csr.older ) { sink.lineBreak(); iconError( sink ); sink.rawText( missing ); cliOlder.append( "\nsvn rm " ).append( missing ); } if ( !cliOlder.toString().isEmpty() ) { sink.lineBreak(); SinkEventAttributeSet atts = new SinkEventAttributeSet(); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_START ) }, atts ); sink.text( cliOlder.toString() ); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_END ) }, null ); } sink.tableCell_(); sink.tableRow_(); } @Override protected void executeReport( Locale locale ) throws MavenReportException { if ( !outputDirectory.exists() ) { outputDirectory.mkdirs(); } try { this.execute(); } catch ( MojoExecutionException ex ) { throw new MavenReportException( ex.getMessage(), ex ); } Sink sink = getSink(); sink.head(); sink.title(); sink.text( "Check source release" ); sink.title_(); sink.head_(); sink.body(); sink.section1(); sink.paragraph(); sink.text( "Check Source Release" + " (= artifactId + version + '-source-release.zip[.asc|.md5]') availability in:" ); sink.paragraph_(); sink.paragraph(); sink.text( "cli command and olders artifact exploration is Work In Progress" ); sink.paragraph_(); sink.list(); sink.listItem(); sink.link( repoBaseUrl ); sink.text( "central" ); sink.link_(); sink.listItem_(); sink.listItem(); sink.link( DIST_AREA ); sink.text( "Apache distribution area" ); sink.link_(); sink.listItem_(); sink.list_(); sink.section1_(); sink.table(); sink.tableRow(); sink.tableHeaderCell(); sink.rawText( "groupId" ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.rawText( "artifactId" ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.rawText( "LATEST" ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.rawText( "DATE" ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.rawText( "central" ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.rawText( "dist" ); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.rawText( "Older in dist REGEX ISSUE NO TRUST (mainly for doxia) " ); sink.tableHeaderCell_(); sink.tableRow_(); for ( DistCheckSourceRelease csr : results ) { reportLine( sink, csr ); } sink.table_(); sink.body_(); sink.flush(); sink.close(); } /** * Report a pattern for an artifact. * * @param artifact artifact name * @return regex */ protected static String getArtifactPattern( String artifact ) { /// not the safest return "^" + artifact + "-[0-9].*source-release.*$"; } private Elements selectLinks( String repourl ) throws IOException { try { Document doc = Jsoup.connect( repourl ).get(); return doc.select( "a[href]" ); } catch ( IOException ioe ) { throw new IOException( "IOException while reading " + repourl, ioe ); } } private List<String> checkOldinRepos( String repourl, ConfigurationLineInfo configLine, String version ) throws IOException { Elements links = selectLinks( repourl ); List<String> expectedFile = new LinkedList<>(); expectedFile.add( configLine.getArtifactId() + "-" + version + "-source-release.zip" ); expectedFile.add( configLine.getArtifactId() + "-" + version + "-source-release.zip.asc" ); expectedFile.add( configLine.getArtifactId() + "-" + version + "-source-release.zip.md5" ); List<String> retrievedFile = new LinkedList<>(); for ( Element e : links ) { String art = e.attr( "href" ); if ( art.matches( getArtifactPattern( configLine.getArtifactId() ) ) ) { retrievedFile.add( e.attr( "href" ) ); } } retrievedFile.removeAll( expectedFile ); if ( !retrievedFile.isEmpty() ) { // write the following output in red so it's more readable in jenkins console getLog().error( "Older version than " + version + " for " + configLine.getArtifactId() + " still available in " + repourl ); for ( String sourceItem : retrievedFile ) { getLog().error( " > " + sourceItem + " <" ); } } return retrievedFile; } private List<String> checkRepos( String repourl, ConfigurationLineInfo configLine, String version ) throws IOException { Elements links = selectLinks( repourl ); List<String> expectedFile = new LinkedList<>(); // build source artifact name expectedFile.add( configLine.getArtifactId() + "-" + version + "-source-release.zip" ); expectedFile.add( configLine.getArtifactId() + "-" + version + "-source-release.zip.asc" ); expectedFile.add( configLine.getArtifactId() + "-" + version + "-source-release.zip.md5" ); List<String> retrievedFile = new LinkedList<>(); for ( Element e : links ) { retrievedFile.add( e.attr( "href" ) ); } expectedFile.removeAll( retrievedFile ); if ( !expectedFile.isEmpty() ) { getLog().error( "Missing archive for " + configLine.getArtifactId() + " in " + repourl ); for ( String sourceItem : expectedFile ) { getLog().error( " > " + sourceItem + " <" ); } } return expectedFile; } @Override void checkArtifact( ConfigurationLineInfo configLine, String latestVersion ) throws MojoExecutionException { try { DistCheckSourceRelease result = new DistCheckSourceRelease( configLine, latestVersion ); results.add( result ); // central result.setMissingCentralSourceRelease( checkRepos( configLine.getVersionnedFolderURL( repoBaseUrl, latestVersion ), configLine, latestVersion ) ); //dist result.setMissingDistSourceRelease( checkRepos( configLine.getDist(), configLine, latestVersion ) ); result.setOlderSourceRelease( checkOldinRepos( configLine.getDist(), configLine, latestVersion ) ); } catch ( IOException ex ) { throw new MojoExecutionException( ex.getMessage(), ex ); } } }
true
true
private void reportLine( Sink sink, DistCheckSourceRelease csr ) { ConfigurationLineInfo cli = csr.getConfigurationLine(); sink.tableRow(); sink.tableCell(); // shorten groupid sink.rawText( csr.getConfigurationLine().getGroupId().replaceAll( "org.apache.maven", "o.a.m" ) ); sink.tableCell_(); sink.tableCell(); sink.rawText( csr.getConfigurationLine().getArtifactId() ); sink.tableCell_(); sink.tableCell(); sink.link( cli.getMetadataFileURL( repoBaseUrl ) ); sink.rawText( csr.getVersion() ); sink.link_(); sink.tableCell_(); sink.tableCell(); sink.rawText( csr.getConfigurationLine().getReleaseFromMetadata() ); sink.tableCell_(); sink.tableCell(); sink.link( cli.getBaseURL( repoBaseUrl, "" ) ); sink.text( "artifact" ); sink.link_(); sink.text( "/" ); sink.link( cli.getVersionnedFolderURL( repoBaseUrl, csr.getVersion() ) ); sink.text( csr.getVersion() ); sink.link_(); sink.text( "/source-release" ); if ( csr.central.isEmpty() ) { iconSuccess( sink ); } else { iconWarning( sink ); } for ( String missing : csr.central ) { sink.lineBreak(); iconError( sink ); sink.rawText( missing ); } sink.tableCell_(); // dist sink.tableCell(); sink.link( cli.getDist() ); sink.text( cli.getDist().substring( DIST_AREA.length() ) ); sink.link_(); sink.text( "source-release" ); if ( csr.dist.isEmpty() ) { iconSuccess( sink ); } else { iconWarning( sink ); } StringBuilder cliMissing = new StringBuilder(); for ( String missing : csr.dist ) { sink.lineBreak(); iconError( sink ); sink.rawText( missing ); cliMissing.append( "\nwget -O " ).append( cli.getVersionnedFolderURL( repoBaseUrl, csr.getVersion() ) ). append( "/" ).append( missing ); cliMissing.append( "\nsvn co " ).append( missing ); } if ( !cliMissing.toString().isEmpty() ) { sink.lineBreak(); SinkEventAttributeSet atts = new SinkEventAttributeSet(); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_START ) }, atts ); sink.text( cliMissing.toString() ); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_END ) }, null ); } sink.tableCell_(); //older sink.tableCell(); sink.link( cli.getDist() ); sink.text( cli.getDist().substring( DIST_AREA.length() ) ); sink.link_(); sink.text( "source-release" ); if ( csr.dist.isEmpty() ) { iconSuccess( sink ); } else { iconWarning( sink ); } StringBuilder cliOlder = new StringBuilder(); for ( String missing : csr.older ) { sink.lineBreak(); iconError( sink ); sink.rawText( missing ); cliOlder.append( "\nsvn rm " ).append( missing ); } if ( !cliOlder.toString().isEmpty() ) { sink.lineBreak(); SinkEventAttributeSet atts = new SinkEventAttributeSet(); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_START ) }, atts ); sink.text( cliOlder.toString() ); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_END ) }, null ); } sink.tableCell_(); sink.tableRow_(); }
private void reportLine( Sink sink, DistCheckSourceRelease csr ) { ConfigurationLineInfo cli = csr.getConfigurationLine(); sink.tableRow(); sink.tableCell(); // shorten groupid sink.rawText( csr.getConfigurationLine().getGroupId().replaceAll( "org.apache.maven", "o.a.m" ) ); sink.tableCell_(); sink.tableCell(); sink.rawText( csr.getConfigurationLine().getArtifactId() ); sink.tableCell_(); sink.tableCell(); sink.link( cli.getMetadataFileURL( repoBaseUrl ) ); sink.rawText( csr.getVersion() ); sink.link_(); sink.tableCell_(); sink.tableCell(); sink.rawText( csr.getConfigurationLine().getReleaseFromMetadata() ); sink.tableCell_(); sink.tableCell(); sink.link( cli.getBaseURL( repoBaseUrl, "" ) ); sink.text( "artifact" ); sink.link_(); sink.text( "/" ); sink.link( cli.getVersionnedFolderURL( repoBaseUrl, csr.getVersion() ) ); sink.text( csr.getVersion() ); sink.link_(); sink.text( "/source-release" ); if ( csr.central.isEmpty() ) { iconSuccess( sink ); } else { iconWarning( sink ); } for ( String missing : csr.central ) { sink.lineBreak(); iconError( sink ); sink.rawText( missing ); } sink.tableCell_(); // dist sink.tableCell(); sink.link( cli.getDist() ); sink.text( cli.getDist().substring( DIST_AREA.length() ) ); sink.link_(); sink.text( "source-release" ); if ( csr.dist.isEmpty() ) { iconSuccess( sink ); } else { iconWarning( sink ); } StringBuilder cliMissing = new StringBuilder(); for ( String missing : csr.dist ) { sink.lineBreak(); iconError( sink ); sink.rawText( missing ); cliMissing.append( "\nwget -O " ).append( cli.getVersionnedFolderURL( repoBaseUrl, csr.getVersion() ) ). append( "/" ).append( missing ); cliMissing.append( "\nsvn ci " ).append( missing ); } if ( !cliMissing.toString().isEmpty() ) { sink.lineBreak(); SinkEventAttributeSet atts = new SinkEventAttributeSet(); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_START ) }, atts ); sink.text( cliMissing.toString() ); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_END ) }, null ); } sink.tableCell_(); //older sink.tableCell(); sink.link( cli.getDist() ); sink.text( cli.getDist().substring( DIST_AREA.length() ) ); sink.link_(); sink.text( "source-release" ); if ( csr.dist.isEmpty() ) { iconSuccess( sink ); } else { iconWarning( sink ); } StringBuilder cliOlder = new StringBuilder(); for ( String missing : csr.older ) { sink.lineBreak(); iconError( sink ); sink.rawText( missing ); cliOlder.append( "\nsvn rm " ).append( missing ); } if ( !cliOlder.toString().isEmpty() ) { sink.lineBreak(); SinkEventAttributeSet atts = new SinkEventAttributeSet(); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_START ) }, atts ); sink.text( cliOlder.toString() ); sink.unknown( "pre", new Object[] { new Integer( HtmlMarkup.TAG_TYPE_END ) }, null ); } sink.tableCell_(); sink.tableRow_(); }
diff --git a/src/Main5.java b/src/Main5.java index 58d81dc..a262464 100644 --- a/src/Main5.java +++ b/src/Main5.java @@ -1,6 +1,6 @@ public class Main5 { public static void main(String[] args) { - System.out.println("Hello World testing 5 !"); + System.out.println("Hello World testing 05 !"); } }
true
true
public static void main(String[] args) { System.out.println("Hello World testing 5 !"); }
public static void main(String[] args) { System.out.println("Hello World testing 05 !"); }
diff --git a/src/test/java/net/floodlightcontroller/core/internal/OFChannelHandlerTest.java b/src/test/java/net/floodlightcontroller/core/internal/OFChannelHandlerTest.java index ca138410..56b5f2e3 100644 --- a/src/test/java/net/floodlightcontroller/core/internal/OFChannelHandlerTest.java +++ b/src/test/java/net/floodlightcontroller/core/internal/OFChannelHandlerTest.java @@ -1,1259 +1,1263 @@ package net.floodlightcontroller.core.internal; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.IFloodlightProviderService.Role; import net.floodlightcontroller.core.IOFSwitch.PortChangeEvent; import net.floodlightcontroller.core.IOFSwitch.PortChangeType; import net.floodlightcontroller.core.ImmutablePort; import net.floodlightcontroller.debugcounter.DebugCounter; import net.floodlightcontroller.debugcounter.IDebugCounterService; import net.floodlightcontroller.storage.IResultSet; import net.floodlightcontroller.storage.IStorageSourceService; import net.floodlightcontroller.threadpool.IThreadPoolService; import net.floodlightcontroller.util.OrderedCollection; import net.floodlightcontroller.util.LinkedHashSetWrapper; import org.easymock.Capture; import org.easymock.CaptureType; import org.easymock.EasyMock; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openflow.protocol.OFError; import org.openflow.protocol.OFError.OFBadRequestCode; import org.openflow.protocol.OFError.OFErrorType; import org.openflow.protocol.OFFeaturesReply; import org.openflow.protocol.OFGetConfigReply; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPacketIn; import org.openflow.protocol.OFPhysicalPort; import org.openflow.protocol.OFPortStatus; import org.openflow.protocol.OFPortStatus.OFPortReason; import org.openflow.protocol.OFSetConfig; import org.openflow.protocol.OFStatisticsReply; import org.openflow.protocol.OFStatisticsRequest; import org.openflow.protocol.OFType; import org.openflow.protocol.OFVendor; import org.openflow.protocol.factory.BasicFactory; import org.openflow.protocol.statistics.OFDescriptionStatistics; import org.openflow.protocol.statistics.OFStatisticsType; import org.openflow.util.HexString; import org.openflow.vendor.nicira.OFNiciraVendorData; import org.openflow.vendor.nicira.OFRoleReplyVendorData; import org.openflow.vendor.nicira.OFRoleRequestVendorData; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; public class OFChannelHandlerTest { private static final short CORE_PRIORITY = 4242; private static final short ACCESS_PRIORITY = 42; private Controller controller; private IThreadPoolService threadPool; private IDebugCounterService debugCounterService; private OFChannelHandler handler; private Channel channel; private ChannelHandlerContext ctx; private MessageEvent messageEvent; private ChannelStateEvent channelStateEvent; private ChannelPipeline pipeline; private Capture<ExceptionEvent> exceptionEventCapture; private Capture<List<OFMessage>> writeCapture; private OFFeaturesReply featuresReply; private Set<Integer> seenXids = null; private IStorageSourceService storageSource; private IResultSet storageResultSet; private IOFSwitch sw; @Before public void setUpFeaturesReply() { featuresReply = (OFFeaturesReply)BasicFactory.getInstance() .getMessage(OFType.FEATURES_REPLY); featuresReply.setDatapathId(0x42L); featuresReply.setBuffers(1); featuresReply.setTables((byte)1); featuresReply.setCapabilities(3); featuresReply.setActions(4); List<OFPhysicalPort> ports = new ArrayList<OFPhysicalPort>(); // A dummy port. OFPhysicalPort p = new OFPhysicalPort(); p.setName("Eth1"); p.setPortNumber((short)1); ports.add(p); featuresReply.setPorts(ports); } @Before public void setUp() throws Exception { controller = createMock(Controller.class); threadPool = createMock(IThreadPoolService.class); ctx = createMock(ChannelHandlerContext.class); channelStateEvent = createMock(ChannelStateEvent.class); channel = createMock(Channel.class); messageEvent = createMock(MessageEvent.class); exceptionEventCapture = new Capture<ExceptionEvent>(CaptureType.ALL); pipeline = createMock(ChannelPipeline.class); writeCapture = new Capture<List<OFMessage>>(CaptureType.ALL); sw = createMock(IOFSwitch.class); seenXids = null; // TODO: should mock IDebugCounterService and make sure // the expected counters are updated. debugCounterService = new DebugCounter(); Controller.Counters counters = new Controller.Counters(); counters.createCounters(debugCounterService); expect(controller.getCounters()).andReturn(counters).anyTimes(); replay(controller); handler = new OFChannelHandler(controller); verify(controller); reset(controller); resetChannel(); // thread pool is usually not called, so start empty replay replay(threadPool); // replay controller. Reset it if you need more specific behavior replay(controller); // replay switch. Reset it if you need more specific behavior replay(sw); // Mock ctx and channelStateEvent expect(ctx.getChannel()).andReturn(channel).anyTimes(); expect(channelStateEvent.getChannel()).andReturn(channel).anyTimes(); replay(ctx, channelStateEvent); /* Setup an exception event capture on the channel. Right now * we only expect exception events to be send up the channel. * However, it's easy to extend to other events if we need it */ pipeline.sendUpstream(capture(exceptionEventCapture)); expectLastCall().anyTimes(); replay(pipeline); } @After public void tearDown() { /* ensure no exception was thrown */ if (exceptionEventCapture.hasCaptured()) { Throwable ex = exceptionEventCapture.getValue().getCause(); ex.printStackTrace(); throw new AssertionError("Unexpected exception: " + ex.getClass().getName() + "(" + ex + ")"); } assertFalse("Unexpected messages have been captured", writeCapture.hasCaptured()); // verify all mocks. verify(channel); verify(messageEvent); verify(controller); verify(threadPool); verify(ctx); verify(channelStateEvent); verify(pipeline); verify(sw); } /** Reset the channel mock and set basic method call expectations */ void resetChannel() { reset(channel); expect(channel.getPipeline()).andReturn(pipeline).anyTimes(); expect(channel.getRemoteAddress()).andReturn(null).anyTimes(); } /** reset, setup, and replay the messageEvent mock for the given * messages */ void setupMessageEvent(List<OFMessage> messages) { reset(messageEvent); expect(messageEvent.getMessage()).andReturn(messages).atLeastOnce(); replay(messageEvent); } /** reset, setup, and replay the messageEvent mock for the given * messages, mock controller send message to channel handler * * This method will reset, start replay on controller, and then verify */ void sendMessageToHandlerWithControllerReset(List<OFMessage> messages) throws Exception { verify(controller); reset(controller); sendMessageToHandlerNoControllerReset(messages); } /** reset, setup, and replay the messageEvent mock for the given * messages, mock controller send message to channel handler * * This method will start replay on controller, and then verify */ void sendMessageToHandlerNoControllerReset(List<OFMessage> messages) throws Exception { setupMessageEvent(messages); // mock controller controller.flushAll(); expectLastCall().atLeastOnce(); replay(controller); handler.messageReceived(ctx, messageEvent); verify(controller); } /** * Extract the list of OFMessages that was captured by the Channel.write() * capture. Will check that something was actually captured first. We'll * collapse the messages from multiple writes into a single list of * OFMessages. * Resets the channelWriteCapture. */ List<OFMessage> getMessagesFromCapture() { List<OFMessage> msgs = new ArrayList<OFMessage>(); assertTrue("No write on channel was captured", writeCapture.hasCaptured()); List<List<OFMessage>> capturedVals = writeCapture.getValues(); for (List<OFMessage> oneWriteList: capturedVals) msgs.addAll(oneWriteList); writeCapture.reset(); return msgs; } /** * Verify that the given exception event capture (as returned by * getAndInitExceptionCapture) has thrown an exception of the given * expectedExceptionClass. * Resets the capture */ void verifyExceptionCaptured( Class<? extends Throwable> expectedExceptionClass) { assertTrue("Excpected exception not thrown", exceptionEventCapture.hasCaptured()); Throwable caughtEx = exceptionEventCapture.getValue().getCause(); assertEquals(expectedExceptionClass, caughtEx.getClass()); exceptionEventCapture.reset(); } /** make sure that the transaction ids in the given messages are * not 0 and differ between each other. * While it's not a defect per se if the xids are we want to ensure * we use different ones for each message we send. */ void verifyUniqueXids(List<OFMessage> msgs) { if (seenXids == null) seenXids = new HashSet<Integer>(); for (OFMessage m: msgs) { int xid = m.getXid(); assertTrue("Xid in messags is 0", xid != 0); assertFalse("Xid " + xid + " has already been used", seenXids.contains(xid)); seenXids.add(xid); } } @Test public void testInitState() throws Exception { // Message event needs to be list expect(messageEvent.getMessage()).andReturn(null); replay(channel, messageEvent); handler.messageReceived(ctx, messageEvent); verify(channel, messageEvent); verifyExceptionCaptured(AssertionError.class); // Message event needs to be list *of OFMessages* // TODO: messageReceived can throw exceptions that don't get send // back into the channel (e.g., the ClassCastException below). // Do we need to care? /* reset(channel, messageEvent); List<String> listOfWrongType = Collections.singletonList("FooBar"); expect(messageEvent.getMessage()).andReturn(listOfWrongType) .atLeastOnce(); replay(channel, messageEvent); handler.messageReceived(ctx, messageEvent); verify(channel, messageEvent); verifyExceptionCaptured(ClassCastException.class); */ // We don't expect to receive /any/ messages in init state since // channelConnected moves us to a different state OFMessage m = BasicFactory.getInstance().getMessage(OFType.HELLO); sendMessageToHandlerWithControllerReset(Collections.singletonList(m)); verifyExceptionCaptured(SwitchStateException.class); assertEquals(OFChannelHandler.ChannelState.INIT, handler.getStateForTesting()); } /* Move the channel from scratch to WAIT_HELLO state */ @Test public void moveToWaitHello() throws Exception { resetChannel(); channel.write(capture(writeCapture)); expectLastCall().andReturn(null).once(); replay(channel); // replay unused mocks replay(messageEvent); handler.channelConnected(ctx, channelStateEvent); List<OFMessage> msgs = getMessagesFromCapture(); assertEquals(1, msgs.size()); assertEquals(OFType.HELLO, msgs.get(0).getType()); assertEquals(OFChannelHandler.ChannelState.WAIT_HELLO, handler.getStateForTesting()); verifyUniqueXids(msgs); } /** Move the channel from scratch to WAIT_FEATURES_REPLY state * Builds on moveToWaitHello() * adds testing for WAIT_HELLO state */ @Test public void moveToWaitFeaturesReply() throws Exception { moveToWaitHello(); resetChannel(); channel.write(capture(writeCapture)); expectLastCall().andReturn(null).atLeastOnce(); replay(channel); OFMessage hello = BasicFactory.getInstance().getMessage(OFType.HELLO); sendMessageToHandlerWithControllerReset(Collections.singletonList(hello)); List<OFMessage> msgs = getMessagesFromCapture(); assertEquals(1, msgs.size()); assertEquals(OFType.FEATURES_REQUEST, msgs.get(0).getType()); verifyUniqueXids(msgs); assertEquals(OFChannelHandler.ChannelState.WAIT_FEATURES_REPLY, handler.getStateForTesting()); } /** Move the channel from scratch to WAIT_CONFIG_REPLY state * Builds on moveToWaitFeaturesReply * adds testing for WAIT_FEATURES_REPLY state */ @Test public void moveToWaitConfigReply() throws Exception { moveToWaitFeaturesReply(); resetChannel(); channel.write(capture(writeCapture)); expectLastCall().andReturn(null).atLeastOnce(); replay(channel); sendMessageToHandlerWithControllerReset(Collections.<OFMessage>singletonList(featuresReply)); List<OFMessage> msgs = getMessagesFromCapture(); assertEquals(3, msgs.size()); assertEquals(OFType.SET_CONFIG, msgs.get(0).getType()); OFSetConfig sc = (OFSetConfig)msgs.get(0); assertEquals((short)0xffff, sc.getMissSendLength()); assertEquals(OFType.BARRIER_REQUEST, msgs.get(1).getType()); assertEquals(OFType.GET_CONFIG_REQUEST, msgs.get(2).getType()); verifyUniqueXids(msgs); assertEquals(OFChannelHandler.ChannelState.WAIT_CONFIG_REPLY, handler.getStateForTesting()); } /** Move the channel from scratch to WAIT_DESCRIPTION_STAT_REPLY state * Builds on moveToWaitConfigReply() * adds testing for WAIT_CONFIG_REPLY state */ @Test public void moveToWaitDescriptionStatReply() throws Exception { moveToWaitConfigReply(); resetChannel(); channel.write(capture(writeCapture)); expectLastCall().andReturn(null).atLeastOnce(); replay(channel); OFGetConfigReply cr = (OFGetConfigReply)BasicFactory.getInstance() .getMessage(OFType.GET_CONFIG_REPLY); cr.setMissSendLength((short)0xffff); sendMessageToHandlerWithControllerReset(Collections.<OFMessage>singletonList(cr)); List<OFMessage> msgs = getMessagesFromCapture(); assertEquals(1, msgs.size()); assertEquals(OFType.STATS_REQUEST, msgs.get(0).getType()); OFStatisticsRequest sr = (OFStatisticsRequest)msgs.get(0); assertEquals(OFStatisticsType.DESC, sr.getStatisticType()); // no idea why an OFStatisticsRequest even /has/ a getStatistics() // methods. It really shouldn't assertNull(sr.getStatistics()); verifyUniqueXids(msgs); assertEquals(OFChannelHandler.ChannelState.WAIT_DESCRIPTION_STAT_REPLY, handler.getStateForTesting()); } /** A helper bean that represents the config for a particular switch in * the storage source. */ private class MockStorageSourceConfig { // the dpid public String dpid; // true if the given dpid should be present in the storage source // if false the storage source will return an empty result public boolean isPresent; // the value of isCoreSwitch public boolean isCoreSwitch; } /** setup and replay a mock storage source and result set that * contains the IsCoreSwitch setting */ private void setupMockStorageSource(MockStorageSourceConfig cfg) { storageSource = createMock(IStorageSourceService.class); storageResultSet = createMock(IResultSet.class); Iterator<IResultSet> it = null; if (cfg.isPresent) { storageResultSet.getBoolean(Controller.SWITCH_CONFIG_CORE_SWITCH); expectLastCall().andReturn(cfg.isCoreSwitch).atLeastOnce(); it = Collections.singletonList(storageResultSet).iterator(); } else { it = Collections.<IResultSet>emptyList().iterator(); } storageResultSet.close(); expectLastCall().atLeastOnce(); expect(storageResultSet.iterator()).andReturn(it).atLeastOnce(); storageSource.getRow(Controller.SWITCH_CONFIG_TABLE_NAME, cfg.dpid); expectLastCall().andReturn(storageResultSet).atLeastOnce(); replay(storageResultSet, storageSource); } private void verifyStorageSource() { verify(storageSource); verify(storageResultSet); } /** Move the channel from scratch to WAIT_INITIAL_ROLE state * Builds on moveToWaitDescriptionStatReply() * adds testing for WAIT_DESCRIPTION_STAT_REPLY state * @param storageSourceConfig paramterizes the contents of the storage * source (for IS_CORE_SWITCH) */ public void doMoveToWaitInitialRole(MockStorageSourceConfig cfg) throws Exception { moveToWaitDescriptionStatReply(); // We do not expect a write to the channel per-se. We add // the channel to the controller and the controller will in turn // call handler.sendRoleRequest(). However, we mock the controller so // we don't expect that call. resetChannel(); replay(channel); // build the stats reply OFStatisticsReply sr = (OFStatisticsReply)BasicFactory.getInstance() .getMessage(OFType.STATS_REPLY); sr.setStatisticType(OFStatisticsType.DESC); OFDescriptionStatistics desc = new OFDescriptionStatistics(); desc.setDatapathDescription("Datapath Description"); desc.setHardwareDescription("Hardware Description"); desc.setManufacturerDescription("Manufacturer Description"); desc.setSerialNumber("Serial Number"); desc.setSoftwareDescription("Software Description"); sr.setStatistics(Collections.singletonList(desc)); setupMessageEvent(Collections.<OFMessage>singletonList(sr)); setupMockStorageSource(cfg); reset(sw); sw.setChannel(channel); expectLastCall().once(); sw.setFloodlightProvider(controller); expectLastCall().once(); sw.setThreadPoolService(threadPool); expectLastCall().once(); sw.setDebugCounterService(debugCounterService); expectLastCall().once(); sw.setFeaturesReply(featuresReply); expectLastCall().once(); sw.setConnected(true); expectLastCall().once(); sw.getStringId(); expectLastCall().andReturn(cfg.dpid).atLeastOnce(); sw.isWriteThrottleEnabled(); // used for log message only expectLastCall().andReturn(false).anyTimes(); sw.setAccessFlowPriority(ACCESS_PRIORITY); expectLastCall().once(); sw.setCoreFlowPriority(CORE_PRIORITY); expectLastCall().once(); + sw.startDriverHandshake(); + expectLastCall().once(); + sw.isDriverHandshakeComplete(); + expectLastCall().andReturn(true).once(); if (cfg.isPresent) sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH, cfg.isCoreSwitch); replay(sw); // mock controller reset(controller); expect(controller.getDebugCounter()).andReturn(debugCounterService) .once(); controller.flushAll(); expectLastCall().once(); expect(controller.getThreadPoolService()) .andReturn(threadPool).once(); expect(controller.getOFSwitchInstance(eq(desc))) .andReturn(sw).once(); expect(controller.getCoreFlowPriority()) .andReturn(CORE_PRIORITY).once(); expect(controller.getAccessFlowPriority()) .andReturn(ACCESS_PRIORITY).once(); controller.addSwitchChannelAndSendInitialRole(handler); expectLastCall().once(); expect(controller.getStorageSourceService()) .andReturn(storageSource).atLeastOnce(); replay(controller); // send the description stats reply handler.messageReceived(ctx, messageEvent); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); verifyStorageSource(); } @Test /** Test WaitDescriptionReplyState. No config for switch in storage */ public void testWaitDescriptionReplyState1() throws Exception { MockStorageSourceConfig cfg = new MockStorageSourceConfig(); cfg.dpid = HexString.toHexString(featuresReply.getDatapathId()); cfg.isPresent = false; doMoveToWaitInitialRole(cfg); } @Test /** Test WaitDescriptionReplyState. switch is core switch */ public void testWaitDescriptionReplyState2() throws Exception { MockStorageSourceConfig cfg = new MockStorageSourceConfig(); cfg.dpid = HexString.toHexString(featuresReply.getDatapathId()); cfg.isPresent = true; cfg.isCoreSwitch = true; doMoveToWaitInitialRole(cfg); } @Test /** Test WaitDescriptionReplyState. switch is NOT core switch */ public void testWaitDescriptionReplyState3() throws Exception { MockStorageSourceConfig cfg = new MockStorageSourceConfig(); cfg.dpid = HexString.toHexString(featuresReply.getDatapathId()); cfg.isPresent = true; cfg.isCoreSwitch = true; doMoveToWaitInitialRole(cfg); } /** * Helper * Verify that the given OFMessage is a correct Nicira RoleRequest message * for the given role using the given xid. */ private void verifyRoleRequest(OFMessage m, int expectedXid, Role expectedRole) { assertEquals(OFType.VENDOR, m.getType()); OFVendor vendorMsg = (OFVendor)m; assertEquals(expectedXid, vendorMsg.getXid()); assertEquals(OFNiciraVendorData.NX_VENDOR_ID, vendorMsg.getVendor()); assertTrue("Vendor data is not an instance of OFRoleRequestVendorData" + " its class is: " + vendorMsg.getVendorData().getClass().getName(), vendorMsg.getVendorData() instanceof OFRoleRequestVendorData); OFRoleRequestVendorData requestData = (OFRoleRequestVendorData)vendorMsg.getVendorData(); assertEquals(expectedRole.toNxRole(), requestData.getRole()); } /** * Setup the mock switch and write capture for a role request, set the * role and verify mocks. * @param supportsNxRole whether the switch supports role request messages * to setup the attribute. This must be null (don't yet know if roles * supported: send to check) or true. * @param xid The xid to use in the role request * @param role The role to send * @throws IOException */ private void setupSwitchSendRoleRequestAndVerify(Boolean supportsNxRole, int xid, Role role) throws IOException { assertTrue("This internal test helper method most not be called " + "with supportsNxRole==false. Test setup broken", supportsNxRole == null || supportsNxRole == true); reset(sw); expect(sw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)) .andReturn(supportsNxRole).atLeastOnce(); expect(sw.getNextTransactionId()).andReturn(xid).once(); sw.write(capture(writeCapture), EasyMock.<FloodlightContext>anyObject()); expectLastCall().anyTimes(); replay(sw); handler.sendRoleRequest(role); List<OFMessage> msgs = getMessagesFromCapture(); assertEquals(1, msgs.size()); verifyRoleRequest(msgs.get(0), xid, role); verify(sw); } /** * Setup the mock switch for a role change request where the switch * does not support roles. * * Needs to verify and reset the controller since we need to set * an expectation */ private void setupSwitchRoleChangeUnsupported(int xid, Role role) { boolean supportsNxRole = false; reset(sw); expect(sw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE)) .andReturn(supportsNxRole).atLeastOnce(); // TODO: hmmm. While it's not incorrect that we set the attribute // again it looks odd. Maybe change sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, supportsNxRole); expectLastCall().anyTimes(); sw.setHARole(role); expectLastCall().once(); if (role == Role.SLAVE) { sw.disconnectOutputStream(); expectLastCall().once(); } else { verify(controller); reset(controller); controller.switchActivated(sw); replay(controller); } replay(sw); handler.sendRoleRequest(role); verify(sw); } /** Return a Nicira RoleReply message for the given role */ private OFMessage getRoleReply(int xid, Role role) { OFVendor vm = (OFVendor)BasicFactory.getInstance() .getMessage(OFType.VENDOR); vm.setXid(xid); vm.setVendor(OFNiciraVendorData.NX_VENDOR_ID); OFRoleReplyVendorData replyData = new OFRoleReplyVendorData(); replyData.setRole(role.toNxRole()); vm.setVendorData(replyData); return vm; } /** Return an OFError of the given type with the given xid */ private OFMessage getErrorMessage(OFErrorType type, int i, int xid) { OFError e = (OFError) BasicFactory.getInstance() .getMessage(OFType.ERROR); e.setErrorType(type); e.setErrorCode((short)i); e.setXid(xid); return e; } /** Move the channel from scratch to MASTER state * Builds on doMoveToWaitInitialRole() * adds testing for WAIT_INITAL_ROLE state * * This method tests only the simple case that the switch supports roles * and transitions to MASTER */ @Test public void testInitialMoveToMasterWithRole() throws Exception { int xid = 42; // first, move us to WAIT_INITIAL_ROLE_STATE MockStorageSourceConfig cfg = new MockStorageSourceConfig(); cfg.dpid = HexString.toHexString(featuresReply.getDatapathId()); cfg.isPresent = false; doMoveToWaitInitialRole(cfg); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // Set the role setupSwitchSendRoleRequestAndVerify(null, xid, Role.MASTER); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // prepare mocks and inject the role reply message reset(sw); expect(sw.inputThrottled(anyObject(OFMessage.class))) .andReturn(false).anyTimes(); sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, true); expectLastCall().once(); sw.setHARole(Role.MASTER); expectLastCall().once(); replay(sw); verify(controller); reset(controller); controller.switchActivated(sw); expectLastCall().once(); OFMessage reply = getRoleReply(xid, Role.MASTER); // sendMessageToHandler will verify and rest controller mock sendMessageToHandlerNoControllerReset(Collections.singletonList(reply)); assertEquals(OFChannelHandler.ChannelState.MASTER, handler.getStateForTesting()); } /** Move the channel from scratch to SLAVE state * Builds on doMoveToWaitInitialRole() * adds testing for WAIT_INITAL_ROLE state * * This method tests only the simple case that the switch supports roles * and transitions to SLAVE */ @Test public void testInitialMoveToSlaveWithRole() throws Exception { int xid = 42; // first, move us to WAIT_INITIAL_ROLE_STATE MockStorageSourceConfig cfg = new MockStorageSourceConfig(); cfg.dpid = HexString.toHexString(featuresReply.getDatapathId()); cfg.isPresent = false; doMoveToWaitInitialRole(cfg); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // Set the role setupSwitchSendRoleRequestAndVerify(null, xid, Role.SLAVE); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // prepare mocks and inject the role reply message reset(sw); expect(sw.inputThrottled(anyObject(OFMessage.class))) .andReturn(false).anyTimes(); sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, true); expectLastCall().once(); sw.setHARole(Role.SLAVE); expectLastCall().once(); replay(sw); verify(controller); reset(controller); controller.switchDeactivated(sw); expectLastCall().once(); OFMessage reply = getRoleReply(xid, Role.SLAVE); // sendMessageToHandler will verify and rest controller mock sendMessageToHandlerNoControllerReset(Collections.singletonList(reply)); assertEquals(OFChannelHandler.ChannelState.SLAVE, handler.getStateForTesting()); } /** Move the channel from scratch to MASTER state * Builds on doMoveToWaitInitialRole() * adds testing for WAIT_INITAL_ROLE state * * This method tests the case that the switch does NOT support roles. * The channel handler still needs to send the initial request to find * out that whether the switch supports roles. */ @Test public void testInitialMoveToMasterNoRole() throws Exception { int xid = 43; // first, move us to WAIT_INITIAL_ROLE_STATE MockStorageSourceConfig cfg = new MockStorageSourceConfig(); cfg.dpid = HexString.toHexString(featuresReply.getDatapathId()); cfg.isPresent = false; doMoveToWaitInitialRole(cfg); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // Set the role setupSwitchSendRoleRequestAndVerify(null, xid, Role.MASTER); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // prepare mocks and inject the role reply message reset(sw); expect(sw.inputThrottled(anyObject(OFMessage.class))) .andReturn(false).anyTimes(); sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, false); expectLastCall().once(); sw.setHARole(Role.MASTER); expectLastCall().once(); replay(sw); // FIXME: shouldn't use ordinal(), but OFError is broken // Error with incorrect xid and type. Should be ignored. OFMessage err = getErrorMessage(OFErrorType.OFPET_BAD_ACTION, 0, xid+1); // sendMessageToHandler will verify and rest controller mock sendMessageToHandlerWithControllerReset(Collections.singletonList(err)); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // Error with correct xid. Should trigger state transition err = getErrorMessage(OFErrorType.OFPET_BAD_REQUEST, OFError.OFBadRequestCode.OFPBRC_BAD_VENDOR.ordinal(), xid); verify(controller); reset(controller); controller.switchActivated(sw); expectLastCall().once(); // sendMessageToHandler will verify and rest controller mock sendMessageToHandlerNoControllerReset(Collections.singletonList(err)); assertEquals(OFChannelHandler.ChannelState.MASTER, handler.getStateForTesting()); } /** Move the channel from scratch to MASTER state * Builds on doMoveToWaitInitialRole() * adds testing for WAIT_INITAL_ROLE state * * We let the initial role request time out. Role support should be * disabled but the switch should be activated. */ @Test public void testInitialMoveToMasterTimeout() throws Exception { int timeout = 50; handler.useRoleChangerWithOtherTimeoutForTesting(timeout); int xid = 4343; // first, move us to WAIT_INITIAL_ROLE_STATE MockStorageSourceConfig cfg = new MockStorageSourceConfig(); cfg.dpid = HexString.toHexString(featuresReply.getDatapathId()); cfg.isPresent = false; doMoveToWaitInitialRole(cfg); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // Set the role setupSwitchSendRoleRequestAndVerify(null, xid, Role.MASTER); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // prepare mocks and inject the role reply message reset(sw); expect(sw.inputThrottled(anyObject(OFMessage.class))) .andReturn(false).anyTimes(); sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, false); expectLastCall().once(); sw.setHARole(Role.MASTER); expectLastCall().once(); replay(sw); OFMessage m = BasicFactory.getInstance().getMessage(OFType.ECHO_REPLY); Thread.sleep(timeout+5); verify(controller); reset(controller); controller.switchActivated(sw); expectLastCall().once(); sendMessageToHandlerNoControllerReset(Collections.singletonList(m)); assertEquals(OFChannelHandler.ChannelState.MASTER, handler.getStateForTesting()); } /** Move the channel from scratch to SLAVE state * Builds on doMoveToWaitInitialRole() * adds testing for WAIT_INITAL_ROLE state * * This method tests the case that the switch does NOT support roles. * The channel handler still needs to send the initial request to find * out that whether the switch supports roles. * */ @Test public void testInitialMoveToSlaveNoRole() throws Exception { int xid = 44; // first, move us to WAIT_INITIAL_ROLE_STATE MockStorageSourceConfig cfg = new MockStorageSourceConfig(); cfg.dpid = HexString.toHexString(featuresReply.getDatapathId()); cfg.isPresent = false; doMoveToWaitInitialRole(cfg); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // Set the role setupSwitchSendRoleRequestAndVerify(null, xid, Role.SLAVE); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // prepare mocks and inject the role reply message reset(sw); expect(sw.inputThrottled(anyObject(OFMessage.class))) .andReturn(false).anyTimes(); sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, false); expectLastCall().once(); sw.setHARole(Role.SLAVE); expectLastCall().once(); sw.disconnectOutputStream(); // Make sure we disconnect expectLastCall().once(); replay(sw); // FIXME: shouldn't use ordinal(), but OFError is broken // Error with incorrect xid and type. Should be ignored. OFMessage err = getErrorMessage(OFErrorType.OFPET_BAD_ACTION, 0, xid+1); // sendMessageToHandler will verify and rest controller mock sendMessageToHandlerWithControllerReset(Collections.singletonList(err)); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // Error with correct xid. Should trigger state transition err = getErrorMessage(OFErrorType.OFPET_BAD_REQUEST, OFError.OFBadRequestCode.OFPBRC_BAD_VENDOR.ordinal(), xid); // sendMessageToHandler will verify and rest controller mock sendMessageToHandlerWithControllerReset(Collections.singletonList(err)); } /** Move the channel from scratch to SLAVE state * Builds on doMoveToWaitInitialRole() * adds testing for WAIT_INITAL_ROLE state * * We let the initial role request time out. The switch should be * disconnected */ @Test public void testInitialMoveToSlaveTimeout() throws Exception { int timeout = 50; handler.useRoleChangerWithOtherTimeoutForTesting(timeout); int xid = 4444; // first, move us to WAIT_INITIAL_ROLE_STATE MockStorageSourceConfig cfg = new MockStorageSourceConfig(); cfg.dpid = HexString.toHexString(featuresReply.getDatapathId()); cfg.isPresent = false; doMoveToWaitInitialRole(cfg); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // Set the role setupSwitchSendRoleRequestAndVerify(null, xid, Role.SLAVE); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // prepare mocks and inject the role reply message reset(sw); expect(sw.inputThrottled(anyObject(OFMessage.class))) .andReturn(false).anyTimes(); sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, false); expectLastCall().once(); sw.setHARole(Role.SLAVE); expectLastCall().once(); sw.disconnectOutputStream(); // Make sure we disconnect expectLastCall().once(); replay(sw); OFMessage m = BasicFactory.getInstance().getMessage(OFType.ECHO_REPLY); Thread.sleep(timeout+5); sendMessageToHandlerWithControllerReset(Collections.singletonList(m)); } /** Move channel from scratch to WAIT_INITIAL_STATE, then MASTER, * then SLAVE for cases where the switch does not support roles. * I.e., the final SLAVE transition should disconnect the switch. */ @Test public void testNoRoleInitialToMasterToSlave() throws Exception { int xid = 46; // First, lets move the state to MASTER without role support testInitialMoveToMasterNoRole(); assertEquals(OFChannelHandler.ChannelState.MASTER, handler.getStateForTesting()); // try to set master role again. should be a no-op setupSwitchRoleChangeUnsupported(xid, Role.MASTER); assertEquals(OFChannelHandler.ChannelState.MASTER, handler.getStateForTesting()); setupSwitchRoleChangeUnsupported(xid, Role.SLAVE); assertEquals(OFChannelHandler.ChannelState.SLAVE, handler.getStateForTesting()); } /** Move the channel to MASTER state * Expects that the channel is in MASTER or SLAVE state. * */ public void changeRoleToMasterWithRequest() throws Exception { int xid = 4242; assertTrue("This method can only be called when handler is in " + "MASTER or SLAVE role", handler.isHandshakeComplete()); // Set the role setupSwitchSendRoleRequestAndVerify(true, xid, Role.MASTER); // prepare mocks and inject the role reply message reset(sw); expect(sw.inputThrottled(anyObject(OFMessage.class))) .andReturn(false).anyTimes(); sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, true); expectLastCall().once(); sw.setHARole(Role.MASTER); expectLastCall().once(); replay(sw); verify(controller); reset(controller); controller.switchActivated(sw); expectLastCall().once(); OFMessage reply = getRoleReply(xid, Role.MASTER); // sendMessageToHandler will verify and rest controller mock sendMessageToHandlerNoControllerReset(Collections.singletonList(reply)); assertEquals(OFChannelHandler.ChannelState.MASTER, handler.getStateForTesting()); } /** Move the channel to SLAVE state * Expects that the channel is in MASTER or SLAVE state. * */ public void changeRoleToSlaveWithRequest() throws Exception { int xid = 2323; assertTrue("This method can only be called when handler is in " + "MASTER or SLAVE role", handler.isHandshakeComplete()); // Set the role setupSwitchSendRoleRequestAndVerify(true, xid, Role.SLAVE); // prepare mocks and inject the role reply message reset(sw); expect(sw.inputThrottled(anyObject(OFMessage.class))) .andReturn(false).anyTimes(); sw.setAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE, true); expectLastCall().once(); sw.setHARole(Role.SLAVE); expectLastCall().once(); replay(sw); verify(controller); reset(controller); controller.switchDeactivated(sw); expectLastCall().once(); OFMessage reply = getRoleReply(xid, Role.SLAVE); // sendMessageToHandler will verify and rest controller mock sendMessageToHandlerNoControllerReset(Collections.singletonList(reply)); assertEquals(OFChannelHandler.ChannelState.SLAVE, handler.getStateForTesting()); } @Test public void testMultiRoleChange1() throws Exception { testInitialMoveToMasterWithRole(); changeRoleToMasterWithRequest(); changeRoleToSlaveWithRequest(); changeRoleToSlaveWithRequest(); changeRoleToMasterWithRequest(); changeRoleToSlaveWithRequest(); } @Test public void testMultiRoleChange2() throws Exception { testInitialMoveToSlaveWithRole(); changeRoleToMasterWithRequest(); changeRoleToSlaveWithRequest(); changeRoleToSlaveWithRequest(); changeRoleToMasterWithRequest(); changeRoleToSlaveWithRequest(); } /** Start from scratch and reply with an unexpected error to the role * change request * Builds on doMoveToWaitInitialRole() * adds testing for WAIT_INITAL_ROLE state */ @Test public void testInitialRoleChangeOtherError() throws Exception { int xid = 4343; // first, move us to WAIT_INITIAL_ROLE_STATE MockStorageSourceConfig cfg = new MockStorageSourceConfig(); cfg.dpid = HexString.toHexString(featuresReply.getDatapathId()); cfg.isPresent = false; doMoveToWaitInitialRole(cfg); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // Set the role setupSwitchSendRoleRequestAndVerify(null, xid, Role.MASTER); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); // FIXME: shouldn't use ordinal(), but OFError is broken OFMessage err = getErrorMessage(OFErrorType.OFPET_BAD_ACTION, 0, xid); verify(sw); reset(sw); expect(sw.inputThrottled(anyObject(OFMessage.class))) .andReturn(false).anyTimes(); replay(sw); sendMessageToHandlerWithControllerReset(Collections.singletonList(err)); verifyExceptionCaptured(SwitchStateException.class); } /** * Test dispatch of messages while in MASTER role */ @Test public void testMessageDispatchMaster() throws Exception { testInitialMoveToMasterWithRole(); // Send packet in. expect dispatch OFPacketIn pi = (OFPacketIn) BasicFactory.getInstance().getMessage(OFType.PACKET_IN); reset(controller); controller.handleMessage(sw, pi, null); expectLastCall().once(); sendMessageToHandlerNoControllerReset( Collections.<OFMessage>singletonList(pi)); verify(controller); // TODO: many more to go } /** * Test port status message handling while MASTER * */ @Test public void testPortStatusMessageMaster() throws Exception { long dpid = featuresReply.getDatapathId(); testInitialMoveToMasterWithRole(); OFPhysicalPort p = new OFPhysicalPort(); p.setName("Port1"); p.setPortNumber((short)1); OFPortStatus ps = (OFPortStatus) BasicFactory.getInstance().getMessage(OFType.PORT_STATUS); ps.setDesc(p); // The events we expect sw.handlePortStatus to return // We'll just use the same list for all valid OFPortReasons and add // arbitrary events for arbitrary ports that are not necessarily // related to the port status message. Our goal // here is not to return the correct set of events but the make sure // that a) sw.handlePortStatus is called // b) the list of events sw.handlePortStatus returns is sent // as IOFSwitchListener notifications. OrderedCollection<PortChangeEvent> events = new LinkedHashSetWrapper<PortChangeEvent>(); ImmutablePort p1 = ImmutablePort.create("eth1", (short)1); ImmutablePort p2 = ImmutablePort.create("eth2", (short)2); ImmutablePort p3 = ImmutablePort.create("eth3", (short)3); ImmutablePort p4 = ImmutablePort.create("eth4", (short)4); ImmutablePort p5 = ImmutablePort.create("eth5", (short)5); events.add(new PortChangeEvent(p1, PortChangeType.ADD)); events.add(new PortChangeEvent(p2, PortChangeType.DELETE)); events.add(new PortChangeEvent(p3, PortChangeType.UP)); events.add(new PortChangeEvent(p4, PortChangeType.DOWN)); events.add(new PortChangeEvent(p5, PortChangeType.OTHER_UPDATE)); for (OFPortReason reason: OFPortReason.values()) { ps.setReason(reason.getReasonCode()); reset(sw); expect(sw.inputThrottled(anyObject(OFMessage.class))) .andReturn(false).anyTimes(); expect(sw.getId()).andReturn(dpid).anyTimes(); expect(sw.processOFPortStatus(ps)).andReturn(events).once(); replay(sw); reset(controller); controller.notifyPortChanged(sw, p1, PortChangeType.ADD); controller.notifyPortChanged(sw, p2, PortChangeType.DELETE); controller.notifyPortChanged(sw, p3, PortChangeType.UP); controller.notifyPortChanged(sw, p4, PortChangeType.DOWN); controller.notifyPortChanged(sw, p5, PortChangeType.OTHER_UPDATE); sendMessageToHandlerNoControllerReset( Collections.<OFMessage>singletonList(ps)); verify(sw); verify(controller); } } /** * Test re-assert MASTER * */ @Test public void testReassertMaster() throws Exception { testInitialMoveToMasterWithRole(); OFError err = (OFError) BasicFactory.getInstance().getMessage(OFType.ERROR); err.setXid(42); err.setErrorType(OFErrorType.OFPET_BAD_REQUEST); err.setErrorCode(OFBadRequestCode.OFPBRC_EPERM); reset(controller); controller.reassertRole(handler, Role.MASTER); expectLastCall().once(); controller.handleMessage(sw, err, null); expectLastCall().once(); sendMessageToHandlerNoControllerReset( Collections.<OFMessage>singletonList(err)); verify(sw); verify(controller); } }
true
true
public void doMoveToWaitInitialRole(MockStorageSourceConfig cfg) throws Exception { moveToWaitDescriptionStatReply(); // We do not expect a write to the channel per-se. We add // the channel to the controller and the controller will in turn // call handler.sendRoleRequest(). However, we mock the controller so // we don't expect that call. resetChannel(); replay(channel); // build the stats reply OFStatisticsReply sr = (OFStatisticsReply)BasicFactory.getInstance() .getMessage(OFType.STATS_REPLY); sr.setStatisticType(OFStatisticsType.DESC); OFDescriptionStatistics desc = new OFDescriptionStatistics(); desc.setDatapathDescription("Datapath Description"); desc.setHardwareDescription("Hardware Description"); desc.setManufacturerDescription("Manufacturer Description"); desc.setSerialNumber("Serial Number"); desc.setSoftwareDescription("Software Description"); sr.setStatistics(Collections.singletonList(desc)); setupMessageEvent(Collections.<OFMessage>singletonList(sr)); setupMockStorageSource(cfg); reset(sw); sw.setChannel(channel); expectLastCall().once(); sw.setFloodlightProvider(controller); expectLastCall().once(); sw.setThreadPoolService(threadPool); expectLastCall().once(); sw.setDebugCounterService(debugCounterService); expectLastCall().once(); sw.setFeaturesReply(featuresReply); expectLastCall().once(); sw.setConnected(true); expectLastCall().once(); sw.getStringId(); expectLastCall().andReturn(cfg.dpid).atLeastOnce(); sw.isWriteThrottleEnabled(); // used for log message only expectLastCall().andReturn(false).anyTimes(); sw.setAccessFlowPriority(ACCESS_PRIORITY); expectLastCall().once(); sw.setCoreFlowPriority(CORE_PRIORITY); expectLastCall().once(); if (cfg.isPresent) sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH, cfg.isCoreSwitch); replay(sw); // mock controller reset(controller); expect(controller.getDebugCounter()).andReturn(debugCounterService) .once(); controller.flushAll(); expectLastCall().once(); expect(controller.getThreadPoolService()) .andReturn(threadPool).once(); expect(controller.getOFSwitchInstance(eq(desc))) .andReturn(sw).once(); expect(controller.getCoreFlowPriority()) .andReturn(CORE_PRIORITY).once(); expect(controller.getAccessFlowPriority()) .andReturn(ACCESS_PRIORITY).once(); controller.addSwitchChannelAndSendInitialRole(handler); expectLastCall().once(); expect(controller.getStorageSourceService()) .andReturn(storageSource).atLeastOnce(); replay(controller); // send the description stats reply handler.messageReceived(ctx, messageEvent); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); verifyStorageSource(); }
public void doMoveToWaitInitialRole(MockStorageSourceConfig cfg) throws Exception { moveToWaitDescriptionStatReply(); // We do not expect a write to the channel per-se. We add // the channel to the controller and the controller will in turn // call handler.sendRoleRequest(). However, we mock the controller so // we don't expect that call. resetChannel(); replay(channel); // build the stats reply OFStatisticsReply sr = (OFStatisticsReply)BasicFactory.getInstance() .getMessage(OFType.STATS_REPLY); sr.setStatisticType(OFStatisticsType.DESC); OFDescriptionStatistics desc = new OFDescriptionStatistics(); desc.setDatapathDescription("Datapath Description"); desc.setHardwareDescription("Hardware Description"); desc.setManufacturerDescription("Manufacturer Description"); desc.setSerialNumber("Serial Number"); desc.setSoftwareDescription("Software Description"); sr.setStatistics(Collections.singletonList(desc)); setupMessageEvent(Collections.<OFMessage>singletonList(sr)); setupMockStorageSource(cfg); reset(sw); sw.setChannel(channel); expectLastCall().once(); sw.setFloodlightProvider(controller); expectLastCall().once(); sw.setThreadPoolService(threadPool); expectLastCall().once(); sw.setDebugCounterService(debugCounterService); expectLastCall().once(); sw.setFeaturesReply(featuresReply); expectLastCall().once(); sw.setConnected(true); expectLastCall().once(); sw.getStringId(); expectLastCall().andReturn(cfg.dpid).atLeastOnce(); sw.isWriteThrottleEnabled(); // used for log message only expectLastCall().andReturn(false).anyTimes(); sw.setAccessFlowPriority(ACCESS_PRIORITY); expectLastCall().once(); sw.setCoreFlowPriority(CORE_PRIORITY); expectLastCall().once(); sw.startDriverHandshake(); expectLastCall().once(); sw.isDriverHandshakeComplete(); expectLastCall().andReturn(true).once(); if (cfg.isPresent) sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH, cfg.isCoreSwitch); replay(sw); // mock controller reset(controller); expect(controller.getDebugCounter()).andReturn(debugCounterService) .once(); controller.flushAll(); expectLastCall().once(); expect(controller.getThreadPoolService()) .andReturn(threadPool).once(); expect(controller.getOFSwitchInstance(eq(desc))) .andReturn(sw).once(); expect(controller.getCoreFlowPriority()) .andReturn(CORE_PRIORITY).once(); expect(controller.getAccessFlowPriority()) .andReturn(ACCESS_PRIORITY).once(); controller.addSwitchChannelAndSendInitialRole(handler); expectLastCall().once(); expect(controller.getStorageSourceService()) .andReturn(storageSource).atLeastOnce(); replay(controller); // send the description stats reply handler.messageReceived(ctx, messageEvent); assertEquals(OFChannelHandler.ChannelState.WAIT_INITIAL_ROLE, handler.getStateForTesting()); verifyStorageSource(); }
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java index 140926446..3b9691d8d 100644 --- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java +++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java @@ -1,520 +1,520 @@ /* * ==================================================================== * Copyright (c) 2004-2011 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.wc17; import java.io.File; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import java.util.logging.Level; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.ISVNCommitPathHandler; import org.tmatesoft.svn.core.internal.wc.SVNCommitUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNEventFactory; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.admin.SVNChecksumInputStream; import org.tmatesoft.svn.core.internal.wc.admin.SVNChecksumOutputStream; import org.tmatesoft.svn.core.internal.wc17.SVNWCContext.PristineContentsInfo; import org.tmatesoft.svn.core.internal.wc17.SVNWCContext.WritableBaseInfo; import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.WCDbInfo.InfoField; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNEventAction; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc2.SvnChecksum; import org.tmatesoft.svn.core.wc2.SvnCommitItem; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.4 * @author TMate Software Ltd. */ public class SVNCommitter17 implements ISVNCommitPathHandler { private SVNWCContext myContext; private Map<String, SvnCommitItem> myCommittables; private SVNURL myRepositoryRoot; private Map<File, SvnChecksum> myMd5Checksums; private Map<File, SvnChecksum> mySha1Checksums; private Map<String, SvnCommitItem> myModifiedFiles; private SVNDeltaGenerator myDeltaGenerator; private Collection<File> deletedPaths; public SVNCommitter17(SVNWCContext context, Map<String, SvnCommitItem> committables, SVNURL repositoryRoot, Collection<File> tmpFiles, Map<File, SvnChecksum> md5Checksums, Map<File, SvnChecksum> sha1Checksums) { myContext = context; myCommittables = committables; myRepositoryRoot = repositoryRoot; myMd5Checksums = md5Checksums; mySha1Checksums = sha1Checksums; myModifiedFiles = new TreeMap<String, SvnCommitItem>(); deletedPaths = new TreeSet<File>(); } public static SVNCommitInfo commit(SVNWCContext context, Collection<File> tmpFiles, Map<String, SvnCommitItem> committables, SVNURL repositoryRoot, ISVNEditor commitEditor, Map<File, SvnChecksum> md5Checksums, Map<File, SvnChecksum> sha1Checksums) throws SVNException { SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRoot, tmpFiles, md5Checksums, sha1Checksums); SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1); committer.sendTextDeltas(commitEditor); return commitEditor.closeEdit(); } public Collection<File> getDeletedPaths() { return deletedPaths; } public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException { SvnCommitItem item = myCommittables.get(commitPath); myContext.checkCancelled(); if (item.hasFlag(SvnCommitItem.COPY)) { if (item.getCopyFromUrl() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", item.getPath()); SVNErrorManager.error(err, SVNLogType.WC); } else if (item.getCopyFromRevision() < 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Commit item ''{0}'' has copy flag but an invalid revision", item.getPath()); SVNErrorManager.error(err, SVNLogType.WC); } } boolean closeDir = false; File localAbspath = null; if (item.getKind() != SVNNodeKind.NONE && item.getPath() != null) { localAbspath = item.getPath(); } long rev = item.getRevision(); SVNEvent event = null; if (item.hasFlag(SvnCommitItem.ADD) && item.hasFlag(SvnCommitItem.DELETE)) { event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_REPLACED, null, null, null); event.setPreviousRevision(rev); } else if (item.hasFlag(SvnCommitItem.DELETE)) { event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELETED, null, null, null); event.setPreviousRevision(rev); } else if (item.hasFlag(SvnCommitItem.ADD)) { String mimeType = null; if (item.getKind() == SVNNodeKind.FILE && localAbspath != null) { mimeType = myContext.getProperty(localAbspath, SVNProperty.MIME_TYPE); } event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), mimeType, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_ADDED, null, null, null); event.setPreviousRevision(item.getCopyFromRevision() >= 0 ? item.getCopyFromRevision() : -1); event.setPreviousURL(item.getCopyFromUrl()); } else if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) || item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { SVNStatusType contentState = SVNStatusType.UNCHANGED; if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED)) { contentState = SVNStatusType.CHANGED; } SVNStatusType propState = SVNStatusType.UNCHANGED; if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED) ) { propState = SVNStatusType.CHANGED; } event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, contentState, propState, null, SVNEventAction.COMMIT_MODIFIED, null, null, null); event.setPreviousRevision(rev); } if (event != null) { event.setURL(item.getUrl()); if (myContext.getEventHandler() != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } } if (item.hasFlag(SvnCommitItem.DELETE)) { try { commitEditor.deleteEntry(commitPath, rev); } catch (SVNException e) { - fixError(localAbspath, commitPath, e, SVNNodeKind.FILE); + fixError(localAbspath, commitPath, e, item.getKind()); } if (!item.hasFlag(SvnCommitItem.ADD)) { deletedPaths.add(localAbspath); } } long cfRev = item.getCopyFromRevision(); Map<String, SVNPropertyValue> outgoingProperties = item.getOutgoingProperties(); boolean fileOpen = false; if (item.hasFlag(SvnCommitItem.ADD)) { String copyFromPath = getCopyFromPath(item.getCopyFromUrl()); if (item.getKind() == SVNNodeKind.FILE) { commitEditor.addFile(commitPath, copyFromPath, cfRev); fileOpen = true; } else { commitEditor.addDir(commitPath, copyFromPath, cfRev); closeDir = true; } if (outgoingProperties != null) { for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) { String propName = propsIter.next(); SVNPropertyValue propValue = outgoingProperties.get(propName); if (item.getKind() == SVNNodeKind.FILE) { commitEditor.changeFileProperty(commitPath, propName, propValue); } else { commitEditor.changeDirProperty(propName, propValue); } } outgoingProperties = null; } } if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { // || (outgoingProperties != null && !outgoingProperties.isEmpty())) { if (item.getKind() == SVNNodeKind.FILE) { if (!fileOpen) { try { commitEditor.openFile(commitPath, rev); } catch (SVNException e) { fixError(localAbspath, commitPath, e, SVNNodeKind.FILE); } } fileOpen = true; } else if (!item.hasFlag(SvnCommitItem.ADD)) { // do not open dir twice. try { if ("".equals(commitPath)) { commitEditor.openRoot(rev); } else { commitEditor.openDir(commitPath, rev); } } catch (SVNException svne) { fixError(localAbspath, commitPath, svne, SVNNodeKind.DIR); } closeDir = true; } if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { try { sendPropertiesDelta(localAbspath, commitPath, item, commitEditor); } catch (SVNException e) { fixError(localAbspath, commitPath, e, item.getKind()); } } if (outgoingProperties != null) { for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) { String propName = propsIter.next(); SVNPropertyValue propValue = outgoingProperties.get(propName); if (item.getKind() == SVNNodeKind.FILE) { commitEditor.changeFileProperty(commitPath, propName, propValue); } else { commitEditor.changeDirProperty(propName, propValue); } } } } if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) && item.getKind() == SVNNodeKind.FILE) { if (!fileOpen) { try { commitEditor.openFile(commitPath, rev); } catch (SVNException e) { fixError(localAbspath, commitPath, e, SVNNodeKind.FILE); } } myModifiedFiles.put(commitPath, item); } else if (fileOpen) { commitEditor.closeFile(commitPath, null); } return closeDir; } private void fixError(File localAbspath, String path, SVNException e, SVNNodeKind kind) throws SVNException { SVNErrorMessage err = e.getErrorMessage(); if (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.FS_ALREADY_EXISTS || err.getErrorCode() == SVNErrorCode.FS_TXN_OUT_OF_DATE || err.getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND || err.getErrorCode() == SVNErrorCode.RA_DAV_ALREADY_EXISTS || err.hasChildWithErrorCode(SVNErrorCode.RA_OUT_OF_DATE)) { if (myContext.getEventHandler() != null) { SVNEvent event; if (localAbspath != null) { event = SVNEventFactory.createSVNEvent(localAbspath, kind, null, -1, SVNEventAction.FAILED_OUT_OF_DATE, null, err, null); } else { //TODO: add baseUrl parameter //TODO: add url-based events // event = SVNEventFactory.createSVNEvent(new File(path).getAbsoluteFile(), kind, null, -1, SVNEventAction.FAILED_OUT_OF_DATE, null, err, null); event = null; } if (event != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } } err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is out of date" : "File ''{0}'' is out of date", localAbspath); throw new SVNException(err); } else if (err.hasChildWithErrorCode(SVNErrorCode.FS_NO_LOCK_TOKEN) || err.getErrorCode() == SVNErrorCode.FS_LOCK_OWNER_MISMATCH || err.getErrorCode() == SVNErrorCode.RA_NOT_LOCKED) { if (myContext.getEventHandler() != null) { SVNEvent event; if (localAbspath != null) { event = SVNEventFactory.createSVNEvent(localAbspath, kind, null, -1, SVNEventAction.FAILED_LOCKED, null, err, null); } else { //TODO event = null; } if (event != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } } err = SVNErrorMessage.create(SVNErrorCode.CLIENT_NO_LOCK_TOKEN, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is locked in another working copy" : "File ''{0}'' is locked in another working copy", localAbspath); throw new SVNException(err); } else if (err.hasChildWithErrorCode(SVNErrorCode.RA_DAV_FORBIDDEN) || err.getErrorCode() == SVNErrorCode.AUTHZ_UNWRITABLE) { if (myContext.getEventHandler() != null) { SVNEvent event; if (localAbspath != null) { event = SVNEventFactory.createSVNEvent(localAbspath, kind, null, -1, SVNEventAction.FAILED_FORBIDDEN_BY_SERVER, null, err, null); } else { //TODO event = null; } if (event != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } err = SVNErrorMessage.create(SVNErrorCode.CLIENT_FORBIDDEN_BY_SERVER, kind == SVNNodeKind.DIR ? "Changing directory ''{0}'' is forbidden by the server" : "Changing file ''{0}'' is forbidden by the server", localAbspath); throw new SVNException(err); } } throw e; } private String getCopyFromPath(SVNURL url) { if (url == null) { return null; } String path = url.getPath(); if (myRepositoryRoot.getPath().equals(path)) { return "/"; } return path.substring(myRepositoryRoot.getPath().length()); } private void sendPropertiesDelta(File localAbspath, String commitPath, SvnCommitItem item, ISVNEditor commitEditor) throws SVNException { SVNNodeKind kind = myContext.readKind(localAbspath, false); SVNProperties propMods = myContext.getPropDiffs(localAbspath).propChanges; for (Object i : propMods.nameSet()) { String propName = (String) i; SVNPropertyValue propValue = propMods.getSVNPropertyValue(propName); if (kind == SVNNodeKind.FILE) { commitEditor.changeFileProperty(commitPath, propName, propValue); } else { commitEditor.changeDirProperty(propName, propValue); } } } public void sendTextDeltas(ISVNEditor editor) throws SVNException { for (String path : myModifiedFiles.keySet()) { SvnCommitItem item = myModifiedFiles.get(path); myContext.checkCancelled(); File itemAbspath = item.getPath(); if (myContext.getEventHandler() != null) { SVNEvent event = SVNEventFactory.createSVNEvent(itemAbspath, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELTA_SENT, null, null, null); myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } boolean fulltext = item.hasFlag(SvnCommitItem.ADD); TransmittedChecksums transmitTextDeltas = transmitTextDeltas(path, itemAbspath, fulltext, editor); SvnChecksum newTextBaseMd5Checksum = transmitTextDeltas.md5Checksum; SvnChecksum newTextBaseSha1Checksum = transmitTextDeltas.sha1Checksum; if (myMd5Checksums != null) { myMd5Checksums.put(itemAbspath, newTextBaseMd5Checksum); } if (mySha1Checksums != null) { mySha1Checksums.put(itemAbspath, newTextBaseSha1Checksum); } } } private static class TransmittedChecksums { public SvnChecksum md5Checksum; public SvnChecksum sha1Checksum; } private TransmittedChecksums transmitTextDeltas(String path, File localAbspath, boolean fulltext, ISVNEditor editor) throws SVNException { InputStream localStream = SVNFileUtil.DUMMY_IN; InputStream baseStream = SVNFileUtil.DUMMY_IN; SvnChecksum expectedMd5Checksum = null; SvnChecksum localMd5Checksum = null; SvnChecksum verifyChecksum = null; SVNChecksumOutputStream localSha1ChecksumStream = null; SVNChecksumInputStream verifyChecksumStream = null; SVNErrorMessage error = null; File newPristineTmpAbspath = null; try { localStream = myContext.getTranslatedStream(localAbspath, localAbspath, true, false); WritableBaseInfo openWritableBase = myContext.openWritableBase(localAbspath, false, true); OutputStream newPristineStream = openWritableBase.stream; newPristineTmpAbspath = openWritableBase.tempBaseAbspath; localSha1ChecksumStream = openWritableBase.sha1ChecksumStream; localStream = new CopyingStream(newPristineStream, localStream); File baseFile = null; if (!fulltext) { PristineContentsInfo pristineContents = myContext.getPristineContents(localAbspath, true, true); baseFile = pristineContents.path; baseStream = pristineContents.stream; if (baseStream == null) { baseStream = SVNFileUtil.DUMMY_IN; } expectedMd5Checksum = myContext.getDb().readInfo(localAbspath, InfoField.checksum).checksum; if (expectedMd5Checksum != null && expectedMd5Checksum.getKind() != SvnChecksum.Kind.md5) { expectedMd5Checksum = myContext.getDb().getPristineMD5(localAbspath, expectedMd5Checksum); } if (expectedMd5Checksum != null) { verifyChecksumStream = new SVNChecksumInputStream(baseStream, SVNChecksumInputStream.MD5_ALGORITHM); baseStream = verifyChecksumStream; } else { expectedMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, SVNFileUtil.computeChecksum(baseFile)); } } editor.applyTextDelta(path, expectedMd5Checksum!=null ? expectedMd5Checksum.getDigest() : null); if (myDeltaGenerator == null) { myDeltaGenerator = new SVNDeltaGenerator(); } localMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, myDeltaGenerator.sendDelta(path, baseStream, 0, localStream, editor, true)); if (verifyChecksumStream != null) { //SVNDeltaGenerator#sendDelta doesn't guarantee to read the whole stream (e.g. if baseStream has no data, it is not touched at all) //so we read verifyChecksumStream to force MD5 calculation readRemainingStream(verifyChecksumStream, baseFile); verifyChecksum = new SvnChecksum(SvnChecksum.Kind.md5, verifyChecksumStream.getDigest()); } } catch (SVNException svne) { error = svne.getErrorMessage().wrap("While preparing ''{0}'' for commit", localAbspath); } finally { SVNFileUtil.closeFile(localStream); SVNFileUtil.closeFile(baseStream); } if (expectedMd5Checksum != null && verifyChecksum != null && !expectedMd5Checksum.equals(verifyChecksum)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CHECKSUM_MISMATCH, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] { localAbspath, expectedMd5Checksum, verifyChecksum }); SVNErrorManager.error(err, SVNLogType.WC); } if (error != null) { SVNErrorManager.error(error, SVNLogType.WC); } try { editor.closeFile(path, localMd5Checksum!=null ? localMd5Checksum.getDigest() : null); } catch (SVNException e) { fixError(localAbspath, path, e, SVNNodeKind.FILE); } SvnChecksum localSha1Checksum = new SvnChecksum(SvnChecksum.Kind.sha1, localSha1ChecksumStream.getDigest()); myContext.getDb().installPristine(newPristineTmpAbspath, localSha1Checksum, localMd5Checksum); TransmittedChecksums result = new TransmittedChecksums(); result.md5Checksum = localMd5Checksum; result.sha1Checksum = localSha1Checksum; return result; } private void readRemainingStream(SVNChecksumInputStream verifyChecksumStream, File sourceFile) throws SVNException { final byte[] buffer = new byte[1024]; int bytesRead; do { try { bytesRead = verifyChecksumStream.read(buffer); } catch (IOException e) { SVNErrorMessage err; if (sourceFile != null) { err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read from file ''{0}'': {1}", new Object[]{ sourceFile, e.getMessage() }); } else { err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read from stream: {0}", new Object[]{ sourceFile, e.getMessage() }); } SVNErrorManager.error(err, Level.FINE, SVNLogType.WC); return; } } while (bytesRead >= 0); } private class CopyingStream extends FilterInputStream { private OutputStream myOutput; public CopyingStream(OutputStream out, InputStream in) { super(in); myOutput = out; } public int read() throws IOException { int r = super.read(); if (r != -1) { myOutput.write(r); } return r; } public int read(byte[] b) throws IOException { int r = super.read(b); if (r != -1) { myOutput.write(b, 0, r); } return r; } public int read(byte[] b, int off, int len) throws IOException { int r = super.read(b, off, len); if (r != -1) { myOutput.write(b, off, r); } return r; } public void close() throws IOException { try{ myOutput.close(); } finally { super.close(); } } } }
true
true
public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException { SvnCommitItem item = myCommittables.get(commitPath); myContext.checkCancelled(); if (item.hasFlag(SvnCommitItem.COPY)) { if (item.getCopyFromUrl() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", item.getPath()); SVNErrorManager.error(err, SVNLogType.WC); } else if (item.getCopyFromRevision() < 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Commit item ''{0}'' has copy flag but an invalid revision", item.getPath()); SVNErrorManager.error(err, SVNLogType.WC); } } boolean closeDir = false; File localAbspath = null; if (item.getKind() != SVNNodeKind.NONE && item.getPath() != null) { localAbspath = item.getPath(); } long rev = item.getRevision(); SVNEvent event = null; if (item.hasFlag(SvnCommitItem.ADD) && item.hasFlag(SvnCommitItem.DELETE)) { event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_REPLACED, null, null, null); event.setPreviousRevision(rev); } else if (item.hasFlag(SvnCommitItem.DELETE)) { event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELETED, null, null, null); event.setPreviousRevision(rev); } else if (item.hasFlag(SvnCommitItem.ADD)) { String mimeType = null; if (item.getKind() == SVNNodeKind.FILE && localAbspath != null) { mimeType = myContext.getProperty(localAbspath, SVNProperty.MIME_TYPE); } event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), mimeType, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_ADDED, null, null, null); event.setPreviousRevision(item.getCopyFromRevision() >= 0 ? item.getCopyFromRevision() : -1); event.setPreviousURL(item.getCopyFromUrl()); } else if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) || item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { SVNStatusType contentState = SVNStatusType.UNCHANGED; if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED)) { contentState = SVNStatusType.CHANGED; } SVNStatusType propState = SVNStatusType.UNCHANGED; if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED) ) { propState = SVNStatusType.CHANGED; } event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, contentState, propState, null, SVNEventAction.COMMIT_MODIFIED, null, null, null); event.setPreviousRevision(rev); } if (event != null) { event.setURL(item.getUrl()); if (myContext.getEventHandler() != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } } if (item.hasFlag(SvnCommitItem.DELETE)) { try { commitEditor.deleteEntry(commitPath, rev); } catch (SVNException e) { fixError(localAbspath, commitPath, e, SVNNodeKind.FILE); } if (!item.hasFlag(SvnCommitItem.ADD)) { deletedPaths.add(localAbspath); } } long cfRev = item.getCopyFromRevision(); Map<String, SVNPropertyValue> outgoingProperties = item.getOutgoingProperties(); boolean fileOpen = false; if (item.hasFlag(SvnCommitItem.ADD)) { String copyFromPath = getCopyFromPath(item.getCopyFromUrl()); if (item.getKind() == SVNNodeKind.FILE) { commitEditor.addFile(commitPath, copyFromPath, cfRev); fileOpen = true; } else { commitEditor.addDir(commitPath, copyFromPath, cfRev); closeDir = true; } if (outgoingProperties != null) { for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) { String propName = propsIter.next(); SVNPropertyValue propValue = outgoingProperties.get(propName); if (item.getKind() == SVNNodeKind.FILE) { commitEditor.changeFileProperty(commitPath, propName, propValue); } else { commitEditor.changeDirProperty(propName, propValue); } } outgoingProperties = null; } } if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { // || (outgoingProperties != null && !outgoingProperties.isEmpty())) { if (item.getKind() == SVNNodeKind.FILE) { if (!fileOpen) { try { commitEditor.openFile(commitPath, rev); } catch (SVNException e) { fixError(localAbspath, commitPath, e, SVNNodeKind.FILE); } } fileOpen = true; } else if (!item.hasFlag(SvnCommitItem.ADD)) { // do not open dir twice. try { if ("".equals(commitPath)) { commitEditor.openRoot(rev); } else { commitEditor.openDir(commitPath, rev); } } catch (SVNException svne) { fixError(localAbspath, commitPath, svne, SVNNodeKind.DIR); } closeDir = true; } if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { try { sendPropertiesDelta(localAbspath, commitPath, item, commitEditor); } catch (SVNException e) { fixError(localAbspath, commitPath, e, item.getKind()); } } if (outgoingProperties != null) { for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) { String propName = propsIter.next(); SVNPropertyValue propValue = outgoingProperties.get(propName); if (item.getKind() == SVNNodeKind.FILE) { commitEditor.changeFileProperty(commitPath, propName, propValue); } else { commitEditor.changeDirProperty(propName, propValue); } } } } if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) && item.getKind() == SVNNodeKind.FILE) { if (!fileOpen) { try { commitEditor.openFile(commitPath, rev); } catch (SVNException e) { fixError(localAbspath, commitPath, e, SVNNodeKind.FILE); } } myModifiedFiles.put(commitPath, item); } else if (fileOpen) { commitEditor.closeFile(commitPath, null); } return closeDir; } private void fixError(File localAbspath, String path, SVNException e, SVNNodeKind kind) throws SVNException { SVNErrorMessage err = e.getErrorMessage(); if (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.FS_ALREADY_EXISTS || err.getErrorCode() == SVNErrorCode.FS_TXN_OUT_OF_DATE || err.getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND || err.getErrorCode() == SVNErrorCode.RA_DAV_ALREADY_EXISTS || err.hasChildWithErrorCode(SVNErrorCode.RA_OUT_OF_DATE)) { if (myContext.getEventHandler() != null) { SVNEvent event; if (localAbspath != null) { event = SVNEventFactory.createSVNEvent(localAbspath, kind, null, -1, SVNEventAction.FAILED_OUT_OF_DATE, null, err, null); } else { //TODO: add baseUrl parameter //TODO: add url-based events // event = SVNEventFactory.createSVNEvent(new File(path).getAbsoluteFile(), kind, null, -1, SVNEventAction.FAILED_OUT_OF_DATE, null, err, null); event = null; } if (event != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } } err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is out of date" : "File ''{0}'' is out of date", localAbspath); throw new SVNException(err); } else if (err.hasChildWithErrorCode(SVNErrorCode.FS_NO_LOCK_TOKEN) || err.getErrorCode() == SVNErrorCode.FS_LOCK_OWNER_MISMATCH || err.getErrorCode() == SVNErrorCode.RA_NOT_LOCKED) { if (myContext.getEventHandler() != null) { SVNEvent event; if (localAbspath != null) { event = SVNEventFactory.createSVNEvent(localAbspath, kind, null, -1, SVNEventAction.FAILED_LOCKED, null, err, null); } else { //TODO event = null; } if (event != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } } err = SVNErrorMessage.create(SVNErrorCode.CLIENT_NO_LOCK_TOKEN, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is locked in another working copy" : "File ''{0}'' is locked in another working copy", localAbspath); throw new SVNException(err); } else if (err.hasChildWithErrorCode(SVNErrorCode.RA_DAV_FORBIDDEN) || err.getErrorCode() == SVNErrorCode.AUTHZ_UNWRITABLE) { if (myContext.getEventHandler() != null) { SVNEvent event; if (localAbspath != null) { event = SVNEventFactory.createSVNEvent(localAbspath, kind, null, -1, SVNEventAction.FAILED_FORBIDDEN_BY_SERVER, null, err, null); } else { //TODO event = null; } if (event != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } err = SVNErrorMessage.create(SVNErrorCode.CLIENT_FORBIDDEN_BY_SERVER, kind == SVNNodeKind.DIR ? "Changing directory ''{0}'' is forbidden by the server" : "Changing file ''{0}'' is forbidden by the server", localAbspath); throw new SVNException(err); } } throw e; } private String getCopyFromPath(SVNURL url) { if (url == null) { return null; } String path = url.getPath(); if (myRepositoryRoot.getPath().equals(path)) { return "/"; } return path.substring(myRepositoryRoot.getPath().length()); } private void sendPropertiesDelta(File localAbspath, String commitPath, SvnCommitItem item, ISVNEditor commitEditor) throws SVNException { SVNNodeKind kind = myContext.readKind(localAbspath, false); SVNProperties propMods = myContext.getPropDiffs(localAbspath).propChanges; for (Object i : propMods.nameSet()) { String propName = (String) i; SVNPropertyValue propValue = propMods.getSVNPropertyValue(propName); if (kind == SVNNodeKind.FILE) { commitEditor.changeFileProperty(commitPath, propName, propValue); } else { commitEditor.changeDirProperty(propName, propValue); } } } public void sendTextDeltas(ISVNEditor editor) throws SVNException { for (String path : myModifiedFiles.keySet()) { SvnCommitItem item = myModifiedFiles.get(path); myContext.checkCancelled(); File itemAbspath = item.getPath(); if (myContext.getEventHandler() != null) { SVNEvent event = SVNEventFactory.createSVNEvent(itemAbspath, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELTA_SENT, null, null, null); myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } boolean fulltext = item.hasFlag(SvnCommitItem.ADD); TransmittedChecksums transmitTextDeltas = transmitTextDeltas(path, itemAbspath, fulltext, editor); SvnChecksum newTextBaseMd5Checksum = transmitTextDeltas.md5Checksum; SvnChecksum newTextBaseSha1Checksum = transmitTextDeltas.sha1Checksum; if (myMd5Checksums != null) { myMd5Checksums.put(itemAbspath, newTextBaseMd5Checksum); } if (mySha1Checksums != null) { mySha1Checksums.put(itemAbspath, newTextBaseSha1Checksum); } } } private static class TransmittedChecksums { public SvnChecksum md5Checksum; public SvnChecksum sha1Checksum; } private TransmittedChecksums transmitTextDeltas(String path, File localAbspath, boolean fulltext, ISVNEditor editor) throws SVNException { InputStream localStream = SVNFileUtil.DUMMY_IN; InputStream baseStream = SVNFileUtil.DUMMY_IN; SvnChecksum expectedMd5Checksum = null; SvnChecksum localMd5Checksum = null; SvnChecksum verifyChecksum = null; SVNChecksumOutputStream localSha1ChecksumStream = null; SVNChecksumInputStream verifyChecksumStream = null; SVNErrorMessage error = null; File newPristineTmpAbspath = null; try { localStream = myContext.getTranslatedStream(localAbspath, localAbspath, true, false); WritableBaseInfo openWritableBase = myContext.openWritableBase(localAbspath, false, true); OutputStream newPristineStream = openWritableBase.stream; newPristineTmpAbspath = openWritableBase.tempBaseAbspath; localSha1ChecksumStream = openWritableBase.sha1ChecksumStream; localStream = new CopyingStream(newPristineStream, localStream); File baseFile = null; if (!fulltext) { PristineContentsInfo pristineContents = myContext.getPristineContents(localAbspath, true, true); baseFile = pristineContents.path; baseStream = pristineContents.stream; if (baseStream == null) { baseStream = SVNFileUtil.DUMMY_IN; } expectedMd5Checksum = myContext.getDb().readInfo(localAbspath, InfoField.checksum).checksum; if (expectedMd5Checksum != null && expectedMd5Checksum.getKind() != SvnChecksum.Kind.md5) { expectedMd5Checksum = myContext.getDb().getPristineMD5(localAbspath, expectedMd5Checksum); } if (expectedMd5Checksum != null) { verifyChecksumStream = new SVNChecksumInputStream(baseStream, SVNChecksumInputStream.MD5_ALGORITHM); baseStream = verifyChecksumStream; } else { expectedMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, SVNFileUtil.computeChecksum(baseFile)); } } editor.applyTextDelta(path, expectedMd5Checksum!=null ? expectedMd5Checksum.getDigest() : null); if (myDeltaGenerator == null) { myDeltaGenerator = new SVNDeltaGenerator(); } localMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, myDeltaGenerator.sendDelta(path, baseStream, 0, localStream, editor, true)); if (verifyChecksumStream != null) { //SVNDeltaGenerator#sendDelta doesn't guarantee to read the whole stream (e.g. if baseStream has no data, it is not touched at all) //so we read verifyChecksumStream to force MD5 calculation readRemainingStream(verifyChecksumStream, baseFile); verifyChecksum = new SvnChecksum(SvnChecksum.Kind.md5, verifyChecksumStream.getDigest()); } } catch (SVNException svne) { error = svne.getErrorMessage().wrap("While preparing ''{0}'' for commit", localAbspath); } finally { SVNFileUtil.closeFile(localStream); SVNFileUtil.closeFile(baseStream); } if (expectedMd5Checksum != null && verifyChecksum != null && !expectedMd5Checksum.equals(verifyChecksum)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CHECKSUM_MISMATCH, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] { localAbspath, expectedMd5Checksum, verifyChecksum }); SVNErrorManager.error(err, SVNLogType.WC); } if (error != null) { SVNErrorManager.error(error, SVNLogType.WC); } try { editor.closeFile(path, localMd5Checksum!=null ? localMd5Checksum.getDigest() : null); } catch (SVNException e) { fixError(localAbspath, path, e, SVNNodeKind.FILE); } SvnChecksum localSha1Checksum = new SvnChecksum(SvnChecksum.Kind.sha1, localSha1ChecksumStream.getDigest()); myContext.getDb().installPristine(newPristineTmpAbspath, localSha1Checksum, localMd5Checksum); TransmittedChecksums result = new TransmittedChecksums(); result.md5Checksum = localMd5Checksum; result.sha1Checksum = localSha1Checksum; return result; } private void readRemainingStream(SVNChecksumInputStream verifyChecksumStream, File sourceFile) throws SVNException { final byte[] buffer = new byte[1024]; int bytesRead; do { try { bytesRead = verifyChecksumStream.read(buffer); } catch (IOException e) { SVNErrorMessage err; if (sourceFile != null) { err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read from file ''{0}'': {1}", new Object[]{ sourceFile, e.getMessage() }); } else { err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read from stream: {0}", new Object[]{ sourceFile, e.getMessage() }); } SVNErrorManager.error(err, Level.FINE, SVNLogType.WC); return; } } while (bytesRead >= 0); } private class CopyingStream extends FilterInputStream { private OutputStream myOutput; public CopyingStream(OutputStream out, InputStream in) { super(in); myOutput = out; } public int read() throws IOException { int r = super.read(); if (r != -1) { myOutput.write(r); } return r; } public int read(byte[] b) throws IOException { int r = super.read(b); if (r != -1) { myOutput.write(b, 0, r); } return r; } public int read(byte[] b, int off, int len) throws IOException { int r = super.read(b, off, len); if (r != -1) { myOutput.write(b, off, r); } return r; } public void close() throws IOException { try{ myOutput.close(); } finally { super.close(); } } } }
public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException { SvnCommitItem item = myCommittables.get(commitPath); myContext.checkCancelled(); if (item.hasFlag(SvnCommitItem.COPY)) { if (item.getCopyFromUrl() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", item.getPath()); SVNErrorManager.error(err, SVNLogType.WC); } else if (item.getCopyFromRevision() < 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Commit item ''{0}'' has copy flag but an invalid revision", item.getPath()); SVNErrorManager.error(err, SVNLogType.WC); } } boolean closeDir = false; File localAbspath = null; if (item.getKind() != SVNNodeKind.NONE && item.getPath() != null) { localAbspath = item.getPath(); } long rev = item.getRevision(); SVNEvent event = null; if (item.hasFlag(SvnCommitItem.ADD) && item.hasFlag(SvnCommitItem.DELETE)) { event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_REPLACED, null, null, null); event.setPreviousRevision(rev); } else if (item.hasFlag(SvnCommitItem.DELETE)) { event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELETED, null, null, null); event.setPreviousRevision(rev); } else if (item.hasFlag(SvnCommitItem.ADD)) { String mimeType = null; if (item.getKind() == SVNNodeKind.FILE && localAbspath != null) { mimeType = myContext.getProperty(localAbspath, SVNProperty.MIME_TYPE); } event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), mimeType, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_ADDED, null, null, null); event.setPreviousRevision(item.getCopyFromRevision() >= 0 ? item.getCopyFromRevision() : -1); event.setPreviousURL(item.getCopyFromUrl()); } else if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) || item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { SVNStatusType contentState = SVNStatusType.UNCHANGED; if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED)) { contentState = SVNStatusType.CHANGED; } SVNStatusType propState = SVNStatusType.UNCHANGED; if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED) ) { propState = SVNStatusType.CHANGED; } event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, contentState, propState, null, SVNEventAction.COMMIT_MODIFIED, null, null, null); event.setPreviousRevision(rev); } if (event != null) { event.setURL(item.getUrl()); if (myContext.getEventHandler() != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } } if (item.hasFlag(SvnCommitItem.DELETE)) { try { commitEditor.deleteEntry(commitPath, rev); } catch (SVNException e) { fixError(localAbspath, commitPath, e, item.getKind()); } if (!item.hasFlag(SvnCommitItem.ADD)) { deletedPaths.add(localAbspath); } } long cfRev = item.getCopyFromRevision(); Map<String, SVNPropertyValue> outgoingProperties = item.getOutgoingProperties(); boolean fileOpen = false; if (item.hasFlag(SvnCommitItem.ADD)) { String copyFromPath = getCopyFromPath(item.getCopyFromUrl()); if (item.getKind() == SVNNodeKind.FILE) { commitEditor.addFile(commitPath, copyFromPath, cfRev); fileOpen = true; } else { commitEditor.addDir(commitPath, copyFromPath, cfRev); closeDir = true; } if (outgoingProperties != null) { for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) { String propName = propsIter.next(); SVNPropertyValue propValue = outgoingProperties.get(propName); if (item.getKind() == SVNNodeKind.FILE) { commitEditor.changeFileProperty(commitPath, propName, propValue); } else { commitEditor.changeDirProperty(propName, propValue); } } outgoingProperties = null; } } if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { // || (outgoingProperties != null && !outgoingProperties.isEmpty())) { if (item.getKind() == SVNNodeKind.FILE) { if (!fileOpen) { try { commitEditor.openFile(commitPath, rev); } catch (SVNException e) { fixError(localAbspath, commitPath, e, SVNNodeKind.FILE); } } fileOpen = true; } else if (!item.hasFlag(SvnCommitItem.ADD)) { // do not open dir twice. try { if ("".equals(commitPath)) { commitEditor.openRoot(rev); } else { commitEditor.openDir(commitPath, rev); } } catch (SVNException svne) { fixError(localAbspath, commitPath, svne, SVNNodeKind.DIR); } closeDir = true; } if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { try { sendPropertiesDelta(localAbspath, commitPath, item, commitEditor); } catch (SVNException e) { fixError(localAbspath, commitPath, e, item.getKind()); } } if (outgoingProperties != null) { for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) { String propName = propsIter.next(); SVNPropertyValue propValue = outgoingProperties.get(propName); if (item.getKind() == SVNNodeKind.FILE) { commitEditor.changeFileProperty(commitPath, propName, propValue); } else { commitEditor.changeDirProperty(propName, propValue); } } } } if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) && item.getKind() == SVNNodeKind.FILE) { if (!fileOpen) { try { commitEditor.openFile(commitPath, rev); } catch (SVNException e) { fixError(localAbspath, commitPath, e, SVNNodeKind.FILE); } } myModifiedFiles.put(commitPath, item); } else if (fileOpen) { commitEditor.closeFile(commitPath, null); } return closeDir; } private void fixError(File localAbspath, String path, SVNException e, SVNNodeKind kind) throws SVNException { SVNErrorMessage err = e.getErrorMessage(); if (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.FS_ALREADY_EXISTS || err.getErrorCode() == SVNErrorCode.FS_TXN_OUT_OF_DATE || err.getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND || err.getErrorCode() == SVNErrorCode.RA_DAV_ALREADY_EXISTS || err.hasChildWithErrorCode(SVNErrorCode.RA_OUT_OF_DATE)) { if (myContext.getEventHandler() != null) { SVNEvent event; if (localAbspath != null) { event = SVNEventFactory.createSVNEvent(localAbspath, kind, null, -1, SVNEventAction.FAILED_OUT_OF_DATE, null, err, null); } else { //TODO: add baseUrl parameter //TODO: add url-based events // event = SVNEventFactory.createSVNEvent(new File(path).getAbsoluteFile(), kind, null, -1, SVNEventAction.FAILED_OUT_OF_DATE, null, err, null); event = null; } if (event != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } } err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is out of date" : "File ''{0}'' is out of date", localAbspath); throw new SVNException(err); } else if (err.hasChildWithErrorCode(SVNErrorCode.FS_NO_LOCK_TOKEN) || err.getErrorCode() == SVNErrorCode.FS_LOCK_OWNER_MISMATCH || err.getErrorCode() == SVNErrorCode.RA_NOT_LOCKED) { if (myContext.getEventHandler() != null) { SVNEvent event; if (localAbspath != null) { event = SVNEventFactory.createSVNEvent(localAbspath, kind, null, -1, SVNEventAction.FAILED_LOCKED, null, err, null); } else { //TODO event = null; } if (event != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } } err = SVNErrorMessage.create(SVNErrorCode.CLIENT_NO_LOCK_TOKEN, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is locked in another working copy" : "File ''{0}'' is locked in another working copy", localAbspath); throw new SVNException(err); } else if (err.hasChildWithErrorCode(SVNErrorCode.RA_DAV_FORBIDDEN) || err.getErrorCode() == SVNErrorCode.AUTHZ_UNWRITABLE) { if (myContext.getEventHandler() != null) { SVNEvent event; if (localAbspath != null) { event = SVNEventFactory.createSVNEvent(localAbspath, kind, null, -1, SVNEventAction.FAILED_FORBIDDEN_BY_SERVER, null, err, null); } else { //TODO event = null; } if (event != null) { myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } err = SVNErrorMessage.create(SVNErrorCode.CLIENT_FORBIDDEN_BY_SERVER, kind == SVNNodeKind.DIR ? "Changing directory ''{0}'' is forbidden by the server" : "Changing file ''{0}'' is forbidden by the server", localAbspath); throw new SVNException(err); } } throw e; } private String getCopyFromPath(SVNURL url) { if (url == null) { return null; } String path = url.getPath(); if (myRepositoryRoot.getPath().equals(path)) { return "/"; } return path.substring(myRepositoryRoot.getPath().length()); } private void sendPropertiesDelta(File localAbspath, String commitPath, SvnCommitItem item, ISVNEditor commitEditor) throws SVNException { SVNNodeKind kind = myContext.readKind(localAbspath, false); SVNProperties propMods = myContext.getPropDiffs(localAbspath).propChanges; for (Object i : propMods.nameSet()) { String propName = (String) i; SVNPropertyValue propValue = propMods.getSVNPropertyValue(propName); if (kind == SVNNodeKind.FILE) { commitEditor.changeFileProperty(commitPath, propName, propValue); } else { commitEditor.changeDirProperty(propName, propValue); } } } public void sendTextDeltas(ISVNEditor editor) throws SVNException { for (String path : myModifiedFiles.keySet()) { SvnCommitItem item = myModifiedFiles.get(path); myContext.checkCancelled(); File itemAbspath = item.getPath(); if (myContext.getEventHandler() != null) { SVNEvent event = SVNEventFactory.createSVNEvent(itemAbspath, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELTA_SENT, null, null, null); myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN); } boolean fulltext = item.hasFlag(SvnCommitItem.ADD); TransmittedChecksums transmitTextDeltas = transmitTextDeltas(path, itemAbspath, fulltext, editor); SvnChecksum newTextBaseMd5Checksum = transmitTextDeltas.md5Checksum; SvnChecksum newTextBaseSha1Checksum = transmitTextDeltas.sha1Checksum; if (myMd5Checksums != null) { myMd5Checksums.put(itemAbspath, newTextBaseMd5Checksum); } if (mySha1Checksums != null) { mySha1Checksums.put(itemAbspath, newTextBaseSha1Checksum); } } } private static class TransmittedChecksums { public SvnChecksum md5Checksum; public SvnChecksum sha1Checksum; } private TransmittedChecksums transmitTextDeltas(String path, File localAbspath, boolean fulltext, ISVNEditor editor) throws SVNException { InputStream localStream = SVNFileUtil.DUMMY_IN; InputStream baseStream = SVNFileUtil.DUMMY_IN; SvnChecksum expectedMd5Checksum = null; SvnChecksum localMd5Checksum = null; SvnChecksum verifyChecksum = null; SVNChecksumOutputStream localSha1ChecksumStream = null; SVNChecksumInputStream verifyChecksumStream = null; SVNErrorMessage error = null; File newPristineTmpAbspath = null; try { localStream = myContext.getTranslatedStream(localAbspath, localAbspath, true, false); WritableBaseInfo openWritableBase = myContext.openWritableBase(localAbspath, false, true); OutputStream newPristineStream = openWritableBase.stream; newPristineTmpAbspath = openWritableBase.tempBaseAbspath; localSha1ChecksumStream = openWritableBase.sha1ChecksumStream; localStream = new CopyingStream(newPristineStream, localStream); File baseFile = null; if (!fulltext) { PristineContentsInfo pristineContents = myContext.getPristineContents(localAbspath, true, true); baseFile = pristineContents.path; baseStream = pristineContents.stream; if (baseStream == null) { baseStream = SVNFileUtil.DUMMY_IN; } expectedMd5Checksum = myContext.getDb().readInfo(localAbspath, InfoField.checksum).checksum; if (expectedMd5Checksum != null && expectedMd5Checksum.getKind() != SvnChecksum.Kind.md5) { expectedMd5Checksum = myContext.getDb().getPristineMD5(localAbspath, expectedMd5Checksum); } if (expectedMd5Checksum != null) { verifyChecksumStream = new SVNChecksumInputStream(baseStream, SVNChecksumInputStream.MD5_ALGORITHM); baseStream = verifyChecksumStream; } else { expectedMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, SVNFileUtil.computeChecksum(baseFile)); } } editor.applyTextDelta(path, expectedMd5Checksum!=null ? expectedMd5Checksum.getDigest() : null); if (myDeltaGenerator == null) { myDeltaGenerator = new SVNDeltaGenerator(); } localMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, myDeltaGenerator.sendDelta(path, baseStream, 0, localStream, editor, true)); if (verifyChecksumStream != null) { //SVNDeltaGenerator#sendDelta doesn't guarantee to read the whole stream (e.g. if baseStream has no data, it is not touched at all) //so we read verifyChecksumStream to force MD5 calculation readRemainingStream(verifyChecksumStream, baseFile); verifyChecksum = new SvnChecksum(SvnChecksum.Kind.md5, verifyChecksumStream.getDigest()); } } catch (SVNException svne) { error = svne.getErrorMessage().wrap("While preparing ''{0}'' for commit", localAbspath); } finally { SVNFileUtil.closeFile(localStream); SVNFileUtil.closeFile(baseStream); } if (expectedMd5Checksum != null && verifyChecksum != null && !expectedMd5Checksum.equals(verifyChecksum)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CHECKSUM_MISMATCH, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] { localAbspath, expectedMd5Checksum, verifyChecksum }); SVNErrorManager.error(err, SVNLogType.WC); } if (error != null) { SVNErrorManager.error(error, SVNLogType.WC); } try { editor.closeFile(path, localMd5Checksum!=null ? localMd5Checksum.getDigest() : null); } catch (SVNException e) { fixError(localAbspath, path, e, SVNNodeKind.FILE); } SvnChecksum localSha1Checksum = new SvnChecksum(SvnChecksum.Kind.sha1, localSha1ChecksumStream.getDigest()); myContext.getDb().installPristine(newPristineTmpAbspath, localSha1Checksum, localMd5Checksum); TransmittedChecksums result = new TransmittedChecksums(); result.md5Checksum = localMd5Checksum; result.sha1Checksum = localSha1Checksum; return result; } private void readRemainingStream(SVNChecksumInputStream verifyChecksumStream, File sourceFile) throws SVNException { final byte[] buffer = new byte[1024]; int bytesRead; do { try { bytesRead = verifyChecksumStream.read(buffer); } catch (IOException e) { SVNErrorMessage err; if (sourceFile != null) { err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read from file ''{0}'': {1}", new Object[]{ sourceFile, e.getMessage() }); } else { err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read from stream: {0}", new Object[]{ sourceFile, e.getMessage() }); } SVNErrorManager.error(err, Level.FINE, SVNLogType.WC); return; } } while (bytesRead >= 0); } private class CopyingStream extends FilterInputStream { private OutputStream myOutput; public CopyingStream(OutputStream out, InputStream in) { super(in); myOutput = out; } public int read() throws IOException { int r = super.read(); if (r != -1) { myOutput.write(r); } return r; } public int read(byte[] b) throws IOException { int r = super.read(b); if (r != -1) { myOutput.write(b, 0, r); } return r; } public int read(byte[] b, int off, int len) throws IOException { int r = super.read(b, off, len); if (r != -1) { myOutput.write(b, off, r); } return r; } public void close() throws IOException { try{ myOutput.close(); } finally { super.close(); } } } }
diff --git a/src/share/classes/com/sun/tools/javah/StaticJNIClassHelper.java b/src/share/classes/com/sun/tools/javah/StaticJNIClassHelper.java index eac0cbdd..20eb17ab 100644 --- a/src/share/classes/com/sun/tools/javah/StaticJNIClassHelper.java +++ b/src/share/classes/com/sun/tools/javah/StaticJNIClassHelper.java @@ -1,370 +1,370 @@ /* * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.javah; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import com.sun.tools.javah.staticjni.ArrayCallback; import com.sun.tools.javah.staticjni.Callback; import com.sun.tools.javah.staticjni.ExceptionCallback; import com.sun.tools.javah.staticjni.FieldCallback; import net.xymus.staticjni.NativeArrayAccess; import net.xymus.staticjni.NativeArrayAccesses; import net.xymus.staticjni.NativeArrayAccessCritical; import net.xymus.staticjni.NativeArrayAccessesCritical; import net.xymus.staticjni.NativeCall; import net.xymus.staticjni.NativeCalls; import net.xymus.staticjni.NativeNew; import net.xymus.staticjni.NativeNews; import net.xymus.staticjni.NativeSuperCall; /** * Header file generator for JNI. * * Not a true Gen, actually a wrapper for 3 other Gens */ public class StaticJNIClassHelper { StaticJNIClassHelper( StaticJNI gen ) { this.gen = gen; } StaticJNI gen; TypeElement currentClass = null; // Explicit calls Set<Callback> callbacks = new HashSet<Callback>(); Set<FieldCallback> fieldCallbacks = new HashSet<FieldCallback>(); Set<Callback> superCallbacks = new HashSet<Callback>(); Set<Callback> constCallbacks = new HashSet<Callback>(); Set<ExceptionCallback> exceptionCallbacks = new HashSet<ExceptionCallback>(); Set<ArrayCallback> arrayCallbacks = new HashSet<ArrayCallback>(); // Referred types Set<TypeMirror> referredTypes = new HashSet<TypeMirror>(); @SuppressWarnings("unchecked") public void setCurrentClass ( TypeElement clazz ) { if ( clazz != currentClass ) { currentClass = clazz; callbacks.clear(); fieldCallbacks.clear(); arrayCallbacks.clear(); referredTypes.clear(); List<ExecutableElement> classmethods = ElementFilter.methodsIn(clazz.getEnclosedElements()); for (ExecutableElement md: classmethods) { if(md.getModifiers().contains(Modifier.NATIVE)){ TypeMirror mtr = gen.types.erasure(md.getReturnType()); // return type if ( gen.advancedStaticType( mtr ) ) referredTypes.add( mtr ); // params type List<? extends VariableElement> paramargs = md.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! md.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = clazz.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // scan annotations for NativeCalls List<? extends AnnotationMirror> annotations = md.getAnnotationMirrors(); for ( AnnotationMirror annotation: annotations ) { String str = annotation.getAnnotationType().toString(); // NativeCall annotation if ( str.equals( NativeCall.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeCall( clazz, md, v.toString(), callbacks, fieldCallbacks ); } } // NativeCalls annotation if ( str.equals( NativeCalls.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { // elems.getConstantExpression tryToRegisterNativeCall( clazz, md, ((AnnotationValue)e).getValue().toString(), callbacks, fieldCallbacks ); } } // NativeNew annotation if ( str.equals( NativeNew.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeNew( clazz, md, v.toString(), constCallbacks ); } } // NativeNews annotation if ( str.equals( NativeNews.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { // elems.getConstantExpression tryToRegisterNativeNew( clazz, md, ((AnnotationValue)e).getValue().toString(), constCallbacks ); } } // super if ( str.equals( NativeSuperCall.class.getCanonicalName() ) ) { superCallbacks.add( new Callback(clazz, md) ); } // arrays if ( str.equals( NativeArrayAccess.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, false ); } } if ( str.equals( NativeArrayAccesses.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, false ); } } } // arrays critical - if ( str.equals( NativeArrayAccessesCritical.class.getCanonicalName() ) ) { + if ( str.equals( NativeArrayAccessCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, true ); } } if ( str.equals( NativeArrayAccessesCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, true ); } } } } // check possible throw from the throws keyword for ( TypeMirror t : md.getThrownTypes() ) { exceptionCallbacks.add( new ExceptionCallback(t) ); } // Scan imports for types for ( Callback cb: callbacks ) { ExecutableElement m = cb.meth; TypeMirror r = gen.types.erasure(m.getReturnType()); if ( gen.advancedStaticType(r) ) referredTypes.add( r ); paramargs = m.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! m.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = clazz.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } } for ( FieldCallback f: fieldCallbacks ) { TypeMirror t = f.recvType.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); t = f.field.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); } } } } } void tryToRegisterNativeCall(TypeElement clazz, ExecutableElement from_meth, String name, Set<Callback> callbacks, Set<FieldCallback> callbacks_to_field ) { TypeElement from_clazz = clazz; String from = from_clazz.toString() + "." + from_meth.toString(); // modifies args for non local calls String[] words = name.split(" "); if ( words.length > 1 ) { Element e = gen.elems.getTypeElement( words[0] ); if ( e != null && TypeElement.class.isInstance(e) ) { clazz = (TypeElement)e; name = words[1]; } else { gen.util.error("err.staticjni.classnotfound", words[0], from ); } } // try to find in methods List<ExecutableElement> methods = ElementFilter.methodsIn( clazz.getEnclosedElements() ); for (ExecutableElement m: methods) { if ( name.toString().equals( m.getSimpleName().toString() ) ) { callbacks.add( new Callback(clazz, m)); return; } } // try to find in fields List<VariableElement> fields = ElementFilter.fieldsIn( clazz.getEnclosedElements() ); for ( VariableElement f: fields ) { if ( f.getSimpleName().toString().equals( name ) ) { callbacks_to_field.add( new FieldCallback(clazz, f) ); return; } } gen.util.error("err.staticjni.methnotfound", name, from ); } void tryToRegisterNativeNew(TypeElement clazz, ExecutableElement from_meth, String name, Set<Callback> callbacks ) { TypeElement from_clazz = clazz; String from = from_clazz.toString() + "." + from_meth.toString(); // find class String[] words = name.split(" "); //if ( words.length > 1 ) { Element e = gen.elems.getTypeElement( words[0] ); if ( e != null && TypeElement.class.isInstance(e) ) { clazz = (TypeElement)e; } else { gen.util.error("err.staticjni.classnotfound", words[0], from ); } //} // return first constructor List<ExecutableElement> consts = ElementFilter.constructorsIn( clazz.getEnclosedElements() ); for (ExecutableElement c: consts) { callbacks.add( new Callback(clazz, c)); return; } gen.util.error("err.staticjni.methnotfound", name, from ); } void tryToRegisterNativeArrayAccess(TypeElement clazz, ExecutableElement from_meth, String name, Set<ArrayCallback> callbacks, boolean critical ) { TypeElement from_clazz = clazz; String from = from_clazz.toString() + "." + from_meth.toString(); int p = name.lastIndexOf("[]"); if ( p == -1 ) { gen.util.error("err.staticjni.arrayformatinvalid", name ); return; } // find class TypeMirror t = javaNameToType( name ); if ( t != null ) { callbacks.add(new ArrayCallback((ArrayType)t, critical )); return; } else { gen.util.error("err.staticjni.classnotfound", name, from ); } gen.util.error("err.staticjni.methnotfound", name, from ); } TypeMirror javaNameToType( String name ) { TypeMirror t; int p = name.lastIndexOf("[]"); if ( p != -1 ) { String sub_name = name.substring(0,p); t = javaNameToType( sub_name ); return gen.types.getArrayType(t); } if(name.equals("void")) return gen.types.getPrimitiveType( TypeKind.VOID ); if(name.equals("boolean")) return gen.types.getPrimitiveType( TypeKind.INT ); if(name.equals("byte")) return gen.types.getPrimitiveType( TypeKind.BYTE ); if(name.equals("char")) return gen.types.getPrimitiveType( TypeKind.CHAR ); if(name.equals("short")) return gen.types.getPrimitiveType( TypeKind.SHORT ); if(name.equals("int")) return gen.types.getPrimitiveType( TypeKind.INT ); if(name.equals("long")) return gen.types.getPrimitiveType( TypeKind.LONG ); if(name.equals("float")) return gen.types.getPrimitiveType( TypeKind.FLOAT ); if(name.equals("double")) return gen.types.getPrimitiveType( TypeKind.DOUBLE ); return gen.elems.getTypeElement( name ).asType(); } }
true
true
public void setCurrentClass ( TypeElement clazz ) { if ( clazz != currentClass ) { currentClass = clazz; callbacks.clear(); fieldCallbacks.clear(); arrayCallbacks.clear(); referredTypes.clear(); List<ExecutableElement> classmethods = ElementFilter.methodsIn(clazz.getEnclosedElements()); for (ExecutableElement md: classmethods) { if(md.getModifiers().contains(Modifier.NATIVE)){ TypeMirror mtr = gen.types.erasure(md.getReturnType()); // return type if ( gen.advancedStaticType( mtr ) ) referredTypes.add( mtr ); // params type List<? extends VariableElement> paramargs = md.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! md.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = clazz.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // scan annotations for NativeCalls List<? extends AnnotationMirror> annotations = md.getAnnotationMirrors(); for ( AnnotationMirror annotation: annotations ) { String str = annotation.getAnnotationType().toString(); // NativeCall annotation if ( str.equals( NativeCall.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeCall( clazz, md, v.toString(), callbacks, fieldCallbacks ); } } // NativeCalls annotation if ( str.equals( NativeCalls.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { // elems.getConstantExpression tryToRegisterNativeCall( clazz, md, ((AnnotationValue)e).getValue().toString(), callbacks, fieldCallbacks ); } } // NativeNew annotation if ( str.equals( NativeNew.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeNew( clazz, md, v.toString(), constCallbacks ); } } // NativeNews annotation if ( str.equals( NativeNews.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { // elems.getConstantExpression tryToRegisterNativeNew( clazz, md, ((AnnotationValue)e).getValue().toString(), constCallbacks ); } } // super if ( str.equals( NativeSuperCall.class.getCanonicalName() ) ) { superCallbacks.add( new Callback(clazz, md) ); } // arrays if ( str.equals( NativeArrayAccess.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, false ); } } if ( str.equals( NativeArrayAccesses.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, false ); } } } // arrays critical if ( str.equals( NativeArrayAccessesCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, true ); } } if ( str.equals( NativeArrayAccessesCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, true ); } } } } // check possible throw from the throws keyword for ( TypeMirror t : md.getThrownTypes() ) { exceptionCallbacks.add( new ExceptionCallback(t) ); } // Scan imports for types for ( Callback cb: callbacks ) { ExecutableElement m = cb.meth; TypeMirror r = gen.types.erasure(m.getReturnType()); if ( gen.advancedStaticType(r) ) referredTypes.add( r ); paramargs = m.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! m.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = clazz.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } } for ( FieldCallback f: fieldCallbacks ) { TypeMirror t = f.recvType.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); t = f.field.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); } } } } }
public void setCurrentClass ( TypeElement clazz ) { if ( clazz != currentClass ) { currentClass = clazz; callbacks.clear(); fieldCallbacks.clear(); arrayCallbacks.clear(); referredTypes.clear(); List<ExecutableElement> classmethods = ElementFilter.methodsIn(clazz.getEnclosedElements()); for (ExecutableElement md: classmethods) { if(md.getModifiers().contains(Modifier.NATIVE)){ TypeMirror mtr = gen.types.erasure(md.getReturnType()); // return type if ( gen.advancedStaticType( mtr ) ) referredTypes.add( mtr ); // params type List<? extends VariableElement> paramargs = md.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! md.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = clazz.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // scan annotations for NativeCalls List<? extends AnnotationMirror> annotations = md.getAnnotationMirrors(); for ( AnnotationMirror annotation: annotations ) { String str = annotation.getAnnotationType().toString(); // NativeCall annotation if ( str.equals( NativeCall.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeCall( clazz, md, v.toString(), callbacks, fieldCallbacks ); } } // NativeCalls annotation if ( str.equals( NativeCalls.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { // elems.getConstantExpression tryToRegisterNativeCall( clazz, md, ((AnnotationValue)e).getValue().toString(), callbacks, fieldCallbacks ); } } // NativeNew annotation if ( str.equals( NativeNew.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeNew( clazz, md, v.toString(), constCallbacks ); } } // NativeNews annotation if ( str.equals( NativeNews.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { // elems.getConstantExpression tryToRegisterNativeNew( clazz, md, ((AnnotationValue)e).getValue().toString(), constCallbacks ); } } // super if ( str.equals( NativeSuperCall.class.getCanonicalName() ) ) { superCallbacks.add( new Callback(clazz, md) ); } // arrays if ( str.equals( NativeArrayAccess.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, false ); } } if ( str.equals( NativeArrayAccesses.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, false ); } } } // arrays critical if ( str.equals( NativeArrayAccessCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, true ); } } if ( str.equals( NativeArrayAccessesCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, true ); } } } } // check possible throw from the throws keyword for ( TypeMirror t : md.getThrownTypes() ) { exceptionCallbacks.add( new ExceptionCallback(t) ); } // Scan imports for types for ( Callback cb: callbacks ) { ExecutableElement m = cb.meth; TypeMirror r = gen.types.erasure(m.getReturnType()); if ( gen.advancedStaticType(r) ) referredTypes.add( r ); paramargs = m.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! m.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = clazz.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } } for ( FieldCallback f: fieldCallbacks ) { TypeMirror t = f.recvType.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); t = f.field.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); } } } } }
diff --git a/src/main/java/nl/vu/datalayer/hbase/sail/HBaseSailConnection.java b/src/main/java/nl/vu/datalayer/hbase/sail/HBaseSailConnection.java index e70b18e..2e75f61 100644 --- a/src/main/java/nl/vu/datalayer/hbase/sail/HBaseSailConnection.java +++ b/src/main/java/nl/vu/datalayer/hbase/sail/HBaseSailConnection.java @@ -1,604 +1,604 @@ package nl.vu.datalayer.hbase.sail; import info.aduna.iteration.CloseableIteration; import info.aduna.iteration.CloseableIteratorIteration; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import nl.vu.datalayer.hbase.HBaseClientSolution; import org.openrdf.model.Namespace; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.impl.BNodeImpl; import org.openrdf.model.impl.ContextStatementImpl; import org.openrdf.model.impl.LiteralImpl; import org.openrdf.model.impl.StatementImpl; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.BindingSet; import org.openrdf.query.Dataset; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQueryResult; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.Var; import org.openrdf.query.impl.TupleQueryResultImpl; import org.openrdf.sail.NotifyingSailConnection; import org.openrdf.sail.SailException; import org.openrdf.sail.helpers.NotifyingSailConnectionBase; import org.openrdf.sail.helpers.SailBase; import org.openrdf.sail.memory.MemoryStore; /** * A connection to an HBase Sail object. This class implements methods to break down SPARQL * queries into statement patterns that can be used for querying HBase, to set up an in-memory * store for loading the quads retrieved from HBase, and finally, to run the intial SPARQL query * over the in-memory store and return the results. * <p> * This class implements * An HBaseSailConnection is active from the moment it is created until it is closed. Care * should be taken to properly close HBaseSailConnections as they might block concurrent queries * and/or updates on the Sail while active, depending on the Sail-implementation that is being * used. * * @author Anca Dumitrache */ public class HBaseSailConnection extends NotifyingSailConnectionBase { MemoryStore memStore; NotifyingSailConnection memStoreCon; HBaseClientSolution hbase; // Builder to write the query to bit by bit StringBuilder queryString = new StringBuilder(); /** * Establishes the connection to the HBase Sail, and sets up the in-memory store. * * @param sailBase */ public HBaseSailConnection(SailBase sailBase) { super(sailBase); // System.out.println("SailConnection created"); hbase = ((HBaseSail) sailBase).getHBase(); memStore = new MemoryStore(); try { memStore.initialize(); memStoreCon = memStore.getConnection(); } catch (SailException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override protected void addStatementInternal(Resource arg0, URI arg1, Value arg2, Resource... arg3) throws SailException { ArrayList<Statement> myList = new ArrayList(); Statement s = new StatementImpl(arg0, arg1, arg2); myList.add(s); // TODO: update method for adding quads // try { // HBaseClientSolution sol = // HBaseFactory.getHBaseSolution(HBHexastoreSchema.SCHEMA_NAME, con, // myList); // sol.schema.create(); // sol.util.populateTables(myList); // } // catch (Exception e) { // e.printStackTrace(); // // TODO error handling // } } @Override protected void clearInternal(Resource... arg0) throws SailException { // TODO Auto-generated method stub } @Override protected void clearNamespacesInternal() throws SailException { // TODO Auto-generated method stub } @Override protected void closeInternal() throws SailException { memStoreCon.close(); } @Override protected void commitInternal() throws SailException { // TODO Auto-generated method stub } @Override protected CloseableIteration<? extends Resource, SailException> getContextIDsInternal() throws SailException { // TODO Auto-generated method stub return null; } @Override protected String getNamespaceInternal(String arg0) throws SailException { // TODO Auto-generated method stub return null; } @Override protected CloseableIteration<? extends Namespace, SailException> getNamespacesInternal() throws SailException { // TODO Auto-generated method stub return null; } /** * This function sends a statement pattern to HBase for querying, * then returns the results in RDF Statement format. * * @param arg0 * @param arg1 * @param arg2 * @param arg3 * @param contexts * @return * @throws SailException */ protected CloseableIteration<? extends Statement, SailException> getStatementsInternal(Resource arg0, URI arg1, Value arg2, boolean arg3, Set<URI> contexts) throws SailException { try { ArrayList<Value> g = new ArrayList(); if (contexts != null && contexts.size() != 0) { for (Resource r : contexts) { g.add(r); } } else { g.add(null); } ArrayList<Statement> myList = new ArrayList(); for (Value graph : g) { System.out.println("HBase Query: " + arg0 + " - " + arg1 + " - " + arg2 + " - " + graph); Value[] query = { arg0, arg1, arg2, graph }; ArrayList<ArrayList<Value>> result = null; try { result = hbase.util.getResults(query); myList.addAll(reconstructTriples(result, query)); } catch (Exception e) { // empty list retrieved from HBase } } try { Iterator it = myList.iterator(); CloseableIteration<Statement, SailException> ci = new CloseableIteratorIteration<Statement, SailException>( it); return ci; } catch (Exception e) { // if there are no results to retrieve return null; } } catch (Exception e) { Exception ex = new SailException("HBase connection error: " + e.getMessage()); try { throw ex; } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return null; } /** * This function reconstructs RDF Statements from the list of Value items * returned from HBase. * * @param result * @param triple * @return * @throws SailException */ protected ArrayList<Statement> reconstructTriples(ArrayList<ArrayList<Value>> result, Value[] triple) throws SailException { ArrayList<Statement> list = new ArrayList(); for (ArrayList<Value> arrayList : result) { int index = 0; Resource s = null; URI p = null; Value o = null; Resource c = null; for (Value value : arrayList) { if (index == 0) { // s = (Resource)getSubject(value); s = (Resource) value; } else if (index == 1) { // p = (URI) getPredicate(value); p = (URI) value; } else if (index == 2) { // o = getObject(value); o = value; } else { // c = (Resource)getContext(value); c = (Resource) value; Statement statement = new ContextStatementImpl(s, p, o, c); list.add(statement); } index++; } } return list; } /** * This functions parses a String to return the subject in a query. * * @param s * @return */ Value getSubject(String s) { // System.out.println("SUBJECT: " + s); if (s.startsWith("_")) { return new BNodeImpl(s.substring(2)); } return new URIImpl(s); } /** * This functions parses a String to return the predicate in a query. * * @param s * @return */ Value getPredicate(String s) { // System.out.println("PREDICATE: " + s); return new URIImpl(s); } /** * This functions parses a String to return the object in a query. * * @param s * @return */ Value getObject(String s) { // System.out.println("OBJECT: " + s); if (s.startsWith("_")) { return new BNodeImpl(s.substring(2)); } else if (s.startsWith("\"")) { String literal = ""; String language = ""; String datatype = ""; for (int i = 1; i < s.length(); i++) { while (s.charAt(i) != '"') { // read literal value literal += s.charAt(i); if (s.charAt(i) == '\\') { i++; literal += s.charAt(i); } i++; if (i == s.length()) { // EOF exception } } // System.out.println(literal); // charAt(i) = '"', read next char i++; if (s.charAt(i) == '@') { // read language // System.out.println("reading language"); i++; while (i < s.length()) { language += s.charAt(i); i++; } // System.out.println(language); return new LiteralImpl(literal, language); } else if (s.charAt(i) == '^') { // read datatype i++; // check for second '^' if (i == s.length()) { // EOF exception } else if (s.charAt(i) != '^') { // incorrect formatting exception } i++; // check for '<' if (i == s.length()) { // EOF exception } else if (s.charAt(i) != '<') { // incorrect formatting exception } i++; while (s.charAt(i) != '>') { datatype += s.charAt(i); i++; if (i == s.length()) { // EOF exception } } // System.out.println(datatype); return new LiteralImpl(literal, new URIImpl(datatype)); } else { return new LiteralImpl(literal); } } } Value object; try { object = new URIImpl(s); } catch (Exception e) { object = new LiteralImpl(s); } return object; } /** * This functions parses a String to return the graph in a query. * * @param s * @return */ Value getContext(String s) { // System.out.println("GRAPH: " + s); return new URIImpl(s); } @Override protected void removeNamespaceInternal(String arg0) throws SailException { // TODO Auto-generated method stub } @Override protected void removeStatementsInternal(Resource arg0, URI arg1, Value arg2, Resource... arg3) throws SailException { // TODO Auto-generated method stub } @Override protected void rollbackInternal() throws SailException { // TODO Auto-generated method stub } @Override protected void setNamespaceInternal(String arg0, String arg1) throws SailException { // TODO Auto-generated method stub } @Override protected long sizeInternal(Resource... arg0) throws SailException { // TODO Auto-generated method stub return 0; } @Override protected void startTransactionInternal() throws SailException { // TODO Auto-generated method stub } /** * This function retrieves all the triples from HBase that match with * StatementPatterns in the SPARQL query, without executing the SPARQL query * on them. * * @param arg0 * @return * @throws SailException */ protected ArrayList<Statement> evaluateInternal(TupleExpr arg0, Dataset context) throws SailException { ArrayList<Statement> result = new ArrayList(); try { ArrayList<ArrayList<Var>> statements = HBaseQueryVisitor.convertToStatements(arg0, null, null); // System.out.println("StatementPatterns: " + statements.size()); // ArrayList<Var> contexts = HBaseQueryVisitor.getContexts(arg0); // ArrayList<Resource> cons = new ArrayList(); // Iterator qt = contexts.iterator(); // while (qt.hasNext()) { // Var context = (Var)qt.next(); // if (context != null) { // System.out.println(context.toString()); // } // } Set<URI> contexts; try { contexts = context.getNamedGraphs(); } catch (Exception e) { contexts = new HashSet(); } if (contexts != null && contexts.size() != 0) { for (URI gr : contexts) { System.out.println("CONTEXT FOUND: " + gr.stringValue()); } } Iterator it = statements.iterator(); while (it.hasNext()) { ArrayList<Var> sp = (ArrayList<Var>) it.next(); // System.out.println("CONTEXTS:"); // if (contexts != null) { // for (Var con : contexts) { // System.out.println("CONTEXT: " + con.toString()); // // cons.add((Resource)new URIImpl(con.)); // } // } Resource subj = null; URI pred = null; Value obj = null; Iterator jt = sp.iterator(); int index = 0; while (jt.hasNext()) { Var var = (Var) jt.next(); if (index == 0) { if (var.hasValue()) { subj = (Resource) getSubject(var.getValue().stringValue()); } else if (var.isAnonymous()) { subj = (Resource) getSubject(var.getName()); } } else if (index == 1) { if (var.hasValue()) { pred = (URI) getPredicate(var.getValue().stringValue()); } } else { if (var.hasValue()) { obj = getObject(var.getValue().stringValue()); - System.out.println("OBJECT: " + var.getValue().stringValue()); + System.out.println("OBJECT: " + var.getValue().toString()); } else if (var.isAnonymous()) { obj = getObject(var.getName()); } } index += 1; } if (obj != null) { - System.out.println("OBJECT:" + obj.stringValue()) ; +// System.out.println("OBJECT:" + obj.stringValue()) ; } CloseableIteration ci = getStatementsInternal(subj, pred, obj, false, contexts); while (ci.hasNext()) { Statement statement = (Statement) ci.next(); result.add(statement); } } } catch (Exception e) { throw new SailException(e); } return result; } @Override protected CloseableIteration<? extends BindingSet, QueryEvaluationException> evaluateInternal(TupleExpr arg0, Dataset arg1, BindingSet arg2, boolean arg3) throws SailException { return null; } /** * This function retrieves the relevant triples from HBase, loads them into * an in-memory store, then evaluates the SPARQL query on them. * * @param tupleExpr * @param dataset * @param bindings * @param includeInferred * @return * @throws SailException */ public TupleQueryResult query(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { // System.out.println("Evaluating query"); // System.out.println("EVALUATE:" + tupleExpr.toString()); try { ArrayList<Statement> statements = evaluateInternal(tupleExpr, dataset); // System.out.println("Statements retrieved: " + statements.size()); Resource[] context = null; try { Set<URI> contexts = dataset.getNamedGraphs(); context = new Resource[contexts.size()]; int index = 0; for (URI cont : contexts) { context[index] = cont; index++; } } catch (Exception e) { context = new Resource[1]; context[0] = new URIImpl("http://hbase.sail.vu.nl"); } Iterator it = statements.iterator(); while (it.hasNext()) { Statement statement = (Statement) it.next(); try { memStoreCon.addStatement(statement.getSubject(), statement.getPredicate(), statement.getObject(), context); } catch (Exception e) { System.out.println("THE FOLLOWING STATEMENT COULD NOT BE ADDED TO THE MEMORY STORE: " + statement.toString()); } } CloseableIteration<? extends BindingSet, QueryEvaluationException> ci = memStoreCon.evaluate(tupleExpr, dataset, bindings, includeInferred); CloseableIteration<? extends BindingSet, QueryEvaluationException> cj = memStoreCon.evaluate(tupleExpr, dataset, bindings, includeInferred); List<String> bindingList = new ArrayList<String>(); int index = 0; while (ci.hasNext()) { index++; BindingSet bs = ci.next(); Set<String> localBindings = bs.getBindingNames(); Iterator jt = localBindings.iterator(); while (jt.hasNext()) { String binding = (String) jt.next(); if (bindingList.contains(binding) == false) { bindingList.add(binding); } } } TupleQueryResult result = new TupleQueryResultImpl(bindingList, cj); return result; } catch (SailException e) { e.printStackTrace(); throw e; } catch (QueryEvaluationException e) { throw new SailException(e); } } @Override protected CloseableIteration<? extends Statement, SailException> getStatementsInternal(Resource arg0, URI arg1, Value arg2, boolean arg3, Resource... arg4) throws SailException { // TODO Auto-generated method stub return null; } }
false
true
protected ArrayList<Statement> evaluateInternal(TupleExpr arg0, Dataset context) throws SailException { ArrayList<Statement> result = new ArrayList(); try { ArrayList<ArrayList<Var>> statements = HBaseQueryVisitor.convertToStatements(arg0, null, null); // System.out.println("StatementPatterns: " + statements.size()); // ArrayList<Var> contexts = HBaseQueryVisitor.getContexts(arg0); // ArrayList<Resource> cons = new ArrayList(); // Iterator qt = contexts.iterator(); // while (qt.hasNext()) { // Var context = (Var)qt.next(); // if (context != null) { // System.out.println(context.toString()); // } // } Set<URI> contexts; try { contexts = context.getNamedGraphs(); } catch (Exception e) { contexts = new HashSet(); } if (contexts != null && contexts.size() != 0) { for (URI gr : contexts) { System.out.println("CONTEXT FOUND: " + gr.stringValue()); } } Iterator it = statements.iterator(); while (it.hasNext()) { ArrayList<Var> sp = (ArrayList<Var>) it.next(); // System.out.println("CONTEXTS:"); // if (contexts != null) { // for (Var con : contexts) { // System.out.println("CONTEXT: " + con.toString()); // // cons.add((Resource)new URIImpl(con.)); // } // } Resource subj = null; URI pred = null; Value obj = null; Iterator jt = sp.iterator(); int index = 0; while (jt.hasNext()) { Var var = (Var) jt.next(); if (index == 0) { if (var.hasValue()) { subj = (Resource) getSubject(var.getValue().stringValue()); } else if (var.isAnonymous()) { subj = (Resource) getSubject(var.getName()); } } else if (index == 1) { if (var.hasValue()) { pred = (URI) getPredicate(var.getValue().stringValue()); } } else { if (var.hasValue()) { obj = getObject(var.getValue().stringValue()); System.out.println("OBJECT: " + var.getValue().stringValue()); } else if (var.isAnonymous()) { obj = getObject(var.getName()); } } index += 1; } if (obj != null) { System.out.println("OBJECT:" + obj.stringValue()) ; } CloseableIteration ci = getStatementsInternal(subj, pred, obj, false, contexts); while (ci.hasNext()) { Statement statement = (Statement) ci.next(); result.add(statement); } } } catch (Exception e) { throw new SailException(e); } return result; }
protected ArrayList<Statement> evaluateInternal(TupleExpr arg0, Dataset context) throws SailException { ArrayList<Statement> result = new ArrayList(); try { ArrayList<ArrayList<Var>> statements = HBaseQueryVisitor.convertToStatements(arg0, null, null); // System.out.println("StatementPatterns: " + statements.size()); // ArrayList<Var> contexts = HBaseQueryVisitor.getContexts(arg0); // ArrayList<Resource> cons = new ArrayList(); // Iterator qt = contexts.iterator(); // while (qt.hasNext()) { // Var context = (Var)qt.next(); // if (context != null) { // System.out.println(context.toString()); // } // } Set<URI> contexts; try { contexts = context.getNamedGraphs(); } catch (Exception e) { contexts = new HashSet(); } if (contexts != null && contexts.size() != 0) { for (URI gr : contexts) { System.out.println("CONTEXT FOUND: " + gr.stringValue()); } } Iterator it = statements.iterator(); while (it.hasNext()) { ArrayList<Var> sp = (ArrayList<Var>) it.next(); // System.out.println("CONTEXTS:"); // if (contexts != null) { // for (Var con : contexts) { // System.out.println("CONTEXT: " + con.toString()); // // cons.add((Resource)new URIImpl(con.)); // } // } Resource subj = null; URI pred = null; Value obj = null; Iterator jt = sp.iterator(); int index = 0; while (jt.hasNext()) { Var var = (Var) jt.next(); if (index == 0) { if (var.hasValue()) { subj = (Resource) getSubject(var.getValue().stringValue()); } else if (var.isAnonymous()) { subj = (Resource) getSubject(var.getName()); } } else if (index == 1) { if (var.hasValue()) { pred = (URI) getPredicate(var.getValue().stringValue()); } } else { if (var.hasValue()) { obj = getObject(var.getValue().stringValue()); System.out.println("OBJECT: " + var.getValue().toString()); } else if (var.isAnonymous()) { obj = getObject(var.getName()); } } index += 1; } if (obj != null) { // System.out.println("OBJECT:" + obj.stringValue()) ; } CloseableIteration ci = getStatementsInternal(subj, pred, obj, false, contexts); while (ci.hasNext()) { Statement statement = (Statement) ci.next(); result.add(statement); } } } catch (Exception e) { throw new SailException(e); } return result; }
diff --git a/src/org/broad/igv/util/HttpUtils.java b/src/org/broad/igv/util/HttpUtils.java index c74ff11be..e3883d6b5 100644 --- a/src/org/broad/igv/util/HttpUtils.java +++ b/src/org/broad/igv/util/HttpUtils.java @@ -1,922 +1,921 @@ /* * Copyright (c) 2007-2012 The Broad Institute, Inc. * SOFTWARE COPYRIGHT NOTICE * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved. * * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. */ package org.broad.igv.util; import biz.source_code.base64Coder.Base64Coder; import net.sf.samtools.seekablestream.SeekableHTTPStream; import net.sf.samtools.util.ftp.FTPClient; import net.sf.samtools.util.ftp.FTPStream; import net.sf.samtools.util.ftp.FTPUtils; import org.apache.log4j.Logger; import org.apache.tomcat.util.HttpDate; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.exceptions.HttpResponseException; import org.broad.igv.gs.GSUtils; import org.broad.igv.ui.IGV; import org.broad.igv.util.stream.IGVUrlHelper; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.awt.*; import java.io.*; import java.net.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.List; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; /** * Wrapper utility class... for interacting with HttpURLConnection. * * @author Jim Robinson * @date 9/22/11 */ public class HttpUtils { private static Logger log = Logger.getLogger(HttpUtils.class); private static HttpUtils instance; private Map<String, Boolean> byteRangeTestMap; private ProxySettings proxySettings = null; private final int MAX_REDIRECTS = 5; private String defaultUserName = null; private char[] defaultPassword = null; private static Pattern URLmatcher = Pattern.compile(".{1,8}://.*"); // static provided to support unit testing private static boolean BYTE_RANGE_DISABLED = false; /** * @return the single instance */ public static HttpUtils getInstance() { if (instance == null) { instance = new HttpUtils(); } return instance; } private HttpUtils() { org.broad.tribble.util.ParsingUtils.registerHelperClass(IGVUrlHelper.class); disableCertificateValidation(); CookieHandler.setDefault(new IGVCookieManager()); Authenticator.setDefault(new IGVAuthenticator()); byteRangeTestMap = Collections.synchronizedMap(new HashMap()); } public static boolean isRemoteURL(String string) { String lcString = string.toLowerCase(); return lcString.startsWith("http://") || lcString.startsWith("https://") || lcString.startsWith("ftp://"); } /** * Provided to support unit testing (force disable byte range requests) * @return */ public static void disableByteRange(boolean b) { BYTE_RANGE_DISABLED = b; } /** * Join the {@code elements} with the character {@code joiner}, * URLencoding the {@code elements} along the way. {@code joiner} * is NOT URLEncoded * Example: * String[] parm_list = new String[]{"app les", "oranges", "bananas"}; * String formatted = buildURLString(Arrays.asList(parm_list), "+"); * <p/> * formatted will be "app%20les+oranges+bananas" * * @param elements * @param joiner * @return */ public static String buildURLString(Iterable<String> elements, String joiner) { Iterator<String> iter = elements.iterator(); if (!iter.hasNext()) { return ""; } String wholequery = iter.next(); try { while (iter.hasNext()) { wholequery += joiner + URLEncoder.encode(iter.next(), "UTF-8"); } return wholequery; } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Bad argument in genelist: " + e.getMessage()); } } /** * Return the contents of the url as a String. This method should only be used for queries expected to return * a small amount of data. * * @param url * @return * @throws IOException */ public String getContentsAsString(URL url) throws IOException { InputStream is = null; HttpURLConnection conn = openConnection(url, null); try { is = conn.getInputStream(); return readContents(is); } finally { if (is != null) is.close(); } } public String getContentsAsJSON(URL url) throws IOException { InputStream is = null; Map<String, String> reqProperties = new HashMap(); reqProperties.put("Accept", "application/json,text/plain"); HttpURLConnection conn = openConnection(url, reqProperties); try { is = conn.getInputStream(); return readContents(is); } finally { if (is != null) is.close(); } } /** * Open a connection stream for the URL. * * @param url * @return * @throws IOException */ public InputStream openConnectionStream(URL url) throws IOException { log.debug("Opening connection stream to " + url); if (url.getProtocol().toLowerCase().equals("ftp")) { String userInfo = url.getUserInfo(); String host = url.getHost(); String file = url.getPath(); FTPClient ftp = FTPUtils.connect(host, userInfo, new UserPasswordInputImpl()); ftp.pasv(); ftp.retr(file); return new FTPStream(ftp); } else { return openConnectionStream(url, null); } } public InputStream openConnectionStream(URL url, Map<String, String> requestProperties) throws IOException { HttpURLConnection conn = openConnection(url, requestProperties); if (conn == null) return null; InputStream input = conn.getInputStream(); if ("gzip".equals(conn.getContentEncoding())) { input = new GZIPInputStream(input); } return input; } public boolean resourceAvailable(URL url) { log.debug("Checking if resource is available: " + url); if (url.getProtocol().toLowerCase().equals("ftp")) { return FTPUtils.resourceAvailable(url); } try { HttpURLConnection conn = openConnection(url, null, "HEAD"); int code = conn.getResponseCode(); return code == 200; } catch (IOException e) { return false; } } public String getHeaderField(URL url, String key) throws IOException { HttpURLConnection conn = openConnection(url, null, "HEAD"); if (conn == null) return null; return conn.getHeaderField(key); } public long getLastModified(URL url) throws IOException{ HttpURLConnection conn = openConnection(url, null, "HEAD"); if (conn == null) return 0; return conn.getLastModified(); } public long getContentLength(URL url) throws IOException { String contentLengthString = getHeaderField(url, "Content-Length"); if (contentLengthString == null) { return -1; } else { return Long.parseLong(contentLengthString); } } /** * Compare a local and remote resource. * * @param file * @param url * @return true if the files are "the same", false if the remote file has been modified wrt the local one. * @throws IOException */ public boolean compareResources(File file, URL url) throws IOException { if (!file.exists()) { return false; } HttpURLConnection conn = openConnection(url, null, "HEAD"); // Check content-length first long contentLength = -1; String contentLengthString = conn.getHeaderField("Content-Length"); if (contentLengthString != null) { try { contentLength = Long.parseLong(contentLengthString); } catch (NumberFormatException e) { log.error("Error parsing content-length string: " + contentLengthString + " from URL: " + url.toString()); contentLength = -1; } } if (contentLength != file.length()) { return false; } // Compare last-modified dates String lastModifiedString = conn.getHeaderField("Last-Modified"); if (lastModifiedString == null) { return false; } else { HttpDate date = new HttpDate(); date.parse(lastModifiedString); long remoteModifiedTime = date.getTime(); long localModifiedTime = file.lastModified(); return remoteModifiedTime <= localModifiedTime; } } public void updateProxySettings() { boolean useProxy; String proxyHost; int proxyPort = -1; boolean auth = false; String user = null; String pw = null; PreferenceManager prefMgr = PreferenceManager.getInstance(); useProxy = prefMgr.getAsBoolean(PreferenceManager.USE_PROXY); proxyHost = prefMgr.get(PreferenceManager.PROXY_HOST, null); try { proxyPort = Integer.parseInt(prefMgr.get(PreferenceManager.PROXY_PORT, "-1")); } catch (NumberFormatException e) { proxyPort = -1; } auth = prefMgr.getAsBoolean(PreferenceManager.PROXY_AUTHENTICATE); user = prefMgr.get(PreferenceManager.PROXY_USER, null); String pwString = prefMgr.get(PreferenceManager.PROXY_PW, null); if (pwString != null) { pw = Utilities.base64Decode(pwString); } String proxyTypeString = prefMgr.get(PreferenceManager.PROXY_TYPE, "HTTP"); Proxy.Type type = proxyTypeString.equals("SOCKS") ? Proxy.Type.SOCKS : Proxy.Type.HTTP; proxySettings = new ProxySettings(useProxy, user, pw, auth, proxyHost, proxyPort, type); } public boolean downloadFile(String url, File outputFile) throws IOException { log.info("Downloading " + url + " to " + outputFile.getAbsolutePath()); HttpURLConnection conn = openConnection(new URL(url), null); long contentLength = -1; String contentLengthString = conn.getHeaderField("Content-Length"); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } log.info("Content length = " + contentLength); InputStream is = null; OutputStream out = null; try { is = conn.getInputStream(); out = new FileOutputStream(outputFile); byte[] buf = new byte[64 * 1024]; int downloaded = 0; int bytesRead = 0; while ((bytesRead = is.read(buf)) != -1) { out.write(buf, 0, bytesRead); downloaded += bytesRead; } log.info("Download complete. Total bytes downloaded = " + downloaded); } finally { if (is != null) is.close(); if (out != null) { out.flush(); out.close(); } } long fileLength = outputFile.length(); return contentLength <= 0 || contentLength == fileLength; } public void uploadGenomeSpaceFile(String uri, File file, Map<String, String> headers) throws IOException { HttpURLConnection urlconnection = null; OutputStream bos = null; URL url = new URL(uri); urlconnection = openConnection(url, headers, "PUT"); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); bos = new BufferedOutputStream(urlconnection.getOutputStream()); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); int i; // read byte by byte until end of stream while ((i = bis.read()) > 0) { bos.write(i); } bos.close(); int responseCode = urlconnection.getResponseCode(); // Error messages below. if (responseCode >= 400) { String message = readErrorStream(urlconnection); throw new IOException("Error uploading " + file.getName() + " : " + message); } } public String createGenomeSpaceDirectory(URL url, String body) throws IOException { HttpURLConnection urlconnection = null; OutputStream bos = null; Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); headers.put("Content-Length", String.valueOf(body.getBytes().length)); urlconnection = openConnection(url, headers, "PUT"); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); bos = new BufferedOutputStream(urlconnection.getOutputStream()); bos.write(body.getBytes()); bos.close(); int responseCode = urlconnection.getResponseCode(); // Error messages below. StringBuffer buf = new StringBuffer(); InputStream inputStream; if (responseCode >= 200 && responseCode < 300) { inputStream = urlconnection.getInputStream(); } else { inputStream = urlconnection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String nextLine; while ((nextLine = br.readLine()) != null) { buf.append(nextLine); buf.append('\n'); } inputStream.close(); if (responseCode >= 200 && responseCode < 300) { return buf.toString(); } else { throw new IOException("Error creating GS directory: " + buf.toString()); } } /** * Code for disabling SSL certification */ private void disableCertificateValidation() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (NoSuchAlgorithmException e) { } catch (KeyManagementException e) { } } private String readContents(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int b; while ((b = bis.read()) >= 0) { bos.write(b); } return new String(bos.toByteArray()); } private String readErrorStream(HttpURLConnection connection) throws IOException { InputStream inputStream = null; try { inputStream = connection.getErrorStream(); if (inputStream == null) { return null; } return readContents(inputStream); } finally { if (inputStream != null) inputStream.close(); } } public HttpURLConnection delete(URL url) throws IOException{ return openConnection(url, Collections.<String, String>emptyMap(), "DELETE"); } private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties) throws IOException { return openConnection(url, requestProperties, "GET"); } private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method) throws IOException { return openConnection(url, requestProperties, method, 0); } /** * The "real" connection method * * @param url * @param requestProperties * @param method * @return * @throws java.io.IOException */ private HttpURLConnection openConnection( URL url, Map<String, String> requestProperties, String method, int redirectCount) throws IOException { boolean useProxy = proxySettings != null && proxySettings.useProxy && proxySettings.proxyHost != null && proxySettings.proxyPort > 0; HttpURLConnection conn; if (useProxy) { Proxy proxy = new Proxy(proxySettings.type, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes(); String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes)); conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); } } else { conn = (HttpURLConnection) url.openConnection(); } if (GSUtils.isGenomeSpace(url)) { String token = GSUtils.getGSToken(); if (token != null) conn.setRequestProperty("Cookie", "gs-token=" + token); conn.setRequestProperty("Accept", "application/json,text/plain"); } else { conn.setRequestProperty("Accept", "text/plain"); } //------// - //We sometimes load very large files, trying to cache those can crash the server - //This is essentially a server bug, however through experience it has been found - //that setting useCaches to false works around it. + //There seems to be a bug with JWS caches + //So we avoid caching //This default is persistent, really should be available statically but isn't conn.setDefaultUseCaches(false); conn.setUseCaches(false); //------// conn.setConnectTimeout(Globals.CONNECT_TIMEOUT); conn.setReadTimeout(Globals.READ_TIMEOUT); conn.setRequestMethod(method); conn.setRequestProperty("Connection", "Keep-Alive"); if (requestProperties != null) { for (Map.Entry<String, String> prop : requestProperties.entrySet()) { conn.setRequestProperty(prop.getKey(), prop.getValue()); } } conn.setRequestProperty("User-Agent", Globals.applicationString()); if (method.equals("PUT")) { return conn; } else { int code = conn.getResponseCode(); // Redirects. These can occur even if followRedirects == true if there is a change in protocol, // for example http -> https. if (code >= 300 && code < 400) { if (redirectCount > MAX_REDIRECTS) { throw new IOException("Too many redirects"); } String newLocation = conn.getHeaderField("Location"); log.debug("Redirecting to " + newLocation); return openConnection(new URL(newLocation), requestProperties, method, redirectCount++); } // TODO -- handle other response codes. else if (code >= 400) { String message; if (code == 404) { message = "File not found: " + url.toString(); throw new FileNotFoundException(message); } else if (code == 401) { // Looks like this only happens when user hits "Cancel". // message = "Not authorized to view this file"; // JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE); redirectCount = MAX_REDIRECTS + 1; return null; } else { message = conn.getResponseMessage(); } String details = readErrorStream(conn); log.debug("error stream: " + details); log.debug(message); HttpResponseException exc = new HttpResponseException(code); throw exc; } } return conn; } public void setDefaultPassword(String defaultPassword) { this.defaultPassword = defaultPassword.toCharArray(); } public void setDefaultUserName(String defaultUserName) { this.defaultUserName = defaultUserName; } public void clearDefaultCredentials() { this.defaultPassword = null; this.defaultUserName = null; } /** * Test to see if this client can successfully retrieve a portion of a remote file using the byte-range header. * This is not a test of the server, but the client. In some environments the byte-range header gets removed * by filters after the request is made by IGV. * * @return */ public boolean useByteRange(URL url) { if(BYTE_RANGE_DISABLED) return false; // We can test byte-range success for hosts we can reach. final String host = url.getHost(); if (byteRangeTestMap.containsKey(host)) { return byteRangeTestMap.get(host); } else { try { boolean byteRangeTestSuccess = true; if (host.contains("broadinstitute.org")) { byteRangeTestSuccess = testBroadHost(host); } else { // Non-broad URL byte[] firstBytes = getFirstBytes(url, 10000); if (firstBytes.length > 1000) { int end = firstBytes.length; int start = end - 100; SeekableHTTPStream str = new SeekableHTTPStream(url); str.seek(start); int len = end - start; byte[] buffer = new byte[len]; int n = 0; while (n < len) { int count = str.read(buffer, n, len - n); if (count < 0) throw new EOFException(); n += count; } for (int i = 0; i < len; i++) { if (buffer[i] != firstBytes[i + start]) { byteRangeTestSuccess = false; } } } else { // Too small a sample to test, return "true" but don't record this host as tested. return true; } } if (byteRangeTestSuccess) { log.info("Range-byte request succeeded"); } else { log.info("Range-byte test failed -- problem with client network environment."); } byteRangeTestMap.put(host, byteRangeTestSuccess); return byteRangeTestSuccess; } catch (IOException e) { log.error("Error while testing byte range " + e.getMessage()); // We could not reach the test server, so we can't know if this client can do byte-range tests or // not. Take the "optimistic" view. return true; } } } private boolean testBroadHost(String host) throws IOException { // Test broad urls for successful byte range requests. log.info("Testing range-byte request on host: " + host); String testURL; if (host.startsWith("igvdata.broadinstitute.org")) { // Amazon cloud front testURL = "http://igvdata.broadinstitute.org/genomes/seq/hg19/chr12.txt"; } else if (host.startsWith("igv.broadinstitute.org")) { // Amazon S3 testURL = "http://igv.broadinstitute.org/genomes/seq/hg19/chr12.txt"; } else { // All others testURL = "http://www.broadinstitute.org/igvdata/annotations/seq/hg19/chr12.txt"; } byte[] expectedBytes = {'T', 'C', 'G', 'C', 'T', 'T', 'G', 'A', 'A', 'C', 'C', 'C', 'G', 'G', 'G', 'A', 'G', 'A', 'G', 'G'}; SeekableHTTPStream str = new SeekableHTTPStream(new URL(testURL)); str.seek(25350000); byte[] buffer = new byte[80000]; str.read(buffer); String result = new String(buffer); for (int i = 0; i < expectedBytes.length; i++) { if (buffer[i] != expectedBytes[i]) { return false; } } return true; } /** * Return the first bytes of content from the URL. The number of bytes returned is ~ nominalLength. * * @param url * @param nominalLength * @return * @throws IOException */ private byte[] getFirstBytes(URL url, int nominalLength) throws IOException { InputStream is = null; try { is = url.openStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int b; while ((b = bis.read()) >= 0) { bos.write(b); if (bos.size() >= nominalLength) { break; } } return bos.toByteArray(); } finally { if (is != null) is.close(); } } public void shutdown() { // Do any cleanup required here } /** * Checks if the string is a URL (not necessarily remote, can be any protocol) * * @param f * @return */ public static boolean isURL(String f) { return f.startsWith("http:") || f.startsWith("ftp:") || f.startsWith("https:") || URLmatcher.matcher(f).matches(); } public static class ProxySettings { boolean auth = false; String user; String pw; boolean useProxy; String proxyHost; int proxyPort = -1; Proxy.Type type; public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort) { this(useProxy, user, pw, auth, proxyHost, proxyPort, Proxy.Type.HTTP); this.auth = auth; } public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort, Proxy.Type proxyType) { this.auth = auth; this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.pw = pw; this.useProxy = useProxy; this.user = user; this.type = proxyType; } } /** * The default authenticator */ public class IGVAuthenticator extends Authenticator { Hashtable<String, PasswordAuthentication> pwCache = new Hashtable<String, PasswordAuthentication>(); HashSet<String> cacheAttempts = new HashSet<String>(); /** * Called when password authentication is needed. * * @return */ @Override protected synchronized PasswordAuthentication getPasswordAuthentication() { RequestorType type = getRequestorType(); String urlString = getRequestingURL().toString(); boolean isProxyChallenge = type == RequestorType.PROXY; // Cache user entered PWs. In normal use this shouldn't be necessary as credentials are cached upstream, // but if loading many files in parallel (e.g. from sessions) calls to this method can queue up before the // user enters their credentials, causing needless reentry. String pKey = type.toString() + getRequestingProtocol() + getRequestingHost(); PasswordAuthentication pw = pwCache.get(pKey); if (pw != null) { // Prevents infinite loop if credentials are incorrect if (cacheAttempts.contains(urlString)) { cacheAttempts.remove(urlString); } else { cacheAttempts.add(urlString); return pw; } } if (isProxyChallenge) { if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { return new PasswordAuthentication(proxySettings.user, proxySettings.pw.toCharArray()); } } if (defaultUserName != null && defaultPassword != null) { return new PasswordAuthentication(defaultUserName, defaultPassword); } Frame owner = IGV.hasInstance() ? IGV.getMainFrame() : null; boolean isGenomeSpace = GSUtils.isGenomeSpace(getRequestingURL()); if (isGenomeSpace) { // If we are being challenged by GS the token must be bad/expired GSUtils.logout(); } LoginDialog dlg = new LoginDialog(owner, isGenomeSpace, urlString, isProxyChallenge); dlg.setVisible(true); if (dlg.isCanceled()) { return null; } else { final String userString = dlg.getUsername(); final char[] userPass = dlg.getPassword(); if (isProxyChallenge) { proxySettings.user = userString; proxySettings.pw = new String(userPass); } pw = new PasswordAuthentication(userString, userPass); pwCache.put(pKey, pw); return pw; } } } /** * Provide override for unit tests */ public void setAuthenticator(Authenticator authenticator) { Authenticator.setDefault(authenticator); } /** * For unit tests */ public void resetAuthenticator() { Authenticator.setDefault(new IGVAuthenticator()); } /** * Extension of CookieManager that grabs cookies from the GenomeSpace identity server to store locally. * This is to support the GenomeSpace "single sign-on". Examples ... * gs-username=igvtest; Domain=.genomespace.org; Expires=Mon, 21-Jul-2031 03:27:23 GMT; Path=/ * gs-token=HnR9rBShNO4dTXk8cKXVJT98Oe0jWVY+; Domain=.genomespace.org; Expires=Mon, 21-Jul-2031 03:27:23 GMT; Path=/ */ static class IGVCookieManager extends CookieManager { @Override public void put(URI uri, Map<String, List<String>> stringListMap) throws IOException { if (uri.toString().startsWith(PreferenceManager.getInstance().get(PreferenceManager.GENOME_SPACE_IDENTITY_SERVER))) { List<String> cookies = stringListMap.get("Set-Cookie"); if (cookies != null) { for (String cstring : cookies) { String[] tokens = Globals.equalPattern.split(cstring); if (tokens.length >= 2) { String cookieName = tokens[0]; String[] vTokens = Globals.semicolonPattern.split(tokens[1]); String value = vTokens[0]; if (cookieName.equals("gs-token")) { GSUtils.setGSToken(value); } else if (cookieName.equals("gs-username")) { GSUtils.setGSUser(value); } } } } } super.put(uri, stringListMap); } } }
true
true
private HttpURLConnection openConnection( URL url, Map<String, String> requestProperties, String method, int redirectCount) throws IOException { boolean useProxy = proxySettings != null && proxySettings.useProxy && proxySettings.proxyHost != null && proxySettings.proxyPort > 0; HttpURLConnection conn; if (useProxy) { Proxy proxy = new Proxy(proxySettings.type, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes(); String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes)); conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); } } else { conn = (HttpURLConnection) url.openConnection(); } if (GSUtils.isGenomeSpace(url)) { String token = GSUtils.getGSToken(); if (token != null) conn.setRequestProperty("Cookie", "gs-token=" + token); conn.setRequestProperty("Accept", "application/json,text/plain"); } else { conn.setRequestProperty("Accept", "text/plain"); } //------// //We sometimes load very large files, trying to cache those can crash the server //This is essentially a server bug, however through experience it has been found //that setting useCaches to false works around it. //This default is persistent, really should be available statically but isn't conn.setDefaultUseCaches(false); conn.setUseCaches(false); //------// conn.setConnectTimeout(Globals.CONNECT_TIMEOUT); conn.setReadTimeout(Globals.READ_TIMEOUT); conn.setRequestMethod(method); conn.setRequestProperty("Connection", "Keep-Alive"); if (requestProperties != null) { for (Map.Entry<String, String> prop : requestProperties.entrySet()) { conn.setRequestProperty(prop.getKey(), prop.getValue()); } } conn.setRequestProperty("User-Agent", Globals.applicationString()); if (method.equals("PUT")) { return conn; } else { int code = conn.getResponseCode(); // Redirects. These can occur even if followRedirects == true if there is a change in protocol, // for example http -> https. if (code >= 300 && code < 400) { if (redirectCount > MAX_REDIRECTS) { throw new IOException("Too many redirects"); } String newLocation = conn.getHeaderField("Location"); log.debug("Redirecting to " + newLocation); return openConnection(new URL(newLocation), requestProperties, method, redirectCount++); } // TODO -- handle other response codes. else if (code >= 400) { String message; if (code == 404) { message = "File not found: " + url.toString(); throw new FileNotFoundException(message); } else if (code == 401) { // Looks like this only happens when user hits "Cancel". // message = "Not authorized to view this file"; // JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE); redirectCount = MAX_REDIRECTS + 1; return null; } else { message = conn.getResponseMessage(); } String details = readErrorStream(conn); log.debug("error stream: " + details); log.debug(message); HttpResponseException exc = new HttpResponseException(code); throw exc; } } return conn; }
private HttpURLConnection openConnection( URL url, Map<String, String> requestProperties, String method, int redirectCount) throws IOException { boolean useProxy = proxySettings != null && proxySettings.useProxy && proxySettings.proxyHost != null && proxySettings.proxyPort > 0; HttpURLConnection conn; if (useProxy) { Proxy proxy = new Proxy(proxySettings.type, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes(); String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes)); conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); } } else { conn = (HttpURLConnection) url.openConnection(); } if (GSUtils.isGenomeSpace(url)) { String token = GSUtils.getGSToken(); if (token != null) conn.setRequestProperty("Cookie", "gs-token=" + token); conn.setRequestProperty("Accept", "application/json,text/plain"); } else { conn.setRequestProperty("Accept", "text/plain"); } //------// //There seems to be a bug with JWS caches //So we avoid caching //This default is persistent, really should be available statically but isn't conn.setDefaultUseCaches(false); conn.setUseCaches(false); //------// conn.setConnectTimeout(Globals.CONNECT_TIMEOUT); conn.setReadTimeout(Globals.READ_TIMEOUT); conn.setRequestMethod(method); conn.setRequestProperty("Connection", "Keep-Alive"); if (requestProperties != null) { for (Map.Entry<String, String> prop : requestProperties.entrySet()) { conn.setRequestProperty(prop.getKey(), prop.getValue()); } } conn.setRequestProperty("User-Agent", Globals.applicationString()); if (method.equals("PUT")) { return conn; } else { int code = conn.getResponseCode(); // Redirects. These can occur even if followRedirects == true if there is a change in protocol, // for example http -> https. if (code >= 300 && code < 400) { if (redirectCount > MAX_REDIRECTS) { throw new IOException("Too many redirects"); } String newLocation = conn.getHeaderField("Location"); log.debug("Redirecting to " + newLocation); return openConnection(new URL(newLocation), requestProperties, method, redirectCount++); } // TODO -- handle other response codes. else if (code >= 400) { String message; if (code == 404) { message = "File not found: " + url.toString(); throw new FileNotFoundException(message); } else if (code == 401) { // Looks like this only happens when user hits "Cancel". // message = "Not authorized to view this file"; // JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE); redirectCount = MAX_REDIRECTS + 1; return null; } else { message = conn.getResponseMessage(); } String details = readErrorStream(conn); log.debug("error stream: " + details); log.debug(message); HttpResponseException exc = new HttpResponseException(code); throw exc; } } return conn; }
diff --git a/framework/src/play/db/jpa/JPAPlugin.java b/framework/src/play/db/jpa/JPAPlugin.java index 7c579e68..e7f042cb 100644 --- a/framework/src/play/db/jpa/JPAPlugin.java +++ b/framework/src/play/db/jpa/JPAPlugin.java @@ -1,281 +1,281 @@ package play.db.jpa; import java.io.Serializable; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import java.util.Properties; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.FlushModeType; import javax.persistence.PersistenceException; import javax.persistence.Query; import org.apache.log4j.Level; import org.hibernate.CallbackException; import org.hibernate.EmptyInterceptor; import org.hibernate.collection.PersistentCollection; import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.type.Type; import play.Logger; import play.Play; import play.PlayPlugin; import play.db.DB; import play.exceptions.JPAException; import play.utils.Utils; /** * JPA Plugin */ public class JPAPlugin extends PlayPlugin { public static boolean autoTxs = true; @Override public Object bind(String name, Class clazz, java.lang.reflect.Type type, Map<String, String[]> params) { if(!Play.configuration.getProperty("future.bindJPAObjects", "false").equals("true")) { return null; } // TODO need to be more generic in order to work with JPASupport if(JPASupport.class.isAssignableFrom(clazz)) { String idKey = name + ".id"; if(params.containsKey(idKey) && params.get(idKey).length > 0 && params.get(idKey)[0] != null && params.get(idKey)[0].trim().length() > 0) { String id = params.get(idKey)[0]; try { Query query = JPA.em().createQuery("from " + clazz.getName() + " o where o.id = ?"); query.setParameter(1, play.data.binding.Binder.directBind(id + "", play.db.jpa.JPASupport.findKeyType(clazz))); Object o = query.getSingleResult(); return JPASupport.edit(o, name, params); } catch(Exception e) { return null; } } return JPASupport.create(clazz, name, params); } return super.bind(name, clazz, type, params); } @Override public void onApplicationStart() { if (JPA.entityManagerFactory == null) { List<Class> classes = Play.classloader.getAnnotatedClasses(Entity.class); - if (classes.isEmpty()) { + if (classes.isEmpty() && Play.configuration.getProperty("jpa.entities", "").equals("")) { return; } if (DB.datasource == null) { throw new JPAException("Cannot start a JPA manager without a properly configured database", new NullPointerException("No datasource")); } Ejb3Configuration cfg = new Ejb3Configuration(); cfg.setDataSource(DB.datasource); if (!Play.configuration.getProperty("jpa.ddl", "update").equals("none")) { cfg.setProperty("hibernate.hbm2ddl.auto", Play.configuration.getProperty("jpa.ddl", "update")); } cfg.setProperty("hibernate.dialect", getDefaultDialect(Play.configuration.getProperty("db.driver"))); cfg.setProperty("javax.persistence.transaction", "RESOURCE_LOCAL"); // Explicit SAVE for JPASupport is implemented here // ~~~~~~ // We've hacked the org.hibernate.event.def.AbstractFlushingEventListener line 271, to flush collection update,remove,recreation // only if the owner will be saved. // As is: // if (session.getInterceptor().onCollectionUpdate(coll, ce.getLoadedKey())) { // actionQueue.addAction(...); // } // // This is really hacky. We should move to something better than Hibernate like EBEAN cfg.setInterceptor(new EmptyInterceptor() { @Override public int[] findDirty(Object o, Serializable id, Object[] arg2, Object[] arg3, String[] arg4, Type[] arg5) { if (o instanceof JPASupport && !((JPASupport) o).willBeSaved) { return new int[0]; } return null; } @Override public boolean onCollectionUpdate(Object collection, Serializable key) throws CallbackException { if (collection instanceof PersistentCollection) { Object o = ((PersistentCollection) collection).getOwner(); if (o instanceof JPASupport) { return ((JPASupport) o).willBeSaved; } } else { System.out.println("HOO: Case not handled !!!"); } return super.onCollectionUpdate(collection, key); } @Override public boolean onCollectionRecreate(Object collection, Serializable key) throws CallbackException { if (collection instanceof PersistentCollection) { Object o = ((PersistentCollection) collection).getOwner(); if (o instanceof JPASupport) { return ((JPASupport) o).willBeSaved; } } else { System.out.println("HOO: Case not handled !!!"); } return super.onCollectionRecreate(collection, key); } @Override public boolean onCollectionRemove(Object collection, Serializable key) throws CallbackException { if (collection instanceof PersistentCollection) { Object o = ((PersistentCollection) collection).getOwner(); if (o instanceof JPASupport) { return ((JPASupport) o).willBeSaved; } } else { System.out.println("HOO: Case not handled !!!"); } return super.onCollectionRemove(collection, key); } }); if (Play.configuration.getProperty("jpa.debugSQL", "false").equals("true")) { org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.ALL); } else { org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.OFF); } // inject additional hibernate.* settings declared in Play! configuration cfg.addProperties((Properties) Utils.Maps.filterMap(Play.configuration, "^hibernate\\..*")); try { Field field = cfg.getClass().getDeclaredField("overridenClassLoader"); field.setAccessible(true); field.set(cfg, Play.classloader); } catch (Exception e) { Logger.error(e, "Error trying to override the hibernate classLoader (new hibernate version ???)"); } for (Class clazz : classes) { if (clazz.isAnnotationPresent(Entity.class)) { cfg.addAnnotatedClass(clazz); Logger.trace("JPA Model : %s", clazz); } } String[] moreEntities = Play.configuration.getProperty("jpa.entities", "").split(", "); for(String entity : moreEntities) { if(entity.trim().equals("")) continue; try { cfg.addAnnotatedClass(Play.classloader.loadClass(entity)); } catch(Exception e) { Logger.warn("JPA -> Entity not found: %s", entity); } } Logger.trace("Initializing JPA ..."); try { JPA.entityManagerFactory = cfg.buildEntityManagerFactory(); } catch (PersistenceException e) { throw new JPAException(e.getMessage(), e.getCause() != null ? e.getCause() : e); } JPQLDialect.instance = new JPQLDialect(); } } static String getDefaultDialect(String driver) { if (driver.equals("org.hsqldb.jdbcDriver")) { return "org.hibernate.dialect.HSQLDialect"; } else if (driver.equals("com.mysql.jdbc.Driver")) { return "play.db.jpa.MySQLDialect"; } else { String dialect = Play.configuration.getProperty("jpa.dialect"); if (dialect != null) { return dialect; } throw new UnsupportedOperationException("I do not know which hibernate dialect to use with " + driver + ", use the property jpa.dialect in config file"); } } @Override public void onApplicationStop() { if (JPA.entityManagerFactory != null) { JPA.entityManagerFactory.close(); JPA.entityManagerFactory = null; } } @Override public void beforeInvocation() { startTx(false); } @Override public void afterInvocation() { closeTx(false); } @Override public void afterActionInvocation() { closeTx(false); } @Override public void onInvocationException(Throwable e) { closeTx(true); } @Override public void invocationFinally() { closeTx(true); } /** * initialize the JPA context and starts a JPA transaction * * @param readonly true for a readonly transaction */ public static void startTx(boolean readonly) { if (!JPA.isEnabled()) { return; } EntityManager manager = JPA.entityManagerFactory.createEntityManager(); //if(Play.configuration.getProperty("future.bindJPAObjects", "false").equals("true")) { manager.setFlushMode(FlushModeType.COMMIT); //} if (autoTxs) { manager.getTransaction().begin(); } JPA.createContext(manager, readonly); } /** * clear current JPA context and transaction * @param rollback shall current transaction be committed (false) or cancelled (true) */ public static void closeTx(boolean rollback) { if (!JPA.isEnabled() || JPA.local.get() == null) { return; } EntityManager manager = JPA.get().entityManager; try { if (autoTxs) { if (manager.getTransaction().isActive()) { if (JPA.get().readonly || rollback || manager.getTransaction().getRollbackOnly()) { manager.getTransaction().rollback(); } else { try { if (autoTxs) { manager.getTransaction().commit(); } } catch (Throwable e) { for (int i = 0; i < 10; i++) { if (e instanceof PersistenceException && e.getCause() != null) { e = e.getCause(); break; } e = e.getCause(); if (e == null) { break; } } throw new JPAException("Cannot commit", e); } } } } } finally { manager.close(); JPA.clearContext(); } } }
true
true
public void onApplicationStart() { if (JPA.entityManagerFactory == null) { List<Class> classes = Play.classloader.getAnnotatedClasses(Entity.class); if (classes.isEmpty()) { return; } if (DB.datasource == null) { throw new JPAException("Cannot start a JPA manager without a properly configured database", new NullPointerException("No datasource")); } Ejb3Configuration cfg = new Ejb3Configuration(); cfg.setDataSource(DB.datasource); if (!Play.configuration.getProperty("jpa.ddl", "update").equals("none")) { cfg.setProperty("hibernate.hbm2ddl.auto", Play.configuration.getProperty("jpa.ddl", "update")); } cfg.setProperty("hibernate.dialect", getDefaultDialect(Play.configuration.getProperty("db.driver"))); cfg.setProperty("javax.persistence.transaction", "RESOURCE_LOCAL"); // Explicit SAVE for JPASupport is implemented here // ~~~~~~ // We've hacked the org.hibernate.event.def.AbstractFlushingEventListener line 271, to flush collection update,remove,recreation // only if the owner will be saved. // As is: // if (session.getInterceptor().onCollectionUpdate(coll, ce.getLoadedKey())) { // actionQueue.addAction(...); // } // // This is really hacky. We should move to something better than Hibernate like EBEAN cfg.setInterceptor(new EmptyInterceptor() { @Override public int[] findDirty(Object o, Serializable id, Object[] arg2, Object[] arg3, String[] arg4, Type[] arg5) { if (o instanceof JPASupport && !((JPASupport) o).willBeSaved) { return new int[0]; } return null; } @Override public boolean onCollectionUpdate(Object collection, Serializable key) throws CallbackException { if (collection instanceof PersistentCollection) { Object o = ((PersistentCollection) collection).getOwner(); if (o instanceof JPASupport) { return ((JPASupport) o).willBeSaved; } } else { System.out.println("HOO: Case not handled !!!"); } return super.onCollectionUpdate(collection, key); } @Override public boolean onCollectionRecreate(Object collection, Serializable key) throws CallbackException { if (collection instanceof PersistentCollection) { Object o = ((PersistentCollection) collection).getOwner(); if (o instanceof JPASupport) { return ((JPASupport) o).willBeSaved; } } else { System.out.println("HOO: Case not handled !!!"); } return super.onCollectionRecreate(collection, key); } @Override public boolean onCollectionRemove(Object collection, Serializable key) throws CallbackException { if (collection instanceof PersistentCollection) { Object o = ((PersistentCollection) collection).getOwner(); if (o instanceof JPASupport) { return ((JPASupport) o).willBeSaved; } } else { System.out.println("HOO: Case not handled !!!"); } return super.onCollectionRemove(collection, key); } }); if (Play.configuration.getProperty("jpa.debugSQL", "false").equals("true")) { org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.ALL); } else { org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.OFF); } // inject additional hibernate.* settings declared in Play! configuration cfg.addProperties((Properties) Utils.Maps.filterMap(Play.configuration, "^hibernate\\..*")); try { Field field = cfg.getClass().getDeclaredField("overridenClassLoader"); field.setAccessible(true); field.set(cfg, Play.classloader); } catch (Exception e) { Logger.error(e, "Error trying to override the hibernate classLoader (new hibernate version ???)"); } for (Class clazz : classes) { if (clazz.isAnnotationPresent(Entity.class)) { cfg.addAnnotatedClass(clazz); Logger.trace("JPA Model : %s", clazz); } } String[] moreEntities = Play.configuration.getProperty("jpa.entities", "").split(", "); for(String entity : moreEntities) { if(entity.trim().equals("")) continue; try { cfg.addAnnotatedClass(Play.classloader.loadClass(entity)); } catch(Exception e) { Logger.warn("JPA -> Entity not found: %s", entity); } } Logger.trace("Initializing JPA ..."); try { JPA.entityManagerFactory = cfg.buildEntityManagerFactory(); } catch (PersistenceException e) { throw new JPAException(e.getMessage(), e.getCause() != null ? e.getCause() : e); } JPQLDialect.instance = new JPQLDialect(); } }
public void onApplicationStart() { if (JPA.entityManagerFactory == null) { List<Class> classes = Play.classloader.getAnnotatedClasses(Entity.class); if (classes.isEmpty() && Play.configuration.getProperty("jpa.entities", "").equals("")) { return; } if (DB.datasource == null) { throw new JPAException("Cannot start a JPA manager without a properly configured database", new NullPointerException("No datasource")); } Ejb3Configuration cfg = new Ejb3Configuration(); cfg.setDataSource(DB.datasource); if (!Play.configuration.getProperty("jpa.ddl", "update").equals("none")) { cfg.setProperty("hibernate.hbm2ddl.auto", Play.configuration.getProperty("jpa.ddl", "update")); } cfg.setProperty("hibernate.dialect", getDefaultDialect(Play.configuration.getProperty("db.driver"))); cfg.setProperty("javax.persistence.transaction", "RESOURCE_LOCAL"); // Explicit SAVE for JPASupport is implemented here // ~~~~~~ // We've hacked the org.hibernate.event.def.AbstractFlushingEventListener line 271, to flush collection update,remove,recreation // only if the owner will be saved. // As is: // if (session.getInterceptor().onCollectionUpdate(coll, ce.getLoadedKey())) { // actionQueue.addAction(...); // } // // This is really hacky. We should move to something better than Hibernate like EBEAN cfg.setInterceptor(new EmptyInterceptor() { @Override public int[] findDirty(Object o, Serializable id, Object[] arg2, Object[] arg3, String[] arg4, Type[] arg5) { if (o instanceof JPASupport && !((JPASupport) o).willBeSaved) { return new int[0]; } return null; } @Override public boolean onCollectionUpdate(Object collection, Serializable key) throws CallbackException { if (collection instanceof PersistentCollection) { Object o = ((PersistentCollection) collection).getOwner(); if (o instanceof JPASupport) { return ((JPASupport) o).willBeSaved; } } else { System.out.println("HOO: Case not handled !!!"); } return super.onCollectionUpdate(collection, key); } @Override public boolean onCollectionRecreate(Object collection, Serializable key) throws CallbackException { if (collection instanceof PersistentCollection) { Object o = ((PersistentCollection) collection).getOwner(); if (o instanceof JPASupport) { return ((JPASupport) o).willBeSaved; } } else { System.out.println("HOO: Case not handled !!!"); } return super.onCollectionRecreate(collection, key); } @Override public boolean onCollectionRemove(Object collection, Serializable key) throws CallbackException { if (collection instanceof PersistentCollection) { Object o = ((PersistentCollection) collection).getOwner(); if (o instanceof JPASupport) { return ((JPASupport) o).willBeSaved; } } else { System.out.println("HOO: Case not handled !!!"); } return super.onCollectionRemove(collection, key); } }); if (Play.configuration.getProperty("jpa.debugSQL", "false").equals("true")) { org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.ALL); } else { org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.OFF); } // inject additional hibernate.* settings declared in Play! configuration cfg.addProperties((Properties) Utils.Maps.filterMap(Play.configuration, "^hibernate\\..*")); try { Field field = cfg.getClass().getDeclaredField("overridenClassLoader"); field.setAccessible(true); field.set(cfg, Play.classloader); } catch (Exception e) { Logger.error(e, "Error trying to override the hibernate classLoader (new hibernate version ???)"); } for (Class clazz : classes) { if (clazz.isAnnotationPresent(Entity.class)) { cfg.addAnnotatedClass(clazz); Logger.trace("JPA Model : %s", clazz); } } String[] moreEntities = Play.configuration.getProperty("jpa.entities", "").split(", "); for(String entity : moreEntities) { if(entity.trim().equals("")) continue; try { cfg.addAnnotatedClass(Play.classloader.loadClass(entity)); } catch(Exception e) { Logger.warn("JPA -> Entity not found: %s", entity); } } Logger.trace("Initializing JPA ..."); try { JPA.entityManagerFactory = cfg.buildEntityManagerFactory(); } catch (PersistenceException e) { throw new JPAException(e.getMessage(), e.getCause() != null ? e.getCause() : e); } JPQLDialect.instance = new JPQLDialect(); } }
diff --git a/IndexWriter.java b/IndexWriter.java index fdb4c67..aec413a 100644 --- a/IndexWriter.java +++ b/IndexWriter.java @@ -1,466 +1,469 @@ /* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package plugins.XMLSpider; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.Vector; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import plugins.XMLSpider.db.Config; import plugins.XMLSpider.db.Page; import plugins.XMLSpider.db.PerstRoot; import plugins.XMLSpider.db.Term; import plugins.XMLSpider.db.TermPosition; import plugins.XMLSpider.org.garret.perst.IterableIterator; import plugins.XMLSpider.org.garret.perst.Storage; import plugins.XMLSpider.org.garret.perst.StorageFactory; import freenet.support.Logger; import freenet.support.io.Closer; /** * Write index to disk file */ public class IndexWriter { private static final String[] HEX = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; //- Writing Index public long tProducedIndex; private Vector<String> indices; private int match; private long time_taken; private boolean logMINOR = Logger.shouldLog(Logger.MINOR, this); IndexWriter() { } public synchronized void makeIndex(PerstRoot perstRoot) throws Exception { logMINOR = Logger.shouldLog(Logger.MINOR, this); try { time_taken = System.currentTimeMillis(); Config config = perstRoot.getConfig(); File indexDir = new File(config.getIndexDir()); if (!indexDir.exists() && !indexDir.isDirectory() && !indexDir.mkdirs()) { Logger.error(this, "Cannot create index directory: " + indexDir); return; } makeSubIndices(perstRoot); makeMainIndex(config); time_taken = System.currentTimeMillis() - time_taken; if (logMINOR) Logger.minor(this, "Spider: indexes regenerated - tProducedIndex=" + (System.currentTimeMillis() - tProducedIndex) + "ms ago time taken=" + time_taken + "ms"); tProducedIndex = System.currentTimeMillis(); } finally { } } /** * generates the main index file that can be used by librarian for searching in the list of * subindices * * @param void * @author swati * @throws IOException * @throws NoSuchAlgorithmException */ private void makeMainIndex(Config config) throws IOException, NoSuchAlgorithmException { // Produce the main index file. if (logMINOR) Logger.minor(this, "Producing top index..."); //the main index file File outputFile = new File(config.getIndexDir() + "index.xml"); // Use a stream so we can explicitly close - minimise number of filehandles used. BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream; resultStream = new StreamResult(fos); try { /* Initialize xml builder */ Document xmlDoc = null; DocumentBuilderFactory xmlFactory = null; DocumentBuilder xmlBuilder = null; DOMImplementation impl = null; Element rootElement = null; xmlFactory = DocumentBuilderFactory.newInstance(); try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { Logger.error(this, "Spider: Error while initializing XML generator: " + e.toString(), e); return; } impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ xmlDoc = impl.createDocument(null, "main_index", null); rootElement = xmlDoc.getDocumentElement(); /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* -> owner */ subHeaderElement = xmlDoc.createElement("owner"); subHeaderText = xmlDoc.createTextNode(config.getIndexOwner()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* -> owner email */ if (config.getIndexOwnerEmail() != null) { subHeaderElement = xmlDoc.createElement("email"); subHeaderText = xmlDoc.createTextNode(config.getIndexOwnerEmail()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); } /* * the max number of digits in md5 to be used for matching with the search query is * stored in the xml */ Element prefixElement = xmlDoc.createElement("prefix"); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); for (int i = 0; i < indices.size(); i++) { Element subIndexElement = xmlDoc.createElement("subIndex"); subIndexElement.setAttribute("key", indices.elementAt(i)); //the subindex element key will contain the bits used for matching in that subindex keywordsElement.appendChild(subIndexElement); } prefixElement.setAttribute("value", match + ""); rootElement.appendChild(prefixElement); rootElement.appendChild(headerElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { Logger.error(this, "Spider: Error while serializing XML (transformFactory.newTransformer()): " + e.toString(), e); return; } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { Logger.error(this, "Spider: Error while serializing XML (transform()): " + e.toString(), e); return; } } finally { fos.close(); } //The main xml file is generated //As each word is generated enter it into the respective subindex //The parsing will start and nodes will be added as needed } /** * Generates the subindices. Each index has less than {@code MAX_ENTRIES} words. The original * treemap is split into several sublists indexed by the common substring of the hash code of * the words * * @throws Exception */ private void makeSubIndices(PerstRoot perstRoot) throws Exception { Logger.normal(this, "Generating index..."); indices = new Vector<String>(); match = 1; for (String hex : HEX) generateSubIndex(perstRoot, hex); } private void generateSubIndex(PerstRoot perstRoot, String prefix) throws Exception { if (logMINOR) Logger.minor(this, "Generating subindex for (" + prefix + ")"); if (prefix.length() > match) match = prefix.length(); if (generateXML(perstRoot, prefix)) return; if (logMINOR) Logger.minor(this, "Too big subindex for (" + prefix + ")"); for (String hex : HEX) generateSubIndex(perstRoot, prefix + hex); } /** * generates the xml index with the given list of words with prefix number of matching bits in * md5 * * @param prefix * prefix string * @return successful * @throws IOException */ private boolean generateXML(PerstRoot perstRoot, String prefix) throws IOException { final Config config = perstRoot.getConfig(); final long MAX_SIZE = config.getIndexSubindexMaxSize(); final int MAX_ENTRIES = config.getIndexMaxEntries(); File outputFile = new File(config.getIndexDir() + "index_" + prefix + ".xml"); BufferedOutputStream fos = null; int count = 0; int estimateSize = 0; try { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBuilder; try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException("Spider: Error while initializing XML generator", e); } DOMImplementation impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ Document xmlDoc = impl.createDocument(null, "sub_index", null); Element rootElement = xmlDoc.getDocumentElement(); if (config.isDebug()) { xmlDoc.createAttributeNS("urn:freenet:xmlspider:debug", "debug"); rootElement.appendChild(xmlDoc.createComment(new Date().toGMTString())); } /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* List of files referenced in this subindex */ Element filesElement = xmlDoc.createElement("files"); /* filesElement != fileElement */ Set<Long> fileid = new HashSet<Long>(); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); IterableIterator<Term> termIterator = perstRoot.getTermIterator(prefix, prefix + "g"); for (Term term : termIterator) { Element wordElement = xmlDoc.createElement("word"); wordElement.setAttribute("v", term.getWord()); if (config.isDebug()) wordElement.setAttribute("debug:md5", term.getMD5()); count++; estimateSize += 12; estimateSize += term.getWord().length(); Set<Page> pages = term.getPages(); if ((count > 1 && (estimateSize + pages.size() * 13) > MAX_SIZE) || // (count > MAX_ENTRIES)) { - return false; + if (prefix.length() < 3 && indices.size() < 256) // FIXME this is a hack to limit number of files. remove after metadata fix + return false; } for (Page page : pages) { TermPosition termPos = page.getTermPosition(term, false); if (termPos == null) continue; synchronized (termPos) { synchronized (page) { /* * adding file information uriElement - lists the id of the file * containing a particular word fileElement - lists the id,key,title of * the files mentioned in the entire subindex */ Element uriElement = xmlDoc.createElement("file"); uriElement.setAttribute("id", Long.toString(page.getId())); /* Position by position */ int[] positions = termPos.positions; StringBuilder positionList = new StringBuilder(); for (int k = 0; k < positions.length; k++) { if (k != 0) positionList.append(','); positionList.append(positions[k]); } uriElement.appendChild(xmlDoc.createTextNode(positionList.toString())); wordElement.appendChild(uriElement); estimateSize += 13; estimateSize += positionList.length(); if (!fileid.contains(page.getId())) { fileid.add(page.getId()); Element fileElement = xmlDoc.createElement("file"); fileElement.setAttribute("id", Long.toString(page.getId())); fileElement.setAttribute("key", page.getURI()); fileElement.setAttribute("title", page.getPageTitle() != null ? page.getPageTitle() : page.getURI()); filesElement.appendChild(fileElement); estimateSize += 15; estimateSize += filesElement.getAttribute("id").length(); estimateSize += filesElement.getAttribute("key").length(); estimateSize += filesElement.getAttribute("title").length(); } } } } keywordsElement.appendChild(wordElement); } Element entriesElement = xmlDoc.createElement("entries"); entriesElement.setAttribute("value", count + ""); rootElement.appendChild(entriesElement); rootElement.appendChild(headerElement); rootElement.appendChild(filesElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { throw new RuntimeException("Spider: Error while serializing XML (transformFactory.newTransformer())", e); } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream = new StreamResult(fos); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { throw new RuntimeException("Spider: Error while serializing XML (transform())", e); } } finally { Closer.close(fos); } if (outputFile.length() > MAX_SIZE && count > 1) { - outputFile.delete(); - return false; + if (prefix.length() < 3 && indices.size() < 256) { // FIXME this is a hack to limit number of files. remove after metadata fix + outputFile.delete(); + return false; + } } if (logMINOR) Logger.minor(this, "Spider: indexes regenerated."); indices.add(prefix); return true; } public static void main(String[] arg) throws Exception { Storage db = StorageFactory.getInstance().createStorage(); db.setProperty("perst.object.cache.kind", "pinned"); db.setProperty("perst.object.cache.init.size", 8192); db.setProperty("perst.alternative.btree", true); db.setProperty("perst.string.encoding", "UTF-8"); db.setProperty("perst.concurrent.iterator", true); db.setProperty("perst.file.readonly", true); db.open(arg[0]); PerstRoot root = (PerstRoot) db.getRoot(); IndexWriter writer = new IndexWriter(); int benchmark = 0; long[] timeTaken = null; if (arg[1] != null) { benchmark = Integer.parseInt(arg[1]); timeTaken = new long[benchmark]; } for (int i = 0; i < benchmark; i++) { long startTime = System.currentTimeMillis(); writer.makeIndex(root); long endTime = System.currentTimeMillis(); long memFree = Runtime.getRuntime().freeMemory(); long memTotal = Runtime.getRuntime().totalMemory(); System.out.println("Index generated in " + (endTime - startTime) // + "ms. Used memory=" + (memTotal - memFree)); if (benchmark > 0) { timeTaken[i] = (endTime - startTime); System.out.println("Cooling down."); for (int j = 0; j < 3; j++) { System.gc(); System.runFinalization(); Thread.sleep(3000); } } } if (benchmark > 0) { long totalTime = 0; long totalSqTime = 0; for (long t : timeTaken) { totalTime += t; totalSqTime += t * t; } double meanTime = (totalTime / benchmark); double meanSqTime = (totalSqTime / benchmark); System.out.println("Mean time = " + (long) meanTime + "ms"); System.out.println(" sd = " + (long) Math.sqrt(meanSqTime - meanTime * meanTime) + "ms"); } } }
false
true
private boolean generateXML(PerstRoot perstRoot, String prefix) throws IOException { final Config config = perstRoot.getConfig(); final long MAX_SIZE = config.getIndexSubindexMaxSize(); final int MAX_ENTRIES = config.getIndexMaxEntries(); File outputFile = new File(config.getIndexDir() + "index_" + prefix + ".xml"); BufferedOutputStream fos = null; int count = 0; int estimateSize = 0; try { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBuilder; try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException("Spider: Error while initializing XML generator", e); } DOMImplementation impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ Document xmlDoc = impl.createDocument(null, "sub_index", null); Element rootElement = xmlDoc.getDocumentElement(); if (config.isDebug()) { xmlDoc.createAttributeNS("urn:freenet:xmlspider:debug", "debug"); rootElement.appendChild(xmlDoc.createComment(new Date().toGMTString())); } /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* List of files referenced in this subindex */ Element filesElement = xmlDoc.createElement("files"); /* filesElement != fileElement */ Set<Long> fileid = new HashSet<Long>(); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); IterableIterator<Term> termIterator = perstRoot.getTermIterator(prefix, prefix + "g"); for (Term term : termIterator) { Element wordElement = xmlDoc.createElement("word"); wordElement.setAttribute("v", term.getWord()); if (config.isDebug()) wordElement.setAttribute("debug:md5", term.getMD5()); count++; estimateSize += 12; estimateSize += term.getWord().length(); Set<Page> pages = term.getPages(); if ((count > 1 && (estimateSize + pages.size() * 13) > MAX_SIZE) || // (count > MAX_ENTRIES)) { return false; } for (Page page : pages) { TermPosition termPos = page.getTermPosition(term, false); if (termPos == null) continue; synchronized (termPos) { synchronized (page) { /* * adding file information uriElement - lists the id of the file * containing a particular word fileElement - lists the id,key,title of * the files mentioned in the entire subindex */ Element uriElement = xmlDoc.createElement("file"); uriElement.setAttribute("id", Long.toString(page.getId())); /* Position by position */ int[] positions = termPos.positions; StringBuilder positionList = new StringBuilder(); for (int k = 0; k < positions.length; k++) { if (k != 0) positionList.append(','); positionList.append(positions[k]); } uriElement.appendChild(xmlDoc.createTextNode(positionList.toString())); wordElement.appendChild(uriElement); estimateSize += 13; estimateSize += positionList.length(); if (!fileid.contains(page.getId())) { fileid.add(page.getId()); Element fileElement = xmlDoc.createElement("file"); fileElement.setAttribute("id", Long.toString(page.getId())); fileElement.setAttribute("key", page.getURI()); fileElement.setAttribute("title", page.getPageTitle() != null ? page.getPageTitle() : page.getURI()); filesElement.appendChild(fileElement); estimateSize += 15; estimateSize += filesElement.getAttribute("id").length(); estimateSize += filesElement.getAttribute("key").length(); estimateSize += filesElement.getAttribute("title").length(); } } } } keywordsElement.appendChild(wordElement); } Element entriesElement = xmlDoc.createElement("entries"); entriesElement.setAttribute("value", count + ""); rootElement.appendChild(entriesElement); rootElement.appendChild(headerElement); rootElement.appendChild(filesElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { throw new RuntimeException("Spider: Error while serializing XML (transformFactory.newTransformer())", e); } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream = new StreamResult(fos); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { throw new RuntimeException("Spider: Error while serializing XML (transform())", e); } } finally { Closer.close(fos); } if (outputFile.length() > MAX_SIZE && count > 1) { outputFile.delete(); return false; } if (logMINOR) Logger.minor(this, "Spider: indexes regenerated."); indices.add(prefix); return true; }
private boolean generateXML(PerstRoot perstRoot, String prefix) throws IOException { final Config config = perstRoot.getConfig(); final long MAX_SIZE = config.getIndexSubindexMaxSize(); final int MAX_ENTRIES = config.getIndexMaxEntries(); File outputFile = new File(config.getIndexDir() + "index_" + prefix + ".xml"); BufferedOutputStream fos = null; int count = 0; int estimateSize = 0; try { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBuilder; try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException("Spider: Error while initializing XML generator", e); } DOMImplementation impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ Document xmlDoc = impl.createDocument(null, "sub_index", null); Element rootElement = xmlDoc.getDocumentElement(); if (config.isDebug()) { xmlDoc.createAttributeNS("urn:freenet:xmlspider:debug", "debug"); rootElement.appendChild(xmlDoc.createComment(new Date().toGMTString())); } /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* List of files referenced in this subindex */ Element filesElement = xmlDoc.createElement("files"); /* filesElement != fileElement */ Set<Long> fileid = new HashSet<Long>(); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); IterableIterator<Term> termIterator = perstRoot.getTermIterator(prefix, prefix + "g"); for (Term term : termIterator) { Element wordElement = xmlDoc.createElement("word"); wordElement.setAttribute("v", term.getWord()); if (config.isDebug()) wordElement.setAttribute("debug:md5", term.getMD5()); count++; estimateSize += 12; estimateSize += term.getWord().length(); Set<Page> pages = term.getPages(); if ((count > 1 && (estimateSize + pages.size() * 13) > MAX_SIZE) || // (count > MAX_ENTRIES)) { if (prefix.length() < 3 && indices.size() < 256) // FIXME this is a hack to limit number of files. remove after metadata fix return false; } for (Page page : pages) { TermPosition termPos = page.getTermPosition(term, false); if (termPos == null) continue; synchronized (termPos) { synchronized (page) { /* * adding file information uriElement - lists the id of the file * containing a particular word fileElement - lists the id,key,title of * the files mentioned in the entire subindex */ Element uriElement = xmlDoc.createElement("file"); uriElement.setAttribute("id", Long.toString(page.getId())); /* Position by position */ int[] positions = termPos.positions; StringBuilder positionList = new StringBuilder(); for (int k = 0; k < positions.length; k++) { if (k != 0) positionList.append(','); positionList.append(positions[k]); } uriElement.appendChild(xmlDoc.createTextNode(positionList.toString())); wordElement.appendChild(uriElement); estimateSize += 13; estimateSize += positionList.length(); if (!fileid.contains(page.getId())) { fileid.add(page.getId()); Element fileElement = xmlDoc.createElement("file"); fileElement.setAttribute("id", Long.toString(page.getId())); fileElement.setAttribute("key", page.getURI()); fileElement.setAttribute("title", page.getPageTitle() != null ? page.getPageTitle() : page.getURI()); filesElement.appendChild(fileElement); estimateSize += 15; estimateSize += filesElement.getAttribute("id").length(); estimateSize += filesElement.getAttribute("key").length(); estimateSize += filesElement.getAttribute("title").length(); } } } } keywordsElement.appendChild(wordElement); } Element entriesElement = xmlDoc.createElement("entries"); entriesElement.setAttribute("value", count + ""); rootElement.appendChild(entriesElement); rootElement.appendChild(headerElement); rootElement.appendChild(filesElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { throw new RuntimeException("Spider: Error while serializing XML (transformFactory.newTransformer())", e); } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream = new StreamResult(fos); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { throw new RuntimeException("Spider: Error while serializing XML (transform())", e); } } finally { Closer.close(fos); } if (outputFile.length() > MAX_SIZE && count > 1) { if (prefix.length() < 3 && indices.size() < 256) { // FIXME this is a hack to limit number of files. remove after metadata fix outputFile.delete(); return false; } } if (logMINOR) Logger.minor(this, "Spider: indexes regenerated."); indices.add(prefix); return true; }
diff --git a/mod/src/main/java/io/vertx/redis/RedisMod.java b/mod/src/main/java/io/vertx/redis/RedisMod.java index d4f379f..097b753 100644 --- a/mod/src/main/java/io/vertx/redis/RedisMod.java +++ b/mod/src/main/java/io/vertx/redis/RedisMod.java @@ -1,280 +1,280 @@ package io.vertx.redis; import io.vertx.redis.impl.RedisSubscriptions; import org.vertx.java.busmods.BusModBase; import org.vertx.java.core.Handler; import org.vertx.java.core.eventbus.Message; import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonObject; import io.vertx.redis.reply.*; import io.vertx.redis.impl.MessageHandler; import java.nio.charset.Charset; @SuppressWarnings("unused") public class RedisMod extends BusModBase implements Handler<Message<JsonObject>> { private RedisConnection redisClient; private RedisSubscriptions subscriptions = new RedisSubscriptions(); private String encoding; private String baseAddress; private enum ResponseTransform { NONE, ARRAY_TO_OBJECT, INFO } @Override public void start() { super.start(); String host = getOptionalStringConfig("host", "localhost"); int port = getOptionalIntConfig("port", 6379); String encoding = getOptionalStringConfig("encoding", null); boolean binary = getOptionalBooleanConfig("binary", false); if (binary) { logger.warn("Binary mode is not implemented yet!!!"); } if (encoding != null) { this.encoding = encoding; } else { this.encoding = "UTF-8"; } redisClient = new RedisConnection(vertx, logger, host, port, subscriptions, Charset.forName(this.encoding)); redisClient.connect(null); baseAddress = getOptionalStringConfig("address", "io.vertx.mod-redis"); eb.registerHandler(baseAddress, this); } private ResponseTransform getResponseTransformFor(String command) { if (command.equals("hgetall")) { return ResponseTransform.ARRAY_TO_OBJECT; } if (command.equals("info")) { return ResponseTransform.INFO; } return ResponseTransform.NONE; } @Override public void handle(final Message<JsonObject> message) { - final String command = message.body().getString("command"); + String command = message.body().getString("command"); final JsonArray args = message.body().getArray("args"); if (command == null) { sendError(message, "command must be specified"); return; } else { command = command.toLowerCase(); } final ResponseTransform transform = getResponseTransformFor(command); // subscribe/psubscribe and unsubscribe/punsubscribe commands can have multiple (including zero) replies int expectedReplies = 1; switch (command) { // argument "pattern" ["pattern"...] case "psubscribe": // in this case we need also to register handlers if (args == null) { sendError(message, "at least one pattern is required!"); return; } expectedReplies = args.size(); for (Object obj : args) { String pattern = (String) obj; // compose the listening address as base + . + pattern final String vertxChannel = baseAddress + "." + pattern; subscriptions.registerPatternSubscribeHandler(pattern, new MessageHandler() { @Override public void handle(String pattern, Reply[] replyData) { JsonObject replyMessage = new JsonObject(); replyMessage.putString("status", "ok"); JsonObject message = new JsonObject(); message.putString("pattern", pattern); message.putString("channel", ((BulkReply) replyData[2]).asString(encoding)); message.putString("message", ((BulkReply) replyData[3]).asString(encoding)); replyMessage.putObject("value", message); eb.send(vertxChannel, replyMessage); } }); } break; // argument "channel" ["channel"...] case "subscribe": if (args == null) { sendError(message, "at least one pattern is required!"); return; } // in this case we need also to register handlers expectedReplies = args.size(); for (Object obj : args) { String channel = (String) obj; // compose the listening address as base + . + channel final String vertxChannel = baseAddress + "." + channel; subscriptions.registerChannelSubscribeHandler(channel, new MessageHandler() { @Override public void handle(String channel, Reply[] replyData) { JsonObject replyMessage = new JsonObject(); replyMessage.putString("status", "ok"); JsonObject message = new JsonObject(); message.putString("channel", channel); message.putString("message", ((BulkReply) replyData[2]).asString(encoding)); replyMessage.putObject("value", message); eb.send(vertxChannel, replyMessage); } }); } break; // argument ["pattern" ["pattern"...]] case "punsubscribe": // unregister all channels if (args == null || args.size() == 0) { // unsubscribe all expectedReplies = subscriptions.patternSize(); subscriptions.unregisterPatternSubscribeHandler(null); } else { expectedReplies = args.size(); for (Object obj : args) { String pattern = (String) obj; subscriptions.unregisterPatternSubscribeHandler(pattern); } } break; // argument ["channel" ["channel"...]] case "unsubscribe": // unregister all channels if (args == null || args.size() == 0) { // unsubscribe all expectedReplies = subscriptions.channelSize(); subscriptions.unregisterChannelSubscribeHandler(null); } else { expectedReplies = args.size(); for (Object obj : args) { String channel = (String) obj; subscriptions.unregisterChannelSubscribeHandler(channel); } } break; } redisClient.send(message.body(), expectedReplies, new Handler<Reply>() { @Override public void handle(Reply reply) { processReply(message, reply, transform); } }); } private void processReply(Message<JsonObject> message, Reply reply, ResponseTransform transform) { JsonObject replyMessage; switch (reply.getType()) { case '-': // Error sendError(message, ((ErrorReply) reply).data()); return; case '+': // Status replyMessage = new JsonObject(); replyMessage.putString("value", ((StatusReply) reply).data()); sendOK(message, replyMessage); return; case '$': // Bulk replyMessage = new JsonObject(); if (transform == ResponseTransform.INFO) { String info = ((BulkReply) reply).asString(encoding); String lines[] = info.split("\\r?\\n"); JsonObject value = new JsonObject(); JsonObject section = null; for (String line : lines) { if (line.length() == 0) { // end of section section = null; continue; } if (line.charAt(0) == '#') { // begin section section = new JsonObject(); // create a sub key with the section name value.putObject(line.substring(2).toLowerCase(), section); } else { // entry in section int split = line.indexOf(':'); if (section == null) { value.putString(line.substring(0, split), line.substring(split + 1)); } else { section.putString(line.substring(0, split), line.substring(split + 1)); } } } replyMessage.putObject("value", value); } else { replyMessage.putString("value", ((BulkReply) reply).asString(encoding)); } sendOK(message, replyMessage); return; case '*': // MultiBulk replyMessage = new JsonObject(); MultiBulkReply mbreply = (MultiBulkReply) reply; if (transform == ResponseTransform.ARRAY_TO_OBJECT) { JsonObject bulk = new JsonObject(); Reply[] mbreplyData = mbreply.data(); for (int i = 0; i < mbreplyData.length; i+=2) { if (mbreplyData[i].getType() != '$') { sendError(message, "Expected String as key type in multibulk: " + mbreplyData[i].getType()); return; } BulkReply brKey = (BulkReply) mbreplyData[i]; Reply brValue = mbreplyData[i+1]; switch (brValue.getType()) { case '$': // Bulk bulk.putString(brKey.asString(encoding), ((BulkReply) brValue).asString(encoding)); break; case ':': // Integer bulk.putNumber(brKey.asString(encoding), ((IntegerReply) brValue).data()); break; default: sendError(message, "Unknown sub message type in multibulk: " + mbreplyData[i+1].getType()); return; } } replyMessage.putObject("value", bulk); } else { JsonArray bulk = new JsonArray(); for (Reply r : mbreply.data()) { switch (r.getType()) { case '$': // Bulk bulk.addString(((BulkReply) r).asString(encoding)); break; case ':': // Integer bulk.addNumber(((IntegerReply) r).data()); break; default: sendError(message, "Unknown sub message type in multibulk: " + r.getType()); return; } } replyMessage.putArray("value", bulk); } sendOK(message, replyMessage); return; case ':': // Integer replyMessage = new JsonObject(); replyMessage.putNumber("value", ((IntegerReply) reply).data()); sendOK(message, replyMessage); return; default: sendError(message, "Unknown message type"); } } }
true
true
public void handle(final Message<JsonObject> message) { final String command = message.body().getString("command"); final JsonArray args = message.body().getArray("args"); if (command == null) { sendError(message, "command must be specified"); return; } else { command = command.toLowerCase(); } final ResponseTransform transform = getResponseTransformFor(command); // subscribe/psubscribe and unsubscribe/punsubscribe commands can have multiple (including zero) replies int expectedReplies = 1; switch (command) { // argument "pattern" ["pattern"...] case "psubscribe": // in this case we need also to register handlers if (args == null) { sendError(message, "at least one pattern is required!"); return; } expectedReplies = args.size(); for (Object obj : args) { String pattern = (String) obj; // compose the listening address as base + . + pattern final String vertxChannel = baseAddress + "." + pattern; subscriptions.registerPatternSubscribeHandler(pattern, new MessageHandler() { @Override public void handle(String pattern, Reply[] replyData) { JsonObject replyMessage = new JsonObject(); replyMessage.putString("status", "ok"); JsonObject message = new JsonObject(); message.putString("pattern", pattern); message.putString("channel", ((BulkReply) replyData[2]).asString(encoding)); message.putString("message", ((BulkReply) replyData[3]).asString(encoding)); replyMessage.putObject("value", message); eb.send(vertxChannel, replyMessage); } }); } break; // argument "channel" ["channel"...] case "subscribe": if (args == null) { sendError(message, "at least one pattern is required!"); return; } // in this case we need also to register handlers expectedReplies = args.size(); for (Object obj : args) { String channel = (String) obj; // compose the listening address as base + . + channel final String vertxChannel = baseAddress + "." + channel; subscriptions.registerChannelSubscribeHandler(channel, new MessageHandler() { @Override public void handle(String channel, Reply[] replyData) { JsonObject replyMessage = new JsonObject(); replyMessage.putString("status", "ok"); JsonObject message = new JsonObject(); message.putString("channel", channel); message.putString("message", ((BulkReply) replyData[2]).asString(encoding)); replyMessage.putObject("value", message); eb.send(vertxChannel, replyMessage); } }); } break; // argument ["pattern" ["pattern"...]] case "punsubscribe": // unregister all channels if (args == null || args.size() == 0) { // unsubscribe all expectedReplies = subscriptions.patternSize(); subscriptions.unregisterPatternSubscribeHandler(null); } else { expectedReplies = args.size(); for (Object obj : args) { String pattern = (String) obj; subscriptions.unregisterPatternSubscribeHandler(pattern); } } break; // argument ["channel" ["channel"...]] case "unsubscribe": // unregister all channels if (args == null || args.size() == 0) { // unsubscribe all expectedReplies = subscriptions.channelSize(); subscriptions.unregisterChannelSubscribeHandler(null); } else { expectedReplies = args.size(); for (Object obj : args) { String channel = (String) obj; subscriptions.unregisterChannelSubscribeHandler(channel); } } break; } redisClient.send(message.body(), expectedReplies, new Handler<Reply>() { @Override public void handle(Reply reply) { processReply(message, reply, transform); } }); }
public void handle(final Message<JsonObject> message) { String command = message.body().getString("command"); final JsonArray args = message.body().getArray("args"); if (command == null) { sendError(message, "command must be specified"); return; } else { command = command.toLowerCase(); } final ResponseTransform transform = getResponseTransformFor(command); // subscribe/psubscribe and unsubscribe/punsubscribe commands can have multiple (including zero) replies int expectedReplies = 1; switch (command) { // argument "pattern" ["pattern"...] case "psubscribe": // in this case we need also to register handlers if (args == null) { sendError(message, "at least one pattern is required!"); return; } expectedReplies = args.size(); for (Object obj : args) { String pattern = (String) obj; // compose the listening address as base + . + pattern final String vertxChannel = baseAddress + "." + pattern; subscriptions.registerPatternSubscribeHandler(pattern, new MessageHandler() { @Override public void handle(String pattern, Reply[] replyData) { JsonObject replyMessage = new JsonObject(); replyMessage.putString("status", "ok"); JsonObject message = new JsonObject(); message.putString("pattern", pattern); message.putString("channel", ((BulkReply) replyData[2]).asString(encoding)); message.putString("message", ((BulkReply) replyData[3]).asString(encoding)); replyMessage.putObject("value", message); eb.send(vertxChannel, replyMessage); } }); } break; // argument "channel" ["channel"...] case "subscribe": if (args == null) { sendError(message, "at least one pattern is required!"); return; } // in this case we need also to register handlers expectedReplies = args.size(); for (Object obj : args) { String channel = (String) obj; // compose the listening address as base + . + channel final String vertxChannel = baseAddress + "." + channel; subscriptions.registerChannelSubscribeHandler(channel, new MessageHandler() { @Override public void handle(String channel, Reply[] replyData) { JsonObject replyMessage = new JsonObject(); replyMessage.putString("status", "ok"); JsonObject message = new JsonObject(); message.putString("channel", channel); message.putString("message", ((BulkReply) replyData[2]).asString(encoding)); replyMessage.putObject("value", message); eb.send(vertxChannel, replyMessage); } }); } break; // argument ["pattern" ["pattern"...]] case "punsubscribe": // unregister all channels if (args == null || args.size() == 0) { // unsubscribe all expectedReplies = subscriptions.patternSize(); subscriptions.unregisterPatternSubscribeHandler(null); } else { expectedReplies = args.size(); for (Object obj : args) { String pattern = (String) obj; subscriptions.unregisterPatternSubscribeHandler(pattern); } } break; // argument ["channel" ["channel"...]] case "unsubscribe": // unregister all channels if (args == null || args.size() == 0) { // unsubscribe all expectedReplies = subscriptions.channelSize(); subscriptions.unregisterChannelSubscribeHandler(null); } else { expectedReplies = args.size(); for (Object obj : args) { String channel = (String) obj; subscriptions.unregisterChannelSubscribeHandler(channel); } } break; } redisClient.send(message.body(), expectedReplies, new Handler<Reply>() { @Override public void handle(Reply reply) { processReply(message, reply, transform); } }); }
diff --git a/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java b/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java index 5104dc6..7e8f81f 100644 --- a/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java +++ b/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/Weapons/ProjectileWeapon.java @@ -1,97 +1,96 @@ /* * The MIT License * * Copyright 2013 Manuel Gauto. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.mgenterprises.java.bukkit.gmcfps.Core.Weapons; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.inventory.ItemStack; import org.mgenterprises.java.bukkit.gmcfps.Core.InternalEvents.Events.WeaponFiredEvent; /** * * @author Manuel Gauto */ public abstract class ProjectileWeapon extends Weapon { private Material ammoMaterial; private EntityType projectileType; private int fireDelay; public ProjectileWeapon(WeaponManager wm, String name, Material m, Material ammoType, EntityType projectileType, int fireDelay) { super(wm, name, m); this.ammoMaterial = ammoType; this.fireDelay = fireDelay; this.projectileType = projectileType; } public Material getAmmunitionType() { return this.ammoMaterial; } public abstract void onWeaponFire(Player p); @Override public void onWeaponRightClick(WeaponFiredEvent event) { //System.out.println(event); if(super.getWeaponManager().waiting.contains(event.getPlayer().getName())){ return; } boolean hasAmmoLeft = event.getPlayer().getInventory().contains(ammoMaterial); if (hasAmmoLeft) { ItemStack ammoUsed = new ItemStack(ammoMaterial); - event.getPlayer().getInventory().remove(ammoUsed); int slot = event.getPlayer().getInventory().first(ammoUsed); ItemStack itemStack = event.getPlayer().getInventory().getItem(slot); itemStack.setAmount(itemStack.getAmount()-1); - event.getPlayer().getInventory().remove(slot); + event.getPlayer().getInventory().clear(slot); event.getPlayer().getInventory().addItem(itemStack); onWeaponFire(event.getPlayer()); scheduleDelay(event.getPlayer()); } } @Override public boolean isThrowable() { return false; } @Override public boolean isProjectile() { return true; } public EntityType getProjectileType(){ return this.projectileType; } public abstract void onProjectileHit(EntityDamageByEntityEvent event); private void scheduleDelay(Player p) { Bukkit.getScheduler().scheduleSyncDelayedTask(super.getWeaponManager().getFPSCore().getPluginReference(), new DelayRunnable(super.getWeaponManager().getFPSCore(), p), this.fireDelay); } }
false
true
public void onWeaponRightClick(WeaponFiredEvent event) { //System.out.println(event); if(super.getWeaponManager().waiting.contains(event.getPlayer().getName())){ return; } boolean hasAmmoLeft = event.getPlayer().getInventory().contains(ammoMaterial); if (hasAmmoLeft) { ItemStack ammoUsed = new ItemStack(ammoMaterial); event.getPlayer().getInventory().remove(ammoUsed); int slot = event.getPlayer().getInventory().first(ammoUsed); ItemStack itemStack = event.getPlayer().getInventory().getItem(slot); itemStack.setAmount(itemStack.getAmount()-1); event.getPlayer().getInventory().remove(slot); event.getPlayer().getInventory().addItem(itemStack); onWeaponFire(event.getPlayer()); scheduleDelay(event.getPlayer()); } }
public void onWeaponRightClick(WeaponFiredEvent event) { //System.out.println(event); if(super.getWeaponManager().waiting.contains(event.getPlayer().getName())){ return; } boolean hasAmmoLeft = event.getPlayer().getInventory().contains(ammoMaterial); if (hasAmmoLeft) { ItemStack ammoUsed = new ItemStack(ammoMaterial); int slot = event.getPlayer().getInventory().first(ammoUsed); ItemStack itemStack = event.getPlayer().getInventory().getItem(slot); itemStack.setAmount(itemStack.getAmount()-1); event.getPlayer().getInventory().clear(slot); event.getPlayer().getInventory().addItem(itemStack); onWeaponFire(event.getPlayer()); scheduleDelay(event.getPlayer()); } }
diff --git a/srcj/com/sun/electric/tool/user/menus/EditMenu.java b/srcj/com/sun/electric/tool/user/menus/EditMenu.java index 77cff032d..491dc927b 100644 --- a/srcj/com/sun/electric/tool/user/menus/EditMenu.java +++ b/srcj/com/sun/electric/tool/user/menus/EditMenu.java @@ -1,1489 +1,1491 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: EditMenu.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.user.menus; import com.sun.electric.database.change.Undo; import com.sun.electric.database.geometry.DBMath; import com.sun.electric.database.geometry.Geometric; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.hierarchy.Export; import com.sun.electric.database.hierarchy.Library; import com.sun.electric.database.prototype.NodeProto; import com.sun.electric.database.topology.ArcInst; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.topology.PortInst; import com.sun.electric.database.variable.ElectricObject; import com.sun.electric.database.variable.Variable; import com.sun.electric.technology.ArcProto; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.technology.Technology; import com.sun.electric.technology.technologies.FPGA; import com.sun.electric.technology.technologies.Generic; import com.sun.electric.tool.Job; import com.sun.electric.tool.user.CircuitChanges; import com.sun.electric.tool.user.Clipboard; import com.sun.electric.tool.user.ErrorLogger; import com.sun.electric.tool.user.Highlight; import com.sun.electric.tool.user.Highlighter; import com.sun.electric.tool.user.User; import com.sun.electric.tool.user.dialogs.Array; import com.sun.electric.tool.user.dialogs.ArtworkLook; import com.sun.electric.tool.user.dialogs.Attributes; import com.sun.electric.tool.user.dialogs.Change; import com.sun.electric.tool.user.dialogs.ChangeText; import com.sun.electric.tool.user.dialogs.EditKeyBindings; import com.sun.electric.tool.user.dialogs.FindText; import com.sun.electric.tool.user.dialogs.GetInfoArc; import com.sun.electric.tool.user.dialogs.GetInfoExport; import com.sun.electric.tool.user.dialogs.GetInfoMulti; import com.sun.electric.tool.user.dialogs.GetInfoNode; import com.sun.electric.tool.user.dialogs.GetInfoOutline; import com.sun.electric.tool.user.dialogs.GetInfoText; import com.sun.electric.tool.user.dialogs.MoveBy; import com.sun.electric.tool.user.dialogs.SelectObject; import com.sun.electric.tool.user.dialogs.SpecialProperties; import com.sun.electric.tool.user.dialogs.Spread; import com.sun.electric.tool.user.tecEdit.LibToTech; import com.sun.electric.tool.user.tecEdit.Manipulate; import com.sun.electric.tool.user.tecEdit.TechToLib; import com.sun.electric.tool.user.ui.CurveListener; import com.sun.electric.tool.user.ui.EditWindow; import com.sun.electric.tool.user.ui.OutlineListener; import com.sun.electric.tool.user.ui.SizeListener; import com.sun.electric.tool.user.ui.ToolBar; import com.sun.electric.tool.user.ui.TopLevel; import com.sun.electric.tool.user.ui.WaveformWindow; import com.sun.electric.tool.user.ui.WindowFrame; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.EventListener; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JMenuItem; import javax.swing.KeyStroke; /** * Class to handle the commands in the "Edit" pulldown menu. */ public class EditMenu { private static JMenuItem moveFull, moveHalf, moveQuarter; /** * Method to select proper buttom in EditMenu depending on gridAlignment value * @param ad */ public static void setGridAligment(double ad) { if (ad == 1.0) moveFull.setSelected(true); else if (ad == 0.5) moveHalf.setSelected(true); else if (ad == 0.25) moveQuarter.setSelected(true); } protected static void addEditMenu(MenuBar menuBar) { MenuBar.MenuItem m; int buckyBit = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /****************************** THE EDIT MENU ******************************/ // mnemonic keys available: B JK Q W // still don't have mnemonic for "Repeat Last Action" MenuBar.Menu editMenu = MenuBar.makeMenu("_Edit"); menuBar.add(editMenu); editMenu.addMenuItem("Cu_t", KeyStroke.getKeyStroke('X', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.cut(); } }); editMenu.addMenuItem("Cop_y", KeyStroke.getKeyStroke('C', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.copy(); } }); editMenu.addMenuItem("_Paste", KeyStroke.getKeyStroke('V', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.paste(false); } }); editMenu.addMenuItem("Dup_licate", KeyStroke.getKeyStroke('M', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.duplicate(); } }); editMenu.addSeparator(); MenuBar.MenuItem undo = editMenu.addMenuItem("_Undo", KeyStroke.getKeyStroke('Z', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { undoCommand(); } }); Undo.addPropertyChangeListener(new MenuCommands.MenuEnabler(undo, Undo.propUndoEnabled)); undo.setEnabled(Undo.getUndoEnabled()); // TODO: figure out how to remove this property change listener for correct garbage collection MenuBar.MenuItem redo = editMenu.addMenuItem("Re_do", KeyStroke.getKeyStroke('Y', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { redoCommand(); } }); Undo.addPropertyChangeListener(new MenuCommands.MenuEnabler(redo, Undo.propRedoEnabled)); redo.setEnabled(Undo.getRedoEnabled()); // TODO: figure out how to remove this property change listener for correct garbage collection editMenu.addMenuItem("Repeat Last Action", KeyStroke.getKeyStroke(KeyEvent.VK_AMPERSAND, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { repeatLastCommand(); } }); editMenu.addSeparator(); // mnemonic keys available: AB EFGHIJKLMN PQRSTUV XYZ MenuBar.Menu rotateSubMenu = MenuBar.makeMenu("_Rotate"); editMenu.add(rotateSubMenu); rotateSubMenu.addMenuItem("90 Degrees Clock_wise", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(2700); }}); rotateSubMenu.addMenuItem("90 Degrees _Counterclockwise", KeyStroke.getKeyStroke('J', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(900); }}); rotateSubMenu.addMenuItem("180 _Degrees", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(1800); }}); rotateSubMenu.addMenuItem("_Other...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(0); }}); // mnemonic keys available: ABCDEFGHIJK MNOPQRST VWXYZ MenuBar.Menu mirrorSubMenu = MenuBar.makeMenu("_Mirror"); editMenu.add(mirrorSubMenu); mirrorSubMenu.addMenuItem("_Up <-> Down", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(true); }}); mirrorSubMenu.addMenuItem("_Left <-> Right", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(false); }}); // mnemonic keys available: BCDEFGH JKLM OPQRSTUVWXYZ MenuBar.Menu sizeSubMenu = MenuBar.makeMenu("Si_ze"); editMenu.add(sizeSubMenu); sizeSubMenu.addMenuItem("_Interactively", KeyStroke.getKeyStroke('B', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeObjects(); } }); sizeSubMenu.addMenuItem("All Selected _Nodes...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllNodes(); }}); sizeSubMenu.addMenuItem("All Selected _Arcs...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllArcs(); }}); // mnemonic keys available: DEFGHIJK NOPQ U WXYZ MenuBar.Menu moveSubMenu = MenuBar.makeMenu("Mo_ve"); editMenu.add(moveSubMenu); moveSubMenu.addMenuItem("_Spread...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Spread.showSpreadDialog(); }}); moveSubMenu.addMenuItem("_Move Objects By...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { MoveBy.showMoveByDialog(); }}); moveSubMenu.addMenuItem("_Align to Grid", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignToGrid(); }}); moveSubMenu.addSeparator(); moveSubMenu.addMenuItem("Align Horizontally to _Left", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 0); }}); moveSubMenu.addMenuItem("Align Horizontally to _Right", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 1); }}); moveSubMenu.addMenuItem("Align Horizontally to _Center", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 2); }}); moveSubMenu.addSeparator(); moveSubMenu.addMenuItem("Align Vertically to _Top", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 0); }}); moveSubMenu.addMenuItem("Align Vertically to _Bottom", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 1); }}); moveSubMenu.addMenuItem("Align _Vertically to Center", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 2); }}); editMenu.addSeparator(); m=editMenu.addMenuItem("_Erase", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelected(); } }); menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), null); editMenu.addMenuItem("_Array...", KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { Array.showArrayDialog(); } }); editMenu.addMenuItem("C_hange...", KeyStroke.getKeyStroke('C', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { Change.showChangeDialog(); } }); editMenu.addSeparator(); // mnemonic keys available: ABCDEFGHIJKLMNOPQRS VWXYZ MenuBar.Menu editInfoSubMenu = MenuBar.makeMenu("In_fo"); editMenu.add(editInfoSubMenu); // editInfoSubMenu.addMenuItem("List Layer Coverage", null, // new ActionListener() { public void actionPerformed(ActionEvent e) { LayerCoverageJob.layerCoverageCommand(Job.Type.EXAMINE, LayerCoverageJob.AREA, GeometryHandler.ALGO_SWEEP); } }); editInfoSubMenu.addMenuItem("Show _Undo List", null, new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); } }); // mnemonic keys available: BC EFG IJK M PQR TUVWXYZ MenuBar.Menu editPropertiesSubMenu = MenuBar.makeMenu("Propert_ies"); editMenu.add(editPropertiesSubMenu); editPropertiesSubMenu.addMenuItem("_Object Properties...", KeyStroke.getKeyStroke('I', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { getInfoCommand(false); } }); editPropertiesSubMenu.addMenuItem("_Attribute Properties...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Attributes.showDialog(); } }); editPropertiesSubMenu.addSeparator(); editPropertiesSubMenu.addMenuItem("_See All Attributes on Node", null, new ActionListener() { public void actionPerformed(ActionEvent e) { seeAllParametersCommand(); } }); editPropertiesSubMenu.addMenuItem("_Hide All Attributes on Node", null, new ActionListener() { public void actionPerformed(ActionEvent e) { hideAllParametersCommand(); } }); editPropertiesSubMenu.addMenuItem("_Default Attribute Visibility", null, new ActionListener() { public void actionPerformed(ActionEvent e) { defaultParamVisibilityCommand(); } }); editPropertiesSubMenu.addMenuItem("Update Attributes Inheritance on _Node", null, new ActionListener() { public void actionPerformed(ActionEvent e) { updateInheritance(false); } }); editPropertiesSubMenu.addMenuItem("Update Attributes Inheritance all _Libraries", null, new ActionListener() { public void actionPerformed(ActionEvent e) { updateInheritance(true); } }); // mnemonic keys available: E G I KL OPQ S VWXYZ MenuBar.Menu arcSubMenu = MenuBar.makeMenu("Ar_c"); editMenu.add(arcSubMenu); arcSubMenu.addMenuItem("_Rigid", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcRigidCommand(); }}); arcSubMenu.addMenuItem("_Not Rigid", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotRigidCommand(); }}); arcSubMenu.addMenuItem("_Fixed Angle", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcFixedAngleCommand(); }}); arcSubMenu.addMenuItem("Not Fixed _Angle", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotFixedAngleCommand(); }}); arcSubMenu.addSeparator(); arcSubMenu.addMenuItem("Toggle _Directionality", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcDirectionalCommand(); }}); - arcSubMenu.addMenuItem("Toggle End Extension of _Head", null, + arcSubMenu.addMenuItem("Toggle End Extension of Both Head/Tail", null, + new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcHeadExtendCommand(); CircuitChanges.arcTailExtendCommand();}}); + arcSubMenu.addMenuItem("Toggle End Extension of _Head", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcHeadExtendCommand(); }}); arcSubMenu.addMenuItem("Toggle End Extension of _Tail", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcTailExtendCommand(); }}); arcSubMenu.addSeparator(); arcSubMenu.addMenuItem("Insert _Jog In Arc", null, new ActionListener() { public void actionPerformed(ActionEvent e) { insertJogInArcCommand(); } }); arcSubMenu.addMenuItem("Rip _Bus", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.ripBus(); }}); arcSubMenu.addSeparator(); arcSubMenu.addMenuItem("_Curve through Cursor", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CurveListener.setCurvature(true); } }); arcSubMenu.addMenuItem("Curve abo_ut Cursor", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CurveListener.setCurvature(false); }}); arcSubMenu.addMenuItem("Re_move Curvature", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CurveListener.removeCurvature(); }}); // mnemonic keys available: ABCD FGHIJKL NOPQR TUVWXYZ MenuBar.Menu modeSubMenu = MenuBar.makeMenu("M_odes"); editMenu.add(modeSubMenu); // mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ MenuBar.Menu modeSubMenuEdit = MenuBar.makeMenu("_Edit"); modeSubMenu.add(modeSubMenuEdit); ButtonGroup editGroup = new ButtonGroup(); JMenuItem cursorClickZoomWire, cursorPan, cursorZoom, cursorOutline, cursorMeasure; cursorClickZoomWire = modeSubMenuEdit.addRadioButton(ToolBar.cursorClickZoomWireName, true, editGroup, KeyStroke.getKeyStroke('S', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.clickZoomWireCommand(); } }); ToolBar.CursorMode cm = ToolBar.getCursorMode(); if (cm == ToolBar.CursorMode.CLICKZOOMWIRE) cursorClickZoomWire.setSelected(true); cursorPan = modeSubMenuEdit.addRadioButton(ToolBar.cursorPanName, false, editGroup, KeyStroke.getKeyStroke('P', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.panCommand(); } }); cursorZoom = modeSubMenuEdit.addRadioButton(ToolBar.cursorZoomName, false, editGroup, KeyStroke.getKeyStroke('Z', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.zoomCommand(); } }); cursorOutline = modeSubMenuEdit.addRadioButton(ToolBar.cursorOutlineName, false, editGroup, KeyStroke.getKeyStroke('Y', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.outlineEditCommand(); } }); cursorMeasure = modeSubMenuEdit.addRadioButton(ToolBar.cursorMeasureName, false, editGroup, KeyStroke.getKeyStroke('M', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.measureCommand(); } }); if (cm == ToolBar.CursorMode.PAN) cursorPan.setSelected(true); if (cm == ToolBar.CursorMode.ZOOM) cursorZoom.setSelected(true); if (cm == ToolBar.CursorMode.OUTLINE) cursorOutline.setSelected(true); if (cm == ToolBar.CursorMode.MEASURE) cursorMeasure.setSelected(true); // mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ MenuBar.Menu modeSubMenuMovement = MenuBar.makeMenu("_Movement"); modeSubMenu.add(modeSubMenuMovement); ButtonGroup movementGroup = new ButtonGroup(); moveFull = modeSubMenuMovement.addRadioButton(ToolBar.moveFullName, true, movementGroup, KeyStroke.getKeyStroke('F', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.arrowDistanceCommand(ToolBar.ArrowDistance.FULL); } }); moveHalf = modeSubMenuMovement.addRadioButton(ToolBar.moveHalfName, false, movementGroup, KeyStroke.getKeyStroke('H', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.arrowDistanceCommand(ToolBar.ArrowDistance.HALF); } }); moveQuarter = modeSubMenuMovement.addRadioButton(ToolBar.moveQuarterName, false, movementGroup, null, // do not put shortcut in here! Too dangerous!! new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.arrowDistanceCommand(ToolBar.ArrowDistance.QUARTER); } }); setGridAligment(User.getAlignmentToGrid()); // mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ MenuBar.Menu modeSubMenuSelect = MenuBar.makeMenu("_Select"); modeSubMenu.add(modeSubMenuSelect); ButtonGroup selectGroup = new ButtonGroup(); JMenuItem selectArea, selectObjects; selectArea = modeSubMenuSelect.addRadioButton(ToolBar.selectAreaName, true, selectGroup, null, new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectAreaCommand(); } }); selectObjects = modeSubMenuSelect.addRadioButton(ToolBar.selectObjectsName, false, selectGroup, null, new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectObjectsCommand(); } }); ToolBar.SelectMode sm = ToolBar.getSelectMode(); if (sm == ToolBar.SelectMode.AREA) selectArea.setSelected(true); else selectObjects.setSelected(true); modeSubMenuSelect.addCheckBox(ToolBar.specialSelectName, false, null, new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.toggleSelectSpecialCommand(e); } }); // mnemonic keys available: AB E GH JKLMNOPQRSTUVWXYZ MenuBar.Menu textSubMenu = MenuBar.makeMenu("Te_xt"); editMenu.add(textSubMenu); textSubMenu.addMenuItem("_Find Text...", KeyStroke.getKeyStroke('L', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { FindText.findTextDialog(); }}); textSubMenu.addMenuItem("_Change Text Size...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { ChangeText.changeTextDialog(); }}); textSubMenu.addMenuItem("_Increase All Text Size", KeyStroke.getKeyStroke('=', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { changeGlobalTextSize(1.25); }}); textSubMenu.addMenuItem("_Decrease All Text Size", KeyStroke.getKeyStroke('-', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { changeGlobalTextSize(0.8); }}); // mnemonic keys available: ABCD FGHIJK M O QR TUVWXYZ MenuBar.Menu cleanupSubMenu = MenuBar.makeMenu("Clea_nup Cell"); editMenu.add(cleanupSubMenu); cleanupSubMenu.addMenuItem("Cleanup _Pins", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(false); }}); cleanupSubMenu.addMenuItem("Cleanup Pins _Everywhere", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(true); }}); cleanupSubMenu.addMenuItem("Show _Nonmanhattan", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showNonmanhattanCommand(); }}); cleanupSubMenu.addMenuItem("Show Pure _Layer Nodes", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showPureLayerCommand(); }}); cleanupSubMenu.addMenuItem("_Shorten Selected Arcs", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.shortenArcsCommand(); }}); // mnemonic keys available: GH JK O QRS UVWXYZ MenuBar.Menu specialSubMenu = MenuBar.makeMenu("Technolo_gy Specific"); editMenu.add(specialSubMenu); specialSubMenu.addMenuItem("Toggle Port _Negation", KeyStroke.getKeyStroke('T', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.toggleNegatedCommand(); }}); specialSubMenu.addMenuItem("_Artwork Appearance...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { ArtworkLook.showArtworkLookDialog(); }}); specialSubMenu.addSeparator(); // mnemonic keys available: B DEFG IJKLM O Q TUV XYZ MenuBar.Menu fpgaSubMenu = MenuBar.makeMenu("_FPGA"); specialSubMenu.add(fpgaSubMenu); fpgaSubMenu.addMenuItem("Read _Architecture And Primitives...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.readArchitectureFile(true); }}); fpgaSubMenu.addMenuItem("Read P_rimitives...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.readArchitectureFile(false); }}); fpgaSubMenu.addSeparator(); fpgaSubMenu.addMenuItem("Edit _Pips...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.programPips(); }}); fpgaSubMenu.addSeparator(); fpgaSubMenu.addMenuItem("Show _No Wires", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setWireDisplay(0); }}); fpgaSubMenu.addMenuItem("Show A_ctive Wires", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setWireDisplay(1); }}); fpgaSubMenu.addMenuItem("Show All _Wires", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setWireDisplay(2); }}); fpgaSubMenu.addSeparator(); fpgaSubMenu.addMenuItem("_Show Text", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setTextDisplay(true); }}); fpgaSubMenu.addMenuItem("_Hide Text", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setTextDisplay(false); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Convert Technology to _Library for Editing...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { TechToLib.makeLibFromTech(); }}); specialSubMenu.addMenuItem("Convert Library to _Technology...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { LibToTech.makeTechFromLib(); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("_Identify Primitive Layers", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.identifyLayers(false); }}); specialSubMenu.addMenuItem("Identify _Ports", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.identifyLayers(true); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Edit Library _Dependencies...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.editLibraryDependencies(); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Descri_be this Technology", null, new ActionListener() { public void actionPerformed(ActionEvent e) { describeTechnologyCommand(); } }); specialSubMenu.addMenuItem("Do_cument Current Technology", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.describeTechnology(Technology.getCurrent()); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Rena_me Current Technology...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.renameCurrentTechnology(); } }); // specialSubMenu.addMenuItem("D_elete Current Technology", null, // new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteCurrentTechnology(); } }); // mnemonic keys available: B F I KLM PQ Z MenuBar.Menu selListSubMenu = MenuBar.makeMenu("_Selection"); editMenu.add(selListSubMenu); selListSubMenu.addMenuItem("Sele_ct All", KeyStroke.getKeyStroke('A', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllCommand(); }}); selListSubMenu.addMenuItem("Select All Like _This", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLikeThisCommand(); }}); selListSubMenu.addMenuItem("Select All _Easy", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectEasyCommand(); }}); selListSubMenu.addMenuItem("Select All _Hard", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectHardCommand(); }}); selListSubMenu.addMenuItem("Select Nothin_g", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectNothingCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("_Select Object...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { SelectObject.selectObjectDialog(); }}); selListSubMenu.addMenuItem("Deselect All _Arcs", null, new ActionListener() { public void actionPerformed(ActionEvent e) { deselectAllArcsCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Make Selected Eas_y", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }}); selListSubMenu.addMenuItem("Make Selected Har_d", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeHardCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("P_ush Selection", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EditWindow wnd = EditWindow.getCurrent(); if (wnd == null) return; wnd.getHighlighter().pushHighlight(); }}); selListSubMenu.addMenuItem("P_op Selection", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EditWindow wnd = EditWindow.getCurrent(); if (wnd ==null) return; wnd.getHighlighter().popHighlight(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Enclosed Ob_jects", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectEnclosedObjectsCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Show Ne_xt Error", KeyStroke.getKeyStroke('>'), new ActionListener() { public void actionPerformed(ActionEvent e) { showNextErrorCommand(); }}); selListSubMenu.addMenuItem("Show Pre_vious Error", KeyStroke.getKeyStroke('<'), new ActionListener() { public void actionPerformed(ActionEvent e) { showPrevErrorCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Add to Waveform in _New Panel", KeyStroke.getKeyStroke('A', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { addToWaveformNewCommand(); }}); selListSubMenu.addMenuItem("Add to _Waveform in Current Panel", KeyStroke.getKeyStroke('O', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { addToWaveformCurrentCommand(); }}); selListSubMenu.addMenuItem("_Remove from _Waveform", KeyStroke.getKeyStroke('R', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { removeFromWaveformCommand(); }}); } public static void undoCommand() { new UndoCommand(); } /** * This class implement the command to undo the last change. */ private static class UndoCommand extends Job { private UndoCommand() { super("Undo", User.getUserTool(), Job.Type.UNDO, Undo.upCell(false), null, Job.Priority.USER); startJob(); } public boolean doIt() { if (Undo.undoABatch() == null) System.out.println("Undo failed!"); return true; } } public static void redoCommand() { new RedoCommand(); } /** * This class implement the command to undo the last change (Redo). */ private static class RedoCommand extends Job { private RedoCommand() { super("Redo", User.getUserTool(), Job.Type.UNDO, Undo.upCell(true), null, Job.Priority.USER); startJob(); } public boolean doIt() { if (!Undo.redoABatch()) System.out.println("Redo failed!"); return true; } } /** * Repeat the last Command */ public static void repeatLastCommand() { AbstractButton lastActivated = MenuBar.repeatLastCommandListener.getLastActivated(); if (lastActivated != null) { lastActivated.doClick(); } } /** * This method implements the command to show the Key Bindings Options dialog. */ public static void keyBindingsCommand() { // edit key bindings for current menu TopLevel top = (TopLevel)TopLevel.getCurrentJFrame(); EditKeyBindings dialog = new EditKeyBindings(top.getTheMenuBar(), top, true); dialog.setVisible(true); } /** * This method shows the GetInfo dialog for the highlighted nodes, arcs, and/or text. */ public static void getInfoCommand(boolean doubleClick) { EditWindow wnd = EditWindow.getCurrent(); if (wnd == null) return; if (wnd.getHighlighter().getNumHighlights() == 0) { // information about the cell Cell c = WindowFrame.getCurrentCell(); if (c != null) c.getInfo(); } else { // information about the selected items int arcCount = 0; int nodeCount = 0; int exportCount = 0; int textCount = 0; int graphicsCount = 0; NodeInst theNode = null; for(Iterator it = wnd.getHighlighter().getHighlights().iterator(); it.hasNext(); ) { Highlight h = (Highlight)it.next(); ElectricObject eobj = h.getElectricObject(); if (h.getType() == Highlight.Type.EOBJ) { if (eobj instanceof NodeInst || eobj instanceof PortInst) { nodeCount++; if (eobj instanceof NodeInst) theNode = (NodeInst)eobj; else theNode = ((PortInst)eobj).getNodeInst(); } else if (eobj instanceof ArcInst) { arcCount++; } } else if (h.getType() == Highlight.Type.TEXT) { if (eobj instanceof Export) { if (h.getVar() != null) textCount++; else exportCount++; } else { if (eobj instanceof NodeInst) theNode = (NodeInst)eobj; textCount++; } } else if (h.getType() == Highlight.Type.BBOX) { graphicsCount++; } else if (h.getType() == Highlight.Type.LINE) { graphicsCount++; } } // special dialogs for double-clicking on known nodes if (doubleClick) { if (arcCount == 0 && exportCount == 0 && graphicsCount == 0 && nodeCount + textCount == 1 && theNode != null) { if (SpecialProperties.doubleClickOnNode(wnd, theNode)) return; } } if (arcCount <= 1 && nodeCount <= 1 && exportCount <= 1 && textCount <= 1 && graphicsCount == 0) { if (arcCount == 1) GetInfoArc.showDialog(); if (nodeCount == 1) { // if in outline-edit mode, show that dialog if (WindowFrame.getListener() == OutlineListener.theOne) { GetInfoOutline.showOutlinePropertiesDialog(); } else { GetInfoNode.showDialog(); } } if (exportCount == 1) { if (doubleClick) { GetInfoText.editTextInPlace(); } else { GetInfoExport.showDialog(); } } if (textCount == 1) { if (doubleClick) { GetInfoText.editTextInPlace(); } else { GetInfoText.showDialog(); } } } else { GetInfoMulti.showDialog(); } } } /** * Method to handle the "See All Parameters on Node" command. */ public static void seeAllParametersCommand() { ParameterVisibility job = new ParameterVisibility(0, MenuCommands.getSelectedObjects(true, false)); } /** * Method to handle the "Hide All Parameters on Node" command. */ public static void hideAllParametersCommand() { ParameterVisibility job = new ParameterVisibility(1, MenuCommands.getSelectedObjects(true, false)); } /** * Method to handle the "Default Parameter Visibility" command. */ public static void defaultParamVisibilityCommand() { ParameterVisibility job = new ParameterVisibility(2, MenuCommands.getSelectedObjects(true, false)); } /** * Class to do antenna checking in a new thread. */ private static class ParameterVisibility extends Job { private int how; private List selected; protected ParameterVisibility(int how, List selected) { super("Change Parameter Visibility", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER); this.how = how; this.selected = selected; startJob(); } public boolean doIt() { // change visibility of parameters on the current node(s) int changeCount = 0; java.util.List list = selected; for(Iterator it = list.iterator(); it.hasNext(); ) { NodeInst ni = (NodeInst)it.next(); if (!(ni.getProto() instanceof Cell)) continue; boolean changed = false; for(Iterator vIt = ni.getVariables(); vIt.hasNext(); ) { Variable var = (Variable)vIt.next(); Variable nVar = findParameterSource(var, ni); if (nVar == null) continue; switch (how) { case 0: // make all parameters visible if (var.isDisplay()) continue; var.setDisplay(true); changed = true; break; case 1: // make all parameters invisible if (!var.isDisplay()) continue; var.setDisplay(false); changed = true; break; case 2: // make all parameters have default visiblity if (nVar.getTextDescriptor().isInterior()) { // prototype wants parameter to be invisible if (!var.isDisplay()) continue; var.setDisplay(false); changed = true; } else { // prototype wants parameter to be visible if (var.isDisplay()) continue; var.setDisplay(true); changed = true; } break; } } if (changed) { Undo.redrawObject(ni); changeCount++; } } if (changeCount == 0) System.out.println("No Parameter visibility changed"); else System.out.println("Changed visibility on " + changeCount + " nodes"); return true; } } /** * Method to find the formal parameter that corresponds to the actual parameter * "var" on node "ni". Returns null if not a parameter or cannot be found. */ private static Variable findParameterSource(Variable var, NodeInst ni) { // find this parameter in the cell Cell np = (Cell)ni.getProto(); Cell cnp = np.contentsView(); if (cnp != null) np = cnp; for(Iterator it = np.getVariables(); it.hasNext(); ) { Variable nVar = (Variable)it.next(); if (var.getKey() == nVar.getKey()) return nVar; } return null; } public static void updateInheritance(boolean allLibraries) { // get currently selected node(s) List highlighted = MenuCommands.getSelectedObjects(true, false); UpdateAttributes job = new UpdateAttributes(highlighted, allLibraries, 0); } private static class UpdateAttributes extends Job { private List highlighted; private boolean allLibraries; private int whatToUpdate; /** * Update Attributes. * @param highlighted currently highlighted objects * @param allLibraries if true, update all nodeinsts in all libraries, otherwise update * highlighted * @param whatToUpdate if 0, update inheritance. If 1, update attributes locations. */ UpdateAttributes(List highlighted, boolean allLibraries, int whatToUpdate) { super("Update Inheritance", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER); this.highlighted = highlighted; this.allLibraries = allLibraries; this.whatToUpdate = whatToUpdate; startJob(); } public boolean doIt() { int count = 0; if (allLibraries) { for (Iterator it = Library.getLibraries(); it.hasNext(); ) { Library lib = (Library)it.next(); for (Iterator it2 = lib.getCells(); it2.hasNext(); ) { Cell c = (Cell)it2.next(); for (Iterator it3 = c.getNodes(); it3.hasNext(); ) { NodeInst ni = (NodeInst)it3.next(); if (ni.getProto() instanceof Cell) { if (whatToUpdate == 0) { updateInheritance(ni, (Cell)ni.getProto()); count++; } if (whatToUpdate == 1) { updateLocations(ni, (Cell)ni.getProto()); count++; } } } } } } else { for (Iterator it = highlighted.iterator(); it.hasNext(); ) { ElectricObject eobj = (ElectricObject)it.next(); if (eobj instanceof NodeInst) { NodeInst ni = (NodeInst)eobj; if (ni.getProto() instanceof Cell) { if (whatToUpdate == 0) { updateInheritance(ni, (Cell)ni.getProto()); count++; } if (whatToUpdate == 1) { updateLocations(ni, (Cell)ni.getProto()); count++; } } } } } if (whatToUpdate == 0) System.out.println("Updated Attribute Inheritance on "+count+" nodes"); if (whatToUpdate == 1) System.out.println("Updated Attribute Locations on "+count+" nodes"); return true; } private void updateInheritance(NodeInst ni, Cell proto) { CircuitChanges.inheritAttributes(ni, true); } private void updateLocations(NodeInst ni, Cell proto) { } } /** * Method to change the global text scale by a given amount. * @param scale the amount to scale the global text size. */ public static void changeGlobalTextSize(double scale) { double curScale = User.getGlobalTextScale(); curScale *= scale; if (curScale != 0) { User.setGlobalTextScale(curScale); EditWindow.repaintAllContents(); } } /** * This method implements the command to highlight all objects in the current Cell. */ public static void selectAllCommand() { doSelection(false, false); } /** * This method implements the command to highlight all objects in the current Cell * that are easy to select. */ public static void selectEasyCommand() { doSelection(true, false); } /** * This method implements the command to highlight all objects in the current Cell * that are hard to select. */ public static void selectHardCommand() { doSelection(false, true); } private static void doSelection(boolean mustBeEasy, boolean mustBeHard) { Cell curCell = WindowFrame.needCurCell(); if (curCell == null) return; EditWindow wnd = EditWindow.getCurrent(); if (wnd == null) return; Highlighter highlighter = wnd.getHighlighter(); boolean cellsAreHard = !User.isEasySelectionOfCellInstances(); highlighter.clear(); for(Iterator it = curCell.getNodes(); it.hasNext(); ) { NodeInst ni = (NodeInst)it.next(); // "select all" should not include the cell-center if (ni.getProto() == Generic.tech.cellCenterNode && !mustBeEasy && !mustBeHard) continue; boolean hard = ni.isHardSelect(); if ((ni.getProto() instanceof Cell) && cellsAreHard) hard = true; if (mustBeEasy && hard) continue; if (mustBeHard && !hard) continue; if (ni.isInvisiblePinWithText()) { for(Iterator vIt = ni.getVariables(); vIt.hasNext(); ) { Variable var = (Variable)vIt.next(); if (var.isDisplay()) { highlighter.addText(ni, curCell, var, null); break; } } } else { highlighter.addElectricObject(ni, curCell); } } for(Iterator it = curCell.getArcs(); it.hasNext(); ) { ArcInst ai = (ArcInst)it.next(); boolean hard = ai.isHardSelect(); if (mustBeEasy && hard) continue; if (mustBeHard && !hard) continue; highlighter.addElectricObject(ai, curCell); } // Selecting annotations for(Iterator it = curCell.getVariables(); it.hasNext(); ) { Variable var = (Variable)it.next(); if (var.isAttribute()) highlighter.addText(curCell, curCell, var, null); } highlighter.finished(); } /** * This method implements the command to highlight all objects in the current Cell * that are like the currently selected object. */ public static void selectAllLikeThisCommand() { Cell curCell = WindowFrame.needCurCell(); if (curCell == null) return; EditWindow wnd = EditWindow.getCurrent(); if (wnd == null) return; Highlighter highlighter = wnd.getHighlighter(); HashMap likeThis = new HashMap(); java.util.List highlighted = highlighter.getHighlightedEObjs(true, true); for(Iterator it = highlighted.iterator(); it.hasNext(); ) { Geometric geom = (Geometric)it.next(); if (geom instanceof NodeInst) { NodeInst ni = (NodeInst)geom; likeThis.put(ni.getProto(), ni); } else { ArcInst ai = (ArcInst)geom; likeThis.put(ai.getProto(), ai); } } highlighter.clear(); for(Iterator it = curCell.getNodes(); it.hasNext(); ) { NodeInst ni = (NodeInst)it.next(); Object isLikeThis = likeThis.get(ni.getProto()); if (isLikeThis == null) continue; if (ni.isInvisiblePinWithText()) { for(Iterator vIt = ni.getVariables(); vIt.hasNext(); ) { Variable var = (Variable)vIt.next(); if (var.isDisplay()) { highlighter.addText(ni, curCell, var, null); break; } } } else { highlighter.addElectricObject(ni, curCell); } } for(Iterator it = curCell.getArcs(); it.hasNext(); ) { ArcInst ai = (ArcInst)it.next(); Object isLikeThis = likeThis.get(ai.getProto()); if (isLikeThis == null) continue; highlighter.addElectricObject(ai, curCell); } highlighter.finished(); System.out.println("Selected "+highlighter.getNumHighlights()+ " objects"); } /** * This method implements the command to highlight nothing in the current Cell. */ public static void selectNothingCommand() { EditWindow wnd = EditWindow.getCurrent(); if (wnd == null) return; wnd.getHighlighter().clear(); wnd.getHighlighter().finished(); } /** * This method implements the command to deselect all selected arcs. */ public static void deselectAllArcsCommand() { EditWindow wnd = EditWindow.getCurrent(); if (wnd == null) return; Highlighter highlighter = wnd.getHighlighter(); java.util.List newHighList = new ArrayList(); for(Iterator it = highlighter.getHighlights().iterator(); it.hasNext(); ) { Highlight h = (Highlight)it.next(); if (h.getType() == Highlight.Type.EOBJ || h.getType() == Highlight.Type.TEXT) { if (h.getElectricObject() instanceof ArcInst) continue; } newHighList.add(h); } highlighter.clear(); highlighter.setHighlightList(newHighList); highlighter.finished(); } /** * This method implements the command to make all selected objects be easy-to-select. */ public static void selectMakeEasyCommand() { EditWindow wnd = EditWindow.getCurrent(); if (wnd == null) return; List highlighted = wnd.getHighlighter().getHighlightedEObjs(true, true); new SetEasyHardSelect(true, highlighted); } /** * This method implements the command to make all selected objects be hard-to-select. */ public static void selectMakeHardCommand() { EditWindow wnd = EditWindow.getCurrent(); if (wnd == null) return; java.util.List highlighted = wnd.getHighlighter().getHighlightedEObjs(true, true); new SetEasyHardSelect(false, highlighted); } /** * Class to set selected objects "easy to select" or "hard to select". */ private static class SetEasyHardSelect extends Job { private boolean easy; private List highlighted; private SetEasyHardSelect(boolean easy, List highlighted) { super("Make Selected Objects Easy/Hard To Select", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER); this.easy = easy; this.highlighted = highlighted; startJob(); } public boolean doIt() { for(Iterator it = highlighted.iterator(); it.hasNext(); ) { Geometric geom = (Geometric)it.next(); if (geom instanceof NodeInst) { NodeInst ni = (NodeInst)geom; if (easy) { ni.clearHardSelect(); } else { ni.setHardSelect(); } } else { ArcInst ai = (ArcInst)geom; if (easy) { ai.setHardSelect(false); } else { ai.setHardSelect(true); } } } return true; } } /** * This method implements the command to replace the rectangular highlight * with the selection of objects in that rectangle. */ public static void selectEnclosedObjectsCommand() { EditWindow wnd = EditWindow.needCurrent(); if (wnd == null) return; Highlighter highlighter = wnd.getHighlighter(); Rectangle2D selection = highlighter.getHighlightedArea(wnd); highlighter.clear(); if (selection != null ) highlighter.selectArea(wnd, selection.getMinX(), selection.getMaxX(), selection.getMinY(), selection.getMaxY(), false, ToolBar.getSelectSpecial()); highlighter.finished(); } /** * This method implements the command to show the next logged error. * The error log lists the results of the latest command (DRC, NCC, etc.) */ public static void showNextErrorCommand() { String msg = ErrorLogger.reportNextMessage(); System.out.println(msg); } /** * This method implements the command to show the last logged error. * The error log lists the results of the latest command (DRC, NCC, etc.) */ public static void showPrevErrorCommand() { String msg = ErrorLogger.reportPrevMessage(); System.out.println(msg); } /** * This method implements the command to add the currently selected network * to the waveform window, in a new panel. */ public static void addToWaveformNewCommand() { WindowFrame wf = WindowFrame.getCurrentWindowFrame(); if (!(wf.getContent() instanceof EditWindow)) return; EditWindow wnd = (EditWindow)wf.getContent(); WaveformWindow.Locator wwLoc = new WaveformWindow.Locator(wnd); WaveformWindow ww = wwLoc.getWaveformWindow(); if (ww == null) { System.out.println("Cannot add selected signals to the waveform window: no waveform window is associated with this cell"); return; } ww.showSignals(wnd.getHighlighter(), wwLoc.getContext(), true); } /** * This method implements the command to add the currently selected network * to the waveform window, overlaid on top of the current panel. */ public static void addToWaveformCurrentCommand() { WindowFrame wf = WindowFrame.getCurrentWindowFrame(); if (!(wf.getContent() instanceof EditWindow)) return; EditWindow wnd = (EditWindow)wf.getContent(); WaveformWindow.Locator wwLoc = new WaveformWindow.Locator(wnd); WaveformWindow ww = wwLoc.getWaveformWindow(); if (ww == null) { System.out.println("Cannot overlay selected signals to the waveform window: no waveform window is associated with this cell"); return; } ww.showSignals(wnd.getHighlighter(), wwLoc.getContext(), false); } /** * This method implements the command to remove the currently selected network * from the waveform window. */ public static void removeFromWaveformCommand() { WindowFrame wf = WindowFrame.getCurrentWindowFrame(); if (!(wf.getContent() instanceof EditWindow)) return; EditWindow wnd = (EditWindow)wf.getContent(); WaveformWindow.Locator wwLoc = new WaveformWindow.Locator(wnd); WaveformWindow ww = wwLoc.getWaveformWindow(); if (ww == null) { System.out.println("Cannot remove selected signals from the waveform window: no waveform window is associated with this cell"); return; } Set nets = wnd.getHighlighter().getHighlightedNetworks(); ww.removeSignals(nets, wwLoc.getContext()); } /** * This method implements the command to insert a jog in an arc */ public static void insertJogInArcCommand() { EditWindow wnd = EditWindow.needCurrent(); if (wnd == null) return; ArcInst ai = (ArcInst)wnd.getHighlighter().getOneElectricObject(ArcInst.class); if (ai == null) return; System.out.println("Select the position in the arc to place the jog"); EventListener currentListener = WindowFrame.getListener(); WindowFrame.setListener(new InsertJogInArcListener(wnd, ai, currentListener)); } /** * Class to handle the interactive selection of a jog point in an arc. */ private static class InsertJogInArcListener implements MouseMotionListener, MouseListener, MouseWheelListener, KeyListener { private EditWindow wnd; private ArcInst ai; private EventListener currentListener; /** * Create a new insert-jog-point listener * @param wnd Controlling window * @param ai the arc that is having a jog inserted. * @param currentListener listener to restore when done */ public InsertJogInArcListener(EditWindow wnd, ArcInst ai, EventListener currentListener) { this.wnd = wnd; this.ai = ai; this.currentListener = currentListener; } public void mousePressed(MouseEvent evt) {} public void mouseClicked(MouseEvent evt) {} public void mouseEntered(MouseEvent evt) {} public void mouseExited(MouseEvent evt) {} public void mouseDragged(MouseEvent evt) { mouseMoved(evt); } public void mouseReleased(MouseEvent evt) { Point2D insert = getInsertPoint(evt); InsertJogPoint job = new InsertJogPoint(ai, insert, wnd.getHighlighter()); WindowFrame.setListener(currentListener); } public void mouseMoved(MouseEvent evt) { Point2D insert = getInsertPoint(evt); double x = insert.getX(); double y = insert.getY(); double width = (ai.getWidth() - ai.getProto().getWidthOffset()) / 2; Highlighter highlighter = wnd.getHighlighter(); highlighter.clear(); highlighter.addLine(new Point2D.Double(x-width, y-width), new Point2D.Double(x-width, y+width), ai.getParent()); highlighter.addLine(new Point2D.Double(x-width, y+width), new Point2D.Double(x+width, y+width), ai.getParent()); highlighter.addLine(new Point2D.Double(x+width, y+width), new Point2D.Double(x+width, y-width), ai.getParent()); highlighter.addLine(new Point2D.Double(x+width, y-width), new Point2D.Double(x-width, y-width), ai.getParent()); highlighter.finished(); wnd.repaint(); } private Point2D getInsertPoint(MouseEvent evt) { Point2D mouseDB = wnd.screenToDatabase((int)evt.getX(), (int)evt.getY()); EditWindow.gridAlign(mouseDB); Point2D insert = DBMath.closestPointToSegment(ai.getHeadLocation(), ai.getTailLocation(), mouseDB); return insert; } public void mouseWheelMoved(MouseWheelEvent e) {} public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} private static class InsertJogPoint extends Job { private ArcInst ai; private Point2D insert; private Highlighter highlighter; protected InsertJogPoint(ArcInst ai, Point2D insert, Highlighter highlighter) { super("Insert Jog in Arc", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER); this.ai = ai; this.insert = insert; this.highlighter = highlighter; startJob(); } public boolean doIt() { if (CircuitChanges.cantEdit(ai.getParent(), null, true) != 0) return false; // create the break pins ArcProto ap = ai.getProto(); NodeProto np = ap.findPinProto(); if (np == null) return false; NodeInst ni = NodeInst.makeInstance(np, insert, np.getDefWidth(), np.getDefHeight(), ai.getParent()); if (ni == null) { System.out.println("Cannot create pin " + np.describe(true)); return false; } NodeInst ni2 = NodeInst.makeInstance(np, insert, np.getDefWidth(), np.getDefHeight(), ai.getParent()); if (ni2 == null) { System.out.println("Cannot create pin " + np.describe(true)); return false; } // get location of connection to these pins PortInst pi = ni.getOnlyPortInst(); PortInst pi2 = ni2.getOnlyPortInst(); // // see if edge alignment is appropriate // if (us_edgealignment_ratio != 0 && (ai->end[0].xpos == ai->end[1].xpos || // ai->end[0].ypos == ai->end[1].ypos)) // { // edgealignment = muldiv(us_edgealignment_ratio, WHOLE, el_curlib->lambda[el_curtech->techindex]); // px = us_alignvalue(x, edgealignment, &otheralign); // py = us_alignvalue(y, edgealignment, &otheralign); // if (px != x || py != y) // { // // shift the nodes and make sure the ports are still valid // startobjectchange((INTBIG)ni, VNODEINST); // modifynodeinst(ni, px-x, py-y, px-x, py-y, 0, 0); // endobjectchange((INTBIG)ni, VNODEINST); // startobjectchange((INTBIG)ni2, VNODEINST); // modifynodeinst(ni2, px-x, py-y, px-x, py-y, 0, 0); // endobjectchange((INTBIG)ni2, VNODEINST); // (void)shapeportpoly(ni, ppt, poly, FALSE); // if (!isinside(nx, ny, poly)) getcenter(poly, &nx, &ny); // } // } // now save the arc information and delete it PortInst headPort = ai.getHeadPortInst(); PortInst tailPort = ai.getTailPortInst(); Point2D headPt = ai.getHeadLocation(); Point2D tailPt = ai.getTailLocation(); double width = ai.getWidth(); String arcName = ai.getName(); int angle = (ai.getAngle() + 900) % 3600; // create the new arcs ArcInst newAi1 = ArcInst.makeInstance(ap, width, headPort, pi, headPt, insert, null); ArcInst newAi2 = ArcInst.makeInstance(ap, width, pi, pi2, insert, insert, null); ArcInst newAi3 = ArcInst.makeInstance(ap, width, pi2, tailPort, insert, tailPt, null); newAi1.setHeadNegated(ai.isHeadNegated()); newAi1.setHeadExtended(ai.isHeadExtended()); newAi1.setHeadArrowed(ai.isHeadArrowed()); newAi3.setTailNegated(ai.isTailNegated()); newAi3.setTailExtended(ai.isTailExtended()); newAi3.setTailArrowed(ai.isTailArrowed()); ai.kill(); if (arcName != null) { if (headPt.distance(insert) > tailPt.distance(insert)) { newAi1.setName(arcName); newAi1.copyTextDescriptorFrom(ai, ArcInst.ARC_NAME_TD); } else { newAi3.setName(arcName); newAi3.copyTextDescriptorFrom(ai, ArcInst.ARC_NAME_TD); } } newAi2.setAngle(angle); // highlight one of the jog nodes highlighter.clear(); highlighter.addElectricObject(ni, ai.getParent()); highlighter.finished(); return true; } } } /** * This method implements the command to show the undo history. */ public static void showUndoListCommand() { Undo.showHistoryList(); } public static void describeTechnologyCommand() { Technology tech = Technology.getCurrent(); System.out.println("Technology " + tech.getTechName()); System.out.println(" Full name: " + tech.getTechDesc()); if (tech.isScaleRelevant()) { System.out.println(" Scale: 1 grid unit is " + tech.getScale() + " nanometers (" + (tech.getScale()/1000) + " microns)"); } int arcCount = 0; for(Iterator it = tech.getArcs(); it.hasNext(); ) { ArcProto ap = (ArcProto)it.next(); if (!ap.isNotUsed()) arcCount++; } StringBuffer sb = new StringBuffer(); sb.append(" Has " + arcCount + " arcs (wires):"); for(Iterator it = tech.getArcs(); it.hasNext(); ) { ArcProto ap = (ArcProto)it.next(); if (ap.isNotUsed()) continue; sb.append(" " + ap.getName()); } System.out.println(sb.toString()); int pinCount = 0, totalCount = 0, pureCount = 0, contactCount = 0; for(Iterator it = tech.getNodes(); it.hasNext(); ) { PrimitiveNode np = (PrimitiveNode)it.next(); if (np.isNotUsed()) continue; PrimitiveNode.Function fun = np.getFunction(); totalCount++; if (fun == PrimitiveNode.Function.PIN) pinCount++; else if (fun == PrimitiveNode.Function.CONTACT || fun == PrimitiveNode.Function.CONNECT) contactCount++; else if (fun == PrimitiveNode.Function.NODE) pureCount++; } if (pinCount > 0) { sb = new StringBuffer(); sb.append(" Has " + pinCount + " pin nodes for making bends in arcs:"); for(Iterator it = tech.getNodes(); it.hasNext(); ) { PrimitiveNode np = (PrimitiveNode)it.next(); if (np.isNotUsed()) continue; PrimitiveNode.Function fun = np.getFunction(); if (fun == PrimitiveNode.Function.PIN) sb.append(" " + np.getName()); } System.out.println(sb.toString()); } if (contactCount > 0) { sb = new StringBuffer(); sb.append(" Has " + contactCount + " contact nodes for joining different arcs:"); for(Iterator it = tech.getNodes(); it.hasNext(); ) { PrimitiveNode np = (PrimitiveNode)it.next(); if (np.isNotUsed()) continue; PrimitiveNode.Function fun = np.getFunction(); if (fun == PrimitiveNode.Function.CONTACT || fun == PrimitiveNode.Function.CONNECT) sb.append(" " + np.getName()); } System.out.println(sb.toString()); } if (pinCount+contactCount+pureCount < totalCount) { sb = new StringBuffer(); sb.append(" Has " + (totalCount-pinCount-contactCount-pureCount) + " regular nodes:"); for(Iterator it = tech.getNodes(); it.hasNext(); ) { PrimitiveNode np = (PrimitiveNode)it.next(); if (np.isNotUsed()) continue; PrimitiveNode.Function fun = np.getFunction(); if (fun != PrimitiveNode.Function.PIN && fun != PrimitiveNode.Function.CONTACT && fun != PrimitiveNode.Function.CONNECT && fun != PrimitiveNode.Function.NODE) sb.append(" " + np.getName()); } System.out.println(sb.toString()); } if (pureCount > 0) { sb = new StringBuffer(); sb.append(" Has " + pureCount + " pure-layer nodes for creating custom geometry:"); for(Iterator it = tech.getNodes(); it.hasNext(); ) { PrimitiveNode np = (PrimitiveNode)it.next(); if (np.isNotUsed()) continue; PrimitiveNode.Function fun = np.getFunction(); if (fun == PrimitiveNode.Function.NODE) sb.append(" " + np.getName()); } System.out.println(sb.toString()); } } }
true
true
protected static void addEditMenu(MenuBar menuBar) { MenuBar.MenuItem m; int buckyBit = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /****************************** THE EDIT MENU ******************************/ // mnemonic keys available: B JK Q W // still don't have mnemonic for "Repeat Last Action" MenuBar.Menu editMenu = MenuBar.makeMenu("_Edit"); menuBar.add(editMenu); editMenu.addMenuItem("Cu_t", KeyStroke.getKeyStroke('X', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.cut(); } }); editMenu.addMenuItem("Cop_y", KeyStroke.getKeyStroke('C', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.copy(); } }); editMenu.addMenuItem("_Paste", KeyStroke.getKeyStroke('V', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.paste(false); } }); editMenu.addMenuItem("Dup_licate", KeyStroke.getKeyStroke('M', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.duplicate(); } }); editMenu.addSeparator(); MenuBar.MenuItem undo = editMenu.addMenuItem("_Undo", KeyStroke.getKeyStroke('Z', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { undoCommand(); } }); Undo.addPropertyChangeListener(new MenuCommands.MenuEnabler(undo, Undo.propUndoEnabled)); undo.setEnabled(Undo.getUndoEnabled()); // TODO: figure out how to remove this property change listener for correct garbage collection MenuBar.MenuItem redo = editMenu.addMenuItem("Re_do", KeyStroke.getKeyStroke('Y', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { redoCommand(); } }); Undo.addPropertyChangeListener(new MenuCommands.MenuEnabler(redo, Undo.propRedoEnabled)); redo.setEnabled(Undo.getRedoEnabled()); // TODO: figure out how to remove this property change listener for correct garbage collection editMenu.addMenuItem("Repeat Last Action", KeyStroke.getKeyStroke(KeyEvent.VK_AMPERSAND, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { repeatLastCommand(); } }); editMenu.addSeparator(); // mnemonic keys available: AB EFGHIJKLMN PQRSTUV XYZ MenuBar.Menu rotateSubMenu = MenuBar.makeMenu("_Rotate"); editMenu.add(rotateSubMenu); rotateSubMenu.addMenuItem("90 Degrees Clock_wise", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(2700); }}); rotateSubMenu.addMenuItem("90 Degrees _Counterclockwise", KeyStroke.getKeyStroke('J', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(900); }}); rotateSubMenu.addMenuItem("180 _Degrees", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(1800); }}); rotateSubMenu.addMenuItem("_Other...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(0); }}); // mnemonic keys available: ABCDEFGHIJK MNOPQRST VWXYZ MenuBar.Menu mirrorSubMenu = MenuBar.makeMenu("_Mirror"); editMenu.add(mirrorSubMenu); mirrorSubMenu.addMenuItem("_Up <-> Down", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(true); }}); mirrorSubMenu.addMenuItem("_Left <-> Right", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(false); }}); // mnemonic keys available: BCDEFGH JKLM OPQRSTUVWXYZ MenuBar.Menu sizeSubMenu = MenuBar.makeMenu("Si_ze"); editMenu.add(sizeSubMenu); sizeSubMenu.addMenuItem("_Interactively", KeyStroke.getKeyStroke('B', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeObjects(); } }); sizeSubMenu.addMenuItem("All Selected _Nodes...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllNodes(); }}); sizeSubMenu.addMenuItem("All Selected _Arcs...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllArcs(); }}); // mnemonic keys available: DEFGHIJK NOPQ U WXYZ MenuBar.Menu moveSubMenu = MenuBar.makeMenu("Mo_ve"); editMenu.add(moveSubMenu); moveSubMenu.addMenuItem("_Spread...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Spread.showSpreadDialog(); }}); moveSubMenu.addMenuItem("_Move Objects By...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { MoveBy.showMoveByDialog(); }}); moveSubMenu.addMenuItem("_Align to Grid", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignToGrid(); }}); moveSubMenu.addSeparator(); moveSubMenu.addMenuItem("Align Horizontally to _Left", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 0); }}); moveSubMenu.addMenuItem("Align Horizontally to _Right", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 1); }}); moveSubMenu.addMenuItem("Align Horizontally to _Center", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 2); }}); moveSubMenu.addSeparator(); moveSubMenu.addMenuItem("Align Vertically to _Top", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 0); }}); moveSubMenu.addMenuItem("Align Vertically to _Bottom", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 1); }}); moveSubMenu.addMenuItem("Align _Vertically to Center", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 2); }}); editMenu.addSeparator(); m=editMenu.addMenuItem("_Erase", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelected(); } }); menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), null); editMenu.addMenuItem("_Array...", KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { Array.showArrayDialog(); } }); editMenu.addMenuItem("C_hange...", KeyStroke.getKeyStroke('C', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { Change.showChangeDialog(); } }); editMenu.addSeparator(); // mnemonic keys available: ABCDEFGHIJKLMNOPQRS VWXYZ MenuBar.Menu editInfoSubMenu = MenuBar.makeMenu("In_fo"); editMenu.add(editInfoSubMenu); // editInfoSubMenu.addMenuItem("List Layer Coverage", null, // new ActionListener() { public void actionPerformed(ActionEvent e) { LayerCoverageJob.layerCoverageCommand(Job.Type.EXAMINE, LayerCoverageJob.AREA, GeometryHandler.ALGO_SWEEP); } }); editInfoSubMenu.addMenuItem("Show _Undo List", null, new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); } }); // mnemonic keys available: BC EFG IJK M PQR TUVWXYZ MenuBar.Menu editPropertiesSubMenu = MenuBar.makeMenu("Propert_ies"); editMenu.add(editPropertiesSubMenu); editPropertiesSubMenu.addMenuItem("_Object Properties...", KeyStroke.getKeyStroke('I', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { getInfoCommand(false); } }); editPropertiesSubMenu.addMenuItem("_Attribute Properties...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Attributes.showDialog(); } }); editPropertiesSubMenu.addSeparator(); editPropertiesSubMenu.addMenuItem("_See All Attributes on Node", null, new ActionListener() { public void actionPerformed(ActionEvent e) { seeAllParametersCommand(); } }); editPropertiesSubMenu.addMenuItem("_Hide All Attributes on Node", null, new ActionListener() { public void actionPerformed(ActionEvent e) { hideAllParametersCommand(); } }); editPropertiesSubMenu.addMenuItem("_Default Attribute Visibility", null, new ActionListener() { public void actionPerformed(ActionEvent e) { defaultParamVisibilityCommand(); } }); editPropertiesSubMenu.addMenuItem("Update Attributes Inheritance on _Node", null, new ActionListener() { public void actionPerformed(ActionEvent e) { updateInheritance(false); } }); editPropertiesSubMenu.addMenuItem("Update Attributes Inheritance all _Libraries", null, new ActionListener() { public void actionPerformed(ActionEvent e) { updateInheritance(true); } }); // mnemonic keys available: E G I KL OPQ S VWXYZ MenuBar.Menu arcSubMenu = MenuBar.makeMenu("Ar_c"); editMenu.add(arcSubMenu); arcSubMenu.addMenuItem("_Rigid", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcRigidCommand(); }}); arcSubMenu.addMenuItem("_Not Rigid", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotRigidCommand(); }}); arcSubMenu.addMenuItem("_Fixed Angle", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcFixedAngleCommand(); }}); arcSubMenu.addMenuItem("Not Fixed _Angle", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotFixedAngleCommand(); }}); arcSubMenu.addSeparator(); arcSubMenu.addMenuItem("Toggle _Directionality", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcDirectionalCommand(); }}); arcSubMenu.addMenuItem("Toggle End Extension of _Head", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcHeadExtendCommand(); }}); arcSubMenu.addMenuItem("Toggle End Extension of _Tail", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcTailExtendCommand(); }}); arcSubMenu.addSeparator(); arcSubMenu.addMenuItem("Insert _Jog In Arc", null, new ActionListener() { public void actionPerformed(ActionEvent e) { insertJogInArcCommand(); } }); arcSubMenu.addMenuItem("Rip _Bus", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.ripBus(); }}); arcSubMenu.addSeparator(); arcSubMenu.addMenuItem("_Curve through Cursor", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CurveListener.setCurvature(true); } }); arcSubMenu.addMenuItem("Curve abo_ut Cursor", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CurveListener.setCurvature(false); }}); arcSubMenu.addMenuItem("Re_move Curvature", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CurveListener.removeCurvature(); }}); // mnemonic keys available: ABCD FGHIJKL NOPQR TUVWXYZ MenuBar.Menu modeSubMenu = MenuBar.makeMenu("M_odes"); editMenu.add(modeSubMenu); // mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ MenuBar.Menu modeSubMenuEdit = MenuBar.makeMenu("_Edit"); modeSubMenu.add(modeSubMenuEdit); ButtonGroup editGroup = new ButtonGroup(); JMenuItem cursorClickZoomWire, cursorPan, cursorZoom, cursorOutline, cursorMeasure; cursorClickZoomWire = modeSubMenuEdit.addRadioButton(ToolBar.cursorClickZoomWireName, true, editGroup, KeyStroke.getKeyStroke('S', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.clickZoomWireCommand(); } }); ToolBar.CursorMode cm = ToolBar.getCursorMode(); if (cm == ToolBar.CursorMode.CLICKZOOMWIRE) cursorClickZoomWire.setSelected(true); cursorPan = modeSubMenuEdit.addRadioButton(ToolBar.cursorPanName, false, editGroup, KeyStroke.getKeyStroke('P', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.panCommand(); } }); cursorZoom = modeSubMenuEdit.addRadioButton(ToolBar.cursorZoomName, false, editGroup, KeyStroke.getKeyStroke('Z', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.zoomCommand(); } }); cursorOutline = modeSubMenuEdit.addRadioButton(ToolBar.cursorOutlineName, false, editGroup, KeyStroke.getKeyStroke('Y', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.outlineEditCommand(); } }); cursorMeasure = modeSubMenuEdit.addRadioButton(ToolBar.cursorMeasureName, false, editGroup, KeyStroke.getKeyStroke('M', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.measureCommand(); } }); if (cm == ToolBar.CursorMode.PAN) cursorPan.setSelected(true); if (cm == ToolBar.CursorMode.ZOOM) cursorZoom.setSelected(true); if (cm == ToolBar.CursorMode.OUTLINE) cursorOutline.setSelected(true); if (cm == ToolBar.CursorMode.MEASURE) cursorMeasure.setSelected(true); // mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ MenuBar.Menu modeSubMenuMovement = MenuBar.makeMenu("_Movement"); modeSubMenu.add(modeSubMenuMovement); ButtonGroup movementGroup = new ButtonGroup(); moveFull = modeSubMenuMovement.addRadioButton(ToolBar.moveFullName, true, movementGroup, KeyStroke.getKeyStroke('F', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.arrowDistanceCommand(ToolBar.ArrowDistance.FULL); } }); moveHalf = modeSubMenuMovement.addRadioButton(ToolBar.moveHalfName, false, movementGroup, KeyStroke.getKeyStroke('H', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.arrowDistanceCommand(ToolBar.ArrowDistance.HALF); } }); moveQuarter = modeSubMenuMovement.addRadioButton(ToolBar.moveQuarterName, false, movementGroup, null, // do not put shortcut in here! Too dangerous!! new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.arrowDistanceCommand(ToolBar.ArrowDistance.QUARTER); } }); setGridAligment(User.getAlignmentToGrid()); // mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ MenuBar.Menu modeSubMenuSelect = MenuBar.makeMenu("_Select"); modeSubMenu.add(modeSubMenuSelect); ButtonGroup selectGroup = new ButtonGroup(); JMenuItem selectArea, selectObjects; selectArea = modeSubMenuSelect.addRadioButton(ToolBar.selectAreaName, true, selectGroup, null, new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectAreaCommand(); } }); selectObjects = modeSubMenuSelect.addRadioButton(ToolBar.selectObjectsName, false, selectGroup, null, new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectObjectsCommand(); } }); ToolBar.SelectMode sm = ToolBar.getSelectMode(); if (sm == ToolBar.SelectMode.AREA) selectArea.setSelected(true); else selectObjects.setSelected(true); modeSubMenuSelect.addCheckBox(ToolBar.specialSelectName, false, null, new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.toggleSelectSpecialCommand(e); } }); // mnemonic keys available: AB E GH JKLMNOPQRSTUVWXYZ MenuBar.Menu textSubMenu = MenuBar.makeMenu("Te_xt"); editMenu.add(textSubMenu); textSubMenu.addMenuItem("_Find Text...", KeyStroke.getKeyStroke('L', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { FindText.findTextDialog(); }}); textSubMenu.addMenuItem("_Change Text Size...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { ChangeText.changeTextDialog(); }}); textSubMenu.addMenuItem("_Increase All Text Size", KeyStroke.getKeyStroke('=', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { changeGlobalTextSize(1.25); }}); textSubMenu.addMenuItem("_Decrease All Text Size", KeyStroke.getKeyStroke('-', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { changeGlobalTextSize(0.8); }}); // mnemonic keys available: ABCD FGHIJK M O QR TUVWXYZ MenuBar.Menu cleanupSubMenu = MenuBar.makeMenu("Clea_nup Cell"); editMenu.add(cleanupSubMenu); cleanupSubMenu.addMenuItem("Cleanup _Pins", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(false); }}); cleanupSubMenu.addMenuItem("Cleanup Pins _Everywhere", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(true); }}); cleanupSubMenu.addMenuItem("Show _Nonmanhattan", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showNonmanhattanCommand(); }}); cleanupSubMenu.addMenuItem("Show Pure _Layer Nodes", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showPureLayerCommand(); }}); cleanupSubMenu.addMenuItem("_Shorten Selected Arcs", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.shortenArcsCommand(); }}); // mnemonic keys available: GH JK O QRS UVWXYZ MenuBar.Menu specialSubMenu = MenuBar.makeMenu("Technolo_gy Specific"); editMenu.add(specialSubMenu); specialSubMenu.addMenuItem("Toggle Port _Negation", KeyStroke.getKeyStroke('T', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.toggleNegatedCommand(); }}); specialSubMenu.addMenuItem("_Artwork Appearance...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { ArtworkLook.showArtworkLookDialog(); }}); specialSubMenu.addSeparator(); // mnemonic keys available: B DEFG IJKLM O Q TUV XYZ MenuBar.Menu fpgaSubMenu = MenuBar.makeMenu("_FPGA"); specialSubMenu.add(fpgaSubMenu); fpgaSubMenu.addMenuItem("Read _Architecture And Primitives...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.readArchitectureFile(true); }}); fpgaSubMenu.addMenuItem("Read P_rimitives...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.readArchitectureFile(false); }}); fpgaSubMenu.addSeparator(); fpgaSubMenu.addMenuItem("Edit _Pips...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.programPips(); }}); fpgaSubMenu.addSeparator(); fpgaSubMenu.addMenuItem("Show _No Wires", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setWireDisplay(0); }}); fpgaSubMenu.addMenuItem("Show A_ctive Wires", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setWireDisplay(1); }}); fpgaSubMenu.addMenuItem("Show All _Wires", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setWireDisplay(2); }}); fpgaSubMenu.addSeparator(); fpgaSubMenu.addMenuItem("_Show Text", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setTextDisplay(true); }}); fpgaSubMenu.addMenuItem("_Hide Text", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setTextDisplay(false); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Convert Technology to _Library for Editing...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { TechToLib.makeLibFromTech(); }}); specialSubMenu.addMenuItem("Convert Library to _Technology...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { LibToTech.makeTechFromLib(); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("_Identify Primitive Layers", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.identifyLayers(false); }}); specialSubMenu.addMenuItem("Identify _Ports", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.identifyLayers(true); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Edit Library _Dependencies...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.editLibraryDependencies(); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Descri_be this Technology", null, new ActionListener() { public void actionPerformed(ActionEvent e) { describeTechnologyCommand(); } }); specialSubMenu.addMenuItem("Do_cument Current Technology", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.describeTechnology(Technology.getCurrent()); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Rena_me Current Technology...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.renameCurrentTechnology(); } }); // specialSubMenu.addMenuItem("D_elete Current Technology", null, // new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteCurrentTechnology(); } }); // mnemonic keys available: B F I KLM PQ Z MenuBar.Menu selListSubMenu = MenuBar.makeMenu("_Selection"); editMenu.add(selListSubMenu); selListSubMenu.addMenuItem("Sele_ct All", KeyStroke.getKeyStroke('A', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllCommand(); }}); selListSubMenu.addMenuItem("Select All Like _This", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLikeThisCommand(); }}); selListSubMenu.addMenuItem("Select All _Easy", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectEasyCommand(); }}); selListSubMenu.addMenuItem("Select All _Hard", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectHardCommand(); }}); selListSubMenu.addMenuItem("Select Nothin_g", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectNothingCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("_Select Object...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { SelectObject.selectObjectDialog(); }}); selListSubMenu.addMenuItem("Deselect All _Arcs", null, new ActionListener() { public void actionPerformed(ActionEvent e) { deselectAllArcsCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Make Selected Eas_y", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }}); selListSubMenu.addMenuItem("Make Selected Har_d", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeHardCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("P_ush Selection", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EditWindow wnd = EditWindow.getCurrent(); if (wnd == null) return; wnd.getHighlighter().pushHighlight(); }}); selListSubMenu.addMenuItem("P_op Selection", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EditWindow wnd = EditWindow.getCurrent(); if (wnd ==null) return; wnd.getHighlighter().popHighlight(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Enclosed Ob_jects", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectEnclosedObjectsCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Show Ne_xt Error", KeyStroke.getKeyStroke('>'), new ActionListener() { public void actionPerformed(ActionEvent e) { showNextErrorCommand(); }}); selListSubMenu.addMenuItem("Show Pre_vious Error", KeyStroke.getKeyStroke('<'), new ActionListener() { public void actionPerformed(ActionEvent e) { showPrevErrorCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Add to Waveform in _New Panel", KeyStroke.getKeyStroke('A', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { addToWaveformNewCommand(); }}); selListSubMenu.addMenuItem("Add to _Waveform in Current Panel", KeyStroke.getKeyStroke('O', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { addToWaveformCurrentCommand(); }}); selListSubMenu.addMenuItem("_Remove from _Waveform", KeyStroke.getKeyStroke('R', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { removeFromWaveformCommand(); }}); }
protected static void addEditMenu(MenuBar menuBar) { MenuBar.MenuItem m; int buckyBit = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /****************************** THE EDIT MENU ******************************/ // mnemonic keys available: B JK Q W // still don't have mnemonic for "Repeat Last Action" MenuBar.Menu editMenu = MenuBar.makeMenu("_Edit"); menuBar.add(editMenu); editMenu.addMenuItem("Cu_t", KeyStroke.getKeyStroke('X', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.cut(); } }); editMenu.addMenuItem("Cop_y", KeyStroke.getKeyStroke('C', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.copy(); } }); editMenu.addMenuItem("_Paste", KeyStroke.getKeyStroke('V', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.paste(false); } }); editMenu.addMenuItem("Dup_licate", KeyStroke.getKeyStroke('M', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.duplicate(); } }); editMenu.addSeparator(); MenuBar.MenuItem undo = editMenu.addMenuItem("_Undo", KeyStroke.getKeyStroke('Z', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { undoCommand(); } }); Undo.addPropertyChangeListener(new MenuCommands.MenuEnabler(undo, Undo.propUndoEnabled)); undo.setEnabled(Undo.getUndoEnabled()); // TODO: figure out how to remove this property change listener for correct garbage collection MenuBar.MenuItem redo = editMenu.addMenuItem("Re_do", KeyStroke.getKeyStroke('Y', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { redoCommand(); } }); Undo.addPropertyChangeListener(new MenuCommands.MenuEnabler(redo, Undo.propRedoEnabled)); redo.setEnabled(Undo.getRedoEnabled()); // TODO: figure out how to remove this property change listener for correct garbage collection editMenu.addMenuItem("Repeat Last Action", KeyStroke.getKeyStroke(KeyEvent.VK_AMPERSAND, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { repeatLastCommand(); } }); editMenu.addSeparator(); // mnemonic keys available: AB EFGHIJKLMN PQRSTUV XYZ MenuBar.Menu rotateSubMenu = MenuBar.makeMenu("_Rotate"); editMenu.add(rotateSubMenu); rotateSubMenu.addMenuItem("90 Degrees Clock_wise", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(2700); }}); rotateSubMenu.addMenuItem("90 Degrees _Counterclockwise", KeyStroke.getKeyStroke('J', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(900); }}); rotateSubMenu.addMenuItem("180 _Degrees", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(1800); }}); rotateSubMenu.addMenuItem("_Other...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(0); }}); // mnemonic keys available: ABCDEFGHIJK MNOPQRST VWXYZ MenuBar.Menu mirrorSubMenu = MenuBar.makeMenu("_Mirror"); editMenu.add(mirrorSubMenu); mirrorSubMenu.addMenuItem("_Up <-> Down", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(true); }}); mirrorSubMenu.addMenuItem("_Left <-> Right", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(false); }}); // mnemonic keys available: BCDEFGH JKLM OPQRSTUVWXYZ MenuBar.Menu sizeSubMenu = MenuBar.makeMenu("Si_ze"); editMenu.add(sizeSubMenu); sizeSubMenu.addMenuItem("_Interactively", KeyStroke.getKeyStroke('B', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeObjects(); } }); sizeSubMenu.addMenuItem("All Selected _Nodes...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllNodes(); }}); sizeSubMenu.addMenuItem("All Selected _Arcs...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllArcs(); }}); // mnemonic keys available: DEFGHIJK NOPQ U WXYZ MenuBar.Menu moveSubMenu = MenuBar.makeMenu("Mo_ve"); editMenu.add(moveSubMenu); moveSubMenu.addMenuItem("_Spread...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Spread.showSpreadDialog(); }}); moveSubMenu.addMenuItem("_Move Objects By...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { MoveBy.showMoveByDialog(); }}); moveSubMenu.addMenuItem("_Align to Grid", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignToGrid(); }}); moveSubMenu.addSeparator(); moveSubMenu.addMenuItem("Align Horizontally to _Left", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 0); }}); moveSubMenu.addMenuItem("Align Horizontally to _Right", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 1); }}); moveSubMenu.addMenuItem("Align Horizontally to _Center", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 2); }}); moveSubMenu.addSeparator(); moveSubMenu.addMenuItem("Align Vertically to _Top", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 0); }}); moveSubMenu.addMenuItem("Align Vertically to _Bottom", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 1); }}); moveSubMenu.addMenuItem("Align _Vertically to Center", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 2); }}); editMenu.addSeparator(); m=editMenu.addMenuItem("_Erase", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelected(); } }); menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), null); editMenu.addMenuItem("_Array...", KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { Array.showArrayDialog(); } }); editMenu.addMenuItem("C_hange...", KeyStroke.getKeyStroke('C', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { Change.showChangeDialog(); } }); editMenu.addSeparator(); // mnemonic keys available: ABCDEFGHIJKLMNOPQRS VWXYZ MenuBar.Menu editInfoSubMenu = MenuBar.makeMenu("In_fo"); editMenu.add(editInfoSubMenu); // editInfoSubMenu.addMenuItem("List Layer Coverage", null, // new ActionListener() { public void actionPerformed(ActionEvent e) { LayerCoverageJob.layerCoverageCommand(Job.Type.EXAMINE, LayerCoverageJob.AREA, GeometryHandler.ALGO_SWEEP); } }); editInfoSubMenu.addMenuItem("Show _Undo List", null, new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); } }); // mnemonic keys available: BC EFG IJK M PQR TUVWXYZ MenuBar.Menu editPropertiesSubMenu = MenuBar.makeMenu("Propert_ies"); editMenu.add(editPropertiesSubMenu); editPropertiesSubMenu.addMenuItem("_Object Properties...", KeyStroke.getKeyStroke('I', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { getInfoCommand(false); } }); editPropertiesSubMenu.addMenuItem("_Attribute Properties...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Attributes.showDialog(); } }); editPropertiesSubMenu.addSeparator(); editPropertiesSubMenu.addMenuItem("_See All Attributes on Node", null, new ActionListener() { public void actionPerformed(ActionEvent e) { seeAllParametersCommand(); } }); editPropertiesSubMenu.addMenuItem("_Hide All Attributes on Node", null, new ActionListener() { public void actionPerformed(ActionEvent e) { hideAllParametersCommand(); } }); editPropertiesSubMenu.addMenuItem("_Default Attribute Visibility", null, new ActionListener() { public void actionPerformed(ActionEvent e) { defaultParamVisibilityCommand(); } }); editPropertiesSubMenu.addMenuItem("Update Attributes Inheritance on _Node", null, new ActionListener() { public void actionPerformed(ActionEvent e) { updateInheritance(false); } }); editPropertiesSubMenu.addMenuItem("Update Attributes Inheritance all _Libraries", null, new ActionListener() { public void actionPerformed(ActionEvent e) { updateInheritance(true); } }); // mnemonic keys available: E G I KL OPQ S VWXYZ MenuBar.Menu arcSubMenu = MenuBar.makeMenu("Ar_c"); editMenu.add(arcSubMenu); arcSubMenu.addMenuItem("_Rigid", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcRigidCommand(); }}); arcSubMenu.addMenuItem("_Not Rigid", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotRigidCommand(); }}); arcSubMenu.addMenuItem("_Fixed Angle", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcFixedAngleCommand(); }}); arcSubMenu.addMenuItem("Not Fixed _Angle", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotFixedAngleCommand(); }}); arcSubMenu.addSeparator(); arcSubMenu.addMenuItem("Toggle _Directionality", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcDirectionalCommand(); }}); arcSubMenu.addMenuItem("Toggle End Extension of Both Head/Tail", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcHeadExtendCommand(); CircuitChanges.arcTailExtendCommand();}}); arcSubMenu.addMenuItem("Toggle End Extension of _Head", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcHeadExtendCommand(); }}); arcSubMenu.addMenuItem("Toggle End Extension of _Tail", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcTailExtendCommand(); }}); arcSubMenu.addSeparator(); arcSubMenu.addMenuItem("Insert _Jog In Arc", null, new ActionListener() { public void actionPerformed(ActionEvent e) { insertJogInArcCommand(); } }); arcSubMenu.addMenuItem("Rip _Bus", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.ripBus(); }}); arcSubMenu.addSeparator(); arcSubMenu.addMenuItem("_Curve through Cursor", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CurveListener.setCurvature(true); } }); arcSubMenu.addMenuItem("Curve abo_ut Cursor", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CurveListener.setCurvature(false); }}); arcSubMenu.addMenuItem("Re_move Curvature", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CurveListener.removeCurvature(); }}); // mnemonic keys available: ABCD FGHIJKL NOPQR TUVWXYZ MenuBar.Menu modeSubMenu = MenuBar.makeMenu("M_odes"); editMenu.add(modeSubMenu); // mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ MenuBar.Menu modeSubMenuEdit = MenuBar.makeMenu("_Edit"); modeSubMenu.add(modeSubMenuEdit); ButtonGroup editGroup = new ButtonGroup(); JMenuItem cursorClickZoomWire, cursorPan, cursorZoom, cursorOutline, cursorMeasure; cursorClickZoomWire = modeSubMenuEdit.addRadioButton(ToolBar.cursorClickZoomWireName, true, editGroup, KeyStroke.getKeyStroke('S', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.clickZoomWireCommand(); } }); ToolBar.CursorMode cm = ToolBar.getCursorMode(); if (cm == ToolBar.CursorMode.CLICKZOOMWIRE) cursorClickZoomWire.setSelected(true); cursorPan = modeSubMenuEdit.addRadioButton(ToolBar.cursorPanName, false, editGroup, KeyStroke.getKeyStroke('P', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.panCommand(); } }); cursorZoom = modeSubMenuEdit.addRadioButton(ToolBar.cursorZoomName, false, editGroup, KeyStroke.getKeyStroke('Z', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.zoomCommand(); } }); cursorOutline = modeSubMenuEdit.addRadioButton(ToolBar.cursorOutlineName, false, editGroup, KeyStroke.getKeyStroke('Y', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.outlineEditCommand(); } }); cursorMeasure = modeSubMenuEdit.addRadioButton(ToolBar.cursorMeasureName, false, editGroup, KeyStroke.getKeyStroke('M', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.measureCommand(); } }); if (cm == ToolBar.CursorMode.PAN) cursorPan.setSelected(true); if (cm == ToolBar.CursorMode.ZOOM) cursorZoom.setSelected(true); if (cm == ToolBar.CursorMode.OUTLINE) cursorOutline.setSelected(true); if (cm == ToolBar.CursorMode.MEASURE) cursorMeasure.setSelected(true); // mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ MenuBar.Menu modeSubMenuMovement = MenuBar.makeMenu("_Movement"); modeSubMenu.add(modeSubMenuMovement); ButtonGroup movementGroup = new ButtonGroup(); moveFull = modeSubMenuMovement.addRadioButton(ToolBar.moveFullName, true, movementGroup, KeyStroke.getKeyStroke('F', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.arrowDistanceCommand(ToolBar.ArrowDistance.FULL); } }); moveHalf = modeSubMenuMovement.addRadioButton(ToolBar.moveHalfName, false, movementGroup, KeyStroke.getKeyStroke('H', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.arrowDistanceCommand(ToolBar.ArrowDistance.HALF); } }); moveQuarter = modeSubMenuMovement.addRadioButton(ToolBar.moveQuarterName, false, movementGroup, null, // do not put shortcut in here! Too dangerous!! new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.arrowDistanceCommand(ToolBar.ArrowDistance.QUARTER); } }); setGridAligment(User.getAlignmentToGrid()); // mnemonic keys available: ABCDEFGHIJKLMNOPQRSTUVWXYZ MenuBar.Menu modeSubMenuSelect = MenuBar.makeMenu("_Select"); modeSubMenu.add(modeSubMenuSelect); ButtonGroup selectGroup = new ButtonGroup(); JMenuItem selectArea, selectObjects; selectArea = modeSubMenuSelect.addRadioButton(ToolBar.selectAreaName, true, selectGroup, null, new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectAreaCommand(); } }); selectObjects = modeSubMenuSelect.addRadioButton(ToolBar.selectObjectsName, false, selectGroup, null, new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectObjectsCommand(); } }); ToolBar.SelectMode sm = ToolBar.getSelectMode(); if (sm == ToolBar.SelectMode.AREA) selectArea.setSelected(true); else selectObjects.setSelected(true); modeSubMenuSelect.addCheckBox(ToolBar.specialSelectName, false, null, new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.toggleSelectSpecialCommand(e); } }); // mnemonic keys available: AB E GH JKLMNOPQRSTUVWXYZ MenuBar.Menu textSubMenu = MenuBar.makeMenu("Te_xt"); editMenu.add(textSubMenu); textSubMenu.addMenuItem("_Find Text...", KeyStroke.getKeyStroke('L', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { FindText.findTextDialog(); }}); textSubMenu.addMenuItem("_Change Text Size...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { ChangeText.changeTextDialog(); }}); textSubMenu.addMenuItem("_Increase All Text Size", KeyStroke.getKeyStroke('=', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { changeGlobalTextSize(1.25); }}); textSubMenu.addMenuItem("_Decrease All Text Size", KeyStroke.getKeyStroke('-', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { changeGlobalTextSize(0.8); }}); // mnemonic keys available: ABCD FGHIJK M O QR TUVWXYZ MenuBar.Menu cleanupSubMenu = MenuBar.makeMenu("Clea_nup Cell"); editMenu.add(cleanupSubMenu); cleanupSubMenu.addMenuItem("Cleanup _Pins", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(false); }}); cleanupSubMenu.addMenuItem("Cleanup Pins _Everywhere", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(true); }}); cleanupSubMenu.addMenuItem("Show _Nonmanhattan", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showNonmanhattanCommand(); }}); cleanupSubMenu.addMenuItem("Show Pure _Layer Nodes", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showPureLayerCommand(); }}); cleanupSubMenu.addMenuItem("_Shorten Selected Arcs", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.shortenArcsCommand(); }}); // mnemonic keys available: GH JK O QRS UVWXYZ MenuBar.Menu specialSubMenu = MenuBar.makeMenu("Technolo_gy Specific"); editMenu.add(specialSubMenu); specialSubMenu.addMenuItem("Toggle Port _Negation", KeyStroke.getKeyStroke('T', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.toggleNegatedCommand(); }}); specialSubMenu.addMenuItem("_Artwork Appearance...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { ArtworkLook.showArtworkLookDialog(); }}); specialSubMenu.addSeparator(); // mnemonic keys available: B DEFG IJKLM O Q TUV XYZ MenuBar.Menu fpgaSubMenu = MenuBar.makeMenu("_FPGA"); specialSubMenu.add(fpgaSubMenu); fpgaSubMenu.addMenuItem("Read _Architecture And Primitives...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.readArchitectureFile(true); }}); fpgaSubMenu.addMenuItem("Read P_rimitives...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.readArchitectureFile(false); }}); fpgaSubMenu.addSeparator(); fpgaSubMenu.addMenuItem("Edit _Pips...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.programPips(); }}); fpgaSubMenu.addSeparator(); fpgaSubMenu.addMenuItem("Show _No Wires", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setWireDisplay(0); }}); fpgaSubMenu.addMenuItem("Show A_ctive Wires", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setWireDisplay(1); }}); fpgaSubMenu.addMenuItem("Show All _Wires", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setWireDisplay(2); }}); fpgaSubMenu.addSeparator(); fpgaSubMenu.addMenuItem("_Show Text", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setTextDisplay(true); }}); fpgaSubMenu.addMenuItem("_Hide Text", null, new ActionListener() { public void actionPerformed(ActionEvent e) { FPGA.setTextDisplay(false); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Convert Technology to _Library for Editing...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { TechToLib.makeLibFromTech(); }}); specialSubMenu.addMenuItem("Convert Library to _Technology...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { LibToTech.makeTechFromLib(); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("_Identify Primitive Layers", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.identifyLayers(false); }}); specialSubMenu.addMenuItem("Identify _Ports", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.identifyLayers(true); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Edit Library _Dependencies...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.editLibraryDependencies(); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Descri_be this Technology", null, new ActionListener() { public void actionPerformed(ActionEvent e) { describeTechnologyCommand(); } }); specialSubMenu.addMenuItem("Do_cument Current Technology", null, new ActionListener() { public void actionPerformed(ActionEvent e) { Manipulate.describeTechnology(Technology.getCurrent()); }}); specialSubMenu.addSeparator(); specialSubMenu.addMenuItem("Rena_me Current Technology...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.renameCurrentTechnology(); } }); // specialSubMenu.addMenuItem("D_elete Current Technology", null, // new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteCurrentTechnology(); } }); // mnemonic keys available: B F I KLM PQ Z MenuBar.Menu selListSubMenu = MenuBar.makeMenu("_Selection"); editMenu.add(selListSubMenu); selListSubMenu.addMenuItem("Sele_ct All", KeyStroke.getKeyStroke('A', buckyBit), new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllCommand(); }}); selListSubMenu.addMenuItem("Select All Like _This", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLikeThisCommand(); }}); selListSubMenu.addMenuItem("Select All _Easy", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectEasyCommand(); }}); selListSubMenu.addMenuItem("Select All _Hard", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectHardCommand(); }}); selListSubMenu.addMenuItem("Select Nothin_g", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectNothingCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("_Select Object...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { SelectObject.selectObjectDialog(); }}); selListSubMenu.addMenuItem("Deselect All _Arcs", null, new ActionListener() { public void actionPerformed(ActionEvent e) { deselectAllArcsCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Make Selected Eas_y", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }}); selListSubMenu.addMenuItem("Make Selected Har_d", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeHardCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("P_ush Selection", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EditWindow wnd = EditWindow.getCurrent(); if (wnd == null) return; wnd.getHighlighter().pushHighlight(); }}); selListSubMenu.addMenuItem("P_op Selection", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EditWindow wnd = EditWindow.getCurrent(); if (wnd ==null) return; wnd.getHighlighter().popHighlight(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Enclosed Ob_jects", null, new ActionListener() { public void actionPerformed(ActionEvent e) { selectEnclosedObjectsCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Show Ne_xt Error", KeyStroke.getKeyStroke('>'), new ActionListener() { public void actionPerformed(ActionEvent e) { showNextErrorCommand(); }}); selListSubMenu.addMenuItem("Show Pre_vious Error", KeyStroke.getKeyStroke('<'), new ActionListener() { public void actionPerformed(ActionEvent e) { showPrevErrorCommand(); }}); selListSubMenu.addSeparator(); selListSubMenu.addMenuItem("Add to Waveform in _New Panel", KeyStroke.getKeyStroke('A', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { addToWaveformNewCommand(); }}); selListSubMenu.addMenuItem("Add to _Waveform in Current Panel", KeyStroke.getKeyStroke('O', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { addToWaveformCurrentCommand(); }}); selListSubMenu.addMenuItem("_Remove from _Waveform", KeyStroke.getKeyStroke('R', 0), new ActionListener() { public void actionPerformed(ActionEvent e) { removeFromWaveformCommand(); }}); }
diff --git a/mc-src/net/minecraft/src/MAtDataGatherer.java b/mc-src/net/minecraft/src/MAtDataGatherer.java index 490032e..f689e03 100644 --- a/mc-src/net/minecraft/src/MAtDataGatherer.java +++ b/mc-src/net/minecraft/src/MAtDataGatherer.java @@ -1,213 +1,213 @@ package net.minecraft.src; import java.util.ArrayList; import java.util.List; import eu.ha3.matmos.engine.MAtmosData; /* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2004 Sam Hocevar <[email protected]> Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO. */ public class MAtDataGatherer { final static String INSTANTS = "Instants"; final static String DELTAS = "Deltas"; final static String LARGESCAN = "LargeScan"; final static String SMALLSCAN = "SmallScan"; final static String LARGESCAN_THOUSAND = "LargeScanPerMil"; final static String SMALLSCAN_THOUSAND = "SmallScanPerMil"; final static String SPECIAL_LARGE = "SpecialLarge"; final static String SPECIAL_SMALL = "SpecialSmall"; final static String CONTACTSCAN = "ContactScan"; final static String CONFIGVARS = "ConfigVars"; final static int COUNT_WORLD_BLOCKS = 4096; final static int COUNT_INSTANTS = 256; final static int COUNT_CONFIGVARS = 256; final static int MAX_LARGESCAN_PASS = 10; private MAtMod mod; private MAtScanVolumetricModel largeScanner; private MAtScanVolumetricModel smallScanner; private MAtScanCoordsPipeline largePipeline; private MAtScanCoordsPipeline smallPipeline; private MAtProcessorModel relaxedProcessor; private MAtProcessorModel frequentProcessor; private MAtProcessorModel contactProcessor; private MAtProcessorModel configVarsProcessor; private List<MAtProcessorModel> additionalRelaxedProcessors; private List<MAtProcessorModel> additionalFrequentProcessors; private MAtmosData data; private int cyclicTick; private long lastLargeScanX; private long lastLargeScanY; private long lastLargeScanZ; private int lastLargeScanPassed; MAtDataGatherer(MAtMod mAtmosHaddon) { this.mod = mAtmosHaddon; } void resetRegulators() { this.lastLargeScanPassed = MAX_LARGESCAN_PASS; this.cyclicTick = 0; } void load() { resetRegulators(); this.largeScanner = new MAtScanVolumetricModel(this.mod); this.smallScanner = new MAtScanVolumetricModel(this.mod); this.additionalRelaxedProcessors = new ArrayList<MAtProcessorModel>(); this.additionalFrequentProcessors = new ArrayList<MAtProcessorModel>(); this.data = new MAtmosData(); prepareSheets(); this.largePipeline = new MAtPipelineIDAccumulator(this.mod, this.data, LARGESCAN, LARGESCAN_THOUSAND, 1000); this.smallPipeline = new MAtPipelineIDAccumulator(this.mod, this.data, SMALLSCAN, SMALLSCAN_THOUSAND, 1000); this.largeScanner.setPipeline(this.largePipeline); this.smallScanner.setPipeline(this.smallPipeline); this.relaxedProcessor = new MAtProcessorRelaxed(this.mod, this.data, INSTANTS, DELTAS); this.frequentProcessor = new MAtProcessorFrequent(this.mod, this.data, INSTANTS, DELTAS); this.contactProcessor = new MAtProcessorContact(this.mod, this.data, CONTACTSCAN, null); this.configVarsProcessor = new MAtProcessorConfig(this.mod, this.data, CONFIGVARS, null); } public MAtmosData getData() { return this.data; } void tickRoutine() { if (this.cyclicTick % 64 == 0) { EntityPlayer player = this.mod.manager().getMinecraft().thePlayer; long x = (long) Math.floor(player.posX); long y = (long) Math.floor(player.posY); long z = (long) Math.floor(player.posZ); - if (this.cyclicTick == 0) + if (this.cyclicTick % 256 == 0) { if (this.lastLargeScanPassed >= MAX_LARGESCAN_PASS || Math.abs(x - this.lastLargeScanX) > 16 || Math.abs(y - this.lastLargeScanY) > 8 || Math.abs(z - this.lastLargeScanZ) > 16) { this.lastLargeScanX = x; this.lastLargeScanY = y; this.lastLargeScanZ = z; this.lastLargeScanPassed = 0; this.largeScanner.startScan(x, y, z, 64, 32, 64, 8192, null); } else { this.lastLargeScanPassed++; } } this.smallScanner.startScan(x, y, z, 16, 8, 16, 2048, null); this.relaxedProcessor.process(); for (MAtProcessorModel processor : this.additionalRelaxedProcessors) { processor.process(); } this.data.flagUpdate(); } //if (this.cyclicTick % 1 == 0) // XXX if (true) { this.contactProcessor.process(); this.frequentProcessor.process(); for (MAtProcessorModel processor : this.additionalFrequentProcessors) { processor.process(); } this.data.flagUpdate(); } if (this.cyclicTick % 2048 == 0) { this.configVarsProcessor.process(); } this.largeScanner.routine(); this.smallScanner.routine(); //this.cyclicTick = (this.cyclicTick + 1) % 256; this.cyclicTick = this.cyclicTick + 1; } void prepareSheets() { createSheet(LARGESCAN, COUNT_WORLD_BLOCKS); createSheet(LARGESCAN_THOUSAND, COUNT_WORLD_BLOCKS); createSheet(SMALLSCAN, COUNT_WORLD_BLOCKS); createSheet(SMALLSCAN_THOUSAND, COUNT_WORLD_BLOCKS); createSheet(CONTACTSCAN, COUNT_WORLD_BLOCKS); createSheet(INSTANTS, COUNT_INSTANTS); createSheet(DELTAS, COUNT_INSTANTS); createSheet(SPECIAL_LARGE, 2); createSheet(SPECIAL_SMALL, 1); createSheet(CONFIGVARS, COUNT_CONFIGVARS); } void createSheet(String name, int count) { ArrayList<Integer> array = new ArrayList<Integer>(); this.data.sheets.put(name, array); for (int i = 0; i < count; i++) { array.add(0); } } }
true
true
void tickRoutine() { if (this.cyclicTick % 64 == 0) { EntityPlayer player = this.mod.manager().getMinecraft().thePlayer; long x = (long) Math.floor(player.posX); long y = (long) Math.floor(player.posY); long z = (long) Math.floor(player.posZ); if (this.cyclicTick == 0) { if (this.lastLargeScanPassed >= MAX_LARGESCAN_PASS || Math.abs(x - this.lastLargeScanX) > 16 || Math.abs(y - this.lastLargeScanY) > 8 || Math.abs(z - this.lastLargeScanZ) > 16) { this.lastLargeScanX = x; this.lastLargeScanY = y; this.lastLargeScanZ = z; this.lastLargeScanPassed = 0; this.largeScanner.startScan(x, y, z, 64, 32, 64, 8192, null); } else { this.lastLargeScanPassed++; } } this.smallScanner.startScan(x, y, z, 16, 8, 16, 2048, null); this.relaxedProcessor.process(); for (MAtProcessorModel processor : this.additionalRelaxedProcessors) { processor.process(); } this.data.flagUpdate(); } //if (this.cyclicTick % 1 == 0) // XXX if (true) { this.contactProcessor.process(); this.frequentProcessor.process(); for (MAtProcessorModel processor : this.additionalFrequentProcessors) { processor.process(); } this.data.flagUpdate(); } if (this.cyclicTick % 2048 == 0) { this.configVarsProcessor.process(); } this.largeScanner.routine(); this.smallScanner.routine(); //this.cyclicTick = (this.cyclicTick + 1) % 256; this.cyclicTick = this.cyclicTick + 1; }
void tickRoutine() { if (this.cyclicTick % 64 == 0) { EntityPlayer player = this.mod.manager().getMinecraft().thePlayer; long x = (long) Math.floor(player.posX); long y = (long) Math.floor(player.posY); long z = (long) Math.floor(player.posZ); if (this.cyclicTick % 256 == 0) { if (this.lastLargeScanPassed >= MAX_LARGESCAN_PASS || Math.abs(x - this.lastLargeScanX) > 16 || Math.abs(y - this.lastLargeScanY) > 8 || Math.abs(z - this.lastLargeScanZ) > 16) { this.lastLargeScanX = x; this.lastLargeScanY = y; this.lastLargeScanZ = z; this.lastLargeScanPassed = 0; this.largeScanner.startScan(x, y, z, 64, 32, 64, 8192, null); } else { this.lastLargeScanPassed++; } } this.smallScanner.startScan(x, y, z, 16, 8, 16, 2048, null); this.relaxedProcessor.process(); for (MAtProcessorModel processor : this.additionalRelaxedProcessors) { processor.process(); } this.data.flagUpdate(); } //if (this.cyclicTick % 1 == 0) // XXX if (true) { this.contactProcessor.process(); this.frequentProcessor.process(); for (MAtProcessorModel processor : this.additionalFrequentProcessors) { processor.process(); } this.data.flagUpdate(); } if (this.cyclicTick % 2048 == 0) { this.configVarsProcessor.process(); } this.largeScanner.routine(); this.smallScanner.routine(); //this.cyclicTick = (this.cyclicTick + 1) % 256; this.cyclicTick = this.cyclicTick + 1; }
diff --git a/algebricks-core/src/main/java/edu/uci/ics/algebricks/compiler/algebra/operators/physical/HashPartitionMergeExchangePOperator.java b/algebricks-core/src/main/java/edu/uci/ics/algebricks/compiler/algebra/operators/physical/HashPartitionMergeExchangePOperator.java index 7f6480a..1bcc55f 100644 --- a/algebricks-core/src/main/java/edu/uci/ics/algebricks/compiler/algebra/operators/physical/HashPartitionMergeExchangePOperator.java +++ b/algebricks-core/src/main/java/edu/uci/ics/algebricks/compiler/algebra/operators/physical/HashPartitionMergeExchangePOperator.java @@ -1,160 +1,160 @@ /* * Copyright 2009-2010 by The Regents of the University of California * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * you may obtain a copy of the License from * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.algebricks.compiler.algebra.operators.physical; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import edu.uci.ics.algebricks.api.data.IBinaryComparatorFactoryProvider; import edu.uci.ics.algebricks.api.data.IBinaryHashFunctionFactoryProvider; import edu.uci.ics.algebricks.api.exceptions.AlgebricksException; import edu.uci.ics.algebricks.compiler.algebra.base.ILogicalOperator; import edu.uci.ics.algebricks.compiler.algebra.base.LogicalVariable; import edu.uci.ics.algebricks.compiler.algebra.base.PhysicalOperatorTag; import edu.uci.ics.algebricks.compiler.algebra.operators.logical.AbstractLogicalOperator; import edu.uci.ics.algebricks.compiler.algebra.operators.logical.IOperatorSchema; import edu.uci.ics.algebricks.compiler.algebra.operators.logical.OrderOperator.IOrder.OrderKind; import edu.uci.ics.algebricks.compiler.algebra.properties.ILocalStructuralProperty; import edu.uci.ics.algebricks.compiler.algebra.properties.INodeDomain; import edu.uci.ics.algebricks.compiler.algebra.properties.IPartitioningProperty; import edu.uci.ics.algebricks.compiler.algebra.properties.IPartitioningRequirementsCoordinator; import edu.uci.ics.algebricks.compiler.algebra.properties.IPhysicalPropertiesVector; import edu.uci.ics.algebricks.compiler.algebra.properties.LocalOrderProperty; import edu.uci.ics.algebricks.compiler.algebra.properties.OrderColumn; import edu.uci.ics.algebricks.compiler.algebra.properties.PhysicalRequirements; import edu.uci.ics.algebricks.compiler.algebra.properties.StructuralPropertiesVector; import edu.uci.ics.algebricks.compiler.algebra.properties.UnorderedPartitionedProperty; import edu.uci.ics.algebricks.compiler.algebra.properties.ILocalStructuralProperty.PropertyType; import edu.uci.ics.algebricks.compiler.optimizer.base.IOptimizationContext; import edu.uci.ics.algebricks.runtime.hyracks.jobgen.base.IHyracksJobBuilder.TargetConstraint; import edu.uci.ics.algebricks.runtime.hyracks.jobgen.impl.JobGenContext; import edu.uci.ics.algebricks.utils.Pair; import edu.uci.ics.hyracks.api.dataflow.IConnectorDescriptor; import edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparatorFactory; import edu.uci.ics.hyracks.api.dataflow.value.IBinaryHashFunctionFactory; import edu.uci.ics.hyracks.api.dataflow.value.ITuplePartitionComputerFactory; import edu.uci.ics.hyracks.api.job.JobSpecification; import edu.uci.ics.hyracks.dataflow.common.data.partition.FieldHashPartitionComputerFactory; import edu.uci.ics.hyracks.dataflow.std.connectors.MToNHashPartitioningMergingConnectorDescriptor; public class HashPartitionMergeExchangePOperator extends AbstractExchangePOperator { private List<OrderColumn> orderColumns; private List<LogicalVariable> partitionFields; private INodeDomain domain; public HashPartitionMergeExchangePOperator(List<OrderColumn> orderColumns, List<LogicalVariable> partitionFields, INodeDomain domain) { this.orderColumns = orderColumns; this.partitionFields = partitionFields; this.domain = domain; } @Override public PhysicalOperatorTag getOperatorTag() { return PhysicalOperatorTag.HASH_PARTITION_MERGE_EXCHANGE; } public List<OrderColumn> getOrderExpressions() { return orderColumns; } @Override public void computeDeliveredProperties(ILogicalOperator op, IOptimizationContext context) { IPartitioningProperty p = new UnorderedPartitionedProperty(new HashSet<LogicalVariable>(partitionFields), domain); AbstractLogicalOperator op2 = (AbstractLogicalOperator) op.getInputs().get(0).getOperator(); List<ILocalStructuralProperty> op2Locals = op2.getDeliveredPhysicalProperties().getLocalProperties(); List<ILocalStructuralProperty> locals = new ArrayList<ILocalStructuralProperty>(); for (ILocalStructuralProperty prop : op2Locals) { if (prop.getPropertyType() == PropertyType.LOCAL_ORDER_PROPERTY) { locals.add(prop); } else { break; } } this.deliveredProperties = new StructuralPropertiesVector(p, locals); } @Override public PhysicalRequirements getRequiredPropertiesForChildren(ILogicalOperator op, IPhysicalPropertiesVector reqdByParent) { List<ILocalStructuralProperty> orderProps = new LinkedList<ILocalStructuralProperty>(); for (OrderColumn oc : orderColumns) { LogicalVariable var = oc.getColumn(); switch (oc.getOrder()) { case ASC: { orderProps.add(new LocalOrderProperty(new OrderColumn(var, OrderKind.ASC))); break; } case DESC: { orderProps.add(new LocalOrderProperty(new OrderColumn(var, OrderKind.DESC))); break; } default: { throw new IllegalStateException(); } } } StructuralPropertiesVector[] r = new StructuralPropertiesVector[] { new StructuralPropertiesVector(null, orderProps) }; return new PhysicalRequirements(r, IPartitioningRequirementsCoordinator.NO_COORDINATION); } @Override public String toString() { return getOperatorTag().toString() + " MERGE:" + orderColumns + " HASH:" + partitionFields; } @Override public Pair<IConnectorDescriptor, TargetConstraint> createConnectorDescriptor(JobSpecification spec, IOperatorSchema opSchema, JobGenContext context) throws AlgebricksException { - int[] keys = new int[orderColumns.size()]; + int[] keys = new int[partitionFields.size()]; IBinaryHashFunctionFactory[] hashFunctionFactories = new IBinaryHashFunctionFactory[partitionFields.size()]; { int i = 0; IBinaryHashFunctionFactoryProvider hashFunProvider = context.getBinaryHashFunctionFactoryProvider(); for (LogicalVariable v : partitionFields) { keys[i] = opSchema.findVariable(v); hashFunctionFactories[i] = hashFunProvider.getBinaryHashFunctionFactory(context.getVarType(v)); ++i; } } ITuplePartitionComputerFactory tpcf = new FieldHashPartitionComputerFactory(keys, hashFunctionFactories); int n = orderColumns.size(); int[] sortFields = new int[n]; IBinaryComparatorFactory[] comparatorFactories = new IBinaryComparatorFactory[n]; { int j = 0; for (OrderColumn oc : orderColumns) { LogicalVariable var = oc.getColumn(); sortFields[j] = opSchema.findVariable(var); Object type = context.getVarType(var); IBinaryComparatorFactoryProvider bcfp = context.getBinaryComparatorFactoryProvider(); comparatorFactories[j] = bcfp.getBinaryComparatorFactory(type, oc.getOrder()); j++; } } IConnectorDescriptor conn = new MToNHashPartitioningMergingConnectorDescriptor(spec, tpcf, sortFields, comparatorFactories); return new Pair<IConnectorDescriptor, TargetConstraint>(conn, null); } }
true
true
public Pair<IConnectorDescriptor, TargetConstraint> createConnectorDescriptor(JobSpecification spec, IOperatorSchema opSchema, JobGenContext context) throws AlgebricksException { int[] keys = new int[orderColumns.size()]; IBinaryHashFunctionFactory[] hashFunctionFactories = new IBinaryHashFunctionFactory[partitionFields.size()]; { int i = 0; IBinaryHashFunctionFactoryProvider hashFunProvider = context.getBinaryHashFunctionFactoryProvider(); for (LogicalVariable v : partitionFields) { keys[i] = opSchema.findVariable(v); hashFunctionFactories[i] = hashFunProvider.getBinaryHashFunctionFactory(context.getVarType(v)); ++i; } } ITuplePartitionComputerFactory tpcf = new FieldHashPartitionComputerFactory(keys, hashFunctionFactories); int n = orderColumns.size(); int[] sortFields = new int[n]; IBinaryComparatorFactory[] comparatorFactories = new IBinaryComparatorFactory[n]; { int j = 0; for (OrderColumn oc : orderColumns) { LogicalVariable var = oc.getColumn(); sortFields[j] = opSchema.findVariable(var); Object type = context.getVarType(var); IBinaryComparatorFactoryProvider bcfp = context.getBinaryComparatorFactoryProvider(); comparatorFactories[j] = bcfp.getBinaryComparatorFactory(type, oc.getOrder()); j++; } } IConnectorDescriptor conn = new MToNHashPartitioningMergingConnectorDescriptor(spec, tpcf, sortFields, comparatorFactories); return new Pair<IConnectorDescriptor, TargetConstraint>(conn, null); }
public Pair<IConnectorDescriptor, TargetConstraint> createConnectorDescriptor(JobSpecification spec, IOperatorSchema opSchema, JobGenContext context) throws AlgebricksException { int[] keys = new int[partitionFields.size()]; IBinaryHashFunctionFactory[] hashFunctionFactories = new IBinaryHashFunctionFactory[partitionFields.size()]; { int i = 0; IBinaryHashFunctionFactoryProvider hashFunProvider = context.getBinaryHashFunctionFactoryProvider(); for (LogicalVariable v : partitionFields) { keys[i] = opSchema.findVariable(v); hashFunctionFactories[i] = hashFunProvider.getBinaryHashFunctionFactory(context.getVarType(v)); ++i; } } ITuplePartitionComputerFactory tpcf = new FieldHashPartitionComputerFactory(keys, hashFunctionFactories); int n = orderColumns.size(); int[] sortFields = new int[n]; IBinaryComparatorFactory[] comparatorFactories = new IBinaryComparatorFactory[n]; { int j = 0; for (OrderColumn oc : orderColumns) { LogicalVariable var = oc.getColumn(); sortFields[j] = opSchema.findVariable(var); Object type = context.getVarType(var); IBinaryComparatorFactoryProvider bcfp = context.getBinaryComparatorFactoryProvider(); comparatorFactories[j] = bcfp.getBinaryComparatorFactory(type, oc.getOrder()); j++; } } IConnectorDescriptor conn = new MToNHashPartitioningMergingConnectorDescriptor(spec, tpcf, sortFields, comparatorFactories); return new Pair<IConnectorDescriptor, TargetConstraint>(conn, null); }
diff --git a/src/main/java/ch/uzh/ddis/katts/bolts/join/TemporalJoinBolt.java b/src/main/java/ch/uzh/ddis/katts/bolts/join/TemporalJoinBolt.java index aaf2c0b..576f899 100644 --- a/src/main/java/ch/uzh/ddis/katts/bolts/join/TemporalJoinBolt.java +++ b/src/main/java/ch/uzh/ddis/katts/bolts/join/TemporalJoinBolt.java @@ -1,148 +1,148 @@ package ch.uzh.ddis.katts.bolts.join; import java.lang.reflect.Constructor; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.Set; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import ch.uzh.ddis.katts.bolts.AbstractStreamSynchronizedBolt; import ch.uzh.ddis.katts.bolts.Event; import ch.uzh.ddis.katts.bolts.VariableBindings; import ch.uzh.ddis.katts.query.processor.join.JoinConditionConfiguration; import ch.uzh.ddis.katts.query.processor.join.TemporalJoinConfiguration; import ch.uzh.ddis.katts.query.stream.Stream; import ch.uzh.ddis.katts.query.stream.StreamConsumer; import ch.uzh.ddis.katts.query.stream.Variable; /** * The temporal join basically happens in two steps. First, all events arrive over the input streams are kept in the * join cache. The semantic join operation that checks for the actual join conditions is then executed over the data in * this cache. Events that do not satisfy the temporal conditions anymore are evicted from the join cache. * * There are three steps that are being executed on the arrival of each new element in the cache. First, a configurable * set of eviction rules will be applied to the cache, in order to remove all data entries that have to be removed from * the cache <i>before</i> the join conditions are checked. Second, the actual join operation is executed, which will * emit all variable bindings that satisfy all join conditions. Lastly, there is a second set of eviction rules that can * be configured to be executed <i>after</i> the join has been executed. * * @author lfischer */ public class TemporalJoinBolt extends AbstractStreamSynchronizedBolt { // TODO lorenz: use global storage facility private static final long serialVersionUID = 1L; /** This object holds the configuration details for this bolt. */ private final TemporalJoinConfiguration configuration; /** A set containing all ids of all incoming streams. */ private Set<String> incomingStreamIds; /** The join condition this bolt uses. */ private JoinCondition joinCondition; /** * This manager manages the eviction indices and provides methods for invoking the eviction rules. */ private EvictionRuleManager evictionRuleManager; /** We store all of our state variables into this object. */ // private Storage<Object, Map<StreamConsumer, PriorityQueue<Event>>> // queues; // private Logger logger = LoggerFactory.getLogger(TemporalJoinBolt.class); /** * Creates a new instance of this bolt type using the configuration provided. * * @param configuration * the jaxb configuration object. */ public TemporalJoinBolt(TemporalJoinConfiguration configuration) { this.configuration = configuration; } @Override public void prepare(@SuppressWarnings("rawtypes") Map stormConf, TopologyContext context, OutputCollector collector) { super.prepare(stormConf, context, collector); // Create a set containing the identifiers of all incoming streams. this.incomingStreamIds = new HashSet<String>(); for (StreamConsumer consumer : this.configuration.getConsumers()) { this.incomingStreamIds.add(consumer.getStream().getId()); } // Create and configure the join condition JoinConditionConfiguration config; Constructor<? extends JoinCondition> constructor; // there is always exactly one condition! config = this.configuration.getJoinCondition(); try { constructor = config.getImplementingClass().getConstructor(); this.joinCondition = constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("Could not instantiate the configured join condition.", e); } this.joinCondition.prepare(config, this.incomingStreamIds); // Create and configure the eviction rules this.evictionRuleManager = new EvictionRuleManager(this.configuration.getBeforeEvictionRules(), this.configuration.getAfterEvictionRules(), this.joinCondition, this.incomingStreamIds); } @Override public void execute(Event event) { Set<SimpleVariableBindings> joinResults; SimpleVariableBindings newBindings = new SimpleVariableBindings(event.getTuple()); String streamId = event.getEmittedOn().getStream().getId(); this.evictionRuleManager.addBindingsToIndices(newBindings, streamId); this.evictionRuleManager.executeBeforeEvictionRules(newBindings, streamId); joinResults = this.joinCondition.join(newBindings, streamId); this.evictionRuleManager.executeAfterEvictionRules(newBindings, streamId); /* * Emit the joined results by creating a variableBindings object for each stream */ for (Stream stream : this.getStreams()) { /* * copy all variable bindings from the result of the join into the new bindings variable which we emit from * this bolt. */ for (SimpleVariableBindings simpleBindings : joinResults) { VariableBindings bindingsToEmit = getEmitter().createVariableBindings(stream, event); for (Variable variable : stream.getVariables()) { - if (simpleBindings.get(variable.getName()) == null) { + if (simpleBindings.get(variable.getReferencesTo()) == null) { throw new NullPointerException(); } - bindingsToEmit.add(variable, simpleBindings.get(variable.getName())); + bindingsToEmit.add(variable, simpleBindings.get(variable.getReferencesTo())); } bindingsToEmit.setStartDate((Date) simpleBindings.get("startDate")); bindingsToEmit.setEndDate((Date) simpleBindings.get("endDate")); bindingsToEmit.emit(); } } ack(event); } @Override public String getId() { return this.configuration.getId(); } @Override public String getSynchronizationDateExpression() { // TODO Make this configurable return "#event.endDate"; } }
false
true
public void execute(Event event) { Set<SimpleVariableBindings> joinResults; SimpleVariableBindings newBindings = new SimpleVariableBindings(event.getTuple()); String streamId = event.getEmittedOn().getStream().getId(); this.evictionRuleManager.addBindingsToIndices(newBindings, streamId); this.evictionRuleManager.executeBeforeEvictionRules(newBindings, streamId); joinResults = this.joinCondition.join(newBindings, streamId); this.evictionRuleManager.executeAfterEvictionRules(newBindings, streamId); /* * Emit the joined results by creating a variableBindings object for each stream */ for (Stream stream : this.getStreams()) { /* * copy all variable bindings from the result of the join into the new bindings variable which we emit from * this bolt. */ for (SimpleVariableBindings simpleBindings : joinResults) { VariableBindings bindingsToEmit = getEmitter().createVariableBindings(stream, event); for (Variable variable : stream.getVariables()) { if (simpleBindings.get(variable.getName()) == null) { throw new NullPointerException(); } bindingsToEmit.add(variable, simpleBindings.get(variable.getName())); } bindingsToEmit.setStartDate((Date) simpleBindings.get("startDate")); bindingsToEmit.setEndDate((Date) simpleBindings.get("endDate")); bindingsToEmit.emit(); } } ack(event); }
public void execute(Event event) { Set<SimpleVariableBindings> joinResults; SimpleVariableBindings newBindings = new SimpleVariableBindings(event.getTuple()); String streamId = event.getEmittedOn().getStream().getId(); this.evictionRuleManager.addBindingsToIndices(newBindings, streamId); this.evictionRuleManager.executeBeforeEvictionRules(newBindings, streamId); joinResults = this.joinCondition.join(newBindings, streamId); this.evictionRuleManager.executeAfterEvictionRules(newBindings, streamId); /* * Emit the joined results by creating a variableBindings object for each stream */ for (Stream stream : this.getStreams()) { /* * copy all variable bindings from the result of the join into the new bindings variable which we emit from * this bolt. */ for (SimpleVariableBindings simpleBindings : joinResults) { VariableBindings bindingsToEmit = getEmitter().createVariableBindings(stream, event); for (Variable variable : stream.getVariables()) { if (simpleBindings.get(variable.getReferencesTo()) == null) { throw new NullPointerException(); } bindingsToEmit.add(variable, simpleBindings.get(variable.getReferencesTo())); } bindingsToEmit.setStartDate((Date) simpleBindings.get("startDate")); bindingsToEmit.setEndDate((Date) simpleBindings.get("endDate")); bindingsToEmit.emit(); } } ack(event); }
diff --git a/src/main/java/org/spoutcraft/launcher/skin/BackgroundImageWorker.java b/src/main/java/org/spoutcraft/launcher/skin/BackgroundImageWorker.java index a3d3752..8173ad4 100644 --- a/src/main/java/org/spoutcraft/launcher/skin/BackgroundImageWorker.java +++ b/src/main/java/org/spoutcraft/launcher/skin/BackgroundImageWorker.java @@ -1,99 +1,99 @@ /* * This file is part of Spoutcraft Launcher. * * Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/> * Spoutcraft Launcher is licensed under the SpoutDev License Version 1. * * Spoutcraft Launcher is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the SpoutDev License Version 1. * * Spoutcraft Launcher is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License, * the MIT license and the SpoutDev License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spoutcraft.launcher.skin; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.channels.Channels; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.SwingConstants; import org.jdesktop.swingworker.SwingWorker; import org.spoutcraft.launcher.api.util.Download; import org.spoutcraft.launcher.api.util.Download.Result; import org.spoutcraft.launcher.api.util.ImageUtils; public class BackgroundImageWorker extends SwingWorker<Object, Object> { private static final int IMAGE_CYCLE_TIME = 24 * 60 * 60 * 1000; private File backgroundImage; private JLabel background; public BackgroundImageWorker(File backgroundImage, JLabel background) { this.backgroundImage = backgroundImage; this.background = background; } @Override protected Object doInBackground() { Download download = null; try { if (!backgroundImage.exists() || backgroundImage.length() < 10 * 1024 || System.currentTimeMillis() - backgroundImage.lastModified() > IMAGE_CYCLE_TIME) { download = new Download("http://get.spout.org/splash/random.png", backgroundImage.getPath()); download.run(); } } catch (Exception e) { Logger.getLogger("launcher").log(Level.WARNING, "Failed to download background image", e); } - if (download == null || download.getResult() != Result.SUCCESS) { + if (download != null && download.getResult() != Result.SUCCESS) { InputStream image = ImageUtils.getResourceAsStream("/org/spoutcraft/launcher/resources/background.png"); backgroundImage.delete(); FileInputStream fis = null; try { fis = new FileInputStream(backgroundImage); fis.getChannel().transferFrom(Channels.newChannel(image), 0, Integer.MAX_VALUE); } catch (IOException e) { Logger.getLogger("launcher").log(Level.WARNING, "Failed read local background image", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } if (image != null) { try { image.close(); } catch (IOException ignore) { } } } } return null; } @Override protected void done() { background.setIcon(new ImageIcon(backgroundImage.getPath())); background.setVerticalAlignment(SwingConstants.TOP); background.setHorizontalAlignment(SwingConstants.LEFT); } }
true
true
protected Object doInBackground() { Download download = null; try { if (!backgroundImage.exists() || backgroundImage.length() < 10 * 1024 || System.currentTimeMillis() - backgroundImage.lastModified() > IMAGE_CYCLE_TIME) { download = new Download("http://get.spout.org/splash/random.png", backgroundImage.getPath()); download.run(); } } catch (Exception e) { Logger.getLogger("launcher").log(Level.WARNING, "Failed to download background image", e); } if (download == null || download.getResult() != Result.SUCCESS) { InputStream image = ImageUtils.getResourceAsStream("/org/spoutcraft/launcher/resources/background.png"); backgroundImage.delete(); FileInputStream fis = null; try { fis = new FileInputStream(backgroundImage); fis.getChannel().transferFrom(Channels.newChannel(image), 0, Integer.MAX_VALUE); } catch (IOException e) { Logger.getLogger("launcher").log(Level.WARNING, "Failed read local background image", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } if (image != null) { try { image.close(); } catch (IOException ignore) { } } } } return null; }
protected Object doInBackground() { Download download = null; try { if (!backgroundImage.exists() || backgroundImage.length() < 10 * 1024 || System.currentTimeMillis() - backgroundImage.lastModified() > IMAGE_CYCLE_TIME) { download = new Download("http://get.spout.org/splash/random.png", backgroundImage.getPath()); download.run(); } } catch (Exception e) { Logger.getLogger("launcher").log(Level.WARNING, "Failed to download background image", e); } if (download != null && download.getResult() != Result.SUCCESS) { InputStream image = ImageUtils.getResourceAsStream("/org/spoutcraft/launcher/resources/background.png"); backgroundImage.delete(); FileInputStream fis = null; try { fis = new FileInputStream(backgroundImage); fis.getChannel().transferFrom(Channels.newChannel(image), 0, Integer.MAX_VALUE); } catch (IOException e) { Logger.getLogger("launcher").log(Level.WARNING, "Failed read local background image", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } if (image != null) { try { image.close(); } catch (IOException ignore) { } } } } return null; }
diff --git a/obo2solr/src/main/java/edu/toronto/cs/cidb/obo2solr/maps/AbstractNumericValueMap.java b/obo2solr/src/main/java/edu/toronto/cs/cidb/obo2solr/maps/AbstractNumericValueMap.java index 0bbf5e0d7..0988f21c1 100644 --- a/obo2solr/src/main/java/edu/toronto/cs/cidb/obo2solr/maps/AbstractNumericValueMap.java +++ b/obo2solr/src/main/java/edu/toronto/cs/cidb/obo2solr/maps/AbstractNumericValueMap.java @@ -1,127 +1,127 @@ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package edu.toronto.cs.cidb.obo2solr.maps; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; public abstract class AbstractNumericValueMap<K, N extends Number> extends LinkedHashMap<K, N> implements NumericValueMap<K, N> { public AbstractNumericValueMap() { super(); } public AbstractNumericValueMap(int initialCapacity) { super(initialCapacity); } public N addTo(K key, N value) { N crtValue = this.get(key); if (crtValue == null) { return this.put(key, value); } else { return this.put(key, value); } } protected abstract N getZero(); public N reset(K key) { return this.put(key, getZero()); } public N safeGet(K key) { N value = this.get(key); return value == null ? getZero() : value; } public List<K> sort() { return this.sort(false); } @SuppressWarnings("unchecked") public List<K> sort(final boolean descending) { K[] sortedKeys = (K[]) this.keySet().toArray(); Arrays.sort(sortedKeys, new Comparator<K>() { public int compare(K a, K b) { if (safeGet(a).equals(safeGet(b))) { return 0; } try { - return ((((Comparable<N>) safeGet(a)).compareTo(safeGet(b)) > 0) && descending) ? -1 : 1; + return (descending ? -1 : 1) * (((Comparable<N>) safeGet(a)).compareTo(safeGet(b))); } catch (ClassCastException ex) { return 0; } } }); LinkedList<K> result = new LinkedList<K>(); for (K key : sortedKeys) { result.add(key); } return result; } public K getMax() { if (this.size() == 0) { return null; } return this.sort(true).get(0); } public K getMin() { if (this.size() == 0) { return null; } return this.sort().get(0); } public N getMaxValue() { return this.safeGet(getMax()); } public N getMinValue() { return this.safeGet(getMin()); } public void writeTo(PrintStream out) { for (K key : this.keySet()) { out.println(key + " : " + this.get(key)); } } }
true
true
public List<K> sort(final boolean descending) { K[] sortedKeys = (K[]) this.keySet().toArray(); Arrays.sort(sortedKeys, new Comparator<K>() { public int compare(K a, K b) { if (safeGet(a).equals(safeGet(b))) { return 0; } try { return ((((Comparable<N>) safeGet(a)).compareTo(safeGet(b)) > 0) && descending) ? -1 : 1; } catch (ClassCastException ex) { return 0; } } }); LinkedList<K> result = new LinkedList<K>(); for (K key : sortedKeys) { result.add(key); } return result; }
public List<K> sort(final boolean descending) { K[] sortedKeys = (K[]) this.keySet().toArray(); Arrays.sort(sortedKeys, new Comparator<K>() { public int compare(K a, K b) { if (safeGet(a).equals(safeGet(b))) { return 0; } try { return (descending ? -1 : 1) * (((Comparable<N>) safeGet(a)).compareTo(safeGet(b))); } catch (ClassCastException ex) { return 0; } } }); LinkedList<K> result = new LinkedList<K>(); for (K key : sortedKeys) { result.add(key); } return result; }
diff --git a/source/com/mucommander/ui/action/CommandAction.java b/source/com/mucommander/ui/action/CommandAction.java index a95944c7..9df8d318 100644 --- a/source/com/mucommander/ui/action/CommandAction.java +++ b/source/com/mucommander/ui/action/CommandAction.java @@ -1,91 +1,91 @@ /* * This file is part of muCommander, http://www.mucommander.com * Copyright (C) 2002-2009 Maxence Bernard * * muCommander is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * muCommander is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mucommander.ui.action; import com.mucommander.Debug; import com.mucommander.command.Command; import com.mucommander.file.FileProtocols; import com.mucommander.file.impl.local.LocalFile; import com.mucommander.file.util.FileSet; import com.mucommander.job.TempOpenWithJob; import com.mucommander.process.ProcessRunner; import com.mucommander.text.Translator; import com.mucommander.ui.dialog.ErrorDialog; import com.mucommander.ui.dialog.file.ProgressDialog; import com.mucommander.ui.main.MainFrame; import java.util.Hashtable; /** * @author Nicolas Rinaudo */ public class CommandAction extends MuAction { // - Instance fields ------------------------------------------------------- // ------------------------------------------------------------------------- /** Command to run. */ private Command command; // - Initialization -------------------------------------------------------- // ------------------------------------------------------------------------- /** * Creates a new <code>CommandAction</code> initialized with the specified parameters. * @param mainFrame frame that will be affected by this action. * @param properties ignored. * @param command command to run when this action is called. */ public CommandAction(MainFrame mainFrame, Hashtable properties, Command command) { super(mainFrame, properties, false); this.command = command; setLabel(command.getDisplayName()); } // - Action code ----------------------------------------------------------- // ------------------------------------------------------------------------- public void performAction() { FileSet selectedFiles; // Retrieves the current selection. selectedFiles = mainFrame.getActiveTable().getSelectedFiles(); // If no files are either selected or marked, aborts. if(selectedFiles.size() == 0) return; // If we're working with local files, go ahead and runs the command. - if(selectedFiles.getBaseFolder().getURL().getScheme().equals(FileProtocols.FILE) && (selectedFiles.getBaseFolder() instanceof LocalFile)) { + if(selectedFiles.getBaseFolder().getURL().getScheme().equals(FileProtocols.FILE) && (selectedFiles.getBaseFolder().getTopAncestor() instanceof LocalFile)) { try {ProcessRunner.execute(command.getTokens(selectedFiles), selectedFiles.getBaseFolder());} catch(Exception e) { ErrorDialog.showErrorDialog(mainFrame); if(Debug.ON) { Debug.trace("Failed to execute command: " + command.getCommand()); Debug.trace(e); } } } // Otherwise, copies the files locally before running the command. else { ProgressDialog progressDialog = new ProgressDialog(mainFrame, Translator.get("copy_dialog.copying")); progressDialog.start(new TempOpenWithJob(new ProgressDialog(mainFrame, Translator.get("copy_dialog.copying")), mainFrame, selectedFiles, command)); } } }
true
true
public void performAction() { FileSet selectedFiles; // Retrieves the current selection. selectedFiles = mainFrame.getActiveTable().getSelectedFiles(); // If no files are either selected or marked, aborts. if(selectedFiles.size() == 0) return; // If we're working with local files, go ahead and runs the command. if(selectedFiles.getBaseFolder().getURL().getScheme().equals(FileProtocols.FILE) && (selectedFiles.getBaseFolder() instanceof LocalFile)) { try {ProcessRunner.execute(command.getTokens(selectedFiles), selectedFiles.getBaseFolder());} catch(Exception e) { ErrorDialog.showErrorDialog(mainFrame); if(Debug.ON) { Debug.trace("Failed to execute command: " + command.getCommand()); Debug.trace(e); } } } // Otherwise, copies the files locally before running the command. else { ProgressDialog progressDialog = new ProgressDialog(mainFrame, Translator.get("copy_dialog.copying")); progressDialog.start(new TempOpenWithJob(new ProgressDialog(mainFrame, Translator.get("copy_dialog.copying")), mainFrame, selectedFiles, command)); } }
public void performAction() { FileSet selectedFiles; // Retrieves the current selection. selectedFiles = mainFrame.getActiveTable().getSelectedFiles(); // If no files are either selected or marked, aborts. if(selectedFiles.size() == 0) return; // If we're working with local files, go ahead and runs the command. if(selectedFiles.getBaseFolder().getURL().getScheme().equals(FileProtocols.FILE) && (selectedFiles.getBaseFolder().getTopAncestor() instanceof LocalFile)) { try {ProcessRunner.execute(command.getTokens(selectedFiles), selectedFiles.getBaseFolder());} catch(Exception e) { ErrorDialog.showErrorDialog(mainFrame); if(Debug.ON) { Debug.trace("Failed to execute command: " + command.getCommand()); Debug.trace(e); } } } // Otherwise, copies the files locally before running the command. else { ProgressDialog progressDialog = new ProgressDialog(mainFrame, Translator.get("copy_dialog.copying")); progressDialog.start(new TempOpenWithJob(new ProgressDialog(mainFrame, Translator.get("copy_dialog.copying")), mainFrame, selectedFiles, command)); } }
diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java index e2c296245..0b0deae50 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java @@ -1,187 +1,187 @@ /* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.SourceLocation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; /** * */ public class EclipseAdapterUtils { //XXX some cut-and-paste from eclipse sources public static String makeLocationContext(ICompilationUnit compilationUnit, IProblem problem) { //extra from the source the innacurate token //and "highlight" it using some underneath ^^^^^ //put some context around too. //this code assumes that the font used in the console is fixed size //sanity ..... int startPosition = problem.getSourceStart(); int endPosition = problem.getSourceEnd(); if ((startPosition > endPosition) || ((startPosition <= 0) && (endPosition <= 0)) || compilationUnit==null) //return Util.bind("problem.noSourceInformation"); //$NON-NLS-1$ return "(no source information available)"; final char SPACE = '\u0020'; final char MARK = '^'; final char TAB = '\t'; char[] source = compilationUnit.getContents(); //the next code tries to underline the token..... //it assumes (for a good display) that token source does not //contain any \r \n. This is false on statements ! //(the code still works but the display is not optimal !) //compute the how-much-char we are displaying around the inaccurate token int begin = startPosition >= source.length ? source.length - 1 : startPosition; int relativeStart = 0; int end = endPosition >= source.length ? source.length - 1 : endPosition; int relativeEnd = 0; label : for (relativeStart = 0;; relativeStart++) { if (begin == 0) break label; if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r')) break label; begin--; } label : for (relativeEnd = 0;; relativeEnd++) { if ((end + 1) >= source.length) break label; if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) { break label; } end++; } //extract the message form the source char[] extract = new char[end - begin + 1]; System.arraycopy(source, begin, extract, 0, extract.length); char c; //remove all SPACE and TAB that begin the error message... int trimLeftIndex = 0; - while (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) { - }; + while ( (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) && trimLeftIndex<extract.length ) { }; + if (trimLeftIndex>=extract.length) return new String(extract)+"\n"; System.arraycopy( extract, trimLeftIndex - 1, extract = new char[extract.length - trimLeftIndex + 1], 0, extract.length); relativeStart -= trimLeftIndex; //buffer spaces and tabs in order to reach the error position int pos = 0; char[] underneath = new char[extract.length]; // can't be bigger for (int i = 0; i <= relativeStart; i++) { if (extract[i] == TAB) { underneath[pos++] = TAB; } else { underneath[pos++] = SPACE; } } //mark the error position for (int i = startPosition + trimLeftIndex; // AMC if we took stuff off the start, take it into account! i <= (endPosition >= source.length ? source.length - 1 : endPosition); i++) underneath[pos++] = MARK; //resize underneathto remove 'null' chars System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos); return new String(extract) + "\n" + new String(underneath); //$NON-NLS-2$ //$NON-NLS-1$ } /** * Extract source location file, start and end lines, and context. * Column is not extracted correctly. * @return ISourceLocation with correct file and lines but not column. */ public static ISourceLocation makeSourceLocation(ICompilationUnit unit, IProblem problem) { int line = problem.getSourceLineNumber(); File file = new File(new String(problem.getOriginatingFileName())); String context = makeLocationContext(unit, problem); // XXX 0 column is wrong but recoverable from makeLocationContext return new SourceLocation(file, line, line, 0, context); } /** * Extract message text and source location, including context. */ public static IMessage makeMessage(ICompilationUnit unit, IProblem problem) { ISourceLocation sourceLocation = makeSourceLocation(unit, problem); IProblem[] seeAlso = problem.seeAlso(); ISourceLocation[] seeAlsoLocations = new ISourceLocation[seeAlso.length]; for (int i = 0; i < seeAlso.length; i++) { seeAlsoLocations[i] = new SourceLocation(new File(new String(seeAlso[i].getOriginatingFileName())), seeAlso[i].getSourceLineNumber()); } // We transform messages from AJ types to eclipse IProblems // and back to AJ types. During their time as eclipse problems, // we remember whether the message originated from a declare // in the extraDetails. String extraDetails = problem.getSupplementaryMessageInfo(); boolean declared = false; if (extraDetails!=null && extraDetails.endsWith("[deow=true]")) { declared = true; extraDetails = extraDetails.substring(0,extraDetails.length()-"[deow=true]".length()); } // If the 'problem' represents a TO DO kind of thing then use the message kind that // represents this so AJDT sees it correctly. IMessage.Kind kind; if (problem.getID()==IProblem.Task) { kind=IMessage.TASKTAG; } else { if (problem.isError()) { kind = IMessage.ERROR; } else { kind = IMessage.WARNING; } } IMessage msg = new Message(problem.getMessage(), extraDetails, kind, sourceLocation, null, seeAlsoLocations, declared, problem.getID(), problem.getSourceStart(),problem.getSourceEnd()); return msg; } public static IMessage makeErrorMessage(ICompilationUnit unit, String text, Exception ex) { ISourceLocation loc = new SourceLocation(new File(new String(unit.getFileName())), 0,0,0,""); IMessage msg = new Message(text,IMessage.ERROR,ex,loc); return msg; } public static IMessage makeErrorMessage(String srcFile, String text, Exception ex) { ISourceLocation loc = new SourceLocation(new File(srcFile), 0,0,0,""); IMessage msg = new Message(text,IMessage.ERROR,ex,loc); return msg; } private EclipseAdapterUtils() { } }
true
true
public static String makeLocationContext(ICompilationUnit compilationUnit, IProblem problem) { //extra from the source the innacurate token //and "highlight" it using some underneath ^^^^^ //put some context around too. //this code assumes that the font used in the console is fixed size //sanity ..... int startPosition = problem.getSourceStart(); int endPosition = problem.getSourceEnd(); if ((startPosition > endPosition) || ((startPosition <= 0) && (endPosition <= 0)) || compilationUnit==null) //return Util.bind("problem.noSourceInformation"); //$NON-NLS-1$ return "(no source information available)"; final char SPACE = '\u0020'; final char MARK = '^'; final char TAB = '\t'; char[] source = compilationUnit.getContents(); //the next code tries to underline the token..... //it assumes (for a good display) that token source does not //contain any \r \n. This is false on statements ! //(the code still works but the display is not optimal !) //compute the how-much-char we are displaying around the inaccurate token int begin = startPosition >= source.length ? source.length - 1 : startPosition; int relativeStart = 0; int end = endPosition >= source.length ? source.length - 1 : endPosition; int relativeEnd = 0; label : for (relativeStart = 0;; relativeStart++) { if (begin == 0) break label; if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r')) break label; begin--; } label : for (relativeEnd = 0;; relativeEnd++) { if ((end + 1) >= source.length) break label; if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) { break label; } end++; } //extract the message form the source char[] extract = new char[end - begin + 1]; System.arraycopy(source, begin, extract, 0, extract.length); char c; //remove all SPACE and TAB that begin the error message... int trimLeftIndex = 0; while (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) { }; System.arraycopy( extract, trimLeftIndex - 1, extract = new char[extract.length - trimLeftIndex + 1], 0, extract.length); relativeStart -= trimLeftIndex; //buffer spaces and tabs in order to reach the error position int pos = 0; char[] underneath = new char[extract.length]; // can't be bigger for (int i = 0; i <= relativeStart; i++) { if (extract[i] == TAB) { underneath[pos++] = TAB; } else { underneath[pos++] = SPACE; } } //mark the error position for (int i = startPosition + trimLeftIndex; // AMC if we took stuff off the start, take it into account! i <= (endPosition >= source.length ? source.length - 1 : endPosition); i++) underneath[pos++] = MARK; //resize underneathto remove 'null' chars System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos); return new String(extract) + "\n" + new String(underneath); //$NON-NLS-2$ //$NON-NLS-1$ }
public static String makeLocationContext(ICompilationUnit compilationUnit, IProblem problem) { //extra from the source the innacurate token //and "highlight" it using some underneath ^^^^^ //put some context around too. //this code assumes that the font used in the console is fixed size //sanity ..... int startPosition = problem.getSourceStart(); int endPosition = problem.getSourceEnd(); if ((startPosition > endPosition) || ((startPosition <= 0) && (endPosition <= 0)) || compilationUnit==null) //return Util.bind("problem.noSourceInformation"); //$NON-NLS-1$ return "(no source information available)"; final char SPACE = '\u0020'; final char MARK = '^'; final char TAB = '\t'; char[] source = compilationUnit.getContents(); //the next code tries to underline the token..... //it assumes (for a good display) that token source does not //contain any \r \n. This is false on statements ! //(the code still works but the display is not optimal !) //compute the how-much-char we are displaying around the inaccurate token int begin = startPosition >= source.length ? source.length - 1 : startPosition; int relativeStart = 0; int end = endPosition >= source.length ? source.length - 1 : endPosition; int relativeEnd = 0; label : for (relativeStart = 0;; relativeStart++) { if (begin == 0) break label; if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r')) break label; begin--; } label : for (relativeEnd = 0;; relativeEnd++) { if ((end + 1) >= source.length) break label; if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) { break label; } end++; } //extract the message form the source char[] extract = new char[end - begin + 1]; System.arraycopy(source, begin, extract, 0, extract.length); char c; //remove all SPACE and TAB that begin the error message... int trimLeftIndex = 0; while ( (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) && trimLeftIndex<extract.length ) { }; if (trimLeftIndex>=extract.length) return new String(extract)+"\n"; System.arraycopy( extract, trimLeftIndex - 1, extract = new char[extract.length - trimLeftIndex + 1], 0, extract.length); relativeStart -= trimLeftIndex; //buffer spaces and tabs in order to reach the error position int pos = 0; char[] underneath = new char[extract.length]; // can't be bigger for (int i = 0; i <= relativeStart; i++) { if (extract[i] == TAB) { underneath[pos++] = TAB; } else { underneath[pos++] = SPACE; } } //mark the error position for (int i = startPosition + trimLeftIndex; // AMC if we took stuff off the start, take it into account! i <= (endPosition >= source.length ? source.length - 1 : endPosition); i++) underneath[pos++] = MARK; //resize underneathto remove 'null' chars System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos); return new String(extract) + "\n" + new String(underneath); //$NON-NLS-2$ //$NON-NLS-1$ }
diff --git a/src/org/bouncycastle/asn1/x9/X962NamedCurves.java b/src/org/bouncycastle/asn1/x9/X962NamedCurves.java index 06e47b6e..764017e7 100644 --- a/src/org/bouncycastle/asn1/x9/X962NamedCurves.java +++ b/src/org/bouncycastle/asn1/x9/X962NamedCurves.java @@ -1,621 +1,621 @@ package org.bouncycastle.asn1.x9; import java.math.BigInteger; import java.util.Enumeration; import java.util.Hashtable; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; /** * table of the current named curves defined in X.962 EC-DSA. */ public class X962NamedCurves { static X9ECParametersHolder prime192v1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { ECCurve cFp192v1 = new ECCurve.Fp( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); return new X9ECParameters( cFp192v1, cFp192v1.decodePoint( Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), new BigInteger("ffffffffffffffffffffffff99def836146bc9b1b4d22831", 16), BigInteger.valueOf(1), Hex.decode("3045AE6FC8422f64ED579528D38120EAE12196D5")); } }; static X9ECParametersHolder prime192v2 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { ECCurve cFp192v2 = new ECCurve.Fp( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("cc22d6dfb95c6b25e49c0d6364a4e5980c393aa21668d953", 16)); return new X9ECParameters( cFp192v2, cFp192v2.decodePoint( Hex.decode("03eea2bae7e1497842f2de7769cfe9c989c072ad696f48034a")), new BigInteger("fffffffffffffffffffffffe5fb1a724dc80418648d8dd31", 16), BigInteger.valueOf(1), Hex.decode("31a92ee2029fd10d901b113e990710f0d21ac6b6")); } }; static X9ECParametersHolder prime192v3 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { ECCurve cFp192v3 = new ECCurve.Fp( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("22123dc2395a05caa7423daeccc94760a7d462256bd56916", 16)); return new X9ECParameters( cFp192v3, cFp192v3.decodePoint( Hex.decode("027d29778100c65a1da1783716588dce2b8b4aee8e228f1896")), new BigInteger("ffffffffffffffffffffffff7a62d031c83f4294f640ec13", 16), BigInteger.valueOf(1), Hex.decode("c469684435deb378c4b65ca9591e2a5763059a2e")); } }; static X9ECParametersHolder prime239v1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { ECCurve cFp239v1 = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); return new X9ECParameters( cFp239v1, cFp239v1.decodePoint( Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), new BigInteger("7fffffffffffffffffffffff7fffff9e5e9a9f5d9071fbd1522688909d0b", 16), BigInteger.valueOf(1), Hex.decode("e43bb460f0b80cc0c0b075798e948060f8321b7d")); } }; static X9ECParametersHolder prime239v2 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { ECCurve cFp239v2 = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), new BigInteger("617fab6832576cbbfed50d99f0249c3fee58b94ba0038c7ae84c8c832f2c", 16)); return new X9ECParameters( cFp239v2, cFp239v2.decodePoint( Hex.decode("0238af09d98727705120c921bb5e9e26296a3cdcf2f35757a0eafd87b830e7")), new BigInteger("7fffffffffffffffffffffff800000cfa7e8594377d414c03821bc582063", 16), BigInteger.valueOf(1), Hex.decode("e8b4011604095303ca3b8099982be09fcb9ae616")); } }; static X9ECParametersHolder prime239v3 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { ECCurve cFp239v3 = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), new BigInteger("255705fa2a306654b1f4cb03d6a750a30c250102d4988717d9ba15ab6d3e", 16)); return new X9ECParameters( cFp239v3, cFp239v3.decodePoint( Hex.decode("036768ae8e18bb92cfcf005c949aa2c6d94853d0e660bbf854b1c9505fe95a")), new BigInteger("7fffffffffffffffffffffff7fffff975deb41b3a6057c3c432146526551", 16), BigInteger.valueOf(1), Hex.decode("7d7374168ffe3471b60a857686a19475d3bfa2ff")); } }; static X9ECParametersHolder prime256v1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { ECCurve cFp256v1 = new ECCurve.Fp( new BigInteger("115792089210356248762697446949407573530086143415290314195533631308867097853951"), new BigInteger("ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", 16), new BigInteger("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", 16)); return new X9ECParameters( cFp256v1, cFp256v1.decodePoint( Hex.decode("036b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296")), new BigInteger("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", 16), BigInteger.valueOf(1), Hex.decode("c49d360886e704936a6678e1139d26b7819f7e90")); } }; /* * F2m Curves */ static X9ECParametersHolder c2pnb163v1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m163v1n = new BigInteger("0400000000000000000001E60FC8821CC74DAEAFC1", 16); BigInteger c2m163v1h = BigInteger.valueOf(2); ECCurve c2m163v1 = new ECCurve.F2m( 163, 1, 2, 8, new BigInteger("072546B5435234A422E0789675F432C89435DE5242", 16), new BigInteger("00C9517D06D5240D3CFF38C74B20B6CD4D6F9DD4D9", 16), c2m163v1n, c2m163v1h); return new X9ECParameters( c2m163v1, c2m163v1.decodePoint( Hex.decode("0307AF69989546103D79329FCC3D74880F33BBE803CB")), c2m163v1n, c2m163v1h, - Hex.decode("D2COFB15760860DEF1EEF4D696E6768756151754")); + Hex.decode("D2C0FB15760860DEF1EEF4D696E6768756151754")); } }; static X9ECParametersHolder c2pnb163v2 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m163v2n = new BigInteger("03FFFFFFFFFFFFFFFFFFFDF64DE1151ADBB78F10A7", 16); BigInteger c2m163v2h = BigInteger.valueOf(2); ECCurve c2m163v2 = new ECCurve.F2m( 163, 1, 2, 8, new BigInteger("0108B39E77C4B108BED981ED0E890E117C511CF072", 16), new BigInteger("0667ACEB38AF4E488C407433FFAE4F1C811638DF20", 16), c2m163v2n, c2m163v2h); return new X9ECParameters( c2m163v2, c2m163v2.decodePoint( Hex.decode("030024266E4EB5106D0A964D92C4860E2671DB9B6CC5")), c2m163v2n, c2m163v2h, null); } }; static X9ECParametersHolder c2pnb163v3 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m163v3n = new BigInteger("03FFFFFFFFFFFFFFFFFFFE1AEE140F110AFF961309", 16); BigInteger c2m163v3h = BigInteger.valueOf(2); ECCurve c2m163v3 = new ECCurve.F2m( 163, 1, 2, 8, new BigInteger("07A526C63D3E25A256A007699F5447E32AE456B50E", 16), new BigInteger("03F7061798EB99E238FD6F1BF95B48FEEB4854252B", 16), c2m163v3n, c2m163v3h); return new X9ECParameters( c2m163v3, c2m163v3.decodePoint( Hex.decode("0202F9F87B7C574D0BDECF8A22E6524775F98CDEBDCB")), c2m163v3n, c2m163v3h, null); } }; static X9ECParametersHolder c2pnb176w1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m176w1n = new BigInteger("010092537397ECA4F6145799D62B0A19CE06FE26AD", 16); BigInteger c2m176w1h = BigInteger.valueOf(0xFF6E); ECCurve c2m176w1 = new ECCurve.F2m( 176, 1, 2, 43, new BigInteger("00E4E6DB2995065C407D9D39B8D0967B96704BA8E9C90B", 16), new BigInteger("005DDA470ABE6414DE8EC133AE28E9BBD7FCEC0AE0FFF2", 16), c2m176w1n, c2m176w1h); return new X9ECParameters( c2m176w1, c2m176w1.decodePoint( Hex.decode("038D16C2866798B600F9F08BB4A8E860F3298CE04A5798")), c2m176w1n, c2m176w1h, null); } }; static X9ECParametersHolder c2tnb191v1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m191v1n = new BigInteger("40000000000000000000000004A20E90C39067C893BBB9A5", 16); BigInteger c2m191v1h = BigInteger.valueOf(2); ECCurve c2m191v1 = new ECCurve.F2m( 191, 9, new BigInteger("2866537B676752636A68F56554E12640276B649EF7526267", 16), new BigInteger("2E45EF571F00786F67B0081B9495A3D95462F5DE0AA185EC", 16), c2m191v1n, c2m191v1h); return new X9ECParameters( c2m191v1, c2m191v1.decodePoint( Hex.decode("0236B3DAF8A23206F9C4F299D7B21A9C369137F2C84AE1AA0D")), c2m191v1n, c2m191v1h, Hex.decode("4E13CA542744D696E67687561517552F279A8C84")); } }; static X9ECParametersHolder c2tnb191v2 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m191v2n = new BigInteger("20000000000000000000000050508CB89F652824E06B8173", 16); BigInteger c2m191v2h = BigInteger.valueOf(4); ECCurve c2m191v2 = new ECCurve.F2m( 191, 9, new BigInteger("401028774D7777C7B7666D1366EA432071274F89FF01E718", 16), new BigInteger("0620048D28BCBD03B6249C99182B7C8CD19700C362C46A01", 16), c2m191v2n, c2m191v2h); return new X9ECParameters( c2m191v2, c2m191v2.decodePoint( Hex.decode("023809B2B7CC1B28CC5A87926AAD83FD28789E81E2C9E3BF10")), c2m191v2n, c2m191v2h, null); } }; static X9ECParametersHolder c2tnb191v3 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m191v3n = new BigInteger("155555555555555555555555610C0B196812BFB6288A3EA3", 16); BigInteger c2m191v3h = BigInteger.valueOf(6); ECCurve c2m191v3 = new ECCurve.F2m( 191, 9, new BigInteger("6C01074756099122221056911C77D77E77A777E7E7E77FCB", 16), new BigInteger("71FE1AF926CF847989EFEF8DB459F66394D90F32AD3F15E8", 16), c2m191v3n, c2m191v3h); return new X9ECParameters( c2m191v3, c2m191v3.decodePoint( Hex.decode("03375D4CE24FDE434489DE8746E71786015009E66E38A926DD")), c2m191v3n, c2m191v3h, null); } }; static X9ECParametersHolder c2pnb208w1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m208w1n = new BigInteger("0101BAF95C9723C57B6C21DA2EFF2D5ED588BDD5717E212F9D", 16); BigInteger c2m208w1h = BigInteger.valueOf(0xFE48); ECCurve c2m208w1 = new ECCurve.F2m( 208, 1, 2, 83, new BigInteger("0", 16), new BigInteger("00C8619ED45A62E6212E1160349E2BFA844439FAFC2A3FD1638F9E", 16), c2m208w1n, c2m208w1h); return new X9ECParameters( c2m208w1, c2m208w1.decodePoint( Hex.decode("0289FDFBE4ABE193DF9559ECF07AC0CE78554E2784EB8C1ED1A57A")), c2m208w1n, c2m208w1h, null); } }; static X9ECParametersHolder c2tnb239v1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m239v1n = new BigInteger("2000000000000000000000000000000F4D42FFE1492A4993F1CAD666E447", 16); BigInteger c2m239v1h = BigInteger.valueOf(4); ECCurve c2m239v1 = new ECCurve.F2m( 239, 36, new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16), c2m239v1n, c2m239v1h); return new X9ECParameters( c2m239v1, c2m239v1.decodePoint( Hex.decode("0257927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D")), c2m239v1n, c2m239v1h, null); } }; static X9ECParametersHolder c2tnb239v2 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m239v2n = new BigInteger("1555555555555555555555555555553C6F2885259C31E3FCDF154624522D", 16); BigInteger c2m239v2h = BigInteger.valueOf(6); ECCurve c2m239v2 = new ECCurve.F2m( 239, 36, new BigInteger("4230017757A767FAE42398569B746325D45313AF0766266479B75654E65F", 16), new BigInteger("5037EA654196CFF0CD82B2C14A2FCF2E3FF8775285B545722F03EACDB74B", 16), c2m239v2n, c2m239v2h); return new X9ECParameters( c2m239v2, c2m239v2.decodePoint( Hex.decode("0228F9D04E900069C8DC47A08534FE76D2B900B7D7EF31F5709F200C4CA205")), c2m239v2n, c2m239v2h, null); } }; static X9ECParametersHolder c2tnb239v3 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m239v3n = new BigInteger("0CCCCCCCCCCCCCCCCCCCCCCCCCCCCCAC4912D2D9DF903EF9888B8A0E4CFF", 16); BigInteger c2m239v3h = BigInteger.valueOf(10); ECCurve c2m239v3 = new ECCurve.F2m( 239, 36, new BigInteger("01238774666A67766D6676F778E676B66999176666E687666D8766C66A9F", 16), new BigInteger("6A941977BA9F6A435199ACFC51067ED587F519C5ECB541B8E44111DE1D40", 16), c2m239v3n, c2m239v3h); return new X9ECParameters( c2m239v3, c2m239v3.decodePoint( Hex.decode("0370F6E9D04D289C4E89913CE3530BFDE903977D42B146D539BF1BDE4E9C92")), c2m239v3n, c2m239v3h, null); } }; static X9ECParametersHolder c2pnb272w1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m272w1n = new BigInteger("0100FAF51354E0E39E4892DF6E319C72C8161603FA45AA7B998A167B8F1E629521", 16); BigInteger c2m272w1h = BigInteger.valueOf(0xFF06); ECCurve c2m272w1 = new ECCurve.F2m( 272, 1, 3, 56, new BigInteger("0091A091F03B5FBA4AB2CCF49C4EDD220FB028712D42BE752B2C40094DBACDB586FB20", 16), new BigInteger("7167EFC92BB2E3CE7C8AAAFF34E12A9C557003D7C73A6FAF003F99F6CC8482E540F7", 16), c2m272w1n, c2m272w1h); return new X9ECParameters( c2m272w1, c2m272w1.decodePoint( Hex.decode("026108BABB2CEEBCF787058A056CBE0CFE622D7723A289E08A07AE13EF0D10D171DD8D")), c2m272w1n, c2m272w1h, null); } }; static X9ECParametersHolder c2pnb304w1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m304w1n = new BigInteger("0101D556572AABAC800101D556572AABAC8001022D5C91DD173F8FB561DA6899164443051D", 16); BigInteger c2m304w1h = BigInteger.valueOf(0xFE2E); ECCurve c2m304w1 = new ECCurve.F2m( 304, 1, 2, 11, new BigInteger("00FD0D693149A118F651E6DCE6802085377E5F882D1B510B44160074C1288078365A0396C8E681", 16), new BigInteger("00BDDB97E555A50A908E43B01C798EA5DAA6788F1EA2794EFCF57166B8C14039601E55827340BE", 16), c2m304w1n, c2m304w1h); return new X9ECParameters( c2m304w1, c2m304w1.decodePoint( Hex.decode("02197B07845E9BE2D96ADB0F5F3C7F2CFFBD7A3EB8B6FEC35C7FD67F26DDF6285A644F740A2614")), c2m304w1n, c2m304w1h, null); } }; static X9ECParametersHolder c2tnb359v1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m359v1n = new BigInteger("01AF286BCA1AF286BCA1AF286BCA1AF286BCA1AF286BC9FB8F6B85C556892C20A7EB964FE7719E74F490758D3B", 16); BigInteger c2m359v1h = BigInteger.valueOf(0x4C); ECCurve c2m359v1 = new ECCurve.F2m( 359, 68, new BigInteger("5667676A654B20754F356EA92017D946567C46675556F19556A04616B567D223A5E05656FB549016A96656A557", 16), new BigInteger("2472E2D0197C49363F1FE7F5B6DB075D52B6947D135D8CA445805D39BC345626089687742B6329E70680231988", 16), c2m359v1n, c2m359v1h); return new X9ECParameters( c2m359v1, c2m359v1.decodePoint( Hex.decode("033C258EF3047767E7EDE0F1FDAA79DAEE3841366A132E163ACED4ED2401DF9C6BDCDE98E8E707C07A2239B1B097")), c2m359v1n, c2m359v1h, null); } }; static X9ECParametersHolder c2pnb368w1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m368w1n = new BigInteger("010090512DA9AF72B08349D98A5DD4C7B0532ECA51CE03E2D10F3B7AC579BD87E909AE40A6F131E9CFCE5BD967", 16); BigInteger c2m368w1h = BigInteger.valueOf(0xFF70); ECCurve c2m368w1 = new ECCurve.F2m( 368, 1, 2, 85, new BigInteger("00E0D2EE25095206F5E2A4F9ED229F1F256E79A0E2B455970D8D0D865BD94778C576D62F0AB7519CCD2A1A906AE30D", 16), new BigInteger("00FC1217D4320A90452C760A58EDCD30C8DD069B3C34453837A34ED50CB54917E1C2112D84D164F444F8F74786046A", 16), c2m368w1n, c2m368w1h); return new X9ECParameters( c2m368w1, c2m368w1.decodePoint( Hex.decode("021085E2755381DCCCE3C1557AFA10C2F0C0C2825646C5B34A394CBCFA8BC16B22E7E789E927BE216F02E1FB136A5F")), c2m368w1n, c2m368w1h, null); } }; static X9ECParametersHolder c2tnb431r1 = new X9ECParametersHolder() { protected X9ECParameters createParameters() { BigInteger c2m431r1n = new BigInteger("0340340340340340340340340340340340340340340340340340340323C313FAB50589703B5EC68D3587FEC60D161CC149C1AD4A91", 16); BigInteger c2m431r1h = BigInteger.valueOf(0x2760); ECCurve c2m431r1 = new ECCurve.F2m( 431, 120, new BigInteger("1A827EF00DD6FC0E234CAF046C6A5D8A85395B236CC4AD2CF32A0CADBDC9DDF620B0EB9906D0957F6C6FEACD615468DF104DE296CD8F", 16), new BigInteger("10D9B4A3D9047D8B154359ABFB1B7F5485B04CEB868237DDC9DEDA982A679A5A919B626D4E50A8DD731B107A9962381FB5D807BF2618", 16), c2m431r1n, c2m431r1h); return new X9ECParameters( c2m431r1, c2m431r1.decodePoint( Hex.decode("02120FC05D3C67A99DE161D2F4092622FECA701BE4F50F4758714E8A87BBF2A658EF8C21E7C5EFE965361F6C2999C0C247B0DBD70CE6B7")), c2m431r1n, c2m431r1h, null); } }; static final Hashtable objIds = new Hashtable(); static final Hashtable curves = new Hashtable(); static final Hashtable names = new Hashtable(); static void defineCurve(String name, ASN1ObjectIdentifier oid, X9ECParametersHolder holder) { objIds.put(name, oid); names.put(oid, name); curves.put(oid, holder); } static { defineCurve("prime192v1", X9ObjectIdentifiers.prime192v1, prime192v1); defineCurve("prime192v2", X9ObjectIdentifiers.prime192v2, prime192v2); defineCurve("prime192v3", X9ObjectIdentifiers.prime192v3, prime192v3); defineCurve("prime239v1", X9ObjectIdentifiers.prime239v1, prime239v1); defineCurve("prime239v2", X9ObjectIdentifiers.prime239v2, prime239v2); defineCurve("prime239v3", X9ObjectIdentifiers.prime239v3, prime239v3); defineCurve("prime256v1", X9ObjectIdentifiers.prime256v1, prime256v1); defineCurve("c2pnb163v1", X9ObjectIdentifiers.c2pnb163v1, c2pnb163v1); defineCurve("c2pnb163v2", X9ObjectIdentifiers.c2pnb163v2, c2pnb163v2); defineCurve("c2pnb163v3", X9ObjectIdentifiers.c2pnb163v3, c2pnb163v3); defineCurve("c2pnb176w1", X9ObjectIdentifiers.c2pnb176w1, c2pnb176w1); defineCurve("c2tnb191v1", X9ObjectIdentifiers.c2tnb191v1, c2tnb191v1); defineCurve("c2tnb191v2", X9ObjectIdentifiers.c2tnb191v2, c2tnb191v2); defineCurve("c2tnb191v3", X9ObjectIdentifiers.c2tnb191v3, c2tnb191v3); defineCurve("c2pnb208w1", X9ObjectIdentifiers.c2pnb208w1, c2pnb208w1); defineCurve("c2tnb239v1", X9ObjectIdentifiers.c2tnb239v1, c2tnb239v1); defineCurve("c2tnb239v2", X9ObjectIdentifiers.c2tnb239v2, c2tnb239v2); defineCurve("c2tnb239v3", X9ObjectIdentifiers.c2tnb239v3, c2tnb239v3); defineCurve("c2pnb272w1", X9ObjectIdentifiers.c2pnb272w1, c2pnb272w1); defineCurve("c2pnb304w1", X9ObjectIdentifiers.c2pnb304w1, c2pnb304w1); defineCurve("c2tnb359v1", X9ObjectIdentifiers.c2tnb359v1, c2tnb359v1); defineCurve("c2pnb368w1", X9ObjectIdentifiers.c2pnb368w1, c2pnb368w1); defineCurve("c2tnb431r1", X9ObjectIdentifiers.c2tnb431r1, c2tnb431r1); } public static X9ECParameters getByName( String name) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)objIds.get(Strings.toLowerCase(name)); if (oid != null) { return getByOID(oid); } return null; } /** * return the X9ECParameters object for the named curve represented by * the passed in object identifier. Null if the curve isn't present. * * @param oid an object identifier representing a named curve, if present. */ public static X9ECParameters getByOID( ASN1ObjectIdentifier oid) { X9ECParametersHolder holder = (X9ECParametersHolder)curves.get(oid); if (holder != null) { return holder.getParameters(); } return null; } /** * return the object identifier signified by the passed in name. Null * if there is no object identifier associated with name. * * @return the object identifier associated with name, if present. */ public static ASN1ObjectIdentifier getOID( String name) { return (ASN1ObjectIdentifier)objIds.get(Strings.toLowerCase(name)); } /** * return the named curve name represented by the given object identifier. */ public static String getName( ASN1ObjectIdentifier oid) { return (String)names.get(oid); } /** * returns an enumeration containing the name strings for curves * contained in this structure. */ public static Enumeration getNames() { return objIds.keys(); } }
true
true
protected X9ECParameters createParameters() { BigInteger c2m163v1n = new BigInteger("0400000000000000000001E60FC8821CC74DAEAFC1", 16); BigInteger c2m163v1h = BigInteger.valueOf(2); ECCurve c2m163v1 = new ECCurve.F2m( 163, 1, 2, 8, new BigInteger("072546B5435234A422E0789675F432C89435DE5242", 16), new BigInteger("00C9517D06D5240D3CFF38C74B20B6CD4D6F9DD4D9", 16), c2m163v1n, c2m163v1h); return new X9ECParameters( c2m163v1, c2m163v1.decodePoint( Hex.decode("0307AF69989546103D79329FCC3D74880F33BBE803CB")), c2m163v1n, c2m163v1h, Hex.decode("D2COFB15760860DEF1EEF4D696E6768756151754")); }
protected X9ECParameters createParameters() { BigInteger c2m163v1n = new BigInteger("0400000000000000000001E60FC8821CC74DAEAFC1", 16); BigInteger c2m163v1h = BigInteger.valueOf(2); ECCurve c2m163v1 = new ECCurve.F2m( 163, 1, 2, 8, new BigInteger("072546B5435234A422E0789675F432C89435DE5242", 16), new BigInteger("00C9517D06D5240D3CFF38C74B20B6CD4D6F9DD4D9", 16), c2m163v1n, c2m163v1h); return new X9ECParameters( c2m163v1, c2m163v1.decodePoint( Hex.decode("0307AF69989546103D79329FCC3D74880F33BBE803CB")), c2m163v1n, c2m163v1h, Hex.decode("D2C0FB15760860DEF1EEF4D696E6768756151754")); }
diff --git a/JDigest/src/jdigest/JLeftClippingLabel.java b/JDigest/src/jdigest/JLeftClippingLabel.java index 8628ceb..748168f 100755 --- a/JDigest/src/jdigest/JLeftClippingLabel.java +++ b/JDigest/src/jdigest/JLeftClippingLabel.java @@ -1,80 +1,80 @@ package jdigest; import java.awt.FontMetrics; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import javax.swing.JLabel; public class JLeftClippingLabel extends JLabel { private static final long serialVersionUID = 1L; private String fullText; public JLeftClippingLabel(String text) { super(text); fullText = text; this.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { adjustText(); } }); } public void setText(String text) { fullText = text; adjustText(); } private void adjustText() { int availTextWidth = getSize().width - getInsets().left - getInsets().right; String text = fullText; - System.out.println(text); if(availTextWidth <= 0) super.setText(text); else { FontMetrics fm = getFontMetrics(getFont()); if(fm.stringWidth(text) <= availTextWidth) super.setText(text); else { String clipString = "..."; int width = fm.stringWidth(clipString); int i = text.length(); - while(--i >= 0 && width <= availTextWidth) + while(width <= availTextWidth && --i >= 0) width += fm.charWidth(text.charAt(i)); - String newText = text.substring(i + 1); + String newText = i + 1 <= text.length()? + text.substring(i + 1): ""; super.setText("..." + newText); } } } // public static void main(String[] args) // { // try // { // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // } // catch(Exception e) // { // } // // JFrame w = new JFrame(); // w.setTitle("test"); // w.add(new JLeftClippingLabel("a very long text which will be clipped")); // w.pack(); // w.setVisible(true); // w.setLocationRelativeTo(null); // } }
false
true
private void adjustText() { int availTextWidth = getSize().width - getInsets().left - getInsets().right; String text = fullText; System.out.println(text); if(availTextWidth <= 0) super.setText(text); else { FontMetrics fm = getFontMetrics(getFont()); if(fm.stringWidth(text) <= availTextWidth) super.setText(text); else { String clipString = "..."; int width = fm.stringWidth(clipString); int i = text.length(); while(--i >= 0 && width <= availTextWidth) width += fm.charWidth(text.charAt(i)); String newText = text.substring(i + 1); super.setText("..." + newText); } } }
private void adjustText() { int availTextWidth = getSize().width - getInsets().left - getInsets().right; String text = fullText; if(availTextWidth <= 0) super.setText(text); else { FontMetrics fm = getFontMetrics(getFont()); if(fm.stringWidth(text) <= availTextWidth) super.setText(text); else { String clipString = "..."; int width = fm.stringWidth(clipString); int i = text.length(); while(width <= availTextWidth && --i >= 0) width += fm.charWidth(text.charAt(i)); String newText = i + 1 <= text.length()? text.substring(i + 1): ""; super.setText("..." + newText); } } }
diff --git a/src/org/odk/collect/android/activities/InstanceChooserList.java b/src/org/odk/collect/android/activities/InstanceChooserList.java index 17d2c18..809185b 100644 --- a/src/org/odk/collect/android/activities/InstanceChooserList.java +++ b/src/org/odk/collect/android/activities/InstanceChooserList.java @@ -1,146 +1,146 @@ /* * Copyright (C) 2009 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.provider.InstanceProviderAPI; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import android.app.AlertDialog; import android.app.ListActivity; import android.content.ContentUris; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * Responsible for displaying all the valid instances in the instance directory. * * @author Yaw Anokwa ([email protected]) * @author Carl Hartung ([email protected]) */ public class InstanceChooserList extends ListActivity { private static boolean EXIT = true; private static boolean DO_NOT_EXIT = false; private AlertDialog mAlertDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.chooser_list_layout); setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data)); TextView tv = (TextView) findViewById(R.id.status_text); tv.setVisibility(View.GONE); - String selection = InstanceColumns.STATUS + " is not ?"; + String selection = InstanceColumns.STATUS + " != ?"; String[] selectionArgs = {InstanceProviderAPI.STATUS_SUBMITTED}; Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, InstanceColumns.STATUS + " desc"); String[] data = new String[] { InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_SUBTEXT }; int[] view = new int[] { R.id.text1, R.id.text2 }; // render total instance view SimpleCursorAdapter instances = new SimpleCursorAdapter(this, R.layout.two_item, c, data, view); setListAdapter(instances); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); } /** * Stores the path of selected instance in the parent class and finishes. */ @Override protected void onListItemClick(ListView listView, View view, int position, long id) { Cursor c = (Cursor) getListAdapter().getItem(position); startManagingCursor(c); Uri instanceUri = ContentUris.withAppendedId(InstanceColumns.CONTENT_URI, c.getLong(c.getColumnIndex(InstanceColumns._ID))); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action)) { // caller is waiting on a picked form setResult(RESULT_OK, new Intent().setData(instanceUri)); } else { // the form can be edited if it is incomplete or if, when it was // marked as complete, it was determined that it could be edited // later. String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS)); String strCanEditWhenComplete = c.getString(c.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)); boolean canEdit = status.equals(InstanceProviderAPI.STATUS_INCOMPLETE) || Boolean.parseBoolean(strCanEditWhenComplete); if (!canEdit) { createErrorDialog(getString(R.string.cannot_edit_completed_form), DO_NOT_EXIT); return; } // caller wants to view/edit a form, so launch formentryactivity startActivity(new Intent(Intent.ACTION_EDIT, instanceUri)); } finish(); } private void createErrorDialog(String errorMsg, final boolean shouldExit) { mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: if (shouldExit) { finish(); } break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), errorListener); mAlertDialog.show(); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.chooser_list_layout); setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data)); TextView tv = (TextView) findViewById(R.id.status_text); tv.setVisibility(View.GONE); String selection = InstanceColumns.STATUS + " is not ?"; String[] selectionArgs = {InstanceProviderAPI.STATUS_SUBMITTED}; Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, InstanceColumns.STATUS + " desc"); String[] data = new String[] { InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_SUBTEXT }; int[] view = new int[] { R.id.text1, R.id.text2 }; // render total instance view SimpleCursorAdapter instances = new SimpleCursorAdapter(this, R.layout.two_item, c, data, view); setListAdapter(instances); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.chooser_list_layout); setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data)); TextView tv = (TextView) findViewById(R.id.status_text); tv.setVisibility(View.GONE); String selection = InstanceColumns.STATUS + " != ?"; String[] selectionArgs = {InstanceProviderAPI.STATUS_SUBMITTED}; Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, InstanceColumns.STATUS + " desc"); String[] data = new String[] { InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_SUBTEXT }; int[] view = new int[] { R.id.text1, R.id.text2 }; // render total instance view SimpleCursorAdapter instances = new SimpleCursorAdapter(this, R.layout.two_item, c, data, view); setListAdapter(instances); }
diff --git a/src/QueryResult.java b/src/QueryResult.java index 0f1521f..b9552ee 100644 --- a/src/QueryResult.java +++ b/src/QueryResult.java @@ -1,58 +1,55 @@ /** * Wraps the (document, score) pair as a result of a query * @author mircea * */ public class QueryResult implements Comparable<QueryResult> { private String docId; private double score; public QueryResult(String docId, double score) { this.docId = docId; this.score = score; } public String getDocId() { return docId; } public void setDocId(String docId) { this.docId = docId; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public int compareTo(QueryResult result) { if (score > result.score) { return -1; } - else if (score == result.score) { - return 0; - } else { return 1; } } @Override public boolean equals(Object entry) { if (!entry.getClass().equals(QueryResult.class)) return false; return docId.equals(((QueryResult) entry).getDocId()); } public String toString() { return "(" + docId + ", " + score + ")"; } }
true
true
public int compareTo(QueryResult result) { if (score > result.score) { return -1; } else if (score == result.score) { return 0; } else { return 1; } }
public int compareTo(QueryResult result) { if (score > result.score) { return -1; } else { return 1; } }
diff --git a/TantalumCore/src/main/java/org/tantalum/net/HttpGetter.java b/TantalumCore/src/main/java/org/tantalum/net/HttpGetter.java index fc620437..3fce0dd1 100644 --- a/TantalumCore/src/main/java/org/tantalum/net/HttpGetter.java +++ b/TantalumCore/src/main/java/org/tantalum/net/HttpGetter.java @@ -1,1145 +1,1148 @@ /* Copyright (c) 2013, Paul Houghton and Futurice Oy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.tantalum.net; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Hashtable; import java.util.Vector; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.security.DigestException; import org.tantalum.PlatformUtils; import org.tantalum.Task; import org.tantalum.util.CryptoUtils; import org.tantalum.util.L; import org.tantalum.util.RollingAverage; /** * GET something from a URL on the Worker thread * * This Task will, when fork()ed, get the byte[] from a specified web service * URL. * * Be default, the client will automatically retry 3 times if the web service * does not respond on the first attempt (happens frequently with the mobile * web...). You can disable this by calling setRetriesRemaining(0). * * The input "key" is a url with optional additional lines of text which are * ignored from the URL but may be useful for distinguishing multiple HTTP * operations to the same URL (HttpPoster). You can optionally attach additional * information to the key after \n (newline) to create a unique hashcode for * cache management purposes. This is sometimes needed for example with HTTP * POST where the url does not alone indicate a unique cachable entity- the post * parameters do. * * @author pahought */ public class HttpGetter extends Task { private static final int READ_BUFFER_LENGTH = 8192; //8k read buffer if no Content-Length header from server private static final int OUTPUT_BUFFER_INITIAL_LENGTH = 8192; //8k read buffer if no Content-Length header from server /** * HTTP GET is the default operation */ public static final String HTTP_GET = "GET"; /** * HTTP HEAD is not supported by JME */ public static final String HTTP_HEAD = "HEAD"; /** * HTTP POST is used if a byte[] to send is provided by the * <code>HttpPoster</code> */ public static final String HTTP_POST = "POST"; /** * HTTP PUT is not supported by JME */ public static final String HTTP_PUT = "PUT"; /** * HTTP DELETE is not supported by JME */ public static final String HTTP_DELETE = "DELETE"; /** * HTTP TRACE is not supported by JME */ public static final String HTTP_TRACE = "TRACE"; /** * HTTP CONNECT is not supported by JME */ public static final String HTTP_CONNECT = "CONNECT"; /* * HTTP Status constants */ /** * HTTP response code value */ public static final int HTTP_100_CONTINUE = 100; /** * HTTP response code value */ public static final int HTTP_101_SWITCHING_PROTOCOLS = 101; /** * HTTP response code value */ public static final int HTTP_102_PROCESSING = 102; /** * HTTP response code value */ public static final int HTTP_200_OK = 200; /** * HTTP response code value */ public static final int HTTP_201_CREATED = 201; /** * HTTP response code value */ public static final int HTTP_202_ACCEPTED = 202; /** * HTTP response code value */ public static final int HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203; /** * HTTP response code value */ public static final int HTTP_204_NO_CONTENT = 204; /** * HTTP response code value */ public static final int HTTP_205_RESET_CONTENT = 205; /** * HTTP response code value */ public static final int HTTP_206_PARTIAL_CONTENT = 206; /** * HTTP response code value */ public static final int HTTP_207_MULTI_STATUS = 207; /** * HTTP response code value */ public static final int HTTP_208_ALREADY_REPORTED = 208; /** * HTTP response code value */ public static final int HTTP_250_LOW_ON_STORAGE_SPACE = 250; /** * HTTP response code value */ public static final int HTTP_226_IM_USED = 226; /** * HTTP response code value */ public static final int HTTP_300_MULTIPLE_CHOICES = 300; /** * HTTP response code value */ public static final int HTTP_301_MOVED_PERMANENTLY = 301; /** * HTTP response code value */ public static final int HTTP_302_FOUND = 302; /** * HTTP response code value */ public static final int HTTP_303_SEE_OTHER = 303; /** * HTTP response code value */ public static final int HTTP_304_NOT_MODIFIED = 304; /** * HTTP response code value */ public static final int HTTP_305_USE_PROXY = 305; /** * HTTP response code value */ public static final int HTTP_306_SWITCH_PROXY = 306; /** * HTTP response code value */ public static final int HTTP_307_TEMPORARY_REDIRECT = 307; /** * HTTP response code value */ public static final int HTTP_308_PERMANENT_REDIRECT = 308; /** * HTTP response code value */ public static final int HTTP_400_BAD_REQUEST = 400; /** * HTTP response code value */ public static final int HTTP_401_UNAUTHORIZED = 401; /** * HTTP response code value */ public static final int HTTP_402_PAYMENT_REQUIRED = 402; /** * HTTP response code value */ public static final int HTTP_403_FORBIDDEN = 403; /** * HTTP response code value */ public static final int HTTP_404_NOT_FOUND = 404; /** * HTTP response code value */ public static final int HTTP_405_METHOD_NOT_ALLOWED = 405; /** * HTTP response code value */ public static final int HTTP_406_NOT_ACCEPTABLE = 406; /** * HTTP response code value */ public static final int HTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407; /** * HTTP response code value */ public static final int HTTP_408_REQUEST_TIMEOUT = 408; /** * HTTP response code value */ public static final int HTTP_409_CONFLICT = 409; /** * HTTP response code value */ public static final int HTTP_410_GONE = 410; /** * HTTP response code value */ public static final int HTTP_411_LENGTH_REQUIRED = 411; /** * HTTP response code value */ public static final int HTTP_412_PRECONDITION_FAILED = 412; /** * HTTP response code value */ public static final int HTTP_413_REQUEST_ENTITY_TOO_LARGE = 413; /** * HTTP response code value */ public static final int HTTP_414_REQUEST_URI_TOO_LONG = 414; /** * HTTP response code value */ public static final int HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415; /** * HTTP response code value */ public static final int HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416; /** * HTTP response code value */ /** * HTTP response code value */ public static final int HTTP_417_EXPECTATION_FAILED = 417; /** * HTTP response code value */ public static final int HTTP_418_IM_A_TEAPOT = 418; /** * HTTP response code value */ public static final int HTTP_420_ENHANCE_YOUR_CALM = 420; /** * HTTP response code value */ public static final int HTTP_422_UNPROCESSABLE_ENTITY = 422; /** * HTTP response code value */ public static final int HTTP_423_LOCKED = 423; /** * HTTP response code value */ public static final int HTTP_424_FAILED_DEPENDENCY = 424; /** * HTTP response code value */ public static final int HTTP_424_METHOD_FAILURE = 424; /** * HTTP response code value */ public static final int HTTP_425_UNORDERED_COLLECTION = 425; /** * HTTP response code value */ public static final int HTTP_426_UPGRADE_REQUIRED = 426; /** * HTTP response code value */ public static final int HTTP_428_PRECONDITION_REQUIRED = 428; /** * HTTP response code value */ public static final int HTTP_429_TOO_MANY_REQUESTS = 429; /** * HTTP response code value */ public static final int HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; /** * HTTP response code value */ public static final int HTTP_444_NO_RESPONSE = 444; /** * HTTP response code value */ public static final int HTTP_449_RETRY_WITH = 449; /** * HTTP response code value */ public static final int HTTP_450_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS = 450; /** * HTTP response code value */ public static final int HTTP_451_PARAMETER_NOT_UNDERSTOOD = 451; /** * HTTP response code value */ public static final int HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451; /** * HTTP response code value */ public static final int HTTP_451_REDIRECT = 451; /** * HTTP response code value */ public static final int HTTP_452_CONFERENCE_NOT_FOUND = 452; /** * HTTP response code value */ public static final int HTTP_453_NOT_ENOUGH_BANDWIDTH = 453; /** * HTTP response code value */ public static final int HTTP_454_SESSION_NOT_FOUND = 454; /** * HTTP response code value */ public static final int HTTP_455_METHOD_NOT_VALID_IN_THIS_STATE = 455; /** * HTTP response code value */ public static final int HTTP_456_HEADER_FIELD_NOT_VALID_FOR_RESOURCE = 456; /** * HTTP response code value */ public static final int HTTP_457_INVALID_RANGE = 457; /** * HTTP response code value */ public static final int HTTP_458_PARAMETER_IS_READ_ONLY = 458; /** * HTTP response code value */ public static final int HTTP_459_AGGREGATE_OPERATION_NOT_ALLOWED = 459; /** * HTTP response code value */ public static final int HTTP_460_ONLY_AGGREGATE_OPERATION_ALLOWED = 460; /** * HTTP response code value */ public static final int HTTP_461_UNSUPPORTED_TRANSPORT = 461; /** * HTTP response code value */ public static final int HTTP_462_DESTINATION_UNREACHABLE = 462; /** * HTTP response code value */ public static final int HTTP_494_REQUEST_HEADER_TOO_LARGE = 494; /** * HTTP response code value */ public static final int HTTP_495_CERT_ERROR = 495; /** * HTTP response code value */ public static final int HTTP_496_NO_CERT = 496; /** * HTTP response code value */ public static final int HTTP_497_HTTP_TO_HTTPS = 497; /** * HTTP response code value */ public static final int HTTP_499_CLIENT_CLOSED_REQUEST = 499; /** * HTTP response code value */ public static final int HTTP_500_INTERNAL_SERVER_ERROR = 500; /** * HTTP response code value */ public static final int HTTP_501_NOT_IMPLEMENTED = 501; /** * HTTP response code value */ public static final int HTTP_502_BAD_GATEWAY = 502; /** * HTTP response code value */ public static final int HTTP_503_SERVICE_UNAVAILABLE = 503; /** * HTTP response code value */ public static final int HTTP_504_GATEWAY_TIMEOUT = 504; /** * HTTP response code value */ public static final int HTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505; /** * HTTP response code value */ public static final int HTTP_506_VARIANT_ALSO_NEGOTIATES = 506; /** * HTTP response code value */ public static final int HTTP_507_INSUFFICIENT_STORAGE = 507; /** * HTTP response code value */ public static final int HTTP_508_LOOP_DETECTED = 508; /** * HTTP response code value */ public static final int HTTP_509_BANDWIDTH_LIMIT_EXCEEDED = 509; /** * HTTP response code value */ public static final int HTTP_510_NOT_EXTENDED = 510; /** * HTTP response code value */ public static final int HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511; /** * HTTP response code value */ public static final int HTTP_550_PERMISSION_DENIED = 550; /** * HTTP response code value */ public static final int HTTP_551_OPTION_NOT_SUPPORTED = 551; /** * HTTP response code value */ public static final int HTTP_598_NETWORK_READ_TIMEOUT_ERROR = 598; /** * HTTP response code value */ public static final int HTTP_599_NETWORK_CONNECT_TIMEOUT_ERROR = 599; /** * The HTTP server has not yet been contacted, so no response code is yet * available */ public static final int HTTP_OPERATION_PENDING = -1; private static final int HTTP_GET_RETRIES = 3; private static final int HTTP_RETRY_DELAY = 5000; // 5 seconds /** * Connections slower than this drop into single file load with header * pre-wind to increase interface responsiveness to each HTTP action as seen * alone and decrease phone thread context switching. * * Note that due to measurement error this is not a real baud rate, but the * rate at which data can be pulled from the network buffers. If phone * network buffering associated with the first packets were removed from the * measure, the actual baud rate over the air would be slower than this. */ public static final float THRESHOLD_BAUD = 128000f; /** * The rolling average of how long it takes the server to respond with the * first response body byte to an HTTP request. This will shift up and down * slowly based on the servers and data network you use. It is in some cases * useful as a performance tuning parameter. */ public static final RollingAverage averageResponseDelayMillis = new RollingAverage(10, 700.0f); /** * bits per second realized by a each connection. When multiple connections * are reading simultaneously this will be lower than the total bits per * second of the phone's downlink. It is used in conjunction with * THRESHOLD_BAUD to determine if we should switch to serial reading with * header pre-wind to help UX by decreasing the user's perceived response * time per HTTP GET. * * We start the app with the assumption we are on a slow connection by * quickly adapt if the data arrives quickly. Note that since the * measurement is continuous and realized we do not make assumptions based * on whether the user or phone think they are on a fast WIFI connection or * not. Changing network connections or network connection real speeds * should result in a change of mode within a few HTTP operations if * appropriate. */ public static final RollingAverage averageBaud = new RollingAverage(10, THRESHOLD_BAUD / 2); /** * At what time earliest can the next HTTP request to a server can begin * when in slow connection mode */ private static volatile long nextHeaderStartTime = 0; /** * At what time earliest can the next HTTP body read operation can begin * when in slow connection mode */ private static volatile long nextBodyStartTime = 0; /** * How many more times will we try to re-connect after a 5 second delay * before giving up. This aids in working with low quality networks and * normal HTTP connection setup errors even on a "good" mobile network. */ protected int retriesRemaining = HTTP_GET_RETRIES; /** * Data to be sent to the server as part of an HTTP POST operation */ protected byte[] postMessage = null; // Always access in a synchronized(HttpGetter.this) block private final Hashtable responseHeaders = new Hashtable(); private Vector requestPropertyKeys = new Vector(); private Vector requestPropertyValues = new Vector(); /** * Counter, estimated downloaded bytes during the app session. * * Access only in static synchronized block */ private static int downstreamDataCount = 0; /** * Counter, estimated uploaded bytes during the app session. * * Access only in static synchronized block */ private static int upstreamDataCount = 0; private volatile StreamWriter streamWriter = null; private volatile StreamReader streamReader = null; // Always access in a synchronized(HttpGetter.this) block private int responseCode = HTTP_OPERATION_PENDING; private volatile long startTime = 0; static { HttpGetter.averageBaud.setLowerBound(HttpGetter.THRESHOLD_BAUD / 10); HttpGetter.averageResponseDelayMillis.setUpperBound(5000.0f); } /** * Create a Task.NORMAL_PRIORITY getter * */ public HttpGetter() { this(Task.NORMAL_PRIORITY); } /** * Get the byte[] from the URL specified by the input argument when * exec(url) is called. This may be chained from a previous chain()ed * asynchronous task. * * @param priority */ public HttpGetter(final int priority) { super(priority); setShutdownBehaviour(Task.DEQUEUE_OR_CANCEL_ON_SHUTDOWN); } /** * Create a Task for the specified URL. * * @param priority * @param url */ public HttpGetter(final int priority, final String url) { this(priority); if (url == null) { throw new IllegalArgumentException("Attempt to create an HttpGetter with null URL. Perhaps you want to use the alternate new HttpGetter() constructor and let the previous Task in a chain set the URL."); } set(url); } /** * Create a Task.NORMAL_PRIORITY getter * * @param url */ public HttpGetter(final String url) { this(Task.NORMAL_PRIORITY, url); } /** * On a 2G-speed network, this method will block the calling thread up to * several seconds until the next HTTP operation can begin. * * On a fast network, this will not delay the calling thread. * * The HttpGetter will call this for you at the start of Task exec() to * reduce network contention. You may also want to call as part of your loop * that creates multiple HTTP GET operations such as fetching images. You * can in this way delay the decision to actually fetch a resource and not * do so if the data is not needed several seconds later. This is also * useful to reduce the number of worker threads being held in a header wait * state by HttpGetter Tasks. * * @throws InterruptedException */ public static void staggerHeaderStartTime() throws InterruptedException { long t = System.currentTimeMillis(); long t2; boolean staggerStartMode; while ((staggerStartMode = (HttpGetter.averageBaud.value() < THRESHOLD_BAUD)) && (t2 = nextHeaderStartTime) > t) { //#debug L.i("Header get stagger delay", (t2 - t) + "ms"); Thread.sleep(t2 - t); t = System.currentTimeMillis(); } if (staggerStartMode) { nextHeaderStartTime = t + (((int) HttpGetter.averageResponseDelayMillis.value()) * 7) / 8; } } /** * Get the time at which the HTTP network connection started * * @return */ public long getStartTime() { return startTime; } /** * Set the StreamWriter which will provide data in the optional streaming * upload mode. Most HTTP activities are block-oriented in which case a * stream does not need to be set up. * * If you are tracking data usage, update addUpstreamDataCount() after or * while streaming * * @return */ public StreamWriter getWriter() { return streamWriter; } /** * Set the StreamReader which will receive data in the optional streaming * download mode. Most HTTP activities are block-oriented in which case a * stream does not need to be set up. * * If you are tracking data usage, update addDownstreamDataCount() after or * while streaming * * @param writer */ public void setWriter(final StreamWriter writer) { this.streamWriter = writer; } /** * Get the current streaming download reader. * * Most HTTP use is block-oriented in which case the value is null. * * @return */ public StreamReader getReader() { return streamReader; } /** * Get the current streaming upload reader. * * Most HTTP use is block-oriented in which case the value is null. * * @param reader */ public void setReader(final StreamReader reader) { this.streamReader = reader; } /** * Specify how many more times the HttpGetter should re-attempt HTTP GET if * there is a network error. * * This will automatically count down to zero at which point the Task shifts * to the Task.EXCEPTION state and onCanceled() will be called from the UI * Thread. * * @param retries * @return */ public Task setRetriesRemaining(final int retries) { this.retriesRemaining = retries; return this; } /** * Find the HTTP server's response code, or HTTP_OPERATION_PENDING if the * HTTP server has not yet been contacted. * * @return */ public synchronized int getResponseCode() { return responseCode; } /** * Get a Hashtable of all HTTP headers recieved from the server * * @return */ public synchronized Hashtable getResponseHeaders() { return responseHeaders; } /** * Add an HTTP header to the request sent to the server * * @param key * @param value */ public synchronized void setRequestProperty(final String key, final String value) { if (responseCode != HTTP_OPERATION_PENDING) { throw new IllegalStateException("Can not set request property to HTTP operation already executed (" + key + ": " + value + ")"); } this.requestPropertyKeys.addElement(key); this.requestPropertyValues.addElement(value); } /** * Get the contents of a URL and return that asynchronously as a AsyncResult * * Note that your web service should set the HTTP Header field * content_length as this makes the phone run slightly faster when we can * predict how many bytes to expect. * * @param in * @return */ public Object exec(final Object in) throws InterruptedException { staggerHeaderStartTime(); byte[] out = null; startTime = System.currentTimeMillis(); if (!(in instanceof String) || ((String) in).indexOf(':') <= 0) { final String s = "HTTP operation was passed a bad url=" + in + ". Check calling method or previous chained task: " + this; //#debug L.e("HttpGetter with non-String input", s, new IllegalArgumentException()); cancel(false, s); return out; } final String url = keyIncludingPostDataHashtoUrl((String) in); //#debug L.i(this, "Start", url); ByteArrayOutputStream bos = null; PlatformUtils.HttpConn httpConn = null; boolean tryAgain = false; boolean success = false; addUpstreamDataCount(url.length()); try { final OutputStream outputStream; if (this instanceof HttpPoster) { if (postMessage == null && streamWriter == null) { throw new IllegalArgumentException("null HTTP POST- did you forget to call httpPoster.setMessage(byte[]) ? : " + url); } httpConn = PlatformUtils.getInstance().getHttpPostConn(url, requestPropertyKeys, requestPropertyValues, postMessage); outputStream = httpConn.getOutputStream(); final StreamWriter writer = this.streamWriter; if (writer != null) { writer.writeReady(outputStream); success = true; } addUpstreamDataCount(postMessage.length); } else { httpConn = PlatformUtils.getInstance().getHttpGetConn(url, requestPropertyKeys, requestPropertyValues); } final InputStream inputStream = httpConn.getInputStream(); final StreamReader reader = streamReader; if (reader != null) { reader.readReady(inputStream); success = true; } // Estimate data length of the sent headers for (int i = 0; i < requestPropertyKeys.size(); i++) { addUpstreamDataCount(((String) requestPropertyKeys.elementAt(i)).length()); addUpstreamDataCount(((String) requestPropertyValues.elementAt(i)).length()); } final int length = (int) httpConn.getLength(); final int downstreamDataHeaderLength; synchronized (this) { responseCode = httpConn.getResponseCode(); httpConn.getResponseHeaders(responseHeaders); downstreamDataHeaderLength = PlatformUtils.responseHeadersToString(responseHeaders).length(); } // Response headers length estimation addDownstreamDataCount(downstreamDataHeaderLength); long firstByteTime = Long.MAX_VALUE; if (length == 0) { //#debug L.i(this, "Exec", "No response. Stream is null, or length is 0"); } else if (length > httpConn.getMaxLengthSupportedAsBlockOperation()) { cancel(false, "Http server sent Content-Length > " + httpConn.getMaxLengthSupportedAsBlockOperation() + " which might cause out-of-memory on this platform"); } else if (length > 0) { final byte[] bytes = new byte[length]; firstByteTime = readBytesFixedLength(url, inputStream, bytes); out = bytes; } else { bos = new ByteArrayOutputStream(OUTPUT_BUFFER_INITIAL_LENGTH); firstByteTime = readBytesVariableLength(inputStream, bos); out = bos.toByteArray(); } if (firstByteTime != Long.MAX_VALUE) { final long responseTime = firstByteTime - startTime; HttpGetter.averageResponseDelayMillis.update(responseTime); //#debug L.i(this, "Average HTTP header response time", HttpGetter.averageResponseDelayMillis.value() + " current=" + responseTime); } final long lastByteTime = System.currentTimeMillis(); final float baud; - final int dataLength = ((byte[]) out).length; + int dataLength = 0; + if (out != null) { + dataLength = out.length; + } if (dataLength > 0 && lastByteTime > firstByteTime) { baud = (dataLength * 8 * 1000) / ((int) (lastByteTime - firstByteTime)); } else { baud = THRESHOLD_BAUD * 2; } HttpGetter.averageBaud.update(baud); //#debug L.i(this, "Average HTTP body read baud", HttpGetter.averageBaud.value() + " current=" + baud); if (out != null) { addDownstreamDataCount(dataLength); //#debug L.i(this, "End read", "url=" + url + " bytes=" + ((byte[]) out).length); } synchronized (this) { success = checkResponseCode(url, responseCode, responseHeaders); } //#debug L.i(this, "Response", "HTTP response code indicates success=" + success); } catch (IllegalArgumentException e) { //#debug L.e(this, "HttpGetter has illegal argument", url, e); throw e; } catch (IOException e) { //#debug L.e(this, "Retries remaining", url + ", retries=" + retriesRemaining, e); if (retriesRemaining > 0) { retriesRemaining--; tryAgain = true; } else { //#debug L.i(this, "No more retries", url); cancel(false, "No more retries"); } } finally { if (httpConn != null) { try { httpConn.close(); } catch (Exception e) { //#debug L.e(this, "Closing Http InputStream error", url, e); } finally { httpConn = null; } } try { if (bos != null) { bos.close(); } } catch (Exception e) { //#debug L.e(this, "HttpGetter byteArrayOutputStream close error", url, e); } finally { bos = null; } if (tryAgain) { try { Thread.sleep(HTTP_RETRY_DELAY); } catch (InterruptedException ex) { cancel(false, "Interrupted HttpGetter while sleeping between retries: " + this); } out = (byte[]) exec(url); } else if (!success) { //#debug - L.i("HTTP GET FAILED, cancel() of task and any chained Tasks", this.toString()); - cancel(false, "HttpGetter failed response code and header check: " + this.toString()); + L.i("HTTP GET FAILED, cancel() of task and any chained Tasks", (this != null ? this.toString() : "null")); + cancel(false, "HttpGetter failed response code and header check: " + this); } //#debug L.i(this, "End", url + " status=" + getStatus() + " out=" + out); } if (!success) { return null; } return out; } /** * Read an exact number of bytes specified in the header Content-Length * field * * @param url * @param inputStream * @param bytes * @return time of first byte received * @throws IOException */ private long readBytesFixedLength(final String url, final InputStream inputStream, final byte[] bytes) throws IOException { long firstByteReceivedTime = Long.MAX_VALUE; if (bytes.length != 0) { int totalBytesRead = 0; final int b = inputStream.read(); // Prime the read loop before mistakenly synchronizing on a net stream that has no data available yet if (b >= 0) { bytes[totalBytesRead++] = (byte) b; } else { prematureEOF(url, totalBytesRead, bytes.length); } firstByteReceivedTime = System.currentTimeMillis(); while (totalBytesRead < bytes.length) { final int br = inputStream.read(bytes, totalBytesRead, bytes.length - totalBytesRead); if (br >= 0) { totalBytesRead += br; if (totalBytesRead < bytes.length) { Thread.currentThread().yield(); } } else { prematureEOF(url, totalBytesRead, bytes.length); } } } return firstByteReceivedTime; } private void prematureEOF(final String url, final int bytesRead, final int length) throws IOException { //#debug L.i(this, "EOF before Content-Length sent by server", url + ", Content-Length=" + length + " bytesRead=" + bytesRead); throw new IOException(getClassName() + " recieved EOF before content_length exceeded"); } /** * Read an unknown length field because the server did not specify how long * the result is * * @param inputStream * @param bos * @return time of first byte received * @throws IOException */ private long readBytesVariableLength(final InputStream inputStream, final OutputStream bos) throws IOException { final byte[] readBuffer = new byte[READ_BUFFER_LENGTH]; final int b = inputStream.read(); // Prime the read loop before mistakenly synchronizing on a net stream that has no data available yet if (b < 0) { return Long.MAX_VALUE; } bos.write(b); final long firstByteReceivedTime = System.currentTimeMillis(); while (true) { final int bytesRead = inputStream.read(readBuffer); if (bytesRead < 0) { break; } bos.write(readBuffer, 0, bytesRead); } return firstByteReceivedTime; } /** * Check headers and HTTP response code as needed for your web service to * see if this is a valid response. Override if needed. * * @param url * @param responseCode * @param headers * @return * @throws IOException */ protected boolean checkResponseCode(final String url, final int responseCode, final Hashtable headers) throws IOException { if (responseCode < 300) { return true; } else if (responseCode < 500) { // We might be able to extract some useful information in case of a 400+ error code //#debug L.i("Bad response code (" + responseCode + ")", "url=" + url); return false; } /* * 500+ error codes, which means that something went wrong on server side. * Probably not recoverable, so should we throw an exception instead? */ //#debug L.i(this, "Server error. Unrecoverable HTTP response code (" + responseCode + ")", "url=" + url); throw new IOException("Server error. Unrecoverable HTTP response code (" + responseCode + ") url=" + url); } /** * Strip additional (optional) lines from the key to create a URL. The key * may contain this data to create several unique hashcodes for cache * management purposes. * * @return */ private String keyIncludingPostDataHashtoUrl(final String key) { final int i = key.indexOf('\n'); if (i < 0) { return key; } return key.substring(0, i); } /** * * @param url * @return * @throws DigestException * @throws UnsupportedEncodingException */ protected String urlToKeyIncludingPostDataHash(final String url) throws DigestException, UnsupportedEncodingException { if (this.postMessage == null) { throw new IllegalStateException("Attempt to get post-style crypto digest, but postData==null"); } final long digest = CryptoUtils.getInstance().toDigest(this.postMessage); final String digestAsHex = Long.toString(digest, 16); return url + '\n' + digestAsHex; } /** * Retrieves an estimated count of transfered bytes downstream. The counter * is valid during the application run. * * @return byte count */ public synchronized static int getDownstreamDataCount() { return downstreamDataCount; } /** * Retrieves an estimated count of transfered bytes upstream. The counter is * valid during the application run. * * @return byte count */ public synchronized static int getUpstreamDataCount() { return upstreamDataCount; } /** * Clears the downstream data counter. */ public synchronized static void clearDownstreamDataCount() { downstreamDataCount = 0; } /** * Clears the upstream data counter. */ public synchronized static void clearUpstreamDataCount() { upstreamDataCount = 0; } /** * Accumulates the downstream data counter. * * @param byteCount */ protected synchronized static void addDownstreamDataCount(final int byteCount) { downstreamDataCount += byteCount; } /** * Accumulates the upstream data counter. * * @param byteCount */ protected synchronized static void addUpstreamDataCount(final int byteCount) { upstreamDataCount += byteCount; } //#mdebug public synchronized String toString() { final StringBuffer sb = new StringBuffer(); sb.append(super.toString()); sb.append(" retriesRemaining="); sb.append(retriesRemaining); sb.append(" postMessageLength="); if (postMessage == null) { sb.append("<null>"); } else { sb.append(postMessage.length); } if (requestPropertyKeys.isEmpty()) { sb.append(L.CRLF + "(default HTTP request, no customer header params)"); } else { sb.append(L.CRLF + "HTTP REQUEST CUSTOM HEADERS"); for (int i = 0; i < requestPropertyKeys.size(); i++) { final String key = (String) requestPropertyKeys.elementAt(i); sb.append(L.CRLF + " "); sb.append(key); sb.append(": "); final String value = (String) requestPropertyValues.elementAt(i); sb.append(value); } } if (responseCode == HTTP_OPERATION_PENDING) { sb.append(L.CRLF + "(http operation pending, no server response yet)"); } else { sb.append(L.CRLF + "serverHTTPResponseCode="); sb.append(responseCode); sb.append(L.CRLF + "HTTP RESPONSE HEADERS" + L.CRLF); sb.append(PlatformUtils.responseHeadersToString(responseHeaders)); } sb.append(L.CRLF); return sb.toString(); } //#enddebug }
false
true
public Object exec(final Object in) throws InterruptedException { staggerHeaderStartTime(); byte[] out = null; startTime = System.currentTimeMillis(); if (!(in instanceof String) || ((String) in).indexOf(':') <= 0) { final String s = "HTTP operation was passed a bad url=" + in + ". Check calling method or previous chained task: " + this; //#debug L.e("HttpGetter with non-String input", s, new IllegalArgumentException()); cancel(false, s); return out; } final String url = keyIncludingPostDataHashtoUrl((String) in); //#debug L.i(this, "Start", url); ByteArrayOutputStream bos = null; PlatformUtils.HttpConn httpConn = null; boolean tryAgain = false; boolean success = false; addUpstreamDataCount(url.length()); try { final OutputStream outputStream; if (this instanceof HttpPoster) { if (postMessage == null && streamWriter == null) { throw new IllegalArgumentException("null HTTP POST- did you forget to call httpPoster.setMessage(byte[]) ? : " + url); } httpConn = PlatformUtils.getInstance().getHttpPostConn(url, requestPropertyKeys, requestPropertyValues, postMessage); outputStream = httpConn.getOutputStream(); final StreamWriter writer = this.streamWriter; if (writer != null) { writer.writeReady(outputStream); success = true; } addUpstreamDataCount(postMessage.length); } else { httpConn = PlatformUtils.getInstance().getHttpGetConn(url, requestPropertyKeys, requestPropertyValues); } final InputStream inputStream = httpConn.getInputStream(); final StreamReader reader = streamReader; if (reader != null) { reader.readReady(inputStream); success = true; } // Estimate data length of the sent headers for (int i = 0; i < requestPropertyKeys.size(); i++) { addUpstreamDataCount(((String) requestPropertyKeys.elementAt(i)).length()); addUpstreamDataCount(((String) requestPropertyValues.elementAt(i)).length()); } final int length = (int) httpConn.getLength(); final int downstreamDataHeaderLength; synchronized (this) { responseCode = httpConn.getResponseCode(); httpConn.getResponseHeaders(responseHeaders); downstreamDataHeaderLength = PlatformUtils.responseHeadersToString(responseHeaders).length(); } // Response headers length estimation addDownstreamDataCount(downstreamDataHeaderLength); long firstByteTime = Long.MAX_VALUE; if (length == 0) { //#debug L.i(this, "Exec", "No response. Stream is null, or length is 0"); } else if (length > httpConn.getMaxLengthSupportedAsBlockOperation()) { cancel(false, "Http server sent Content-Length > " + httpConn.getMaxLengthSupportedAsBlockOperation() + " which might cause out-of-memory on this platform"); } else if (length > 0) { final byte[] bytes = new byte[length]; firstByteTime = readBytesFixedLength(url, inputStream, bytes); out = bytes; } else { bos = new ByteArrayOutputStream(OUTPUT_BUFFER_INITIAL_LENGTH); firstByteTime = readBytesVariableLength(inputStream, bos); out = bos.toByteArray(); } if (firstByteTime != Long.MAX_VALUE) { final long responseTime = firstByteTime - startTime; HttpGetter.averageResponseDelayMillis.update(responseTime); //#debug L.i(this, "Average HTTP header response time", HttpGetter.averageResponseDelayMillis.value() + " current=" + responseTime); } final long lastByteTime = System.currentTimeMillis(); final float baud; final int dataLength = ((byte[]) out).length; if (dataLength > 0 && lastByteTime > firstByteTime) { baud = (dataLength * 8 * 1000) / ((int) (lastByteTime - firstByteTime)); } else { baud = THRESHOLD_BAUD * 2; } HttpGetter.averageBaud.update(baud); //#debug L.i(this, "Average HTTP body read baud", HttpGetter.averageBaud.value() + " current=" + baud); if (out != null) { addDownstreamDataCount(dataLength); //#debug L.i(this, "End read", "url=" + url + " bytes=" + ((byte[]) out).length); } synchronized (this) { success = checkResponseCode(url, responseCode, responseHeaders); } //#debug L.i(this, "Response", "HTTP response code indicates success=" + success); } catch (IllegalArgumentException e) { //#debug L.e(this, "HttpGetter has illegal argument", url, e); throw e; } catch (IOException e) { //#debug L.e(this, "Retries remaining", url + ", retries=" + retriesRemaining, e); if (retriesRemaining > 0) { retriesRemaining--; tryAgain = true; } else { //#debug L.i(this, "No more retries", url); cancel(false, "No more retries"); } } finally { if (httpConn != null) { try { httpConn.close(); } catch (Exception e) { //#debug L.e(this, "Closing Http InputStream error", url, e); } finally { httpConn = null; } } try { if (bos != null) { bos.close(); } } catch (Exception e) { //#debug L.e(this, "HttpGetter byteArrayOutputStream close error", url, e); } finally { bos = null; } if (tryAgain) { try { Thread.sleep(HTTP_RETRY_DELAY); } catch (InterruptedException ex) { cancel(false, "Interrupted HttpGetter while sleeping between retries: " + this); } out = (byte[]) exec(url); } else if (!success) { //#debug L.i("HTTP GET FAILED, cancel() of task and any chained Tasks", this.toString()); cancel(false, "HttpGetter failed response code and header check: " + this.toString()); } //#debug L.i(this, "End", url + " status=" + getStatus() + " out=" + out); } if (!success) { return null; } return out; }
public Object exec(final Object in) throws InterruptedException { staggerHeaderStartTime(); byte[] out = null; startTime = System.currentTimeMillis(); if (!(in instanceof String) || ((String) in).indexOf(':') <= 0) { final String s = "HTTP operation was passed a bad url=" + in + ". Check calling method or previous chained task: " + this; //#debug L.e("HttpGetter with non-String input", s, new IllegalArgumentException()); cancel(false, s); return out; } final String url = keyIncludingPostDataHashtoUrl((String) in); //#debug L.i(this, "Start", url); ByteArrayOutputStream bos = null; PlatformUtils.HttpConn httpConn = null; boolean tryAgain = false; boolean success = false; addUpstreamDataCount(url.length()); try { final OutputStream outputStream; if (this instanceof HttpPoster) { if (postMessage == null && streamWriter == null) { throw new IllegalArgumentException("null HTTP POST- did you forget to call httpPoster.setMessage(byte[]) ? : " + url); } httpConn = PlatformUtils.getInstance().getHttpPostConn(url, requestPropertyKeys, requestPropertyValues, postMessage); outputStream = httpConn.getOutputStream(); final StreamWriter writer = this.streamWriter; if (writer != null) { writer.writeReady(outputStream); success = true; } addUpstreamDataCount(postMessage.length); } else { httpConn = PlatformUtils.getInstance().getHttpGetConn(url, requestPropertyKeys, requestPropertyValues); } final InputStream inputStream = httpConn.getInputStream(); final StreamReader reader = streamReader; if (reader != null) { reader.readReady(inputStream); success = true; } // Estimate data length of the sent headers for (int i = 0; i < requestPropertyKeys.size(); i++) { addUpstreamDataCount(((String) requestPropertyKeys.elementAt(i)).length()); addUpstreamDataCount(((String) requestPropertyValues.elementAt(i)).length()); } final int length = (int) httpConn.getLength(); final int downstreamDataHeaderLength; synchronized (this) { responseCode = httpConn.getResponseCode(); httpConn.getResponseHeaders(responseHeaders); downstreamDataHeaderLength = PlatformUtils.responseHeadersToString(responseHeaders).length(); } // Response headers length estimation addDownstreamDataCount(downstreamDataHeaderLength); long firstByteTime = Long.MAX_VALUE; if (length == 0) { //#debug L.i(this, "Exec", "No response. Stream is null, or length is 0"); } else if (length > httpConn.getMaxLengthSupportedAsBlockOperation()) { cancel(false, "Http server sent Content-Length > " + httpConn.getMaxLengthSupportedAsBlockOperation() + " which might cause out-of-memory on this platform"); } else if (length > 0) { final byte[] bytes = new byte[length]; firstByteTime = readBytesFixedLength(url, inputStream, bytes); out = bytes; } else { bos = new ByteArrayOutputStream(OUTPUT_BUFFER_INITIAL_LENGTH); firstByteTime = readBytesVariableLength(inputStream, bos); out = bos.toByteArray(); } if (firstByteTime != Long.MAX_VALUE) { final long responseTime = firstByteTime - startTime; HttpGetter.averageResponseDelayMillis.update(responseTime); //#debug L.i(this, "Average HTTP header response time", HttpGetter.averageResponseDelayMillis.value() + " current=" + responseTime); } final long lastByteTime = System.currentTimeMillis(); final float baud; int dataLength = 0; if (out != null) { dataLength = out.length; } if (dataLength > 0 && lastByteTime > firstByteTime) { baud = (dataLength * 8 * 1000) / ((int) (lastByteTime - firstByteTime)); } else { baud = THRESHOLD_BAUD * 2; } HttpGetter.averageBaud.update(baud); //#debug L.i(this, "Average HTTP body read baud", HttpGetter.averageBaud.value() + " current=" + baud); if (out != null) { addDownstreamDataCount(dataLength); //#debug L.i(this, "End read", "url=" + url + " bytes=" + ((byte[]) out).length); } synchronized (this) { success = checkResponseCode(url, responseCode, responseHeaders); } //#debug L.i(this, "Response", "HTTP response code indicates success=" + success); } catch (IllegalArgumentException e) { //#debug L.e(this, "HttpGetter has illegal argument", url, e); throw e; } catch (IOException e) { //#debug L.e(this, "Retries remaining", url + ", retries=" + retriesRemaining, e); if (retriesRemaining > 0) { retriesRemaining--; tryAgain = true; } else { //#debug L.i(this, "No more retries", url); cancel(false, "No more retries"); } } finally { if (httpConn != null) { try { httpConn.close(); } catch (Exception e) { //#debug L.e(this, "Closing Http InputStream error", url, e); } finally { httpConn = null; } } try { if (bos != null) { bos.close(); } } catch (Exception e) { //#debug L.e(this, "HttpGetter byteArrayOutputStream close error", url, e); } finally { bos = null; } if (tryAgain) { try { Thread.sleep(HTTP_RETRY_DELAY); } catch (InterruptedException ex) { cancel(false, "Interrupted HttpGetter while sleeping between retries: " + this); } out = (byte[]) exec(url); } else if (!success) { //#debug L.i("HTTP GET FAILED, cancel() of task and any chained Tasks", (this != null ? this.toString() : "null")); cancel(false, "HttpGetter failed response code and header check: " + this); } //#debug L.i(this, "End", url + " status=" + getStatus() + " out=" + out); } if (!success) { return null; } return out; }
diff --git a/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/businessprocess/treeoperations/FindResponsibleNodesForComponentNameOp.java b/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/businessprocess/treeoperations/FindResponsibleNodesForComponentNameOp.java index afedb2953..fc05d7523 100644 --- a/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/businessprocess/treeoperations/FindResponsibleNodesForComponentNameOp.java +++ b/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/businessprocess/treeoperations/FindResponsibleNodesForComponentNameOp.java @@ -1,63 +1,67 @@ /******************************************************************************* * Copyright (c) 2004, 2010 BREDEX GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * BREDEX GmbH - initial API and implementation and/or initial documentation *******************************************************************************/ package org.eclipse.jubula.client.core.businessprocess.treeoperations; import org.eclipse.jubula.client.core.businessprocess.CompNameResult; import org.eclipse.jubula.client.core.businessprocess.CompNamesBP; import org.eclipse.jubula.client.core.businessprocess.ComponentNamesBP; import org.eclipse.jubula.client.core.model.ICapPO; import org.eclipse.jubula.client.core.model.INodePO; import org.eclipse.jubula.client.core.persistence.Hibernator; import org.eclipse.jubula.client.core.utils.ITreeTraverserContext; /** * Operation for finding all nodes that are responsible for a specific Component * Name in the OME. * * @author BREDEX GmbH * @created Aug 30, 2010 */ public class FindResponsibleNodesForComponentNameOp extends FindNodesForComponentNameOp { /** * <code>m_compNameBP</code> */ private CompNamesBP m_compNameBP = null; /** * Constructor * * @param compNameGuid The GUID of the Component Name to use for this * operation. */ public FindResponsibleNodesForComponentNameOp(String compNameGuid) { super(compNameGuid); m_compNameBP = new CompNamesBP(); } /** * {@inheritDoc} */ public boolean operate(ITreeTraverserContext<INodePO> ctx, INodePO parent, INodePO node, boolean alreadyVisited) { if (Hibernator.isPoSubclass(node, ICapPO.class)) { final ICapPO cap = (ICapPO)node; CompNameResult result = m_compNameBP.findCompName(ctx.getCurrentTreePath(), cap, cap.getComponentName(), ComponentNamesBP.getInstance()); if (getCompNameGuid().equals(result.getCompName())) { - getNodes().add(result.getResponsibleNode()); + INodePO responsibleNode = result.getResponsibleNode(); + if (Hibernator.isPoSubclass(responsibleNode, ICapPO.class)) { + getNodes().add(parent); + } + getNodes().add(responsibleNode); } } return true; } }
true
true
public boolean operate(ITreeTraverserContext<INodePO> ctx, INodePO parent, INodePO node, boolean alreadyVisited) { if (Hibernator.isPoSubclass(node, ICapPO.class)) { final ICapPO cap = (ICapPO)node; CompNameResult result = m_compNameBP.findCompName(ctx.getCurrentTreePath(), cap, cap.getComponentName(), ComponentNamesBP.getInstance()); if (getCompNameGuid().equals(result.getCompName())) { getNodes().add(result.getResponsibleNode()); } } return true; }
public boolean operate(ITreeTraverserContext<INodePO> ctx, INodePO parent, INodePO node, boolean alreadyVisited) { if (Hibernator.isPoSubclass(node, ICapPO.class)) { final ICapPO cap = (ICapPO)node; CompNameResult result = m_compNameBP.findCompName(ctx.getCurrentTreePath(), cap, cap.getComponentName(), ComponentNamesBP.getInstance()); if (getCompNameGuid().equals(result.getCompName())) { INodePO responsibleNode = result.getResponsibleNode(); if (Hibernator.isPoSubclass(responsibleNode, ICapPO.class)) { getNodes().add(parent); } getNodes().add(responsibleNode); } } return true; }
diff --git a/src/state/Factory_PartB.java b/src/state/Factory_PartB.java index d4bdc37..059667c 100644 --- a/src/state/Factory_PartB.java +++ b/src/state/Factory_PartB.java @@ -1,86 +1,86 @@ package state; import agents.*; import gui.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.util.ArrayList; import java.util.HashMap; import javax.swing.*; public class Factory_PartB extends JFrame implements ActionListener { static final int WIDTH = 800; static final int HEIGHT = 600; // GUI Elements CardLayout cards; final Rectangle2D.Double bkgrnd = new Rectangle2D.Double(0, 0, WIDTH, HEIGHT); // Classes that do stuff public GUI_PartRobot partRobot; public ArrayList<GUI_Part> guiPartList; public ArrayList<GUI_Nest> guiNestList; public ArrayList<GUI_Component> compList; public GUI_KitStand guiKitStand; public Factory_PartB() { //Setup member variables guiNestList = new ArrayList<GUI_Nest>(8); guiPartList = new ArrayList<GUI_Part>(); compList = new ArrayList<GUI_Component>(); partRobot = new GUI_PartRobot(this); compList.add(partRobot); for(int i=0; i<8; i++) { - GUI_Nest n = new GUI_Nest(i, (i/4) * 120 + 150, (i%4) * 120 + 75); + GUI_Nest n = new GUI_Nest(i, (i/4) * 120 + 400, (i%4) * 120 + 75); guiNestList.add(n); compList.add(n); } //Setup this (Factory_PartB) this.setContentPane(new JPanel() { public void paint(Graphics g) { // called upon app.repaint() in Game class Graphics2D g2D = (Graphics2D) g; g2D.setColor(new Color(230, 230, 230)); g2D.fill(bkgrnd); // CALLS ALL paintComponent methods of components to be displayed for(GUI_Component c : compList) c.paintComponent(this, g2D); } }); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(WIDTH, HEIGHT); this.setResizable(false); this.setTitle("Nemo Factory v0 Part B"); this.setVisible(true); } public void doPickUpParts(HashMap<Part, Integer> parts) { ArrayList<GUI_Part> partsToGet = new ArrayList<GUI_Part>(); ArrayList<Integer> nestIndices = new ArrayList<Integer>(); for (GUI_Part gp : guiPartList) { if (parts.containsKey(gp.agentPart)) { partsToGet.add(gp); nestIndices.add(parts.get(gp.agentPart)); } } partRobot.doTransferParts(partsToGet, nestIndices); } public static void main(String[] args) { Factory_PartB app = new Factory_PartB(); new Timer(15, app).start(); } public void actionPerformed(ActionEvent ae) { // This will be called by the Timer // CALLS ALL updateGraphics methods of components to be displayed partRobot.updateGraphics(); this.repaint(); } }
true
true
public Factory_PartB() { //Setup member variables guiNestList = new ArrayList<GUI_Nest>(8); guiPartList = new ArrayList<GUI_Part>(); compList = new ArrayList<GUI_Component>(); partRobot = new GUI_PartRobot(this); compList.add(partRobot); for(int i=0; i<8; i++) { GUI_Nest n = new GUI_Nest(i, (i/4) * 120 + 150, (i%4) * 120 + 75); guiNestList.add(n); compList.add(n); } //Setup this (Factory_PartB) this.setContentPane(new JPanel() { public void paint(Graphics g) { // called upon app.repaint() in Game class Graphics2D g2D = (Graphics2D) g; g2D.setColor(new Color(230, 230, 230)); g2D.fill(bkgrnd); // CALLS ALL paintComponent methods of components to be displayed for(GUI_Component c : compList) c.paintComponent(this, g2D); } }); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(WIDTH, HEIGHT); this.setResizable(false); this.setTitle("Nemo Factory v0 Part B"); this.setVisible(true); }
public Factory_PartB() { //Setup member variables guiNestList = new ArrayList<GUI_Nest>(8); guiPartList = new ArrayList<GUI_Part>(); compList = new ArrayList<GUI_Component>(); partRobot = new GUI_PartRobot(this); compList.add(partRobot); for(int i=0; i<8; i++) { GUI_Nest n = new GUI_Nest(i, (i/4) * 120 + 400, (i%4) * 120 + 75); guiNestList.add(n); compList.add(n); } //Setup this (Factory_PartB) this.setContentPane(new JPanel() { public void paint(Graphics g) { // called upon app.repaint() in Game class Graphics2D g2D = (Graphics2D) g; g2D.setColor(new Color(230, 230, 230)); g2D.fill(bkgrnd); // CALLS ALL paintComponent methods of components to be displayed for(GUI_Component c : compList) c.paintComponent(this, g2D); } }); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(WIDTH, HEIGHT); this.setResizable(false); this.setTitle("Nemo Factory v0 Part B"); this.setVisible(true); }
diff --git a/src/main/java/jawher/moulder/moulds/AttrModifier.java b/src/main/java/jawher/moulder/moulds/AttrModifier.java index ecb8bcb..2f978f4 100644 --- a/src/main/java/jawher/moulder/moulds/AttrModifier.java +++ b/src/main/java/jawher/moulder/moulds/AttrModifier.java @@ -1,75 +1,77 @@ package jawher.moulder.moulds; import java.util.ArrayList; import java.util.List; import jawher.moulder.ElementAndData; import jawher.moulder.Moulder; import jawher.moulder.MoulderUtils; import jawher.moulder.NodeAndData; import jawher.moulder.Value; import jawher.moulder.values.SimpleValue; /** * A moulder that adds/modifies/removes an attribute to its input element * * @author jawher * */ public class AttrModifier implements Moulder { private Value<String> attr; private Value<String> value; /** * * @param attr * a value that returns the attribute name * @param value * a value that returns the attribute's value. If null is * supplied, or if <code>value</code> generates a null value, the * attribute is removed from the input element */ public AttrModifier(Value<String> attr, Value<String> value) { this.attr = attr; this.value = value; } /** * A variant of {@link #AttrModifier(Value, Value)} that wraps the * <code>attr</code> argument in a {@link SimpleValue} * * @param attr * @param value */ public AttrModifier(String attr, Value<String> value) { this(new SimpleValue<String>(attr), value); } /** * A variant of {@link #AttrModifier(Value, Value)} that wraps the * <code>attr</code> and <code>value</code> arguments in {@link SimpleValue} * * @param attr * @param value */ public AttrModifier(String attr, String value) { this(new SimpleValue<String>(attr), new SimpleValue<String>(value)); } public List<NodeAndData> process(ElementAndData nd, MoulderUtils f) { attr.bind(nd); - value.bind(nd); + if (value != null) { + value.bind(nd); + } List<NodeAndData> res = new ArrayList<NodeAndData>(); String attr = this.attr.get(); if (attr != null) { String value = this.value == null ? null : this.value.get(); if (value == null) { nd.node.removeAttr(attr); } else { nd.node.attr(attr, value); } } res.add(nd.toNodeAndData()); return res; } }
true
true
public List<NodeAndData> process(ElementAndData nd, MoulderUtils f) { attr.bind(nd); value.bind(nd); List<NodeAndData> res = new ArrayList<NodeAndData>(); String attr = this.attr.get(); if (attr != null) { String value = this.value == null ? null : this.value.get(); if (value == null) { nd.node.removeAttr(attr); } else { nd.node.attr(attr, value); } } res.add(nd.toNodeAndData()); return res; }
public List<NodeAndData> process(ElementAndData nd, MoulderUtils f) { attr.bind(nd); if (value != null) { value.bind(nd); } List<NodeAndData> res = new ArrayList<NodeAndData>(); String attr = this.attr.get(); if (attr != null) { String value = this.value == null ? null : this.value.get(); if (value == null) { nd.node.removeAttr(attr); } else { nd.node.attr(attr, value); } } res.add(nd.toNodeAndData()); return res; }
diff --git a/src/main/java/com/minecraftdimensions/bungeesuite/managers/BansManager.java b/src/main/java/com/minecraftdimensions/bungeesuite/managers/BansManager.java index 50db83b..f1fa304 100644 --- a/src/main/java/com/minecraftdimensions/bungeesuite/managers/BansManager.java +++ b/src/main/java/com/minecraftdimensions/bungeesuite/managers/BansManager.java @@ -1,269 +1,269 @@ package com.minecraftdimensions.bungeesuite.managers; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import com.minecraftdimensions.bungeesuite.Utilities; import com.minecraftdimensions.bungeesuite.configs.BansConfig; import com.minecraftdimensions.bungeesuite.objects.BSPlayer; import com.minecraftdimensions.bungeesuite.objects.Ban; import com.minecraftdimensions.bungeesuite.objects.Messages; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; public class BansManager { public static boolean isPlayerBanned(String player) { return SQLManager .existanceQuery("SELECT player FROM BungeeBans WHERE player='" + player + "'"); } public static void banPlayer(String bannedBy, String player, String reason) throws SQLException{ BSPlayer p = PlayerManager.getPlayer(bannedBy); BSPlayer t = PlayerManager.getSimilarPlayer(player); if(t!=null){ player = t.getName(); } if(!PlayerManager.playerExists(player)){ p.sendMessage(Messages.PLAYER_DOES_NOT_EXIST); return; } if(isPlayerBanned(player)){ p.sendMessage(Messages.PLAYER_ALREADY_BANNED); return; } if(reason.equals("")){ reason = Messages.DEFAULT_BAN_REASON; } SQLManager.standardQuery("INSERT INTO BungeeBans (player,banned_by,reason,type,banned_on) VALUES ('"+player+"','"+bannedBy+"','"+reason+"','ban',NOW())"); if(PlayerManager.isPlayerOnline(player)){ disconnectPlayer(player,Messages.BAN_PLAYER_MESSAGE.replace("{message}", reason).replace("{sender}", bannedBy)); } if(BansConfig.broadcastBans){ PlayerManager.sendBroadcast(Messages.BAN_PLAYER_BROADCAST.replace("{player}", player).replace("{message}", reason).replace("{sender}", bannedBy)); }else{ p.sendMessage(Messages.BAN_PLAYER_BROADCAST.replace("{player}", player).replace("{message}", reason).replace("{sender}", bannedBy)); } } public static String getPlayersIP(String player) throws SQLException{ return PlayerManager.getPlayersIP(player); } public static void unbanPlayer(String sender,String player) throws SQLException { if(!PlayerManager.playerExists(player)){ PlayerManager.sendMessageToPlayer(sender, Messages.PLAYER_DOES_NOT_EXIST); return; } if(!isPlayerBanned(player)){ PlayerManager.sendMessageToPlayer(sender, Messages.PLAYER_NOT_BANNED); return; } SQLManager.standardQuery("DELETE FROM BungeeBans WHERE player ='"+player+"'"); if(BansConfig.broadcastBans){ PlayerManager.sendBroadcast(Messages.PLAYER_UNBANNED.replace("{player}", player).replace("{sender}", sender)); }else{ PlayerManager.sendMessageToPlayer(sender,Messages.PLAYER_UNBANNED.replace("{player}", player).replace("{sender}", sender)); } } public static void banIP(String bannedBy, String player, String reason) throws SQLException { if(reason.equals("")){ reason = Messages.DEFAULT_BAN_REASON; } ArrayList<String> accounts = null; if(Utilities.isIPAddress(player)){ accounts = PlayerManager.getPlayersAltAccountsByIP(player); }else{ accounts = PlayerManager.getPlayersAltAccounts(player); } for(String a: accounts){ if(!isPlayerBanned(a)){ SQLManager.standardQuery("INSERT INTO BungeeBans VALUES ('"+a+"', '"+bannedBy+"', '"+reason+"', 'ipban', NOW(), NULL)"); }else{ SQLManager.standardQuery("UPDATE BungeeBans SET type='ipban' WHERE player ='"+a+"')"); } if(PlayerManager.isPlayerOnline(a)){ disconnectPlayer(a,Messages.IPBAN_PLAYER.replace("{message}", reason).replace("{sender}", bannedBy)); } } if(BansConfig.broadcastBans){ PlayerManager.sendBroadcast(Messages.IPBAN_PLAYER_BROADCAST.replace("{player}", player).replace("{message}", reason).replace("{sender}", bannedBy)); }else{ PlayerManager.sendMessageToPlayer(bannedBy, Messages.IPBAN_PLAYER_BROADCAST.replace("{player}", player).replace("{message}", reason).replace("{sender}", bannedBy)); } } public static void unbanIP(String player, String sender) throws SQLException { if(!Utilities.isIPAddress(player)){ player=PlayerManager.getPlayersIP(player); } SQLManager.standardQuery("DELETE BungeeBans FROM BungeeBans INNER JOIN BungeePlayers ON BungeeBans.player = BungeePlayers.playername WHERE BungeePlayers.ipaddress = '"+player+"'"); if(BansConfig.broadcastBans){ PlayerManager.sendBroadcast(Messages.PLAYER_UNBANNED.replace("{player}", player).replace("{sender}", sender)); }else{ PlayerManager.sendMessageToPlayer(sender,Messages.PLAYER_UNBANNED.replace("{player}", player).replace("{sender}", sender)); } } public static void kickAll(String sender, String message) { if(message.equals("")){ message = Messages.DEFAULT_KICK_MESSAGE; } message = Messages.KICK_PLAYER_MESSAGE.replace("{message}", message).replace("{sender}", sender); for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) { disconnectPlayer(p, message); } } public static Ban getBanInfo(String player) throws SQLException { Ban b = null; ResultSet res =SQLManager.sqlQuery("SELECT * FROM BungeeBans WHERE player = '"+player+"'"); while (res.next()){ b = new Ban(res.getString("player"), res.getString("banned_by"), res.getString("reason"), res.getString("type"), res.getTimestamp("banned_on"), res.getTimestamp("banned_until")); } res.close(); return b; } public static void checkPlayersBan(String sender, String player) throws SQLException{ BSPlayer p = PlayerManager.getPlayer(sender); Ban b = getBanInfo(player); if(b==null){ p.sendMessage(Messages.PLAYER_NOT_BANNED); return; }else{ SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern("dd MMM yyyy HH:mm:ss z"); p.sendMessage(ChatColor.DARK_AQUA+"--------"+ChatColor.DARK_RED+"Ban Info"+ChatColor.DARK_AQUA+"--------"); p.sendMessage(ChatColor.RED+"Player: "+ChatColor.AQUA+b.getPlayer()); p.sendMessage(ChatColor.RED+"Ban type: "+ChatColor.AQUA+b.getType()); p.sendMessage(ChatColor.RED+"Banned by: "+ChatColor.AQUA+b.getBannedBy()); p.sendMessage(ChatColor.RED+"Ban reason: "+ChatColor.AQUA+b.getReasaon()); p.sendMessage(ChatColor.RED+"Bannned on: "+ChatColor.AQUA+sdf.format(b.getBannedOn())); if(b.getBannedUntil()==null){ p.sendMessage(ChatColor.RED+"Bannned until: "+ChatColor.AQUA+"-Forever-"); }else{ p.sendMessage(ChatColor.RED+"Bannned until: "+ChatColor.AQUA+sdf.format(b.getBannedUntil())); } } } public static void kickPlayer(String sender, String player, String reason) { if(reason.equals("")){ reason = Messages.DEFAULT_KICK_MESSAGE; } BSPlayer p = PlayerManager.getPlayer(sender); BSPlayer t = PlayerManager.getSimilarPlayer(player); if(t==null){ p.sendMessage(Messages.PLAYER_NOT_ONLINE); return; } player = PlayerManager.getSimilarPlayer(player).getName(); if(PlayerManager.isPlayerOnline(player)){ disconnectPlayer(t.getName(),Messages.KICK_PLAYER_MESSAGE.replace("{message}", reason).replace("{sender}", sender)); if(BansConfig.broadcastKicks){ PlayerManager.sendBroadcast(Messages.KICK_PLAYER_BROADCAST.replace("{message}", reason).replace("{player}", t.getName()).replace("{sender}", sender)); } } } public static void disconnectPlayer(ProxiedPlayer player, String message) { player.disconnect(message); } public static void disconnectPlayer(String player, String message) { ProxyServer.getInstance().getPlayer(player).disconnect(message); } public static void disconnectPlayer(BSPlayer player, String message) { player.getProxiedPlayer().disconnect(message); } public ArrayList<String> getAltAccounts(String player) throws SQLException { return PlayerManager.getPlayersAltAccounts(player); } public ArrayList<String> getBannedAltAccounts(String player) throws SQLException { ArrayList<String> accounts = getAltAccounts(player); boolean check = false; for(String p :getAltAccounts(player)){ if(isPlayerBanned(p)){ check = true; String newPlayer = ChatColor.DARK_RED+"[Banned] "+p; p = newPlayer; } } if(check){ return accounts; }else{ return null; } } public static void reloadBans(String sender) { PlayerManager.getPlayer(sender).sendMessage("Bans Reloaded"); BansConfig.reloadBans(); } public static void tempBanPlayer(String sender, String player, int minute, int hour, int day, String message) throws SQLException { BSPlayer p = PlayerManager.getPlayer(sender); BSPlayer t = PlayerManager.getSimilarPlayer(player); if(t!=null){ player = t.getName(); } if(!PlayerManager.playerExists(player)){ p.sendMessage(Messages.PLAYER_DOES_NOT_EXIST); return; } if(isPlayerBanned(player)){ p.sendMessage(Messages.PLAYER_ALREADY_BANNED); return; } if(message.equals("")){ message = Messages.DEFAULT_BAN_REASON; } Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, minute); cal.add(Calendar.HOUR_OF_DAY, hour); cal.add(Calendar.DATE, day); Date sqlToday = new Date(cal.getTimeInMillis()); SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern("dd MMM yyyy HH:mm:ss"); - String time = sdf.format(sqlToday+ "("+day+" days, "+hour+" hours, "+minute+ " minutes)"); + String time = sdf.format(sqlToday)+"("+day+" days, "+hour+" hours, "+minute+ " minutes)"; sdf.applyPattern("yyyy-MM-dd HH:mm:ss"); SQLManager.standardQuery("INSERT INTO BungeeBans (player,banned_by,reason,type,banned_on,banned_until) VALUES('"+player+"','"+sender+"','"+message+"','tempban',NOW(),'"+sdf.format(sqlToday)+"')"); if(t!=null){ disconnectPlayer(t.getName(),Messages.TEMP_BAN_MESSAGE.replace("{sender}", p.getName()).replace("{time}", time).replace("{message}", message)); } if(BansConfig.broadcastBans){ PlayerManager.sendBroadcast(Messages.TEMP_BAN_BROADCAST.replace("{player}", player).replace("{sender}", p.getName()).replace("{message}", message).replace("{time}", time)); }else{ p.sendMessage(Messages.TEMP_BAN_BROADCAST.replace("{player}", player).replace("{sender}", p.getName()).replace("{message}", message).replace("{time}", time)); } } public static boolean checkTempBan(Ban b) throws SQLException { java.util.Date today = new java.util.Date(Calendar.getInstance().getTimeInMillis()); java.util.Date banned = b.getBannedUntil(); if(today.compareTo(banned)>=0){ SQLManager.standardQuery("DELETE FROM BungeeBans WHERE player = '"+b.getPlayer()+"'"); return false; } return true; } }
true
true
public static void tempBanPlayer(String sender, String player, int minute, int hour, int day, String message) throws SQLException { BSPlayer p = PlayerManager.getPlayer(sender); BSPlayer t = PlayerManager.getSimilarPlayer(player); if(t!=null){ player = t.getName(); } if(!PlayerManager.playerExists(player)){ p.sendMessage(Messages.PLAYER_DOES_NOT_EXIST); return; } if(isPlayerBanned(player)){ p.sendMessage(Messages.PLAYER_ALREADY_BANNED); return; } if(message.equals("")){ message = Messages.DEFAULT_BAN_REASON; } Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, minute); cal.add(Calendar.HOUR_OF_DAY, hour); cal.add(Calendar.DATE, day); Date sqlToday = new Date(cal.getTimeInMillis()); SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern("dd MMM yyyy HH:mm:ss"); String time = sdf.format(sqlToday+ "("+day+" days, "+hour+" hours, "+minute+ " minutes)"); sdf.applyPattern("yyyy-MM-dd HH:mm:ss"); SQLManager.standardQuery("INSERT INTO BungeeBans (player,banned_by,reason,type,banned_on,banned_until) VALUES('"+player+"','"+sender+"','"+message+"','tempban',NOW(),'"+sdf.format(sqlToday)+"')"); if(t!=null){ disconnectPlayer(t.getName(),Messages.TEMP_BAN_MESSAGE.replace("{sender}", p.getName()).replace("{time}", time).replace("{message}", message)); } if(BansConfig.broadcastBans){ PlayerManager.sendBroadcast(Messages.TEMP_BAN_BROADCAST.replace("{player}", player).replace("{sender}", p.getName()).replace("{message}", message).replace("{time}", time)); }else{ p.sendMessage(Messages.TEMP_BAN_BROADCAST.replace("{player}", player).replace("{sender}", p.getName()).replace("{message}", message).replace("{time}", time)); } }
public static void tempBanPlayer(String sender, String player, int minute, int hour, int day, String message) throws SQLException { BSPlayer p = PlayerManager.getPlayer(sender); BSPlayer t = PlayerManager.getSimilarPlayer(player); if(t!=null){ player = t.getName(); } if(!PlayerManager.playerExists(player)){ p.sendMessage(Messages.PLAYER_DOES_NOT_EXIST); return; } if(isPlayerBanned(player)){ p.sendMessage(Messages.PLAYER_ALREADY_BANNED); return; } if(message.equals("")){ message = Messages.DEFAULT_BAN_REASON; } Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, minute); cal.add(Calendar.HOUR_OF_DAY, hour); cal.add(Calendar.DATE, day); Date sqlToday = new Date(cal.getTimeInMillis()); SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern("dd MMM yyyy HH:mm:ss"); String time = sdf.format(sqlToday)+"("+day+" days, "+hour+" hours, "+minute+ " minutes)"; sdf.applyPattern("yyyy-MM-dd HH:mm:ss"); SQLManager.standardQuery("INSERT INTO BungeeBans (player,banned_by,reason,type,banned_on,banned_until) VALUES('"+player+"','"+sender+"','"+message+"','tempban',NOW(),'"+sdf.format(sqlToday)+"')"); if(t!=null){ disconnectPlayer(t.getName(),Messages.TEMP_BAN_MESSAGE.replace("{sender}", p.getName()).replace("{time}", time).replace("{message}", message)); } if(BansConfig.broadcastBans){ PlayerManager.sendBroadcast(Messages.TEMP_BAN_BROADCAST.replace("{player}", player).replace("{sender}", p.getName()).replace("{message}", message).replace("{time}", time)); }else{ p.sendMessage(Messages.TEMP_BAN_BROADCAST.replace("{player}", player).replace("{sender}", p.getName()).replace("{message}", message).replace("{time}", time)); } }
diff --git a/core/src/main/java/org/bouncycastle/crypto/tls/ProtocolVersion.java b/core/src/main/java/org/bouncycastle/crypto/tls/ProtocolVersion.java index b32bd9d3e..a87d93412 100644 --- a/core/src/main/java/org/bouncycastle/crypto/tls/ProtocolVersion.java +++ b/core/src/main/java/org/bouncycastle/crypto/tls/ProtocolVersion.java @@ -1,125 +1,131 @@ package org.bouncycastle.crypto.tls; import java.io.IOException; public final class ProtocolVersion { public static final ProtocolVersion SSLv3 = new ProtocolVersion(0x0300, "SSL 3.0"); public static final ProtocolVersion TLSv10 = new ProtocolVersion(0x0301, "TLS 1.0"); public static final ProtocolVersion TLSv11 = new ProtocolVersion(0x0302, "TLS 1.1"); public static final ProtocolVersion TLSv12 = new ProtocolVersion(0x0303, "TLS 1.2"); public static final ProtocolVersion DTLSv10 = new ProtocolVersion(0xFEFF, "DTLS 1.0"); public static final ProtocolVersion DTLSv12 = new ProtocolVersion(0xFEFD, "DTLS 1.2"); private int version; private String name; private ProtocolVersion(int v, String name) { this.version = v & 0xffff; this.name = name; } public int getFullVersion() { return version; } public int getMajorVersion() { return version >> 8; } public int getMinorVersion() { return version & 0xff; } public boolean isDTLS() { return getMajorVersion() == 0xFE; } public boolean isSSL() { return this == SSLv3; } public ProtocolVersion getEquivalentTLSVersion() { if (!isDTLS()) { return this; } if (this == DTLSv10) { return TLSv11; } return TLSv12; } public boolean isEqualOrEarlierVersionOf(ProtocolVersion version) { if (getMajorVersion() != version.getMajorVersion()) { return false; } int diffMinorVersion = version.getMinorVersion() - getMinorVersion(); return isDTLS() ? diffMinorVersion <= 0 : diffMinorVersion >= 0; } public boolean isLaterVersionOf(ProtocolVersion version) { if (getMajorVersion() != version.getMajorVersion()) { return false; } int diffMinorVersion = version.getMinorVersion() - getMinorVersion(); return isDTLS() ? diffMinorVersion > 0 : diffMinorVersion < 0; } public boolean equals(Object obj) { return this == obj; } public int hashCode() { return version; } public static ProtocolVersion get(int major, int minor) throws IOException { switch (major) { case 0x03: + { switch (minor) { case 0x00: return SSLv3; case 0x01: return TLSv10; case 0x02: return TLSv11; case 0x03: return TLSv12; } + break; + } case 0xFE: + { switch (minor) { case 0xFF: return DTLSv10; case 0xFD: return DTLSv12; } + break; + } } throw new TlsFatalAlert(AlertDescription.illegal_parameter); } public String toString() { return name; } }
false
true
public static ProtocolVersion get(int major, int minor) throws IOException { switch (major) { case 0x03: switch (minor) { case 0x00: return SSLv3; case 0x01: return TLSv10; case 0x02: return TLSv11; case 0x03: return TLSv12; } case 0xFE: switch (minor) { case 0xFF: return DTLSv10; case 0xFD: return DTLSv12; } } throw new TlsFatalAlert(AlertDescription.illegal_parameter); }
public static ProtocolVersion get(int major, int minor) throws IOException { switch (major) { case 0x03: { switch (minor) { case 0x00: return SSLv3; case 0x01: return TLSv10; case 0x02: return TLSv11; case 0x03: return TLSv12; } break; } case 0xFE: { switch (minor) { case 0xFF: return DTLSv10; case 0xFD: return DTLSv12; } break; } } throw new TlsFatalAlert(AlertDescription.illegal_parameter); }
diff --git a/src/com/guntherdw/bukkit/tweakcraft/Commands/General/CommandWhois.java b/src/com/guntherdw/bukkit/tweakcraft/Commands/General/CommandWhois.java index b173e4e..97612d0 100644 --- a/src/com/guntherdw/bukkit/tweakcraft/Commands/General/CommandWhois.java +++ b/src/com/guntherdw/bukkit/tweakcraft/Commands/General/CommandWhois.java @@ -1,94 +1,94 @@ /* * Copyright (c) 2011 GuntherDW * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.guntherdw.bukkit.tweakcraft.Commands.General; import com.guntherdw.bukkit.tweakcraft.Commands.Command; import com.guntherdw.bukkit.tweakcraft.Exceptions.CommandException; import com.guntherdw.bukkit.tweakcraft.Exceptions.CommandSenderException; import com.guntherdw.bukkit.tweakcraft.Exceptions.CommandUsageException; import com.guntherdw.bukkit.tweakcraft.Exceptions.PermissionsException; import com.guntherdw.bukkit.tweakcraft.TweakcraftUtils; import com.nijiko.permissions.Group; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; /** * @author GuntherDW */ public class CommandWhois implements Command { @Override public boolean executeCommand(CommandSender sender, String command, String[] args, TweakcraftUtils plugin) throws PermissionsException, CommandSenderException, CommandUsageException, CommandException { // First search for a nick Boolean getIP = true; if(sender instanceof Player) { if(!plugin.check((Player)sender, "whois")) throw new PermissionsException(command); if(!plugin.check((Player)sender, "whois.ip")) getIP = false; } if(args.length==1) { Player nick = plugin.getPlayerListener().findPlayerByNick(args[0]); // sender.sendMessage(nick.toString()); String gname = null; Group g = null; Player sp = findPlayer(args[0], plugin); Player who = nick==null?sp:nick; if(who != null) { // g = plugin.getPermissionHandler().getGroupObject(who.getWorld().getName(), plugin.getPermissionHandler().getPrimaryGroup(who.getWorld().getName(), who.getName())); gname = plugin.getPermissionHandler().getPrimaryGroup(who.getWorld().getName(), who.getName()); g = plugin.getPermissionHandler().getGroupObject(who.getWorld().getName(), gname); sender.sendMessage(ChatColor.YELLOW+"Playername : "+who.getName()+" "+(nick!=null?"("+plugin.getNickWithColors(who.getName())+ChatColor.YELLOW+")":"")); // String group = plugin.getPermissionHandler.getG(who.getWorld().getName(), who.getName()); sender.sendMessage(ChatColor.YELLOW+"Group : "+g.getName()); if(!getIP && sender instanceof Player) { if(((Player)sender).getName().equalsIgnoreCase(who.getName())) getIP = true; } if(getIP) - sender.sendMessage(ChatColor.YELLOW + "IP: " + who.getAddress().getAddress().getHostName() + " (" + who.getAddress().getAddress().toString() + ")"); + sender.sendMessage(ChatColor.YELLOW + "IP: " + who.getAddress().getAddress().getHostName()); } else { throw new CommandException("Can't find player!"); } } else { throw new CommandUsageException("I need a player!"); } return true; } @Override public String getPermissionSuffix() { return "whois"; //To change body of implemented methods use File | Settings | File Templates. } public Player findPlayer(String playername, TweakcraftUtils plugin) { for(Player p : plugin.getServer().matchPlayer(playername)) { if(p.getName().toLowerCase().contains(playername.toLowerCase())) { return p; } } return null; } }
true
true
public boolean executeCommand(CommandSender sender, String command, String[] args, TweakcraftUtils plugin) throws PermissionsException, CommandSenderException, CommandUsageException, CommandException { // First search for a nick Boolean getIP = true; if(sender instanceof Player) { if(!plugin.check((Player)sender, "whois")) throw new PermissionsException(command); if(!plugin.check((Player)sender, "whois.ip")) getIP = false; } if(args.length==1) { Player nick = plugin.getPlayerListener().findPlayerByNick(args[0]); // sender.sendMessage(nick.toString()); String gname = null; Group g = null; Player sp = findPlayer(args[0], plugin); Player who = nick==null?sp:nick; if(who != null) { // g = plugin.getPermissionHandler().getGroupObject(who.getWorld().getName(), plugin.getPermissionHandler().getPrimaryGroup(who.getWorld().getName(), who.getName())); gname = plugin.getPermissionHandler().getPrimaryGroup(who.getWorld().getName(), who.getName()); g = plugin.getPermissionHandler().getGroupObject(who.getWorld().getName(), gname); sender.sendMessage(ChatColor.YELLOW+"Playername : "+who.getName()+" "+(nick!=null?"("+plugin.getNickWithColors(who.getName())+ChatColor.YELLOW+")":"")); // String group = plugin.getPermissionHandler.getG(who.getWorld().getName(), who.getName()); sender.sendMessage(ChatColor.YELLOW+"Group : "+g.getName()); if(!getIP && sender instanceof Player) { if(((Player)sender).getName().equalsIgnoreCase(who.getName())) getIP = true; } if(getIP) sender.sendMessage(ChatColor.YELLOW + "IP: " + who.getAddress().getAddress().getHostName() + " (" + who.getAddress().getAddress().toString() + ")"); } else { throw new CommandException("Can't find player!"); } } else { throw new CommandUsageException("I need a player!"); } return true; }
public boolean executeCommand(CommandSender sender, String command, String[] args, TweakcraftUtils plugin) throws PermissionsException, CommandSenderException, CommandUsageException, CommandException { // First search for a nick Boolean getIP = true; if(sender instanceof Player) { if(!plugin.check((Player)sender, "whois")) throw new PermissionsException(command); if(!plugin.check((Player)sender, "whois.ip")) getIP = false; } if(args.length==1) { Player nick = plugin.getPlayerListener().findPlayerByNick(args[0]); // sender.sendMessage(nick.toString()); String gname = null; Group g = null; Player sp = findPlayer(args[0], plugin); Player who = nick==null?sp:nick; if(who != null) { // g = plugin.getPermissionHandler().getGroupObject(who.getWorld().getName(), plugin.getPermissionHandler().getPrimaryGroup(who.getWorld().getName(), who.getName())); gname = plugin.getPermissionHandler().getPrimaryGroup(who.getWorld().getName(), who.getName()); g = plugin.getPermissionHandler().getGroupObject(who.getWorld().getName(), gname); sender.sendMessage(ChatColor.YELLOW+"Playername : "+who.getName()+" "+(nick!=null?"("+plugin.getNickWithColors(who.getName())+ChatColor.YELLOW+")":"")); // String group = plugin.getPermissionHandler.getG(who.getWorld().getName(), who.getName()); sender.sendMessage(ChatColor.YELLOW+"Group : "+g.getName()); if(!getIP && sender instanceof Player) { if(((Player)sender).getName().equalsIgnoreCase(who.getName())) getIP = true; } if(getIP) sender.sendMessage(ChatColor.YELLOW + "IP: " + who.getAddress().getAddress().getHostName()); } else { throw new CommandException("Can't find player!"); } } else { throw new CommandUsageException("I need a player!"); } return true; }
diff --git a/hk2/osgi-main/src/java/org/jvnet/hk2/osgimain/Main.java b/hk2/osgi-main/src/java/org/jvnet/hk2/osgimain/Main.java index cf9dc6905..c938591a6 100644 --- a/hk2/osgi-main/src/java/org/jvnet/hk2/osgimain/Main.java +++ b/hk2/osgi-main/src/java/org/jvnet/hk2/osgimain/Main.java @@ -1,394 +1,395 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package org.jvnet.hk2.osgimain; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.Bundle; import org.osgi.framework.ServiceReference; import org.osgi.framework.BundleException; import org.osgi.service.packageadmin.PackageAdmin; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.util.logging.Logger; import java.util.logging.Level; import java.util.StringTokenizer; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.Collections; import java.util.Set; import java.util.HashSet; import java.util.Collection; import java.net.URISyntaxException; import java.net.URI; /** * Goes through a directory structure recurssively and installs all the * jar files as OSGi bundles. This bundle can be passed a list of bundle paths * to be started automatically. The bundle path is treated relative to the * directory from where it installs all the bundles. It does not stop those bundle * when this bundle is stopped. It stops them in reverse order. * * This bundle is also responsible for updating or uninstalling bundle during * subsequent restart if jars have been updated or deleted. * * It does not manage itself. So, we use reference: scheme to install this bundle * which allows us to see changes to this jar file automatically. * * @author [email protected] */ public class Main implements BundleActivator { /* * The reason for this bundle not to use config admin service is that config admin is not part of core framework. * This being a provisioning service itself can't expect too many other services to be available. So, it relies on * core framework services only. */ public static final String BUNDLES_DIR = "org.jvnet.hk2.osgimain.bundlesDir"; // a comma separated list of dir names relative to bundles dir // that need to be excluded. e.g., autostart public static final String EXCLUDED_SUBDIRS = "org.jvnet.hk2.osgimain.excludedSubDirs"; public final static String HK2_CACHE_DIR = "com.sun.enterprise.hk2.cacheDir"; public final static String INHABITANTS_CACHE = "inhabitants"; public static final String AUTO_START_BUNDLES_PROP = "org.jvnet.hk2.osgimain.autostartBundles"; private static final Logger logger = Logger.getLogger(Main.class.getPackage().getName()); private BundleContext context; private File bundlesDir; // files under bundles dir structure that are excluded from processing // if any of the excluded file is a directory, then entire content // of the directiry is excluded. private Collection<File> excludedSubDirs = new HashSet<File>(); private List<URI> autoStartBundleLocations = new ArrayList<URI>(); private Map<URI, Jar> currentManagedBundles = new HashMap<URI, Jar>(); private static final String THIS_JAR_NAME = "osgi-main.jar"; public void start(BundleContext context) throws Exception { this.context = context; - bundlesDir = new File(context.getProperty(BUNDLES_DIR)); - if (bundlesDir == null) { + final String bundlesDirPath = context.getProperty(BUNDLES_DIR); + if (bundlesDirPath == null) { // nothing to do, let's return return; } + bundlesDir = new File(bundlesDirPath); String autostartBundlesProp = context.getProperty(AUTO_START_BUNDLES_PROP); if (autostartBundlesProp != null) { StringTokenizer st = new StringTokenizer(autostartBundlesProp, ","); while (st.hasMoreTokens()) { String bundleRelPath = st.nextToken().trim(); if (bundleRelPath.isEmpty()) break; URI bundleURI = new File(bundlesDir, bundleRelPath).toURI().normalize(); autoStartBundleLocations.add(bundleURI); } } String excludedFilesProp = context.getProperty(EXCLUDED_SUBDIRS); if (excludedFilesProp != null) { for (String s : excludedFilesProp.split(",")) { excludedSubDirs.add(new File(bundlesDir, s.trim())); } } traverse(); for (URI location : autoStartBundleLocations) { long id = currentManagedBundles.get(location).getBundleId(); if (id < 0) { logger.logp(Level.WARNING, "Main", "start", "Not able to locate autostart bundle for location = {0}", new Object[]{location}); continue; } final Bundle bundle = context.getBundle(id); // check is necessary as bundle could have been uninstalled if (bundle != null) { try { bundle.start(Bundle.START_TRANSIENT); } catch (BundleException e) { logger.logp(Level.WARNING, "Main", "start", "Exception while starting bundle " + bundle, e); } } } } /** * Stops all the autostart bundles in reverse order * @param context * @throws Exception */ public void stop(BundleContext context) throws Exception { List<URI> bundlesToStop = new ArrayList<URI>(autoStartBundleLocations); Collections.reverse(bundlesToStop); for (URI location : bundlesToStop) { long id = currentManagedBundles.get(location).getBundleId(); if (id < 0) { logger.logp(Level.WARNING, "Main", "stop", "Not able to locate autostart bundle for location = {0}", new Object[]{location}); continue; } final Bundle bundle = context.getBundle(id); // check is necessary as bundle could have been uninstalled if (bundle != null) bundle.stop(); } } private Set<Jar> discoverJars() { final Set<Jar> jars = new HashSet<Jar>(); bundlesDir.listFiles(new FileFilter(){ final String JAR_EXT = ".jar"; public boolean accept(File file) { if (file.isDirectory() && !excludedSubDirs.contains(file)) { file.listFiles(this); } else if (file.isFile() && file.getName().endsWith(JAR_EXT) && !file.getName().equals(THIS_JAR_NAME)) { jars.add(new Jar(file)); return true; } return false; } }); return jars; } /** * This method goes through all the currently installed bundles * and returns information about those bundles whose location * refers to a file in our {@link #bundlesDir}. */ private void initCurrentManagedBundles() { Bundle[] bundles = this.context.getBundles(); String watchedDirPath = bundlesDir.toURI().normalize().getPath(); final long thisBundleId = context.getBundle().getBundleId(); for (Bundle bundle : bundles) { try { final long id = bundle.getBundleId(); if (id == 0 || id == thisBundleId) { // We can't manage system bundle or this bundle continue; } Jar jar = new Jar(bundle); String path = jar.getPath(); if (path == null) { // jar.getPath is null means we could not parse the location // as a meaningful URI or file path. e.g., location // represented an Opaque URI. // We can't do any meaningful processing for this bundle. continue; } if (path.regionMatches(0, watchedDirPath, 0, watchedDirPath.length())) { currentManagedBundles.put(jar.getURI(), jar); } } catch (URISyntaxException e) { // Ignore and continue. // This can never happen for bundles that have been installed // by FileInstall, as we always use proper filepath as location. } } } /** * This method goes collects list of bundles that have been installed * from the watched directory in previous run of the program, * compares them with the current set of jar files, * uninstalls old bundles, updates modified bundles, installs new bundles * and refreshes the framework for the changes to take effect. */ private void traverse() { initCurrentManagedBundles(); final Collection<Jar> current = currentManagedBundles.values(); Set<Jar> discovered = discoverJars(); // Find out all the new, deleted and common bundles. // new = discovered - current Set<Jar> newBundles = new HashSet<Jar>(discovered); newBundles.removeAll(current); // deleted = current - discovered Set<Jar> deletedBundles = new HashSet<Jar>(current); deletedBundles.removeAll(discovered); // existing = intersection of current & discovered Set<Jar> existingBundles = new HashSet<Jar>(discovered); // We remove discovered ones from current, so that we are left // with a collection of Jars made from files so that we can compare // them with bundles. existingBundles.retainAll(current); // We do the operations in the following order: // uninstall, update, install, refresh & start. uninstall(deletedBundles); int updated = update(existingBundles); install(newBundles); if ((newBundles.size() + deletedBundles.size() + updated) > 0) { refresh(); } } private void uninstall(Collection<Jar> bundles) { for (Jar jar : bundles) { Bundle bundle = context.getBundle(jar.getBundleId()); if (bundle == null) { // this is highly unlikely, but can't be ruled out. continue; } if (isExcludedFile(new File(jar.getPath()))) { // This is a bundle which is excluded from our processing. // The reason we have not discovered this jar is because // we have exclueded them in discoverJars(). So, don't uninstall // them. continue; } try { bundle.uninstall(); logger.logp(Level.INFO, "Main", "uninstall", "Uninstalled bundle {0} installed from {1} ", new Object[]{bundle.getBundleId(), jar.getPath()}); } catch (Exception e) { logger.logp(Level.WARNING, "Main", "uninstall", "Failed to uninstall bundle " + jar.getPath(), e); } } } private int update(Collection<Jar> jars) { int updated = 0; for (Jar jar : jars) { final Jar existingJar= currentManagedBundles.get(jar.getURI()); if (jar.isNewer(existingJar)) { Bundle bundle = context.getBundle(existingJar.getBundleId()); if (bundle == null) { // this is highly unlikely, but can't be ruled out. continue; } try { bundle.update(); updated++; logger.logp(Level.INFO, "Main", "update", "Updated bundle {0} from {1} ", new Object[]{bundle.getBundleId(), jar.getPath()}); } catch (Exception e) { logger.logp(Level.WARNING, "Main", "update", "Failed to update " + jar.getPath(), e); } } } return updated; } private void install(Collection<Jar> jars) { for (Jar jar : jars) { try { final String path = jar.getPath(); File file = new File(path); final FileInputStream is = new FileInputStream(file); try { Bundle b = context.installBundle(jar.getURI().toString(), is); currentManagedBundles.put(jar.getURI(), new Jar(b)); logger.logp(Level.FINE, "Main", "install", "Installed bundle {0} from {1} ", new Object[]{b.getBundleId(), jar.getURI()}); } finally { try { is.close(); } catch (IOException e) { } } } catch (Exception e) { logger.logp(Level.WARNING, "Main", "install", "Failed to install " + jar.getURI(), e); } } } private void refresh() { final ServiceReference reference = context.getServiceReference(PackageAdmin.class.getName()); PackageAdmin pa = PackageAdmin.class.cast( context.getService(reference)); pa.refreshPackages(null); // null to refresh any bundle that's obsolete context.ungetService(reference); // This is a HACK - thanks to some weired optimization trick // done for GlassFish. HK2 maintains a cache of inhabitants and // that needs to be recreated when there is a change in modules dir. final String cacheDir = System.getProperty(HK2_CACHE_DIR); if (cacheDir != null) { File inhabitantsCache = new File(cacheDir, INHABITANTS_CACHE); if (inhabitantsCache.exists()) inhabitantsCache.delete(); } } private boolean isExcludedFile(File f) { String path = f.getPath(); for (File excludedSubDir : excludedSubDirs) { String excludedSubDirPath = excludedSubDir.getPath(); if (path.regionMatches(0, excludedSubDirPath, 0, excludedSubDirPath.length())) { return true; } } return false; } }
false
true
public void start(BundleContext context) throws Exception { this.context = context; bundlesDir = new File(context.getProperty(BUNDLES_DIR)); if (bundlesDir == null) { // nothing to do, let's return return; } String autostartBundlesProp = context.getProperty(AUTO_START_BUNDLES_PROP); if (autostartBundlesProp != null) { StringTokenizer st = new StringTokenizer(autostartBundlesProp, ","); while (st.hasMoreTokens()) { String bundleRelPath = st.nextToken().trim(); if (bundleRelPath.isEmpty()) break; URI bundleURI = new File(bundlesDir, bundleRelPath).toURI().normalize(); autoStartBundleLocations.add(bundleURI); } } String excludedFilesProp = context.getProperty(EXCLUDED_SUBDIRS); if (excludedFilesProp != null) { for (String s : excludedFilesProp.split(",")) { excludedSubDirs.add(new File(bundlesDir, s.trim())); } } traverse(); for (URI location : autoStartBundleLocations) { long id = currentManagedBundles.get(location).getBundleId(); if (id < 0) { logger.logp(Level.WARNING, "Main", "start", "Not able to locate autostart bundle for location = {0}", new Object[]{location}); continue; } final Bundle bundle = context.getBundle(id); // check is necessary as bundle could have been uninstalled if (bundle != null) { try { bundle.start(Bundle.START_TRANSIENT); } catch (BundleException e) { logger.logp(Level.WARNING, "Main", "start", "Exception while starting bundle " + bundle, e); } } } }
public void start(BundleContext context) throws Exception { this.context = context; final String bundlesDirPath = context.getProperty(BUNDLES_DIR); if (bundlesDirPath == null) { // nothing to do, let's return return; } bundlesDir = new File(bundlesDirPath); String autostartBundlesProp = context.getProperty(AUTO_START_BUNDLES_PROP); if (autostartBundlesProp != null) { StringTokenizer st = new StringTokenizer(autostartBundlesProp, ","); while (st.hasMoreTokens()) { String bundleRelPath = st.nextToken().trim(); if (bundleRelPath.isEmpty()) break; URI bundleURI = new File(bundlesDir, bundleRelPath).toURI().normalize(); autoStartBundleLocations.add(bundleURI); } } String excludedFilesProp = context.getProperty(EXCLUDED_SUBDIRS); if (excludedFilesProp != null) { for (String s : excludedFilesProp.split(",")) { excludedSubDirs.add(new File(bundlesDir, s.trim())); } } traverse(); for (URI location : autoStartBundleLocations) { long id = currentManagedBundles.get(location).getBundleId(); if (id < 0) { logger.logp(Level.WARNING, "Main", "start", "Not able to locate autostart bundle for location = {0}", new Object[]{location}); continue; } final Bundle bundle = context.getBundle(id); // check is necessary as bundle could have been uninstalled if (bundle != null) { try { bundle.start(Bundle.START_TRANSIENT); } catch (BundleException e) { logger.logp(Level.WARNING, "Main", "start", "Exception while starting bundle " + bundle, e); } } } }
diff --git a/MODSRC/vazkii/tinkerer/tile/TileEntityMagnet.java b/MODSRC/vazkii/tinkerer/tile/TileEntityMagnet.java index 843cb3e7..a3195bcc 100644 --- a/MODSRC/vazkii/tinkerer/tile/TileEntityMagnet.java +++ b/MODSRC/vazkii/tinkerer/tile/TileEntityMagnet.java @@ -1,71 +1,71 @@ /** * This class was created by <Vazkii>. It's distributed as * part of the ThaumicTinkerer Mod. * * ThaumicTinkerer is Open Source and distributed under a * Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License * (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB) * * ThaumicTinkerer is a Derivative Work on Thaumcraft 3. * Thaumcraft 3 � Azanor 2012 * (http://www.minecraftforum.net/topic/1585216-) * * File Created @ [28 Jun 2013, 18:22:16 (GMT)] */ package vazkii.tinkerer.tile; import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.common.ForgeDirection; import thaumcraft.client.codechicken.core.vec.Vector3; import vazkii.tinkerer.ThaumicTinkerer; public class TileEntityMagnet extends TileEntity { @Override public void updateEntity() { int redstone = 0; for(ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) redstone = Math.max(redstone, worldObj.getIndirectPowerLevelTo(xCoord + dir.offsetX, yCoord + dir.offsetY, zCoord + dir.offsetZ, dir.ordinal())); if(redstone > 0) { double x1 = xCoord + 0.5; double y1 = yCoord + 0.5; double z1 = zCoord + 0.5; boolean blue = getBlockMetadata() == 0; int speedMod = blue ? 1 : -1; double range = redstone / 2; AxisAlignedBB boundingBox = AxisAlignedBB.getBoundingBox(x1 - range, yCoord, z1 - range, x1 + range, y1 + range, z1 + range); List<EntityItem> items = worldObj.getEntitiesWithinAABB(EntityItem.class, boundingBox); for(EntityItem item : items) { double x2 = item.posX; double y2 = item.posY; double z2 = item.posZ; - float distanceSqrd = (float) ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2)); + float distanceSqrd = blue ? ((float) ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2))) : 1.1F; if(distanceSqrd > 1) { setEntityMotionFromVector(item, x1, y1, z1, speedMod * 0.25F); ThaumicTinkerer.tcProxy.sparkle((float) x2, (float) y2, (float) z2, blue ? 2 : 4); } } } } private static void setEntityMotionFromVector(Entity entity, double x, double y, double z, float modifier) { Vector3 originalPosVector = new Vector3(x, y, z); Vector3 entityVector = Vector3.fromEntityCenter(entity); Vector3 finalVector = originalPosVector.subtract(entityVector).normalize(); entity.motionX = finalVector.x * modifier; entity.motionY = finalVector.y * modifier; entity.motionZ = finalVector.z * modifier; } }
true
true
public void updateEntity() { int redstone = 0; for(ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) redstone = Math.max(redstone, worldObj.getIndirectPowerLevelTo(xCoord + dir.offsetX, yCoord + dir.offsetY, zCoord + dir.offsetZ, dir.ordinal())); if(redstone > 0) { double x1 = xCoord + 0.5; double y1 = yCoord + 0.5; double z1 = zCoord + 0.5; boolean blue = getBlockMetadata() == 0; int speedMod = blue ? 1 : -1; double range = redstone / 2; AxisAlignedBB boundingBox = AxisAlignedBB.getBoundingBox(x1 - range, yCoord, z1 - range, x1 + range, y1 + range, z1 + range); List<EntityItem> items = worldObj.getEntitiesWithinAABB(EntityItem.class, boundingBox); for(EntityItem item : items) { double x2 = item.posX; double y2 = item.posY; double z2 = item.posZ; float distanceSqrd = (float) ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2)); if(distanceSqrd > 1) { setEntityMotionFromVector(item, x1, y1, z1, speedMod * 0.25F); ThaumicTinkerer.tcProxy.sparkle((float) x2, (float) y2, (float) z2, blue ? 2 : 4); } } } }
public void updateEntity() { int redstone = 0; for(ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) redstone = Math.max(redstone, worldObj.getIndirectPowerLevelTo(xCoord + dir.offsetX, yCoord + dir.offsetY, zCoord + dir.offsetZ, dir.ordinal())); if(redstone > 0) { double x1 = xCoord + 0.5; double y1 = yCoord + 0.5; double z1 = zCoord + 0.5; boolean blue = getBlockMetadata() == 0; int speedMod = blue ? 1 : -1; double range = redstone / 2; AxisAlignedBB boundingBox = AxisAlignedBB.getBoundingBox(x1 - range, yCoord, z1 - range, x1 + range, y1 + range, z1 + range); List<EntityItem> items = worldObj.getEntitiesWithinAABB(EntityItem.class, boundingBox); for(EntityItem item : items) { double x2 = item.posX; double y2 = item.posY; double z2 = item.posZ; float distanceSqrd = blue ? ((float) ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2))) : 1.1F; if(distanceSqrd > 1) { setEntityMotionFromVector(item, x1, y1, z1, speedMod * 0.25F); ThaumicTinkerer.tcProxy.sparkle((float) x2, (float) y2, (float) z2, blue ? 2 : 4); } } } }
diff --git a/src/main/java/org/springframework/data/hadoop/fs/FsShellPermissions.java b/src/main/java/org/springframework/data/hadoop/fs/FsShellPermissions.java index d6369cac..5387b47b 100644 --- a/src/main/java/org/springframework/data/hadoop/fs/FsShellPermissions.java +++ b/src/main/java/org/springframework/data/hadoop/fs/FsShellPermissions.java @@ -1,109 +1,111 @@ /* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.hadoop.fs; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedList; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FsShell; import org.springframework.beans.BeanUtils; import org.springframework.data.hadoop.HadoopException; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; /** * Utility class for accessing Hadoop FsShellPermissions (which is not public) * without having to duplicate its code. * * @author Costin Leau */ abstract class FsShellPermissions { private static boolean IS_HADOOP_20X = ClassUtils.isPresent("org.apache.hadoop.fs.FsShellPermissions$Chmod", FsShellPermissions.class.getClassLoader()); enum Op { CHOWN("-chown"), CHMOD("-chmod"), CHGRP("-chgrp"); private final String cmd; Op(String cmd) { this.cmd = cmd; } public String getCmd() { return cmd; } } // TODO: move this into Spring Core (but add JDK 1.5 compatibility first) static <T> T[] concatAll(T[] first, T[]... rest) { // can add some sanity checks int totalLength = first.length; for (T[] array : rest) { totalLength += array.length; } T[] result = Arrays.copyOf(first, totalLength); int offset = first.length; for (T[] array : rest) { System.arraycopy(array, 0, result, offset, array.length); offset += array.length; } return result; } static void changePermissions(FileSystem fs, Configuration config, Op op, boolean recursive, String group, String... uris) { String[] argvs = new String[0]; if (recursive) { ObjectUtils.addObjectToArray(argvs, "-R"); } argvs = concatAll(argvs, new String[] { group }, uris); // Hadoop 1.0.x if (!IS_HADOOP_20X) { Class<?> cls = ClassUtils.resolveClassName("org.apache.hadoop.fs.FsShellPermissions", config.getClass().getClassLoader()); Object[] args = new Object[] { fs, op.getCmd(), argvs, 0, new FsShell(config) }; Method m = ReflectionUtils.findMethod(cls, "changePermissions", FileSystem.class, String.class, String[].class, int.class, FsShell.class); ReflectionUtils.makeAccessible(m); ReflectionUtils.invokeMethod(m, null, args); } // Hadoop 2.x else { Class<?> cmd = ClassUtils.resolveClassName("org.apache.hadoop.fs.shell.Command", config.getClass().getClassLoader()); Class<?> targetClz = ClassUtils.resolveClassName("org.apache.hadoop.fs.FsShellPermissions$Chmod", config.getClass().getClassLoader()); Configurable target = (Configurable) BeanUtils.instantiate(targetClz); target.setConf(config); // run(String...) swallows the exceptions - re-implement it here // LinkedList<String> args = new LinkedList<String>(Arrays.asList(argvs)); try { Method m = ReflectionUtils.findMethod(cmd, "processOptions", LinkedList.class); + ReflectionUtils.makeAccessible(m); ReflectionUtils.invokeMethod(m, target, args); m = ReflectionUtils.findMethod(cmd, "processRawArguments", LinkedList.class); + ReflectionUtils.makeAccessible(m); ReflectionUtils.invokeMethod(m, target, args); } catch (IllegalStateException ex){ - throw new HadoopException("Cannot change permissions/ownership " + ex.getCause().getMessage(), ex.getCause()); + throw new HadoopException("Cannot change permissions/ownership " + ex); } } } }
false
true
static void changePermissions(FileSystem fs, Configuration config, Op op, boolean recursive, String group, String... uris) { String[] argvs = new String[0]; if (recursive) { ObjectUtils.addObjectToArray(argvs, "-R"); } argvs = concatAll(argvs, new String[] { group }, uris); // Hadoop 1.0.x if (!IS_HADOOP_20X) { Class<?> cls = ClassUtils.resolveClassName("org.apache.hadoop.fs.FsShellPermissions", config.getClass().getClassLoader()); Object[] args = new Object[] { fs, op.getCmd(), argvs, 0, new FsShell(config) }; Method m = ReflectionUtils.findMethod(cls, "changePermissions", FileSystem.class, String.class, String[].class, int.class, FsShell.class); ReflectionUtils.makeAccessible(m); ReflectionUtils.invokeMethod(m, null, args); } // Hadoop 2.x else { Class<?> cmd = ClassUtils.resolveClassName("org.apache.hadoop.fs.shell.Command", config.getClass().getClassLoader()); Class<?> targetClz = ClassUtils.resolveClassName("org.apache.hadoop.fs.FsShellPermissions$Chmod", config.getClass().getClassLoader()); Configurable target = (Configurable) BeanUtils.instantiate(targetClz); target.setConf(config); // run(String...) swallows the exceptions - re-implement it here // LinkedList<String> args = new LinkedList<String>(Arrays.asList(argvs)); try { Method m = ReflectionUtils.findMethod(cmd, "processOptions", LinkedList.class); ReflectionUtils.invokeMethod(m, target, args); m = ReflectionUtils.findMethod(cmd, "processRawArguments", LinkedList.class); ReflectionUtils.invokeMethod(m, target, args); } catch (IllegalStateException ex){ throw new HadoopException("Cannot change permissions/ownership " + ex.getCause().getMessage(), ex.getCause()); } } }
static void changePermissions(FileSystem fs, Configuration config, Op op, boolean recursive, String group, String... uris) { String[] argvs = new String[0]; if (recursive) { ObjectUtils.addObjectToArray(argvs, "-R"); } argvs = concatAll(argvs, new String[] { group }, uris); // Hadoop 1.0.x if (!IS_HADOOP_20X) { Class<?> cls = ClassUtils.resolveClassName("org.apache.hadoop.fs.FsShellPermissions", config.getClass().getClassLoader()); Object[] args = new Object[] { fs, op.getCmd(), argvs, 0, new FsShell(config) }; Method m = ReflectionUtils.findMethod(cls, "changePermissions", FileSystem.class, String.class, String[].class, int.class, FsShell.class); ReflectionUtils.makeAccessible(m); ReflectionUtils.invokeMethod(m, null, args); } // Hadoop 2.x else { Class<?> cmd = ClassUtils.resolveClassName("org.apache.hadoop.fs.shell.Command", config.getClass().getClassLoader()); Class<?> targetClz = ClassUtils.resolveClassName("org.apache.hadoop.fs.FsShellPermissions$Chmod", config.getClass().getClassLoader()); Configurable target = (Configurable) BeanUtils.instantiate(targetClz); target.setConf(config); // run(String...) swallows the exceptions - re-implement it here // LinkedList<String> args = new LinkedList<String>(Arrays.asList(argvs)); try { Method m = ReflectionUtils.findMethod(cmd, "processOptions", LinkedList.class); ReflectionUtils.makeAccessible(m); ReflectionUtils.invokeMethod(m, target, args); m = ReflectionUtils.findMethod(cmd, "processRawArguments", LinkedList.class); ReflectionUtils.makeAccessible(m); ReflectionUtils.invokeMethod(m, target, args); } catch (IllegalStateException ex){ throw new HadoopException("Cannot change permissions/ownership " + ex); } } }
diff --git a/bridge-impl/src/main/java/com/liferay/faces/bridge/renderkit/icefaces/HeadRendererICEfacesImpl.java b/bridge-impl/src/main/java/com/liferay/faces/bridge/renderkit/icefaces/HeadRendererICEfacesImpl.java index 3589e2dd3..1f589f5c3 100644 --- a/bridge-impl/src/main/java/com/liferay/faces/bridge/renderkit/icefaces/HeadRendererICEfacesImpl.java +++ b/bridge-impl/src/main/java/com/liferay/faces/bridge/renderkit/icefaces/HeadRendererICEfacesImpl.java @@ -1,97 +1,97 @@ /** * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.liferay.faces.bridge.renderkit.icefaces; import java.util.ArrayList; import java.util.List; import javax.el.ELContext; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import javax.faces.component.UIComponent; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import com.liferay.faces.bridge.component.ResourceComponent; import com.liferay.faces.bridge.renderkit.html_basic.HeadRendererBridgeImpl; import com.liferay.faces.bridge.renderkit.html_basic.HeadResponseWriter; import com.liferay.faces.util.lang.StringPool; /** * @author Neil Griffin */ public class HeadRendererICEfacesImpl extends HeadRendererBridgeImpl { // Private Constants private static final String ICEFACES_LIBRARY_NAME_ACE = "icefaces.ace"; private static final String ICEFACES_THEME_NAME_SAM = "sam"; private static final String ICEFACES_THEME_NAME_RIME = "rime"; private static final String ICEFACES_THEME_DEFAULT = ICEFACES_THEME_NAME_SAM; private static final String ICEFACES_THEME_PARAM = "org.icefaces.ace.theme"; private static final String ICEFACES_THEME_NONE = "none"; private static final String ICEFACES_THEME_PREFIX = "ace-"; private static final String ICEFACES_THEME_RESOURCE_NAME = "theme.css"; private static final String ICEFACES_THEME_DIR = "themes"; @Override protected List<UIComponent> getFirstResources(FacesContext facesContext, UIComponent uiComponent) { List<UIComponent> resources = super.getFirstResources(facesContext, uiComponent); // ICEfaces Theme ExternalContext externalContext = facesContext.getExternalContext(); - String primeFacesThemeName = externalContext.getInitParameter(ICEFACES_THEME_PARAM); + String iceFacesThemeName = externalContext.getInitParameter(ICEFACES_THEME_PARAM); - if (primeFacesThemeName != null) { + if (iceFacesThemeName != null) { ELContext elContext = facesContext.getELContext(); ExpressionFactory expressionFactory = facesContext.getApplication().getExpressionFactory(); - ValueExpression valueExpression = expressionFactory.createValueExpression(elContext, primeFacesThemeName, + ValueExpression valueExpression = expressionFactory.createValueExpression(elContext, iceFacesThemeName, String.class); - primeFacesThemeName = (String) valueExpression.getValue(elContext); + iceFacesThemeName = (String) valueExpression.getValue(elContext); } else { - primeFacesThemeName = ICEFACES_THEME_DEFAULT; + iceFacesThemeName = ICEFACES_THEME_DEFAULT; } - if ((primeFacesThemeName != null) && !primeFacesThemeName.equals(ICEFACES_THEME_NONE)) { + if ((iceFacesThemeName != null) && !iceFacesThemeName.equals(ICEFACES_THEME_NONE)) { if (resources == null) { resources = new ArrayList<UIComponent>(); } String resourceName = ICEFACES_THEME_RESOURCE_NAME; - String resourceLibrary = ICEFACES_THEME_PREFIX + primeFacesThemeName; + String resourceLibrary = ICEFACES_THEME_PREFIX + iceFacesThemeName; - if (primeFacesThemeName.equals(ICEFACES_THEME_NAME_SAM) || - primeFacesThemeName.equals(ICEFACES_THEME_NAME_RIME)) { + if (iceFacesThemeName.equals(ICEFACES_THEME_NAME_SAM) || + iceFacesThemeName.equals(ICEFACES_THEME_NAME_RIME)) { StringBuilder buf = new StringBuilder(); buf.append(ICEFACES_THEME_DIR); buf.append(StringPool.FORWARD_SLASH); - buf.append(primeFacesThemeName); + buf.append(iceFacesThemeName); buf.append(StringPool.FORWARD_SLASH); buf.append(ICEFACES_THEME_RESOURCE_NAME); resourceName = buf.toString(); resourceLibrary = ICEFACES_LIBRARY_NAME_ACE; } - ResourceComponent primeFacesStyleSheet = new ResourceComponent(facesContext, resourceName, resourceLibrary, + ResourceComponent iceFacesStyleSheet = new ResourceComponent(facesContext, resourceName, resourceLibrary, HeadResponseWriter.ELEMENT_HEAD); - resources.add(primeFacesStyleSheet); + resources.add(iceFacesStyleSheet); } return resources; } }
false
true
protected List<UIComponent> getFirstResources(FacesContext facesContext, UIComponent uiComponent) { List<UIComponent> resources = super.getFirstResources(facesContext, uiComponent); // ICEfaces Theme ExternalContext externalContext = facesContext.getExternalContext(); String primeFacesThemeName = externalContext.getInitParameter(ICEFACES_THEME_PARAM); if (primeFacesThemeName != null) { ELContext elContext = facesContext.getELContext(); ExpressionFactory expressionFactory = facesContext.getApplication().getExpressionFactory(); ValueExpression valueExpression = expressionFactory.createValueExpression(elContext, primeFacesThemeName, String.class); primeFacesThemeName = (String) valueExpression.getValue(elContext); } else { primeFacesThemeName = ICEFACES_THEME_DEFAULT; } if ((primeFacesThemeName != null) && !primeFacesThemeName.equals(ICEFACES_THEME_NONE)) { if (resources == null) { resources = new ArrayList<UIComponent>(); } String resourceName = ICEFACES_THEME_RESOURCE_NAME; String resourceLibrary = ICEFACES_THEME_PREFIX + primeFacesThemeName; if (primeFacesThemeName.equals(ICEFACES_THEME_NAME_SAM) || primeFacesThemeName.equals(ICEFACES_THEME_NAME_RIME)) { StringBuilder buf = new StringBuilder(); buf.append(ICEFACES_THEME_DIR); buf.append(StringPool.FORWARD_SLASH); buf.append(primeFacesThemeName); buf.append(StringPool.FORWARD_SLASH); buf.append(ICEFACES_THEME_RESOURCE_NAME); resourceName = buf.toString(); resourceLibrary = ICEFACES_LIBRARY_NAME_ACE; } ResourceComponent primeFacesStyleSheet = new ResourceComponent(facesContext, resourceName, resourceLibrary, HeadResponseWriter.ELEMENT_HEAD); resources.add(primeFacesStyleSheet); } return resources; }
protected List<UIComponent> getFirstResources(FacesContext facesContext, UIComponent uiComponent) { List<UIComponent> resources = super.getFirstResources(facesContext, uiComponent); // ICEfaces Theme ExternalContext externalContext = facesContext.getExternalContext(); String iceFacesThemeName = externalContext.getInitParameter(ICEFACES_THEME_PARAM); if (iceFacesThemeName != null) { ELContext elContext = facesContext.getELContext(); ExpressionFactory expressionFactory = facesContext.getApplication().getExpressionFactory(); ValueExpression valueExpression = expressionFactory.createValueExpression(elContext, iceFacesThemeName, String.class); iceFacesThemeName = (String) valueExpression.getValue(elContext); } else { iceFacesThemeName = ICEFACES_THEME_DEFAULT; } if ((iceFacesThemeName != null) && !iceFacesThemeName.equals(ICEFACES_THEME_NONE)) { if (resources == null) { resources = new ArrayList<UIComponent>(); } String resourceName = ICEFACES_THEME_RESOURCE_NAME; String resourceLibrary = ICEFACES_THEME_PREFIX + iceFacesThemeName; if (iceFacesThemeName.equals(ICEFACES_THEME_NAME_SAM) || iceFacesThemeName.equals(ICEFACES_THEME_NAME_RIME)) { StringBuilder buf = new StringBuilder(); buf.append(ICEFACES_THEME_DIR); buf.append(StringPool.FORWARD_SLASH); buf.append(iceFacesThemeName); buf.append(StringPool.FORWARD_SLASH); buf.append(ICEFACES_THEME_RESOURCE_NAME); resourceName = buf.toString(); resourceLibrary = ICEFACES_LIBRARY_NAME_ACE; } ResourceComponent iceFacesStyleSheet = new ResourceComponent(facesContext, resourceName, resourceLibrary, HeadResponseWriter.ELEMENT_HEAD); resources.add(iceFacesStyleSheet); } return resources; }
diff --git a/src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersistenceUnitLoaderTest.java b/src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersistenceUnitLoaderTest.java index 17d3632d0..0d0b9eb37 100644 --- a/src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersistenceUnitLoaderTest.java +++ b/src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersistenceUnitLoaderTest.java @@ -1,103 +1,103 @@ /******************************************************************************* * * Copyright 2012 Impetus Infotech. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. ******************************************************************************/ package com.impetus.kundera.persistence; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.List; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.impetus.kundera.loader.PersistenceXMLLoader; import com.impetus.kundera.metadata.model.PersistenceUnitMetadata; /** * Unit test case to load persistence.xml properties. * * @author vivek.mishra * */ public class PersistenceUnitLoaderTest { /** logger instance */ private static final Logger log = LoggerFactory.getLogger(PersistenceUnitLoaderTest.class); /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { // do nothing. } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { // do nothing. } /** * Test method on persistence unit loading. */ @Test public void testLoadPersistenceUnitLoading() { try { Enumeration<URL> xmls = this.getClass().getClassLoader() .getResources("META-INF/persistence.xml"); while (xmls.hasMoreElements()) { final String _pattern = "/core/target/test-classes/"; List<PersistenceUnitMetadata> metadatas = PersistenceXMLLoader.findPersistenceUnits(xmls.nextElement()); Assert.assertNotNull(metadatas); - Assert.assertEquals(11, metadatas.size()); + Assert.assertEquals(12, metadatas.size()); // commented out to keep ConfiguratorTest happy! as it tries to // load it. // Assert.assertEquals(2, // metadatas.get(0).getJarFiles().size()); Assert.assertEquals(53, metadatas.get(0).getClasses().size()); Assert.assertNotNull(metadatas.get(0).getPersistenceUnitRootUrl()); Assert.assertTrue(metadatas.get(0).getPersistenceUnitRootUrl().getPath().endsWith(_pattern)); } } catch (IOException ioex) { log.error(ioex.getMessage()); Assert.fail(); } catch (Exception e) { log.error(e.getMessage()); Assert.fail(); } } }
true
true
public void testLoadPersistenceUnitLoading() { try { Enumeration<URL> xmls = this.getClass().getClassLoader() .getResources("META-INF/persistence.xml"); while (xmls.hasMoreElements()) { final String _pattern = "/core/target/test-classes/"; List<PersistenceUnitMetadata> metadatas = PersistenceXMLLoader.findPersistenceUnits(xmls.nextElement()); Assert.assertNotNull(metadatas); Assert.assertEquals(11, metadatas.size()); // commented out to keep ConfiguratorTest happy! as it tries to // load it. // Assert.assertEquals(2, // metadatas.get(0).getJarFiles().size()); Assert.assertEquals(53, metadatas.get(0).getClasses().size()); Assert.assertNotNull(metadatas.get(0).getPersistenceUnitRootUrl()); Assert.assertTrue(metadatas.get(0).getPersistenceUnitRootUrl().getPath().endsWith(_pattern)); } } catch (IOException ioex) { log.error(ioex.getMessage()); Assert.fail(); } catch (Exception e) { log.error(e.getMessage()); Assert.fail(); } }
public void testLoadPersistenceUnitLoading() { try { Enumeration<URL> xmls = this.getClass().getClassLoader() .getResources("META-INF/persistence.xml"); while (xmls.hasMoreElements()) { final String _pattern = "/core/target/test-classes/"; List<PersistenceUnitMetadata> metadatas = PersistenceXMLLoader.findPersistenceUnits(xmls.nextElement()); Assert.assertNotNull(metadatas); Assert.assertEquals(12, metadatas.size()); // commented out to keep ConfiguratorTest happy! as it tries to // load it. // Assert.assertEquals(2, // metadatas.get(0).getJarFiles().size()); Assert.assertEquals(53, metadatas.get(0).getClasses().size()); Assert.assertNotNull(metadatas.get(0).getPersistenceUnitRootUrl()); Assert.assertTrue(metadatas.get(0).getPersistenceUnitRootUrl().getPath().endsWith(_pattern)); } } catch (IOException ioex) { log.error(ioex.getMessage()); Assert.fail(); } catch (Exception e) { log.error(e.getMessage()); Assert.fail(); } }
diff --git a/tools/maven2/maven-bundle-plugin/src/main/java/org/apache/felix/tools/maven2/bundleplugin/BundlePlugin.java b/tools/maven2/maven-bundle-plugin/src/main/java/org/apache/felix/tools/maven2/bundleplugin/BundlePlugin.java index 4e28260dd..af6a42597 100644 --- a/tools/maven2/maven-bundle-plugin/src/main/java/org/apache/felix/tools/maven2/bundleplugin/BundlePlugin.java +++ b/tools/maven2/maven-bundle-plugin/src/main/java/org/apache/felix/tools/maven2/bundleplugin/BundlePlugin.java @@ -1,268 +1,268 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.tools.maven2.bundleplugin; import java.io.*; import java.lang.reflect.*; import java.util.*; import java.util.regex.*; import java.util.zip.ZipException; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.*; import org.apache.maven.plugin.*; import org.apache.maven.project.MavenProject; import aQute.lib.osgi.*; /** * * @goal bundle * @phase package * @requiresDependencyResolution runtime * @description build an OSGi bundle jar */ public class BundlePlugin extends AbstractMojo { /** * @parameter expression="${project.build.outputDirectory}" * @required * @readonly */ File outputDirectory; /** * The directory for the pom * * @parameter expression="${basedir}" * @required */ private File baseDir; /** * The directory for the generated JAR. * * @parameter expression="${project.build.directory}" * @required */ private String buildDirectory; /** * The Maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * The name of the generated JAR file. * * @parameter */ private Map instructions = new HashMap(); public void execute() throws MojoExecutionException { try { File jarFile = new File(buildDirectory, project.getBuild() .getFinalName() + ".jar"); // Setup defaults String bsn = project.getGroupId() + "." + project.getArtifactId(); Properties properties = new Properties(); properties.put(Analyzer.BUNDLE_SYMBOLICNAME, bsn); properties.put(Analyzer.IMPORT_PACKAGE, "*"); if (!instructions.containsKey(Analyzer.PRIVATE_PACKAGE)) { properties.put(Analyzer.EXPORT_PACKAGE, bsn + ".*"); } String version = project.getVersion(); - Pattern P_VERSION = Pattern.compile("([0-9]+(\\.[0-9])*)-(.*)"); + Pattern P_VERSION = Pattern.compile("([0-9]+(\\.[0-9]+)*)-(.*)"); Matcher m = P_VERSION.matcher(version); if (m.matches()) { version = m.group(1) + "." + m.group(3); } properties.put(Analyzer.BUNDLE_VERSION, version); header(properties, Analyzer.BUNDLE_DESCRIPTION, project .getDescription()); header(properties, Analyzer.BUNDLE_LICENSE, printLicenses(project .getLicenses())); header(properties, Analyzer.BUNDLE_NAME, project.getName()); if (project.getOrganization() != null) { header(properties, Analyzer.BUNDLE_VENDOR, project .getOrganization().getName()); if (project.getOrganization().getUrl() != null) { header(properties, Analyzer.BUNDLE_DOCURL, project .getOrganization().getUrl()); } } if (new File(baseDir, "src/main/resources").exists()) { header(properties, Analyzer.INCLUDE_RESOURCE, "src/main/resources/"); } properties.putAll(project.getProperties()); properties.putAll(project.getModel().getProperties()); properties.putAll( getProperies("project.build.", project.getBuild())); properties.putAll( getProperies("pom.", project.getModel())); properties.putAll( getProperies("project.", project)); properties.put("project.baseDir", baseDir ); properties.put("project.build.directory", buildDirectory ); properties.put("project.build.outputdirectory", outputDirectory ); properties.putAll(instructions); Builder builder = new Builder(); builder.setBase(baseDir); Jar[] cp = getClasspath(); builder.setProperties(properties); builder.setClasspath(cp); builder.build(); Jar jar = builder.getJar(); doMavenMetadata(jar); builder.setJar(jar); List errors = builder.getErrors(); List warnings = builder.getWarnings(); if (errors.size() > 0) { jarFile.delete(); for (Iterator e = errors.iterator(); e.hasNext();) { String msg = (String) e.next(); getLog().error(msg); } throw new MojoFailureException("Found errors, see log"); } else { jarFile.getParentFile().mkdirs(); builder.getJar().write(jarFile); project.getArtifact().setFile(jarFile); } for (Iterator w = warnings.iterator(); w.hasNext();) { String msg = (String) w.next(); getLog().warn(msg); } } catch (Exception e) { e.printStackTrace(); throw new MojoExecutionException("Unknown error occurred", e); } } private Map getProperies(String prefix, Object model) { Map properties = new HashMap(); Method methods[] = Model.class.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String name = methods[i].getName(); if ( name.startsWith("get") ) { try { Object v = methods[i].invoke(project.getModel(), null ); if ( v != null ) { name = prefix + Character.toLowerCase(name.charAt(3)) + name.substring(4); if ( v.getClass().isArray() ) properties.put( name, Arrays.asList((Object[])v).toString() ); else properties.put( name, v ); } } catch (Exception e) { // too bad } } } return properties; } private StringBuffer printLicenses(List licenses) { if (licenses == null || licenses.size() == 0) return null; StringBuffer sb = new StringBuffer(); String del = ""; for (Iterator i = licenses.iterator(); i.hasNext();) { License l = (License) i.next(); String url = l.getUrl(); sb.append(del); sb.append(url); del = ", "; } return sb; } /** * @param jar * @throws IOException */ private void doMavenMetadata(Jar jar) throws IOException { String path = "META-INF/maven/" + project.getGroupId() + "/" + project.getArtifactId(); File pomFile = new File(baseDir, "pom.xml"); jar.putResource(path + "/pom.xml", new FileResource(pomFile)); Properties p = new Properties(); p.put("version", project.getVersion()); p.put("groupId", project.getGroupId()); p.put("artifactId", project.getArtifactId()); ByteArrayOutputStream out = new ByteArrayOutputStream(); p.store(out, "Generated by org.apache.felix.plugin.bundle"); jar.putResource(path + "/pom.properties", new EmbeddedResource(out .toByteArray())); } /** * @return * @throws ZipException * @throws IOException */ private Jar[] getClasspath() throws ZipException, IOException { List list = new ArrayList(); if (outputDirectory != null && outputDirectory.exists()) { list.add(new Jar(".", outputDirectory)); } Set artifacts = project.getArtifacts(); for (Iterator it = artifacts.iterator(); it.hasNext();) { Artifact artifact = (Artifact) it.next(); if (Artifact.SCOPE_COMPILE.equals(artifact.getScope()) || Artifact.SCOPE_SYSTEM.equals(artifact.getScope()) || Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) { Jar jar = new Jar(artifact.getArtifactId(), artifact.getFile()); list.add(jar); } } Jar[] cp = new Jar[list.size()]; list.toArray(cp); return cp; } private void header(Properties properties, String key, Object value) { if (value == null) return; if (value instanceof Collection && ((Collection) value).isEmpty()) return; properties.put(key, value.toString()); } }
true
true
public void execute() throws MojoExecutionException { try { File jarFile = new File(buildDirectory, project.getBuild() .getFinalName() + ".jar"); // Setup defaults String bsn = project.getGroupId() + "." + project.getArtifactId(); Properties properties = new Properties(); properties.put(Analyzer.BUNDLE_SYMBOLICNAME, bsn); properties.put(Analyzer.IMPORT_PACKAGE, "*"); if (!instructions.containsKey(Analyzer.PRIVATE_PACKAGE)) { properties.put(Analyzer.EXPORT_PACKAGE, bsn + ".*"); } String version = project.getVersion(); Pattern P_VERSION = Pattern.compile("([0-9]+(\\.[0-9])*)-(.*)"); Matcher m = P_VERSION.matcher(version); if (m.matches()) { version = m.group(1) + "." + m.group(3); } properties.put(Analyzer.BUNDLE_VERSION, version); header(properties, Analyzer.BUNDLE_DESCRIPTION, project .getDescription()); header(properties, Analyzer.BUNDLE_LICENSE, printLicenses(project .getLicenses())); header(properties, Analyzer.BUNDLE_NAME, project.getName()); if (project.getOrganization() != null) { header(properties, Analyzer.BUNDLE_VENDOR, project .getOrganization().getName()); if (project.getOrganization().getUrl() != null) { header(properties, Analyzer.BUNDLE_DOCURL, project .getOrganization().getUrl()); } } if (new File(baseDir, "src/main/resources").exists()) { header(properties, Analyzer.INCLUDE_RESOURCE, "src/main/resources/"); } properties.putAll(project.getProperties()); properties.putAll(project.getModel().getProperties()); properties.putAll( getProperies("project.build.", project.getBuild())); properties.putAll( getProperies("pom.", project.getModel())); properties.putAll( getProperies("project.", project)); properties.put("project.baseDir", baseDir ); properties.put("project.build.directory", buildDirectory ); properties.put("project.build.outputdirectory", outputDirectory ); properties.putAll(instructions); Builder builder = new Builder(); builder.setBase(baseDir); Jar[] cp = getClasspath(); builder.setProperties(properties); builder.setClasspath(cp); builder.build(); Jar jar = builder.getJar(); doMavenMetadata(jar); builder.setJar(jar); List errors = builder.getErrors(); List warnings = builder.getWarnings(); if (errors.size() > 0) { jarFile.delete(); for (Iterator e = errors.iterator(); e.hasNext();) { String msg = (String) e.next(); getLog().error(msg); } throw new MojoFailureException("Found errors, see log"); } else { jarFile.getParentFile().mkdirs(); builder.getJar().write(jarFile); project.getArtifact().setFile(jarFile); } for (Iterator w = warnings.iterator(); w.hasNext();) { String msg = (String) w.next(); getLog().warn(msg); } } catch (Exception e) { e.printStackTrace(); throw new MojoExecutionException("Unknown error occurred", e); } }
public void execute() throws MojoExecutionException { try { File jarFile = new File(buildDirectory, project.getBuild() .getFinalName() + ".jar"); // Setup defaults String bsn = project.getGroupId() + "." + project.getArtifactId(); Properties properties = new Properties(); properties.put(Analyzer.BUNDLE_SYMBOLICNAME, bsn); properties.put(Analyzer.IMPORT_PACKAGE, "*"); if (!instructions.containsKey(Analyzer.PRIVATE_PACKAGE)) { properties.put(Analyzer.EXPORT_PACKAGE, bsn + ".*"); } String version = project.getVersion(); Pattern P_VERSION = Pattern.compile("([0-9]+(\\.[0-9]+)*)-(.*)"); Matcher m = P_VERSION.matcher(version); if (m.matches()) { version = m.group(1) + "." + m.group(3); } properties.put(Analyzer.BUNDLE_VERSION, version); header(properties, Analyzer.BUNDLE_DESCRIPTION, project .getDescription()); header(properties, Analyzer.BUNDLE_LICENSE, printLicenses(project .getLicenses())); header(properties, Analyzer.BUNDLE_NAME, project.getName()); if (project.getOrganization() != null) { header(properties, Analyzer.BUNDLE_VENDOR, project .getOrganization().getName()); if (project.getOrganization().getUrl() != null) { header(properties, Analyzer.BUNDLE_DOCURL, project .getOrganization().getUrl()); } } if (new File(baseDir, "src/main/resources").exists()) { header(properties, Analyzer.INCLUDE_RESOURCE, "src/main/resources/"); } properties.putAll(project.getProperties()); properties.putAll(project.getModel().getProperties()); properties.putAll( getProperies("project.build.", project.getBuild())); properties.putAll( getProperies("pom.", project.getModel())); properties.putAll( getProperies("project.", project)); properties.put("project.baseDir", baseDir ); properties.put("project.build.directory", buildDirectory ); properties.put("project.build.outputdirectory", outputDirectory ); properties.putAll(instructions); Builder builder = new Builder(); builder.setBase(baseDir); Jar[] cp = getClasspath(); builder.setProperties(properties); builder.setClasspath(cp); builder.build(); Jar jar = builder.getJar(); doMavenMetadata(jar); builder.setJar(jar); List errors = builder.getErrors(); List warnings = builder.getWarnings(); if (errors.size() > 0) { jarFile.delete(); for (Iterator e = errors.iterator(); e.hasNext();) { String msg = (String) e.next(); getLog().error(msg); } throw new MojoFailureException("Found errors, see log"); } else { jarFile.getParentFile().mkdirs(); builder.getJar().write(jarFile); project.getArtifact().setFile(jarFile); } for (Iterator w = warnings.iterator(); w.hasNext();) { String msg = (String) w.next(); getLog().warn(msg); } } catch (Exception e) { e.printStackTrace(); throw new MojoExecutionException("Unknown error occurred", e); } }
diff --git a/src/oca/java/src/org/opennebula/client/Client.java b/src/oca/java/src/org/opennebula/client/Client.java index 426837378..b5386efc1 100644 --- a/src/oca/java/src/org/opennebula/client/Client.java +++ b/src/oca/java/src/org/opennebula/client/Client.java @@ -1,248 +1,248 @@ /******************************************************************************* * Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.opennebula.client; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; /** * This class represents the connection with the core and handles the * xml-rpc calls. * */ public class Client{ //-------------------------------------------------------------------------- // PUBLIC INTERFACE //-------------------------------------------------------------------------- /** * Creates a new xml-rpc client with default options: the auth. file will be * assumed to be at $ONE_AUTH, and the endpoint will be set to $ONE_XMLRPC. <br/> * It is the equivalent of Client(null, null). * * @throws ClientConfigurationException * if the default configuration options are invalid. */ public Client() throws ClientConfigurationException { setOneAuth(null); setOneEndPoint(null); } /** * Creates a new xml-rpc client with specified options. * * @param secret * A string containing the ONE user:password tuple. Can be null * @param endpoint * Where the rpc server is listening, must be something like * "http://localhost:2633/RPC2". Can be null * @throws ClientConfigurationException * if the configuration options are invalid */ public Client(String secret, String endpoint) throws ClientConfigurationException { setOneAuth(secret); setOneEndPoint(endpoint); } /** * Performs an XML-RPC call. * * @param action ONE action * @param args ONE arguments * @return The server's xml-rpc response encapsulated */ public OneResponse call(String action, Object...args) { boolean success = false; String msg = null; try { Object[] params = new Object[args.length + 1]; params[0] = oneAuth; for(int i=0; i<args.length; i++) params[i+1] = args[i]; Object[] result = (Object[]) client.execute("one."+action, params); success = (Boolean) result[0]; // In some cases, the xml-rpc response only has a boolean // OUT parameter if(result.length > 1) { try { msg = (String) result[1]; } catch (ClassCastException e) { // The result may be an Integer msg = ((Integer) result[1]).toString(); } } } catch (XmlRpcException e) { msg = e.getMessage(); } return new OneResponse(success, msg); } //-------------------------------------------------------------------------- // PRIVATE ATTRIBUTES AND METHODS //-------------------------------------------------------------------------- private String oneAuth; private String oneEndPoint; private XmlRpcClient client; private void setOneAuth(String secret) throws ClientConfigurationException { String oneSecret = secret; try { if(oneSecret == null) { String oneAuthEnv = System.getenv("ONE_AUTH"); File authFile; if ( oneAuthEnv != null && oneAuthEnv.length() != 0) { authFile = new File(oneAuthEnv); } else { authFile = new File(System.getenv("HOME")+"/.one/one_auth"); } oneSecret = (new BufferedReader(new FileReader(authFile))).readLine(); } String[] token = oneSecret.split(":"); if ( token.length > 2 ) { oneAuth = oneSecret; } - else if ( token.lenght == 2 ) + else if ( token.length == 2 ) { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] digest = md.digest(token[1].getBytes()); String hash = ""; for(byte aux : digest) { int b = aux & 0xff; if (Integer.toHexString(b).length() == 1) { hash += "0"; } hash += Integer.toHexString(b); } oneAuth = token[0] + ":" + hash; } else { throw new ClientConfigurationException( "Wrong format for authorization string: " + oneSecret + "\nFormat expected is user:password"); } } catch (FileNotFoundException e) { // This comes first, since it is a special case of IOException throw new ClientConfigurationException("ONE_AUTH file not present"); } catch (IOException e) { // You could have the file but for some reason the program can not // read it throw new ClientConfigurationException("ONE_AUTH file unreadable"); } catch (NoSuchAlgorithmException e) { // A client application cannot recover if the SHA-1 digest // algorithm cannot be initialized throw new RuntimeException( "Error initializing MessageDigest with SHA-1", e); } } private void setOneEndPoint(String endpoint) throws ClientConfigurationException { oneEndPoint = "http://localhost:2633/RPC2"; if(endpoint != null) { oneEndPoint = endpoint; } else { String oneXmlRpcEnv = System.getenv("ONE_XMLRPC"); if ( oneXmlRpcEnv != null && oneXmlRpcEnv.length() != 0 ) { oneEndPoint = oneXmlRpcEnv; } } XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(oneEndPoint)); } catch (MalformedURLException e) { throw new ClientConfigurationException( "The URL "+oneEndPoint+" is malformed."); } client = new XmlRpcClient(); client.setConfig(config); } }
true
true
private void setOneAuth(String secret) throws ClientConfigurationException { String oneSecret = secret; try { if(oneSecret == null) { String oneAuthEnv = System.getenv("ONE_AUTH"); File authFile; if ( oneAuthEnv != null && oneAuthEnv.length() != 0) { authFile = new File(oneAuthEnv); } else { authFile = new File(System.getenv("HOME")+"/.one/one_auth"); } oneSecret = (new BufferedReader(new FileReader(authFile))).readLine(); } String[] token = oneSecret.split(":"); if ( token.length > 2 ) { oneAuth = oneSecret; } else if ( token.lenght == 2 ) { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] digest = md.digest(token[1].getBytes()); String hash = ""; for(byte aux : digest) { int b = aux & 0xff; if (Integer.toHexString(b).length() == 1) { hash += "0"; } hash += Integer.toHexString(b); } oneAuth = token[0] + ":" + hash; } else { throw new ClientConfigurationException( "Wrong format for authorization string: " + oneSecret + "\nFormat expected is user:password"); } } catch (FileNotFoundException e) { // This comes first, since it is a special case of IOException throw new ClientConfigurationException("ONE_AUTH file not present"); } catch (IOException e) { // You could have the file but for some reason the program can not // read it throw new ClientConfigurationException("ONE_AUTH file unreadable"); } catch (NoSuchAlgorithmException e) { // A client application cannot recover if the SHA-1 digest // algorithm cannot be initialized throw new RuntimeException( "Error initializing MessageDigest with SHA-1", e); } }
private void setOneAuth(String secret) throws ClientConfigurationException { String oneSecret = secret; try { if(oneSecret == null) { String oneAuthEnv = System.getenv("ONE_AUTH"); File authFile; if ( oneAuthEnv != null && oneAuthEnv.length() != 0) { authFile = new File(oneAuthEnv); } else { authFile = new File(System.getenv("HOME")+"/.one/one_auth"); } oneSecret = (new BufferedReader(new FileReader(authFile))).readLine(); } String[] token = oneSecret.split(":"); if ( token.length > 2 ) { oneAuth = oneSecret; } else if ( token.length == 2 ) { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] digest = md.digest(token[1].getBytes()); String hash = ""; for(byte aux : digest) { int b = aux & 0xff; if (Integer.toHexString(b).length() == 1) { hash += "0"; } hash += Integer.toHexString(b); } oneAuth = token[0] + ":" + hash; } else { throw new ClientConfigurationException( "Wrong format for authorization string: " + oneSecret + "\nFormat expected is user:password"); } } catch (FileNotFoundException e) { // This comes first, since it is a special case of IOException throw new ClientConfigurationException("ONE_AUTH file not present"); } catch (IOException e) { // You could have the file but for some reason the program can not // read it throw new ClientConfigurationException("ONE_AUTH file unreadable"); } catch (NoSuchAlgorithmException e) { // A client application cannot recover if the SHA-1 digest // algorithm cannot be initialized throw new RuntimeException( "Error initializing MessageDigest with SHA-1", e); } }
diff --git a/HBaseAdapter/src/main/java/com/nearinfinity/hbaseclient/HBaseClient.java b/HBaseAdapter/src/main/java/com/nearinfinity/hbaseclient/HBaseClient.java index a872ad9f..2a1fc015 100644 --- a/HBaseAdapter/src/main/java/com/nearinfinity/hbaseclient/HBaseClient.java +++ b/HBaseAdapter/src/main/java/com/nearinfinity/hbaseclient/HBaseClient.java @@ -1,453 +1,453 @@ package com.nearinfinity.hbaseclient; import com.nearinfinity.hbaseclient.filter.UUIDFilter; import com.nearinfinity.hbaseclient.strategy.ScanStrategy; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.PrefixFilter; import org.apache.hadoop.hbase.util.Bytes; import org.apache.log4j.Logger; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * Created with IntelliJ IDEA. * User: jedstrom * Date: 7/25/12 * Time: 2:09 PM * To change this template use File | Settings | File Templates. */ public class HBaseClient { private HTable table; private HBaseAdmin admin; private WriteBuffer writeBuffer; private final ConcurrentHashMap<String, TableInfo> tableCache = new ConcurrentHashMap<String, TableInfo>(); private static final Logger logger = Logger.getLogger(HBaseClient.class); public HBaseClient(String tableName, String zkQuorum) { logger.info("HBaseClient: Constructing with HBase table name: " + tableName); logger.info("HBaseClient: Constructing with ZK Quorum: " + zkQuorum); Configuration configuration = HBaseConfiguration.create(); configuration.set("hbase.zookeeper.quorum", zkQuorum); try { this.admin = new HBaseAdmin(configuration); this.initializeSqlTable(); this.table = new HTable(configuration, tableName); this.writeBuffer = new WriteBuffer(table); } catch (MasterNotRunningException e) { logger.error("MasterNotRunningException thrown", e); } catch (ZooKeeperConnectionException e) { logger.error("ZooKeeperConnectionException thrown", e); } catch (IOException e) { logger.error("IOException thrown", e); } catch (InterruptedException e) { logger.error("InterruptedException thrown", e); } } private void initializeSqlTable() throws IOException, InterruptedException { HTableDescriptor sqlTableDescriptor; HColumnDescriptor nicColumn = new HColumnDescriptor(Constants.NIC); if (!this.admin.tableExists(Constants.SQL)) { logger.info("Creating sql table"); sqlTableDescriptor = new HTableDescriptor(Constants.SQL); sqlTableDescriptor.addFamily(nicColumn); this.admin.createTable(sqlTableDescriptor); } sqlTableDescriptor = this.admin.getTableDescriptor(Constants.SQL); if (!sqlTableDescriptor.hasFamily(Constants.NIC)) { logger.info("Adding nic column family to sql table"); if (!this.admin.isTableDisabled(Constants.SQL)) { logger.info("Disabling sql table"); this.admin.disableTable(Constants.SQL); } this.admin.addColumn(Constants.SQL, nicColumn); } if (this.admin.isTableDisabled(Constants.SQL)) { logger.info("Enabling sql table"); this.admin.enableTable(Constants.SQL); } this.admin.flush(Constants.SQL); } private void createTable(String tableName, List<Put> puts) throws IOException { //Get and increment the table counter (assumes it exists) long tableId = table.incrementColumnValue(RowKeyFactory.ROOT, Constants.NIC, new byte[0], 1); //Add a row with the table name puts.add(new Put(RowKeyFactory.ROOT).add(Constants.NIC, tableName.getBytes(), Bytes.toBytes(tableId))); //Cache the table tableCache.put(tableName, new TableInfo(tableName, tableId)); } private void addColumns(String tableName, Map<String, ColumnMetadata> columns, List<Put> puts) throws IOException { //Get table id from cache long tableId = tableCache.get(tableName).getId(); //Build the column row key byte[] columnBytes = ByteBuffer.allocate(9).put(RowType.COLUMNS.getValue()).putLong(tableId).array(); //Allocate ids and compute start id long numColumns = columns.size(); long lastColumnId = table.incrementColumnValue(columnBytes, Constants.NIC, new byte[0], numColumns); long startColumn = lastColumnId - numColumns; for (String columnName : columns.keySet()) { long columnId = ++startColumn; //Add column Put columnPut = new Put(columnBytes).add(Constants.NIC, columnName.getBytes(), Bytes.toBytes(columnId)); puts.add(columnPut); // Add column metadata byte[] columnInfoBytes = RowKeyFactory.buildColumnInfoKey(tableId, columnId); Put columnInfoPut = new Put(columnInfoBytes); ColumnMetadata metadata = columns.get(columnName); columnInfoPut.add(Constants.NIC, Constants.METADATA, metadata.toJson()); puts.add(columnInfoPut); //Add to cache tableCache.get(tableName).addColumn(columnName, columnId, columns.get(columnName)); } } public void createTableFull(String tableName, Map<String, ColumnMetadata> columns) throws IOException { //Batch put list List<Put> putList = new LinkedList<Put>(); //Create table and add to put list createTable(tableName, putList); //Create columns and add to put list addColumns(tableName, columns, putList); //Perform all puts writeBuffer.put(putList); writeBuffer.flushCommits(); } public void writeRow(String tableName, Map<String, byte[]> values) throws IOException { TableInfo info = getTableInfo(tableName); List<Put> putList = PutListFactory.createPutList(values, info); //Final put writeBuffer.put(putList); } public Result getDataRow(UUID uuid, String tableName) throws IOException { TableInfo info = getTableInfo(tableName); long tableId = info.getId(); byte[] rowKey = RowKeyFactory.buildDataKey(tableId, uuid); Get get = new Get(rowKey); return table.get(get); } public TableInfo getTableInfo(String tableName) throws IOException { if (tableCache.containsKey(tableName)) { return tableCache.get(tableName); } //Get the table id from HBase Get tableIdGet = new Get(RowKeyFactory.ROOT); Result result = table.get(tableIdGet); if (result.isEmpty()) { throw new TableNotFoundException(tableName + " was not found."); } long tableId = ByteBuffer.wrap(result.getValue(Constants.NIC, tableName.getBytes())).getLong(); TableInfo info = new TableInfo(tableName, tableId); byte[] rowKey = RowKeyFactory.buildColumnsKey(tableId); Get columnsGet = new Get(rowKey); Result columnsResult = table.get(columnsGet); Map<byte[], byte[]> columns = columnsResult.getFamilyMap(Constants.NIC); for (byte[] qualifier : columns.keySet()) { String columnName = new String(qualifier); long columnId = ByteBuffer.wrap(columns.get(qualifier)).getLong(); info.addColumn(columnName, columnId, getMetadataForColumn(tableId, columnId)); } tableCache.put(tableName, info); return info; } public ColumnMetadata getMetadataForColumn(long tableId, long columnId) throws IOException { Get metadataGet = new Get(RowKeyFactory.buildColumnInfoKey(tableId, columnId)); Result result = table.get(metadataGet); byte[] jsonBytes = result.getValue(Constants.NIC, Constants.METADATA); return new ColumnMetadata(jsonBytes); } public Map<String, byte[]> parseDataRow(Result result, String tableName) throws IOException { TableInfo info = getTableInfo(tableName); //Get columns returned from Result Map<String, byte[]> columns = new HashMap<String, byte[]>(); Map<byte[], byte[]> returnedColumns = result.getNoVersionMap().get(Constants.NIC); if (returnedColumns.size() == 1 && returnedColumns.containsKey(new byte[0])) { // The row of all nulls special case strikes again return columns; } //Loop through columns, add to returned map for (byte[] qualifier : returnedColumns.keySet()) { long columnId = ByteBuffer.wrap(qualifier).getLong(); String columnName = info.getColumnNameById(columnId); columns.put(columnName, returnedColumns.get(qualifier)); } return columns; } public boolean deleteRow(String tableName, UUID uuid) throws IOException { if (uuid == null) { return false; } TableInfo info = getTableInfo(tableName); long tableId = info.getId(); List<Delete> deleteList = new LinkedList<Delete>(); //Delete data row byte[] dataRowKey = RowKeyFactory.buildDataKey(tableId, uuid); deleteList.add(new Delete(dataRowKey)); Get get = new Get(dataRowKey); Result result = table.get(get); Map<String,byte[]> valueMap = parseDataRow(result, tableName); //Loop through ALL columns to determine which should be NULL - for (String columnName : valueMap.keySet()) { + for (String columnName : info.getColumnNames()) { long columnId = info.getColumnIdByName(columnName); byte[] value = valueMap.get(columnName); ColumnMetadata metadata = info.getColumnMetadata(columnName); ColumnType columnType = metadata.getType(); if (value == null) { byte[] nullIndexKey = RowKeyFactory.buildNullIndexKey(tableId, columnId, uuid); deleteList.add(new Delete(nullIndexKey)); continue; } //Determine pad length int padLength = 0; if (columnType == ColumnType.STRING || columnType == ColumnType.BINARY) { long maxLength = metadata.getMaxLength(); padLength = (int) maxLength - value.length; } byte[] indexKey = RowKeyFactory.buildValueIndexKey(tableId, columnId, value, uuid, columnType, padLength); byte[] reverseKey = RowKeyFactory.buildReverseIndexKey(tableId, columnId, value, columnType, uuid, padLength); deleteList.add(new Delete(indexKey)); deleteList.add(new Delete(reverseKey)); } // //Scan the index rows // byte[] indexStartKey = RowKeyFactory.buildValueIndexKey(tableId, 0L, new byte[0], uuid, ColumnType.NONE, 0); // byte[] indexEndKey = RowKeyFactory.buildValueIndexKey(tableId + 1, 0L, new byte[0], uuid, ColumnType.NONE, 0); // deleteList.addAll(scanAndDeleteAllUUIDs(indexStartKey, indexEndKey, uuid)); // // //Scan the reverse index rows // byte[] reverseStartKey = RowKeyFactory.buildReverseIndexKey(tableId, 0L, new byte[0], ColumnType.NONE, uuid, 0); // byte[] reverseEndKey = RowKeyFactory.buildReverseIndexKey(tableId+1, 0L, new byte[0], ColumnType.NONE, uuid, 0); // deleteList.addAll(scanAndDeleteAllUUIDs(reverseStartKey, reverseEndKey, uuid)); // // //Scan the null index rows // byte[] nullStartKey = RowKeyFactory.buildNullIndexKey(tableId, 0L, uuid); // byte[] nullEndKey = RowKeyFactory.buildNullIndexKey(tableId + 1, 0L, uuid); // deleteList.addAll(scanAndDeleteAllUUIDs(nullStartKey, nullEndKey, uuid)); table.delete(deleteList); return true; } private List<Delete> scanAndDeleteAllUUIDs(byte[] startKey, byte[] endKey, UUID uuid) throws IOException { List<Delete> deleteList = new LinkedList<Delete>(); Scan scan = ScanFactory.buildScan(startKey, endKey); Filter uuidFilter = new UUIDFilter(uuid); scan.setFilter(uuidFilter); for (Result result : table.getScanner(scan)) { deleteList.add(new Delete(result.getRow())); } return deleteList; } public boolean dropTable(String tableName) throws IOException { logger.info("Preparing to drop table " + tableName); TableInfo info = getTableInfo(tableName); long tableId = info.getId(); deleteIndexRows(tableId); deleteDataRows(tableId); deleteColumnInfoRows(info); deleteColumns(tableId); deleteTableFromRoot(tableName); logger.info("Table " + tableName + " is no more!"); return true; } public int deleteAllRows(String tableName) throws IOException { long tableId = getTableInfo(tableName).getId(); logger.info("Deleting all rows from table " + tableName + " with tableId " + tableId); deleteIndexRows(tableId); int rowsAffected = deleteDataRows(tableId); return rowsAffected; } public int deleteDataRows(long tableId) throws IOException { logger.info("Deleting all data rows"); byte[] prefix = ByteBuffer.allocate(9).put(RowType.DATA.getValue()).putLong(tableId).array(); return deleteRowsWithPrefix(prefix); } public int deleteColumns(long tableId) throws IOException { // TODO: Update this to delete column info rows when they are done logger.info("Deleting all columns"); byte[] prefix = ByteBuffer.allocate(9).put(RowType.COLUMNS.getValue()).putLong(tableId).array(); return deleteRowsWithPrefix(prefix); } public int deleteIndexRows(long tableId) throws IOException { logger.info("Deleting all index rows"); int affectedRows = 0; byte[] valuePrefix = ByteBuffer.allocate(9).put(RowType.PRIMARY_INDEX.getValue()).putLong(tableId).array(); byte[] reversePrefix = ByteBuffer.allocate(9).put(RowType.REVERSE_INDEX.getValue()).putLong(tableId).array(); byte[] nullPrefix = ByteBuffer.allocate(9).put(RowType.NULL_INDEX.getValue()).putLong(tableId).array(); affectedRows += deleteRowsWithPrefix(valuePrefix); affectedRows += deleteRowsWithPrefix(reversePrefix); affectedRows += deleteRowsWithPrefix(nullPrefix); return affectedRows; } public int deleteColumnInfoRows(TableInfo info) throws IOException { logger.info("Deleting all column metadata rows"); long tableId = info.getId(); int affectedRows = 0; for (Long columnId : info.getColumnIds()) { byte[] metadataKey = RowKeyFactory.buildColumnInfoKey(tableId, columnId); affectedRows += deleteRowsWithPrefix(metadataKey); } return affectedRows; } public int deleteRowsWithPrefix(byte[] prefix) throws IOException { Scan scan = ScanFactory.buildScan(); PrefixFilter filter = new PrefixFilter(prefix); scan.setFilter(filter); ResultScanner scanner = table.getScanner(scan); List<Delete> deleteList = new LinkedList<Delete>(); int count = 0; for (Result result : scanner) { //Delete the data row key byte[] rowKey = result.getRow(); Delete rowDelete = new Delete(rowKey); deleteList.add(rowDelete); ++count; } table.delete(deleteList); return count; } public void deleteTableFromRoot(String tableName) throws IOException { Delete delete = new Delete((RowKeyFactory.ROOT)); delete.deleteColumns(Constants.NIC, tableName.getBytes()); table.delete(delete); } public void setCacheSize(int cacheSize) { logger.info("Setting table scan row cache to " + cacheSize); ScanFactory.setCacheAmount(cacheSize); } public void setAutoFlushTables(boolean shouldFlushChangesImmediately) { this.writeBuffer.setAutoFlush(shouldFlushChangesImmediately); logger.info(shouldFlushChangesImmediately ? "Changes to tables will be written to HBase immediately" : "Changes to tables will be written to HBase when the write buffer has become full"); } public void setWriteBufferSize(long numBytes) { try { this.writeBuffer.setWriteBufferLimit(numBytes); } catch (IOException e) { logger.error("Encountered an error setting write buffer size", e); } logger.info("Size of HBase write buffer set to " + numBytes + " bytes (" + (numBytes / 1024 / 1024) + " megabytes)"); } public void flushWrites() { try { writeBuffer.flushCommits(); } catch (IOException e) { logger.error("Encountered an exception while flushing commits : ", e); } } public ResultScanner getScanner(ScanStrategy strategy) throws IOException { TableInfo info = getTableInfo(strategy.getTableName()); Scan scan = strategy.getScan(info); return table.getScanner(scan); } }
true
true
public boolean deleteRow(String tableName, UUID uuid) throws IOException { if (uuid == null) { return false; } TableInfo info = getTableInfo(tableName); long tableId = info.getId(); List<Delete> deleteList = new LinkedList<Delete>(); //Delete data row byte[] dataRowKey = RowKeyFactory.buildDataKey(tableId, uuid); deleteList.add(new Delete(dataRowKey)); Get get = new Get(dataRowKey); Result result = table.get(get); Map<String,byte[]> valueMap = parseDataRow(result, tableName); //Loop through ALL columns to determine which should be NULL for (String columnName : valueMap.keySet()) { long columnId = info.getColumnIdByName(columnName); byte[] value = valueMap.get(columnName); ColumnMetadata metadata = info.getColumnMetadata(columnName); ColumnType columnType = metadata.getType(); if (value == null) { byte[] nullIndexKey = RowKeyFactory.buildNullIndexKey(tableId, columnId, uuid); deleteList.add(new Delete(nullIndexKey)); continue; } //Determine pad length int padLength = 0; if (columnType == ColumnType.STRING || columnType == ColumnType.BINARY) { long maxLength = metadata.getMaxLength(); padLength = (int) maxLength - value.length; } byte[] indexKey = RowKeyFactory.buildValueIndexKey(tableId, columnId, value, uuid, columnType, padLength); byte[] reverseKey = RowKeyFactory.buildReverseIndexKey(tableId, columnId, value, columnType, uuid, padLength); deleteList.add(new Delete(indexKey)); deleteList.add(new Delete(reverseKey)); } // //Scan the index rows // byte[] indexStartKey = RowKeyFactory.buildValueIndexKey(tableId, 0L, new byte[0], uuid, ColumnType.NONE, 0); // byte[] indexEndKey = RowKeyFactory.buildValueIndexKey(tableId + 1, 0L, new byte[0], uuid, ColumnType.NONE, 0); // deleteList.addAll(scanAndDeleteAllUUIDs(indexStartKey, indexEndKey, uuid)); // // //Scan the reverse index rows // byte[] reverseStartKey = RowKeyFactory.buildReverseIndexKey(tableId, 0L, new byte[0], ColumnType.NONE, uuid, 0); // byte[] reverseEndKey = RowKeyFactory.buildReverseIndexKey(tableId+1, 0L, new byte[0], ColumnType.NONE, uuid, 0); // deleteList.addAll(scanAndDeleteAllUUIDs(reverseStartKey, reverseEndKey, uuid)); // // //Scan the null index rows // byte[] nullStartKey = RowKeyFactory.buildNullIndexKey(tableId, 0L, uuid); // byte[] nullEndKey = RowKeyFactory.buildNullIndexKey(tableId + 1, 0L, uuid); // deleteList.addAll(scanAndDeleteAllUUIDs(nullStartKey, nullEndKey, uuid)); table.delete(deleteList); return true; }
public boolean deleteRow(String tableName, UUID uuid) throws IOException { if (uuid == null) { return false; } TableInfo info = getTableInfo(tableName); long tableId = info.getId(); List<Delete> deleteList = new LinkedList<Delete>(); //Delete data row byte[] dataRowKey = RowKeyFactory.buildDataKey(tableId, uuid); deleteList.add(new Delete(dataRowKey)); Get get = new Get(dataRowKey); Result result = table.get(get); Map<String,byte[]> valueMap = parseDataRow(result, tableName); //Loop through ALL columns to determine which should be NULL for (String columnName : info.getColumnNames()) { long columnId = info.getColumnIdByName(columnName); byte[] value = valueMap.get(columnName); ColumnMetadata metadata = info.getColumnMetadata(columnName); ColumnType columnType = metadata.getType(); if (value == null) { byte[] nullIndexKey = RowKeyFactory.buildNullIndexKey(tableId, columnId, uuid); deleteList.add(new Delete(nullIndexKey)); continue; } //Determine pad length int padLength = 0; if (columnType == ColumnType.STRING || columnType == ColumnType.BINARY) { long maxLength = metadata.getMaxLength(); padLength = (int) maxLength - value.length; } byte[] indexKey = RowKeyFactory.buildValueIndexKey(tableId, columnId, value, uuid, columnType, padLength); byte[] reverseKey = RowKeyFactory.buildReverseIndexKey(tableId, columnId, value, columnType, uuid, padLength); deleteList.add(new Delete(indexKey)); deleteList.add(new Delete(reverseKey)); } // //Scan the index rows // byte[] indexStartKey = RowKeyFactory.buildValueIndexKey(tableId, 0L, new byte[0], uuid, ColumnType.NONE, 0); // byte[] indexEndKey = RowKeyFactory.buildValueIndexKey(tableId + 1, 0L, new byte[0], uuid, ColumnType.NONE, 0); // deleteList.addAll(scanAndDeleteAllUUIDs(indexStartKey, indexEndKey, uuid)); // // //Scan the reverse index rows // byte[] reverseStartKey = RowKeyFactory.buildReverseIndexKey(tableId, 0L, new byte[0], ColumnType.NONE, uuid, 0); // byte[] reverseEndKey = RowKeyFactory.buildReverseIndexKey(tableId+1, 0L, new byte[0], ColumnType.NONE, uuid, 0); // deleteList.addAll(scanAndDeleteAllUUIDs(reverseStartKey, reverseEndKey, uuid)); // // //Scan the null index rows // byte[] nullStartKey = RowKeyFactory.buildNullIndexKey(tableId, 0L, uuid); // byte[] nullEndKey = RowKeyFactory.buildNullIndexKey(tableId + 1, 0L, uuid); // deleteList.addAll(scanAndDeleteAllUUIDs(nullStartKey, nullEndKey, uuid)); table.delete(deleteList); return true; }
diff --git a/Data/MotionData.java b/Data/MotionData.java index df7c987..ee1279c 100644 --- a/Data/MotionData.java +++ b/Data/MotionData.java @@ -1,158 +1,158 @@ package Tools.Data; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.FileInputStream; import java.util.ArrayList; import java.awt.Point; public class MotionData{ public static final int TORSO = 0; public static final int NECK = 1; public static final int HEAD = 2; public static final int R_SHOULDER = 3; public static final int R_ELBOW = 4; public static final int R_HAND = 5; public static final int L_SHOULDER = 6; public static final int L_ELBOW = 7; public static final int L_HAND = 8; public static final int R_HIP = 9; public static final int R_KNEE = 10; public static final int R_FOOT = 11; public static final int L_HIP = 12; public static final int L_KNEE = 13; public static final int L_FOOT = 14; private static final Point[] line = { new Point(TORSO,NECK), new Point(NECK,HEAD), new Point(TORSO,R_SHOULDER), new Point(R_SHOULDER,R_ELBOW), new Point(R_ELBOW,R_HAND), new Point(TORSO,L_SHOULDER), new Point(L_SHOULDER,L_ELBOW), new Point(L_ELBOW,L_HAND), new Point(TORSO,R_HIP), new Point(R_HIP,R_KNEE), new Point(R_KNEE,R_FOOT), new Point(TORSO,L_HIP), new Point(L_HIP,L_KNEE), new Point(L_KNEE,L_FOOT), new Point(L_HIP,R_HIP), new Point(L_SHOULDER,R_SHOULDER) }; public static final int JOINT_NUMBER = 15; private ArrayList<Vec3D[]> data = new ArrayList<Vec3D[]>(); public MotionData(){} public Point[] getLine(){ return line.clone(); } public void add(Vec3D[] a){ data.add(a); } public int size(){ return data.size(); } public boolean readFile(BufferedReader in){ String str; data.clear(); try{ while((str = in.readLine()) != null){ Vec3D[] newData = new Vec3D[JOINT_NUMBER]; for(int i = 0; i < JOINT_NUMBER; i++){ - if(str == null){ + if(str == null && i > 0){ data.clear(); System.out.println("Illegal data format"); return false; } double[] d = new double[3]; String[] tmp = str.split(" "); for(int j = 0; j < 3; j++){ d[j] = Double.parseDouble(tmp[j]); } newData[i] = new Vec3D(d); -// System.out.println("("+data.size()+","+i+") : "+newData[i]); - str = in.readLine(); + // System.out.println("("+data.size()+","+i+") : "+newData[i]); + if(i < JOINT_NUMBER-1) str = in.readLine(); } data.add(newData); } in.close(); }catch(IOException e){ return false; } return true; } public boolean readFile(String s){ boolean ret; try{ BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(s))); ret = readFile(in); }catch(IOException e){ System.out.println("Cannot find \""+s+"\""); return false; } return ret; } public Vec3D[] get(int time){ if(time < 0 || time >= data.size()) return null; return data.get(time); } public Vec3D get(int time, int position){ if(time < 0 || time >= data.size() || position < 0 || position >= JOINT_NUMBER) return null; else return data.get(time)[position]; } public Vec3D[] convert(MotionData model, int i){ if(empty() || model.empty()){ return null; } Vec3D diff = new Vec3D(get(0,TORSO).sub(model.get(0,TORSO))); Vec3D[] vec = new Vec3D[JOINT_NUMBER]; vec[TORSO] = get(i,TORSO).add(diff); vec[NECK] = makeNext(model,vec,i, TORSO, NECK); vec[HEAD] = makeNext(model,vec,i, NECK, HEAD); vec[R_SHOULDER] = makeNext(model,vec,i, TORSO, R_SHOULDER); vec[R_ELBOW] = makeNext(model,vec,i, R_SHOULDER, R_ELBOW); vec[R_HAND] = makeNext(model,vec,i, R_ELBOW, R_HAND); vec[L_SHOULDER] = makeNext(model,vec,i, TORSO, L_SHOULDER); vec[L_ELBOW] = makeNext(model,vec,i, L_SHOULDER, L_ELBOW); vec[L_HAND] = makeNext(model,vec,i, L_ELBOW, L_HAND); vec[R_HIP] = makeNext(model,vec,i, TORSO, R_HIP); vec[R_KNEE] = makeNext(model,vec,i, R_HIP, R_KNEE); vec[R_FOOT] = makeNext(model,vec,i, R_KNEE, R_FOOT); vec[L_HIP] = makeNext(model,vec,i, TORSO, L_HIP); vec[L_KNEE] = makeNext(model,vec,i, L_HIP, L_KNEE); vec[L_FOOT] = makeNext(model,vec,i, L_KNEE, L_FOOT); return vec; } public boolean empty(){ return data.size() == 0; } public MotionData convertAll(MotionData model){ MotionData ret = new MotionData(); int end = Math.min(model.size(),size()); for(int i = 0; i < end; i++){ ret.add(convert(model,i)); } return ret; } private Vec3D makeNext(MotionData model, Vec3D[] ret, int t, int from, int to){ Vec3D unit = model.get(t,to).sub(model.get(t,from)); unit = unit.times(1.0/unit.abs()); return ret[from].add(unit.times((get(t,to).sub(get(t,from)).abs()))); } }
false
true
public boolean readFile(BufferedReader in){ String str; data.clear(); try{ while((str = in.readLine()) != null){ Vec3D[] newData = new Vec3D[JOINT_NUMBER]; for(int i = 0; i < JOINT_NUMBER; i++){ if(str == null){ data.clear(); System.out.println("Illegal data format"); return false; } double[] d = new double[3]; String[] tmp = str.split(" "); for(int j = 0; j < 3; j++){ d[j] = Double.parseDouble(tmp[j]); } newData[i] = new Vec3D(d); // System.out.println("("+data.size()+","+i+") : "+newData[i]); str = in.readLine(); } data.add(newData); } in.close(); }catch(IOException e){ return false; } return true; }
public boolean readFile(BufferedReader in){ String str; data.clear(); try{ while((str = in.readLine()) != null){ Vec3D[] newData = new Vec3D[JOINT_NUMBER]; for(int i = 0; i < JOINT_NUMBER; i++){ if(str == null && i > 0){ data.clear(); System.out.println("Illegal data format"); return false; } double[] d = new double[3]; String[] tmp = str.split(" "); for(int j = 0; j < 3; j++){ d[j] = Double.parseDouble(tmp[j]); } newData[i] = new Vec3D(d); // System.out.println("("+data.size()+","+i+") : "+newData[i]); if(i < JOINT_NUMBER-1) str = in.readLine(); } data.add(newData); } in.close(); }catch(IOException e){ return false; } return true; }
diff --git a/workspace/tv-show-crawler/src/com/example/tvshowcrawler/TVShowEditActivity.java b/workspace/tv-show-crawler/src/com/example/tvshowcrawler/TVShowEditActivity.java index ef96513..c19f7df 100644 --- a/workspace/tv-show-crawler/src/com/example/tvshowcrawler/TVShowEditActivity.java +++ b/workspace/tv-show-crawler/src/com/example/tvshowcrawler/TVShowEditActivity.java @@ -1,100 +1,100 @@ package com.example.tvshowcrawler; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.CheckBox; import android.widget.EditText; public class TVShowEditActivity extends Activity { @Override public void finish() { // called automatically when back button is pressed Intent intent = new Intent(); EditText nameEditText = (EditText) findViewById(R.id.editTextName); EditText seasonEditText = (EditText) findViewById(R.id.editTextSeason); EditText episodeEditText = (EditText) findViewById(R.id.editTextEpisode); CheckBox activeBox = (CheckBox) findViewById(R.id.checkBoxActive); if (nameEditText.getText().toString().trim().length() > 0) { // update show from views // set name, removing leading/trailing whitespace show.setName(nameEditText.getText().toString().trim()); // set season if (seasonEditText.getText().toString().trim().length() > 0) show.setSeason(Integer.parseInt(seasonEditText.getText().toString())); else show.setSeason(1); // default to 1 // set episode - if (seasonEditText.getText().toString().trim().length() > 0) + if (episodeEditText.getText().toString().trim().length() > 0) show.setEpisode(Integer.parseInt(episodeEditText.getText().toString())); else show.setEpisode(0); // default to 0 show.setActive(activeBox.isChecked()); intent.putExtra("tvShow", show); intent.putExtra("tvShowIndex", position); // ignored when adding new show intent.setAction(getIntent().getAction()); // return original action // Activity finished ok, return the data setResult(RESULT_OK, intent); } else { // no name entered, assume user wanted to cancel setResult(RESULT_CANCELED); } super.finish(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tvshowedit); final Intent intent = getIntent(); final String action = intent.getAction(); if (Intent.ACTION_EDIT.equals(action)) { // get TVShow from bundle position = intent.getExtras().getInt("tvShowIndex"); show = intent.getExtras().getParcelable("tvShow"); // update views EditText nameEditText = (EditText) findViewById(R.id.editTextName); nameEditText.setText(show.getName()); EditText seasonEditText = (EditText) findViewById(R.id.editTextSeason); seasonEditText.setText(String.valueOf(show.getSeason())); EditText episodeEditText = (EditText) findViewById(R.id.editTextEpisode); episodeEditText.setText(String.valueOf(show.getEpisode())); CheckBox activeBox = (CheckBox) findViewById(R.id.checkBoxActive); activeBox.setChecked(show.getActive()); } else if (Intent.ACTION_INSERT.equals(action)) { // create new show show = new TVShow(); } else { // Logs an error that the action was not understood, finishes the Activity, and // returns RESULT_CANCELED to an originating Activity. Log.e(TAG, "Unknown action, exiting"); finish(); return; } } private TVShow show; private int position; private static final String TAG = "TVShowCrawler"; }
true
true
public void finish() { // called automatically when back button is pressed Intent intent = new Intent(); EditText nameEditText = (EditText) findViewById(R.id.editTextName); EditText seasonEditText = (EditText) findViewById(R.id.editTextSeason); EditText episodeEditText = (EditText) findViewById(R.id.editTextEpisode); CheckBox activeBox = (CheckBox) findViewById(R.id.checkBoxActive); if (nameEditText.getText().toString().trim().length() > 0) { // update show from views // set name, removing leading/trailing whitespace show.setName(nameEditText.getText().toString().trim()); // set season if (seasonEditText.getText().toString().trim().length() > 0) show.setSeason(Integer.parseInt(seasonEditText.getText().toString())); else show.setSeason(1); // default to 1 // set episode if (seasonEditText.getText().toString().trim().length() > 0) show.setEpisode(Integer.parseInt(episodeEditText.getText().toString())); else show.setEpisode(0); // default to 0 show.setActive(activeBox.isChecked()); intent.putExtra("tvShow", show); intent.putExtra("tvShowIndex", position); // ignored when adding new show intent.setAction(getIntent().getAction()); // return original action // Activity finished ok, return the data setResult(RESULT_OK, intent); } else { // no name entered, assume user wanted to cancel setResult(RESULT_CANCELED); } super.finish(); }
public void finish() { // called automatically when back button is pressed Intent intent = new Intent(); EditText nameEditText = (EditText) findViewById(R.id.editTextName); EditText seasonEditText = (EditText) findViewById(R.id.editTextSeason); EditText episodeEditText = (EditText) findViewById(R.id.editTextEpisode); CheckBox activeBox = (CheckBox) findViewById(R.id.checkBoxActive); if (nameEditText.getText().toString().trim().length() > 0) { // update show from views // set name, removing leading/trailing whitespace show.setName(nameEditText.getText().toString().trim()); // set season if (seasonEditText.getText().toString().trim().length() > 0) show.setSeason(Integer.parseInt(seasonEditText.getText().toString())); else show.setSeason(1); // default to 1 // set episode if (episodeEditText.getText().toString().trim().length() > 0) show.setEpisode(Integer.parseInt(episodeEditText.getText().toString())); else show.setEpisode(0); // default to 0 show.setActive(activeBox.isChecked()); intent.putExtra("tvShow", show); intent.putExtra("tvShowIndex", position); // ignored when adding new show intent.setAction(getIntent().getAction()); // return original action // Activity finished ok, return the data setResult(RESULT_OK, intent); } else { // no name entered, assume user wanted to cancel setResult(RESULT_CANCELED); } super.finish(); }
diff --git a/plugins/org.eclipse.viatra2.patternlanguage.emf.ui/src/org/eclipse/viatra2/patternlanguage/ui/labeling/EMFPatternLanguageLabelProvider.java b/plugins/org.eclipse.viatra2.patternlanguage.emf.ui/src/org/eclipse/viatra2/patternlanguage/ui/labeling/EMFPatternLanguageLabelProvider.java index 15ec75bb..872219d0 100644 --- a/plugins/org.eclipse.viatra2.patternlanguage.emf.ui/src/org/eclipse/viatra2/patternlanguage/ui/labeling/EMFPatternLanguageLabelProvider.java +++ b/plugins/org.eclipse.viatra2.patternlanguage.emf.ui/src/org/eclipse/viatra2/patternlanguage/ui/labeling/EMFPatternLanguageLabelProvider.java @@ -1,183 +1,189 @@ /******************************************************************************* * Copyright (c) 2011 Zoltan Ujhelyi and Daniel Varro * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Zoltan Ujhelyi - initial API and implementation *******************************************************************************/ package org.eclipse.viatra2.patternlanguage.ui.labeling; import java.util.ArrayList; import java.util.List; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; import org.eclipse.viatra2.patternlanguage.EMFPatternLanguageScopeHelper; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.AggregatedValue; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.AggregatorExpression; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.BoolValue; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.CheckConstraint; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.CompareConstraint; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.CompareFeature; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.CountAggregator; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.DoubleValue; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.IntValue; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.ListValue; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PathExpressionConstraint; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PathExpressionHead; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PathExpressionTail; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.Pattern; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PatternBody; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PatternCall; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PatternCompositionConstraint; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.StringValue; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.ValueReference; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.VariableValue; import org.eclipse.viatra2.patternlanguage.eMFPatternLanguage.ClassType; import org.eclipse.viatra2.patternlanguage.eMFPatternLanguage.EClassifierConstraint; import org.eclipse.viatra2.patternlanguage.eMFPatternLanguage.EnumValue; import org.eclipse.viatra2.patternlanguage.eMFPatternLanguage.PackageImport; import org.eclipse.viatra2.patternlanguage.eMFPatternLanguage.PatternModel; import org.eclipse.viatra2.patternlanguage.eMFPatternLanguage.ReferenceType; import org.eclipse.xtext.ui.label.DefaultEObjectLabelProvider; import org.eclipse.xtext.util.Strings; import com.google.inject.Inject; /** * Provides labels for a EObjects. * * see http://www.eclipse.org/Xtext/documentation/latest/xtext.html#labelProvider */ public class EMFPatternLanguageLabelProvider extends DefaultEObjectLabelProvider { @Inject public EMFPatternLanguageLabelProvider(AdapterFactoryLabelProvider delegate) { super(delegate); } String text(PatternModel model) { return "Pattern Model"; } String text(PackageImport ele) { String name = (ele.getEPackage() != null) ? ele.getEPackage().getName() : "«package»"; return String.format("import %s", name); } String text(Pattern pattern) { return String.format("pattern %s/%d", pattern.getName(), pattern.getParameters().size()); } String text(PatternBody ele) { return String.format("body #%d", ((Pattern)ele.eContainer()).getBodies().indexOf(ele) + 1); } String text(EClassifierConstraint constraint) { String typename = ((ClassType)constraint.getType()).getClassname().getName(); return String.format("%s (%s)", typename, constraint.getVar().getVar()); } String text(CompareConstraint constraint) { CompareFeature feature = constraint.getFeature(); String op = feature.equals(CompareFeature.EQUALITY) ? "==" : feature.equals(CompareFeature.INEQUALITY) ? "!=" : "<???>"; String left = getValueText(constraint.getLeftOperand()); String right = getValueText(constraint.getRightOperand()); return String.format("%s %s %s", left, op, right); } String text(PatternCompositionConstraint constraint) { String modifiers = (constraint.isNegative()) ? "neg " : ""; return String.format("%s%s", modifiers, text(constraint.getCall())); } String text(PatternCall call) { String transitiveOp = call.isTransitive() ? "+" : ""; final String name = call.getPatternRef() == null ? "<null>" : call.getPatternRef().getName(); return String.format("find %s/%d%s", name, call.getParameters().size(), transitiveOp); } String text(PathExpressionConstraint constraint) { String typename = ((ClassType)constraint.getHead().getType()).getClassname().getName(); String varName = (constraint.getHead().getSrc() != null) ? constraint.getHead().getSrc().getVar() : "«type»"; return String.format("%s (%s)", typename, varName); } String text(CheckConstraint constraint) { return String.format("check()"); } String text(AggregatedValue aggregate) { String aggregator = getAggregatorText(aggregate.getAggregator()); String call = text(aggregate.getCall()); return String.format(/*"aggregate %s %s"*/"%s %s", aggregator, call); } String text(PathExpressionTail tail) { EStructuralFeature refname = ((ReferenceType)tail.getType()).getRefname(); String type = (refname != null) ? refname.getName() : "«type»"; String varName = ""; if (tail.getTail() == null) { PathExpressionHead head = EMFPatternLanguageScopeHelper.getExpressionHead(tail); varName = String.format("(%s)",getValueText(head.getDst())); } return String.format("%s %s",type, varName); } // String text(ComputationValue computation) { // // } private String getAggregatorText(AggregatorExpression aggregator) { if (aggregator instanceof CountAggregator) { return String.format("count"); } else return aggregator.toString(); } String getValueText(ValueReference ref) { if (ref instanceof VariableValue) { return ((VariableValue) ref).getValue().getVar(); } else if (ref instanceof IntValue) { return Integer.toString(((IntValue) ref).getValue()); } else if (ref instanceof BoolValue) { return Boolean.toString(((BoolValue) ref).isValue()); } else if (ref instanceof DoubleValue) { return Double.toString(((DoubleValue) ref).getValue()); } else if (ref instanceof ListValue) { EList<ValueReference> values = ((ListValue) ref).getValues(); List<String> valueStrings = new ArrayList<String>(); for (ValueReference valueReference : values) { valueStrings.add(getValueText(valueReference)); } return "{" + Strings.concat(", ", valueStrings)+ "}"; } else if (ref instanceof StringValue) { return "\"" + ((StringValue) ref).getValue() + "\""; } else if (ref instanceof EnumValue) { EnumValue enumVal = (EnumValue) ref; - return enumVal.getEnumeration().getName() + "::" + enumVal.getLiteral().getLiteral(); + String enumName; + if (enumVal.getEnumeration() != null) { + enumName = enumVal.getEnumeration().getName(); + } else { + enumName = enumVal.getLiteral().getEEnum().getName(); + } + return enumName + "::" + enumVal.getLiteral().getLiteral(); } else if (ref instanceof AggregatedValue) { return text((AggregatedValue)ref); } return null; } /* //Labels and icons can be computed like this: String text(MyModel ele) { return "my "+ele.getName(); } String image(MyModel ele) { return "MyModel.gif"; } */ }
true
true
String getValueText(ValueReference ref) { if (ref instanceof VariableValue) { return ((VariableValue) ref).getValue().getVar(); } else if (ref instanceof IntValue) { return Integer.toString(((IntValue) ref).getValue()); } else if (ref instanceof BoolValue) { return Boolean.toString(((BoolValue) ref).isValue()); } else if (ref instanceof DoubleValue) { return Double.toString(((DoubleValue) ref).getValue()); } else if (ref instanceof ListValue) { EList<ValueReference> values = ((ListValue) ref).getValues(); List<String> valueStrings = new ArrayList<String>(); for (ValueReference valueReference : values) { valueStrings.add(getValueText(valueReference)); } return "{" + Strings.concat(", ", valueStrings)+ "}"; } else if (ref instanceof StringValue) { return "\"" + ((StringValue) ref).getValue() + "\""; } else if (ref instanceof EnumValue) { EnumValue enumVal = (EnumValue) ref; return enumVal.getEnumeration().getName() + "::" + enumVal.getLiteral().getLiteral(); } else if (ref instanceof AggregatedValue) { return text((AggregatedValue)ref); } return null; }
String getValueText(ValueReference ref) { if (ref instanceof VariableValue) { return ((VariableValue) ref).getValue().getVar(); } else if (ref instanceof IntValue) { return Integer.toString(((IntValue) ref).getValue()); } else if (ref instanceof BoolValue) { return Boolean.toString(((BoolValue) ref).isValue()); } else if (ref instanceof DoubleValue) { return Double.toString(((DoubleValue) ref).getValue()); } else if (ref instanceof ListValue) { EList<ValueReference> values = ((ListValue) ref).getValues(); List<String> valueStrings = new ArrayList<String>(); for (ValueReference valueReference : values) { valueStrings.add(getValueText(valueReference)); } return "{" + Strings.concat(", ", valueStrings)+ "}"; } else if (ref instanceof StringValue) { return "\"" + ((StringValue) ref).getValue() + "\""; } else if (ref instanceof EnumValue) { EnumValue enumVal = (EnumValue) ref; String enumName; if (enumVal.getEnumeration() != null) { enumName = enumVal.getEnumeration().getName(); } else { enumName = enumVal.getLiteral().getEEnum().getName(); } return enumName + "::" + enumVal.getLiteral().getLiteral(); } else if (ref instanceof AggregatedValue) { return text((AggregatedValue)ref); } return null; }
diff --git a/src/com/mobilepearls/sokoban/SokobanGameState.java b/src/com/mobilepearls/sokoban/SokobanGameState.java index 7a56f1d..302e560 100644 --- a/src/com/mobilepearls/sokoban/SokobanGameState.java +++ b/src/com/mobilepearls/sokoban/SokobanGameState.java @@ -1,225 +1,229 @@ package com.mobilepearls.sokoban; import java.io.Serializable; import java.util.LinkedList; @SuppressWarnings("serial") public class SokobanGameState implements Serializable { static class Undo implements Serializable { public char c1; public char c2; public char c3; public byte x1; public byte x2; public byte x3; public byte y1; public byte y2; public byte y3; } public static final char CHAR_DIAMOND_ON_FLOOR = '$'; public static final char CHAR_DIAMOND_ON_TARGET = '*'; public static final char CHAR_FLOOR = ' '; public static final char CHAR_MAN_ON_FLOOR = '@'; public static final char CHAR_MAN_ON_TARGET = '+'; public static final char CHAR_TARGET = '.'; public static final char CHAR_WALL = '#'; private static char newCharWhenDiamondPushed(char current) { return (current == CHAR_FLOOR) ? CHAR_DIAMOND_ON_FLOOR : CHAR_DIAMOND_ON_TARGET; } private static char newCharWhenManEnters(char current) { switch (current) { case CHAR_FLOOR: case CHAR_DIAMOND_ON_FLOOR: return CHAR_MAN_ON_FLOOR; case CHAR_TARGET: case CHAR_DIAMOND_ON_TARGET: return CHAR_MAN_ON_TARGET; } throw new RuntimeException("Invalid current char: '" + current + "'"); } private static char originalCharWhenManLeaves(char current) { return (current == CHAR_MAN_ON_FLOOR) ? CHAR_FLOOR : CHAR_TARGET; } private static char[][] stringArrayToCharMatrix(String[] s) { char[][] result = new char[s[0].length()][s.length]; for (int x = 0; x < s[0].length(); x++) { for (int y = 0; y < s.length; y++) { result[x][y] = s[y].charAt(x); } } return result; } private int currentLevel; final int currentLevelSet; private char[][] map; private transient final int[] playerPosition = new int[2]; final LinkedList<Undo> undos = new LinkedList<Undo>(); public SokobanGameState(int level, int levelSet) { currentLevel = level; currentLevelSet = levelSet; loadLevel(currentLevel, levelSet); } public int getCurrentLevel() { return currentLevel; } public int getHeightInTiles() { return map[0].length; } public char getItemAt(int x, int y) { return map[x][y]; } public int[] getPlayerPosition() { for (int x = 0; x < map.length; x++) { for (int y = 0; y < map[0].length; y++) { char c = map[x][y]; if (CHAR_MAN_ON_FLOOR == c || CHAR_MAN_ON_TARGET == c) { playerPosition[0] = x; playerPosition[1] = y; } } } return playerPosition; } public int getWidthInTiles() { return map.length; } public boolean isDone() { for (int x = 0; x < map.length; x++) for (int y = 0; y < map[0].length; y++) if (map[x][y] == CHAR_DIAMOND_ON_FLOOR) return false; return true; } private void loadLevel(int level, int levelSet) { this.currentLevel = level; map = stringArrayToCharMatrix(SokobanLevels.levelMaps.get(levelSet)[level]); } public boolean performUndo() { if (undos.isEmpty()) return false; Undo undo = undos.removeLast(); map[undo.x1][undo.y1] = undo.c1; map[undo.x2][undo.y2] = undo.c2; if (undo.c3 != 0) map[undo.x3][undo.y3] = undo.c3; return true; } public void restart() { loadLevel(currentLevel, currentLevelSet); undos.clear(); } /** Return whether something was changed. */ public boolean tryMove(int dx, int dy) { if (dx == 0 && dy == 0) return false; if (dx != 0 && dy != 0) { throw new IllegalArgumentException("Can only move straight lines. dx=" + dx + ", dy=" + dy); } int steps = Math.max(Math.abs(dx), Math.abs(dy)); int stepX = (dx == 0) ? 0 : (int) Math.signum(dx); int stepY = (dy == 0) ? 0 : (int) Math.signum(dy); boolean somethingChanged = false; int playerX = -1; int playerY = -1; // find player position for (int x = 0; x < map.length; x++) { for (int y = 0; y < map[0].length; y++) { char c = map[x][y]; if (CHAR_MAN_ON_FLOOR == c || CHAR_MAN_ON_TARGET == c) { playerX = x; playerY = y; } } } for (int i = 0; i < steps; i++) { int newX = playerX + stepX; int newY = playerY + stepY; boolean ok = false; boolean pushed = false; switch (map[newX][newY]) { case CHAR_FLOOR: // move to empty space case CHAR_TARGET: // move to empty target ok = true; break; case CHAR_DIAMOND_ON_FLOOR: // pushing away diamond on floor case CHAR_DIAMOND_ON_TARGET: // pushing away diamond on target char pushTo = map[newX + stepX][newY + stepY]; ok = (pushTo == CHAR_FLOOR || pushTo == CHAR_TARGET); // ok if pushing to empty space if (ok) { pushed = true; } break; } if (ok) { Undo undo; if (undos.size() > 2000) { // size of undo: 9 bytes + object overhead = 25? // reuse and clear undo object undo = undos.removeFirst(); undo.c3 = 0; } else { undo = new Undo(); } undos.add(undo); somethingChanged = true; if (pushed) { byte pushedX = (byte) (newX + stepX); byte pushedY = (byte) (newY + stepY); undo.x3 = pushedX; undo.y3 = pushedY; undo.c3 = map[pushedX][pushedY]; map[pushedX][pushedY] = newCharWhenDiamondPushed(map[pushedX][pushedY]); } undo.x1 = (byte) playerX; undo.y1 = (byte) playerY; undo.c1 = map[playerX][playerY]; map[playerX][playerY] = originalCharWhenManLeaves(map[playerX][playerY]); undo.x2 = (byte) newX; undo.y2 = (byte) newY; undo.c2 = map[newX][newY]; map[newX][newY] = newCharWhenManEnters(map[newX][newY]); playerX = newX; playerY = newY; + if (isDone()) { + // if moving multiple steps at once, stop if an intermediate step may finish the game: + return true; + } } } return somethingChanged; } }
true
true
public boolean tryMove(int dx, int dy) { if (dx == 0 && dy == 0) return false; if (dx != 0 && dy != 0) { throw new IllegalArgumentException("Can only move straight lines. dx=" + dx + ", dy=" + dy); } int steps = Math.max(Math.abs(dx), Math.abs(dy)); int stepX = (dx == 0) ? 0 : (int) Math.signum(dx); int stepY = (dy == 0) ? 0 : (int) Math.signum(dy); boolean somethingChanged = false; int playerX = -1; int playerY = -1; // find player position for (int x = 0; x < map.length; x++) { for (int y = 0; y < map[0].length; y++) { char c = map[x][y]; if (CHAR_MAN_ON_FLOOR == c || CHAR_MAN_ON_TARGET == c) { playerX = x; playerY = y; } } } for (int i = 0; i < steps; i++) { int newX = playerX + stepX; int newY = playerY + stepY; boolean ok = false; boolean pushed = false; switch (map[newX][newY]) { case CHAR_FLOOR: // move to empty space case CHAR_TARGET: // move to empty target ok = true; break; case CHAR_DIAMOND_ON_FLOOR: // pushing away diamond on floor case CHAR_DIAMOND_ON_TARGET: // pushing away diamond on target char pushTo = map[newX + stepX][newY + stepY]; ok = (pushTo == CHAR_FLOOR || pushTo == CHAR_TARGET); // ok if pushing to empty space if (ok) { pushed = true; } break; } if (ok) { Undo undo; if (undos.size() > 2000) { // size of undo: 9 bytes + object overhead = 25? // reuse and clear undo object undo = undos.removeFirst(); undo.c3 = 0; } else { undo = new Undo(); } undos.add(undo); somethingChanged = true; if (pushed) { byte pushedX = (byte) (newX + stepX); byte pushedY = (byte) (newY + stepY); undo.x3 = pushedX; undo.y3 = pushedY; undo.c3 = map[pushedX][pushedY]; map[pushedX][pushedY] = newCharWhenDiamondPushed(map[pushedX][pushedY]); } undo.x1 = (byte) playerX; undo.y1 = (byte) playerY; undo.c1 = map[playerX][playerY]; map[playerX][playerY] = originalCharWhenManLeaves(map[playerX][playerY]); undo.x2 = (byte) newX; undo.y2 = (byte) newY; undo.c2 = map[newX][newY]; map[newX][newY] = newCharWhenManEnters(map[newX][newY]); playerX = newX; playerY = newY; } } return somethingChanged; }
public boolean tryMove(int dx, int dy) { if (dx == 0 && dy == 0) return false; if (dx != 0 && dy != 0) { throw new IllegalArgumentException("Can only move straight lines. dx=" + dx + ", dy=" + dy); } int steps = Math.max(Math.abs(dx), Math.abs(dy)); int stepX = (dx == 0) ? 0 : (int) Math.signum(dx); int stepY = (dy == 0) ? 0 : (int) Math.signum(dy); boolean somethingChanged = false; int playerX = -1; int playerY = -1; // find player position for (int x = 0; x < map.length; x++) { for (int y = 0; y < map[0].length; y++) { char c = map[x][y]; if (CHAR_MAN_ON_FLOOR == c || CHAR_MAN_ON_TARGET == c) { playerX = x; playerY = y; } } } for (int i = 0; i < steps; i++) { int newX = playerX + stepX; int newY = playerY + stepY; boolean ok = false; boolean pushed = false; switch (map[newX][newY]) { case CHAR_FLOOR: // move to empty space case CHAR_TARGET: // move to empty target ok = true; break; case CHAR_DIAMOND_ON_FLOOR: // pushing away diamond on floor case CHAR_DIAMOND_ON_TARGET: // pushing away diamond on target char pushTo = map[newX + stepX][newY + stepY]; ok = (pushTo == CHAR_FLOOR || pushTo == CHAR_TARGET); // ok if pushing to empty space if (ok) { pushed = true; } break; } if (ok) { Undo undo; if (undos.size() > 2000) { // size of undo: 9 bytes + object overhead = 25? // reuse and clear undo object undo = undos.removeFirst(); undo.c3 = 0; } else { undo = new Undo(); } undos.add(undo); somethingChanged = true; if (pushed) { byte pushedX = (byte) (newX + stepX); byte pushedY = (byte) (newY + stepY); undo.x3 = pushedX; undo.y3 = pushedY; undo.c3 = map[pushedX][pushedY]; map[pushedX][pushedY] = newCharWhenDiamondPushed(map[pushedX][pushedY]); } undo.x1 = (byte) playerX; undo.y1 = (byte) playerY; undo.c1 = map[playerX][playerY]; map[playerX][playerY] = originalCharWhenManLeaves(map[playerX][playerY]); undo.x2 = (byte) newX; undo.y2 = (byte) newY; undo.c2 = map[newX][newY]; map[newX][newY] = newCharWhenManEnters(map[newX][newY]); playerX = newX; playerY = newY; if (isDone()) { // if moving multiple steps at once, stop if an intermediate step may finish the game: return true; } } } return somethingChanged; }
diff --git a/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/DefaultNetIdManagementService.java b/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/DefaultNetIdManagementService.java index 5e925732..9ec6b846 100644 --- a/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/DefaultNetIdManagementService.java +++ b/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/DefaultNetIdManagementService.java @@ -1,140 +1,140 @@ package org.openregistry.core.service.identifier; import org.openregistry.core.domain.AuxiliaryIdentifier; import org.openregistry.core.domain.Identifier; import org.openregistry.core.domain.IdentifierType; import org.openregistry.core.domain.Person; import org.openregistry.core.domain.validation.IdentifierFormatValidator; import org.openregistry.core.repository.AuxiliaryIdentifierRepository; import org.openregistry.core.repository.ReferenceRepository; import org.openregistry.core.repository.RepositoryAccessException; import org.openregistry.core.service.GeneralServiceExecutionResult; import org.openregistry.core.service.PersonService; import org.openregistry.core.service.ServiceExecutionResult; import org.openregistry.core.service.auxiliaryprograms.AuxiliaryProgramService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import static java.lang.String.format; import javax.inject.Inject; import java.util.Date; import java.util.Deque; import java.util.List; import java.util.Map; /** * @since 1.0 */ @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Service public class DefaultNetIdManagementService implements NetIdManagementService { private PersonService personService; private ReferenceRepository referenceRepository; private String netIdTypeCode = "NETID"; private AuxiliaryIdentifierRepository auxiliaryIdentifierRepository; @Inject private IdentifierFormatValidator identifierFormatValidatorImpl; @Inject public DefaultNetIdManagementService(PersonService personService, ReferenceRepository referenceRepository, AuxiliaryIdentifierRepository auxiliaryIdentifierRepository ) { this.personService = personService; this.referenceRepository = referenceRepository; this.auxiliaryIdentifierRepository = auxiliaryIdentifierRepository; } public void setNetIdTypeCode(String netIdTypeCode) { this.netIdTypeCode = netIdTypeCode; } @Override public ServiceExecutionResult<Identifier> changePrimaryNetId(String currentNetIdValue, String newNetIdValue) throws IllegalArgumentException, IllegalStateException { if(currentNetIdValue == newNetIdValue) { throw new IllegalArgumentException("Primary and Non-Primary net ids cannot be the same"); } //Check if the netId is according to proper format if(!identifierFormatValidatorImpl.isNetIDAcceptable(newNetIdValue)){ throw new IllegalArgumentException("NetId is not according to accepted format"); } final Person person = this.personService.findPersonByIdentifier(netIdTypeCode, currentNetIdValue); if (person == null) { throw new IllegalArgumentException(format("The person with the provided netid [%s] does not exist", currentNetIdValue)); } final Person person2 = this.personService.findPersonByIdentifier(netIdTypeCode, newNetIdValue); if (person2 != null && person.getId() != person2.getId()) { throw new IllegalStateException(format("The person with the proposed new netid [%s] already exists.", newNetIdValue)); } //check if the netId already exists for an auxiliary program (also called program account) if (auxiliaryIdentifierRepository.identifierExistsForProgramAccount(newNetIdValue,netIdTypeCode)) { throw new IllegalStateException(format("netid [%s] already exists for a program.", newNetIdValue)); } Map<String, Identifier> primaryIds = person.getPrimaryIdentifiersByType(); Identifier currentNetId = primaryIds.get(netIdTypeCode); //Candidate for NPE - which is not handeled here as it would be serious data error to not have a primary netid if (currentNetId.getValue().equals(newNetIdValue)) { throw new IllegalStateException(format("The provided new primary netid [%s] already assigned to the person.", newNetIdValue)); } else if(!currentNetId.getValue().equals(currentNetIdValue)) { throw new IllegalArgumentException(format("The provided primary netid [%s] does not match the current primary netid", currentNetIdValue)); } //check if the provided new net id is already there, and if so, do the update, otherwise - do the insert. - providedId = person.findIdentifierByValue(netIdTypeCode, newNetIdValue); + Identifier providedId = person.findIdentifierByValue(netIdTypeCode, newNetIdValue); if (providedId == null) { final IdentifierType idType = this.referenceRepository.findIdentifierType(this.netIdTypeCode); providedId = person.addIdentifier(idType, newNetIdValue); } //TODO cleanup deleted flag? providedId.setPrimary(true); currentNetId.setDeletedDate(new Date()); currentNetId.setPrimary(false); return new GeneralServiceExecutionResult<Identifier>(providedId); } @Override public ServiceExecutionResult<Identifier> addNonPrimaryNetId(String primaryNetIdValue, String newNonPrimaryNetIdValue) throws IllegalArgumentException, IllegalStateException { //Check if the netId is according to proper format if(!identifierFormatValidatorImpl.isNetIDAcceptable(newNonPrimaryNetIdValue)){ throw new IllegalArgumentException("NetId is not according to accepted format"); } if ((this.personService.findPersonByIdentifier(netIdTypeCode, newNonPrimaryNetIdValue) != null)) { throw new IllegalStateException(format("The person with the proposed new netid [%s] already exists.", newNonPrimaryNetIdValue)); } //check if the NetID already exists for an auxiliary program (also called program account) if (auxiliaryIdentifierRepository.identifierExistsForProgramAccount(newNonPrimaryNetIdValue,netIdTypeCode)){ throw new IllegalStateException(format("netid [%s] already exists for a program.", newNonPrimaryNetIdValue)); } final Person person = this.personService.findPersonByIdentifier(netIdTypeCode, primaryNetIdValue); if (person == null) { throw new IllegalArgumentException(format("The person with the provided primary netid [%s] does not exist", primaryNetIdValue)); } Map<String, Identifier> primaryIds = person.getPrimaryIdentifiersByType(); Identifier i = primaryIds.get(netIdTypeCode); //Candidate for NPE - which is not handeled here as it would be serious data error to not have a primary netid if (!i.getValue().equals(primaryNetIdValue)) { throw new IllegalArgumentException(format("The provided primary netid [%s] does not match the current primary netid", primaryNetIdValue)); } final IdentifierType idType = this.referenceRepository.findIdentifierType(this.netIdTypeCode); final Identifier newNetId = person.addIdentifier(idType, newNonPrimaryNetIdValue); newNetId.setPrimary(false); return new GeneralServiceExecutionResult<Identifier>(newNetId); } }
true
true
public ServiceExecutionResult<Identifier> changePrimaryNetId(String currentNetIdValue, String newNetIdValue) throws IllegalArgumentException, IllegalStateException { if(currentNetIdValue == newNetIdValue) { throw new IllegalArgumentException("Primary and Non-Primary net ids cannot be the same"); } //Check if the netId is according to proper format if(!identifierFormatValidatorImpl.isNetIDAcceptable(newNetIdValue)){ throw new IllegalArgumentException("NetId is not according to accepted format"); } final Person person = this.personService.findPersonByIdentifier(netIdTypeCode, currentNetIdValue); if (person == null) { throw new IllegalArgumentException(format("The person with the provided netid [%s] does not exist", currentNetIdValue)); } final Person person2 = this.personService.findPersonByIdentifier(netIdTypeCode, newNetIdValue); if (person2 != null && person.getId() != person2.getId()) { throw new IllegalStateException(format("The person with the proposed new netid [%s] already exists.", newNetIdValue)); } //check if the netId already exists for an auxiliary program (also called program account) if (auxiliaryIdentifierRepository.identifierExistsForProgramAccount(newNetIdValue,netIdTypeCode)) { throw new IllegalStateException(format("netid [%s] already exists for a program.", newNetIdValue)); } Map<String, Identifier> primaryIds = person.getPrimaryIdentifiersByType(); Identifier currentNetId = primaryIds.get(netIdTypeCode); //Candidate for NPE - which is not handeled here as it would be serious data error to not have a primary netid if (currentNetId.getValue().equals(newNetIdValue)) { throw new IllegalStateException(format("The provided new primary netid [%s] already assigned to the person.", newNetIdValue)); } else if(!currentNetId.getValue().equals(currentNetIdValue)) { throw new IllegalArgumentException(format("The provided primary netid [%s] does not match the current primary netid", currentNetIdValue)); } //check if the provided new net id is already there, and if so, do the update, otherwise - do the insert. providedId = person.findIdentifierByValue(netIdTypeCode, newNetIdValue); if (providedId == null) { final IdentifierType idType = this.referenceRepository.findIdentifierType(this.netIdTypeCode); providedId = person.addIdentifier(idType, newNetIdValue); } //TODO cleanup deleted flag? providedId.setPrimary(true); currentNetId.setDeletedDate(new Date()); currentNetId.setPrimary(false); return new GeneralServiceExecutionResult<Identifier>(providedId); }
public ServiceExecutionResult<Identifier> changePrimaryNetId(String currentNetIdValue, String newNetIdValue) throws IllegalArgumentException, IllegalStateException { if(currentNetIdValue == newNetIdValue) { throw new IllegalArgumentException("Primary and Non-Primary net ids cannot be the same"); } //Check if the netId is according to proper format if(!identifierFormatValidatorImpl.isNetIDAcceptable(newNetIdValue)){ throw new IllegalArgumentException("NetId is not according to accepted format"); } final Person person = this.personService.findPersonByIdentifier(netIdTypeCode, currentNetIdValue); if (person == null) { throw new IllegalArgumentException(format("The person with the provided netid [%s] does not exist", currentNetIdValue)); } final Person person2 = this.personService.findPersonByIdentifier(netIdTypeCode, newNetIdValue); if (person2 != null && person.getId() != person2.getId()) { throw new IllegalStateException(format("The person with the proposed new netid [%s] already exists.", newNetIdValue)); } //check if the netId already exists for an auxiliary program (also called program account) if (auxiliaryIdentifierRepository.identifierExistsForProgramAccount(newNetIdValue,netIdTypeCode)) { throw new IllegalStateException(format("netid [%s] already exists for a program.", newNetIdValue)); } Map<String, Identifier> primaryIds = person.getPrimaryIdentifiersByType(); Identifier currentNetId = primaryIds.get(netIdTypeCode); //Candidate for NPE - which is not handeled here as it would be serious data error to not have a primary netid if (currentNetId.getValue().equals(newNetIdValue)) { throw new IllegalStateException(format("The provided new primary netid [%s] already assigned to the person.", newNetIdValue)); } else if(!currentNetId.getValue().equals(currentNetIdValue)) { throw new IllegalArgumentException(format("The provided primary netid [%s] does not match the current primary netid", currentNetIdValue)); } //check if the provided new net id is already there, and if so, do the update, otherwise - do the insert. Identifier providedId = person.findIdentifierByValue(netIdTypeCode, newNetIdValue); if (providedId == null) { final IdentifierType idType = this.referenceRepository.findIdentifierType(this.netIdTypeCode); providedId = person.addIdentifier(idType, newNetIdValue); } //TODO cleanup deleted flag? providedId.setPrimary(true); currentNetId.setDeletedDate(new Date()); currentNetId.setPrimary(false); return new GeneralServiceExecutionResult<Identifier>(providedId); }
diff --git a/src/cc/game/TestGame/screen/gamescreen/GameScreen.java b/src/cc/game/TestGame/screen/gamescreen/GameScreen.java index 2de452d..c1fdea5 100644 --- a/src/cc/game/TestGame/screen/gamescreen/GameScreen.java +++ b/src/cc/game/TestGame/screen/gamescreen/GameScreen.java @@ -1,41 +1,41 @@ package cc.game.TestGame.screen.gamescreen; import cc.game.TestGame.Camera; import cc.game.TestGame.World; import cc.game.TestGame.screen.Screen; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; /** * Created with IntelliJ IDEA. * User: calv * Date: 30/03/13 * Time: 14:29 * To change this template use File | Settings | File Templates. */ public abstract class GameScreen extends Screen { private Image bgImage; protected int levelID; protected GameScreen(World game, int levelID) { super(game); this.levelID = levelID; try { - this.bgImage = new Image("/res/screens/gamescreens" + this.levelID + ".png"); + this.bgImage = new Image("/res/screens/gamescreens/" + this.levelID + ".png"); } catch (SlickException e) { System.err.println("Couldn't load background image."); e.printStackTrace(); } } @Override public void update(GameContainer gameContainer, int deltaTime) throws SlickException { } @Override public void render(GameContainer paramGameContainer) { bgImage.draw(); } }
true
true
protected GameScreen(World game, int levelID) { super(game); this.levelID = levelID; try { this.bgImage = new Image("/res/screens/gamescreens" + this.levelID + ".png"); } catch (SlickException e) { System.err.println("Couldn't load background image."); e.printStackTrace(); } }
protected GameScreen(World game, int levelID) { super(game); this.levelID = levelID; try { this.bgImage = new Image("/res/screens/gamescreens/" + this.levelID + ".png"); } catch (SlickException e) { System.err.println("Couldn't load background image."); e.printStackTrace(); } }
diff --git a/plugins/org.teiid.designer.vdb.ui/src/org/teiid/designer/vdb/ui/translators/TranslatorOverridesPanel.java b/plugins/org.teiid.designer.vdb.ui/src/org/teiid/designer/vdb/ui/translators/TranslatorOverridesPanel.java index e10ee063e..ac0f445ad 100644 --- a/plugins/org.teiid.designer.vdb.ui/src/org/teiid/designer/vdb/ui/translators/TranslatorOverridesPanel.java +++ b/plugins/org.teiid.designer.vdb.ui/src/org/teiid/designer/vdb/ui/translators/TranslatorOverridesPanel.java @@ -1,877 +1,877 @@ /* * JBoss, Home of Professional Open Source. * * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. * * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. */ package org.teiid.designer.vdb.ui.translators; import static org.teiid.designer.vdb.ui.VdbUiConstants.Util; import static org.teiid.designer.vdb.ui.VdbUiConstants.Images.ADD; import static org.teiid.designer.vdb.ui.VdbUiConstants.Images.ADD_TRANSLATOR; import static org.teiid.designer.vdb.ui.VdbUiConstants.Images.EDIT_TRANSLATOR; import static org.teiid.designer.vdb.ui.VdbUiConstants.Images.EDIT; import static org.teiid.designer.vdb.ui.VdbUiConstants.Images.REMOVE; import static org.teiid.designer.vdb.ui.VdbUiConstants.Images.REMOVE_TRANSLATOR; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.ISharedImages; import org.teiid.core.designer.properties.PropertyDefinition; import org.teiid.core.designer.util.I18nUtil; import org.teiid.designer.core.util.StringUtilities; import org.teiid.designer.ui.common.UiPlugin; import org.teiid.designer.ui.common.util.WidgetFactory; import org.teiid.designer.ui.common.util.WidgetUtil; import org.teiid.designer.vdb.TranslatorOverride; import org.teiid.designer.vdb.TranslatorOverrideProperty; import org.teiid.designer.vdb.TranslatorPropertyDefinition; import org.teiid.designer.vdb.Vdb; import org.teiid.designer.vdb.connections.SourceHandler; import org.teiid.designer.vdb.connections.SourceHandlerExtensionManager; import org.teiid.designer.vdb.ui.VdbUiPlugin; /** * * * @since 8.0 */ public final class TranslatorOverridesPanel extends Composite { static final String PREFIX = I18nUtil.getPropertyPrefix(TranslatorOverridesPanel.class); Button addPropertyButton; Button deletePropertyButton; Button restorePropertyButton; Button addTranslatorButton; Button deleteTranslatorButton; Button editTranslatorButton; private final TableViewer propertiesViewer; private final TableViewer translatorsViewer; private final Text txtDescription; private final Vdb vdb; /** * @param parent * @param vdb */ public TranslatorOverridesPanel( Composite parent, Vdb vdb ) { super(parent, SWT.NONE); setLayout(new GridLayout()); setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); this.vdb = vdb; SashForm splitter = new SashForm(this, SWT.HORIZONTAL); splitter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); { // left-side is list of overridden translators Composite pnlTranslators = new Composite(splitter, SWT.BORDER); pnlTranslators.setLayout(new GridLayout()); pnlTranslators.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // // add the list for holding overridden translators // this.translatorsViewer = new TableViewer(pnlTranslators, (SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION | SWT.BORDER)); this.translatorsViewer.setContentProvider(new IStructuredContentProvider() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ @Override public void dispose() { // nothing to do } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ @Override public Object[] getElements( Object inputElement ) { return getTranslatorOverrides().toArray(); } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { // nothing to do } }); // sort the table rows by translator name this.translatorsViewer.setComparator(new ViewerComparator() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public int compare( Viewer viewer, Object t1, Object t2 ) { TranslatorOverride translator1 = (TranslatorOverride)t1; TranslatorOverride translator2 = (TranslatorOverride)t2; return super.compare(viewer, translator1.getName(), translator2.getName()); } }); // add selection listener this.translatorsViewer.addSelectionChangedListener(new ISelectionChangedListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ @Override public void selectionChanged( SelectionChangedEvent event ) { handleTranslatorSelected(event); } }); final Table table = this.translatorsViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); table.setLayout(new TableLayout()); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // create column final TableViewerColumn column = new TableViewerColumn(this.translatorsViewer, SWT.LEFT); column.getColumn().setText(Util.getString(PREFIX + "translatorColumn.text")); //$NON-NLS-1$ column.setLabelProvider(new ColumnLabelProvider() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ColumnLabelProvider#getText(java.lang.Object) */ @Override public String getText( Object element ) { TranslatorOverride translator = (TranslatorOverride)element; return translator.getName(); } }); column.getColumn().pack(); table.addControlListener(new ControlAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.ControlAdapter#controlResized(org.eclipse.swt.events.ControlEvent) */ @Override public void controlResized( ControlEvent e ) { column.getColumn().setWidth(table.getSize().x); } }); // // add toolbar below the list of translators // Composite toolbarPanel = WidgetFactory.createPanel(pnlTranslators, SWT.NONE, GridData.VERTICAL_ALIGN_BEGINNING, 1, 3); this.addTranslatorButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.addTranslatorButton.setImage(VdbUiPlugin.singleton.getImage(ADD_TRANSLATOR)); this.addTranslatorButton.setToolTipText(Util.getString(PREFIX + "addTranslatorAction.toolTip")); //$NON-NLS-1$ this.addTranslatorButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleAddTranslatorOverride(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.editTranslatorButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.editTranslatorButton.setImage(VdbUiPlugin.singleton.getImage(EDIT_TRANSLATOR)); this.editTranslatorButton.setToolTipText(Util.getString(PREFIX + "editTranslatorAction.toolTip")); //$NON-NLS-1$ this.editTranslatorButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleTranslatorRemoved(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.editTranslatorButton.setEnabled(false); this.deleteTranslatorButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.deleteTranslatorButton.setImage(VdbUiPlugin.singleton.getImage(REMOVE_TRANSLATOR)); this.deleteTranslatorButton.setToolTipText(Util.getString(PREFIX + "removeTranslatorAction.toolTip")); //$NON-NLS-1$ this.deleteTranslatorButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleTranslatorRemoved(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.deleteTranslatorButton.setEnabled(false); this.translatorsViewer.addDoubleClickListener(new IDoubleClickListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent) */ @Override public void doubleClick( DoubleClickEvent event ) { handleEditTranslatorOverride(); } }); } { // right-side is an override description and table with the selected translator's properties Composite pnlOverrides = new Composite(splitter, SWT.BORDER); pnlOverrides.setLayout(new GridLayout(2, false)); pnlOverrides.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); Label lblDescription = new Label(pnlOverrides, SWT.NONE); lblDescription.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); lblDescription.setText(Util.getString(PREFIX + "lblTranslatorDescription")); //$NON-NLS-1$ this.txtDescription = new Text(pnlOverrides, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); this.txtDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); ((GridData)this.txtDescription.getLayoutData()).heightHint = 35; this.txtDescription.setToolTipText(Util.getString(PREFIX + "txtTranslatorDescription.toolTip")); //$NON-NLS-1$ this.txtDescription.setEnabled(false); this.txtDescription.addModifyListener(new ModifyListener() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) */ @Override public void modifyText( ModifyEvent e ) { handleDescriptionChanged(); } }); this.propertiesViewer = new TableViewer(pnlOverrides, (SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION | SWT.BORDER)); ColumnViewerToolTipSupport.enableFor(this.propertiesViewer); this.propertiesViewer.setContentProvider(new IStructuredContentProvider() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ @Override public void dispose() { // nothing to do } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ @Override public Object[] getElements( Object inputElement ) { TranslatorOverride translator = getSelectedTranslator(); if (translator == null) { return new Object[0]; } return translator.getProperties(); } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { // nothing to do } }); // sort the table rows by display name this.propertiesViewer.setComparator(new ViewerComparator() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public int compare( Viewer viewer, Object e1, Object e2 ) { TranslatorOverrideProperty prop1 = (TranslatorOverrideProperty)e1; TranslatorOverrideProperty prop2 = (TranslatorOverrideProperty)e2; return super.compare(viewer, prop1.getDefinition().getDisplayName(), prop2.getDefinition().getDisplayName()); } }); Table table = this.propertiesViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); table.setLayout(new TableLayout()); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); ((GridData)table.getLayoutData()).horizontalSpan = 2; // create columns TableViewerColumn column = new TableViewerColumn(this.propertiesViewer, SWT.LEFT); column.getColumn().setText(Util.getString(PREFIX + "propertyColumn.text") + " "); //$NON-NLS-1$ //$NON-NLS-2$ column.setLabelProvider(new PropertyLabelProvider(true)); column.getColumn().pack(); column = new TableViewerColumn(this.propertiesViewer, SWT.LEFT); column.getColumn().setText(Util.getString(PREFIX + "valueColumn.text")); //$NON-NLS-1$ column.setLabelProvider(new PropertyLabelProvider(false)); column.setEditingSupport(new TranslatorOverridePropertyEditingSupport(this.propertiesViewer, this.vdb.getFile())); column.getColumn().pack(); this.propertiesViewer.addSelectionChangedListener(new ISelectionChangedListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ @Override public void selectionChanged( SelectionChangedEvent event ) { handlePropertySelected(event); } }); // // add toolbar below the table // Composite toolbarPanel = WidgetFactory.createPanel(pnlOverrides, SWT.NONE, GridData.VERTICAL_ALIGN_BEGINNING, 1, 3); this.addPropertyButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.addPropertyButton.setImage(VdbUiPlugin.singleton.getImage(ADD)); this.addPropertyButton.setToolTipText(Util.getString(PREFIX + "addPropertyAction.toolTip")); //$NON-NLS-1$ this.addPropertyButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleAddProperty(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.addPropertyButton.setEnabled(false); this.restorePropertyButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.restorePropertyButton.setEnabled(false); this.restorePropertyButton.setImage(VdbUiPlugin.singleton.getImage(EDIT)); - this.restorePropertyButton.setToolTipText(Util.getString(PREFIX + "restorePropertyAction.toolTip")); //$NON-NLS-1$ + this.restorePropertyButton.setToolTipText(Util.getString(PREFIX + "restorePropertyDefaultAction.toolTip")); //$NON-NLS-1$ this.restorePropertyButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleRestorePropertyDefaultValue(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.deletePropertyButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.deletePropertyButton.setEnabled(false); this.deletePropertyButton.setImage(VdbUiPlugin.singleton.getImage(REMOVE)); this.deletePropertyButton.setToolTipText(Util.getString(PREFIX + "removePropertyAction.toolTip")); //$NON-NLS-1$ this.deletePropertyButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handlePropertyRemoved(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); } splitter.setWeights(new int[] { 25, 75 }); // populate with data from the VDB this.translatorsViewer.setInput(this); this.propertiesViewer.setInput(this); } private TranslatorOverrideProperty getSelectedProperty() { IStructuredSelection selection = (IStructuredSelection)this.propertiesViewer.getSelection(); if (selection.isEmpty()) { return null; } return (TranslatorOverrideProperty)selection.getFirstElement(); } TranslatorOverride getSelectedTranslator() { ISelection selection = this.translatorsViewer.getSelection(); if (selection.isEmpty()) { return null; } return (TranslatorOverride)((IStructuredSelection)selection).getFirstElement(); } Set<TranslatorOverride> getTranslatorOverrides() { return this.vdb.getTranslators(); } private List<String> getTranslatorOverrideNames() { List<String> names = new ArrayList<String>(this.vdb.getTranslators().size()); for (TranslatorOverride translator : this.vdb.getTranslators()) { names.add(translator.getName()); } return names; } private String[] getTranslatorTypes() { SourceHandler handler = SourceHandlerExtensionManager.getVdbConnectionFinder(); return handler.getTranslatorTypes(); } void handleAddProperty() { assert (!this.translatorsViewer.getSelection().isEmpty()); AddPropertyDialog dialog = new AddPropertyDialog(getShell(), getSelectedTranslator().getPropertyNames()); if (dialog.open() == Window.OK) { // update model TranslatorOverride translator = getSelectedTranslator(); TranslatorOverrideProperty property = dialog.getProperty(); translator.addProperty(property); // update UI from model this.propertiesViewer.refresh(); // select the new property TranslatorPropertyDefinition propDefn = property.getDefinition(); for (TranslatorOverrideProperty prop : translator.getProperties()) { if (prop.getDefinition().equals(propDefn)) { this.propertiesViewer.setSelection(new StructuredSelection(prop), true); break; } } } } void handleAddTranslatorOverride() { TranslatorOverride translatorOverride = null; String[] translatorTypes = getTranslatorTypes(); // if no default teiid instance or server not connected then there won't be any translators if (translatorTypes == null) { AddTranslatorOverrideDialog dialog = new AddTranslatorOverrideDialog(getShell(), getTranslatorOverrideNames()); if (dialog.open() == Window.OK) { translatorOverride = new TranslatorOverride(this.vdb, dialog.getName(), dialog.getType(), null); } } else { EditTranslatorOverrideDialog dialog = new EditTranslatorOverrideDialog(getShell(), translatorTypes, this.vdb.getTranslators()); if (dialog.open() == Window.OK) { translatorOverride = new TranslatorOverride(this.vdb, dialog.getName(), dialog.getType(), null); } } if (translatorOverride != null) { // update model this.vdb.addTranslator(translatorOverride, null); // update UI this.translatorsViewer.refresh(); // reload translators this.translatorsViewer.setSelection(new StructuredSelection(translatorOverride), true); } } void handleDescriptionChanged() { if (!this.translatorsViewer.getSelection().isEmpty()) { TranslatorOverride translator = getSelectedTranslator(); translator.setDescription(this.txtDescription.getText()); } } void handleEditTranslatorOverride() { assert (!this.translatorsViewer.getSelection().isEmpty()); TranslatorOverride translatorOverride = getSelectedTranslator(); EditTranslatorOverrideDialog dialog = new EditTranslatorOverrideDialog(getShell(), translatorOverride, this.vdb.getTranslators()); if (dialog.open() == Window.OK) { this.translatorsViewer.refresh(translatorOverride); } } void handlePropertyRemoved() { TranslatorOverrideProperty selectedProperty = getSelectedProperty(); assert (selectedProperty != null); // update model TranslatorOverride translator = getSelectedTranslator(); translator.removeProperty(selectedProperty.getDefinition().getId()); // TODO need to dirty VDB // update UI this.propertiesViewer.refresh(); } void handlePropertySelected( SelectionChangedEvent event ) { IStructuredSelection selection = (IStructuredSelection)event.getSelection(); if (selection.isEmpty()) { if (this.deletePropertyButton.isEnabled()) { this.deletePropertyButton.setEnabled(false); } if (this.restorePropertyButton.isEnabled()) { this.restorePropertyButton.setEnabled(false); } } else { TranslatorOverrideProperty prop = (TranslatorOverrideProperty)selection.getFirstElement(); // only enable delete property if it is a custom property boolean enable = prop.isCustom(); if (this.deletePropertyButton.isEnabled() != enable) { this.deletePropertyButton.setEnabled(enable); } // only enable restore default value if it has overridden value enable = prop.hasOverridenValue(); if (this.restorePropertyButton.isEnabled() != enable) { this.restorePropertyButton.setEnabled(enable); } } } void handleRestorePropertyDefaultValue() { assert (!this.propertiesViewer.getSelection().isEmpty()); TranslatorOverrideProperty prop = getSelectedProperty(); prop.setValue(null); // TODO this needs to dirty VDB this.propertiesViewer.refresh(prop); this.restorePropertyButton.setEnabled(false); } void handleTranslatorRemoved() { assert (!this.translatorsViewer.getSelection().isEmpty()); TranslatorOverride translatorOverride = getSelectedTranslator(); if (this.vdb.removeTranslator(translatorOverride, null)) { this.translatorsViewer.remove(translatorOverride); } } void handleTranslatorSelected( SelectionChangedEvent event ) { ISelection selection = this.translatorsViewer.getSelection(); if (selection.isEmpty()) { this.txtDescription.setText(StringUtilities.EMPTY_STRING); if (this.txtDescription.isEnabled()) { this.txtDescription.setEnabled(false); } if (this.editTranslatorButton.isEnabled()) { this.editTranslatorButton.setEnabled(false); } if (this.deleteTranslatorButton.isEnabled()) { this.deleteTranslatorButton.setEnabled(false); } if (this.addPropertyButton.isEnabled()) { this.addPropertyButton.setEnabled(false); } } else { if (!this.txtDescription.isEnabled()) { this.txtDescription.setEnabled(true); } if (!this.editTranslatorButton.isEnabled()) { this.editTranslatorButton.setEnabled(true); } if (!this.deleteTranslatorButton.isEnabled()) { this.deleteTranslatorButton.setEnabled(true); } if (!this.addPropertyButton.isEnabled()) { this.addPropertyButton.setEnabled(true); } TranslatorOverride translator = getSelectedTranslator(); assert (translator != null); // get properties (server may have modified properties, server may be down, etc.) SourceHandler handler = SourceHandlerExtensionManager.getVdbConnectionFinder(); PropertyDefinition[] propertyDefinitionsFromServer = handler.getTranslatorDefinitions(translator.getType()); TranslatorOverrideProperty[] currentProps = translator.getProperties(); List<TranslatorOverrideProperty> propsToRemove = new ArrayList<TranslatorOverrideProperty>(); if (propertyDefinitionsFromServer != null) { List<PropertyDefinition> newServerProps = new ArrayList<PropertyDefinition>(); // assume all server properties are new for (PropertyDefinition propDefn : propertyDefinitionsFromServer) { newServerProps.add(propDefn); } if (currentProps.length != 0) { // translator properties already exist, match with server props for (TranslatorOverrideProperty property : currentProps) { PropertyDefinition serverPropDefn = null; // see if property definitions from server already exist in overridden translator for (PropertyDefinition propDefn : propertyDefinitionsFromServer) { // found a matching one if (property.getDefinition().getId().equals(propDefn.getId())) { serverPropDefn = propDefn; newServerProps.remove(propDefn); break; } } if (serverPropDefn != null) { // found existing property so update defn and use value from old defn translator.updatePropertyDefinition(property.getDefinition().getId(), serverPropDefn, false); } else if (property.hasOverridenValue()) { // not found on server but has an overridden value translator.markAsUserDefined(property); } else { // not found on server and has no overridden value so remove propsToRemove.add(property); } } } // add in new properties from server if (!newServerProps.isEmpty()) { for (PropertyDefinition delegate : newServerProps) { TranslatorOverrideProperty newProp = new TranslatorOverrideProperty(new TranslatorPropertyDefinition(delegate), null); translator.addProperty(newProp, false); } } } else { // no properties found for server so remove all without values (no default teiid instance, server is down) if (currentProps.length != 0) { for (TranslatorOverrideProperty property : currentProps) { if (!property.hasOverridenValue()) { propsToRemove.add(property); } } } } // remove orphaned properties that don't have overridden values if (!propsToRemove.isEmpty()) { for (TranslatorOverrideProperty property : propsToRemove) { translator.removeProperty(property.getDefinition().getId(), false); } } this.txtDescription.setText(translator.getDescription()); } this.propertiesViewer.refresh(); WidgetUtil.pack(this.propertiesViewer); } /** * Public access to refresh the contents of this panel based on external changes to the translator override * properties */ public void refresh() { this.translatorsViewer.setInput(this); this.translatorsViewer.refresh(); this.propertiesViewer.setInput(this); this.propertiesViewer.refresh(); } class PropertyLabelProvider extends ColumnLabelProvider { private final boolean nameColumn; public PropertyLabelProvider( boolean nameColumn ) { this.nameColumn = nameColumn; } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ColumnLabelProvider#getImage(java.lang.Object) */ @Override public Image getImage( Object element ) { TranslatorOverrideProperty property = (TranslatorOverrideProperty)element; String overridenValue = property.getOverriddenValue(); Image image = null; if (this.nameColumn) { if (property.isCustom()) { image = VdbUiPlugin.singleton.getImage(EDIT_TRANSLATOR); } } else { if (property.getDefinition().isValidValue(overridenValue) == null) { if (property.hasOverridenValue()) { if (!property.isCustom() || !property.getDefinition().getDefaultValue().equals(overridenValue)) { image = VdbUiPlugin.singleton.getImage(EDIT_TRANSLATOR); } } } else { image = UiPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_ERROR_TSK); } } return image; } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ColumnLabelProvider#getText(java.lang.Object) */ @Override public String getText( Object element ) { TranslatorOverrideProperty property = (TranslatorOverrideProperty)element; if (this.nameColumn) { return property.getDefinition().getDisplayName(); } boolean masked = property.getDefinition().isMasked(); final String maskedValue = "*****"; //$NON-NLS-1$ // return override value if it exists if (property.hasOverridenValue()) { return (masked ? maskedValue : property.getOverriddenValue()); } // return default value return (masked ? maskedValue : property.getDefinition().getDefaultValue()); } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.CellLabelProvider#getToolTipText(java.lang.Object) */ @Override public String getToolTipText( Object element ) { TranslatorOverrideProperty property = (TranslatorOverrideProperty)element; if (this.nameColumn) { return property.getDefinition().getDescription(); } if (property.hasOverridenValue()) { if (!property.isCustom() || !property.getDefinition().getDefaultValue().equals(property.getOverriddenValue())) { return property.getDefinition().isValidValue(property.getOverriddenValue()); } } // default value is being used return Util.getString(TranslatorOverridesPanel.PREFIX + "usingPropertyDefaultValue"); //$NON-NLS-1$ } } }
true
true
public TranslatorOverridesPanel( Composite parent, Vdb vdb ) { super(parent, SWT.NONE); setLayout(new GridLayout()); setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); this.vdb = vdb; SashForm splitter = new SashForm(this, SWT.HORIZONTAL); splitter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); { // left-side is list of overridden translators Composite pnlTranslators = new Composite(splitter, SWT.BORDER); pnlTranslators.setLayout(new GridLayout()); pnlTranslators.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // // add the list for holding overridden translators // this.translatorsViewer = new TableViewer(pnlTranslators, (SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION | SWT.BORDER)); this.translatorsViewer.setContentProvider(new IStructuredContentProvider() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ @Override public void dispose() { // nothing to do } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ @Override public Object[] getElements( Object inputElement ) { return getTranslatorOverrides().toArray(); } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { // nothing to do } }); // sort the table rows by translator name this.translatorsViewer.setComparator(new ViewerComparator() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public int compare( Viewer viewer, Object t1, Object t2 ) { TranslatorOverride translator1 = (TranslatorOverride)t1; TranslatorOverride translator2 = (TranslatorOverride)t2; return super.compare(viewer, translator1.getName(), translator2.getName()); } }); // add selection listener this.translatorsViewer.addSelectionChangedListener(new ISelectionChangedListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ @Override public void selectionChanged( SelectionChangedEvent event ) { handleTranslatorSelected(event); } }); final Table table = this.translatorsViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); table.setLayout(new TableLayout()); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // create column final TableViewerColumn column = new TableViewerColumn(this.translatorsViewer, SWT.LEFT); column.getColumn().setText(Util.getString(PREFIX + "translatorColumn.text")); //$NON-NLS-1$ column.setLabelProvider(new ColumnLabelProvider() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ColumnLabelProvider#getText(java.lang.Object) */ @Override public String getText( Object element ) { TranslatorOverride translator = (TranslatorOverride)element; return translator.getName(); } }); column.getColumn().pack(); table.addControlListener(new ControlAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.ControlAdapter#controlResized(org.eclipse.swt.events.ControlEvent) */ @Override public void controlResized( ControlEvent e ) { column.getColumn().setWidth(table.getSize().x); } }); // // add toolbar below the list of translators // Composite toolbarPanel = WidgetFactory.createPanel(pnlTranslators, SWT.NONE, GridData.VERTICAL_ALIGN_BEGINNING, 1, 3); this.addTranslatorButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.addTranslatorButton.setImage(VdbUiPlugin.singleton.getImage(ADD_TRANSLATOR)); this.addTranslatorButton.setToolTipText(Util.getString(PREFIX + "addTranslatorAction.toolTip")); //$NON-NLS-1$ this.addTranslatorButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleAddTranslatorOverride(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.editTranslatorButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.editTranslatorButton.setImage(VdbUiPlugin.singleton.getImage(EDIT_TRANSLATOR)); this.editTranslatorButton.setToolTipText(Util.getString(PREFIX + "editTranslatorAction.toolTip")); //$NON-NLS-1$ this.editTranslatorButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleTranslatorRemoved(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.editTranslatorButton.setEnabled(false); this.deleteTranslatorButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.deleteTranslatorButton.setImage(VdbUiPlugin.singleton.getImage(REMOVE_TRANSLATOR)); this.deleteTranslatorButton.setToolTipText(Util.getString(PREFIX + "removeTranslatorAction.toolTip")); //$NON-NLS-1$ this.deleteTranslatorButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleTranslatorRemoved(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.deleteTranslatorButton.setEnabled(false); this.translatorsViewer.addDoubleClickListener(new IDoubleClickListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent) */ @Override public void doubleClick( DoubleClickEvent event ) { handleEditTranslatorOverride(); } }); } { // right-side is an override description and table with the selected translator's properties Composite pnlOverrides = new Composite(splitter, SWT.BORDER); pnlOverrides.setLayout(new GridLayout(2, false)); pnlOverrides.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); Label lblDescription = new Label(pnlOverrides, SWT.NONE); lblDescription.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); lblDescription.setText(Util.getString(PREFIX + "lblTranslatorDescription")); //$NON-NLS-1$ this.txtDescription = new Text(pnlOverrides, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); this.txtDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); ((GridData)this.txtDescription.getLayoutData()).heightHint = 35; this.txtDescription.setToolTipText(Util.getString(PREFIX + "txtTranslatorDescription.toolTip")); //$NON-NLS-1$ this.txtDescription.setEnabled(false); this.txtDescription.addModifyListener(new ModifyListener() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) */ @Override public void modifyText( ModifyEvent e ) { handleDescriptionChanged(); } }); this.propertiesViewer = new TableViewer(pnlOverrides, (SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION | SWT.BORDER)); ColumnViewerToolTipSupport.enableFor(this.propertiesViewer); this.propertiesViewer.setContentProvider(new IStructuredContentProvider() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ @Override public void dispose() { // nothing to do } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ @Override public Object[] getElements( Object inputElement ) { TranslatorOverride translator = getSelectedTranslator(); if (translator == null) { return new Object[0]; } return translator.getProperties(); } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { // nothing to do } }); // sort the table rows by display name this.propertiesViewer.setComparator(new ViewerComparator() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public int compare( Viewer viewer, Object e1, Object e2 ) { TranslatorOverrideProperty prop1 = (TranslatorOverrideProperty)e1; TranslatorOverrideProperty prop2 = (TranslatorOverrideProperty)e2; return super.compare(viewer, prop1.getDefinition().getDisplayName(), prop2.getDefinition().getDisplayName()); } }); Table table = this.propertiesViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); table.setLayout(new TableLayout()); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); ((GridData)table.getLayoutData()).horizontalSpan = 2; // create columns TableViewerColumn column = new TableViewerColumn(this.propertiesViewer, SWT.LEFT); column.getColumn().setText(Util.getString(PREFIX + "propertyColumn.text") + " "); //$NON-NLS-1$ //$NON-NLS-2$ column.setLabelProvider(new PropertyLabelProvider(true)); column.getColumn().pack(); column = new TableViewerColumn(this.propertiesViewer, SWT.LEFT); column.getColumn().setText(Util.getString(PREFIX + "valueColumn.text")); //$NON-NLS-1$ column.setLabelProvider(new PropertyLabelProvider(false)); column.setEditingSupport(new TranslatorOverridePropertyEditingSupport(this.propertiesViewer, this.vdb.getFile())); column.getColumn().pack(); this.propertiesViewer.addSelectionChangedListener(new ISelectionChangedListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ @Override public void selectionChanged( SelectionChangedEvent event ) { handlePropertySelected(event); } }); // // add toolbar below the table // Composite toolbarPanel = WidgetFactory.createPanel(pnlOverrides, SWT.NONE, GridData.VERTICAL_ALIGN_BEGINNING, 1, 3); this.addPropertyButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.addPropertyButton.setImage(VdbUiPlugin.singleton.getImage(ADD)); this.addPropertyButton.setToolTipText(Util.getString(PREFIX + "addPropertyAction.toolTip")); //$NON-NLS-1$ this.addPropertyButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleAddProperty(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.addPropertyButton.setEnabled(false); this.restorePropertyButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.restorePropertyButton.setEnabled(false); this.restorePropertyButton.setImage(VdbUiPlugin.singleton.getImage(EDIT)); this.restorePropertyButton.setToolTipText(Util.getString(PREFIX + "restorePropertyAction.toolTip")); //$NON-NLS-1$ this.restorePropertyButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleRestorePropertyDefaultValue(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.deletePropertyButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.deletePropertyButton.setEnabled(false); this.deletePropertyButton.setImage(VdbUiPlugin.singleton.getImage(REMOVE)); this.deletePropertyButton.setToolTipText(Util.getString(PREFIX + "removePropertyAction.toolTip")); //$NON-NLS-1$ this.deletePropertyButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handlePropertyRemoved(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); } splitter.setWeights(new int[] { 25, 75 }); // populate with data from the VDB this.translatorsViewer.setInput(this); this.propertiesViewer.setInput(this); }
public TranslatorOverridesPanel( Composite parent, Vdb vdb ) { super(parent, SWT.NONE); setLayout(new GridLayout()); setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); this.vdb = vdb; SashForm splitter = new SashForm(this, SWT.HORIZONTAL); splitter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); { // left-side is list of overridden translators Composite pnlTranslators = new Composite(splitter, SWT.BORDER); pnlTranslators.setLayout(new GridLayout()); pnlTranslators.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // // add the list for holding overridden translators // this.translatorsViewer = new TableViewer(pnlTranslators, (SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION | SWT.BORDER)); this.translatorsViewer.setContentProvider(new IStructuredContentProvider() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ @Override public void dispose() { // nothing to do } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ @Override public Object[] getElements( Object inputElement ) { return getTranslatorOverrides().toArray(); } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { // nothing to do } }); // sort the table rows by translator name this.translatorsViewer.setComparator(new ViewerComparator() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public int compare( Viewer viewer, Object t1, Object t2 ) { TranslatorOverride translator1 = (TranslatorOverride)t1; TranslatorOverride translator2 = (TranslatorOverride)t2; return super.compare(viewer, translator1.getName(), translator2.getName()); } }); // add selection listener this.translatorsViewer.addSelectionChangedListener(new ISelectionChangedListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ @Override public void selectionChanged( SelectionChangedEvent event ) { handleTranslatorSelected(event); } }); final Table table = this.translatorsViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); table.setLayout(new TableLayout()); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // create column final TableViewerColumn column = new TableViewerColumn(this.translatorsViewer, SWT.LEFT); column.getColumn().setText(Util.getString(PREFIX + "translatorColumn.text")); //$NON-NLS-1$ column.setLabelProvider(new ColumnLabelProvider() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ColumnLabelProvider#getText(java.lang.Object) */ @Override public String getText( Object element ) { TranslatorOverride translator = (TranslatorOverride)element; return translator.getName(); } }); column.getColumn().pack(); table.addControlListener(new ControlAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.ControlAdapter#controlResized(org.eclipse.swt.events.ControlEvent) */ @Override public void controlResized( ControlEvent e ) { column.getColumn().setWidth(table.getSize().x); } }); // // add toolbar below the list of translators // Composite toolbarPanel = WidgetFactory.createPanel(pnlTranslators, SWT.NONE, GridData.VERTICAL_ALIGN_BEGINNING, 1, 3); this.addTranslatorButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.addTranslatorButton.setImage(VdbUiPlugin.singleton.getImage(ADD_TRANSLATOR)); this.addTranslatorButton.setToolTipText(Util.getString(PREFIX + "addTranslatorAction.toolTip")); //$NON-NLS-1$ this.addTranslatorButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleAddTranslatorOverride(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.editTranslatorButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.editTranslatorButton.setImage(VdbUiPlugin.singleton.getImage(EDIT_TRANSLATOR)); this.editTranslatorButton.setToolTipText(Util.getString(PREFIX + "editTranslatorAction.toolTip")); //$NON-NLS-1$ this.editTranslatorButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleTranslatorRemoved(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.editTranslatorButton.setEnabled(false); this.deleteTranslatorButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.deleteTranslatorButton.setImage(VdbUiPlugin.singleton.getImage(REMOVE_TRANSLATOR)); this.deleteTranslatorButton.setToolTipText(Util.getString(PREFIX + "removeTranslatorAction.toolTip")); //$NON-NLS-1$ this.deleteTranslatorButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleTranslatorRemoved(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.deleteTranslatorButton.setEnabled(false); this.translatorsViewer.addDoubleClickListener(new IDoubleClickListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent) */ @Override public void doubleClick( DoubleClickEvent event ) { handleEditTranslatorOverride(); } }); } { // right-side is an override description and table with the selected translator's properties Composite pnlOverrides = new Composite(splitter, SWT.BORDER); pnlOverrides.setLayout(new GridLayout(2, false)); pnlOverrides.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); Label lblDescription = new Label(pnlOverrides, SWT.NONE); lblDescription.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); lblDescription.setText(Util.getString(PREFIX + "lblTranslatorDescription")); //$NON-NLS-1$ this.txtDescription = new Text(pnlOverrides, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); this.txtDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); ((GridData)this.txtDescription.getLayoutData()).heightHint = 35; this.txtDescription.setToolTipText(Util.getString(PREFIX + "txtTranslatorDescription.toolTip")); //$NON-NLS-1$ this.txtDescription.setEnabled(false); this.txtDescription.addModifyListener(new ModifyListener() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) */ @Override public void modifyText( ModifyEvent e ) { handleDescriptionChanged(); } }); this.propertiesViewer = new TableViewer(pnlOverrides, (SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION | SWT.BORDER)); ColumnViewerToolTipSupport.enableFor(this.propertiesViewer); this.propertiesViewer.setContentProvider(new IStructuredContentProvider() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ @Override public void dispose() { // nothing to do } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ @Override public Object[] getElements( Object inputElement ) { TranslatorOverride translator = getSelectedTranslator(); if (translator == null) { return new Object[0]; } return translator.getProperties(); } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { // nothing to do } }); // sort the table rows by display name this.propertiesViewer.setComparator(new ViewerComparator() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public int compare( Viewer viewer, Object e1, Object e2 ) { TranslatorOverrideProperty prop1 = (TranslatorOverrideProperty)e1; TranslatorOverrideProperty prop2 = (TranslatorOverrideProperty)e2; return super.compare(viewer, prop1.getDefinition().getDisplayName(), prop2.getDefinition().getDisplayName()); } }); Table table = this.propertiesViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); table.setLayout(new TableLayout()); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); ((GridData)table.getLayoutData()).horizontalSpan = 2; // create columns TableViewerColumn column = new TableViewerColumn(this.propertiesViewer, SWT.LEFT); column.getColumn().setText(Util.getString(PREFIX + "propertyColumn.text") + " "); //$NON-NLS-1$ //$NON-NLS-2$ column.setLabelProvider(new PropertyLabelProvider(true)); column.getColumn().pack(); column = new TableViewerColumn(this.propertiesViewer, SWT.LEFT); column.getColumn().setText(Util.getString(PREFIX + "valueColumn.text")); //$NON-NLS-1$ column.setLabelProvider(new PropertyLabelProvider(false)); column.setEditingSupport(new TranslatorOverridePropertyEditingSupport(this.propertiesViewer, this.vdb.getFile())); column.getColumn().pack(); this.propertiesViewer.addSelectionChangedListener(new ISelectionChangedListener() { /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ @Override public void selectionChanged( SelectionChangedEvent event ) { handlePropertySelected(event); } }); // // add toolbar below the table // Composite toolbarPanel = WidgetFactory.createPanel(pnlOverrides, SWT.NONE, GridData.VERTICAL_ALIGN_BEGINNING, 1, 3); this.addPropertyButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.addPropertyButton.setImage(VdbUiPlugin.singleton.getImage(ADD)); this.addPropertyButton.setToolTipText(Util.getString(PREFIX + "addPropertyAction.toolTip")); //$NON-NLS-1$ this.addPropertyButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleAddProperty(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.addPropertyButton.setEnabled(false); this.restorePropertyButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.restorePropertyButton.setEnabled(false); this.restorePropertyButton.setImage(VdbUiPlugin.singleton.getImage(EDIT)); this.restorePropertyButton.setToolTipText(Util.getString(PREFIX + "restorePropertyDefaultAction.toolTip")); //$NON-NLS-1$ this.restorePropertyButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handleRestorePropertyDefaultValue(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); this.deletePropertyButton = WidgetFactory.createButton(toolbarPanel, GridData.FILL); this.deletePropertyButton.setEnabled(false); this.deletePropertyButton.setImage(VdbUiPlugin.singleton.getImage(REMOVE)); this.deletePropertyButton.setToolTipText(Util.getString(PREFIX + "removePropertyAction.toolTip")); //$NON-NLS-1$ this.deletePropertyButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { handlePropertyRemoved(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }); } splitter.setWeights(new int[] { 25, 75 }); // populate with data from the VDB this.translatorsViewer.setInput(this); this.propertiesViewer.setInput(this); }
diff --git a/plugins/org.eclipse.uml2.diagram.clazz/src/org/eclipse/uml2/diagram/clazz/edit/parts/UMLEditPartFactory.java b/plugins/org.eclipse.uml2.diagram.clazz/src/org/eclipse/uml2/diagram/clazz/edit/parts/UMLEditPartFactory.java index b025e39a6..8dc255d11 100644 --- a/plugins/org.eclipse.uml2.diagram.clazz/src/org/eclipse/uml2/diagram/clazz/edit/parts/UMLEditPartFactory.java +++ b/plugins/org.eclipse.uml2.diagram.clazz/src/org/eclipse/uml2/diagram/clazz/edit/parts/UMLEditPartFactory.java @@ -1,536 +1,534 @@ package org.eclipse.uml2.diagram.clazz.edit.parts; import org.eclipse.draw2d.FigureUtilities; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPartFactory; import org.eclipse.gef.tools.CellEditorLocator; import org.eclipse.gmf.runtime.diagram.ui.editparts.ITextAwareEditPart; import org.eclipse.gmf.runtime.draw2d.ui.figures.WrapLabel; import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Text; import org.eclipse.uml2.diagram.clazz.part.UMLVisualIDRegistry; /** * @generated */ public class UMLEditPartFactory implements EditPartFactory { /** * @generated */ public EditPart createEditPart(EditPart context, Object model) { if (model instanceof View) { View view = (View) model; switch (UMLVisualIDRegistry.getVisualID(view)) { case PackageEditPart.VISUAL_ID: return new PackageEditPart(view); case Package2EditPart.VISUAL_ID: return new Package2EditPart(view); case PackageNameEditPart.VISUAL_ID: return new PackageNameEditPart(view); case Class2EditPart.VISUAL_ID: return new Class2EditPart(view); case ClassNameEditPart.VISUAL_ID: return new ClassNameEditPart(view); case ClassStereotypeEditPart.VISUAL_ID: return new ClassStereotypeEditPart(view); case AssociationClass2EditPart.VISUAL_ID: return new AssociationClass2EditPart(view); case AssociationClassNameEditPart.VISUAL_ID: return new AssociationClassNameEditPart(view); case DataType2EditPart.VISUAL_ID: return new DataType2EditPart(view); case DataTypeNameEditPart.VISUAL_ID: return new DataTypeNameEditPart(view); case PrimitiveType2EditPart.VISUAL_ID: return new PrimitiveType2EditPart(view); case PrimitiveTypeNameEditPart.VISUAL_ID: return new PrimitiveTypeNameEditPart(view); case Enumeration2EditPart.VISUAL_ID: return new Enumeration2EditPart(view); case EnumerationNameEditPart.VISUAL_ID: return new EnumerationNameEditPart(view); case InterfaceEditPart.VISUAL_ID: return new InterfaceEditPart(view); case InterfaceNameEditPart.VISUAL_ID: return new InterfaceNameEditPart(view); case ConstraintEditPart.VISUAL_ID: return new ConstraintEditPart(view); case ConstraintNameEditPart.VISUAL_ID: return new ConstraintNameEditPart(view); case InstanceSpecification2EditPart.VISUAL_ID: return new InstanceSpecification2EditPart(view); case InstanceSpecificationNameEditPart.VISUAL_ID: return new InstanceSpecificationNameEditPart(view); case DependencyEditPart.VISUAL_ID: return new DependencyEditPart(view); case DependencyNameEditPart.VISUAL_ID: return new DependencyNameEditPart(view); case GeneralizationSetEditPart.VISUAL_ID: return new GeneralizationSetEditPart(view); case GeneralizationSetIsCoveringIsDisjointEditPart.VISUAL_ID: return new GeneralizationSetIsCoveringIsDisjointEditPart(view); case GeneralizationSetNameEditPart.VISUAL_ID: return new GeneralizationSetNameEditPart(view); case Interface2EditPart.VISUAL_ID: return new Interface2EditPart(view); case InterfaceName2EditPart.VISUAL_ID: return new InterfaceName2EditPart(view); case Package4EditPart.VISUAL_ID: return new Package4EditPart(view); case PackageName2EditPart.VISUAL_ID: return new PackageName2EditPart(view); case AssociationClassRhombEditPart.VISUAL_ID: return new AssociationClassRhombEditPart(view); case PackageAsFrameEditPart.VISUAL_ID: return new PackageAsFrameEditPart(view); case PackageName3EditPart.VISUAL_ID: return new PackageName3EditPart(view); case Package3EditPart.VISUAL_ID: return new Package3EditPart(view); case ClassEditPart.VISUAL_ID: return new ClassEditPart(view); case DataTypeEditPart.VISUAL_ID: return new DataTypeEditPart(view); case PrimitiveTypeEditPart.VISUAL_ID: return new PrimitiveTypeEditPart(view); case EnumerationEditPart.VISUAL_ID: return new EnumerationEditPart(view); case AssociationClassEditPart.VISUAL_ID: return new AssociationClassEditPart(view); case InstanceSpecificationEditPart.VISUAL_ID: return new InstanceSpecificationEditPart(view); case PropertyEditPart.VISUAL_ID: return new PropertyEditPart(view); case OperationEditPart.VISUAL_ID: return new OperationEditPart(view); case Class3EditPart.VISUAL_ID: return new Class3EditPart(view); case PortEditPart.VISUAL_ID: return new PortEditPart(view); case PortNameEditPart.VISUAL_ID: return new PortNameEditPart(view); case RedefinableTemplateSignatureEditPart.VISUAL_ID: return new RedefinableTemplateSignatureEditPart(view); case TemplateSignatureNode_signatureEditPart.VISUAL_ID: return new TemplateSignatureNode_signatureEditPart(view); case Property2EditPart.VISUAL_ID: return new Property2EditPart(view); case Operation2EditPart.VISUAL_ID: return new Operation2EditPart(view); case Property3EditPart.VISUAL_ID: return new Property3EditPart(view); case Operation3EditPart.VISUAL_ID: return new Operation3EditPart(view); case Property4EditPart.VISUAL_ID: return new Property4EditPart(view); case Operation4EditPart.VISUAL_ID: return new Operation4EditPart(view); case EnumerationLiteralEditPart.VISUAL_ID: return new EnumerationLiteralEditPart(view); case Property5EditPart.VISUAL_ID: return new Property5EditPart(view); case Operation5EditPart.VISUAL_ID: return new Operation5EditPart(view); case SlotEditPart.VISUAL_ID: return new SlotEditPart(view); case Property6EditPart.VISUAL_ID: return new Property6EditPart(view); case Operation6EditPart.VISUAL_ID: return new Operation6EditPart(view); case Class4EditPart.VISUAL_ID: return new Class4EditPart(view); case ElementImportEditPart.VISUAL_ID: return new ElementImportEditPart(view); case Package6EditPart.VISUAL_ID: return new Package6EditPart(view); case PackageName4EditPart.VISUAL_ID: return new PackageName4EditPart(view); case Class5EditPart.VISUAL_ID: return new Class5EditPart(view); case ClassName2EditPart.VISUAL_ID: return new ClassName2EditPart(view); case ClassQualifiedNameEditPart.VISUAL_ID: return new ClassQualifiedNameEditPart(view); case Enumeration3EditPart.VISUAL_ID: return new Enumeration3EditPart(view); case EnumerationName2EditPart.VISUAL_ID: return new EnumerationName2EditPart(view); case InstanceSpecification3EditPart.VISUAL_ID: return new InstanceSpecification3EditPart(view); case InstanceSpecificationName2EditPart.VISUAL_ID: return new InstanceSpecificationName2EditPart(view); case DataType3EditPart.VISUAL_ID: return new DataType3EditPart(view); case DataTypeName2EditPart.VISUAL_ID: return new DataTypeName2EditPart(view); case PrimitiveType3EditPart.VISUAL_ID: return new PrimitiveType3EditPart(view); case PrimitiveTypeName2EditPart.VISUAL_ID: return new PrimitiveTypeName2EditPart(view); case PackagePackagesEditPart.VISUAL_ID: return new PackagePackagesEditPart(view); case PackageClassifiersEditPart.VISUAL_ID: return new PackageClassifiersEditPart(view); case PackageOtherEditPart.VISUAL_ID: return new PackageOtherEditPart(view); case ClassAttributesEditPart.VISUAL_ID: return new ClassAttributesEditPart(view); case ClassOperationsEditPart.VISUAL_ID: return new ClassOperationsEditPart(view); case ClassClassesEditPart.VISUAL_ID: return new ClassClassesEditPart(view); case AssociationClassAttributesEditPart.VISUAL_ID: return new AssociationClassAttributesEditPart(view); case AssociationClassOperationsEditPart.VISUAL_ID: return new AssociationClassOperationsEditPart(view); case AssociationClassClassesEditPart.VISUAL_ID: return new AssociationClassClassesEditPart(view); case DataTypeAttributesEditPart.VISUAL_ID: return new DataTypeAttributesEditPart(view); case DataTypeOperationsEditPart.VISUAL_ID: return new DataTypeOperationsEditPart(view); case PrimitiveTypeAttributesEditPart.VISUAL_ID: return new PrimitiveTypeAttributesEditPart(view); case PrimitiveTypeOperationsEditPart.VISUAL_ID: return new PrimitiveTypeOperationsEditPart(view); case EnumerationLiteralsEditPart.VISUAL_ID: return new EnumerationLiteralsEditPart(view); case EnumerationAttributesEditPart.VISUAL_ID: return new EnumerationAttributesEditPart(view); case EnumerationOperationsEditPart.VISUAL_ID: return new EnumerationOperationsEditPart(view); case InstanceSpecificationSlotsEditPart.VISUAL_ID: return new InstanceSpecificationSlotsEditPart(view); case InterfaceAttributesEditPart.VISUAL_ID: return new InterfaceAttributesEditPart(view); case InterfaceOperationsEditPart.VISUAL_ID: return new InterfaceOperationsEditPart(view); case InterfaceClassesEditPart.VISUAL_ID: return new InterfaceClassesEditPart(view); case PackageImportsEditPart.VISUAL_ID: return new PackageImportsEditPart(view); case PackageAsFrameContentsEditPart.VISUAL_ID: return new PackageAsFrameContentsEditPart(view); case PackageAsFrameContents2EditPart.VISUAL_ID: return new PackageAsFrameContents2EditPart(view); case ClassAttributes2EditPart.VISUAL_ID: return new ClassAttributes2EditPart(view); case ClassOperations2EditPart.VISUAL_ID: return new ClassOperations2EditPart(view); case ClassClasses2EditPart.VISUAL_ID: return new ClassClasses2EditPart(view); case EnumerationLiterals2EditPart.VISUAL_ID: return new EnumerationLiterals2EditPart(view); case EnumerationAttributes2EditPart.VISUAL_ID: return new EnumerationAttributes2EditPart(view); case EnumerationOperations2EditPart.VISUAL_ID: return new EnumerationOperations2EditPart(view); case InstanceSpecificationSlots2EditPart.VISUAL_ID: return new InstanceSpecificationSlots2EditPart(view); case DataTypeAttributes2EditPart.VISUAL_ID: return new DataTypeAttributes2EditPart(view); case DataTypeOperations2EditPart.VISUAL_ID: return new DataTypeOperations2EditPart(view); case PrimitiveTypeAttributes2EditPart.VISUAL_ID: return new PrimitiveTypeAttributes2EditPart(view); case PrimitiveTypeOperations2EditPart.VISUAL_ID: return new PrimitiveTypeOperations2EditPart(view); case GeneralizationEditPart.VISUAL_ID: return new GeneralizationEditPart(view); case Dependency2EditPart.VISUAL_ID: return new Dependency2EditPart(view); case DependencyName2EditPart.VISUAL_ID: return new DependencyName2EditPart(view); case DependencyName3EditPart.VISUAL_ID: return new DependencyName3EditPart(view); case Property7EditPart.VISUAL_ID: return new Property7EditPart(view); case PropertyNameEditPart.VISUAL_ID: return new PropertyNameEditPart(view); case PropertyName2EditPart.VISUAL_ID: return new PropertyName2EditPart(view); case ConstraintConstrainedElementEditPart.VISUAL_ID: return new ConstraintConstrainedElementEditPart(view); case AssociationEditPart.VISUAL_ID: return new AssociationEditPart(view); case AssociationNameEditPart.VISUAL_ID: return new AssociationNameEditPart(view); case AssociationName2EditPart.VISUAL_ID: return new AssociationName2EditPart(view); case AssociationName3EditPart.VISUAL_ID: return new AssociationName3EditPart(view); case AssociationName4EditPart.VISUAL_ID: return new AssociationName4EditPart(view); case AssociationName5EditPart.VISUAL_ID: return new AssociationName5EditPart(view); case AssociationName6EditPart.VISUAL_ID: return new AssociationName6EditPart(view); case AssociationName7EditPart.VISUAL_ID: return new AssociationName7EditPart(view); case DependencySupplierEditPart.VISUAL_ID: return new DependencySupplierEditPart(view); case DependencyClientEditPart.VISUAL_ID: return new DependencyClientEditPart(view); case InterfaceRealizationEditPart.VISUAL_ID: return new InterfaceRealizationEditPart(view); case RealizationEditPart.VISUAL_ID: return new RealizationEditPart(view); case RealizationNameEditPart.VISUAL_ID: return new RealizationNameEditPart(view); case Generalization2EditPart.VISUAL_ID: return new Generalization2EditPart(view); case GeneralizationGeneralEditPart.VISUAL_ID: return new GeneralizationGeneralEditPart(view); case UsageEditPart.VISUAL_ID: return new UsageEditPart(view); case AssociationClassConnectorEditPart.VISUAL_ID: return new AssociationClassConnectorEditPart(view); - case AssociationInstanceEditPart.VISUAL_ID: - return new AssociationInstanceEditPart(view); } } return createUnrecognizedEditPart(context, model); } /** * @generated */ private EditPart createUnrecognizedEditPart(EditPart context, Object model) { // Handle creation of unrecognized child node EditParts here return null; } /** * @generated */ public static CellEditorLocator getTextCellEditorLocator(ITextAwareEditPart source) { if (source.getFigure() instanceof WrappingLabel) return new TextCellEditorLocator((WrappingLabel) source.getFigure()); else { return new LabelCellEditorLocator((Label) source.getFigure()); } } /** * @generated */ static private class TextCellEditorLocator implements CellEditorLocator { /** * @generated */ private WrappingLabel wrapLabel; /** * @generated */ public TextCellEditorLocator(WrappingLabel wrapLabel) { this.wrapLabel = wrapLabel; } /** * @generated */ public WrappingLabel getWrapLabel() { return wrapLabel; } /** * @generated */ public void relocate(CellEditor celleditor) { Text text = (Text) celleditor.getControl(); Rectangle rect = getWrapLabel().getTextBounds().getCopy(); getWrapLabel().translateToAbsolute(rect); if (getWrapLabel().isTextWrapOn() && getWrapLabel().getText().length() > 0) { rect.setSize(new Dimension(text.computeSize(rect.width, SWT.DEFAULT))); } else { int avr = FigureUtilities.getFontMetrics(text.getFont()).getAverageCharWidth(); rect.setSize(new Dimension(text.computeSize(SWT.DEFAULT, SWT.DEFAULT)).expand(avr * 2, 0)); } if (!rect.equals(new Rectangle(text.getBounds()))) { text.setBounds(rect.x, rect.y, rect.width, rect.height); } } } /** * @generated */ private static class LabelCellEditorLocator implements CellEditorLocator { /** * @generated */ private Label label; /** * @generated */ public LabelCellEditorLocator(Label label) { this.label = label; } /** * @generated */ public Label getLabel() { return label; } /** * @generated */ public void relocate(CellEditor celleditor) { Text text = (Text) celleditor.getControl(); Rectangle rect = getLabel().getTextBounds().getCopy(); getLabel().translateToAbsolute(rect); int avr = FigureUtilities.getFontMetrics(text.getFont()).getAverageCharWidth(); rect.setSize(new Dimension(text.computeSize(SWT.DEFAULT, SWT.DEFAULT)).expand(avr * 2, 0)); if (!rect.equals(new Rectangle(text.getBounds()))) { text.setBounds(rect.x, rect.y, rect.width, rect.height); } } } }
true
true
public EditPart createEditPart(EditPart context, Object model) { if (model instanceof View) { View view = (View) model; switch (UMLVisualIDRegistry.getVisualID(view)) { case PackageEditPart.VISUAL_ID: return new PackageEditPart(view); case Package2EditPart.VISUAL_ID: return new Package2EditPart(view); case PackageNameEditPart.VISUAL_ID: return new PackageNameEditPart(view); case Class2EditPart.VISUAL_ID: return new Class2EditPart(view); case ClassNameEditPart.VISUAL_ID: return new ClassNameEditPart(view); case ClassStereotypeEditPart.VISUAL_ID: return new ClassStereotypeEditPart(view); case AssociationClass2EditPart.VISUAL_ID: return new AssociationClass2EditPart(view); case AssociationClassNameEditPart.VISUAL_ID: return new AssociationClassNameEditPart(view); case DataType2EditPart.VISUAL_ID: return new DataType2EditPart(view); case DataTypeNameEditPart.VISUAL_ID: return new DataTypeNameEditPart(view); case PrimitiveType2EditPart.VISUAL_ID: return new PrimitiveType2EditPart(view); case PrimitiveTypeNameEditPart.VISUAL_ID: return new PrimitiveTypeNameEditPart(view); case Enumeration2EditPart.VISUAL_ID: return new Enumeration2EditPart(view); case EnumerationNameEditPart.VISUAL_ID: return new EnumerationNameEditPart(view); case InterfaceEditPart.VISUAL_ID: return new InterfaceEditPart(view); case InterfaceNameEditPart.VISUAL_ID: return new InterfaceNameEditPart(view); case ConstraintEditPart.VISUAL_ID: return new ConstraintEditPart(view); case ConstraintNameEditPart.VISUAL_ID: return new ConstraintNameEditPart(view); case InstanceSpecification2EditPart.VISUAL_ID: return new InstanceSpecification2EditPart(view); case InstanceSpecificationNameEditPart.VISUAL_ID: return new InstanceSpecificationNameEditPart(view); case DependencyEditPart.VISUAL_ID: return new DependencyEditPart(view); case DependencyNameEditPart.VISUAL_ID: return new DependencyNameEditPart(view); case GeneralizationSetEditPart.VISUAL_ID: return new GeneralizationSetEditPart(view); case GeneralizationSetIsCoveringIsDisjointEditPart.VISUAL_ID: return new GeneralizationSetIsCoveringIsDisjointEditPart(view); case GeneralizationSetNameEditPart.VISUAL_ID: return new GeneralizationSetNameEditPart(view); case Interface2EditPart.VISUAL_ID: return new Interface2EditPart(view); case InterfaceName2EditPart.VISUAL_ID: return new InterfaceName2EditPart(view); case Package4EditPart.VISUAL_ID: return new Package4EditPart(view); case PackageName2EditPart.VISUAL_ID: return new PackageName2EditPart(view); case AssociationClassRhombEditPart.VISUAL_ID: return new AssociationClassRhombEditPart(view); case PackageAsFrameEditPart.VISUAL_ID: return new PackageAsFrameEditPart(view); case PackageName3EditPart.VISUAL_ID: return new PackageName3EditPart(view); case Package3EditPart.VISUAL_ID: return new Package3EditPart(view); case ClassEditPart.VISUAL_ID: return new ClassEditPart(view); case DataTypeEditPart.VISUAL_ID: return new DataTypeEditPart(view); case PrimitiveTypeEditPart.VISUAL_ID: return new PrimitiveTypeEditPart(view); case EnumerationEditPart.VISUAL_ID: return new EnumerationEditPart(view); case AssociationClassEditPart.VISUAL_ID: return new AssociationClassEditPart(view); case InstanceSpecificationEditPart.VISUAL_ID: return new InstanceSpecificationEditPart(view); case PropertyEditPart.VISUAL_ID: return new PropertyEditPart(view); case OperationEditPart.VISUAL_ID: return new OperationEditPart(view); case Class3EditPart.VISUAL_ID: return new Class3EditPart(view); case PortEditPart.VISUAL_ID: return new PortEditPart(view); case PortNameEditPart.VISUAL_ID: return new PortNameEditPart(view); case RedefinableTemplateSignatureEditPart.VISUAL_ID: return new RedefinableTemplateSignatureEditPart(view); case TemplateSignatureNode_signatureEditPart.VISUAL_ID: return new TemplateSignatureNode_signatureEditPart(view); case Property2EditPart.VISUAL_ID: return new Property2EditPart(view); case Operation2EditPart.VISUAL_ID: return new Operation2EditPart(view); case Property3EditPart.VISUAL_ID: return new Property3EditPart(view); case Operation3EditPart.VISUAL_ID: return new Operation3EditPart(view); case Property4EditPart.VISUAL_ID: return new Property4EditPart(view); case Operation4EditPart.VISUAL_ID: return new Operation4EditPart(view); case EnumerationLiteralEditPart.VISUAL_ID: return new EnumerationLiteralEditPart(view); case Property5EditPart.VISUAL_ID: return new Property5EditPart(view); case Operation5EditPart.VISUAL_ID: return new Operation5EditPart(view); case SlotEditPart.VISUAL_ID: return new SlotEditPart(view); case Property6EditPart.VISUAL_ID: return new Property6EditPart(view); case Operation6EditPart.VISUAL_ID: return new Operation6EditPart(view); case Class4EditPart.VISUAL_ID: return new Class4EditPart(view); case ElementImportEditPart.VISUAL_ID: return new ElementImportEditPart(view); case Package6EditPart.VISUAL_ID: return new Package6EditPart(view); case PackageName4EditPart.VISUAL_ID: return new PackageName4EditPart(view); case Class5EditPart.VISUAL_ID: return new Class5EditPart(view); case ClassName2EditPart.VISUAL_ID: return new ClassName2EditPart(view); case ClassQualifiedNameEditPart.VISUAL_ID: return new ClassQualifiedNameEditPart(view); case Enumeration3EditPart.VISUAL_ID: return new Enumeration3EditPart(view); case EnumerationName2EditPart.VISUAL_ID: return new EnumerationName2EditPart(view); case InstanceSpecification3EditPart.VISUAL_ID: return new InstanceSpecification3EditPart(view); case InstanceSpecificationName2EditPart.VISUAL_ID: return new InstanceSpecificationName2EditPart(view); case DataType3EditPart.VISUAL_ID: return new DataType3EditPart(view); case DataTypeName2EditPart.VISUAL_ID: return new DataTypeName2EditPart(view); case PrimitiveType3EditPart.VISUAL_ID: return new PrimitiveType3EditPart(view); case PrimitiveTypeName2EditPart.VISUAL_ID: return new PrimitiveTypeName2EditPart(view); case PackagePackagesEditPart.VISUAL_ID: return new PackagePackagesEditPart(view); case PackageClassifiersEditPart.VISUAL_ID: return new PackageClassifiersEditPart(view); case PackageOtherEditPart.VISUAL_ID: return new PackageOtherEditPart(view); case ClassAttributesEditPart.VISUAL_ID: return new ClassAttributesEditPart(view); case ClassOperationsEditPart.VISUAL_ID: return new ClassOperationsEditPart(view); case ClassClassesEditPart.VISUAL_ID: return new ClassClassesEditPart(view); case AssociationClassAttributesEditPart.VISUAL_ID: return new AssociationClassAttributesEditPart(view); case AssociationClassOperationsEditPart.VISUAL_ID: return new AssociationClassOperationsEditPart(view); case AssociationClassClassesEditPart.VISUAL_ID: return new AssociationClassClassesEditPart(view); case DataTypeAttributesEditPart.VISUAL_ID: return new DataTypeAttributesEditPart(view); case DataTypeOperationsEditPart.VISUAL_ID: return new DataTypeOperationsEditPart(view); case PrimitiveTypeAttributesEditPart.VISUAL_ID: return new PrimitiveTypeAttributesEditPart(view); case PrimitiveTypeOperationsEditPart.VISUAL_ID: return new PrimitiveTypeOperationsEditPart(view); case EnumerationLiteralsEditPart.VISUAL_ID: return new EnumerationLiteralsEditPart(view); case EnumerationAttributesEditPart.VISUAL_ID: return new EnumerationAttributesEditPart(view); case EnumerationOperationsEditPart.VISUAL_ID: return new EnumerationOperationsEditPart(view); case InstanceSpecificationSlotsEditPart.VISUAL_ID: return new InstanceSpecificationSlotsEditPart(view); case InterfaceAttributesEditPart.VISUAL_ID: return new InterfaceAttributesEditPart(view); case InterfaceOperationsEditPart.VISUAL_ID: return new InterfaceOperationsEditPart(view); case InterfaceClassesEditPart.VISUAL_ID: return new InterfaceClassesEditPart(view); case PackageImportsEditPart.VISUAL_ID: return new PackageImportsEditPart(view); case PackageAsFrameContentsEditPart.VISUAL_ID: return new PackageAsFrameContentsEditPart(view); case PackageAsFrameContents2EditPart.VISUAL_ID: return new PackageAsFrameContents2EditPart(view); case ClassAttributes2EditPart.VISUAL_ID: return new ClassAttributes2EditPart(view); case ClassOperations2EditPart.VISUAL_ID: return new ClassOperations2EditPart(view); case ClassClasses2EditPart.VISUAL_ID: return new ClassClasses2EditPart(view); case EnumerationLiterals2EditPart.VISUAL_ID: return new EnumerationLiterals2EditPart(view); case EnumerationAttributes2EditPart.VISUAL_ID: return new EnumerationAttributes2EditPart(view); case EnumerationOperations2EditPart.VISUAL_ID: return new EnumerationOperations2EditPart(view); case InstanceSpecificationSlots2EditPart.VISUAL_ID: return new InstanceSpecificationSlots2EditPart(view); case DataTypeAttributes2EditPart.VISUAL_ID: return new DataTypeAttributes2EditPart(view); case DataTypeOperations2EditPart.VISUAL_ID: return new DataTypeOperations2EditPart(view); case PrimitiveTypeAttributes2EditPart.VISUAL_ID: return new PrimitiveTypeAttributes2EditPart(view); case PrimitiveTypeOperations2EditPart.VISUAL_ID: return new PrimitiveTypeOperations2EditPart(view); case GeneralizationEditPart.VISUAL_ID: return new GeneralizationEditPart(view); case Dependency2EditPart.VISUAL_ID: return new Dependency2EditPart(view); case DependencyName2EditPart.VISUAL_ID: return new DependencyName2EditPart(view); case DependencyName3EditPart.VISUAL_ID: return new DependencyName3EditPart(view); case Property7EditPart.VISUAL_ID: return new Property7EditPart(view); case PropertyNameEditPart.VISUAL_ID: return new PropertyNameEditPart(view); case PropertyName2EditPart.VISUAL_ID: return new PropertyName2EditPart(view); case ConstraintConstrainedElementEditPart.VISUAL_ID: return new ConstraintConstrainedElementEditPart(view); case AssociationEditPart.VISUAL_ID: return new AssociationEditPart(view); case AssociationNameEditPart.VISUAL_ID: return new AssociationNameEditPart(view); case AssociationName2EditPart.VISUAL_ID: return new AssociationName2EditPart(view); case AssociationName3EditPart.VISUAL_ID: return new AssociationName3EditPart(view); case AssociationName4EditPart.VISUAL_ID: return new AssociationName4EditPart(view); case AssociationName5EditPart.VISUAL_ID: return new AssociationName5EditPart(view); case AssociationName6EditPart.VISUAL_ID: return new AssociationName6EditPart(view); case AssociationName7EditPart.VISUAL_ID: return new AssociationName7EditPart(view); case DependencySupplierEditPart.VISUAL_ID: return new DependencySupplierEditPart(view); case DependencyClientEditPart.VISUAL_ID: return new DependencyClientEditPart(view); case InterfaceRealizationEditPart.VISUAL_ID: return new InterfaceRealizationEditPart(view); case RealizationEditPart.VISUAL_ID: return new RealizationEditPart(view); case RealizationNameEditPart.VISUAL_ID: return new RealizationNameEditPart(view); case Generalization2EditPart.VISUAL_ID: return new Generalization2EditPart(view); case GeneralizationGeneralEditPart.VISUAL_ID: return new GeneralizationGeneralEditPart(view); case UsageEditPart.VISUAL_ID: return new UsageEditPart(view); case AssociationClassConnectorEditPart.VISUAL_ID: return new AssociationClassConnectorEditPart(view); case AssociationInstanceEditPart.VISUAL_ID: return new AssociationInstanceEditPart(view); } } return createUnrecognizedEditPart(context, model); }
public EditPart createEditPart(EditPart context, Object model) { if (model instanceof View) { View view = (View) model; switch (UMLVisualIDRegistry.getVisualID(view)) { case PackageEditPart.VISUAL_ID: return new PackageEditPart(view); case Package2EditPart.VISUAL_ID: return new Package2EditPart(view); case PackageNameEditPart.VISUAL_ID: return new PackageNameEditPart(view); case Class2EditPart.VISUAL_ID: return new Class2EditPart(view); case ClassNameEditPart.VISUAL_ID: return new ClassNameEditPart(view); case ClassStereotypeEditPart.VISUAL_ID: return new ClassStereotypeEditPart(view); case AssociationClass2EditPart.VISUAL_ID: return new AssociationClass2EditPart(view); case AssociationClassNameEditPart.VISUAL_ID: return new AssociationClassNameEditPart(view); case DataType2EditPart.VISUAL_ID: return new DataType2EditPart(view); case DataTypeNameEditPart.VISUAL_ID: return new DataTypeNameEditPart(view); case PrimitiveType2EditPart.VISUAL_ID: return new PrimitiveType2EditPart(view); case PrimitiveTypeNameEditPart.VISUAL_ID: return new PrimitiveTypeNameEditPart(view); case Enumeration2EditPart.VISUAL_ID: return new Enumeration2EditPart(view); case EnumerationNameEditPart.VISUAL_ID: return new EnumerationNameEditPart(view); case InterfaceEditPart.VISUAL_ID: return new InterfaceEditPart(view); case InterfaceNameEditPart.VISUAL_ID: return new InterfaceNameEditPart(view); case ConstraintEditPart.VISUAL_ID: return new ConstraintEditPart(view); case ConstraintNameEditPart.VISUAL_ID: return new ConstraintNameEditPart(view); case InstanceSpecification2EditPart.VISUAL_ID: return new InstanceSpecification2EditPart(view); case InstanceSpecificationNameEditPart.VISUAL_ID: return new InstanceSpecificationNameEditPart(view); case DependencyEditPart.VISUAL_ID: return new DependencyEditPart(view); case DependencyNameEditPart.VISUAL_ID: return new DependencyNameEditPart(view); case GeneralizationSetEditPart.VISUAL_ID: return new GeneralizationSetEditPart(view); case GeneralizationSetIsCoveringIsDisjointEditPart.VISUAL_ID: return new GeneralizationSetIsCoveringIsDisjointEditPart(view); case GeneralizationSetNameEditPart.VISUAL_ID: return new GeneralizationSetNameEditPart(view); case Interface2EditPart.VISUAL_ID: return new Interface2EditPart(view); case InterfaceName2EditPart.VISUAL_ID: return new InterfaceName2EditPart(view); case Package4EditPart.VISUAL_ID: return new Package4EditPart(view); case PackageName2EditPart.VISUAL_ID: return new PackageName2EditPart(view); case AssociationClassRhombEditPart.VISUAL_ID: return new AssociationClassRhombEditPart(view); case PackageAsFrameEditPart.VISUAL_ID: return new PackageAsFrameEditPart(view); case PackageName3EditPart.VISUAL_ID: return new PackageName3EditPart(view); case Package3EditPart.VISUAL_ID: return new Package3EditPart(view); case ClassEditPart.VISUAL_ID: return new ClassEditPart(view); case DataTypeEditPart.VISUAL_ID: return new DataTypeEditPart(view); case PrimitiveTypeEditPart.VISUAL_ID: return new PrimitiveTypeEditPart(view); case EnumerationEditPart.VISUAL_ID: return new EnumerationEditPart(view); case AssociationClassEditPart.VISUAL_ID: return new AssociationClassEditPart(view); case InstanceSpecificationEditPart.VISUAL_ID: return new InstanceSpecificationEditPart(view); case PropertyEditPart.VISUAL_ID: return new PropertyEditPart(view); case OperationEditPart.VISUAL_ID: return new OperationEditPart(view); case Class3EditPart.VISUAL_ID: return new Class3EditPart(view); case PortEditPart.VISUAL_ID: return new PortEditPart(view); case PortNameEditPart.VISUAL_ID: return new PortNameEditPart(view); case RedefinableTemplateSignatureEditPart.VISUAL_ID: return new RedefinableTemplateSignatureEditPart(view); case TemplateSignatureNode_signatureEditPart.VISUAL_ID: return new TemplateSignatureNode_signatureEditPart(view); case Property2EditPart.VISUAL_ID: return new Property2EditPart(view); case Operation2EditPart.VISUAL_ID: return new Operation2EditPart(view); case Property3EditPart.VISUAL_ID: return new Property3EditPart(view); case Operation3EditPart.VISUAL_ID: return new Operation3EditPart(view); case Property4EditPart.VISUAL_ID: return new Property4EditPart(view); case Operation4EditPart.VISUAL_ID: return new Operation4EditPart(view); case EnumerationLiteralEditPart.VISUAL_ID: return new EnumerationLiteralEditPart(view); case Property5EditPart.VISUAL_ID: return new Property5EditPart(view); case Operation5EditPart.VISUAL_ID: return new Operation5EditPart(view); case SlotEditPart.VISUAL_ID: return new SlotEditPart(view); case Property6EditPart.VISUAL_ID: return new Property6EditPart(view); case Operation6EditPart.VISUAL_ID: return new Operation6EditPart(view); case Class4EditPart.VISUAL_ID: return new Class4EditPart(view); case ElementImportEditPart.VISUAL_ID: return new ElementImportEditPart(view); case Package6EditPart.VISUAL_ID: return new Package6EditPart(view); case PackageName4EditPart.VISUAL_ID: return new PackageName4EditPart(view); case Class5EditPart.VISUAL_ID: return new Class5EditPart(view); case ClassName2EditPart.VISUAL_ID: return new ClassName2EditPart(view); case ClassQualifiedNameEditPart.VISUAL_ID: return new ClassQualifiedNameEditPart(view); case Enumeration3EditPart.VISUAL_ID: return new Enumeration3EditPart(view); case EnumerationName2EditPart.VISUAL_ID: return new EnumerationName2EditPart(view); case InstanceSpecification3EditPart.VISUAL_ID: return new InstanceSpecification3EditPart(view); case InstanceSpecificationName2EditPart.VISUAL_ID: return new InstanceSpecificationName2EditPart(view); case DataType3EditPart.VISUAL_ID: return new DataType3EditPart(view); case DataTypeName2EditPart.VISUAL_ID: return new DataTypeName2EditPart(view); case PrimitiveType3EditPart.VISUAL_ID: return new PrimitiveType3EditPart(view); case PrimitiveTypeName2EditPart.VISUAL_ID: return new PrimitiveTypeName2EditPart(view); case PackagePackagesEditPart.VISUAL_ID: return new PackagePackagesEditPart(view); case PackageClassifiersEditPart.VISUAL_ID: return new PackageClassifiersEditPart(view); case PackageOtherEditPart.VISUAL_ID: return new PackageOtherEditPart(view); case ClassAttributesEditPart.VISUAL_ID: return new ClassAttributesEditPart(view); case ClassOperationsEditPart.VISUAL_ID: return new ClassOperationsEditPart(view); case ClassClassesEditPart.VISUAL_ID: return new ClassClassesEditPart(view); case AssociationClassAttributesEditPart.VISUAL_ID: return new AssociationClassAttributesEditPart(view); case AssociationClassOperationsEditPart.VISUAL_ID: return new AssociationClassOperationsEditPart(view); case AssociationClassClassesEditPart.VISUAL_ID: return new AssociationClassClassesEditPart(view); case DataTypeAttributesEditPart.VISUAL_ID: return new DataTypeAttributesEditPart(view); case DataTypeOperationsEditPart.VISUAL_ID: return new DataTypeOperationsEditPart(view); case PrimitiveTypeAttributesEditPart.VISUAL_ID: return new PrimitiveTypeAttributesEditPart(view); case PrimitiveTypeOperationsEditPart.VISUAL_ID: return new PrimitiveTypeOperationsEditPart(view); case EnumerationLiteralsEditPart.VISUAL_ID: return new EnumerationLiteralsEditPart(view); case EnumerationAttributesEditPart.VISUAL_ID: return new EnumerationAttributesEditPart(view); case EnumerationOperationsEditPart.VISUAL_ID: return new EnumerationOperationsEditPart(view); case InstanceSpecificationSlotsEditPart.VISUAL_ID: return new InstanceSpecificationSlotsEditPart(view); case InterfaceAttributesEditPart.VISUAL_ID: return new InterfaceAttributesEditPart(view); case InterfaceOperationsEditPart.VISUAL_ID: return new InterfaceOperationsEditPart(view); case InterfaceClassesEditPart.VISUAL_ID: return new InterfaceClassesEditPart(view); case PackageImportsEditPart.VISUAL_ID: return new PackageImportsEditPart(view); case PackageAsFrameContentsEditPart.VISUAL_ID: return new PackageAsFrameContentsEditPart(view); case PackageAsFrameContents2EditPart.VISUAL_ID: return new PackageAsFrameContents2EditPart(view); case ClassAttributes2EditPart.VISUAL_ID: return new ClassAttributes2EditPart(view); case ClassOperations2EditPart.VISUAL_ID: return new ClassOperations2EditPart(view); case ClassClasses2EditPart.VISUAL_ID: return new ClassClasses2EditPart(view); case EnumerationLiterals2EditPart.VISUAL_ID: return new EnumerationLiterals2EditPart(view); case EnumerationAttributes2EditPart.VISUAL_ID: return new EnumerationAttributes2EditPart(view); case EnumerationOperations2EditPart.VISUAL_ID: return new EnumerationOperations2EditPart(view); case InstanceSpecificationSlots2EditPart.VISUAL_ID: return new InstanceSpecificationSlots2EditPart(view); case DataTypeAttributes2EditPart.VISUAL_ID: return new DataTypeAttributes2EditPart(view); case DataTypeOperations2EditPart.VISUAL_ID: return new DataTypeOperations2EditPart(view); case PrimitiveTypeAttributes2EditPart.VISUAL_ID: return new PrimitiveTypeAttributes2EditPart(view); case PrimitiveTypeOperations2EditPart.VISUAL_ID: return new PrimitiveTypeOperations2EditPart(view); case GeneralizationEditPart.VISUAL_ID: return new GeneralizationEditPart(view); case Dependency2EditPart.VISUAL_ID: return new Dependency2EditPart(view); case DependencyName2EditPart.VISUAL_ID: return new DependencyName2EditPart(view); case DependencyName3EditPart.VISUAL_ID: return new DependencyName3EditPart(view); case Property7EditPart.VISUAL_ID: return new Property7EditPart(view); case PropertyNameEditPart.VISUAL_ID: return new PropertyNameEditPart(view); case PropertyName2EditPart.VISUAL_ID: return new PropertyName2EditPart(view); case ConstraintConstrainedElementEditPart.VISUAL_ID: return new ConstraintConstrainedElementEditPart(view); case AssociationEditPart.VISUAL_ID: return new AssociationEditPart(view); case AssociationNameEditPart.VISUAL_ID: return new AssociationNameEditPart(view); case AssociationName2EditPart.VISUAL_ID: return new AssociationName2EditPart(view); case AssociationName3EditPart.VISUAL_ID: return new AssociationName3EditPart(view); case AssociationName4EditPart.VISUAL_ID: return new AssociationName4EditPart(view); case AssociationName5EditPart.VISUAL_ID: return new AssociationName5EditPart(view); case AssociationName6EditPart.VISUAL_ID: return new AssociationName6EditPart(view); case AssociationName7EditPart.VISUAL_ID: return new AssociationName7EditPart(view); case DependencySupplierEditPart.VISUAL_ID: return new DependencySupplierEditPart(view); case DependencyClientEditPart.VISUAL_ID: return new DependencyClientEditPart(view); case InterfaceRealizationEditPart.VISUAL_ID: return new InterfaceRealizationEditPart(view); case RealizationEditPart.VISUAL_ID: return new RealizationEditPart(view); case RealizationNameEditPart.VISUAL_ID: return new RealizationNameEditPart(view); case Generalization2EditPart.VISUAL_ID: return new Generalization2EditPart(view); case GeneralizationGeneralEditPart.VISUAL_ID: return new GeneralizationGeneralEditPart(view); case UsageEditPart.VISUAL_ID: return new UsageEditPart(view); case AssociationClassConnectorEditPart.VISUAL_ID: return new AssociationClassConnectorEditPart(view); } } return createUnrecognizedEditPart(context, model); }
diff --git a/src/com/trellmor/berrymotes/provider/EmotesProvider.java b/src/com/trellmor/berrymotes/provider/EmotesProvider.java index 3ab14a6..c88f6bb 100644 --- a/src/com/trellmor/berrymotes/provider/EmotesProvider.java +++ b/src/com/trellmor/berrymotes/provider/EmotesProvider.java @@ -1,247 +1,247 @@ /* * BerryMotes android * Copyright (C) 2013 Daniel Triendl <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.trellmor.berrymotes.provider; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.preference.PreferenceManager; import com.trellmor.berrymotes.provider.EmotesContract; import com.trellmor.berrymotes.SettingsActivity; import com.trellmor.berrymotes.util.SelectionBuilder; public class EmotesProvider extends ContentProvider { EmotesDatabase mDatabaseHelper; private static final String AUTHORITY = EmotesContract.CONTENT_AUTHORITY; public static final int ROUTE_EMOTES = 1; public static final int ROUTE_EMOTES_ID = 2; public static final int ROUTE_EMOTES_DISTINCT = 3; private static final UriMatcher sUriMatcher = new UriMatcher( UriMatcher.NO_MATCH); static { sUriMatcher.addURI(AUTHORITY, EmotesContract.PATH_EMOTES, ROUTE_EMOTES); sUriMatcher.addURI(AUTHORITY, EmotesContract.PATH_EMOTES + "/*", ROUTE_EMOTES_ID); sUriMatcher.addURI(AUTHORITY, EmotesContract.PATH_EMOTES_DISTINCT, ROUTE_EMOTES_DISTINCT); } @Override public boolean onCreate() { mDatabaseHelper = new EmotesDatabase(getContext()); return true; } @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case ROUTE_EMOTES: return EmotesContract.Emote.CONTENT_TYPE; case ROUTE_EMOTES_DISTINCT: return EmotesContract.Emote.CONTENT_TYPE; case ROUTE_EMOTES_ID: return EmotesContract.Emote.CONTENT_ITEM_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = mDatabaseHelper.getReadableDatabase(); SelectionBuilder builder = new SelectionBuilder(); Context ctx = getContext(); assert ctx != null; Cursor c; int uriMatch = sUriMatcher.match(uri); switch (uriMatch) { case ROUTE_EMOTES_ID: // Return a single entry, by ID String id = uri.getLastPathSegment(); builder.where(EmotesContract.Emote._ID + "=?", id); case ROUTE_EMOTES: // Return all known entries builder.table(EmotesContract.Emote.TABLE_NAME).where(selection, selectionArgs); - if (PreferenceManager.getDefaultSharedPreferences(getContext()) + if (!PreferenceManager.getDefaultSharedPreferences(getContext()) .getBoolean(SettingsActivity.KEY_SHOW_NSFW, false)) { builder.where(EmotesContract.Emote.COLUMN_NSFW + "=?", "0"); } c = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to // correctly register ContentObservers. c.setNotificationUri(ctx.getContentResolver(), uri); return c; case ROUTE_EMOTES_DISTINCT: // Return all known entries builder.table(EmotesContract.Emote.TABLE_NAME).where(selection, selectionArgs); c = builder.query(true, db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to // correctly register ContentObservers. c.setNotificationUri(ctx.getContentResolver(), uri); return c; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); assert db != null; final int match = sUriMatcher.match(uri); Uri result; switch (match) { case ROUTE_EMOTES: long id = db.insertOrThrow(EmotesContract.Emote.TABLE_NAME, null, values); result = Uri.parse(EmotesContract.Emote.CONTENT_URI + "/" + id); break; case ROUTE_EMOTES_ID: throw new UnsupportedOperationException( "Insert not supported on URI: " + uri); default: throw new UnsupportedOperationException("Unknown uri: " + uri); } // Send broadcast to registered ContentObservers, to refresh UI. Context ctx = getContext(); assert ctx != null; ctx.getContentResolver().notifyChange(uri, null, false); return result; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SelectionBuilder builder = new SelectionBuilder(); final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int count; switch (match) { case ROUTE_EMOTES: count = builder.table(EmotesContract.Emote.TABLE_NAME) .where(selection, selectionArgs).delete(db); break; case ROUTE_EMOTES_ID: String id = uri.getLastPathSegment(); count = builder.table(EmotesContract.Emote.TABLE_NAME) .where(EmotesContract.Emote._ID + "=?", id) .where(selection, selectionArgs).delete(db); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } // Send broadcast to registered ContentObservers, to refresh UI. Context ctx = getContext(); assert ctx != null; ctx.getContentResolver().notifyChange(uri, null, false); return count; } public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException("Update not supported"); } static class EmotesDatabase extends SQLiteOpenHelper { private final Context mContext; public static final int DATABASE_VERSION = 3; private static final String DATABASE_NAME = "emotes.db"; private static final String IDX_ENTRIES_NAME = "idx_" + EmotesContract.Emote.TABLE_NAME + "_" + EmotesContract.Emote.COLUMN_NAME; private static final String IDX_ENTRIES_HASH = "idx_" + EmotesContract.Emote.TABLE_NAME + "_" + EmotesContract.Emote.COLUMN_HASH; private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + EmotesContract.Emote.TABLE_NAME + " (" + EmotesContract.Emote._ID + " INTEGER PRIMARY KEY," + EmotesContract.Emote.COLUMN_NAME + " TEXT," + EmotesContract.Emote.COLUMN_NSFW + " INTEGER," + EmotesContract.Emote.COLUMN_APNG + " INTEGER," + EmotesContract.Emote.COLUMN_IMAGE + " TEXT," + EmotesContract.Emote.COLUMN_HASH + " TEXT," + EmotesContract.Emote.COLUMN_INDEX + " INTEGER," + EmotesContract.Emote.COLUMN_DELAY + " INTEGER)"; private static final String SQL_CREATE_IDX_ENTRIES_NAME = "CREATE INDEX " + IDX_ENTRIES_NAME + " ON " + EmotesContract.Emote.TABLE_NAME + "(" + EmotesContract.Emote.COLUMN_NAME + ")"; private static final String SQL_CREATE_IDX_ENTRIES_HASH = "CREATE INDEX " + IDX_ENTRIES_HASH + " ON " + EmotesContract.Emote.TABLE_NAME + "(" + EmotesContract.Emote.COLUMN_HASH + ")"; private static final String SQL_DROP_ENTRIES = "DROP TABLE IF EXISTS " + EmotesContract.Emote.TABLE_NAME; private static final String SQL_DROP_IDX_ENTRIES_NAME = "DROP INDEX IF EXISTS " + IDX_ENTRIES_NAME; private static final String SQL_DROP_IDX_ENTRIES_HASH = "DROP INDEX IF EXISTS " + IDX_ENTRIES_HASH; public EmotesDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mContext = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); db.execSQL(SQL_CREATE_IDX_ENTRIES_NAME); db.execSQL(SQL_CREATE_IDX_ENTRIES_HASH); PreferenceManager.getDefaultSharedPreferences(mContext).edit() .remove(SettingsActivity.KEY_SYNC_LAST_MODIFIED).commit(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DROP_IDX_ENTRIES_HASH); db.execSQL(SQL_DROP_IDX_ENTRIES_NAME); db.execSQL(SQL_DROP_ENTRIES); onCreate(db); } } }
true
true
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = mDatabaseHelper.getReadableDatabase(); SelectionBuilder builder = new SelectionBuilder(); Context ctx = getContext(); assert ctx != null; Cursor c; int uriMatch = sUriMatcher.match(uri); switch (uriMatch) { case ROUTE_EMOTES_ID: // Return a single entry, by ID String id = uri.getLastPathSegment(); builder.where(EmotesContract.Emote._ID + "=?", id); case ROUTE_EMOTES: // Return all known entries builder.table(EmotesContract.Emote.TABLE_NAME).where(selection, selectionArgs); if (PreferenceManager.getDefaultSharedPreferences(getContext()) .getBoolean(SettingsActivity.KEY_SHOW_NSFW, false)) { builder.where(EmotesContract.Emote.COLUMN_NSFW + "=?", "0"); } c = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to // correctly register ContentObservers. c.setNotificationUri(ctx.getContentResolver(), uri); return c; case ROUTE_EMOTES_DISTINCT: // Return all known entries builder.table(EmotesContract.Emote.TABLE_NAME).where(selection, selectionArgs); c = builder.query(true, db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to // correctly register ContentObservers. c.setNotificationUri(ctx.getContentResolver(), uri); return c; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } }
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = mDatabaseHelper.getReadableDatabase(); SelectionBuilder builder = new SelectionBuilder(); Context ctx = getContext(); assert ctx != null; Cursor c; int uriMatch = sUriMatcher.match(uri); switch (uriMatch) { case ROUTE_EMOTES_ID: // Return a single entry, by ID String id = uri.getLastPathSegment(); builder.where(EmotesContract.Emote._ID + "=?", id); case ROUTE_EMOTES: // Return all known entries builder.table(EmotesContract.Emote.TABLE_NAME).where(selection, selectionArgs); if (!PreferenceManager.getDefaultSharedPreferences(getContext()) .getBoolean(SettingsActivity.KEY_SHOW_NSFW, false)) { builder.where(EmotesContract.Emote.COLUMN_NSFW + "=?", "0"); } c = builder.query(db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to // correctly register ContentObservers. c.setNotificationUri(ctx.getContentResolver(), uri); return c; case ROUTE_EMOTES_DISTINCT: // Return all known entries builder.table(EmotesContract.Emote.TABLE_NAME).where(selection, selectionArgs); c = builder.query(true, db, projection, sortOrder); // Note: Notification URI must be manually set here for loaders to // correctly register ContentObservers. c.setNotificationUri(ctx.getContentResolver(), uri); return c; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } }
diff --git a/doc/examples/notify/ExampleLowBattery.java b/doc/examples/notify/ExampleLowBattery.java index 7c54b4a8..91e02b1c 100644 --- a/doc/examples/notify/ExampleLowBattery.java +++ b/doc/examples/notify/ExampleLowBattery.java @@ -1,105 +1,105 @@ /* * java-gnome, a UI library for writing GTK and GNOME programs from Java! * * Copyright © 2009-2010 Operational Dynamics Consulting, Pty Ltd and Others * * The code in this file, and the program it is a part of, is made available * to you by its authors as open source software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version * 2 ("GPL") as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details. * * You should have received a copy of the GPL along with this program. If not, * see http://www.gnu.org/licenses/. The authors of this program may be * contacted through http://java-gnome.sourceforge.net/. */ package notify; import org.gnome.gtk.Gtk; import org.gnome.gtk.StatusIcon; import org.gnome.notify.Notification; import org.gnome.notify.Notify; import org.gnome.notify.Urgency; /** * A simple program that sits in tray and displays a low battery warning. * * @author Serkan Kaba * @since 4.0.12 */ public class ExampleLowBattery { public static void main(String[] args) { final StatusIcon icon; final Notification notification; /* * Initialize GTK. */ Gtk.init(args); /* * Initialize notification system. */ Notify.init("low-battery-example"); /* * Create a StatusIcon with GNOME Power Manager icon. Note that * StatusIcon can not be directly constructed with an icon name. */ icon = new StatusIcon(); icon.setFromIconName("gnome-power-manager"); /* * Create a notification with a warning icon, attached to StatusIcon. */ notification = new Notification("Low Battery Example", "Your battery is low!", - "messagebox_warning", icon); + "messagebox_warning"); /* * Quit the application after notification disappears. */ notification.connect(new org.gnome.notify.Notification.Closed() { public void onClosed(Notification source) { Notify.uninit(); Gtk.mainQuit(); } }); /* * Make it play the warning sound from gnome-sound. Note that this may * change in distributions. Normally this hint should be set if the * server supports sounds. But unfortunately notification-daemon * doesn't report its sound capability although it supports sounds. * * See http://trac.galago-project.org/ticket/187 */ notification.setHint("sound-file", "/usr/share/sounds/warning.wav"); /* * Make the notification critical. */ notification.setUrgency(Urgency.CRITICAL); /* * Display the notification. */ notification.show(); /* * Run the main loop. */ Gtk.main(); } }
true
true
public static void main(String[] args) { final StatusIcon icon; final Notification notification; /* * Initialize GTK. */ Gtk.init(args); /* * Initialize notification system. */ Notify.init("low-battery-example"); /* * Create a StatusIcon with GNOME Power Manager icon. Note that * StatusIcon can not be directly constructed with an icon name. */ icon = new StatusIcon(); icon.setFromIconName("gnome-power-manager"); /* * Create a notification with a warning icon, attached to StatusIcon. */ notification = new Notification("Low Battery Example", "Your battery is low!", "messagebox_warning", icon); /* * Quit the application after notification disappears. */ notification.connect(new org.gnome.notify.Notification.Closed() { public void onClosed(Notification source) { Notify.uninit(); Gtk.mainQuit(); } }); /* * Make it play the warning sound from gnome-sound. Note that this may * change in distributions. Normally this hint should be set if the * server supports sounds. But unfortunately notification-daemon * doesn't report its sound capability although it supports sounds. * * See http://trac.galago-project.org/ticket/187 */ notification.setHint("sound-file", "/usr/share/sounds/warning.wav"); /* * Make the notification critical. */ notification.setUrgency(Urgency.CRITICAL); /* * Display the notification. */ notification.show(); /* * Run the main loop. */ Gtk.main(); }
public static void main(String[] args) { final StatusIcon icon; final Notification notification; /* * Initialize GTK. */ Gtk.init(args); /* * Initialize notification system. */ Notify.init("low-battery-example"); /* * Create a StatusIcon with GNOME Power Manager icon. Note that * StatusIcon can not be directly constructed with an icon name. */ icon = new StatusIcon(); icon.setFromIconName("gnome-power-manager"); /* * Create a notification with a warning icon, attached to StatusIcon. */ notification = new Notification("Low Battery Example", "Your battery is low!", "messagebox_warning"); /* * Quit the application after notification disappears. */ notification.connect(new org.gnome.notify.Notification.Closed() { public void onClosed(Notification source) { Notify.uninit(); Gtk.mainQuit(); } }); /* * Make it play the warning sound from gnome-sound. Note that this may * change in distributions. Normally this hint should be set if the * server supports sounds. But unfortunately notification-daemon * doesn't report its sound capability although it supports sounds. * * See http://trac.galago-project.org/ticket/187 */ notification.setHint("sound-file", "/usr/share/sounds/warning.wav"); /* * Make the notification critical. */ notification.setUrgency(Urgency.CRITICAL); /* * Display the notification. */ notification.show(); /* * Run the main loop. */ Gtk.main(); }
diff --git a/src/com/example/reptilexpress/transportapi/BusInformation.java b/src/com/example/reptilexpress/transportapi/BusInformation.java index 67ed598..bdac25e 100644 --- a/src/com/example/reptilexpress/transportapi/BusInformation.java +++ b/src/com/example/reptilexpress/transportapi/BusInformation.java @@ -1,246 +1,246 @@ package com.example.reptilexpress.transportapi; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.location.Location; import android.net.Uri; import android.text.format.Time; import android.util.Log; public class BusInformation { public static List<Stop> getClosestStops(final Location location) { try { return sharedInstance.closestStops(location); } catch (Exception e) { throw new RuntimeException("Failed getting closest stops", e); } } public static List<Arrival> getStopTimetable(final Stop stop) { try { return sharedInstance.stopTimetable(stop); } catch (Exception e) { throw new RuntimeException("Failed getting stop timetable", e); } } public static List<Arrival> getBusTimetable(final Arrival arrival) { try { return sharedInstance.busTimetable(arrival); } catch (Exception e) { throw new RuntimeException("Failed getting bus timetable", e); } } /* Unsafe singleton, * but it doesn't matter if we accidentally (or deliberately) * create more than one instance. */ private static BusInformation sharedInstance = new BusInformation("56189ff394e20f89ed61a4bf32f1c065", "525bfde7"); private final String apiKey; private final String appId; private final HttpClient http; public BusInformation(final String apiKey, final String appId) { this.apiKey = apiKey; this.appId = appId; this.http = new DefaultHttpClient(); } private static final int numberOfClosestStops = 5; public List<Stop> closestStops(final Location location) throws Exception { final Uri url = Uri.parse("http://transportapi.com").buildUpon() .path("v3/uk/bus/stops/near.json") .appendQueryParameter("api_key", apiKey) .appendQueryParameter("app_id", appId) .appendQueryParameter("lat", String.valueOf(location.getLatitude())) .appendQueryParameter("lon", String.valueOf(location.getLongitude())) .appendQueryParameter("rpp", String.valueOf(numberOfClosestStops)) .appendQueryParameter("page", String.valueOf(1)) .build(); Log.d("JSON API", String.format("Requesting %s", url)); final HttpResponse response = http.execute(new HttpGet(url.toString())); final StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { response.getEntity().getContent().close(); throw new IOException(status.getReasonPhrase()); } final JSONArray stops; { try { stops = new JSONObject(EntityUtils.toString(response.getEntity())) .getJSONArray("stops"); } catch (JSONException e) { throw new Exception("Request returned invalid JSON", e); } if (stops == null) { throw new Exception("Request returned invalid JSON (data missing)"); } } final ArrayList<Stop> result = new ArrayList<Stop>(stops.length()); for (int i = 0; i < stops.length(); ++i) { final JSONObject stop = stops.getJSONObject(i); result.add(new Stop( stop.getString("atcocode"), stop.getString("name"))); } return result; } public List<Arrival> stopTimetable(final Stop stop) throws Exception { final Calendar now = Calendar.getInstance(Locale.UK); final Uri url = Uri.parse("http://transportapi.com").buildUpon() .path(String.format("v3/uk/bus/stop/%s/%s/%s/timetable.json", stop.atcocode, dateFormat.format(now.getTime()), timeFormat.format(now.getTime()))) .appendQueryParameter("api_key", apiKey) .appendQueryParameter("app_id", appId) .appendQueryParameter("group", "no") .build(); Log.d("JSON API", String.format("Requesting %s", url)); final HttpResponse response = http.execute(new HttpGet(url.toString())); final StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { response.getEntity().getContent().close(); throw new IOException(status.getReasonPhrase()); } final JSONArray arrivals; { try { JSONObject root = new JSONObject(EntityUtils.toString(response.getEntity())); root = root.getJSONObject("departures"); if (root == null) throw new Exception("Request returned invalid JSON (data missing)"); arrivals = root.getJSONArray("all"); } catch (JSONException e) { throw new Exception("Request returned invalid JSON", e); } if (arrivals == null) { throw new Exception("Request returned invalid JSON (data missing)"); } } final ArrayList<Arrival> result = new ArrayList<Arrival>(arrivals.length()); for (int i = 0; i < arrivals.length(); ++i) { final JSONObject arrival = arrivals.getJSONObject(i); result.add(new Arrival( new Bus(arrival.getString("line"), arrival.getString("operator"), arrival.getString("direction")), stop, parseSimpleTime(arrival.getString("aimed_departure_time")))); } return result; } public List<Arrival> busTimetable(final Arrival arrival) throws Exception { final Calendar now = Calendar.getInstance(Locale.UK); final Uri url = Uri.parse("http://transportapi.com").buildUpon() .path(String.format("v3/uk/bus/route/%s/%s/inbound/%s/%s/%s/timetable", arrival.bus.operator, arrival.bus.route, arrival.stop.atcocode, dateFormat.format(now.getTime()), timeFormat.format(now.getTime()))) .appendQueryParameter("api_key", apiKey) .appendQueryParameter("app_id", appId) .appendQueryParameter("group", "no") .build(); Log.d("JSON API", String.format("Requesting %s", url)); final HttpResponse response = http.execute(new HttpGet(url.toString())); final StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { response.getEntity().getContent().close(); throw new IOException(status.getReasonPhrase()); } final Document doc = Jsoup.parse( EntityUtils.toString(response.getEntity()), url.toString()); - final Element stopList = doc.getElementById("busroutelist"); + final Element stopList = doc.getElementsByClass("busroutelist").first(); final Elements stopListItems = stopList.getElementsByTag("li"); ArrayList<Arrival> result = new ArrayList<Arrival>(); for (Element stopListItem : stopListItems) { String destcode; String destname; Time desttime; Element timeElement = stopListItem.getElementsByClass("routelist-time").first(); desttime = parseSimpleTime(timeElement.text().substring(0, 5)); Element destElement = stopListItem.getElementsByClass("routelist-destination").first(); String href = destElement.getElementsByTag("a").first().attr("href"); destcode = href; if (destcode.startsWith("/v3/uk/bus/stop/")) { destcode = destcode.substring("/v3/uk/bus/stop/".length()); } if (destcode.indexOf('/') > 0) { destcode = destcode.substring(0, destcode.indexOf('/')); } destname = destElement.text(); result.add(new Arrival( arrival.bus, new Stop(destcode, destname), desttime)); } return result; } private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.UK); private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.UK); private static Time parseSimpleTime(final String time) throws ParseException { Date raw = timeFormat.parse(time); Calendar now = Calendar.getInstance(Locale.UK); Calendar calendar = Calendar.getInstance(Locale.UK); calendar.setTime(raw); while (calendar.before(now)) calendar.add(Calendar.DATE, 1); Time result = new Time(); result.set(calendar.getTimeInMillis()); return result; } }
true
true
public List<Arrival> busTimetable(final Arrival arrival) throws Exception { final Calendar now = Calendar.getInstance(Locale.UK); final Uri url = Uri.parse("http://transportapi.com").buildUpon() .path(String.format("v3/uk/bus/route/%s/%s/inbound/%s/%s/%s/timetable", arrival.bus.operator, arrival.bus.route, arrival.stop.atcocode, dateFormat.format(now.getTime()), timeFormat.format(now.getTime()))) .appendQueryParameter("api_key", apiKey) .appendQueryParameter("app_id", appId) .appendQueryParameter("group", "no") .build(); Log.d("JSON API", String.format("Requesting %s", url)); final HttpResponse response = http.execute(new HttpGet(url.toString())); final StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { response.getEntity().getContent().close(); throw new IOException(status.getReasonPhrase()); } final Document doc = Jsoup.parse( EntityUtils.toString(response.getEntity()), url.toString()); final Element stopList = doc.getElementById("busroutelist"); final Elements stopListItems = stopList.getElementsByTag("li"); ArrayList<Arrival> result = new ArrayList<Arrival>(); for (Element stopListItem : stopListItems) { String destcode; String destname; Time desttime; Element timeElement = stopListItem.getElementsByClass("routelist-time").first(); desttime = parseSimpleTime(timeElement.text().substring(0, 5)); Element destElement = stopListItem.getElementsByClass("routelist-destination").first(); String href = destElement.getElementsByTag("a").first().attr("href"); destcode = href; if (destcode.startsWith("/v3/uk/bus/stop/")) { destcode = destcode.substring("/v3/uk/bus/stop/".length()); } if (destcode.indexOf('/') > 0) { destcode = destcode.substring(0, destcode.indexOf('/')); } destname = destElement.text(); result.add(new Arrival( arrival.bus, new Stop(destcode, destname), desttime)); } return result; }
public List<Arrival> busTimetable(final Arrival arrival) throws Exception { final Calendar now = Calendar.getInstance(Locale.UK); final Uri url = Uri.parse("http://transportapi.com").buildUpon() .path(String.format("v3/uk/bus/route/%s/%s/inbound/%s/%s/%s/timetable", arrival.bus.operator, arrival.bus.route, arrival.stop.atcocode, dateFormat.format(now.getTime()), timeFormat.format(now.getTime()))) .appendQueryParameter("api_key", apiKey) .appendQueryParameter("app_id", appId) .appendQueryParameter("group", "no") .build(); Log.d("JSON API", String.format("Requesting %s", url)); final HttpResponse response = http.execute(new HttpGet(url.toString())); final StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { response.getEntity().getContent().close(); throw new IOException(status.getReasonPhrase()); } final Document doc = Jsoup.parse( EntityUtils.toString(response.getEntity()), url.toString()); final Element stopList = doc.getElementsByClass("busroutelist").first(); final Elements stopListItems = stopList.getElementsByTag("li"); ArrayList<Arrival> result = new ArrayList<Arrival>(); for (Element stopListItem : stopListItems) { String destcode; String destname; Time desttime; Element timeElement = stopListItem.getElementsByClass("routelist-time").first(); desttime = parseSimpleTime(timeElement.text().substring(0, 5)); Element destElement = stopListItem.getElementsByClass("routelist-destination").first(); String href = destElement.getElementsByTag("a").first().attr("href"); destcode = href; if (destcode.startsWith("/v3/uk/bus/stop/")) { destcode = destcode.substring("/v3/uk/bus/stop/".length()); } if (destcode.indexOf('/') > 0) { destcode = destcode.substring(0, destcode.indexOf('/')); } destname = destElement.text(); result.add(new Arrival( arrival.bus, new Stop(destcode, destname), desttime)); } return result; }
diff --git a/trunk/GeoBeagle/src/com/google/code/geobeagle/xmlimport/EventHandlerGpx.java b/trunk/GeoBeagle/src/com/google/code/geobeagle/xmlimport/EventHandlerGpx.java index 485e9213..461ae410 100644 --- a/trunk/GeoBeagle/src/com/google/code/geobeagle/xmlimport/EventHandlerGpx.java +++ b/trunk/GeoBeagle/src/com/google/code/geobeagle/xmlimport/EventHandlerGpx.java @@ -1,121 +1,121 @@ /* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import java.io.IOException; class EventHandlerGpx implements EventHandler { static final String XPATH_CACHE_CONTAINER = "/gpx/wpt/groundspeak:cache/groundspeak:container"; static final String XPATH_CACHE_DIFFICULTY = "/gpx/wpt/groundspeak:cache/groundspeak:difficulty"; static final String XPATH_CACHE_TERRAIN = "/gpx/wpt/groundspeak:cache/groundspeak:terrain"; static final String XPATH_CACHE_TYPE = "/gpx/wpt/groundspeak:cache/groundspeak:type"; static final String XPATH_GEOCACHE_CONTAINER = "/gpx/wpt/geocache/container"; static final String XPATH_GEOCACHE_DIFFICULTY = "/gpx/wpt/geocache/difficulty"; static final String XPATH_GEOCACHE_TERRAIN = "/gpx/wpt/geocache/terrain"; static final String XPATH_GEOCACHE_TYPE = "/gpx/wpt/geocache/type"; static final String XPATH_GEOCACHEHINT = "/gpx/wpt/geocache/hints"; static final String XPATH_GEOCACHELOGDATE = "/gpx/wpt/geocache/logs/log/time"; static final String XPATH_GEOCACHENAME = "/gpx/wpt/geocache/name"; static final String XPATH_GPXNAME = "/gpx/name"; static final String XPATH_GPXTIME = "/gpx/time"; static final String XPATH_GROUNDSPEAKNAME = "/gpx/wpt/groundspeak:cache/groundspeak:name"; static final String XPATH_HINT = "/gpx/wpt/groundspeak:cache/groundspeak:encoded_hints"; static final String XPATH_LOGDATE = "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:date"; static final String[] XPATH_PLAINLINES = { "/gpx/wpt/cmt", "/gpx/wpt/desc", "/gpx/wpt/groundspeak:cache/groundspeak:type", "/gpx/wpt/groundspeak:cache/groundspeak:container", "/gpx/wpt/groundspeak:cache/groundspeak:short_description", "/gpx/wpt/groundspeak:cache/groundspeak:long_description", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:type", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:finder", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:text", /* here are the geocaching.com.au entries */ "/gpx/wpt/geocache/owner", "/gpx/wpt/geocache/type", "/gpx/wpt/geocache/summary", "/gpx/wpt/geocache/description", "/gpx/wpt/geocache/logs/log/geocacher", "/gpx/wpt/geocache/logs/log/type", "/gpx/wpt/geocache/logs/log/text" }; static final String XPATH_SYM = "/gpx/wpt/sym"; static final String XPATH_WPT = "/gpx/wpt"; static final String XPATH_WPTDESC = "/gpx/wpt/desc"; static final String XPATH_WPTNAME = "/gpx/wpt/name"; static final String XPATH_WAYPOINT_TYPE = "/gpx/wpt/type"; private final CachePersisterFacade mCachePersisterFacade; public EventHandlerGpx(CachePersisterFacade cachePersisterFacade) { mCachePersisterFacade = cachePersisterFacade; } public void endTag(String previousFullPath) throws IOException { if (previousFullPath.equals(XPATH_WPT)) { mCachePersisterFacade.endCache(Source.GPX); } } public void startTag(String fullPath, XmlPullParserWrapper xmlPullParser) { if (fullPath.equals(XPATH_WPT)) { mCachePersisterFacade.startCache(); mCachePersisterFacade.wpt(xmlPullParser.getAttributeValue(null, "lat"), xmlPullParser .getAttributeValue(null, "lon")); } } public boolean text(String fullPath, String text) throws IOException { - text = text.trim(); + String trimmedText = text.trim(); //Log.d("GeoBeagle", "fullPath " + fullPath + ", text " + text); if (fullPath.equals(XPATH_WPTNAME)) { - mCachePersisterFacade.wptName(text); + mCachePersisterFacade.wptName(trimmedText); } else if (fullPath.equals(XPATH_WPTDESC)) { - mCachePersisterFacade.wptDesc(text); + mCachePersisterFacade.wptDesc(trimmedText); } else if (fullPath.equals(XPATH_GPXTIME)) { - return mCachePersisterFacade.gpxTime(text); + return mCachePersisterFacade.gpxTime(trimmedText); } else if (fullPath.equals(XPATH_GROUNDSPEAKNAME) || fullPath.equals(XPATH_GEOCACHENAME)) { - mCachePersisterFacade.groundspeakName(text); + mCachePersisterFacade.groundspeakName(trimmedText); } else if (fullPath.equals(XPATH_LOGDATE) || fullPath.equals(XPATH_GEOCACHELOGDATE)) { - mCachePersisterFacade.logDate(text); + mCachePersisterFacade.logDate(trimmedText); } else if (fullPath.equals(XPATH_SYM)) { - mCachePersisterFacade.symbol(text); + mCachePersisterFacade.symbol(trimmedText); } else if (fullPath.equals(XPATH_HINT) || fullPath.equals(XPATH_GEOCACHEHINT)) { - if (!text.equals("")) { - mCachePersisterFacade.hint(text); + if (!trimmedText.equals("")) { + mCachePersisterFacade.hint(trimmedText); } } else if (fullPath.equals(XPATH_CACHE_TYPE) || fullPath.equals(XPATH_GEOCACHE_TYPE) || fullPath.equals(XPATH_WAYPOINT_TYPE)) { //Log.d("GeoBeagle", "Setting cache type " + text); - mCachePersisterFacade.cacheType(text); + mCachePersisterFacade.cacheType(trimmedText); } else if (fullPath.equals(XPATH_CACHE_DIFFICULTY) || fullPath.equals(XPATH_GEOCACHE_DIFFICULTY)) { - mCachePersisterFacade.difficulty(text); + mCachePersisterFacade.difficulty(trimmedText); } else if (fullPath.equals(XPATH_CACHE_TERRAIN) || fullPath.equals(XPATH_GEOCACHE_TERRAIN)) { - mCachePersisterFacade.terrain(text); + mCachePersisterFacade.terrain(trimmedText); } else if (fullPath.equals(XPATH_CACHE_CONTAINER) || fullPath.equals(XPATH_GEOCACHE_CONTAINER)) { - mCachePersisterFacade.container(text); + mCachePersisterFacade.container(trimmedText); } for (String writeLineMatch : XPATH_PLAINLINES) { if (fullPath.equals(writeLineMatch)) { - mCachePersisterFacade.line(text); + mCachePersisterFacade.line(trimmedText); return true; } } return true; } }
false
true
public boolean text(String fullPath, String text) throws IOException { text = text.trim(); //Log.d("GeoBeagle", "fullPath " + fullPath + ", text " + text); if (fullPath.equals(XPATH_WPTNAME)) { mCachePersisterFacade.wptName(text); } else if (fullPath.equals(XPATH_WPTDESC)) { mCachePersisterFacade.wptDesc(text); } else if (fullPath.equals(XPATH_GPXTIME)) { return mCachePersisterFacade.gpxTime(text); } else if (fullPath.equals(XPATH_GROUNDSPEAKNAME) || fullPath.equals(XPATH_GEOCACHENAME)) { mCachePersisterFacade.groundspeakName(text); } else if (fullPath.equals(XPATH_LOGDATE) || fullPath.equals(XPATH_GEOCACHELOGDATE)) { mCachePersisterFacade.logDate(text); } else if (fullPath.equals(XPATH_SYM)) { mCachePersisterFacade.symbol(text); } else if (fullPath.equals(XPATH_HINT) || fullPath.equals(XPATH_GEOCACHEHINT)) { if (!text.equals("")) { mCachePersisterFacade.hint(text); } } else if (fullPath.equals(XPATH_CACHE_TYPE) || fullPath.equals(XPATH_GEOCACHE_TYPE) || fullPath.equals(XPATH_WAYPOINT_TYPE)) { //Log.d("GeoBeagle", "Setting cache type " + text); mCachePersisterFacade.cacheType(text); } else if (fullPath.equals(XPATH_CACHE_DIFFICULTY) || fullPath.equals(XPATH_GEOCACHE_DIFFICULTY)) { mCachePersisterFacade.difficulty(text); } else if (fullPath.equals(XPATH_CACHE_TERRAIN) || fullPath.equals(XPATH_GEOCACHE_TERRAIN)) { mCachePersisterFacade.terrain(text); } else if (fullPath.equals(XPATH_CACHE_CONTAINER) || fullPath.equals(XPATH_GEOCACHE_CONTAINER)) { mCachePersisterFacade.container(text); } for (String writeLineMatch : XPATH_PLAINLINES) { if (fullPath.equals(writeLineMatch)) { mCachePersisterFacade.line(text); return true; } } return true; }
public boolean text(String fullPath, String text) throws IOException { String trimmedText = text.trim(); //Log.d("GeoBeagle", "fullPath " + fullPath + ", text " + text); if (fullPath.equals(XPATH_WPTNAME)) { mCachePersisterFacade.wptName(trimmedText); } else if (fullPath.equals(XPATH_WPTDESC)) { mCachePersisterFacade.wptDesc(trimmedText); } else if (fullPath.equals(XPATH_GPXTIME)) { return mCachePersisterFacade.gpxTime(trimmedText); } else if (fullPath.equals(XPATH_GROUNDSPEAKNAME) || fullPath.equals(XPATH_GEOCACHENAME)) { mCachePersisterFacade.groundspeakName(trimmedText); } else if (fullPath.equals(XPATH_LOGDATE) || fullPath.equals(XPATH_GEOCACHELOGDATE)) { mCachePersisterFacade.logDate(trimmedText); } else if (fullPath.equals(XPATH_SYM)) { mCachePersisterFacade.symbol(trimmedText); } else if (fullPath.equals(XPATH_HINT) || fullPath.equals(XPATH_GEOCACHEHINT)) { if (!trimmedText.equals("")) { mCachePersisterFacade.hint(trimmedText); } } else if (fullPath.equals(XPATH_CACHE_TYPE) || fullPath.equals(XPATH_GEOCACHE_TYPE) || fullPath.equals(XPATH_WAYPOINT_TYPE)) { //Log.d("GeoBeagle", "Setting cache type " + text); mCachePersisterFacade.cacheType(trimmedText); } else if (fullPath.equals(XPATH_CACHE_DIFFICULTY) || fullPath.equals(XPATH_GEOCACHE_DIFFICULTY)) { mCachePersisterFacade.difficulty(trimmedText); } else if (fullPath.equals(XPATH_CACHE_TERRAIN) || fullPath.equals(XPATH_GEOCACHE_TERRAIN)) { mCachePersisterFacade.terrain(trimmedText); } else if (fullPath.equals(XPATH_CACHE_CONTAINER) || fullPath.equals(XPATH_GEOCACHE_CONTAINER)) { mCachePersisterFacade.container(trimmedText); } for (String writeLineMatch : XPATH_PLAINLINES) { if (fullPath.equals(writeLineMatch)) { mCachePersisterFacade.line(trimmedText); return true; } } return true; }
diff --git a/Product/Controller/src/org/openremote/controller/servlet/AdministratorServlet.java b/Product/Controller/src/org/openremote/controller/servlet/AdministratorServlet.java index 9ca6ff7..5881111 100644 --- a/Product/Controller/src/org/openremote/controller/servlet/AdministratorServlet.java +++ b/Product/Controller/src/org/openremote/controller/servlet/AdministratorServlet.java @@ -1,210 +1,214 @@ /* * OpenRemote, the Home of the Digital Home. * Copyright 2008-2012, OpenRemote Inc. * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openremote.controller.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.openremote.controller.Constants; import org.openremote.controller.ControllerConfiguration; import org.openremote.controller.service.ClientService; import org.openremote.controller.service.ConfigurationService; import org.openremote.controller.spring.SpringContext; import org.openremote.controller.utils.AuthenticationUtil; import org.openremote.controller.utils.ResultSetUtil; import freemarker.template.Configuration; import freemarker.template.ObjectWrapper; import freemarker.template.Template; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * This servlet is used to show the list of clients, * manage the clients (accept, revoke and putting the client in a group) * * @author <a href="mailto:[email protected]">Melroy van den Berg</a> 2012 * */ @SuppressWarnings("serial") public class AdministratorServlet extends HttpServlet { private final static Logger logger = Logger.getLogger(Constants.SERVLET_LOG_CATEGORY); private static ClientService clientService = (ClientService) SpringContext.getInstance().getBean("clientService"); private static ConfigurationService configurationService = (ConfigurationService) SpringContext.getInstance().getBean("configurationService"); /** * Set the result set into a collection * * @param resultSet ResultSet * @return Collection */ @SuppressWarnings("rawtypes") private Collection resultSetToCollection(ResultSet resultSet) { Collection collection = null; try { collection = ResultSetUtil.getMaps(resultSet); } catch (SQLException e) { logger.error("SQLException: " + e.getMessage()); } return collection; } /** * Set the result sets in a hash map and give it to Freemarker * * @return String a HTML template with the data */ @SuppressWarnings("rawtypes") private String setDataInTemplate() { Map<String, Object> root = new HashMap<String, Object>(); String result = ""; - String errorString = ""; + String errorString = "", warningString = ""; int numClients = 0; boolean isAuthenticationEnabled = false; Collection clientCollection = null, settingCollection = null; ResultSet clients = clientService.getClients(); numClients = clientService.getNumClients(); clientCollection = resultSetToCollection(clients); clientService.free(); ResultSet settings = configurationService.getAllItems(); settingCollection = resultSetToCollection(settings); configurationService.free(); try { isAuthenticationEnabled = configurationService.getBooleanItem("authentication"); if(clientCollection != null && settingCollection != null) { if(numClients > 0) { root.put( "clients", clientCollection ); } else { if(isAuthenticationEnabled) { - errorString = "No clients in the database."; + warningString = "No clients in the database."; } } root.put( "configurations", settingCollection ); } else { - errorString = "Database problem!"; + errorString = "Database problem!<br />"; } if(configurationService.shouldReboot()) { - errorString += "<br /><b><font color='#FFA500'>Do NOT forget to restart your Tomcat server manually to apply the changes.</font></b>"; + errorString += "<b>Do NOT forget to restart your Tomcat server manually to apply the changes.</b>"; } if(!errorString.isEmpty()) { root.put( "errorMessage", errorString); } + if(!warningString.isEmpty()) + { + root.put( "warningMessage", warningString); + } root.put( "authEnabled", isAuthenticationEnabled); result = freemarkerDo(root, "administrator.ftl"); } catch(Exception e) { result = "<h1>Template Exception</h1>"; result += e.getLocalizedMessage(); logger.error(e.getMessage()); } return result; } /** * Process a template using FreeMarker and print the results * * @param root HashMap with data * @param template the name of the template file * @return HTML template with the specified data * @throws Exception FreeMarker exception */ @SuppressWarnings("rawtypes") static String freemarkerDo(Map root, String template) throws Exception { Configuration cfg = new Configuration(); // Read the XML file and process the template using FreeMarker ControllerConfiguration configuration = ControllerConfiguration.readXML(); cfg.setDirectoryForTemplateLoading(new File(configuration.getResourcePath())); cfg.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER); Template temp = cfg.getTemplate(template); StringWriter out = new StringWriter(); temp.process( root, out ); return out.getBuffer().toString(); } /** * Get request handler for the administrator URI * @param request the request from HTTP servlet * @param reponse where the respond can be written to */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(!AuthenticationUtil.isAuth(request, configurationService)){ response.sendRedirect("/controller/login"); return; } PrintWriter printWriter = response.getWriter(); try { printWriter.print(setDataInTemplate()); response.setStatus(200); } catch (NullPointerException e) { response.setStatus(406); logger.error("NullPointer in Administrator Servlet: ", e); } } }
false
true
private String setDataInTemplate() { Map<String, Object> root = new HashMap<String, Object>(); String result = ""; String errorString = ""; int numClients = 0; boolean isAuthenticationEnabled = false; Collection clientCollection = null, settingCollection = null; ResultSet clients = clientService.getClients(); numClients = clientService.getNumClients(); clientCollection = resultSetToCollection(clients); clientService.free(); ResultSet settings = configurationService.getAllItems(); settingCollection = resultSetToCollection(settings); configurationService.free(); try { isAuthenticationEnabled = configurationService.getBooleanItem("authentication"); if(clientCollection != null && settingCollection != null) { if(numClients > 0) { root.put( "clients", clientCollection ); } else { if(isAuthenticationEnabled) { errorString = "No clients in the database."; } } root.put( "configurations", settingCollection ); } else { errorString = "Database problem!"; } if(configurationService.shouldReboot()) { errorString += "<br /><b><font color='#FFA500'>Do NOT forget to restart your Tomcat server manually to apply the changes.</font></b>"; } if(!errorString.isEmpty()) { root.put( "errorMessage", errorString); } root.put( "authEnabled", isAuthenticationEnabled); result = freemarkerDo(root, "administrator.ftl"); } catch(Exception e) { result = "<h1>Template Exception</h1>"; result += e.getLocalizedMessage(); logger.error(e.getMessage()); } return result; }
private String setDataInTemplate() { Map<String, Object> root = new HashMap<String, Object>(); String result = ""; String errorString = "", warningString = ""; int numClients = 0; boolean isAuthenticationEnabled = false; Collection clientCollection = null, settingCollection = null; ResultSet clients = clientService.getClients(); numClients = clientService.getNumClients(); clientCollection = resultSetToCollection(clients); clientService.free(); ResultSet settings = configurationService.getAllItems(); settingCollection = resultSetToCollection(settings); configurationService.free(); try { isAuthenticationEnabled = configurationService.getBooleanItem("authentication"); if(clientCollection != null && settingCollection != null) { if(numClients > 0) { root.put( "clients", clientCollection ); } else { if(isAuthenticationEnabled) { warningString = "No clients in the database."; } } root.put( "configurations", settingCollection ); } else { errorString = "Database problem!<br />"; } if(configurationService.shouldReboot()) { errorString += "<b>Do NOT forget to restart your Tomcat server manually to apply the changes.</b>"; } if(!errorString.isEmpty()) { root.put( "errorMessage", errorString); } if(!warningString.isEmpty()) { root.put( "warningMessage", warningString); } root.put( "authEnabled", isAuthenticationEnabled); result = freemarkerDo(root, "administrator.ftl"); } catch(Exception e) { result = "<h1>Template Exception</h1>"; result += e.getLocalizedMessage(); logger.error(e.getMessage()); } return result; }
diff --git a/components/bio-formats/src/loci/formats/RandomAccessStream.java b/components/bio-formats/src/loci/formats/RandomAccessStream.java index 19f3feffb..0611f2d5f 100644 --- a/components/bio-formats/src/loci/formats/RandomAccessStream.java +++ b/components/bio-formats/src/loci/formats/RandomAccessStream.java @@ -1,715 +1,718 @@ // // RandomAccessStream.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats; import java.io.*; import java.util.*; import java.util.zip.*; import loci.formats.codec.CBZip2InputStream; /** * RandomAccessStream provides methods for "intelligent" reading of files and * byte arrays. It also automagically deals with closing and reopening files * to prevent an IOException caused by too many open files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/RandomAccessStream.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/RandomAccessStream.java">SVN</a></dd></dl> * * @author Melissa Linkert linkert at wisc.edu */ public class RandomAccessStream extends InputStream implements DataInput { // -- Constants -- /** Maximum size of the buffer used by the DataInputStream. */ protected static final int MAX_OVERHEAD = 1048576; /** Maximum number of open files. */ protected static final int MAX_FILES = 100; /** Indicators for most efficient method of reading. */ protected static final int DIS = 0; protected static final int RAF = 1; protected static final int ARRAY = 2; // -- Static fields -- /** Hashtable of all files that have been opened at some point. */ private static Hashtable fileCache = new Hashtable(); /** Number of currently open files. */ private static int openFiles = 0; // -- Fields -- protected IRandomAccess raf; protected DataInputStream dis; /** Length of the file. */ protected long length; /** The file pointer within the DIS. */ protected long fp; /** The "absolute" file pointer. */ protected long afp; /** Most recent mark. */ protected long mark; /** Next place to mark. */ protected long nextMark; /** The file name. */ protected String file; /** Starting buffer. */ protected byte[] buf; /** Endianness of the stream. */ protected boolean littleEndian = false; /** Number of bytes by which to extend the stream. */ protected int ext = 0; /** Flag indicating this file has been compressed. */ protected boolean compressed = false; // -- Constructors -- /** * Constructs a hybrid RandomAccessFile/DataInputStream * around the given file. */ public RandomAccessStream(String file) throws IOException { File f = new File(Location.getMappedId(file)); f = f.getAbsoluteFile(); if (Location.getMappedFile(file) != null) { raf = Location.getMappedFile(file); length = raf.length(); } else if (f.exists()) { raf = new RAFile(f, "r"); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD); String path = f.getPath().toLowerCase(); if (path.endsWith(".gz")) { dis = new DataInputStream(new GZIPInputStream(bis)); compressed = true; length = 0; while (true) { int skip = dis.skipBytes(1024); if (skip <= 0) break; length += skip; } bis = new BufferedInputStream( new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD); dis = new DataInputStream(new GZIPInputStream(bis)); } else if (path.endsWith(".zip")) { ZipFile zf = new ZipFile(Location.getMappedId(file)); // strip off .zip extension and directory prefix String innerId = path.substring(0, path.length() - 4); int slash = innerId.lastIndexOf(File.separator); if (slash < 0) slash = innerId.lastIndexOf("/"); if (slash >= 0) innerId = innerId.substring(slash + 1); // look for zip entry with same prefix as the ZIP file ZipEntry entry = null; Enumeration en = zf.entries(); while (en.hasMoreElements()) { ZipEntry ze = (ZipEntry) en.nextElement(); if (ze.getName().startsWith(innerId)) { // found entry with matching name entry = ze; break; } else if (entry == null) entry = ze; // default to first entry } if (entry == null) { throw new IOException("Zip file '" + file + "' has no entries"); } compressed = true; length = entry.getSize(); dis = new DataInputStream(new BufferedInputStream( zf.getInputStream(entry), MAX_OVERHEAD)); } else if (path.endsWith(".bz2")) { bis.skip(2); dis = new DataInputStream(new CBZip2InputStream(bis)); compressed = true; length = 0; while (true) { int skip = dis.skipBytes(1024); if (skip <= 0) break; length += skip; } bis = new BufferedInputStream( new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD); bis.skip(2); dis = new DataInputStream(new CBZip2InputStream(bis)); } else dis = new DataInputStream(bis); if (!compressed) { length = raf.length(); buf = new byte[(int) (length < MAX_OVERHEAD ? length : MAX_OVERHEAD)]; raf.readFully(buf); raf.seek(0); nextMark = MAX_OVERHEAD; } } else if (file.startsWith("http")) { raf = new RAUrl(Location.getMappedId(file), "r"); length = raf.length(); } else throw new IOException("File not found : " + file); this.file = file; fp = 0; afp = 0; fileCache.put(this, Boolean.TRUE); openFiles++; if (openFiles > MAX_FILES) cleanCache(); } /** Constructs a random access stream around the given byte array. */ public RandomAccessStream(byte[] array) throws IOException { // this doesn't use a file descriptor, so we don't need to add it to the // file cache raf = new RABytes(array); fp = 0; afp = 0; length = raf.length(); } // -- RandomAccessStream API methods -- /** Returns the underlying InputStream. */ public DataInputStream getInputStream() { try { if (Boolean.FALSE.equals(fileCache.get(this))) reopen(); } catch (IOException e) { return null; } return dis; } /** * Sets the number of bytes by which to extend the stream. This only applies * to InputStream API methods. */ public void setExtend(int extend) { ext = extend; } /** Seeks to the given offset within the stream. */ public void seek(long pos) throws IOException { afp = pos; } /** Alias for readByte(). */ public int read() throws IOException { int b = (int) readByte(); if (b == -1 && (afp >= length()) && ext > 0) return 0; return b; } /** Gets the number of bytes in the file. */ public long length() throws IOException { if (Boolean.FALSE.equals(fileCache.get(this))) reopen(); return length; } /** Gets the current (absolute) file pointer. */ public long getFilePointer() { return afp; } /** Closes the streams. */ public void close() throws IOException { if (raf != null) raf.close(); raf = null; if (dis != null) dis.close(); dis = null; buf = null; if (Boolean.TRUE.equals(fileCache.get(this))) { fileCache.put(this, Boolean.FALSE); openFiles--; } } /** Sets the endianness of the stream. */ public void order(boolean little) { littleEndian = little; } /** Gets the endianness of the stream. */ public boolean isLittleEndian() { return littleEndian; } // -- DataInput API methods -- /** Read an input byte and return true if the byte is nonzero. */ public boolean readBoolean() throws IOException { return (readByte() != 0); } /** Read one byte and return it. */ public byte readByte() throws IOException { int status = checkEfficiency(1); long oldAFP = afp; if (afp < length - 1) afp++; if (status == DIS) { byte b = dis.readByte(); fp++; return b; } else if (status == ARRAY) { return buf[(int) oldAFP]; } else { byte b = raf.readByte(); return b; } } /** Read an input char. */ public char readChar() throws IOException { return (char) readByte(); } /** Read eight bytes and return a double value. */ public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } /** Read four bytes and return a float value. */ public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } /** Read four input bytes and return an int value. */ public int readInt() throws IOException { return DataTools.read4SignedBytes(this, littleEndian); } /** Read the next line of text from the input stream. */ public String readLine() throws IOException { StringBuffer sb = new StringBuffer(); char c = readChar(); while (c != '\n') { sb = sb.append(c); c = readChar(); } return sb.toString(); } /** Read a string of arbitrary length, terminated by a null char. */ public String readCString() throws IOException { StringBuffer sb = new StringBuffer(); char achar = readChar(); while (achar != 0) { sb = sb.append(achar); achar = readChar(); } return sb.toString(); } /** Read a string of length n. */ public String readString(int n) throws IOException { byte[] b = new byte[n]; read(b); return new String(b); } /** Read eight input bytes and return a long value. */ public long readLong() throws IOException { return DataTools.read8SignedBytes(this, littleEndian); } /** Read two input bytes and return a short value. */ public short readShort() throws IOException { return DataTools.read2SignedBytes(this, littleEndian); } /** Read an input byte and zero extend it appropriately. */ public int readUnsignedByte() throws IOException { return DataTools.readUnsignedByte(this); } /** Read two bytes and return an int in the range 0 through 65535. */ public int readUnsignedShort() throws IOException { return DataTools.read2UnsignedBytes(this, littleEndian); } /** Read a string that has been encoded using a modified UTF-8 format. */ public String readUTF() throws IOException { return null; // not implemented yet...we don't really need this } /** Skip n bytes within the stream. */ public int skipBytes(int n) throws IOException { afp += n; return n; } /** Read bytes from the stream into the given array. */ public int read(byte[] array) throws IOException { int status = checkEfficiency(array.length); int n = 0; if (status == DIS) { return read(array, 0, array.length); } else if (status == ARRAY) { n = array.length; if ((buf.length - afp) < array.length) { n = buf.length - (int) afp; } System.arraycopy(buf, (int) afp, array, 0, n); } else n = raf.read(array); afp += n; if (status == DIS) fp += n; if (n < array.length && ext > 0) { while (n < array.length && ext > 0) { n++; ext--; } } return n; } /** * Read n bytes from the stream into the given array at the specified offset. */ public int read(byte[] array, int offset, int n) throws IOException { int toRead = n; int status = checkEfficiency(n); if (status == DIS) { int p = dis.read(array, offset, n); if (p == -1) return -1; if ((p >= 0) && ((fp + p) < length)) { int k = p; while ((k >= 0) && (p < n) && ((afp + p) <= length) && ((offset + p) < array.length)) { k = dis.read(array, offset + p, n - p); if (k >= 0) p += k; } } n = p; } else if (status == ARRAY) { if ((buf.length - afp) < n) n = buf.length - (int) afp; System.arraycopy(buf, (int) afp, array, offset, n); } else { n = raf.read(array, offset, n); } afp += n; if (status == DIS) fp += n; if (n < toRead && ext > 0) { while (n < array.length && ext > 0) { n++; ext--; } } return n; } /** Read bytes from the stream into the given array. */ public void readFully(byte[] array) throws IOException { readFully(array, 0, array.length); } /** * Read n bytes from the stream into the given array at the specified offset. */ public void readFully(byte[] array, int offset, int n) throws IOException { int status = checkEfficiency(n); if (status == DIS) { dis.readFully(array, offset, n); } else if (status == ARRAY) { System.arraycopy(buf, (int) afp, array, offset, n); } else { raf.readFully(array, offset, n); } afp += n; if (status == DIS) fp += n; } // -- InputStream API methods -- public int available() throws IOException { if (Boolean.FALSE.equals(fileCache.get(this))) reopen(); int available = dis != null ? dis.available() + ext : (int) (length() - getFilePointer()); if (available < 0) available = Integer.MAX_VALUE; return available; } public void mark(int readLimit) { try { if (Boolean.FALSE.equals(fileCache.get(this))) reopen(); } catch (IOException e) { } if (!compressed) dis.mark(readLimit); } public boolean markSupported() { return !compressed; } public void reset() throws IOException { if (Boolean.FALSE.equals(fileCache.get(this))) reopen(); dis.reset(); fp = length() - dis.available(); } // -- Helper methods - I/O -- /** * Determine whether it is more efficient to use the DataInputStream or * RandomAccessFile for reading (based on the current file pointers). * Returns 0 if we should use the DataInputStream, 1 if we should use the * RandomAccessFile, and 2 for a direct array access. */ protected int checkEfficiency(int toRead) throws IOException { if (Boolean.FALSE.equals(fileCache.get(this))) reopen(); if (compressed) { // can only read from the input stream if (afp < fp) { dis.close(); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD); String path = Location.getMappedId(file).toLowerCase(); if (path.endsWith(".gz")) { dis = new DataInputStream(new GZIPInputStream(bis)); } else if (path.endsWith(".zip")) { ZipFile zf = new ZipFile(Location.getMappedId(file)); InputStream zip = new BufferedInputStream(zf.getInputStream( (ZipEntry) zf.entries().nextElement()), MAX_OVERHEAD); dis = new DataInputStream(zip); } else if (path.endsWith(".bz2")) { bis.skip(2); dis = new DataInputStream(new CBZip2InputStream(bis)); } fp = 0; } - while (fp < afp) { - fp += dis.skipBytes((int) (afp - fp)); + int skip = 0; + do { + skip = dis.skipBytes((int) (afp - fp)); + fp += skip; } + while (fp < afp && skip > 0); return DIS; } if (dis != null && raf != null && afp + toRead < MAX_OVERHEAD && afp + toRead < length() && afp + toRead < buf.length) { // this is a really special case that allows us to read directly from // an array when working with the first MAX_OVERHEAD bytes of the file // ** also note that it doesn't change the stream return ARRAY; } if (dis != null) { if (fp < length()) { while (fp > (length() - dis.available())) { while (fp - length() + dis.available() > Integer.MAX_VALUE) { dis.skipBytes(Integer.MAX_VALUE); } dis.skipBytes((int) (fp - (length() - dis.available()))); } } else { fp = afp; BufferedInputStream bis = new BufferedInputStream( new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD); dis = new DataInputStream(bis); while (fp > (length() - dis.available())) { while (fp - length() + dis.available() > Integer.MAX_VALUE) { dis.skipBytes(Integer.MAX_VALUE); } dis.skipBytes((int) (fp - length() + dis.available())); } } } if (afp >= fp && dis != null) { while (fp < afp) { while (afp - fp > Integer.MAX_VALUE) { fp += dis.skipBytes(Integer.MAX_VALUE); } int skip = dis.skipBytes((int) (afp - fp)); if (skip == 0) break; fp += skip; } if (fp >= nextMark) { dis.mark(MAX_OVERHEAD); } nextMark = fp + MAX_OVERHEAD; mark = fp; return DIS; } else { if (dis != null && afp >= mark && fp < mark) { boolean valid = true; try { dis.reset(); } catch (IOException io) { valid = false; } if (valid) { dis.mark(MAX_OVERHEAD); fp = length() - dis.available(); while (fp < afp) { while (afp - fp > Integer.MAX_VALUE) { fp += dis.skipBytes(Integer.MAX_VALUE); } int skip = dis.skipBytes((int) (afp - fp)); if (skip == 0) break; fp += skip; } if (fp >= nextMark) { dis.mark(MAX_OVERHEAD); } nextMark = fp + MAX_OVERHEAD; mark = fp; return DIS; } else { raf.seek(afp); return RAF; } } else { // we don't want this to happen very often raf.seek(afp); return RAF; } } } // -- Helper methods - cache management -- /** Re-open a file that has been closed */ private void reopen() throws IOException { File f = new File(Location.getMappedId(file)); f = f.getAbsoluteFile(); if (Location.getMappedFile(file) != null) { raf = Location.getMappedFile(file); length = raf.length(); } else if (f.exists()) { raf = new RAFile(f, "r"); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD); String path = f.getPath().toLowerCase(); if (path.endsWith(".gz")) { dis = new DataInputStream(new GZIPInputStream(bis)); compressed = true; } else if (path.endsWith(".zip")) { ZipFile zf = new ZipFile(Location.getMappedId(file)); InputStream zip = new BufferedInputStream(zf.getInputStream( (ZipEntry) zf.entries().nextElement()), MAX_OVERHEAD); dis = new DataInputStream(zip); compressed = true; } else if (path.endsWith(".bz2")) { bis.skip(2); dis = new DataInputStream(new CBZip2InputStream(bis)); compressed = true; } else dis = new DataInputStream(bis); if (!compressed) { length = raf.length(); buf = new byte[(int) (length < MAX_OVERHEAD ? length : MAX_OVERHEAD)]; raf.readFully(buf); raf.seek(0); } } else if (file.startsWith("http")) { raf = new RAUrl(Location.getMappedId(file), "r"); length = raf.length(); } fileCache.put(this, Boolean.TRUE); openFiles++; if (openFiles > MAX_FILES) cleanCache(); } /** If we have too many open files, close most of them. */ private void cleanCache() { int toClose = MAX_FILES - 10; RandomAccessStream[] files = (RandomAccessStream[]) fileCache.keySet().toArray(new RandomAccessStream[0]); int closed = 0; int ndx = 0; while (closed < toClose) { if (!this.equals(files[ndx]) && !fileCache.get(files[ndx]).equals(Boolean.FALSE) && files[ndx].file != null) { try { files[ndx].close(); } catch (IOException exc) { LogTools.trace(exc); } closed++; } ndx++; } } }
false
true
protected int checkEfficiency(int toRead) throws IOException { if (Boolean.FALSE.equals(fileCache.get(this))) reopen(); if (compressed) { // can only read from the input stream if (afp < fp) { dis.close(); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD); String path = Location.getMappedId(file).toLowerCase(); if (path.endsWith(".gz")) { dis = new DataInputStream(new GZIPInputStream(bis)); } else if (path.endsWith(".zip")) { ZipFile zf = new ZipFile(Location.getMappedId(file)); InputStream zip = new BufferedInputStream(zf.getInputStream( (ZipEntry) zf.entries().nextElement()), MAX_OVERHEAD); dis = new DataInputStream(zip); } else if (path.endsWith(".bz2")) { bis.skip(2); dis = new DataInputStream(new CBZip2InputStream(bis)); } fp = 0; } while (fp < afp) { fp += dis.skipBytes((int) (afp - fp)); } return DIS; } if (dis != null && raf != null && afp + toRead < MAX_OVERHEAD && afp + toRead < length() && afp + toRead < buf.length) { // this is a really special case that allows us to read directly from // an array when working with the first MAX_OVERHEAD bytes of the file // ** also note that it doesn't change the stream return ARRAY; } if (dis != null) { if (fp < length()) { while (fp > (length() - dis.available())) { while (fp - length() + dis.available() > Integer.MAX_VALUE) { dis.skipBytes(Integer.MAX_VALUE); } dis.skipBytes((int) (fp - (length() - dis.available()))); } } else { fp = afp; BufferedInputStream bis = new BufferedInputStream( new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD); dis = new DataInputStream(bis); while (fp > (length() - dis.available())) { while (fp - length() + dis.available() > Integer.MAX_VALUE) { dis.skipBytes(Integer.MAX_VALUE); } dis.skipBytes((int) (fp - length() + dis.available())); } } } if (afp >= fp && dis != null) { while (fp < afp) { while (afp - fp > Integer.MAX_VALUE) { fp += dis.skipBytes(Integer.MAX_VALUE); } int skip = dis.skipBytes((int) (afp - fp)); if (skip == 0) break; fp += skip; } if (fp >= nextMark) { dis.mark(MAX_OVERHEAD); } nextMark = fp + MAX_OVERHEAD; mark = fp; return DIS; } else { if (dis != null && afp >= mark && fp < mark) { boolean valid = true; try { dis.reset(); } catch (IOException io) { valid = false; } if (valid) { dis.mark(MAX_OVERHEAD); fp = length() - dis.available(); while (fp < afp) { while (afp - fp > Integer.MAX_VALUE) { fp += dis.skipBytes(Integer.MAX_VALUE); } int skip = dis.skipBytes((int) (afp - fp)); if (skip == 0) break; fp += skip; } if (fp >= nextMark) { dis.mark(MAX_OVERHEAD); } nextMark = fp + MAX_OVERHEAD; mark = fp; return DIS; } else { raf.seek(afp); return RAF; } } else { // we don't want this to happen very often raf.seek(afp); return RAF; } } }
protected int checkEfficiency(int toRead) throws IOException { if (Boolean.FALSE.equals(fileCache.get(this))) reopen(); if (compressed) { // can only read from the input stream if (afp < fp) { dis.close(); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD); String path = Location.getMappedId(file).toLowerCase(); if (path.endsWith(".gz")) { dis = new DataInputStream(new GZIPInputStream(bis)); } else if (path.endsWith(".zip")) { ZipFile zf = new ZipFile(Location.getMappedId(file)); InputStream zip = new BufferedInputStream(zf.getInputStream( (ZipEntry) zf.entries().nextElement()), MAX_OVERHEAD); dis = new DataInputStream(zip); } else if (path.endsWith(".bz2")) { bis.skip(2); dis = new DataInputStream(new CBZip2InputStream(bis)); } fp = 0; } int skip = 0; do { skip = dis.skipBytes((int) (afp - fp)); fp += skip; } while (fp < afp && skip > 0); return DIS; } if (dis != null && raf != null && afp + toRead < MAX_OVERHEAD && afp + toRead < length() && afp + toRead < buf.length) { // this is a really special case that allows us to read directly from // an array when working with the first MAX_OVERHEAD bytes of the file // ** also note that it doesn't change the stream return ARRAY; } if (dis != null) { if (fp < length()) { while (fp > (length() - dis.available())) { while (fp - length() + dis.available() > Integer.MAX_VALUE) { dis.skipBytes(Integer.MAX_VALUE); } dis.skipBytes((int) (fp - (length() - dis.available()))); } } else { fp = afp; BufferedInputStream bis = new BufferedInputStream( new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD); dis = new DataInputStream(bis); while (fp > (length() - dis.available())) { while (fp - length() + dis.available() > Integer.MAX_VALUE) { dis.skipBytes(Integer.MAX_VALUE); } dis.skipBytes((int) (fp - length() + dis.available())); } } } if (afp >= fp && dis != null) { while (fp < afp) { while (afp - fp > Integer.MAX_VALUE) { fp += dis.skipBytes(Integer.MAX_VALUE); } int skip = dis.skipBytes((int) (afp - fp)); if (skip == 0) break; fp += skip; } if (fp >= nextMark) { dis.mark(MAX_OVERHEAD); } nextMark = fp + MAX_OVERHEAD; mark = fp; return DIS; } else { if (dis != null && afp >= mark && fp < mark) { boolean valid = true; try { dis.reset(); } catch (IOException io) { valid = false; } if (valid) { dis.mark(MAX_OVERHEAD); fp = length() - dis.available(); while (fp < afp) { while (afp - fp > Integer.MAX_VALUE) { fp += dis.skipBytes(Integer.MAX_VALUE); } int skip = dis.skipBytes((int) (afp - fp)); if (skip == 0) break; fp += skip; } if (fp >= nextMark) { dis.mark(MAX_OVERHEAD); } nextMark = fp + MAX_OVERHEAD; mark = fp; return DIS; } else { raf.seek(afp); return RAF; } } else { // we don't want this to happen very often raf.seek(afp); return RAF; } } }
diff --git a/jnalib/src/com/sun/jna/Pointer.java b/jnalib/src/com/sun/jna/Pointer.java index 4f9bb210..deb7cc21 100644 --- a/jnalib/src/com/sun/jna/Pointer.java +++ b/jnalib/src/com/sun/jna/Pointer.java @@ -1,781 +1,781 @@ /* This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * <p/> * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package com.sun.jna; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * An abstraction for a native pointer data type. A Pointer instance * represents, on the Java side, a native pointer. The native pointer could * be any <em>type</em> of native pointer. Methods such as <code>write</code>, * <code>read</code>, <code>getXXX</code>, and <code>setXXX</code>, provide * means to access memory underlying the native pointer.<p> * The constructors are intentionally package-private, since it's not generally * a good idea to be creating C pointers de novo. * * @author Sheng Liang, originator * @author Todd Fast, suitability modifications * @author Timothy Wall, robust library loading * @see Function */ public class Pointer { /** Size of a native pointer, in bytes. */ public static final int SIZE; static { // Force load of native library if ((SIZE = Native.POINTER_SIZE) == 0) { throw new Error("Native library not initialized"); } } /** Convenience constant, same as <code>null</code>. */ public static final Pointer NULL = null; /** Convenience constant, equivalent to <code>(void*)-1</code>. */ public static final Pointer createConstant(long peer) { return new Opaque(peer); } /** Pointer value of the real native pointer. Use long to be 64-bit safe. */ long peer; /** Derived class must assign peer pointer value. */ Pointer() { } /** Create from native pointer. */ Pointer(long peer) { this.peer = peer; } /** Provide a view of this pointer with a different peer base. */ public Pointer share(long offset, long sz) { return new Pointer(peer + offset); } /** Zero memory for the given number of bytes. */ void clear(long size) { setMemory(0, size, (byte)0); } /** * Compares this <code>Pointer</code> to the specified object. * * @param o * A <code>Pointer</code> instance * @return True if the other object is a <code>Pointer</code>, * and the C pointers being pointed to by these objects are also * equal. Returns false otherwise. */ public boolean equals(Object o) { if (o == null) return peer == 0; return (o instanceof Pointer) && ((Pointer)o).peer == peer; } /** * Returns a hashcode for the native pointer represented by this * <code>Pointer</code> object * * @return A hash code value for the represented native pointer */ public int hashCode() { return (int)((peer >>> 32) + (peer & 0xFFFFFFFF)); } ////////////////////////////////////////////////////////////////////////// // Raw read methods ////////////////////////////////////////////////////////////////////////// /** Returns the offset of the given value in memory from the given offset, * or -1 if the value is not found. */ public native long indexOf(long bOff, byte value); /** * Indirect the native pointer, copying <em>from</em> memory pointed to by * native pointer, into the specified array. * * @param bOff byte offset from pointer into which data is copied * @param buf <code>byte</code> array into which data is copied * @param index array index from which to start copying * @param length number of elements from native pointer that must be copied */ public native void read(long bOff, byte[] buf, int index, int length); /** * Indirect the native pointer, copying <em>from</em> memory pointed to by * native pointer, into the specified array. * * @param bOff byte offset from pointer from which data is copied * @param buf <code>short</code> array into which data is copied * @param index array index to which data is copied * @param length number of elements from native pointer that must be copied */ public native void read(long bOff, short[] buf, int index, int length); /** * Indirect the native pointer, copying <em>from</em> memory pointed to by * native pointer, into the specified array. * * @param bOff byte offset from pointer from which data is copied * @param buf <code>char</code> array into which data is copied * @param index array index to which data is copied * @param length number of elements from native pointer that must be copied */ public native void read(long bOff, char[] buf, int index, int length); /** * Indirect the native pointer, copying <em>from</em> memory pointed to by * native pointer, into the specified array. * * @param bOff byte offset from pointer from which data is copied * @param buf <code>int</code> array into which data is copied * @param index array index to which data is copied * @param length number of elements from native pointer that must be copied */ public native void read(long bOff, int[] buf, int index, int length); /** * Indirect the native pointer, copying <em>from</em> memory pointed to by * native pointer, into the specified array. * * @param bOff byte offset from pointer from which data is copied * @param buf <code>long</code> array into which data is copied * @param index array index to which data is copied * @param length number of elements from native pointer that must be copied */ public native void read(long bOff, long[] buf, int index, int length); /** * Indirect the native pointer, copying <em>from</em> memory pointed to by * native pointer, into the specified array. * * @param bOff byte offset from pointer from which data is copied * @param buf <code>float</code> array into which data is copied * @param index array index to which data is copied * @param length number of elements from native pointer that must be copied */ public native void read(long bOff, float[] buf, int index, int length); /** * Indirect the native pointer, copying <em>from</em> memory pointed to by * native pointer, into the specified array. * * @param bOff byte offset from pointer from which data is copied * @param buf <code>double</code> array into which data is copied * @param index array index to which data is copied * @param length number of elements from native pointer that must be copied */ public native void read(long bOff, double[] buf, int index, int length); ////////////////////////////////////////////////////////////////////////// // Raw write methods ////////////////////////////////////////////////////////////////////////// /** * Indirect the native pointer, copying <em>into</em> memory pointed to by * native pointer, from the specified array. * * @param bOff byte offset from pointer into which data is copied * @param buf <code>byte</code> array from which to copy * @param index array index from which to start copying * @param length number of elements from <code>buf</code> that must be * copied */ public native void write(long bOff, byte[] buf, int index, int length); /** * Indirect the native pointer, copying <em>into</em> memory pointed to by * native pointer, from the specified array. * * @param bOff byte offset from pointer into which data is copied * @param buf <code>short</code> array from which to copy * @param index array index from which to start copying * @param length number of elements from <code>buf</code> that must be * copied */ public native void write(long bOff, short[] buf, int index, int length); /** * Indirect the native pointer, copying <em>into</em> memory pointed to by * native pointer, from the specified array. * * @param bOff byte offset from pointer into which data is copied * @param buf <code>char</code> array from which to copy * @param index array index from which to start copying * @param length number of elements from <code>buf</code> that must be * copied */ public native void write(long bOff, char[] buf, int index, int length); /** * Indirect the native pointer, copying <em>into</em> memory pointed to by * native pointer, from the specified array. * * @param bOff byte offset from pointer into which data is copied * @param buf <code>int</code> array from which to copy * @param index array index from which to start copying * @param length number of elements from <code>buf</code> that must be * copied */ public native void write(long bOff, int[] buf, int index, int length); /** * Indirect the native pointer, copying <em>into</em> memory pointed to by * native pointer, from the specified array. * * @param bOff byte offset from pointer into which data is copied * @param buf <code>long</code> array from which to copy * @param index array index from which to start copying * @param length number of elements from <code>buf</code> that must be * copied */ public native void write(long bOff, long[] buf, int index, int length); /** * Indirect the native pointer, copying <em>into</em> memory pointed to by * native pointer, from the specified array. * * @param bOff byte offset from pointer into which data is copied * @param buf <code>float</code> array from which to copy * @param index array index from which to start copying * @param length number of elements from <code>buf</code> that must be * copied */ public native void write(long bOff, float[] buf, int index, int length); /** * Indirect the native pointer, copying <em>into</em> memory pointed to by * native pointer, from the specified array. * * @param bOff byte offset from pointer into which data is copied * @param buf <code>double</code> array from which to copy * @param index array index from which to start copying * @param length number of elements from <code>buf</code> that must be * copied */ public native void write(long bOff, double[] buf, int index, int length); /** Write the given array of Pointer to native memory. * @param bOff byte offset from pointer into which data is copied * @param buf <code>Pointer</code> array from which to copy * @param index array index from which to start copying * @param length number of elements from <code>buf</code> that must be * copied */ public void write(long bOff, Pointer[] buf, int index, int length) { for (int i=0;i < length;i++) { setPointer(bOff + i * Pointer.SIZE, buf[index + i]); } } ////////////////////////////////////////////////////////////////////////// // Java type read methods ////////////////////////////////////////////////////////////////////////// /** * Indirect the native pointer as a pointer to <code>byte</code>. This is * equivalent to the expression * <code>*((jbyte *)((char *)Pointer + offset))</code>. * * @param offset offset from pointer to perform the indirection * @return the <code>byte</code> value being pointed to */ public native byte getByte(long offset); /** * Indirect the native pointer as a pointer to <code>wchar_t</code>. This * is equivalent to the expression * <code>*((wchar_t*)((char *)Pointer + offset))</code>. * * @param offset offset from pointer to perform the indirection * @return the <code>wchar_t</code> value being pointed to */ public native char getChar(long offset); /** * Indirect the native pointer as a pointer to <code>short</code>. This is * equivalent to the expression * <code>*((jshort *)((char *)Pointer + offset))</code>. * * @param offset byte offset from pointer to perform the indirection * @return the <code>short</code> value being pointed to */ public native short getShort(long offset); /** * Indirect the native pointer as a pointer to <code>int</code>. This is * equivalent to the expression * <code>*((jint *)((char *)Pointer + offset))</code>. * * @param offset byte offset from pointer to perform the indirection * @return the <code>int</code> value being pointed to */ public native int getInt(long offset); /** * Indirect the native pointer as a pointer to <code>long</code>. This is * equivalent to the expression * <code>*((jlong *)((char *)Pointer + offset))</code>. * * @param offset byte offset from pointer to perform the indirection * @return the <code>long</code> value being pointed to */ public native long getLong(long offset); /** * Indirect the native pointer as a pointer to <code>long</code>. This is * equivalent to the expression * <code>*((long *)((char *)Pointer + offset))</code>. * * @param offset byte offset from pointer to perform the indirection * @return the <code>long</code> value being pointed to */ public NativeLong getNativeLong(long offset) { return new NativeLong(NativeLong.SIZE == 8 ? getLong(offset) : getInt(offset)); } /** * Indirect the native pointer as a pointer to <code>float</code>. This is * equivalent to the expression * <code>*((jfloat *)((char *)Pointer + offset))</code>. * * @param offset byte offset from pointer to perform the indirection * @return the <code>float</code> value being pointed to */ public native float getFloat(long offset); /** * Indirect the native pointer as a pointer to <code>double</code>. This * is equivalent to the expression * <code>*((jdouble *)((char *)Pointer + offset))</code>. * * @param offset byte offset from pointer to perform the indirection * @return the <code>double</code> value being pointed to */ public native double getDouble(long offset); /** * Indirect the native pointer as a pointer to pointer. This is equivalent * to the expression * <code>*((void **)((char *)Pointer + offset))</code>. * * @param offset byte offset from pointer to perform the indirection * @return a {@link Pointer} equivalent of the pointer value * being pointed to, or <code>null</code> if the pointer value is * <code>NULL</code>; */ public native Pointer getPointer(long offset); /** * Get a ByteBuffer mapped to the memory pointed to by the pointer, * ensuring the buffer uses native byte order. * * @param offset byte offset from pointer to start the buffer * @param length Length of ByteBuffer * @return a direct ByteBuffer that accesses the memory being pointed to, */ public ByteBuffer getByteBuffer(long offset, long length) { return getDirectByteBuffer(offset, length).order(ByteOrder.nativeOrder()); } /** * Get a direct ByteBuffer mapped to the memory pointed to by the pointer. * * @param offset byte offset from pointer to start the buffer * @param length Length of ByteBuffer * @return a direct ByteBuffer that accesses the memory being pointed to, */ private native ByteBuffer getDirectByteBuffer(long offset, long length); /** * Copy native memory to a Java String. If <code>wide</code> is true, * access the memory as an array of <code>wchar_t</code>, otherwise * as an array of <code>char</code>, using the default platform encoding. * * @param offset byte offset from pointer to obtain the native string * @param wide whether to convert from a wide or standard C string * @return the <code>String</code> value being pointed to */ public native String getString(long offset, boolean wide); /** * Copy native memory to a Java String. If the system property * <code>jna.encoding</code> is set, uses it as the native charset * when decoding the value, otherwise falls back to the default platform * encoding. * * @param offset byte offset from pointer to obtain the native string * @return the <code>String</code> value being pointed to */ public String getString(long offset) { String encoding = System.getProperty("jna.encoding"); if (encoding != null) { long len = indexOf(offset, (byte)0); if (len != -1) { if (len > Integer.MAX_VALUE) { - throw new OutOfMemoryError("String exceeds maximum length"); + throw new OutOfMemoryError("String exceeds maximum length: " + len); } byte[] data = getByteArray(offset, (int)len); try { return new String(data, encoding); } catch(UnsupportedEncodingException e) { } } } return getString(offset, false); } public byte[] getByteArray(long offset, int arraySize) { byte[] buf = new byte[arraySize]; read(offset, buf, 0, arraySize); return buf; } public char[] getCharArray(long offset, int arraySize) { char[] buf = new char[arraySize]; read(offset, buf, 0, arraySize); return buf; } public short[] getShortArray(long offset, int arraySize) { short[] buf = new short[arraySize]; read(offset, buf, 0, arraySize); return buf; } public int[] getIntArray(long offset, int arraySize) { int[] buf = new int[arraySize]; read(offset, buf, 0, arraySize); return buf; } public long[] getLongArray(long offset, int arraySize) { long[] buf = new long[arraySize]; read(offset, buf, 0, arraySize); return buf; } public float[] getFloatArray(long offset, int arraySize) { float[] buf = new float[arraySize]; read(offset, buf, 0, arraySize); return buf; } public double[] getDoubleArray(long offset, int arraySize) { double[] buf = new double[arraySize]; read(offset, buf, 0, arraySize); return buf; } public Pointer[] getPointerArray(long offset, int arraySize) { Pointer[] buf = new Pointer[arraySize]; for (int i=0;i < buf.length;i++) { buf[i] = getPointer(offset + i*SIZE); } return buf; } ////////////////////////////////////////////////////////////////////////// // Java type write methods ////////////////////////////////////////////////////////////////////////// /** Write <code>value</code> to the requested bank of memory. * @param offset byte offset from pointer to start * @param length number of bytes to write * @param value value to be written */ public native void setMemory(long offset, long length, byte value); /** * Set <code>value</code> at location being pointed to. This is equivalent * to the expression * <code>*((jbyte *)((char *)Pointer + offset)) = value</code>. * * @param offset byte offset from pointer at which <code>value</code> * must be set * @param value <code>byte</code> value to set */ public native void setByte(long offset, byte value); /** * Set <code>value</code> at location being pointed to. This is equivalent * to the expression * <code>*((jshort *)((char *)Pointer + offset)) = value</code>. * * @param offset byte offset from pointer at which <code>value</code> * must be set * @param value <code>short</code> value to set */ public native void setShort(long offset, short value); /** * Set <code>value</code> at location being pointed to. This is equivalent * to the expression * <code>*((wchar_t *)((char *)Pointer + offset)) = value</code>. * * @param offset byte offset from pointer at which <code>value</code> * must be set * @param value <code>char</code> value to set */ public native void setChar(long offset, char value); /** * Set <code>value</code> at location being pointed to. This is equivalent * to the expression * <code>*((jint *)((char *)Pointer + offset)) = value</code>. * * @param offset byte offset from pointer at which <code>value</code> * must be set * @param value <code>int</code> value to set */ public native void setInt(long offset, int value); /** * Set <code>value</code> at location being pointed to. This is equivalent * to the expression * <code>*((jlong *)((char *)Pointer + offset)) = value</code>. * * @param offset byte offset from pointer at which <code>value</code> * must be set * @param value <code>long</code> value to set */ public native void setLong(long offset, long value); /** * Set <code>value</code> at location being pointed to. This is equivalent * to the expression * <code>*((long *)((char *)Pointer + offset)) = value</code>. * * @param offset byte offset from pointer at which <code>value</code> * must be set * @param value <code>long</code> value to set */ public void setNativeLong(long offset, NativeLong value) { if (NativeLong.SIZE == 8) { setLong(offset, value.longValue()); } else { setInt(offset, value.intValue()); } } /** * Set <code>value</code> at location being pointed to. This is equivalent * to the expression * <code>*((jfloat *)((char *)Pointer + offset)) = value</code>. * * @param offset byte offset from pointer at which <code>value</code> * must be set * @param value <code>float</code> value to set */ public native void setFloat(long offset, float value); /** * Set <code>value</code> at location being pointed to. This is equivalent * to the expression * <code>*((jdouble *)((char *)Pointer + offset)) = value</code>. * * @param offset byte offset from pointer at which <code>value</code> * must be set * @param value <code>double</code> value to set */ public native void setDouble(long offset, double value); /** * Set <code>value</code> at location being pointed to. This is equivalent * to the expression * <code>*((void **)((char *)Pointer + offset)) = value</code>. * * @param offset byte offset from pointer at which <code>value</code> * must be set * @param value <code>Pointer</code> holding the actual pointer value to * set, which may be <code>null</code> to indicate a <code>NULL</code> * pointer. */ public native void setPointer(long offset, Pointer value); /** * Copy string <code>value</code> to the location being pointed to. Copy * each element in <code>value</code>, converted to native encoding, at an * <code>offset</code>from the location pointed to by this pointer. * * @param offset byte offset from pointer at which characters in * <code>value</code> must be set * @param value <code>java.lang.String</code> value to set * @param wide whether to write the native string as an array of * <code>wchar_t</code>. If false, writes as a NUL-terminated array of * <code>char</code> using the default platform encoding. */ public native void setString(long offset, String value, boolean wide); /** * Copy string <code>value</code> to the location being pointed to. Copy * each element in <code>value</code>, converted to native encoding, at an * <code>offset</code>from the location pointed to by this pointer. * Uses the value of the system property <code>jna.encoding</code>, if set, * to determine the appropriate native charset in which to encode the value. * If the property is not set, uses the default platform encoding. * * @param offset byte offset from pointer at which characters in * <code>value</code> must be set * @param value <code>java.lang.String</code> value to set */ public void setString(long offset, String value) { byte[] data = Native.getBytes(value); write(offset, data, 0, data.length); setByte(offset + data.length, (byte)0); } public String toString() { return "native@0x" + Long.toHexString(peer); } /** Pointer which disallows all read/write access. */ private static class Opaque extends Pointer { private Opaque(long peer) { super(peer); } private String MSG = "This pointer is opaque: " + this; public long indexOf(long offset, byte value) { throw new UnsupportedOperationException(MSG); } public void read(long bOff, byte[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void read(long bOff, char[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void read(long bOff, short[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void read(long bOff, int[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void read(long bOff, long[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void read(long bOff, float[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void read(long bOff, double[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void write(long bOff, byte[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void write(long bOff, char[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void write(long bOff, short[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void write(long bOff, int[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void write(long bOff, long[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void write(long bOff, float[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public void write(long bOff, double[] buf, int index, int length) { throw new UnsupportedOperationException(MSG); } public byte getByte(long bOff) { throw new UnsupportedOperationException(MSG); } public char getChar(long bOff) { throw new UnsupportedOperationException(MSG); } public short getShort(long bOff) { throw new UnsupportedOperationException(MSG); } public int getInt(long bOff) { throw new UnsupportedOperationException(MSG); } public long getLong(long bOff) { throw new UnsupportedOperationException(MSG); } public float getFloat(long bOff) { throw new UnsupportedOperationException(MSG); } public double getDouble(long bOff) { throw new UnsupportedOperationException(MSG); } public Pointer getPointer(long bOff) { throw new UnsupportedOperationException(MSG); } public String getString(long bOff, boolean wide) { throw new UnsupportedOperationException(MSG); } public void setByte(long bOff, byte value) { throw new UnsupportedOperationException(MSG); } public void setChar(long bOff, char value) { throw new UnsupportedOperationException(MSG); } public void setShort(long bOff, short value) { throw new UnsupportedOperationException(MSG); } public void setInt(long bOff, int value) { throw new UnsupportedOperationException(MSG); } public void setLong(long bOff, long value) { throw new UnsupportedOperationException(MSG); } public void setFloat(long bOff, float value) { throw new UnsupportedOperationException(MSG); } public void setDouble(long bOff, double value) { throw new UnsupportedOperationException(MSG); } public void setPointer(long offset, Pointer value) { throw new UnsupportedOperationException(MSG); } public void setString(long offset, String value, boolean wide) { throw new UnsupportedOperationException(MSG); } public String toString() { return "opaque@0x" + Long.toHexString(peer); } } }
true
true
public String getString(long offset) { String encoding = System.getProperty("jna.encoding"); if (encoding != null) { long len = indexOf(offset, (byte)0); if (len != -1) { if (len > Integer.MAX_VALUE) { throw new OutOfMemoryError("String exceeds maximum length"); } byte[] data = getByteArray(offset, (int)len); try { return new String(data, encoding); } catch(UnsupportedEncodingException e) { } } } return getString(offset, false); }
public String getString(long offset) { String encoding = System.getProperty("jna.encoding"); if (encoding != null) { long len = indexOf(offset, (byte)0); if (len != -1) { if (len > Integer.MAX_VALUE) { throw new OutOfMemoryError("String exceeds maximum length: " + len); } byte[] data = getByteArray(offset, (int)len); try { return new String(data, encoding); } catch(UnsupportedEncodingException e) { } } } return getString(offset, false); }
diff --git a/src/cgeo/geocaching/cgeoimages.java b/src/cgeo/geocaching/cgeoimages.java index 4e6b4938d..118730e9a 100644 --- a/src/cgeo/geocaching/cgeoimages.java +++ b/src/cgeo/geocaching/cgeoimages.java @@ -1,301 +1,299 @@ package cgeo.geocaching; import java.util.ArrayList; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.net.Uri; import android.app.Activity; import android.app.ProgressDialog; import android.util.Log; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.LinearLayout; import android.content.Intent; import android.content.res.Resources; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.view.ViewGroup.LayoutParams; public class cgeoimages extends Activity { public static final int LOG_IMAGE = 1; public static final int SPOILER_IMAGE = 2; private int img_type; private ArrayList<cgImage> images = new ArrayList<cgImage>(); private Resources res = null; private String geocode = null; private String title = null; private String url = null; private cgeoapplication app = null; private Activity activity = null; private cgSettings settings = null; private cgBase base = null; private cgWarning warning = null; private LayoutInflater inflater = null; private ProgressDialog progressDialog = null; private ProgressDialog waitDialog = null; private LinearLayout imagesView = null; private int offline = 0; private boolean save = true; private int count = 0; private int countDone = 0; private String load_process_string; private Handler loadImagesHandler = new Handler() { @Override public void handleMessage(Message msg) { try { if (images.isEmpty()) { if (waitDialog != null) { waitDialog.dismiss(); } switch (img_type) { case LOG_IMAGE: warning.showToast(res.getString(R.string.warn_load_log_image)); break; case SPOILER_IMAGE: warning.showToast(res.getString(R.string.warn_load_spoiler_image)); break; } finish(); return; } else { if (waitDialog != null) { waitDialog.dismiss(); } if (app.isOffline(geocode, null) == true) { offline = 1; } else { offline = 0; } count = images.size(); progressDialog = new ProgressDialog(activity); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage(load_process_string); progressDialog.setCancelable(true); progressDialog.setMax(count); progressDialog.show(); LinearLayout rowView = null; for (final cgImage img : images) { rowView = (LinearLayout) inflater.inflate(R.layout.cache_image_item, null); ((TextView) rowView.findViewById(R.id.title)).setText(Html.fromHtml(img.title)); if (img.description != null && img.description.length() > 0) { final TextView descView = (TextView) rowView.findViewById(R.id.description); descView.setText(Html.fromHtml(img.description), TextView.BufferType.SPANNABLE); descView.setVisibility(View.VISIBLE); } final Handler handler = new onLoadHandler(rowView, img); new Thread() { @Override public void run() { BitmapDrawable image = null; try { cgHtmlImg imgGetter = new cgHtmlImg(activity, settings, geocode, true, offline, false, save); image = imgGetter.getDrawable(img.url); Message message = handler.obtainMessage(0, image); handler.sendMessage(message); } catch (Exception e) { Log.e(cgSettings.tag, "cgeoimages.onCreate.onClick.run: " + e.toString()); } } }.start(); imagesView.addView(rowView); } } } catch (Exception e) { if (waitDialog != null) { waitDialog.dismiss(); } Log.e(cgSettings.tag, "cgeoimages.loadImagesHandler: " + e.toString()); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // init activity = this; res = this.getResources(); app = (cgeoapplication) this.getApplication(); settings = new cgSettings(this, getSharedPreferences(cgSettings.preferences, 0)); base = new cgBase(app, settings, getSharedPreferences(cgSettings.preferences, 0)); warning = new cgWarning(this); // set layout if (settings.skin == 1) { setTheme(R.style.light); } else { setTheme(R.style.dark); } setContentView(R.layout.spoilers); // get parameters Bundle extras = getIntent().getExtras(); // try to get data from extras if (extras != null) { geocode = extras.getString("geocode"); img_type = extras.getInt("type", 0); } // google analytics if (img_type == SPOILER_IMAGE) { base.setTitle(activity, res.getString(R.string.cache_spoiler_images_title)); - base.sendAnal(activity, "/spoilers"); } else if (img_type == LOG_IMAGE) { base.setTitle(activity, res.getString(R.string.cache_log_images_title)); - base.sendAnal(activity, "/logimg"); } if (geocode == null) { warning.showToast("Sorry, c:geo forgot for what cache you want to load spoiler images."); finish(); return; } switch (img_type) { case LOG_IMAGE: title = extras.getString("title"); url = extras.getString("url"); if ((title == null) || (url == null)) { warning.showToast("Sorry, c:geo forgot which logimage you wanted to load."); finish(); return; } break; } inflater = activity.getLayoutInflater(); if (imagesView == null) { imagesView = (LinearLayout) findViewById(R.id.spoiler_list); } switch (img_type) { case SPOILER_IMAGE: load_process_string = res.getString(R.string.cache_spoiler_images_loading); save = true; break; case LOG_IMAGE: load_process_string = res.getString(R.string.cache_log_images_loading); if (settings.storelogimages == true) { save = true; } else { save = false; } break; default: load_process_string = new String("Loading..."); } waitDialog = ProgressDialog.show(this, null, load_process_string, true); waitDialog.setCancelable(true); switch (img_type) { case LOG_IMAGE: cgImage logimage = new cgImage(); logimage.title = title; logimage.url = url; logimage.description = ""; images.add(logimage); try { loadImagesHandler.sendMessage(new Message()); } catch (Exception e) { Log.e(cgSettings.tag, "cgeoimages.loadImagesHandler.sendMessage: " + e.toString()); } break; case SPOILER_IMAGE: (new loadSpoilers()).start(); break; default: warning.showToast("Sorry, can't load unknown image type."); finish(); } } @Override public void onResume() { super.onResume(); settings.load(); } private class loadSpoilers extends Thread { @Override public void run() { try { images = app.loadSpoilers(geocode); loadImagesHandler.sendMessage(new Message()); } catch (Exception e) { Log.e(cgSettings.tag, "cgeospoilers.loadSpoilers.run: " + e.toString()); } } } private class onLoadHandler extends Handler { LinearLayout view = null; cgImage img = null; public onLoadHandler(LinearLayout view, cgImage image) { this.view = view; this.img = image; } @Override public void handleMessage(Message message) { BitmapDrawable image = (BitmapDrawable) message.obj; if (image != null) { ImageView image_view = null; image_view = (ImageView) inflater.inflate(R.layout.image_item, null); Rect bounds = image.getBounds(); image_view.setImageResource(R.drawable.image_not_loaded); image_view.setClickable(true); image_view.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(img.url))); } }); image_view.setImageDrawable((BitmapDrawable) message.obj); image_view.setScaleType(ImageView.ScaleType.CENTER_CROP); image_view.setLayoutParams(new LayoutParams(bounds.width(), bounds.height())); view.addView(image_view); } countDone++; progressDialog.setProgress(countDone); if (progressDialog.getProgress() >= count) { progressDialog.dismiss(); } } } public void goHome(View view) { base.goHome(activity); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // init activity = this; res = this.getResources(); app = (cgeoapplication) this.getApplication(); settings = new cgSettings(this, getSharedPreferences(cgSettings.preferences, 0)); base = new cgBase(app, settings, getSharedPreferences(cgSettings.preferences, 0)); warning = new cgWarning(this); // set layout if (settings.skin == 1) { setTheme(R.style.light); } else { setTheme(R.style.dark); } setContentView(R.layout.spoilers); // get parameters Bundle extras = getIntent().getExtras(); // try to get data from extras if (extras != null) { geocode = extras.getString("geocode"); img_type = extras.getInt("type", 0); } // google analytics if (img_type == SPOILER_IMAGE) { base.setTitle(activity, res.getString(R.string.cache_spoiler_images_title)); base.sendAnal(activity, "/spoilers"); } else if (img_type == LOG_IMAGE) { base.setTitle(activity, res.getString(R.string.cache_log_images_title)); base.sendAnal(activity, "/logimg"); } if (geocode == null) { warning.showToast("Sorry, c:geo forgot for what cache you want to load spoiler images."); finish(); return; } switch (img_type) { case LOG_IMAGE: title = extras.getString("title"); url = extras.getString("url"); if ((title == null) || (url == null)) { warning.showToast("Sorry, c:geo forgot which logimage you wanted to load."); finish(); return; } break; } inflater = activity.getLayoutInflater(); if (imagesView == null) { imagesView = (LinearLayout) findViewById(R.id.spoiler_list); } switch (img_type) { case SPOILER_IMAGE: load_process_string = res.getString(R.string.cache_spoiler_images_loading); save = true; break; case LOG_IMAGE: load_process_string = res.getString(R.string.cache_log_images_loading); if (settings.storelogimages == true) { save = true; } else { save = false; } break; default: load_process_string = new String("Loading..."); } waitDialog = ProgressDialog.show(this, null, load_process_string, true); waitDialog.setCancelable(true); switch (img_type) { case LOG_IMAGE: cgImage logimage = new cgImage(); logimage.title = title; logimage.url = url; logimage.description = ""; images.add(logimage); try { loadImagesHandler.sendMessage(new Message()); } catch (Exception e) { Log.e(cgSettings.tag, "cgeoimages.loadImagesHandler.sendMessage: " + e.toString()); } break; case SPOILER_IMAGE: (new loadSpoilers()).start(); break; default: warning.showToast("Sorry, can't load unknown image type."); finish(); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // init activity = this; res = this.getResources(); app = (cgeoapplication) this.getApplication(); settings = new cgSettings(this, getSharedPreferences(cgSettings.preferences, 0)); base = new cgBase(app, settings, getSharedPreferences(cgSettings.preferences, 0)); warning = new cgWarning(this); // set layout if (settings.skin == 1) { setTheme(R.style.light); } else { setTheme(R.style.dark); } setContentView(R.layout.spoilers); // get parameters Bundle extras = getIntent().getExtras(); // try to get data from extras if (extras != null) { geocode = extras.getString("geocode"); img_type = extras.getInt("type", 0); } // google analytics if (img_type == SPOILER_IMAGE) { base.setTitle(activity, res.getString(R.string.cache_spoiler_images_title)); } else if (img_type == LOG_IMAGE) { base.setTitle(activity, res.getString(R.string.cache_log_images_title)); } if (geocode == null) { warning.showToast("Sorry, c:geo forgot for what cache you want to load spoiler images."); finish(); return; } switch (img_type) { case LOG_IMAGE: title = extras.getString("title"); url = extras.getString("url"); if ((title == null) || (url == null)) { warning.showToast("Sorry, c:geo forgot which logimage you wanted to load."); finish(); return; } break; } inflater = activity.getLayoutInflater(); if (imagesView == null) { imagesView = (LinearLayout) findViewById(R.id.spoiler_list); } switch (img_type) { case SPOILER_IMAGE: load_process_string = res.getString(R.string.cache_spoiler_images_loading); save = true; break; case LOG_IMAGE: load_process_string = res.getString(R.string.cache_log_images_loading); if (settings.storelogimages == true) { save = true; } else { save = false; } break; default: load_process_string = new String("Loading..."); } waitDialog = ProgressDialog.show(this, null, load_process_string, true); waitDialog.setCancelable(true); switch (img_type) { case LOG_IMAGE: cgImage logimage = new cgImage(); logimage.title = title; logimage.url = url; logimage.description = ""; images.add(logimage); try { loadImagesHandler.sendMessage(new Message()); } catch (Exception e) { Log.e(cgSettings.tag, "cgeoimages.loadImagesHandler.sendMessage: " + e.toString()); } break; case SPOILER_IMAGE: (new loadSpoilers()).start(); break; default: warning.showToast("Sorry, can't load unknown image type."); finish(); } }
diff --git a/src/com/android/settings/wifi/AdvancedWifiSettings.java b/src/com/android/settings/wifi/AdvancedWifiSettings.java index 5d673c454..d8a408068 100644 --- a/src/com/android/settings/wifi/AdvancedWifiSettings.java +++ b/src/com/android/settings/wifi/AdvancedWifiSettings.java @@ -1,197 +1,203 @@ /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.wifi; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceScreen; import android.provider.Settings; import android.provider.Settings.Secure; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.android.settings.R; import com.android.settings.SettingsPreferenceFragment; import com.android.settings.Utils; public class AdvancedWifiSettings extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener { private static final String TAG = "AdvancedWifiSettings"; private static final String KEY_MAC_ADDRESS = "mac_address"; private static final String KEY_CURRENT_IP_ADDRESS = "current_ip_address"; private static final String KEY_FREQUENCY_BAND = "frequency_band"; private static final String KEY_NOTIFY_OPEN_NETWORKS = "notify_open_networks"; private static final String KEY_SLEEP_POLICY = "sleep_policy"; private static final String KEY_ENABLE_WIFI_WATCHDOG = "wifi_enable_watchdog_service"; private WifiManager mWifiManager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.wifi_advanced_settings); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); } @Override public void onResume() { super.onResume(); initPreferences(); refreshWifiInfo(); } private void initPreferences() { CheckBoxPreference notifyOpenNetworks = (CheckBoxPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS); notifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(), Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1); notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled()); - CheckBoxPreference watchdogEnabled = + boolean watchdogEnabled = Secure.getInt(getContentResolver(), + Secure.WIFI_WATCHDOG_ON, 1) != 0; + CheckBoxPreference watchdog = (CheckBoxPreference) findPreference(KEY_ENABLE_WIFI_WATCHDOG); - if (watchdogEnabled != null) { - watchdogEnabled.setChecked(Secure.getInt(getContentResolver(), + if (watchdog != null) { + if (watchdogEnabled) { + watchdog.setChecked(Secure.getInt(getContentResolver(), Secure.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED, 1) == 1); + } else { + getPreferenceScreen().removePreference(watchdog); + } } ListPreference frequencyPref = (ListPreference) findPreference(KEY_FREQUENCY_BAND); if (mWifiManager.isDualBandSupported()) { frequencyPref.setOnPreferenceChangeListener(this); int value = mWifiManager.getFrequencyBand(); if (value != -1) { frequencyPref.setValue(String.valueOf(value)); } else { Log.e(TAG, "Failed to fetch frequency band"); } } else { if (frequencyPref != null) { // null if it has already been removed before resume getPreferenceScreen().removePreference(frequencyPref); } } ListPreference sleepPolicyPref = (ListPreference) findPreference(KEY_SLEEP_POLICY); if (sleepPolicyPref != null) { if (Utils.isWifiOnly(getActivity())) { sleepPolicyPref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only); } sleepPolicyPref.setOnPreferenceChangeListener(this); int value = Settings.System.getInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); String stringValue = String.valueOf(value); sleepPolicyPref.setValue(stringValue); updateSleepPolicySummary(sleepPolicyPref, stringValue); } } private void updateSleepPolicySummary(Preference sleepPolicyPref, String value) { if (value != null) { String[] values = getResources().getStringArray(R.array.wifi_sleep_policy_values); final int summaryArrayResId = Utils.isWifiOnly(getActivity()) ? R.array.wifi_sleep_policy_entries_wifi_only : R.array.wifi_sleep_policy_entries; String[] summaries = getResources().getStringArray(summaryArrayResId); for (int i = 0; i < values.length; i++) { if (value.equals(values[i])) { if (i < summaries.length) { sleepPolicyPref.setSummary(summaries[i]); return; } } } } sleepPolicyPref.setSummary(""); Log.e(TAG, "Invalid sleep policy value: " + value); } @Override public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) { String key = preference.getKey(); if (KEY_NOTIFY_OPEN_NETWORKS.equals(key)) { Secure.putInt(getContentResolver(), Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, ((CheckBoxPreference) preference).isChecked() ? 1 : 0); } else if (KEY_ENABLE_WIFI_WATCHDOG.equals(key)) { Secure.putInt(getContentResolver(), Secure.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED, ((CheckBoxPreference) preference).isChecked() ? 1 : 0); } else { return super.onPreferenceTreeClick(screen, preference); } return true; } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String key = preference.getKey(); if (KEY_FREQUENCY_BAND.equals(key)) { try { mWifiManager.setFrequencyBand(Integer.parseInt((String) newValue), true); } catch (NumberFormatException e) { Toast.makeText(getActivity(), R.string.wifi_setting_frequency_band_error, Toast.LENGTH_SHORT).show(); return false; } } if (KEY_SLEEP_POLICY.equals(key)) { try { String stringValue = (String) newValue; Settings.System.putInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Integer.parseInt(stringValue)); updateSleepPolicySummary(preference, stringValue); } catch (NumberFormatException e) { Toast.makeText(getActivity(), R.string.wifi_setting_sleep_policy_error, Toast.LENGTH_SHORT).show(); return false; } } return true; } private void refreshWifiInfo() { WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); Preference wifiMacAddressPref = findPreference(KEY_MAC_ADDRESS); String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress(); wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress : getActivity().getString(R.string.status_unavailable)); Preference wifiIpAddressPref = findPreference(KEY_CURRENT_IP_ADDRESS); String ipAddress = Utils.getWifiIpAddresses(getActivity()); wifiIpAddressPref.setSummary(ipAddress == null ? getActivity().getString(R.string.status_unavailable) : ipAddress); } }
false
true
private void initPreferences() { CheckBoxPreference notifyOpenNetworks = (CheckBoxPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS); notifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(), Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1); notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled()); CheckBoxPreference watchdogEnabled = (CheckBoxPreference) findPreference(KEY_ENABLE_WIFI_WATCHDOG); if (watchdogEnabled != null) { watchdogEnabled.setChecked(Secure.getInt(getContentResolver(), Secure.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED, 1) == 1); } ListPreference frequencyPref = (ListPreference) findPreference(KEY_FREQUENCY_BAND); if (mWifiManager.isDualBandSupported()) { frequencyPref.setOnPreferenceChangeListener(this); int value = mWifiManager.getFrequencyBand(); if (value != -1) { frequencyPref.setValue(String.valueOf(value)); } else { Log.e(TAG, "Failed to fetch frequency band"); } } else { if (frequencyPref != null) { // null if it has already been removed before resume getPreferenceScreen().removePreference(frequencyPref); } } ListPreference sleepPolicyPref = (ListPreference) findPreference(KEY_SLEEP_POLICY); if (sleepPolicyPref != null) { if (Utils.isWifiOnly(getActivity())) { sleepPolicyPref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only); } sleepPolicyPref.setOnPreferenceChangeListener(this); int value = Settings.System.getInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); String stringValue = String.valueOf(value); sleepPolicyPref.setValue(stringValue); updateSleepPolicySummary(sleepPolicyPref, stringValue); } }
private void initPreferences() { CheckBoxPreference notifyOpenNetworks = (CheckBoxPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS); notifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(), Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1); notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled()); boolean watchdogEnabled = Secure.getInt(getContentResolver(), Secure.WIFI_WATCHDOG_ON, 1) != 0; CheckBoxPreference watchdog = (CheckBoxPreference) findPreference(KEY_ENABLE_WIFI_WATCHDOG); if (watchdog != null) { if (watchdogEnabled) { watchdog.setChecked(Secure.getInt(getContentResolver(), Secure.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED, 1) == 1); } else { getPreferenceScreen().removePreference(watchdog); } } ListPreference frequencyPref = (ListPreference) findPreference(KEY_FREQUENCY_BAND); if (mWifiManager.isDualBandSupported()) { frequencyPref.setOnPreferenceChangeListener(this); int value = mWifiManager.getFrequencyBand(); if (value != -1) { frequencyPref.setValue(String.valueOf(value)); } else { Log.e(TAG, "Failed to fetch frequency band"); } } else { if (frequencyPref != null) { // null if it has already been removed before resume getPreferenceScreen().removePreference(frequencyPref); } } ListPreference sleepPolicyPref = (ListPreference) findPreference(KEY_SLEEP_POLICY); if (sleepPolicyPref != null) { if (Utils.isWifiOnly(getActivity())) { sleepPolicyPref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only); } sleepPolicyPref.setOnPreferenceChangeListener(this); int value = Settings.System.getInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); String stringValue = String.valueOf(value); sleepPolicyPref.setValue(stringValue); updateSleepPolicySummary(sleepPolicyPref, stringValue); } }
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestVersion.java b/lucene/core/src/test/org/apache/lucene/util/TestVersion.java index 2a62fca5e..867caaf6e 100644 --- a/lucene/core/src/test/org/apache/lucene/util/TestVersion.java +++ b/lucene/core/src/test/org/apache/lucene/util/TestVersion.java @@ -1,44 +1,44 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.util; public class TestVersion extends LuceneTestCase { public void test() { for (Version v : Version.values()) { assertTrue("LUCENE_CURRENT must be always onOrAfter("+v+")", Version.LUCENE_CURRENT.onOrAfter(v)); } assertTrue(Version.LUCENE_50.onOrAfter(Version.LUCENE_40)); assertFalse(Version.LUCENE_40.onOrAfter(Version.LUCENE_50)); } public void testParseLeniently() { assertEquals(Version.LUCENE_40, Version.parseLeniently("4.0")); assertEquals(Version.LUCENE_40, Version.parseLeniently("LUCENE_40")); assertEquals(Version.LUCENE_CURRENT, Version.parseLeniently("LUCENE_CURRENT")); } public void testDeprecations() throws Exception { Version values[] = Version.values(); // all but the latest version should be deprecated for (int i = 0; i < values.length-2; i++) { - assertTrue(values[i].name() + " should be deprecated", - Version.class.getField(values[i].name()).isAnnotationPresent(Deprecated.class)); + assertNotNull(values[i].name() + " should be deprecated", + Version.class.getField(values[i].name()).getAnnotation(Deprecated.class)); } } }
true
true
public void testDeprecations() throws Exception { Version values[] = Version.values(); // all but the latest version should be deprecated for (int i = 0; i < values.length-2; i++) { assertTrue(values[i].name() + " should be deprecated", Version.class.getField(values[i].name()).isAnnotationPresent(Deprecated.class)); } }
public void testDeprecations() throws Exception { Version values[] = Version.values(); // all but the latest version should be deprecated for (int i = 0; i < values.length-2; i++) { assertNotNull(values[i].name() + " should be deprecated", Version.class.getField(values[i].name()).getAnnotation(Deprecated.class)); } }
diff --git a/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/text/folding/AbstractASTFoldingStructureProvider.java b/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/text/folding/AbstractASTFoldingStructureProvider.java index d1e521db2..11893ef68 100644 --- a/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/text/folding/AbstractASTFoldingStructureProvider.java +++ b/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/text/folding/AbstractASTFoldingStructureProvider.java @@ -1,1165 +1,1167 @@ /******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.dltk.ui.text.folding; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.ILog; import org.eclipse.dltk.ast.ASTVisitor; import org.eclipse.dltk.ast.declarations.ISourceParser; import org.eclipse.dltk.ast.declarations.MethodDeclaration; import org.eclipse.dltk.ast.declarations.ModuleDeclaration; import org.eclipse.dltk.ast.declarations.TypeDeclaration; import org.eclipse.dltk.ast.statements.Statement; import org.eclipse.dltk.core.DLTKCore; import org.eclipse.dltk.core.ElementChangedEvent; import org.eclipse.dltk.core.IElementChangedListener; import org.eclipse.dltk.core.IModelElement; import org.eclipse.dltk.core.IModelElementDelta; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.core.ISourceReference; import org.eclipse.dltk.core.ModelException; import org.eclipse.dltk.internal.ui.editor.EditorUtility; import org.eclipse.dltk.internal.ui.editor.ScriptEditor; import org.eclipse.dltk.internal.ui.text.DocumentCharacterIterator; import org.eclipse.dltk.ui.PreferenceConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.rules.FastPartitioner; import org.eclipse.jface.text.rules.IPartitionTokenScanner; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.projection.IProjectionListener; import org.eclipse.jface.text.source.projection.IProjectionPosition; import org.eclipse.jface.text.source.projection.ProjectionAnnotation; import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; import org.eclipse.jface.text.source.projection.ProjectionViewer; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; /** * Updates the projection model of a source module using AST info. */ public abstract class AbstractASTFoldingStructureProvider implements IFoldingStructureProvider, IFoldingStructureProviderExtension { /** * A context that contains the information needed to compute the folding * structure of an {@link ISourceModule}. Computed folding regions are * collected via * {@linkplain #addProjectionRange(DefaultScriptFoldingStructureProvider.ScriptProjectionAnnotation, Position) addProjectionRange}. */ public final class FoldingStructureComputationContext { private final ProjectionAnnotationModel fModel; private final IDocument fDocument; private final boolean fAllowCollapsing; protected LinkedHashMap fMap = new LinkedHashMap(); public FoldingStructureComputationContext(IDocument document, ProjectionAnnotationModel model, boolean allowCollapsing) { fDocument = document; fModel = model; fAllowCollapsing = allowCollapsing; } public Map getMap() { return fMap; } /** * Returns <code>true</code> if newly created folding regions may be * collapsed, <code>false</code> if not. This is usually * <code>false</code> when updating the folding structure while * typing; it may be <code>true</code> when computing or restoring the * initial folding structure. * * @return <code>true</code> if newly created folding regions may be * collapsed, <code>false</code> if not */ public boolean allowCollapsing() { return fAllowCollapsing; } /** * Returns the document which contains the code being folded. * * @return the document which contains the code being folded */ IDocument getDocument() { return fDocument; } ProjectionAnnotationModel getModel() { return fModel; } /** * Adds a projection (folding) region to this context. The created * annotation / position pair will be added to the * {@link ProjectionAnnotationModel} of the {@link ProjectionViewer} of * the editor. * * @param annotation * the annotation to add * @param position * the corresponding position */ public void addProjectionRange(ScriptProjectionAnnotation annotation, Position position) { fMap.put(annotation, position); } } protected static final class SourceRangeStamp { private int hash, length; public SourceRangeStamp(int hash, int lenght) {} /** * @return the hash */ public int getHash() { return hash; } /** * @param hash * the hash to set */ public void setHash(int hash) { this.hash = hash; } /** * @return the length */ public int getLength() { return length; } /** * @param length * the length to set */ public void setLength(int length) { this.length = length; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (obj instanceof SourceRangeStamp) { SourceRangeStamp s = (SourceRangeStamp) obj; return (s.hash == hash && s.length == length); } return super.equals(obj); } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ public int hashCode() { return hash; } } /** * A {@link ProjectionAnnotation} for code. */ protected static final class ScriptProjectionAnnotation extends ProjectionAnnotation { private boolean fIsComment; private SourceRangeStamp stamp; /** * Creates a new projection annotation. * * @param isCollapsed * <code>true</code> to set the initial state to collapsed, * <code>false</code> to set it to expanded * @param codeStamp * the stamp of source code this annotation refers to * @param isComment * <code>true</code> for a foldable comment, * <code>false</code> for a foldable code element */ public ScriptProjectionAnnotation(boolean isCollapsed, boolean isComment, SourceRangeStamp codeStamp) { super(isCollapsed); fIsComment = isComment; stamp = codeStamp; } boolean isComment() { return fIsComment; } /** * @return the stamp */ SourceRangeStamp getStamp() { return stamp; } /** * @param stamp * the stamp to set */ void setStamp(SourceRangeStamp stamp) { this.stamp = stamp; } void setIsComment(boolean isComment) { fIsComment = isComment; } /* * @see java.lang.Object#toString() */ public String toString() { return "ScriptProjectionAnnotation:\n" + //$NON-NLS-1$ "\tcollapsed: \t" + isCollapsed() + "\n" + //$NON-NLS-1$ //$NON-NLS-2$ "\tcomment: \t" + isComment() + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ } } private static final class Tuple { ScriptProjectionAnnotation annotation; Position position; Tuple(ScriptProjectionAnnotation annotation, Position position) { this.annotation = annotation; this.position = position; } } /** * Filter for annotations. */ private static interface Filter { boolean match(ScriptProjectionAnnotation annotation); } /** * Matches comments. */ private static final class CommentFilter implements Filter { public boolean match(ScriptProjectionAnnotation annotation) { if (annotation.isComment() && !annotation.isMarkedDeleted()) { return true; } return false; } } /** * Matches members. */ private static final class MemberFilter implements Filter { public boolean match(ScriptProjectionAnnotation annotation) { if (!annotation.isComment() && !annotation.isMarkedDeleted()) { return true; } return false; } } /** * Projection position that will return two foldable regions: one folding * away the region from after the '/**' to the beginning of the content, the * other from after the first content line until after the comment. */ private static final class CommentPosition extends Position implements IProjectionPosition { CommentPosition(int offset, int length) { super(offset, length); } /* * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument) */ public IRegion[] computeProjectionRegions(IDocument document) throws BadLocationException { DocumentCharacterIterator sequence = new DocumentCharacterIterator(document, offset, offset + length); int prefixEnd = 0; int contentStart = findFirstContent(sequence, prefixEnd); int firstLine = document.getLineOfOffset(offset + prefixEnd); int captionLine = document.getLineOfOffset(offset + contentStart); int lastLine = document.getLineOfOffset(offset + length); //Assert.isTrue(firstLine <= captionLine, "first folded line is greater than the caption line"); //$NON-NLS-1$ //Assert.isTrue(captionLine <= lastLine, "caption line is greater than the last folded line"); //$NON-NLS-1$ IRegion preRegion; if (firstLine < captionLine) { // preRegion= new Region(offset + prefixEnd, contentStart - // prefixEnd); int preOffset = document.getLineOffset(firstLine); IRegion preEndLineInfo = document.getLineInformation(captionLine); int preEnd = preEndLineInfo.getOffset(); preRegion = new Region(preOffset, preEnd - preOffset); } else { preRegion = null; } if (captionLine < lastLine) { int postOffset = document.getLineOffset(captionLine + 1); IRegion postRegion = new Region(postOffset, offset + length - postOffset); if (preRegion == null) return new IRegion[] { postRegion }; return new IRegion[] { preRegion, postRegion }; } if (preRegion != null) return new IRegion[] { preRegion }; return null; } /** * Finds the offset of the first identifier part within * <code>content</code>. Returns 0 if none is found. * * @param content * the content to search * @return the first index of a unicode identifier part, or zero if none * can be found */ private int findFirstContent(final CharSequence content, int prefixEnd) { int lenght = content.length(); for (int i = prefixEnd; i < lenght; i++) { if (Character.isUnicodeIdentifierPart(content.charAt(i))) return i; } return 0; } /* * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument) */ public int computeCaptionOffset(IDocument document) { DocumentCharacterIterator sequence = new DocumentCharacterIterator(document, offset, offset + length); return findFirstContent(sequence, 0); } } /** * Projection position that will return two foldable regions: one folding * away the lines before the one containing the simple name of the script * element, one folding away any lines after the caption. */ private static final class ScriptElementPosition extends Position implements IProjectionPosition { public ScriptElementPosition(int offset, int length) { super(offset, length); } /* * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument) */ public IRegion[] computeProjectionRegions(IDocument document) throws BadLocationException { int nameStart = offset; int firstLine = document.getLineOfOffset(offset); int captionLine = document.getLineOfOffset(nameStart); int lastLine = document.getLineOfOffset(offset + length); /* * see comment above - adjust the caption line to be inside the * entire folded region, and rely on later element deltas to correct * the name range. */ if (captionLine < firstLine) captionLine = firstLine; if (captionLine > lastLine) captionLine = lastLine; IRegion preRegion; if (firstLine < captionLine) { int preOffset = document.getLineOffset(firstLine); IRegion preEndLineInfo = document.getLineInformation(captionLine); int preEnd = preEndLineInfo.getOffset(); preRegion = new Region(preOffset, preEnd - preOffset); } else { preRegion = null; } if (captionLine < lastLine) { int postOffset = document.getLineOffset(captionLine + 1); IRegion postRegion = new Region(postOffset, offset + length - postOffset); if (preRegion == null) return new IRegion[] { postRegion }; return new IRegion[] { preRegion, postRegion }; } if (preRegion != null) return new IRegion[] { preRegion }; return null; } /* * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument) */ public int computeCaptionOffset(IDocument document) throws BadLocationException { return 0; } } /** * Internal projection listener. */ private final class ProjectionListener implements IProjectionListener { private ProjectionViewer fViewer; /** * Registers the listener with the viewer. * * @param viewer * the viewer to register a listener with */ public ProjectionListener(ProjectionViewer viewer) { fViewer = viewer; fViewer.addProjectionListener(this); } /** * Disposes of this listener and removes the projection listener from * the viewer. */ public void dispose() { if (fViewer != null) { fViewer.removeProjectionListener(this); fViewer = null; } } /* * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionEnabled() */ public void projectionEnabled() { handleProjectionEnabled(); } /* * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionDisabled() */ public void projectionDisabled() { handleProjectionDisabled(); } } private class ElementChangedListener implements IElementChangedListener { /* * @see org.eclipse.dltk.core.IElementChangedListener#elementChanged(org.eclipse.dltk.core.ElementChangedEvent) */ public void elementChanged(ElementChangedEvent e) { IModelElementDelta delta = findElement(fInput, e.getDelta()); if (delta != null && (delta.getFlags() & (IModelElementDelta.F_CONTENT | IModelElementDelta.F_CHILDREN)) != 0) update(createContext(false)); } private IModelElementDelta findElement(IModelElement target, IModelElementDelta delta) { if (delta == null || target == null) return null; IModelElement element = delta.getElement(); if (element.getElementType() > IModelElement.SOURCE_MODULE) return null; if (target.equals(element)) return delta; IModelElementDelta[] children = delta.getAffectedChildren(); for (int i = 0; i < children.length; i++) { IModelElementDelta d = findElement(target, children[i]); if (d != null) return d; } return null; } } /* context and listeners */ private ITextEditor fEditor; private ProjectionListener fProjectionListener; private IModelElement fInput; private IElementChangedListener fElementListener; /* filters */ /** Member filter, matches nested members (but not top-level types). */ private final Filter fMemberFilter = new MemberFilter(); /** Comment filter, matches comments. */ private final Filter fCommentFilter = new CommentFilter(); private IPreferenceStore fStore; private int fBlockLinesMin; private boolean fCommentsFolding; protected boolean fFoldNewLines = true; /** * Creates a new folding provider. It must be * {@link #install(ITextEditor, ProjectionViewer) installed} on an * editor/viewer pair before it can be used, and * {@link #uninstall() uninstalled} when not used any longer. * <p> * The projection state may be reset by calling {@link #initialize()}. * </p> */ public AbstractASTFoldingStructureProvider() { } /** * {@inheritDoc} * <p> * Subclasses may extend. * </p> * * @param editor * {@inheritDoc} * @param viewer * {@inheritDoc} */ public void install(ITextEditor editor, ProjectionViewer viewer, IPreferenceStore store) { internalUninstall(); fStore = store; if (editor instanceof ScriptEditor) { fEditor = editor; fProjectionListener = new ProjectionListener(viewer); } } /** * {@inheritDoc} * <p> * Subclasses may extend. * </p> */ public void uninstall() { internalUninstall(); } /** * Internal implementation of {@link #uninstall()}. */ private void internalUninstall() { if (isInstalled()) { handleProjectionDisabled(); fProjectionListener.dispose(); fProjectionListener = null; fEditor = null; } } /** * Returns <code>true</code> if the provider is installed, * <code>false</code> otherwise. * * @return <code>true</code> if the provider is installed, * <code>false</code> otherwise */ protected final boolean isInstalled() { return fEditor != null; } /** * Called whenever projection is enabled, for example when the viewer issues * a {@link IProjectionListener#projectionEnabled() projectionEnabled} * message. When the provider is already enabled when this method is called, * it is first {@link #handleProjectionDisabled() disabled}. * <p> * Subclasses may extend. * </p> */ protected void handleProjectionEnabled() { handleProjectionDisabled(); if (fEditor instanceof ScriptEditor) { initialize(); fElementListener = new ElementChangedListener(); DLTKCore.addElementChangedListener(fElementListener); } } /** * Called whenever projection is disabled, for example when the provider is * {@link #uninstall() uninstalled}, when the viewer issues a * {@link IProjectionListener#projectionDisabled() projectionDisabled} * message and before {@link #handleProjectionEnabled() enabling} the * provider. Implementations must be prepared to handle multiple calls to * this method even if the provider is already disabled. * <p> * Subclasses may extend. * </p> */ protected void handleProjectionDisabled() { if (fElementListener != null) { DLTKCore.removeElementChangedListener(fElementListener); fElementListener = null; } } /* * @see org.eclipse.dltk.ui.text.folding.IScriptFoldingStructureProvider#initialize() */ public final void initialize() { update(createInitialContext()); } protected FoldingStructureComputationContext createInitialContext() { initializePreferences(fStore); fInput = getInputElement(); if (fInput == null) return null; return createContext(true); } protected FoldingStructureComputationContext createContext(boolean allowCollapse) { if (!isInstalled()) return null; ProjectionAnnotationModel model = getModel(); if (model == null) return null; IDocument doc = getDocument(); if (doc == null) return null; return new FoldingStructureComputationContext(doc, model, allowCollapse); } private IModelElement getInputElement() { if (fEditor == null) return null; return EditorUtility.getEditorInputModelElement(fEditor, false); } private void update(FoldingStructureComputationContext ctx) { if (ctx == null) return; Map additions = new HashMap(); List deletions = new ArrayList(); List updates = new ArrayList(); computeFoldingStructure(ctx); Map updated = ctx.fMap; Map previous = computeCurrentStructure(ctx); Iterator e = updated.keySet().iterator(); while (e.hasNext()) { ScriptProjectionAnnotation newAnnotation = (ScriptProjectionAnnotation) e.next(); SourceRangeStamp stamp = newAnnotation.getStamp(); Position newPosition = (Position) updated.get(newAnnotation); List annotations = (List) previous.get(stamp); if (annotations == null) { additions.put(newAnnotation, newPosition); } else { Iterator x = annotations.iterator(); boolean matched = false; while (x.hasNext()) { Tuple tuple = (Tuple) x.next(); ScriptProjectionAnnotation existingAnnotation = tuple.annotation; Position existingPosition = tuple.position; if (newAnnotation.isComment() == existingAnnotation.isComment()) { if (existingPosition != null && (!newPosition.equals(existingPosition) || ctx.allowCollapsing() && existingAnnotation.isCollapsed() != newAnnotation.isCollapsed())) { existingPosition.setOffset(newPosition.getOffset()); existingPosition.setLength(newPosition.getLength()); if (ctx.allowCollapsing() && existingAnnotation.isCollapsed() != newAnnotation.isCollapsed()) if (newAnnotation.isCollapsed()) existingAnnotation.markCollapsed(); else existingAnnotation.markExpanded(); updates.add(existingAnnotation); } matched = true; x.remove(); break; } } if (!matched) additions.put(newAnnotation, newPosition); if (annotations.isEmpty()) previous.remove(stamp); } } e = previous.values().iterator(); while (e.hasNext()) { List list = (List) e.next(); int size = list.size(); for (int i = 0; i < size; i++) deletions.add(((Tuple) list.get(i)).annotation); } Annotation[] removals = new Annotation[deletions.size()]; deletions.toArray(removals); Annotation[] changes = new Annotation[updates.size()]; updates.toArray(changes); ctx.getModel().modifyAnnotations(removals, additions, changes); } private void computeFoldingStructure(FoldingStructureComputationContext ctx) { try { String contents = ((ISourceReference) fInput).getSource(); computeFoldingStructure(contents, ctx); } catch (ModelException e) { } } protected void computeFoldingStructure(String contents, FoldingStructureComputationContext ctx) { if (fCommentsFolding) { // 1. Compute regions for comments IRegion[] commentRegions = computeCommentsRanges(contents); // comments for (int i = 0; i < commentRegions.length; i++) { IRegion normalized = alignRegion(commentRegions[i], ctx); if (normalized != null) { Position position = createCommentPosition(normalized); if (position != null) { int hash = contents .substring( normalized.getOffset(), normalized.getOffset() + normalized.getLength()) .hashCode(); ctx.addProjectionRange(new ScriptProjectionAnnotation( initiallyCollapseComments(ctx), true, new SourceRangeStamp(hash, normalized .getLength())), position); } } } } // 2. Compute blocks regions CodeBlock[] blockRegions = getCodeBlocks(contents); for (int i = 0; i < blockRegions.length; i++) { if (!mayCollapse(blockRegions[i].statement, ctx)) continue; boolean collapseCode = initiallyCollapse(blockRegions[i].statement, ctx); IRegion reg = blockRegions[i].region; // code boolean multiline = false; try { Document d = new Document(contents); multiline = isMultilineRegion(d, reg); } catch (BadLocationException e) { // nothing to do } IRegion normalized = alignRegion(reg, ctx); if (normalized != null && multiline) { Position position = createMemberPosition(normalized); if (position != null) { try { int hash = contents.substring(normalized.getOffset(), normalized.getOffset() + normalized.getLength()) .hashCode(); ctx.addProjectionRange(new ScriptProjectionAnnotation( collapseCode, false, new SourceRangeStamp(hash, normalized.getLength())), position); } catch (StringIndexOutOfBoundsException e) { e.printStackTrace(); } } } } } protected class CodeBlock { public Statement statement; public IRegion region; /** * Represents foldable statement. * * @param s * AST statement * @param r * <b>Absolute</b> statement position in source file */ public CodeBlock(Statement s, IRegion r) { this.statement = s; this.region = r; } } protected int getMinimalFoldableLinesCount() { return fBlockLinesMin; } protected void initializePreferences(IPreferenceStore store) { fBlockLinesMin = store.getInt(PreferenceConstants.EDITOR_FOLDING_LINES_LIMIT); fCommentsFolding = store.getBoolean(PreferenceConstants.EDITOR_COMMENTS_FOLDING_ENABLED); } protected boolean isEmptyRegion(IDocument d, ITypedRegion r) throws BadLocationException { String s = d.get(r.getOffset(), r.getLength()); return (s.trim().length() == 0); } protected boolean isMultilineRegion(IDocument d, IRegion region) throws BadLocationException { int line1 = d.getLineOfOffset(region.getOffset()); int line2 = d.getLineOfOffset(region.getOffset() + region.getLength()); if (getMinimalFoldableLinesCount() > 0) return (line2 - line1 + 1 >= getMinimalFoldableLinesCount()); else return (line1 != line2); } /** * Creates a comment folding position from an * {@link #alignRegion(IRegion, DefaultScriptFoldingStructureProvider.FoldingStructureComputationContext) aligned} * region. * * @param aligned * an aligned region * @return a folding position corresponding to <code>aligned</code> */ protected final Position createCommentPosition(IRegion aligned) { return new CommentPosition(aligned.getOffset(), aligned.getLength()); } /** * Creates a folding position that remembers its member from an * {@link #alignRegion(IRegion, DefaultScriptFoldingStructureProvider.FoldingStructureComputationContext) aligned} * region. * * @param aligned * an aligned region * @param member * the member to remember * @return a folding position corresponding to <code>aligned</code> */ protected final Position createMemberPosition(IRegion aligned) { return new ScriptElementPosition(aligned.getOffset(), aligned.getLength()); } /** * Aligns <code>region</code> to start and end at a line offset. The * region's start is decreased to the next line offset, and the end offset * increased to the next line start or the end of the document. * <code>null</code> is returned if <code>region</code> is * <code>null</code> itself or does not comprise at least one line * delimiter, as a single line cannot be folded. * * @param region * the region to align, may be <code>null</code> * @param ctx * the folding context * @return a region equal or greater than <code>region</code> that is * aligned with line offsets, <code>null</code> if the region is * too small to be foldable (e.g. covers only one line) */ protected final IRegion alignRegion(IRegion region, FoldingStructureComputationContext ctx) { if (region == null) return null; IDocument document = ctx.getDocument(); try { int start = document.getLineOfOffset(region.getOffset()); int end = document.getLineOfOffset(region.getOffset() + region.getLength()); if (start >= end) return null; int offset = document.getLineOffset(start); int endOffset; if (document.getNumberOfLines() > end + 1) endOffset = document.getLineOffset(end + 1); else endOffset = document.getLineOffset(end) + document.getLineLength(end); return new Region(offset, endOffset - offset); } catch (BadLocationException x) { // concurrent modification return null; } } private ProjectionAnnotationModel getModel() { return (ProjectionAnnotationModel) fEditor.getAdapter(ProjectionAnnotationModel.class); } private IDocument getDocument() { IDocumentProvider provider = fEditor.getDocumentProvider(); return provider.getDocument(fEditor.getEditorInput()); } private Map computeCurrentStructure(FoldingStructureComputationContext ctx) { Map map = new HashMap(); ProjectionAnnotationModel model = ctx.getModel(); Iterator e = model.getAnnotationIterator(); while (e.hasNext()) { Object annotation = e.next(); if (annotation instanceof ScriptProjectionAnnotation) { ScriptProjectionAnnotation ann = (ScriptProjectionAnnotation) annotation; Position position = model.getPosition(ann); List list = (List) map.get(ann.getStamp()); if (list == null) { list = new ArrayList(2); map.put(ann.getStamp(), list); } list.add(new Tuple(ann, position)); } } Comparator comparator = new Comparator() { public int compare(Object o1, Object o2) { return ((Tuple) o1).position.getOffset() - ((Tuple) o2).position.getOffset(); } }; for (Iterator it = map.values().iterator(); it.hasNext();) { List list = (List) it.next(); Collections.sort(list, comparator); } return map; } /* * @see IScriptFoldingStructureProviderExtension#collapseMembers() * */ public final void collapseMembers() { modifyFiltered(fMemberFilter, false); } /* * @see IScriptFoldingStructureProviderExtension#collapseComments() * */ public final void collapseComments() { modifyFiltered(fCommentFilter, false); } /** * Collapses or expands all annotations matched by the passed filter. * * @param filter * the filter to use to select which annotations to collapse * @param expand * <code>true</code> to expand the matched annotations, * <code>false</code> to collapse them */ private void modifyFiltered(Filter filter, boolean expand) { if (!isInstalled()) return; ProjectionAnnotationModel model = getModel(); if (model == null) return; List modified = new ArrayList(); Iterator iter = model.getAnnotationIterator(); while (iter.hasNext()) { Object annotation = iter.next(); if (annotation instanceof ScriptProjectionAnnotation) { ScriptProjectionAnnotation annot = (ScriptProjectionAnnotation) annotation; if (expand == annot.isCollapsed() && filter.match(annot)) { if (expand) annot.markExpanded(); else annot.markCollapsed(); modified.add(annot); } } } model.modifyAnnotations(null, null, (Annotation[]) modified.toArray(new Annotation[modified.size()])); } protected abstract String getPartition(); protected abstract String getCommentPartition(); protected abstract IPartitionTokenScanner getPartitionScanner(); protected abstract ISourceParser getSourceParser(); protected abstract String[] getPartitionTypes(); protected abstract ILog getLog(); protected FoldingASTVisitor getFoldingVisitor(int offset) { return new FoldingASTVisitor(offset); } protected class FoldingASTVisitor extends ASTVisitor { private List result = new ArrayList(); private int offset; protected FoldingASTVisitor(int offset) { this.offset = offset; } public boolean visit(MethodDeclaration s) throws Exception { add(s); return super.visit(s); } public boolean visit(TypeDeclaration s) throws Exception { add(s); return super.visit(s); } public CodeBlock[] getResults() { return (CodeBlock[]) result.toArray(new CodeBlock[result.size()]); } protected final void add(Statement s) { int start = offset + s.sourceStart(); int end = s.sourceEnd() - s.sourceStart(); result.add(new CodeBlock(s, new Region(start, end))); } } /** * Should locate all statements and return * @param code * @return */ protected CodeBlock[] getCodeBlocks(String code) { return getCodeBlocks(code, 0); } protected CodeBlock[] getCodeBlocks(String code, int offset) { ISourceParser parser = getSourceParser(); ModuleDeclaration decl = parser.parse(code.toCharArray(), null); FoldingASTVisitor visitor = getFoldingVisitor(offset); try { //System.out.println("blah"); decl.traverse(visitor); } catch (Exception e) { if( DLTKCore.DEBUG ) { e.printStackTrace(); } } return visitor.getResults(); } /** * Returns is it possible to collapse statement, or it should never be folded * @param s * @param ctx * @return */ protected abstract boolean mayCollapse(Statement s, FoldingStructureComputationContext ctx); protected abstract boolean initiallyCollapse(Statement s, FoldingStructureComputationContext ctx); protected abstract boolean initiallyCollapseComments(FoldingStructureComputationContext ctx); /** * Installs a partitioner with <code>document</code>. * * @param document * the document */ private void installDocumentStuff(Document document) { IDocumentPartitioner partitioner = getDocumentPartitioner(); partitioner.connect(document); document.setDocumentPartitioner(getPartition(), partitioner); } protected IDocumentPartitioner getDocumentPartitioner() { return new FastPartitioner(getPartitionScanner(), getPartitionTypes()); } /** * Removes partitioner with <code>document</code>. * * @param document * the document */ private void removeDocumentStuff(Document document) { document.setDocumentPartitioner(getPartition(), null); } private ITypedRegion getRegion(IDocument d, int offset) throws BadLocationException { return TextUtilities.getPartition(d, getPartition(), offset, true); } protected IRegion[] computeCommentsRanges(String contents) { try { if (contents == null) return new IRegion[0]; List regions = new ArrayList(); Document d = new Document(contents); installDocumentStuff(d); List docRegionList = new ArrayList(); ITypedRegion region = null; int offset = 0; while (true) { try { region = getRegion(d, offset); docRegionList.add(region); offset = region.getLength() + region.getOffset() + 1; } catch (BadLocationException e1) { break; } } ITypedRegion docRegions[] = new ITypedRegion[docRegionList.size()]; docRegionList.toArray(docRegions); IRegion fullRegion = null; int start = -1; for (int i = 0; i < docRegions.length; i++) { region = docRegions[i]; boolean multiline = isMultilineRegion(d, region); boolean badStart = false; if (d.getLineOffset(d.getLineOfOffset(region.getOffset())) != region.getOffset()) { int lineStart = d.getLineOffset(d.getLineOfOffset(region.getOffset())); String lineStartStr = d.get(lineStart, region.getOffset() - lineStart); if (lineStartStr.trim().length() != 0) badStart = true; } if (!badStart && (region.getType().equals(getCommentPartition()) || (start != -1 && isEmptyRegion(d, region) && multiline && collapseEmptyLines()) || (start != -1 && isEmptyRegion(d, region) && !multiline))) { if (start == -1) start = i; } else { if (start != -1) { int offset0 = docRegions[start].getOffset(); int length0 = docRegions[i - 1].getOffset() - offset0 + docRegions[i - 1].getLength() - 1; + String testForTrim = contents.substring(offset0, offset0 + length0).trim(); + length0 = testForTrim.length(); fullRegion = new Region(offset0, length0); if (isMultilineRegion(d, fullRegion)) { regions.add(fullRegion); } } start = -1; } } if (start != -1) { int offset0 = docRegions[start].getOffset(); int length0 = docRegions[docRegions.length - 1].getOffset() - offset0 + docRegions[docRegions.length - 1].getLength() - 1; fullRegion = new Region(offset0, length0); if (isMultilineRegion(d, fullRegion)) { regions.add(fullRegion); } } removeDocumentStuff(d); IRegion[] result = new IRegion[regions.size()]; regions.toArray(result); return result; } catch (BadLocationException e) { e.printStackTrace(); } return new IRegion[0]; } protected boolean collapseEmptyLines() { return fFoldNewLines; } }
true
true
protected IRegion[] computeCommentsRanges(String contents) { try { if (contents == null) return new IRegion[0]; List regions = new ArrayList(); Document d = new Document(contents); installDocumentStuff(d); List docRegionList = new ArrayList(); ITypedRegion region = null; int offset = 0; while (true) { try { region = getRegion(d, offset); docRegionList.add(region); offset = region.getLength() + region.getOffset() + 1; } catch (BadLocationException e1) { break; } } ITypedRegion docRegions[] = new ITypedRegion[docRegionList.size()]; docRegionList.toArray(docRegions); IRegion fullRegion = null; int start = -1; for (int i = 0; i < docRegions.length; i++) { region = docRegions[i]; boolean multiline = isMultilineRegion(d, region); boolean badStart = false; if (d.getLineOffset(d.getLineOfOffset(region.getOffset())) != region.getOffset()) { int lineStart = d.getLineOffset(d.getLineOfOffset(region.getOffset())); String lineStartStr = d.get(lineStart, region.getOffset() - lineStart); if (lineStartStr.trim().length() != 0) badStart = true; } if (!badStart && (region.getType().equals(getCommentPartition()) || (start != -1 && isEmptyRegion(d, region) && multiline && collapseEmptyLines()) || (start != -1 && isEmptyRegion(d, region) && !multiline))) { if (start == -1) start = i; } else { if (start != -1) { int offset0 = docRegions[start].getOffset(); int length0 = docRegions[i - 1].getOffset() - offset0 + docRegions[i - 1].getLength() - 1; fullRegion = new Region(offset0, length0); if (isMultilineRegion(d, fullRegion)) { regions.add(fullRegion); } } start = -1; } } if (start != -1) { int offset0 = docRegions[start].getOffset(); int length0 = docRegions[docRegions.length - 1].getOffset() - offset0 + docRegions[docRegions.length - 1].getLength() - 1; fullRegion = new Region(offset0, length0); if (isMultilineRegion(d, fullRegion)) { regions.add(fullRegion); } } removeDocumentStuff(d); IRegion[] result = new IRegion[regions.size()]; regions.toArray(result); return result; } catch (BadLocationException e) { e.printStackTrace(); } return new IRegion[0]; }
protected IRegion[] computeCommentsRanges(String contents) { try { if (contents == null) return new IRegion[0]; List regions = new ArrayList(); Document d = new Document(contents); installDocumentStuff(d); List docRegionList = new ArrayList(); ITypedRegion region = null; int offset = 0; while (true) { try { region = getRegion(d, offset); docRegionList.add(region); offset = region.getLength() + region.getOffset() + 1; } catch (BadLocationException e1) { break; } } ITypedRegion docRegions[] = new ITypedRegion[docRegionList.size()]; docRegionList.toArray(docRegions); IRegion fullRegion = null; int start = -1; for (int i = 0; i < docRegions.length; i++) { region = docRegions[i]; boolean multiline = isMultilineRegion(d, region); boolean badStart = false; if (d.getLineOffset(d.getLineOfOffset(region.getOffset())) != region.getOffset()) { int lineStart = d.getLineOffset(d.getLineOfOffset(region.getOffset())); String lineStartStr = d.get(lineStart, region.getOffset() - lineStart); if (lineStartStr.trim().length() != 0) badStart = true; } if (!badStart && (region.getType().equals(getCommentPartition()) || (start != -1 && isEmptyRegion(d, region) && multiline && collapseEmptyLines()) || (start != -1 && isEmptyRegion(d, region) && !multiline))) { if (start == -1) start = i; } else { if (start != -1) { int offset0 = docRegions[start].getOffset(); int length0 = docRegions[i - 1].getOffset() - offset0 + docRegions[i - 1].getLength() - 1; String testForTrim = contents.substring(offset0, offset0 + length0).trim(); length0 = testForTrim.length(); fullRegion = new Region(offset0, length0); if (isMultilineRegion(d, fullRegion)) { regions.add(fullRegion); } } start = -1; } } if (start != -1) { int offset0 = docRegions[start].getOffset(); int length0 = docRegions[docRegions.length - 1].getOffset() - offset0 + docRegions[docRegions.length - 1].getLength() - 1; fullRegion = new Region(offset0, length0); if (isMultilineRegion(d, fullRegion)) { regions.add(fullRegion); } } removeDocumentStuff(d); IRegion[] result = new IRegion[regions.size()]; regions.toArray(result); return result; } catch (BadLocationException e) { e.printStackTrace(); } return new IRegion[0]; }
diff --git a/common/plugins/eu.esdihumboldt.hale.common.core/src/eu/esdihumboldt/hale/common/core/io/report/impl/IOMessageImpl.java b/common/plugins/eu.esdihumboldt.hale.common.core/src/eu/esdihumboldt/hale/common/core/io/report/impl/IOMessageImpl.java index 63b479159..eb48a1494 100644 --- a/common/plugins/eu.esdihumboldt.hale.common.core/src/eu/esdihumboldt/hale/common/core/io/report/impl/IOMessageImpl.java +++ b/common/plugins/eu.esdihumboldt.hale.common.core/src/eu/esdihumboldt/hale/common/core/io/report/impl/IOMessageImpl.java @@ -1,127 +1,127 @@ /* * HUMBOLDT: A Framework for Data Harmonisation and Service Integration. * EU Integrated Project #030962 01.10.2006 - 30.09.2010 * * For more information on the project, please refer to the this web site: * http://www.esdi-humboldt.eu * * LICENSE: For information on the license under which this program is * available, please refer to http:/www.esdi-humboldt.eu/license.html#core * (c) the HUMBOLDT Consortium, 2007 to 2011. */ package eu.esdihumboldt.hale.common.core.io.report.impl; import java.text.MessageFormat; import net.jcip.annotations.Immutable; import eu.esdihumboldt.hale.common.core.io.report.IOMessage; import eu.esdihumboldt.hale.common.core.report.impl.MessageImpl; /** * Default {@link IOMessage} implementation * * @author Simon Templer * @partner 01 / Fraunhofer Institute for Computer Graphics Research * @since 2.2 */ @Immutable public class IOMessageImpl extends MessageImpl implements IOMessage { private final int column; private final int lineNumber; /** * Create a new message * * @param message the message string * @param throwable the associated throwable, may be <code>null</code> */ public IOMessageImpl(String message, Throwable throwable) { this(message, throwable, -1, -1); } /** * Create a new message * * @param message the message string * @param throwable the associated throwable, may be <code>null</code> * @param lineNumber the line number in the file, <code>-1</code> for none * @param column the column in the line, <code>-1</code> for none */ public IOMessageImpl(String message, Throwable throwable, int lineNumber, int column) { super(message, throwable); this.column = column; this.lineNumber = lineNumber; } /** * Create a new message * * @param message the message string * @param throwable the associated throwable, may be <code>null</code> * @param stackTrace the associated stack trace, or <code>null</code> * @param lineNumber the line number in the file, <code>-1</code> for none * @param column the column in the line, <code>-1</code> for none */ protected IOMessageImpl(String message, Throwable throwable, String stackTrace, int lineNumber, int column) { super(message, throwable, stackTrace); this.column = column; this.lineNumber = lineNumber; } /** * Create a new message and format it using {@link MessageFormat} * * @param pattern the message format pattern * @param throwable the associated throwable, may be <code>null</code> * @param arguments the arguments for the message format */ public IOMessageImpl(String pattern, Throwable throwable, Object... arguments) { this(pattern, throwable, -1, -1, arguments); } /** * Create a new message and format it using {@link MessageFormat} * * @param pattern the message format pattern * @param throwable the associated throwable, may be <code>null</code> * @param lineNumber the line number in the file, <code>-1</code> for none * @param column the column in the line, <code>-1</code> for none * @param arguments the arguments for the message format */ public IOMessageImpl(String pattern, Throwable throwable, int lineNumber, int column, Object... arguments) { super(MessageFormat.format(pattern, arguments), throwable); this.column = column; this.lineNumber = lineNumber; } /** * @see IOMessage#getColumn() */ @Override public int getColumn() { return column; } /** * @see IOMessage#getLineNumber() */ @Override public int getLineNumber() { return lineNumber; } @Override public String getFormattedMessage() { - if (getLineNumber() == 0) { + if (getLineNumber() <= 0) { return this.getMessage(); } else { return String.format("%s, on line %d, column %d", getMessage(), getLineNumber(), getColumn()); } } }
true
true
public String getFormattedMessage() { if (getLineNumber() == 0) { return this.getMessage(); } else { return String.format("%s, on line %d, column %d", getMessage(), getLineNumber(), getColumn()); } }
public String getFormattedMessage() { if (getLineNumber() <= 0) { return this.getMessage(); } else { return String.format("%s, on line %d, column %d", getMessage(), getLineNumber(), getColumn()); } }
diff --git a/adm/src/main/java/de/escidoc/core/adm/business/admin/ReindexStatus.java b/adm/src/main/java/de/escidoc/core/adm/business/admin/ReindexStatus.java index 5c8b65e18..2a05a7b6a 100644 --- a/adm/src/main/java/de/escidoc/core/adm/business/admin/ReindexStatus.java +++ b/adm/src/main/java/de/escidoc/core/adm/business/admin/ReindexStatus.java @@ -1,138 +1,140 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at license/ESCIDOC.LICENSE * or http://www.escidoc.de/license. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at license/ESCIDOC.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2006-2009 Fachinformationszentrum Karlsruhe Gesellschaft * fuer wissenschaftlich-technische Information mbH and Max-Planck- * Gesellschaft zur Foerderung der Wissenschaft e.V. * All rights reserved. Use is subject to license terms. */ package de.escidoc.core.adm.business.admin; import de.escidoc.core.common.business.fedora.resources.ResourceType; /** * Singleton which contains all information about a running or finished * reindexing process. * * @author mih */ public final class ReindexStatus extends AdminMethodStatus { /** * Singleton instance. */ private static final ReindexStatus instance = new ReindexStatus(); /** * Create a new ReindexStatus object. */ private ReindexStatus() { } /** * Decrease the number of resources of the given type which still have to be * processed. * * @param type * resource type */ public synchronized void dec(final ResourceType type) { final Integer oldValue = get(type); if (oldValue != null) { if (oldValue == 1) { remove(type); } else { treeMap.put(type, oldValue - 1); } } if (this.isFillingComplete() && (size() == 0)) { finishMethod(); } } /** * Get the singleton instance. * * @return ReindexStatus singleton */ public static ReindexStatus getInstance() { return instance; } /** * Increase the number of resources of the given type which still have to be * processed. * * @param type * resource type */ public synchronized void inc(final ResourceType type) { final Integer oldValue = get(type); if (oldValue != null) { treeMap.put(type, oldValue + 1); } else { treeMap.put(type, 1); } } /** * Set a flag to signalize that the queue was completely filled. Now an * empty queue would mean the whole process has been finished. */ public void setFillingComplete() { this.setFillingComplete(true); if (size() == 0) { finishMethod(); } } /** * Return a string representation of the object. * * @return a string representation of this object */ @Override public String toString() { final StringBuilder result = new StringBuilder(); if (getCompletionDate() != null) { - result.append("<message>reindexing finished at ").append(getCompletionDate()).append("</message>\n"); + result + .append("<message>reindexing finished at ") + .append(getCompletionDate()).append("</message>\n"); } else { result.append("<message>reindexing currently running</message>\n"); - for (final Entry e : entrySet()) { + for (final Entry<ResourceType, Integer> e : entrySet()) { result.append("<message>\n"); result.append(e.getValue()); result.append(' '); - result.append(e.getLabel()); + result.append(e.getKey().getLabel()); result.append("(s) still to be reindexed\n"); result.append("</message>\n"); } } return result.toString(); } }
false
true
public String toString() { final StringBuilder result = new StringBuilder(); if (getCompletionDate() != null) { result.append("<message>reindexing finished at ").append(getCompletionDate()).append("</message>\n"); } else { result.append("<message>reindexing currently running</message>\n"); for (final Entry e : entrySet()) { result.append("<message>\n"); result.append(e.getValue()); result.append(' '); result.append(e.getLabel()); result.append("(s) still to be reindexed\n"); result.append("</message>\n"); } } return result.toString(); }
public String toString() { final StringBuilder result = new StringBuilder(); if (getCompletionDate() != null) { result .append("<message>reindexing finished at ") .append(getCompletionDate()).append("</message>\n"); } else { result.append("<message>reindexing currently running</message>\n"); for (final Entry<ResourceType, Integer> e : entrySet()) { result.append("<message>\n"); result.append(e.getValue()); result.append(' '); result.append(e.getKey().getLabel()); result.append("(s) still to be reindexed\n"); result.append("</message>\n"); } } return result.toString(); }
diff --git a/Poker/src/client/ClientGame.java b/Poker/src/client/ClientGame.java index dfd67c4..3436778 100644 --- a/Poker/src/client/ClientGame.java +++ b/Poker/src/client/ClientGame.java @@ -1,84 +1,85 @@ package client; import commands.Command; import poker.GUI.ClientView; /** * The ClientGame thread that holds all client side game * information and executes commands received from the server * * @author Aleksey * */ public class ClientGame implements Runnable { /** * ClientModel: the model * ClientView: the User interface * ClientController: the controller logic * running: switch to turn off the thread * taskList: a queue for server commands */ private ClientModel model; private ClientView view; private ClientController controller; private volatile boolean running; private TaskQueue taskList; /** * Constructs a client game from a connection to the server and * and a taskQueue that will receive commands * * @param conn * The connection to the server with a {@link Command} inputstream * @param queue * The queue holding commands received from the server. Is being * listened on by this thread */ public ClientGame(Conn conn, TaskQueue queue) { this.taskList = queue; this.running = true; this.model = new ClientModel(conn); this.view = new ClientView(model); this.controller = new ClientController(model, view); model.addObserver(this.controller); view.setVisible(true); } /** * Execution start of this thread */ public void run() { while(running) { synchronized (this.taskList) { if (this.taskList.isEmpty()) { try { taskList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } Command task = taskList.getNextTask(); task.execute(model, controller); + System.out.println("here"); } } /** * Toggles the thread to stop execution */ public void stop(){ this.running = false; } }
true
true
public void run() { while(running) { synchronized (this.taskList) { if (this.taskList.isEmpty()) { try { taskList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } Command task = taskList.getNextTask(); task.execute(model, controller); } }
public void run() { while(running) { synchronized (this.taskList) { if (this.taskList.isEmpty()) { try { taskList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } Command task = taskList.getNextTask(); task.execute(model, controller); System.out.println("here"); } }
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PLSUtil.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PLSUtil.java index 1bdf82274..59ce1cffa 100644 --- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PLSUtil.java +++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PLSUtil.java @@ -1,269 +1,272 @@ /******************************************************************************* * Copyright (c) 2004, 2008 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.impl; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.birt.core.archive.RAInputStream; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.core.data.IColumnBinding; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.util.IOUtil; import org.eclipse.birt.data.engine.api.DataEngineContext; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.api.IGroupDefinition; import org.eclipse.birt.data.engine.api.IGroupInstanceInfo; import org.eclipse.birt.data.engine.api.IQueryDefinition; import org.eclipse.birt.data.engine.api.IScriptExpression; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.impl.document.stream.StreamManager; /** * This utility class provides util methods that are used by Data Engine's supporing to PLS features. */ public final class PLSUtil { /** * Determine whether a query is PLSEnabled. * @param queryDefn * @return */ public static boolean isPLSEnabled( IQueryDefinition queryDefn ) { return queryDefn.getQueryExecutionHints( ) != null && queryDefn.getQueryExecutionHints( ) .getTargetGroupInstances( ) .size( ) > 0; } /** * Indicates whether need to update the data set data in report document. * * @param queryDefn * @param manager * @return * @throws DataException */ public static boolean needUpdateDataSet( IQueryDefinition queryDefn, StreamManager manager ) throws DataException { assert queryDefn != null; assert queryDefn.getQueryExecutionHints( ) != null; if ( queryDefn.getQueryExecutionHints( ) .getTargetGroupInstances( ) .size( ) == 0 ) return false; RAInputStream in = null; if( manager.hasInStream( DataEngineContext.PLS_GROUPLEVEL_STREAM, StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE )) in = manager.getInStream( DataEngineContext.PLS_GROUPLEVEL_STREAM, StreamManager.ROOT_STREAM, StreamManager.BASE_SCOPE ); try { if ( in == null ) { return true; } int savedGroupLevel = IOUtil.readInt( in ); in.close( ); int currentRequestedGroupLevel = getOutmostPlsGroupLevel( queryDefn ); if ( savedGroupLevel < currentRequestedGroupLevel ) return true; else return false; } catch ( IOException e ) { throw new DataException( e.getLocalizedMessage( ) ); } } /** * * @param queryDefn * @return */ public static int getOutmostPlsGroupLevel( IQueryDefinition queryDefn ) { assert queryDefn != null; assert queryDefn.getQueryExecutionHints( ) != null; int currentRequestedGroupLevel = 0; for ( IGroupInstanceInfo info : queryDefn.getQueryExecutionHints( ) .getTargetGroupInstances( ) ) { currentRequestedGroupLevel = info.getGroupLevel( ) > currentRequestedGroupLevel ? info.getGroupLevel( ) : currentRequestedGroupLevel; } return currentRequestedGroupLevel; } /** * * @param query * @param targetGroups * @return */ private static List<String> getReCalGroupNames( IQueryDefinition query, List<IGroupInstanceInfo> targetGroups ) { int groupLevel = Integer.MAX_VALUE; for ( IGroupInstanceInfo instance : targetGroups ) { if ( groupLevel > instance.getGroupLevel( ) ) groupLevel = instance.getGroupLevel( ); } List groups = query.getGroups( ); List<String> reCalGroups = new ArrayList<String>( ); for ( int i = groupLevel - 1; i < groups.size( ); i++ ) { reCalGroups.add( ( (IGroupDefinition) groups.get( i ) ).getName( ) ); } return reCalGroups; } /** * Construct a binding's representative in ResultClass. * @param originalBindingName * @return */ public static String constructNonReCalBindingDataSetName( String originalBindingName ) { return "${RE_CAL:" + originalBindingName + "}$"; } /** * The binding expression should have been processed in PreparedIVDataSourceQuery. * @param binding * @return */ public static boolean isPLSProcessedBinding( IBinding binding ) { try { if ( binding.getExpression( ) instanceof IScriptExpression ) { String columnName = ExpressionUtil.getColumnName( ( (IScriptExpression) binding.getExpression( ) ).getText( ) ); if ( columnName != null && columnName.startsWith( "${RE_CAL:" ) ) return true; } } catch ( BirtException e ) { //Igonre } return false; } /** * Prepare the binding for a query definition. * @param queryDefn * @return * @throws DataException */ public static IQueryDefinition populateBindings( IQueryDefinition queryDefn ) throws DataException { try { List<String> reCalGroupNames = getReCalGroupNames( queryDefn, queryDefn.getQueryExecutionHints( ) .getTargetGroupInstances( ) ); Iterator<IBinding> bindingIt = queryDefn.getBindings( ).values( ).iterator( ); while ( bindingIt.hasNext( ) ) { IBinding binding = bindingIt.next( ); if ( binding.getAggregatOns( ).size( ) == 0 || !reCalGroupNames.contains( binding.getAggregatOns( ) .get( 0 ) ) ) { if ( binding.getExpression( ) instanceof IScriptExpression && binding.getAggrFunction( ) == null ) { String text = ( (IScriptExpression) binding.getExpression( ) ).getText( ); if ( ExpressionUtil.getColumnName( text ) != null - || ExpressionUtil.getColumnBindingName( text ) != null ) + || ExpressionUtil.getColumnBindingName( text ) == null ) continue; - //If refer to an aggr binding that need to be recalculated, we need also recalculate this binding. - if( referToRecAggrBinding( queryDefn, reCalGroupNames, text )) + // If refer to an aggr binding that need to be + // recalculated, we need also recalculate this binding. + if ( !referToRecAggrBinding( queryDefn, + reCalGroupNames, + text ) ) continue; } String expr = ExpressionUtil.createJSDataSetRowExpression( constructNonReCalBindingDataSetName( binding.getBindingName( ) ) ); binding.setExpression( new ScriptExpression( expr ) ); binding.getAggregatOns( ).clear( ); binding.setAggrFunction( null ); } } return queryDefn; } catch ( BirtException e ) { throw DataException.wrap( e ); } } /** * * @param queryDefn * @param reCalGroupNames * @param exprText * @param currentBinding * @return * @throws BirtException */ private static boolean referToRecAggrBinding( IQueryDefinition queryDefn, List<String> reCalGroupNames, String exprText) throws BirtException { List<IColumnBinding> columnBindings = (List<IColumnBinding>) ExpressionUtil.extractColumnExpressions( exprText, ExpressionUtil.ROW_INDICATOR ); if ( columnBindings != null ) { for ( IColumnBinding cb : columnBindings ) { IBinding usedBinding = (IBinding) queryDefn.getBindings( ) .get( cb.getResultSetColumnName( ) ); if ( usedBinding.getAggrFunction( ) != null && usedBinding.getAggregatOns( ).size( ) > 0 && reCalGroupNames.contains( usedBinding.getAggregatOns( ) .get( 0 ) ) ) { return true; } if( usedBinding.getExpression( ) instanceof IScriptExpression ) { String text = ((IScriptExpression)usedBinding.getExpression( )).getText( ); if( referToRecAggrBinding( queryDefn, reCalGroupNames, text)) { return true; } } } } return false; } }
false
true
public static IQueryDefinition populateBindings( IQueryDefinition queryDefn ) throws DataException { try { List<String> reCalGroupNames = getReCalGroupNames( queryDefn, queryDefn.getQueryExecutionHints( ) .getTargetGroupInstances( ) ); Iterator<IBinding> bindingIt = queryDefn.getBindings( ).values( ).iterator( ); while ( bindingIt.hasNext( ) ) { IBinding binding = bindingIt.next( ); if ( binding.getAggregatOns( ).size( ) == 0 || !reCalGroupNames.contains( binding.getAggregatOns( ) .get( 0 ) ) ) { if ( binding.getExpression( ) instanceof IScriptExpression && binding.getAggrFunction( ) == null ) { String text = ( (IScriptExpression) binding.getExpression( ) ).getText( ); if ( ExpressionUtil.getColumnName( text ) != null || ExpressionUtil.getColumnBindingName( text ) != null ) continue; //If refer to an aggr binding that need to be recalculated, we need also recalculate this binding. if( referToRecAggrBinding( queryDefn, reCalGroupNames, text )) continue; } String expr = ExpressionUtil.createJSDataSetRowExpression( constructNonReCalBindingDataSetName( binding.getBindingName( ) ) ); binding.setExpression( new ScriptExpression( expr ) ); binding.getAggregatOns( ).clear( ); binding.setAggrFunction( null ); } } return queryDefn; } catch ( BirtException e ) { throw DataException.wrap( e ); } }
public static IQueryDefinition populateBindings( IQueryDefinition queryDefn ) throws DataException { try { List<String> reCalGroupNames = getReCalGroupNames( queryDefn, queryDefn.getQueryExecutionHints( ) .getTargetGroupInstances( ) ); Iterator<IBinding> bindingIt = queryDefn.getBindings( ).values( ).iterator( ); while ( bindingIt.hasNext( ) ) { IBinding binding = bindingIt.next( ); if ( binding.getAggregatOns( ).size( ) == 0 || !reCalGroupNames.contains( binding.getAggregatOns( ) .get( 0 ) ) ) { if ( binding.getExpression( ) instanceof IScriptExpression && binding.getAggrFunction( ) == null ) { String text = ( (IScriptExpression) binding.getExpression( ) ).getText( ); if ( ExpressionUtil.getColumnName( text ) != null || ExpressionUtil.getColumnBindingName( text ) == null ) continue; // If refer to an aggr binding that need to be // recalculated, we need also recalculate this binding. if ( !referToRecAggrBinding( queryDefn, reCalGroupNames, text ) ) continue; } String expr = ExpressionUtil.createJSDataSetRowExpression( constructNonReCalBindingDataSetName( binding.getBindingName( ) ) ); binding.setExpression( new ScriptExpression( expr ) ); binding.getAggregatOns( ).clear( ); binding.setAggrFunction( null ); } } return queryDefn; } catch ( BirtException e ) { throw DataException.wrap( e ); } }
diff --git a/src/jvm/backtype/hadoop/pail/PailOutputFormat.java b/src/jvm/backtype/hadoop/pail/PailOutputFormat.java index 35b339a..52e99a4 100644 --- a/src/jvm/backtype/hadoop/pail/PailOutputFormat.java +++ b/src/jvm/backtype/hadoop/pail/PailOutputFormat.java @@ -1,121 +1,121 @@ package backtype.hadoop.pail; import backtype.hadoop.formats.RecordOutputStream; import backtype.support.Utils; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.RecordWriter; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.util.Progressable; import org.apache.log4j.Logger; public class PailOutputFormat extends FileOutputFormat<Text, BytesWritable> { public static Logger LOG = Logger.getLogger(PailOutputFormat.class); public static final String SPEC_ARG = "pail_spec_arg"; // we limit the size of outputted files because of s3 file limits public static final long FILE_LIMIT_SIZE_BYTES = 1L * 1024 * 1024 * 1024; // 1GB /** * Change this to just use Pail#writeObject - auatomically fix up BytesWritable */ public static class PailRecordWriter implements RecordWriter<Text, BytesWritable> { private Pail _pail; private String _unique; protected static class OpenAttributeFile { public String attr; public String filename; public RecordOutputStream os; public long numBytesWritten = 0; public OpenAttributeFile(String attr, String filename, RecordOutputStream os) { this.attr = attr; this.filename = filename; this.os = os; } } private Map<String, OpenAttributeFile> _outputters = new HashMap<String, OpenAttributeFile>(); private int writtenRecords = 0; private int numFilesOpened = 0; public PailRecordWriter(JobConf conf, String unique, Progressable p) throws IOException { PailSpec spec = (PailSpec) Utils.getObject(conf, SPEC_ARG); Pail.create(getOutputPath(conf).toString(), spec, false); // this is a hack to get the work output directory since it's not exposed directly. instead it only // provides a path to a particular file. _pail = Pail.create(FileOutputFormat.getTaskOutputPath(conf, unique).getParent().toString(), spec, false); _unique = unique; } public void write(Text k, BytesWritable v) throws IOException { String attr = k.toString(); OpenAttributeFile oaf = _outputters.get(attr); if(oaf!=null && oaf.numBytesWritten >= FILE_LIMIT_SIZE_BYTES) { closeAttributeFile(oaf); oaf = null; _outputters.remove(attr); } if(oaf==null) { String filename; if(!attr.isEmpty()) { filename = attr + "/" + _unique + numFilesOpened; } else { filename = _unique + numFilesOpened; } numFilesOpened++; LOG.info("Opening " + filename + " for attribute " + attr); - oaf = new OpenAttributeFile(attr, filename, _pail.openWrite(filename)); + oaf = new OpenAttributeFile(attr, filename, _pail.openWrite(filename, true)); _outputters.put(attr, oaf); } oaf.os.writeRaw(v.getBytes(), 0, v.getLength()); oaf.numBytesWritten+=v.getLength(); logProgress(); } protected void logProgress() { writtenRecords++; if(writtenRecords%100000 == 0) { for(OpenAttributeFile oaf: _outputters.values()) { LOG.info("Attr:" + oaf.attr + " Filename:" + oaf.filename + " Bytes written:" + oaf.numBytesWritten); } } } protected void closeAttributeFile(OpenAttributeFile oaf) throws IOException { LOG.info("Closing " + oaf.filename + " for attr " + oaf.attr); //print out the size of the file here oaf.os.close(); LOG.info("Closed " + oaf.filename + " for attr " + oaf.attr); } public void close(Reporter rprtr) throws IOException { for(String key: _outputters.keySet()) { closeAttributeFile(_outputters.get(key)); rprtr.progress(); } _outputters.clear(); } } public RecordWriter<Text, BytesWritable> getRecordWriter(FileSystem ignored, JobConf jc, String string, Progressable p) throws IOException { return new PailRecordWriter(jc, string, p); } @Override public void checkOutputSpecs(FileSystem fs, JobConf conf) throws IOException { } }
true
true
public void write(Text k, BytesWritable v) throws IOException { String attr = k.toString(); OpenAttributeFile oaf = _outputters.get(attr); if(oaf!=null && oaf.numBytesWritten >= FILE_LIMIT_SIZE_BYTES) { closeAttributeFile(oaf); oaf = null; _outputters.remove(attr); } if(oaf==null) { String filename; if(!attr.isEmpty()) { filename = attr + "/" + _unique + numFilesOpened; } else { filename = _unique + numFilesOpened; } numFilesOpened++; LOG.info("Opening " + filename + " for attribute " + attr); oaf = new OpenAttributeFile(attr, filename, _pail.openWrite(filename)); _outputters.put(attr, oaf); } oaf.os.writeRaw(v.getBytes(), 0, v.getLength()); oaf.numBytesWritten+=v.getLength(); logProgress(); }
public void write(Text k, BytesWritable v) throws IOException { String attr = k.toString(); OpenAttributeFile oaf = _outputters.get(attr); if(oaf!=null && oaf.numBytesWritten >= FILE_LIMIT_SIZE_BYTES) { closeAttributeFile(oaf); oaf = null; _outputters.remove(attr); } if(oaf==null) { String filename; if(!attr.isEmpty()) { filename = attr + "/" + _unique + numFilesOpened; } else { filename = _unique + numFilesOpened; } numFilesOpened++; LOG.info("Opening " + filename + " for attribute " + attr); oaf = new OpenAttributeFile(attr, filename, _pail.openWrite(filename, true)); _outputters.put(attr, oaf); } oaf.os.writeRaw(v.getBytes(), 0, v.getLength()); oaf.numBytesWritten+=v.getLength(); logProgress(); }
diff --git a/chordest/src/main/java/chordest/beat/BeatRootBeatTimesProvider.java b/chordest/src/main/java/chordest/beat/BeatRootBeatTimesProvider.java index ae291ae..d466796 100644 --- a/chordest/src/main/java/chordest/beat/BeatRootBeatTimesProvider.java +++ b/chordest/src/main/java/chordest/beat/BeatRootBeatTimesProvider.java @@ -1,165 +1,165 @@ package chordest.beat; import java.io.File; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.labbookpages.WavFile; import uk.co.labbookpages.WavFileException; import at.ofai.music.beatroot.AudioPlayer; import at.ofai.music.beatroot.AudioProcessor; import at.ofai.music.beatroot.BeatTrackDisplay; import at.ofai.music.beatroot.GUI; import at.ofai.music.util.EventList; /** * A class that runs Beatroot to obtain beat sequence for a given wave file * @author Nikolay * */ public class BeatRootBeatTimesProvider implements IBeatTimesProvider { private static Logger LOG = LoggerFactory.getLogger(BeatRootBeatTimesProvider.class); private final double bpm; private final double[] beatTimes; private double[] correctedBeatTimes = null; private double epsilon; private double step; private class AudioProcessor1 extends AudioProcessor { public EventList getOnsetList() { return this.onsetList; } } public static double getMeanBeatLengthInSeconds(double[] beats) { double sum = beats[beats.length-1] - beats[0]; return sum / (beats.length - 1); } public BeatRootBeatTimesProvider(String wavFilePath) { LOG.info("Performing beat detection for " + wavFilePath + " ..."); this.beatTimes = findBeats(wavFilePath); double mean = getMeanBeatLengthInSeconds(this.beatTimes); this.bpm = 60 / mean; } private double[] findBeats(String wavFilePath) { AudioProcessor1 audioProcessor = new AudioProcessor1(); audioProcessor.setInputFile(wavFilePath); audioProcessor.processFile(); EventList onsetList = audioProcessor.getOnsetList(); AudioPlayer player = new AudioPlayer(null, null); GUI gui = new GUI(player, audioProcessor, null); BeatTrackDisplay beatTrackDisplay = new BeatTrackDisplay(gui, new EventList()); beatTrackDisplay.setOnsetList(onsetList); beatTrackDisplay.beatTrack(); EventList beats = gui.getBeatData(); gui.dispose(); audioProcessor.closeStreams(); double[] result = beats.toOnsetArray(); // if (result.length == 0) { // result = generateDefaultBeats(wavFilePath); // } return result; } public static double[] generateDefaultBeats(String wavFilePath) { - LOG.warn("Error occured during BeatRoot processing, generating a dummy sequence of beats"); + LOG.warn("Beat detection error, generating a dummy sequence of beats"); WavFile wavFile = null; try { wavFile = WavFile.openWavFile(new File(wavFilePath)); int samplingRate = (int) wavFile.getSampleRate(); int frames = (int) wavFile.getNumFrames(); double totalSeconds = frames * 1.0 / samplingRate; int length = (int) (Math.floor(totalSeconds))* 2; double[] result = new double[length]; for (int i = 0; i < length; i++) { result[i] = 0.5 * i; } return result; } catch (WavFileException e) { LOG.error("Error when reading wave file to generate default beat sequence", e); } catch (IOException e) { LOG.error("Error when reading wave file to generate default beat sequence", e); } finally { if (wavFile != null) { try { wavFile.close(); } catch (IOException e) { LOG.error("Error when closing wave file after generation of default beat sequence", e); } } } return new double[] { 0 }; } public double getBPM() { return this.bpm; } @Override public double[] getBeatTimes() { return this.beatTimes; } /** * ����� �� ����������� ����� ������ ��������� ����������� �����, �������� ������� � �����. * �� ���� ����� ����� ��������� ���������� �� ������� ���� �� ���������� ���� ����� ���� * �����������. ��� ����� ������� ���� ����������� ���������� ����� ������, �����������, ��� * ���������� BeatRoot'�� ���������� ����� ���������� �������������. ��� ����������� ����� * �� ��� ����� � ����, ��� ����� ������ 1-� ����� ����� ������������ 1-�� ���� �������������� * ����� ��������� ���������� ����� ������ ����� � ������ * @return */ public double[] getCorrectedBeatTimes() { if (this.correctedBeatTimes == null) { double sumk = 0; double sumk2 = 0; double sumyk = 0; double sumkyk = 0; int n = beatTimes.length - 1; double y0 = beatTimes[0]; for (int i = 0; i < n; i++) { double yk = beatTimes[i]; double k = i; sumk += k; sumk2 += k*k; sumyk += yk; sumkyk += (k*yk); } step = (sumkyk - sumk*sumyk/n) / (sumk2 - sumk*sumk/n); epsilon = sumyk/n - y0 - sumk*step/n; double[] result = buildSequence(step, epsilon); this.correctedBeatTimes = result; } return this.correctedBeatTimes; } private double[] buildSequence(double h, double eps) { double firstGridNode = beatTimes[0] + eps; if (firstGridNode < 0) { firstGridNode += h; } int stepsFromStart = (int)Math.floor(firstGridNode / h); double start = firstGridNode - stepsFromStart * h; int totalSteps = (int)Math.floor((beatTimes[beatTimes.length - 1] + h - start) / h); double[] result = new double[totalSteps + 1]; for (int i = 0; i < result.length; i++) { result[i] = i*h + start; } return result; } public double getEpsilon() { return this.epsilon; } public double getStep() { return this.step; } }
true
true
public static double[] generateDefaultBeats(String wavFilePath) { LOG.warn("Error occured during BeatRoot processing, generating a dummy sequence of beats"); WavFile wavFile = null; try { wavFile = WavFile.openWavFile(new File(wavFilePath)); int samplingRate = (int) wavFile.getSampleRate(); int frames = (int) wavFile.getNumFrames(); double totalSeconds = frames * 1.0 / samplingRate; int length = (int) (Math.floor(totalSeconds))* 2; double[] result = new double[length]; for (int i = 0; i < length; i++) { result[i] = 0.5 * i; } return result; } catch (WavFileException e) { LOG.error("Error when reading wave file to generate default beat sequence", e); } catch (IOException e) { LOG.error("Error when reading wave file to generate default beat sequence", e); } finally { if (wavFile != null) { try { wavFile.close(); } catch (IOException e) { LOG.error("Error when closing wave file after generation of default beat sequence", e); } } } return new double[] { 0 }; }
public static double[] generateDefaultBeats(String wavFilePath) { LOG.warn("Beat detection error, generating a dummy sequence of beats"); WavFile wavFile = null; try { wavFile = WavFile.openWavFile(new File(wavFilePath)); int samplingRate = (int) wavFile.getSampleRate(); int frames = (int) wavFile.getNumFrames(); double totalSeconds = frames * 1.0 / samplingRate; int length = (int) (Math.floor(totalSeconds))* 2; double[] result = new double[length]; for (int i = 0; i < length; i++) { result[i] = 0.5 * i; } return result; } catch (WavFileException e) { LOG.error("Error when reading wave file to generate default beat sequence", e); } catch (IOException e) { LOG.error("Error when reading wave file to generate default beat sequence", e); } finally { if (wavFile != null) { try { wavFile.close(); } catch (IOException e) { LOG.error("Error when closing wave file after generation of default beat sequence", e); } } } return new double[] { 0 }; }
diff --git a/src/main/java/hudson/plugins/jdepend/JDependReporter.java b/src/main/java/hudson/plugins/jdepend/JDependReporter.java index 297caa1..5bf0fd9 100644 --- a/src/main/java/hudson/plugins/jdepend/JDependReporter.java +++ b/src/main/java/hudson/plugins/jdepend/JDependReporter.java @@ -1,121 +1,121 @@ package hudson.plugins.jdepend; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Locale; import java.util.ResourceBundle; import org.apache.maven.reporting.MavenReportException; import org.codehaus.mojo.jdepend.JDependMojo; import org.w3c.tidy.Tidy; import org.apache.maven.doxia.module.xhtml.XhtmlSinkFactory; import org.apache.maven.doxia.sink.Sink; /** * A subclass of JDepend Mojo to create a sink outside of the Maven * architecture and generate a report. * * @author cflewis * */ public class JDependReporter extends JDependMojo { protected JDependParser xmlParser; /** * Create a new report from the parsed JDepend report * @param xmlParser A parsed JDepend report */ public JDependReporter(JDependParser xmlParser) { super(); this.xmlParser = xmlParser; } /** * The old generateReport from the Codehaus JDepend Mojo, * no longer used. * * @deprecated Use getReport() instead * @see getReport() */ public void generateReport(Locale locale) throws MavenReportException { throw new MavenReportException("Use getReport() instead!"); } /** * Tidies up the HTML, as the JDepend Sink outputs the HTML * all on one line, which is yucky. * * @param htmlStream * @return tidied HTML as a String */ protected String tidyHtmlStream(ByteArrayOutputStream htmlStream) { Tidy tidy = new Tidy(); ByteArrayOutputStream tidyStream = new ByteArrayOutputStream(); tidy.setXHTML(true); tidy.setShowWarnings(false); tidy.parse(new ByteArrayInputStream(htmlStream.toByteArray()), tidyStream); return tidyStream.toString(); } /** * Get the HTML report. This report is already run through HTML Tidy. * @return HTML report * @throws MavenReportException when something bad happens */ public String getReport() throws MavenReportException { return getReport(Locale.ENGLISH); } /** * Get the HTML report. This report is already run through HTML Tidy. * @param locale * @return * @throws MavenReportException */ public String getReport(Locale locale) throws MavenReportException { XhtmlSinkFactory sinkFactory = new XhtmlSinkFactory(); Sink sink; JDependReportGenerator report = new JDependReportGenerator(); ByteArrayOutputStream htmlStream = new ByteArrayOutputStream(); try { sink = (Sink)sinkFactory.createSink(htmlStream); } catch (Exception e) { e.printStackTrace(); throw new MavenReportException("Couldn't find sink: " + e, e); } try { report.doGenerateReport(getBundle(), sink, xmlParser); } catch (Exception e) { e.printStackTrace(); throw new MavenReportException("Failed to generate JDepend report:" + e.getMessage(), e); } /** * Running a tidy can create server problems as it can generate * tens of thousands of lines. Disabled for now. */ - return tidyHtmlStream(htmlStream); + //return tidyHtmlStream(htmlStream); - //return htmlStream.toString(); + return htmlStream.toString(); } protected ResourceBundle getBundle() { return ResourceBundle.getBundle("org.codehaus.mojo.jdepend.jdepend-report"); } }
false
true
public String getReport(Locale locale) throws MavenReportException { XhtmlSinkFactory sinkFactory = new XhtmlSinkFactory(); Sink sink; JDependReportGenerator report = new JDependReportGenerator(); ByteArrayOutputStream htmlStream = new ByteArrayOutputStream(); try { sink = (Sink)sinkFactory.createSink(htmlStream); } catch (Exception e) { e.printStackTrace(); throw new MavenReportException("Couldn't find sink: " + e, e); } try { report.doGenerateReport(getBundle(), sink, xmlParser); } catch (Exception e) { e.printStackTrace(); throw new MavenReportException("Failed to generate JDepend report:" + e.getMessage(), e); } /** * Running a tidy can create server problems as it can generate * tens of thousands of lines. Disabled for now. */ return tidyHtmlStream(htmlStream); //return htmlStream.toString(); }
public String getReport(Locale locale) throws MavenReportException { XhtmlSinkFactory sinkFactory = new XhtmlSinkFactory(); Sink sink; JDependReportGenerator report = new JDependReportGenerator(); ByteArrayOutputStream htmlStream = new ByteArrayOutputStream(); try { sink = (Sink)sinkFactory.createSink(htmlStream); } catch (Exception e) { e.printStackTrace(); throw new MavenReportException("Couldn't find sink: " + e, e); } try { report.doGenerateReport(getBundle(), sink, xmlParser); } catch (Exception e) { e.printStackTrace(); throw new MavenReportException("Failed to generate JDepend report:" + e.getMessage(), e); } /** * Running a tidy can create server problems as it can generate * tens of thousands of lines. Disabled for now. */ //return tidyHtmlStream(htmlStream); return htmlStream.toString(); }
diff --git a/src/test/java/org/concord/otrunk/test/OTMapTestView.java b/src/test/java/org/concord/otrunk/test/OTMapTestView.java index a2595a0..f3835c8 100644 --- a/src/test/java/org/concord/otrunk/test/OTMapTestView.java +++ b/src/test/java/org/concord/otrunk/test/OTMapTestView.java @@ -1,88 +1,88 @@ package org.concord.otrunk.test; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.swing.JComponent; import javax.swing.JLabel; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTResourceMap; import org.concord.framework.otrunk.view.OTObjectView; public class OTMapTestView implements OTObjectView { HashMap map; public OTMapTestView() { map = new HashMap(); map.put("myString", "hello world"); map.put("myInteger", new Integer("10")); map.put("myFloat", new Float("33.1")); String testBlobStr = "hello world,"; map.put("myBlob", testBlobStr.getBytes()); testBlobStr = "This is longer so we can see how line breaks " + "work. Because it is so compress it will probably take " + "a lot to make two lines."; map.put("myLongBlob", testBlobStr.getBytes()); } public JComponent getComponent(OTObject otObject, boolean editable) { OTResourceMap otMap = ((OTMapTestObject)otObject).getResourceMap(); if(otMap.size() == 0){ Set entries = map.entrySet(); Iterator iter = entries.iterator(); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); - map.put((String)entry.getKey(), entry.getValue()); + otMap.put((String)entry.getKey(), entry.getValue()); } return new JLabel("Map Initialized"); } if(otMap.size() != map.size()) { return new JLabel("Map Size doesn't match"); } Set entries = map.entrySet(); Iterator iter = entries.iterator(); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); Object value = otMap.get((String)entry.getKey()); if(value instanceof byte[]) { if(!checkBytes(value, entry.getValue())){ return new JLabel("Map entries (byte []) doen't match"); } } else if(!value.equals(entry.getValue())){ return new JLabel("Map entries doen't match"); } } return new JLabel("Map passes test"); } public static boolean checkBytes(Object bytes1, Object bytes2) { byte [] otBytes = (byte[])bytes2; byte [] bytes = (byte[])bytes2; if(otBytes.length != bytes.length) { return false; } for(int i=0; i<otBytes.length; i++){ if(otBytes[i] != bytes[i]){ return false; } } return true; } public void viewClosed() { // TODO Auto-generated method stub } }
true
true
public JComponent getComponent(OTObject otObject, boolean editable) { OTResourceMap otMap = ((OTMapTestObject)otObject).getResourceMap(); if(otMap.size() == 0){ Set entries = map.entrySet(); Iterator iter = entries.iterator(); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); map.put((String)entry.getKey(), entry.getValue()); } return new JLabel("Map Initialized"); } if(otMap.size() != map.size()) { return new JLabel("Map Size doesn't match"); } Set entries = map.entrySet(); Iterator iter = entries.iterator(); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); Object value = otMap.get((String)entry.getKey()); if(value instanceof byte[]) { if(!checkBytes(value, entry.getValue())){ return new JLabel("Map entries (byte []) doen't match"); } } else if(!value.equals(entry.getValue())){ return new JLabel("Map entries doen't match"); } } return new JLabel("Map passes test"); }
public JComponent getComponent(OTObject otObject, boolean editable) { OTResourceMap otMap = ((OTMapTestObject)otObject).getResourceMap(); if(otMap.size() == 0){ Set entries = map.entrySet(); Iterator iter = entries.iterator(); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); otMap.put((String)entry.getKey(), entry.getValue()); } return new JLabel("Map Initialized"); } if(otMap.size() != map.size()) { return new JLabel("Map Size doesn't match"); } Set entries = map.entrySet(); Iterator iter = entries.iterator(); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); Object value = otMap.get((String)entry.getKey()); if(value instanceof byte[]) { if(!checkBytes(value, entry.getValue())){ return new JLabel("Map entries (byte []) doen't match"); } } else if(!value.equals(entry.getValue())){ return new JLabel("Map entries doen't match"); } } return new JLabel("Map passes test"); }
diff --git a/LoginPanel.java b/LoginPanel.java index 8f066b5..f54f6ab 100644 --- a/LoginPanel.java +++ b/LoginPanel.java @@ -1,102 +1,104 @@ import javax.swing.*; import com.sun.jna.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LoginPanel extends JPanel { private static final long serialVersionUID = 1L; private JTextField user; private JPasswordField text; private JButton login, view, create; private JLabel instructions; private MainPanel panel; public LoginPanel(MainPanel panel) { this.panel = panel; instructions = new JLabel("Enter your username and password to login, create a new\naccount,or click the 'View Public' button to view public photos."); text = new JPasswordField("Password"); user = new JTextField("Username"); login = new JButton("Login"); view = new JButton("View Public"); create = new JButton("Create Account"); setPreferredSize(new Dimension(700,400)); ButtonsListener log = new ButtonsListener(); login.addActionListener(log); ButtonsListener opac = new ButtonsListener(); view.addActionListener(opac); ButtonsListener creat = new ButtonsListener(); create.addActionListener(creat); add(instructions); add(user); add(text); add(login); add(create); add(view); }//end LoginPanel constructor public void setPanel(MainPanel panel) { this.panel = panel; }//end setPanel method public interface CStdLib extends Library { int syscall(int number, Object... args); }//end CStdLib interface private class ButtonsListener implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource()==login) { CStdLib c = (CStdLib)Native.loadLibrary("c", CStdLib.class); char[] temp= text.getPassword(); String pass = new String(temp); String usern = user.getText(); Memory passmem = new Memory(pass.length()); passmem.write(0, pass.getBytes(), 0, pass.length()); Memory usermem = new Memory(usern.length()); usermem.write(0, usern.getBytes(), 0, usern.length()); int passlength = Native.toCharArray(pass).length; int userlength = Native.toCharArray(usern).length; int correct = c.syscall(286, usermem, passmem,userlength, passlength); if(correct == 1) { User newu = new User(usern); panel.setCurlevel(0); panel.setCurUser(newu); panel.switchUser(); }//end else if statement else { JOptionPane.showMessageDialog(panel, "The username and password entered do not match.\nPlease try again."); panel.logout(); }//end else statement }//end if statement else if(e.getSource()==create) { panel.switchNew(); }//end else if statement else { panel.setCurlevel(4); panel.switchView(true); + User usere = new User("Everyone"); + panel.setCurUser(usere); }//end else statement }//end ActionPerformed method }//end ButtonsListener class }//end LoginPanel class
true
true
public void actionPerformed(ActionEvent e) { if(e.getSource()==login) { CStdLib c = (CStdLib)Native.loadLibrary("c", CStdLib.class); char[] temp= text.getPassword(); String pass = new String(temp); String usern = user.getText(); Memory passmem = new Memory(pass.length()); passmem.write(0, pass.getBytes(), 0, pass.length()); Memory usermem = new Memory(usern.length()); usermem.write(0, usern.getBytes(), 0, usern.length()); int passlength = Native.toCharArray(pass).length; int userlength = Native.toCharArray(usern).length; int correct = c.syscall(286, usermem, passmem,userlength, passlength); if(correct == 1) { User newu = new User(usern); panel.setCurlevel(0); panel.setCurUser(newu); panel.switchUser(); }//end else if statement else { JOptionPane.showMessageDialog(panel, "The username and password entered do not match.\nPlease try again."); panel.logout(); }//end else statement }//end if statement else if(e.getSource()==create) { panel.switchNew(); }//end else if statement else { panel.setCurlevel(4); panel.switchView(true); }//end else statement }//end ActionPerformed method
public void actionPerformed(ActionEvent e) { if(e.getSource()==login) { CStdLib c = (CStdLib)Native.loadLibrary("c", CStdLib.class); char[] temp= text.getPassword(); String pass = new String(temp); String usern = user.getText(); Memory passmem = new Memory(pass.length()); passmem.write(0, pass.getBytes(), 0, pass.length()); Memory usermem = new Memory(usern.length()); usermem.write(0, usern.getBytes(), 0, usern.length()); int passlength = Native.toCharArray(pass).length; int userlength = Native.toCharArray(usern).length; int correct = c.syscall(286, usermem, passmem,userlength, passlength); if(correct == 1) { User newu = new User(usern); panel.setCurlevel(0); panel.setCurUser(newu); panel.switchUser(); }//end else if statement else { JOptionPane.showMessageDialog(panel, "The username and password entered do not match.\nPlease try again."); panel.logout(); }//end else statement }//end if statement else if(e.getSource()==create) { panel.switchNew(); }//end else if statement else { panel.setCurlevel(4); panel.switchView(true); User usere = new User("Everyone"); panel.setCurUser(usere); }//end else statement }//end ActionPerformed method
diff --git a/plugins/org.python.pydev/src/org/python/pydev/ui/pythonpathconf/MyEnvWorkingCopy.java b/plugins/org.python.pydev/src/org/python/pydev/ui/pythonpathconf/MyEnvWorkingCopy.java index 912eb5090..ed4be70c5 100644 --- a/plugins/org.python.pydev/src/org/python/pydev/ui/pythonpathconf/MyEnvWorkingCopy.java +++ b/plugins/org.python.pydev/src/org/python/pydev/ui/pythonpathconf/MyEnvWorkingCopy.java @@ -1,411 +1,415 @@ package org.python.pydev.ui.pythonpathconf; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.ILaunchDelegate; import org.eclipse.debug.core.ILaunchManager; @SuppressWarnings("unchecked") public class MyEnvWorkingCopy implements ILaunchConfigurationWorkingCopy { private Map<String, Object> attributes = new HashMap<String, Object>(); private InterpreterInfo info; public void setInfo(InterpreterInfo info) { this.attributes.clear(); this.info = info; HashMap<String, String> map = new HashMap<String, String>(); String[] envVariables = info.getEnvVariables(); if(envVariables != null){ InterpreterInfo.fillMapWithEnv(envVariables, map); this.attributes.put(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, map); }else{ this.attributes.remove(ILaunchManager.ATTR_APPEND_ENVIRONMENT_VARIABLES); } this.attributes.put(ILaunchManager.ATTR_APPEND_ENVIRONMENT_VARIABLES, true); } public InterpreterInfo getInfo() { return this.info; } private void updateInfo() { if(info == null){ //no info set, nothing to do return; } - HashMap<String, String> map = new HashMap<String, String>((Map)this.attributes.get(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES)); + Map existing = (Map)this.attributes.get(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES); + HashMap<String, String> map = null; + if(existing != null){ + map = new HashMap<String, String>(existing); + } //The interpreter info should never contain the PYTHONPATH, as it's managed from other places and not env. attributes. InterpreterInfo.removePythonPathFromEnvMapWithWarning(map); if(map == null){ info.setEnvVariables(null); }else{ info.setEnvVariables(InterpreterInfo.createEnvWithMap(map)); } } public void addModes(Set modes) { throw new RuntimeException(); } public ILaunchConfiguration doSave() throws CoreException { throw new RuntimeException(); } public ILaunchConfiguration getOriginal() { return this; } public ILaunchConfigurationWorkingCopy getParent() { return null; } public boolean isDirty() { throw new RuntimeException(); } public Object removeAttribute(String attributeName) { Object ret = this.attributes.remove(attributeName); if(attributeName.equals(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES)){ updateInfo(); } return ret; } public void removeModes(Set modes) { throw new RuntimeException(); } public void rename(String name) { throw new RuntimeException(); } public void setAttribute(String attributeName, int value) { this.attributes.put(attributeName, value); if(attributeName.equals(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES)){ updateInfo(); } } public void setAttribute(String attributeName, String value) { this.attributes.put(attributeName, value); if(attributeName.equals(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES)){ updateInfo(); } } public void setAttribute(String attributeName, List value) { this.attributes.put(attributeName, value); if(attributeName.equals(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES)){ updateInfo(); } } public void setAttribute(String attributeName, Map value) { this.attributes.put(attributeName, value); if(attributeName.equals(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES)){ updateInfo(); } } public void setAttribute(String attributeName, boolean value) { this.attributes.put(attributeName, value); if(attributeName.equals(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES)){ updateInfo(); } } public void setAttributes(Map attributes) { this.attributes.clear(); if(attributes != null){ } Set<Map.Entry> entrySet = attributes.entrySet(); for (Map.Entry entry : entrySet) { this.attributes.put((String)entry.getKey(), entry.getValue()); } updateInfo(); } public void setContainer(IContainer container) { throw new RuntimeException(); } public void setMappedResources(IResource[] resources) { throw new RuntimeException(); } public void setModes(Set modes) { throw new RuntimeException(); } public void setPreferredLaunchDelegate(Set modes, String delegateId) { throw new RuntimeException(); } public boolean contentsEqual(ILaunchConfiguration configuration) { throw new RuntimeException(); } public ILaunchConfigurationWorkingCopy copy(String name) throws CoreException { throw new RuntimeException(); } public void delete() throws CoreException { throw new RuntimeException(); } public boolean exists() { throw new RuntimeException(); } public boolean getAttribute(String attributeName, boolean defaultValue) throws CoreException { if(this.attributes.containsKey(attributeName)){ return (Boolean) this.attributes.get(attributeName); } return defaultValue; } public int getAttribute(String attributeName, int defaultValue) throws CoreException { if(this.attributes.containsKey(attributeName)){ return (Integer) this.attributes.get(attributeName); } return defaultValue; } public List getAttribute(String attributeName, List defaultValue) throws CoreException { if(this.attributes.containsKey(attributeName)){ return (List) this.attributes.get(attributeName); } return defaultValue; } public Set getAttribute(String attributeName, Set defaultValue) throws CoreException { if(this.attributes.containsKey(attributeName)){ return (Set) this.attributes.get(attributeName); } return defaultValue; } public Map getAttribute(String attributeName, Map defaultValue) throws CoreException { if(this.attributes.containsKey(attributeName)){ return (Map) this.attributes.get(attributeName); } return defaultValue; } public String getAttribute(String attributeName, String defaultValue) throws CoreException { if(this.attributes.containsKey(attributeName)){ return (String) this.attributes.get(attributeName); } return defaultValue; } public Map getAttributes() throws CoreException { return this.attributes; } public String getCategory() throws CoreException { throw new RuntimeException(); } public IFile getFile() { throw new RuntimeException(); } public IPath getLocation() { throw new RuntimeException(); } public IResource[] getMappedResources() throws CoreException { throw new RuntimeException(); } public String getMemento() throws CoreException { throw new RuntimeException(); } public Set getModes() throws CoreException { throw new RuntimeException(); } public String getName() { throw new RuntimeException(); } public ILaunchDelegate getPreferredDelegate(Set modes) throws CoreException { throw new RuntimeException(); } public ILaunchConfigurationType getType() throws CoreException { throw new RuntimeException(); } public ILaunchConfigurationWorkingCopy getWorkingCopy() throws CoreException { throw new RuntimeException(); } public boolean hasAttribute(String attributeName) throws CoreException { return this.attributes.containsKey(attributeName); } public boolean isLocal() { throw new RuntimeException(); } public boolean isMigrationCandidate() throws CoreException { return false; } public boolean isReadOnly() { return false; } public boolean isWorkingCopy() { return true; } public ILaunch launch(String mode, IProgressMonitor monitor) throws CoreException { throw new RuntimeException(); } public ILaunch launch(String mode, IProgressMonitor monitor, boolean build) throws CoreException { throw new RuntimeException(); } public ILaunch launch(String mode, IProgressMonitor monitor, boolean build, boolean register) throws CoreException { throw new RuntimeException(); } public void migrate() throws CoreException { throw new RuntimeException(); } public boolean supportsMode(String mode) throws CoreException { throw new RuntimeException(); } public Object getAdapter(Class adapter) { throw new RuntimeException(); } }
true
true
private void updateInfo() { if(info == null){ //no info set, nothing to do return; } HashMap<String, String> map = new HashMap<String, String>((Map)this.attributes.get(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES)); //The interpreter info should never contain the PYTHONPATH, as it's managed from other places and not env. attributes. InterpreterInfo.removePythonPathFromEnvMapWithWarning(map); if(map == null){ info.setEnvVariables(null); }else{ info.setEnvVariables(InterpreterInfo.createEnvWithMap(map)); } }
private void updateInfo() { if(info == null){ //no info set, nothing to do return; } Map existing = (Map)this.attributes.get(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES); HashMap<String, String> map = null; if(existing != null){ map = new HashMap<String, String>(existing); } //The interpreter info should never contain the PYTHONPATH, as it's managed from other places and not env. attributes. InterpreterInfo.removePythonPathFromEnvMapWithWarning(map); if(map == null){ info.setEnvVariables(null); }else{ info.setEnvVariables(InterpreterInfo.createEnvWithMap(map)); } }
diff --git a/common/net/minecraftforge/fluids/FluidRegistry.java b/common/net/minecraftforge/fluids/FluidRegistry.java index 0eb95ca36..5031fa62b 100644 --- a/common/net/minecraftforge/fluids/FluidRegistry.java +++ b/common/net/minecraftforge/fluids/FluidRegistry.java @@ -1,158 +1,158 @@ package net.minecraftforge.fluids; import java.util.HashMap; import java.util.Map; import net.minecraft.block.Block; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.Event; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableMap; /** * Handles Fluid registrations. Fluids MUST be registered in order to function. * * @author King Lemming, CovertJaguar (LiquidDictionary) * */ public abstract class FluidRegistry { static int maxID = 0; static HashMap<String, Fluid> fluids = new HashMap(); static BiMap<String, Integer> fluidIDs = HashBiMap.create(); static BiMap<Block, Fluid> fluidBlocks; public static final Fluid WATER = new Fluid("water").setBlockID(Block.waterStill.blockID).setUnlocalizedName(Block.waterStill.getUnlocalizedName()); public static final Fluid LAVA = new Fluid("lava").setBlockID(Block.lavaStill.blockID).setLuminosity(15).setDensity(3000).setViscosity(6000).setTemperature(1300).setUnlocalizedName(Block.lavaStill.getUnlocalizedName()); public static int renderIdFluid = -1; static { registerFluid(WATER); registerFluid(LAVA); } private FluidRegistry(){} /** * Called by Forge to prepare the ID map for server -> client sync. */ static void initFluidIDs(BiMap<String, Integer> newfluidIDs) { maxID = newfluidIDs.size(); fluidIDs.clear(); fluidIDs.putAll(newfluidIDs); } /** * Register a new Fluid. If a fluid with the same name already exists, registration is denied. * * @param fluid * The fluid to register. * @return True if the fluid was successfully registered; false if there is a name clash. */ public static boolean registerFluid(Fluid fluid) { if (fluidIDs.containsKey(fluid.getName())) { return false; } fluids.put(fluid.getName(), fluid); fluidIDs.put(fluid.getName(), ++maxID); MinecraftForge.EVENT_BUS.post(new FluidRegisterEvent(fluid.getName(), maxID)); return true; } public static boolean isFluidRegistered(Fluid fluid) { return fluidIDs.containsKey(fluid.getName()); } public static boolean isFluidRegistered(String fluidName) { return fluidIDs.containsKey(fluidName); } public static Fluid getFluid(String fluidName) { return fluids.get(fluidName); } public static Fluid getFluid(int fluidID) { return fluids.get(getFluidName(fluidID)); } public static String getFluidName(int fluidID) { return fluidIDs.inverse().get(fluidID); } public static String getFluidName(FluidStack stack) { return getFluidName(stack.fluidID); } public static int getFluidID(String fluidName) { return fluidIDs.get(fluidName); } public static FluidStack getFluidStack(String fluidName, int amount) { if (!fluidIDs.containsKey(fluidName)) { return null; } return new FluidStack(getFluidID(fluidName), amount); } /** * Returns a read-only map containing Fluid Names and their associated Fluids. */ public static Map<String, Fluid> getRegisteredFluids() { return ImmutableMap.copyOf(fluids); } /** * Returns a read-only map containing Fluid Names and their associated IDs. */ public static Map<String, Integer> getRegisteredFluidIDs() { return ImmutableMap.copyOf(fluidIDs); } public static Fluid lookupFluidForBlock(Block block) { if (fluidBlocks == null) { - fluidBlocks = new BiMap<Block, Fluid>(); + fluidBlocks = HashBiMap.create(); for (Fluid fluid : fluids.values()) { if (fluid.canBePlacedInWorld() && Block.blocksList[fluid.getBlockID()] != null) { fluidBlocks.put(Block.blocksList[fluid.getBlockID()], fluid); } } } return fluidBlocks.get(block); } public static class FluidRegisterEvent extends Event { public final String fluidName; public final int fluidID; public FluidRegisterEvent(String fluidName, int fluidID) { this.fluidName = fluidName; this.fluidID = fluidID; } } }
true
true
public static Fluid lookupFluidForBlock(Block block) { if (fluidBlocks == null) { fluidBlocks = new BiMap<Block, Fluid>(); for (Fluid fluid : fluids.values()) { if (fluid.canBePlacedInWorld() && Block.blocksList[fluid.getBlockID()] != null) { fluidBlocks.put(Block.blocksList[fluid.getBlockID()], fluid); } } } return fluidBlocks.get(block); }
public static Fluid lookupFluidForBlock(Block block) { if (fluidBlocks == null) { fluidBlocks = HashBiMap.create(); for (Fluid fluid : fluids.values()) { if (fluid.canBePlacedInWorld() && Block.blocksList[fluid.getBlockID()] != null) { fluidBlocks.put(Block.blocksList[fluid.getBlockID()], fluid); } } } return fluidBlocks.get(block); }
diff --git a/src/edgruberman/bukkit/waterfix/Main.java b/src/edgruberman/bukkit/waterfix/Main.java index 4caba7a..30229d0 100644 --- a/src/edgruberman/bukkit/waterfix/Main.java +++ b/src/edgruberman/bukkit/waterfix/Main.java @@ -1,46 +1,46 @@ package edgruberman.bukkit.waterfix; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.plugin.java.JavaPlugin; public final class Main extends JavaPlugin implements Listener { private static final byte WATER_FULL = 0; @Override public void onEnable() { this.getServer().getPluginManager().registerEvents(this, this); } @EventHandler(ignoreCancelled = true) public void onBlockFromTo(final BlockFromToEvent event) { final Block from = event.getBlock(); if (from.getTypeId() != Material.STATIONARY_WATER.getId() || from.getData() != Main.WATER_FULL) return; final Block to = event.getToBlock(); if (to.getTypeId() != Material.AIR.getId()) return; // At least one additional, besides original from block, full water source must be directly adjacent for (final BlockFace direction : new BlockFace[] { BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST }) { final int adjacentX = to.getX() + direction.getModX(); final int adjacentY = to.getY() + direction.getModY(); final int adjacentZ = to.getZ() + direction.getModZ(); if (from.getX() == adjacentX && from.getY() == adjacentY && from.getZ() == adjacentZ) continue; if (to.getWorld().getBlockTypeIdAt(adjacentX, adjacentY, adjacentZ) != Material.WATER.getId()) continue; if (to.getRelative(direction).getData() != Main.WATER_FULL) continue; - to.setTypeIdAndData(Material.STATIONARY_WATER.getId(), (byte) 0, true); + to.setTypeIdAndData(Material.STATIONARY_WATER.getId(), Main.WATER_FULL, true); event.setCancelled(true); break; } } }
true
true
public void onBlockFromTo(final BlockFromToEvent event) { final Block from = event.getBlock(); if (from.getTypeId() != Material.STATIONARY_WATER.getId() || from.getData() != Main.WATER_FULL) return; final Block to = event.getToBlock(); if (to.getTypeId() != Material.AIR.getId()) return; // At least one additional, besides original from block, full water source must be directly adjacent for (final BlockFace direction : new BlockFace[] { BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST }) { final int adjacentX = to.getX() + direction.getModX(); final int adjacentY = to.getY() + direction.getModY(); final int adjacentZ = to.getZ() + direction.getModZ(); if (from.getX() == adjacentX && from.getY() == adjacentY && from.getZ() == adjacentZ) continue; if (to.getWorld().getBlockTypeIdAt(adjacentX, adjacentY, adjacentZ) != Material.WATER.getId()) continue; if (to.getRelative(direction).getData() != Main.WATER_FULL) continue; to.setTypeIdAndData(Material.STATIONARY_WATER.getId(), (byte) 0, true); event.setCancelled(true); break; } }
public void onBlockFromTo(final BlockFromToEvent event) { final Block from = event.getBlock(); if (from.getTypeId() != Material.STATIONARY_WATER.getId() || from.getData() != Main.WATER_FULL) return; final Block to = event.getToBlock(); if (to.getTypeId() != Material.AIR.getId()) return; // At least one additional, besides original from block, full water source must be directly adjacent for (final BlockFace direction : new BlockFace[] { BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST }) { final int adjacentX = to.getX() + direction.getModX(); final int adjacentY = to.getY() + direction.getModY(); final int adjacentZ = to.getZ() + direction.getModZ(); if (from.getX() == adjacentX && from.getY() == adjacentY && from.getZ() == adjacentZ) continue; if (to.getWorld().getBlockTypeIdAt(adjacentX, adjacentY, adjacentZ) != Material.WATER.getId()) continue; if (to.getRelative(direction).getData() != Main.WATER_FULL) continue; to.setTypeIdAndData(Material.STATIONARY_WATER.getId(), Main.WATER_FULL, true); event.setCancelled(true); break; } }
diff --git a/src/java/davmail/imap/ImapConnection.java b/src/java/davmail/imap/ImapConnection.java index 474530b..d404d02 100644 --- a/src/java/davmail/imap/ImapConnection.java +++ b/src/java/davmail/imap/ImapConnection.java @@ -1,1488 +1,1488 @@ /* * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway * Copyright (C) 2009 Mickael Guessant * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package davmail.imap; import com.sun.mail.imap.protocol.BASE64MailboxDecoder; import com.sun.mail.imap.protocol.BASE64MailboxEncoder; import davmail.AbstractConnection; import davmail.BundleMessage; import davmail.exception.DavMailException; import davmail.exception.HttpForbiddenException; import davmail.exception.HttpNotFoundException; import davmail.exchange.ExchangeSession; import davmail.exchange.ExchangeSessionFactory; import davmail.ui.tray.DavGatewayTray; import davmail.util.StringUtil; import org.apache.commons.httpclient.HttpException; import javax.mail.MessagingException; import javax.mail.internet.*; import java.io.*; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Dav Gateway smtp connection implementation. * Still alpha code : need to find a way to handle message ids */ public class ImapConnection extends AbstractConnection { ExchangeSession.Folder currentFolder; /** * Initialize the streams and start the thread. * * @param clientSocket IMAP client socket */ public ImapConnection(Socket clientSocket) { super(ImapConnection.class.getSimpleName(), clientSocket, null); } @Override public void run() { String line; String commandId = null; IMAPTokenizer tokens; try { ExchangeSessionFactory.checkConfig(); sendClient("* OK [CAPABILITY IMAP4REV1 AUTH=LOGIN] IMAP4rev1 DavMail server ready"); for (; ;) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new IMAPTokenizer(line); if (tokens.hasMoreTokens()) { commandId = tokens.nextToken(); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); if ("LOGOUT".equalsIgnoreCase(command)) { sendClient("* BYE Closing connection"); break; } if ("capability".equalsIgnoreCase(command)) { sendClient("* CAPABILITY IMAP4REV1 AUTH=LOGIN"); sendClient(commandId + " OK CAPABILITY completed"); } else if ("login".equalsIgnoreCase(command)) { parseCredentials(tokens); try { session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else if ("AUTHENTICATE".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String authenticationMethod = tokens.nextToken(); if ("LOGIN".equalsIgnoreCase(authenticationMethod)) { try { sendClient("+ " + base64Encode("Username:")); state = State.LOGIN; userName = base64Decode(readClient()); sendClient("+ " + base64Encode("Password:")); state = State.PASSWORD; password = base64Decode(readClient()); session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else { sendClient(commandId + " NO unsupported authentication method"); } } else { sendClient(commandId + " BAD authentication method required"); } } else { if (state != State.AUTHENTICATED) { sendClient(commandId + " BAD command authentication required"); } else { // check for expired session session = ExchangeSessionFactory.getInstance(session, userName, password); if ("lsub".equalsIgnoreCase(command) || "list".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderContext = BASE64MailboxDecoder.decode(tokens.nextToken()); if (tokens.hasMoreTokens()) { String folderQuery = folderContext + BASE64MailboxDecoder.decode(tokens.nextToken()); if (folderQuery.endsWith("%/%") && !"/%/%".equals(folderQuery)) { List<ExchangeSession.Folder> folders = session.getSubFolders(folderQuery.substring(0, folderQuery.length() - 3), false); for (ExchangeSession.Folder folder : folders) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendSubFolders(command, folder.folderPath, false); } sendClient(commandId + " OK " + command + " completed"); } else if (folderQuery.endsWith("%") || folderQuery.endsWith("*")) { if ("/*".equals(folderQuery) || "/%".equals(folderQuery) || "/%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(1); if ("%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(0, folderQuery.length() - 2); } sendClient("* " + command + " (\\HasChildren) \"/\" \"/public\""); } if ("*%".equals(folderQuery)) { folderQuery = "*"; } boolean recursive = folderQuery.endsWith("*") && !folderQuery.startsWith("/public"); sendSubFolders(command, folderQuery.substring(0, folderQuery.length() - 1), recursive); sendClient(commandId + " OK " + command + " completed"); } else { ExchangeSession.Folder folder = null; try { folder = session.getFolder(folderQuery); } catch (HttpForbiddenException e) { // access forbidden, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_FORBIDDEN", folderQuery)); } catch (HttpNotFoundException e) { // not found, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_NOT_FOUND", folderQuery)); } catch (HttpException e) { // other errors, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR", folderQuery, e.getMessage())); } if (folder != null) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendClient(commandId + " OK " + command + " completed"); } else { sendClient(commandId + " NO Folder not found"); } } } else { sendClient(commandId + " BAD missing folder argument"); } } else { sendClient(commandId + " BAD missing folder argument"); } } else if ("select".equalsIgnoreCase(command) || "examine".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { currentFolder = session.getFolder(folderName); currentFolder.loadMessages(); sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.count() + " RECENT"); sendClient("* OK [UIDVALIDITY 1]"); if (currentFolder.count() == 0) { sendClient("* OK [UIDNEXT 1]"); } else { sendClient("* OK [UIDNEXT " + currentFolder.getUidNext() + ']'); } sendClient("* FLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)"); sendClient("* OK [PERMANENTFLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk \\*)]"); if ("select".equalsIgnoreCase(command)) { sendClient(commandId + " OK [READ-WRITE] " + command + " completed"); } else { sendClient(commandId + " OK [READ-ONLY] " + command + " completed"); } } catch (HttpNotFoundException e) { sendClient(commandId + " NO Not found"); } catch (HttpForbiddenException e) { sendClient(commandId + " NO Forbidden"); } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("expunge".equalsIgnoreCase(command)) { expunge(false); // need to refresh folder to avoid 404 errors session.refreshFolder(currentFolder); sendClient(commandId + " OK " + command + " completed"); } else if ("close".equalsIgnoreCase(command)) { expunge(true); // deselect folder currentFolder = null; sendClient(commandId + " OK " + command + " completed"); } else if ("create".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); session.createMessageFolder(folderName); sendClient(commandId + " OK folder created"); } else { sendClient(commandId + " BAD missing create argument"); } } else if ("rename".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.moveFolder(folderName, targetName); sendClient(commandId + " OK rename completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("delete".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.deleteFolder(folderName); sendClient(commandId + " OK delete completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("uid".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String subcommand = tokens.nextToken(); if ("fetch".equalsIgnoreCase(subcommand)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { String ranges = tokens.nextToken(); if (ranges == null) { sendClient(commandId + " BAD missing range parameter"); } else { String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, ranges); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); try { handleFetch(message, uidRangeIterator.currentIndex, parameters); } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK UID FETCH completed"); } } } else if ("search".equalsIgnoreCase(subcommand)) { List<Long> uidList = handleSearch(tokens); for (long uid : uidList) { sendClient("* SEARCH " + uid); } sendClient(commandId + " OK SEARCH completed"); } else if ("store".equalsIgnoreCase(subcommand)) { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, uidRangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(subcommand)) { try { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); session.copyMessage(message, targetName); } sendClient(commandId + " OK copy completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("search".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { List<Long> uidList = handleSearch(tokens); int currentIndex = 0; for (ExchangeSession.Message message : currentFolder.messages) { currentIndex++; if (uidList.contains(message.getImapUid())) { sendClient("* SEARCH " + currentIndex); } } sendClient(commandId + " OK SEARCH completed"); } } else if ("fetch".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); try { handleFetch(message, rangeIterator.currentIndex, parameters); } catch (SocketException e) { // client closed connection, rethrow exception throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK FETCH completed"); } } else if ("store".equalsIgnoreCase(command)) { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, rangeIterator, action, flags); } else if ("append".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); HashMap<String, String> properties = new HashMap<String, String>(); String flags = null; String date = null; // handle optional flags String nextToken = tokens.nextQuotedToken(); if (nextToken.startsWith("(")) { flags = removeQuotes(nextToken); if (tokens.hasMoreTokens()) { nextToken = tokens.nextToken(); if (tokens.hasMoreTokens()) { date = nextToken; nextToken = tokens.nextToken(); } } } else if (tokens.hasMoreTokens()) { date = removeQuotes(nextToken); nextToken = tokens.nextToken(); } if (flags != null) { StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equals(flag)) { properties.put("read", "1"); } else if ("\\Flagged".equals(flag)) { properties.put("flagged", "2"); } else if ("\\Answered".equals(flag)) { properties.put("answered", "102"); } else if ("$Forwarded".equals(flag)) { properties.put("forwarded", "104"); } else if ("\\Draft".equals(flag)) { properties.put("draft", "9"); } else if ("Junk".equals(flag)) { properties.put("junk", "1"); } } } // handle optional date if (date != null) { SimpleDateFormat dateParser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH); Date dateReceived = dateParser.parse(date); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE); properties.put("datereceived", dateFormatter.format(dateReceived)); } int size = Integer.parseInt(nextToken); sendClient("+ send literal data"); char[] buffer = new char[size]; int index = 0; int count = 0; while (count >= 0 && index < size) { count = in.read(buffer, index, size - index); if (count >= 0) { index += count; } } // empty line readClient(); String messageName = UUID.randomUUID().toString(); session.createMessage(folderName, messageName, properties, new String(buffer)); sendClient(commandId + " OK APPEND completed"); } else if ("noop".equalsIgnoreCase(command) || "check".equalsIgnoreCase(command)) { if (currentFolder != null) { DavGatewayTray.debug(new BundleMessage("LOG_IMAP_COMMAND", command, currentFolder.folderName)); ExchangeSession.MessageList currentMessages = currentFolder.messages; if (session.refreshFolder(currentFolder)) { // build new uid set HashSet<Long> uidSet = new HashSet<Long>(); for (ExchangeSession.Message message : currentFolder.messages) { uidSet.add(message.getImapUid()); } // send expunge untagged response for removed IMAP message uids // note: some STORE commands trigger a uid change in Exchange, // thus those messages are expunged and reappear with a new uid int index = 1; for (ExchangeSession.Message message : currentMessages) { if (!uidSet.contains(message.getImapUid())) { sendClient("* " + index + " EXPUNGE"); } else { index++; } } sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.count() + " RECENT"); } } sendClient(commandId + " OK " + command + " completed"); } else if ("subscribe".equalsIgnoreCase(command) || "unsubscribe".equalsIgnoreCase(command)) { sendClient(commandId + " OK " + command + " completed"); } else if ("status".equalsIgnoreCase(command)) { try { String encodedFolderName = tokens.nextToken(); String folderName = BASE64MailboxDecoder.decode(encodedFolderName); ExchangeSession.Folder folder = session.getFolder(folderName); // must retrieve messages folder.loadMessages(); String parameters = tokens.nextToken(); StringBuilder answer = new StringBuilder(); StringTokenizer parametersTokens = new StringTokenizer(parameters); while (parametersTokens.hasMoreTokens()) { String token = parametersTokens.nextToken(); if ("MESSAGES".equalsIgnoreCase(token)) { answer.append("MESSAGES ").append(folder.count()).append(' '); } if ("RECENT".equalsIgnoreCase(token)) { answer.append("RECENT ").append(folder.count()).append(' '); } if ("UIDNEXT".equalsIgnoreCase(token)) { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { answer.append("UIDNEXT ").append(folder.getUidNext()).append(' '); } } } if ("UIDVALIDITY".equalsIgnoreCase(token)) { answer.append("UIDVALIDITY 1 "); } if ("UNSEEN".equalsIgnoreCase(token)) { answer.append("UNSEEN ").append(folder.unreadCount).append(' '); } } - sendClient("* STATUS " + encodedFolderName + " (" + answer.toString().trim() + ')'); + sendClient("* STATUS \"" + encodedFolderName + "\" (" + answer.toString().trim() + ')'); sendClient(commandId + " OK " + command + " completed"); } catch (HttpException e) { sendClient(commandId + " NO folder not found"); } } else { sendClient(commandId + " BAD command unrecognized"); } } } } else { sendClient(commandId + " BAD missing command"); } } else { sendClient("BAD Null command"); } DavGatewayTray.resetIcon(); } os.flush(); } catch (SocketTimeoutException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT")); try { sendClient("* BYE Closing connection"); } catch (IOException e1) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_CLOSING_CONNECTION_ON_TIMEOUT")); } } catch (SocketException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLIENT_CLOSED_CONNECTION")); } catch (Exception e) { DavGatewayTray.log(e); try { String message = ((e.getMessage() == null) ? e.toString() : e.getMessage()).replaceAll("\\n", " "); if (commandId != null) { sendClient(commandId + " BAD unable to handle request: " + message); } else { sendClient("* BYE unable to handle request: " + message); } } catch (IOException e2) { DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); } private void handleFetch(ExchangeSession.Message message, int currentIndex, String parameters) throws IOException, MessagingException { StringBuilder buffer = new StringBuilder(); buffer.append("* ").append(currentIndex).append(" FETCH (UID ").append(message.getImapUid()); if (parameters != null) { StringTokenizer paramTokens = new StringTokenizer(parameters); while (paramTokens.hasMoreTokens()) { String param = paramTokens.nextToken(); if ("FLAGS".equals(param)) { buffer.append(" FLAGS (").append(message.getImapFlags()).append(')'); } else if ("ENVELOPE".equals(param)) { appendEnvelope(buffer, message); } else if ("BODYSTRUCTURE".equals(param)) { appendBodyStructure(buffer, message); } else if ("INTERNALDATE".equals(param) && message.date != null && message.date.length() > 0) { try { SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateParser.setTimeZone(ExchangeSession.GMT_TIMEZONE); Date date = dateParser.parse(message.date); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH); buffer.append(" INTERNALDATE \"").append(dateFormatter.format(date)).append('\"'); } catch (ParseException e) { throw new DavMailException("EXCEPTION_INVALID_DATE", message.date); } } else if ("BODY.PEEK[HEADER]".equals(param) || param.startsWith("BODY.PEEK[HEADER") || "RFC822.HEADER".equals(param)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PartOutputStream partOutputStream = new PartOutputStream(baos, true, false, 0); message.write(partOutputStream); baos.close(); buffer.append(" RFC822.SIZE ").append(partOutputStream.size); if ("BODY.PEEK[HEADER]".equals(param)) { buffer.append(" BODY[HEADER] {"); } else if ("RFC822.HEADER".equals(param)) { buffer.append(" RFC822.HEADER {"); } else { buffer.append(" BODY[HEADER.FIELDS ()] {"); } buffer.append(baos.size()).append('}'); sendClient(buffer.toString()); os.write(baos.toByteArray()); os.flush(); buffer.setLength(0); } else if (param.startsWith("BODY[]") || param.startsWith("BODY.PEEK[]") || param.startsWith("BODY[TEXT]") || "BODY.PEEK[TEXT]".equals(param)) { // parse buffer size int startIndex = 0; int ltIndex = param.indexOf('<'); if (ltIndex >= 0) { int dotIndex = param.indexOf('.', ltIndex); if (dotIndex >= 0) { startIndex = Integer.parseInt(param.substring(ltIndex + 1, dotIndex)); // ignore buffer size } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean writeHeaders = true; int rfc822size; if ("BODY.PEEK[TEXT]".equals(param)) { writeHeaders = false; } PartOutputStream bodyOutputStream = new PartOutputStream(baos, writeHeaders, true, startIndex); message.write(bodyOutputStream); rfc822size = bodyOutputStream.size; baos.close(); buffer.append(" RFC822.SIZE ").append(rfc822size).append(' '); if ("BODY.PEEK[TEXT]".equals(param)) { buffer.append("BODY[TEXT]"); } else { buffer.append("BODY[]"); } // partial if (startIndex > 0) { buffer.append('<').append(startIndex).append('>'); } buffer.append(" {").append(baos.size()).append('}'); sendClient(buffer.toString()); os.write(baos.toByteArray()); os.flush(); buffer.setLength(0); } else if (param.startsWith("BODY[")) { int partIndex = 0; // try to parse message part index String partIndexString = StringUtil.getToken(param, "[", "]"); if (partIndexString != null) { try { partIndex = Integer.parseInt(partIndexString); } catch (NumberFormatException e) { throw new DavMailException("EXCEPTION_UNSUPPORTED_PARAMETER", param); } } if (partIndex == 0) { throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param); } MimeMessage mimeMessage = message.getMimeMessage(); Object mimeBody = mimeMessage.getContent(); MimePart bodyPart; if (mimeBody instanceof MimeMultipart) { MimeMultipart multiPart = (MimeMultipart) mimeBody; bodyPart = (MimePart) multiPart.getBodyPart(partIndex - 1); } else if (partIndex == 1) { // no multipart, single body bodyPart = mimeMessage; } else { throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); bodyPart.getDataHandler().writeTo(baos); baos.close(); buffer.append(" {").append(baos.size()).append('}'); sendClient(buffer.toString()); os.write(baos.toByteArray()); os.flush(); buffer.setLength(0); } } } buffer.append(')'); sendClient(buffer.toString()); // do not keep message content in memory message.dropMimeMessage(); } protected void handleStore(String commandId, AbstractRangeIterator rangeIterator, String action, String flags) throws IOException { while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); updateFlags(message, action, flags); sendClient("* " + (rangeIterator.getCurrentIndex()) + " FETCH (UID " + message.getImapUid() + " FLAGS (" + (message.getImapFlags()) + "))"); } sendClient(commandId + " OK STORE completed"); } protected List<Long> handleSearch(IMAPTokenizer tokens) throws IOException { List<Long> uidList = new ArrayList<Long>(); SearchConditions conditions = new SearchConditions(); conditions.append("AND ("); boolean or = false; while (tokens.hasMoreTokens()) { String token = tokens.nextToken().toUpperCase(); if ("OR".equals(token)) { or = true; } else if (token.startsWith("OR ")) { or = true; appendOrSearchParams(token, conditions); } else { String operator; if (conditions.query.length() == 5) { operator = ""; } else if (or) { operator = " OR "; } else { operator = " AND "; } appendSearchParam(operator, tokens, token, conditions); } } conditions.append(")"); String query = conditions.query.toString(); DavGatewayTray.debug(new BundleMessage("LOG_SEARCH_QUERY", conditions.query)); if ("AND ()".equals(query)) { query = null; } ExchangeSession.MessageList localMessages = currentFolder.searchMessages(query); int index = 1; for (ExchangeSession.Message message : localMessages) { if ((conditions.deleted == null || message.deleted == conditions.deleted) && (conditions.flagged == null || message.flagged == conditions.flagged) && (conditions.answered == null || message.answered == conditions.answered) && (conditions.startUid == 0 || message.getImapUid() >= conditions.startUid) && (conditions.startIndex == 0 || (index++ >= conditions.startIndex)) ) { uidList.add(message.getImapUid()); } } return uidList; } protected void appendEnvelope(StringBuilder buffer, ExchangeSession.Message message) throws IOException { buffer.append(" ENVELOPE ("); try { MimeMessage mimeMessage = message.getMimeMessage(); // Envelope for date, subject, from, sender, reply-to, to, cc, bcc,in-reply-to, message-id appendEnvelopeHeader(buffer, mimeMessage.getHeader("Date")); appendEnvelopeHeader(buffer, mimeMessage.getHeader("Subject")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("From", ",")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("Sender", ",")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("Reply-To", ",")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("CC", ",")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("BCC", ",")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("In-Reply-To", ",")); appendEnvelopeHeader(buffer, mimeMessage.getHeader("Messagee-Id")); } catch (MessagingException me) { DavGatewayTray.warn(me); // send fake envelope buffer.append(" NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL"); } buffer.append(')'); } protected void appendEnvelopeHeader(StringBuilder buffer, String[] value) { buffer.append(' '); if (value != null && value.length > 0) { String unfoldedValue = MimeUtility.unfold(value[0]); if (unfoldedValue.indexOf('"') >= 0) { buffer.append('{'); buffer.append(unfoldedValue.length()); buffer.append("}\r\n"); buffer.append(unfoldedValue); } else { buffer.append('"'); buffer.append(unfoldedValue); buffer.append('"'); } } else { buffer.append("NIL"); } } protected void appendMailEnvelopeHeader(StringBuilder buffer, String value) { buffer.append(' '); if (value != null) { try { InternetAddress[] addresses = InternetAddress.parseHeader(value, false); buffer.append('('); for (InternetAddress address : addresses) { buffer.append('('); String personal = address.getPersonal(); if (personal != null) { buffer.append('"').append(MimeUtility.encodeText(personal)).append('"'); } else { buffer.append("NIL"); } buffer.append(" NIL "); String mail = address.getAddress(); int atIndex = mail.indexOf('@'); if (atIndex >= 0) { buffer.append('"').append(mail.substring(0, atIndex)).append('"'); buffer.append(' '); buffer.append('"').append(mail.substring(atIndex + 1)).append('"'); } else { buffer.append("NIL NIL"); } buffer.append(')'); } buffer.append(')'); } catch (AddressException e) { DavGatewayTray.warn(e); buffer.append("NIL"); } catch (UnsupportedEncodingException e) { DavGatewayTray.warn(e); buffer.append("NIL"); } } else { buffer.append("NIL"); } } protected void appendBodyStructure(StringBuilder buffer, ExchangeSession.Message message) throws IOException { buffer.append(" BODYSTRUCTURE "); try { MimeMessage mimeMessage = message.getMimeMessage(); Object mimeBody = mimeMessage.getContent(); if (mimeBody instanceof MimeMultipart) { buffer.append('('); MimeMultipart multiPart = (MimeMultipart) mimeBody; for (int i = 0; i < multiPart.getCount(); i++) { MimeBodyPart bodyPart = (MimeBodyPart) multiPart.getBodyPart(i); appendBodyStructure(buffer, bodyPart); } int slashIndex = multiPart.getContentType().indexOf('/'); if (slashIndex < 0) { throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", multiPart.getContentType()); } int semiColonIndex = multiPart.getContentType().indexOf(';'); if (semiColonIndex < 0) { buffer.append(" \"").append(multiPart.getContentType().substring(slashIndex + 1).toUpperCase()).append("\")"); } else { buffer.append(" \"").append(multiPart.getContentType().substring(slashIndex + 1, semiColonIndex).trim().toUpperCase()).append("\")"); } } else { // no multipart, single body appendBodyStructure(buffer, mimeMessage); } } catch (UnsupportedEncodingException e) { DavGatewayTray.warn(e); // failover: send default bodystructure buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)"); } catch (MessagingException me) { DavGatewayTray.warn(me); // failover: send default bodystructure buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)"); } } protected void appendBodyStructure(StringBuilder buffer, MimePart bodyPart) throws IOException, MessagingException { String contentType = bodyPart.getContentType(); int slashIndex = contentType.indexOf('/'); if (slashIndex < 0) { throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", contentType); } buffer.append("(\"").append(contentType.substring(0, slashIndex).toUpperCase()).append("\" \""); int semiColonIndex = contentType.indexOf(';'); if (semiColonIndex < 0) { buffer.append(contentType.substring(slashIndex + 1).toUpperCase()).append("\" ()"); } else { // extended content type buffer.append(contentType.substring(slashIndex + 1, semiColonIndex).trim().toUpperCase()).append('\"'); int charsetindex = contentType.indexOf("charset="); if (charsetindex >= 0) { buffer.append(" (\"CHARSET\" "); int charsetSemiColonIndex = contentType.indexOf(';', charsetindex); int charsetEndIndex; if (charsetSemiColonIndex > 0) { charsetEndIndex = charsetSemiColonIndex; } else { charsetEndIndex = contentType.length(); } String charSet = contentType.substring(charsetindex + "charset=".length(), charsetEndIndex); if (!charSet.startsWith("\"")) { buffer.append('"'); } buffer.append(charSet.trim().toUpperCase()); if (!charSet.endsWith("\"")) { buffer.append('"'); } buffer.append(')'); } else { buffer.append(" NIL"); } } appendBodyStructureValue(buffer, bodyPart.getContentID()); appendBodyStructureValue(buffer, bodyPart.getDescription()); appendBodyStructureValue(buffer, bodyPart.getEncoding()); appendBodyStructureValue(buffer, bodyPart.getSize()); // line count not implemented in JavaMail, return 0 appendBodyStructureValue(buffer, 0); buffer.append(')'); } protected void appendBodyStructureValue(StringBuilder buffer, String value) { if (value == null) { buffer.append(" NIL"); } else { buffer.append(" \"").append(value.toUpperCase()).append('\"'); } } protected void appendBodyStructureValue(StringBuilder buffer, int value) { if (value < 0) { buffer.append(" NIL"); } else { buffer.append(' ').append(value); } } protected void sendSubFolders(String command, String folderPath, boolean recursive) throws IOException { try { List<ExchangeSession.Folder> folders = session.getSubFolders(folderPath, recursive); for (ExchangeSession.Folder folder : folders) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); } } catch (HttpForbiddenException e) { // access forbidden, ignore DavGatewayTray.debug(new BundleMessage("LOG_SUBFOLDER_ACCESS_FORBIDDEN", folderPath)); } catch (HttpNotFoundException e) { // not found, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_NOT_FOUND", folderPath)); } catch (HttpException e) { // other errors, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR", folderPath, e.getMessage())); } } static final class SearchConditions { Boolean flagged; Boolean answered; Boolean deleted; long startUid; int startIndex; final StringBuilder query = new StringBuilder(); public StringBuilder append(String value) { return query.append(value); } } protected void appendOrSearchParams(String token, SearchConditions conditions) throws IOException { IMAPTokenizer innerTokens = new IMAPTokenizer(token); innerTokens.nextToken(); boolean first = true; while (innerTokens.hasMoreTokens()) { String innerToken = innerTokens.nextToken(); String operator = ""; if (!first) { operator = " OR "; } first = false; appendSearchParam(operator, innerTokens, innerToken, conditions); } } protected void appendSearchParam(String operator, StringTokenizer tokens, String token, SearchConditions conditions) throws IOException { if ("NOT".equals(token)) { appendSearchParam(operator + " NOT ", tokens, tokens.nextToken(), conditions); } else if (token.startsWith("OR ")) { appendOrSearchParams(token, conditions); } else if ("SUBJECT".equals(token)) { conditions.append(operator).append("\"urn:schemas:httpmail:subject\" LIKE '%").append(tokens.nextToken()).append("%'"); } else if ("BODY".equals(token)) { conditions.append(operator).append("\"http://schemas.microsoft.com/mapi/proptag/x01000001E\" LIKE '%").append(tokens.nextToken()).append("%'"); } else if ("FROM".equals(token)) { conditions.append(operator).append("\"urn:schemas:mailheader:from\" LIKE '%").append(tokens.nextToken()).append("%'"); } else if ("TO".equals(token)) { conditions.append(operator).append("\"urn:schemas:mailheader:to\" LIKE '%").append(tokens.nextToken()).append("%'"); } else if ("CC".equals(token)) { conditions.append(operator).append("\"urn:schemas:mailheader:cc\" LIKE '%").append(tokens.nextToken()).append("%'"); } else if ("LARGER".equals(token)) { conditions.append(operator).append("\"http://schemas.microsoft.com/mapi/proptag/x0e080003\" &gt;= ").append(Long.parseLong(tokens.nextToken())).append(""); } else if ("SMALLER".equals(token)) { conditions.append(operator).append("\"http://schemas.microsoft.com/mapi/proptag/x0e080003\" < ").append(Long.parseLong(tokens.nextToken())).append(""); } else if (token.startsWith("SENT") || "SINCE".equals(token) || "BEFORE".equals(token)) { conditions.append(operator); appendDateSearchParam(tokens, token, conditions); } else if ("SEEN".equals(token)) { conditions.append(operator).append("\"urn:schemas:httpmail:read\" = True"); } else if ("UNSEEN".equals(token) || "NEW".equals(token)) { conditions.append(operator).append("\"urn:schemas:httpmail:read\" = False"); } else if ("DELETED".equals(token)) { conditions.deleted = !operator.endsWith(" NOT "); } else if ("UNDELETED".equals(token) || "NOT DELETED".equals(token)) { conditions.deleted = Boolean.FALSE; } else if ("FLAGGED".equals(token)) { conditions.flagged = Boolean.TRUE; } else if ("UNFLAGGED".equals(token) || "NEW".equals(token)) { conditions.flagged = Boolean.FALSE; } else if ("ANSWERED".equals(token)) { conditions.answered = Boolean.TRUE; } else if ("UNANSWERED".equals(token)) { conditions.answered = Boolean.FALSE; } else if ("HEADER".equals(token)) { String headerName = tokens.nextToken().toLowerCase(); String value = tokens.nextToken(); if ("message-id".equals(headerName) && !value.startsWith("<")) { value = '<' + value + '>'; } String namespace; if (headerName.startsWith("x-")) { // look for extended headers in MAPI namespace namespace = "http://schemas.microsoft.com/mapi/string/{00020386-0000-0000-C000-000000000046}/"; } else { // look for standard properties in mailheader namespace namespace = "urn:schemas:mailheader:"; } conditions.append(operator).append('"').append(namespace).append(headerName).append("\"='").append(value).append('\''); } else if ("UID".equals(token)) { String range = tokens.nextToken(); if ("1:*".equals(range)) { // ignore: this is a noop filter } else if (range.endsWith(":*")) { conditions.startUid = Long.parseLong(range.substring(0, range.indexOf(':'))); } else { throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", range); } } else if ("OLD".equals(token) || "RECENT".equals(token) || "ALL".equals(token)) { // ignore } else if (token.indexOf(':') >= 0) { // range search try { conditions.startIndex = Integer.parseInt(token.substring(0, token.indexOf(':'))); } catch (NumberFormatException e) { throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", token); } } else { throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", token); } } protected void appendDateSearchParam(StringTokenizer tokens, String token, SearchConditions conditions) throws IOException { Date startDate; Date endDate; SimpleDateFormat parser = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); parser.setTimeZone(ExchangeSession.GMT_TIMEZONE); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE); String dateToken = tokens.nextToken(); try { startDate = parser.parse(dateToken); Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); calendar.add(Calendar.DAY_OF_MONTH, 1); endDate = calendar.getTime(); } catch (ParseException e) { throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", dateToken); } String searchAttribute; if (token.startsWith("SENT")) { searchAttribute = "urn:schemas:httpmail:date"; } else { searchAttribute = "DAV:getlastmodified"; } if (token.endsWith("ON")) { conditions.append("(\"").append(searchAttribute).append("\" > '") .append(dateFormatter.format(startDate)) .append("' AND \"").append(searchAttribute).append("\" < '") .append(dateFormatter.format(endDate)) .append("')"); } else if (token.endsWith("BEFORE")) { conditions.append("\"").append(searchAttribute).append("\" < '") .append(dateFormatter.format(startDate)) .append('\''); } else if (token.endsWith("SINCE")) { conditions.append("\"").append(searchAttribute).append("\" >= '") .append(dateFormatter.format(startDate)) .append('\''); } } protected void expunge(boolean silent) throws IOException { if (currentFolder.messages != null) { int index = 1; for (ExchangeSession.Message message : currentFolder.messages) { if (message.deleted) { message.delete(); if (!silent) { sendClient("* " + index + " EXPUNGE"); } } else { index++; } } } } protected void updateFlags(ExchangeSession.Message message, String action, String flags) throws IOException { HashMap<String, String> properties = new HashMap<String, String>(); if ("-Flags".equalsIgnoreCase(action) || "-FLAGS.SILENT".equalsIgnoreCase(action)) { StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equals(flag) && message.read) { properties.put("read", "0"); message.read = false; } else if ("\\Flagged".equals(flag) && message.flagged) { properties.put("flagged", "0"); message.flagged = false; } else if ("\\Deleted".equals(flag) && message.deleted) { properties.put("deleted", null); message.deleted = false; } else if ("Junk".equals(flag) && message.junk) { properties.put("junk", "0"); message.junk = false; } } } else if ("+Flags".equalsIgnoreCase(action) || "+FLAGS.SILENT".equalsIgnoreCase(action)) { StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equals(flag) && !message.read) { properties.put("read", "1"); message.read = true; } else if ("\\Deleted".equals(flag) && !message.deleted) { message.deleted = true; properties.put("deleted", "1"); } else if ("\\Flagged".equals(flag) && !message.flagged) { properties.put("flagged", "2"); message.flagged = true; } else if ("\\Answered".equals(flag) && !message.answered) { properties.put("answered", "102"); message.answered = true; } else if ("$Forwarded".equals(flag) && !message.forwarded) { properties.put("forwarded", "104"); message.forwarded = true; } else if ("Junk".equals(flag) && !message.junk) { properties.put("junk", "1"); message.junk = true; } } } else if ("FLAGS".equalsIgnoreCase(action) || "FLAGS.SILENT".equalsIgnoreCase(action)) { // flag list with default values boolean read = false; boolean deleted = false; boolean junk = false; boolean flagged = false; boolean answered = false; boolean forwarded = false; // set flags from new flag list StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equals(flag)) { read = true; } else if ("\\Deleted".equals(flag)) { deleted = true; } else if ("\\Flagged".equals(flag)) { flagged = true; } else if ("\\Answered".equals(flag)) { answered = true; } else if ("$Forwarded".equals(flag)) { forwarded = true; } else if ("Junk".equals(flag)) { junk = true; } } if (read != message.read) { message.read = read; if (message.read) { properties.put("read", "1"); } else { properties.put("read", "0"); } } if (deleted != message.deleted) { message.deleted = deleted; if (message.deleted) { properties.put("deleted", "1"); } else { properties.put("deleted", null); } } if (flagged != message.flagged) { message.flagged = flagged; if (message.flagged) { properties.put("flagged", "2"); } else { properties.put("flagged", "0"); } } if (answered != message.answered) { message.answered = answered; if (message.answered) { properties.put("answered", "102"); } else if (!forwarded) { // remove property only if not forwarded properties.put("answered", null); } } if (forwarded != message.forwarded) { message.forwarded = forwarded; if (message.forwarded) { properties.put("forwarded", "104"); } else if (!answered) { // remove property only if not answered properties.put("forwarded", null); } } if (junk != message.junk) { message.junk = junk; if (message.junk) { properties.put("junk", "1"); } else { properties.put("junk", "0"); } } } if (!properties.isEmpty()) { session.updateMessage(message, properties); } } /** * Decode IMAP credentials * * @param tokens tokens * @throws IOException on error */ protected void parseCredentials(StringTokenizer tokens) throws IOException { if (tokens.hasMoreTokens()) { userName = tokens.nextToken(); } else { throw new DavMailException("EXCEPTION_INVALID_CREDENTIALS"); } if (tokens.hasMoreTokens()) { password = tokens.nextToken(); } else { throw new DavMailException("EXCEPTION_INVALID_CREDENTIALS"); } int backslashindex = userName.indexOf('\\'); if (backslashindex > 0) { userName = userName.substring(0, backslashindex) + userName.substring(backslashindex + 1); } } protected String removeQuotes(String value) { String result = value; if (result.startsWith("\"") || result.startsWith("{") || result.startsWith("(")) { result = result.substring(1); } if (result.endsWith("\"") || result.endsWith("}") || result.endsWith(")")) { result = result.substring(0, result.length() - 1); } return result; } /** * Filter to output only headers, also count full size */ private static final class PartOutputStream extends FilterOutputStream { private static final int START = 0; private static final int CR = 1; private static final int CRLF = 2; private static final int CRLFCR = 3; private static final int BODY = 4; private int state = START; private int size; private final boolean writeHeaders; private final boolean writeBody; private final int startIndex; private PartOutputStream(OutputStream os, boolean writeHeaders, boolean writeBody, int startIndex) { super(os); this.writeHeaders = writeHeaders; this.writeBody = writeBody; this.startIndex = startIndex; } @Override public void write(int b) throws IOException { size++; if (((state != BODY && writeHeaders) || (state == BODY && writeBody)) && (size > startIndex) ) { super.write(b); } if (state == START) { if (b == '\r') { state = CR; } } else if (state == CR) { if (b == '\n') { state = CRLF; } else { state = START; } } else if (state == CRLF) { if (b == '\r') { state = CRLFCR; } else { state = START; } } else if (state == CRLFCR) { if (b == '\n') { state = BODY; } else { state = START; } } } } protected abstract static class AbstractRangeIterator implements Iterator<ExchangeSession.Message> { ExchangeSession.MessageList messages; int currentIndex; protected int getCurrentIndex() { return currentIndex; } } protected static class UIDRangeIterator extends AbstractRangeIterator { final String[] ranges; int currentRangeIndex; long startUid; long endUid; protected UIDRangeIterator(ExchangeSession.MessageList messages, String value) { this.messages = messages; ranges = value.split(","); } protected long convertToLong(String value) { if ("*".equals(value)) { return Long.MAX_VALUE; } else { return Long.parseLong(value); } } protected void skipToNextRangeStartUid() { if (currentRangeIndex < ranges.length) { String currentRange = ranges[currentRangeIndex++]; int colonIndex = currentRange.indexOf(':'); if (colonIndex > 0) { startUid = convertToLong(currentRange.substring(0, colonIndex)); endUid = convertToLong(currentRange.substring(colonIndex + 1)); if (endUid < startUid) { long swap = endUid; endUid = startUid; startUid = swap; } } else { startUid = endUid = convertToLong(currentRange); } while (currentIndex < messages.size() && messages.get(currentIndex).getImapUid() < startUid) { currentIndex++; } } else { currentIndex = messages.size(); } } protected boolean hasNextInRange() { return hasNextIndex() && messages.get(currentIndex).getImapUid() <= endUid; } protected boolean hasNextIndex() { return currentIndex < messages.size(); } protected boolean hasNextRange() { return currentRangeIndex < ranges.length; } public boolean hasNext() { boolean hasNextInRange = hasNextInRange(); // if has next range and current index after current range end, reset index if (hasNextRange() && !hasNextInRange) { currentIndex = 0; } while (hasNextIndex() && !hasNextInRange) { skipToNextRangeStartUid(); hasNextInRange = hasNextInRange(); } return hasNextIndex(); } public ExchangeSession.Message next() { ExchangeSession.Message message = messages.get(currentIndex++); long uid = message.getImapUid(); if (uid < startUid || uid > endUid) { throw new RuntimeException("Message uid " + uid + " not in range " + startUid + ':' + endUid); } return message; } public void remove() { throw new UnsupportedOperationException(); } } protected static class RangeIterator extends AbstractRangeIterator { final String[] ranges; int currentRangeIndex; long startUid; long endUid; protected RangeIterator(ExchangeSession.MessageList messages, String value) { this.messages = messages; ranges = value.split(","); } protected long convertToLong(String value) { if ("*".equals(value)) { return Long.MAX_VALUE; } else { return Long.parseLong(value); } } protected void skipToNextRangeStart() { if (currentRangeIndex < ranges.length) { String currentRange = ranges[currentRangeIndex++]; int colonIndex = currentRange.indexOf(':'); if (colonIndex > 0) { startUid = convertToLong(currentRange.substring(0, colonIndex)); endUid = convertToLong(currentRange.substring(colonIndex + 1)); if (endUid < startUid) { long swap = endUid; endUid = startUid; startUid = swap; } } else { startUid = endUid = convertToLong(currentRange); } while (currentIndex < messages.size() && (currentIndex + 1) < startUid) { currentIndex++; } } else { currentIndex = messages.size(); } } protected boolean hasNextInRange() { return hasNextIndex() && currentIndex < endUid; } protected boolean hasNextIndex() { return currentIndex < messages.size(); } protected boolean hasNextRange() { return currentRangeIndex < ranges.length; } public boolean hasNext() { boolean hasNextInRange = hasNextInRange(); // if has next range and current index after current range end, reset index if (hasNextRange() && !hasNextInRange) { currentIndex = 0; } while (hasNextIndex() && !hasNextInRange) { skipToNextRangeStart(); hasNextInRange = hasNextInRange(); } return hasNextIndex(); } public ExchangeSession.Message next() { return messages.get(currentIndex++); } public void remove() { throw new UnsupportedOperationException(); } } class IMAPTokenizer extends StringTokenizer { IMAPTokenizer(String value) { super(value); } @Override public String nextToken() { return removeQuotes(nextQuotedToken()); } public String nextQuotedToken() { StringBuilder nextToken = new StringBuilder(); nextToken.append(super.nextToken()); while (hasMoreTokens() && nextToken.length() > 0 && nextToken.charAt(0) == '"' && (nextToken.charAt(nextToken.length() - 1) != '"' || nextToken.length() == 1)) { nextToken.append(' ').append(super.nextToken()); } while (hasMoreTokens() && nextToken.length() > 0 && nextToken.charAt(0) == '(' && nextToken.charAt(nextToken.length() - 1) != ')') { nextToken.append(' ').append(super.nextToken()); } return nextToken.toString(); } } }
true
true
public void run() { String line; String commandId = null; IMAPTokenizer tokens; try { ExchangeSessionFactory.checkConfig(); sendClient("* OK [CAPABILITY IMAP4REV1 AUTH=LOGIN] IMAP4rev1 DavMail server ready"); for (; ;) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new IMAPTokenizer(line); if (tokens.hasMoreTokens()) { commandId = tokens.nextToken(); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); if ("LOGOUT".equalsIgnoreCase(command)) { sendClient("* BYE Closing connection"); break; } if ("capability".equalsIgnoreCase(command)) { sendClient("* CAPABILITY IMAP4REV1 AUTH=LOGIN"); sendClient(commandId + " OK CAPABILITY completed"); } else if ("login".equalsIgnoreCase(command)) { parseCredentials(tokens); try { session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else if ("AUTHENTICATE".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String authenticationMethod = tokens.nextToken(); if ("LOGIN".equalsIgnoreCase(authenticationMethod)) { try { sendClient("+ " + base64Encode("Username:")); state = State.LOGIN; userName = base64Decode(readClient()); sendClient("+ " + base64Encode("Password:")); state = State.PASSWORD; password = base64Decode(readClient()); session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else { sendClient(commandId + " NO unsupported authentication method"); } } else { sendClient(commandId + " BAD authentication method required"); } } else { if (state != State.AUTHENTICATED) { sendClient(commandId + " BAD command authentication required"); } else { // check for expired session session = ExchangeSessionFactory.getInstance(session, userName, password); if ("lsub".equalsIgnoreCase(command) || "list".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderContext = BASE64MailboxDecoder.decode(tokens.nextToken()); if (tokens.hasMoreTokens()) { String folderQuery = folderContext + BASE64MailboxDecoder.decode(tokens.nextToken()); if (folderQuery.endsWith("%/%") && !"/%/%".equals(folderQuery)) { List<ExchangeSession.Folder> folders = session.getSubFolders(folderQuery.substring(0, folderQuery.length() - 3), false); for (ExchangeSession.Folder folder : folders) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendSubFolders(command, folder.folderPath, false); } sendClient(commandId + " OK " + command + " completed"); } else if (folderQuery.endsWith("%") || folderQuery.endsWith("*")) { if ("/*".equals(folderQuery) || "/%".equals(folderQuery) || "/%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(1); if ("%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(0, folderQuery.length() - 2); } sendClient("* " + command + " (\\HasChildren) \"/\" \"/public\""); } if ("*%".equals(folderQuery)) { folderQuery = "*"; } boolean recursive = folderQuery.endsWith("*") && !folderQuery.startsWith("/public"); sendSubFolders(command, folderQuery.substring(0, folderQuery.length() - 1), recursive); sendClient(commandId + " OK " + command + " completed"); } else { ExchangeSession.Folder folder = null; try { folder = session.getFolder(folderQuery); } catch (HttpForbiddenException e) { // access forbidden, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_FORBIDDEN", folderQuery)); } catch (HttpNotFoundException e) { // not found, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_NOT_FOUND", folderQuery)); } catch (HttpException e) { // other errors, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR", folderQuery, e.getMessage())); } if (folder != null) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendClient(commandId + " OK " + command + " completed"); } else { sendClient(commandId + " NO Folder not found"); } } } else { sendClient(commandId + " BAD missing folder argument"); } } else { sendClient(commandId + " BAD missing folder argument"); } } else if ("select".equalsIgnoreCase(command) || "examine".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { currentFolder = session.getFolder(folderName); currentFolder.loadMessages(); sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.count() + " RECENT"); sendClient("* OK [UIDVALIDITY 1]"); if (currentFolder.count() == 0) { sendClient("* OK [UIDNEXT 1]"); } else { sendClient("* OK [UIDNEXT " + currentFolder.getUidNext() + ']'); } sendClient("* FLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)"); sendClient("* OK [PERMANENTFLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk \\*)]"); if ("select".equalsIgnoreCase(command)) { sendClient(commandId + " OK [READ-WRITE] " + command + " completed"); } else { sendClient(commandId + " OK [READ-ONLY] " + command + " completed"); } } catch (HttpNotFoundException e) { sendClient(commandId + " NO Not found"); } catch (HttpForbiddenException e) { sendClient(commandId + " NO Forbidden"); } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("expunge".equalsIgnoreCase(command)) { expunge(false); // need to refresh folder to avoid 404 errors session.refreshFolder(currentFolder); sendClient(commandId + " OK " + command + " completed"); } else if ("close".equalsIgnoreCase(command)) { expunge(true); // deselect folder currentFolder = null; sendClient(commandId + " OK " + command + " completed"); } else if ("create".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); session.createMessageFolder(folderName); sendClient(commandId + " OK folder created"); } else { sendClient(commandId + " BAD missing create argument"); } } else if ("rename".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.moveFolder(folderName, targetName); sendClient(commandId + " OK rename completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("delete".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.deleteFolder(folderName); sendClient(commandId + " OK delete completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("uid".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String subcommand = tokens.nextToken(); if ("fetch".equalsIgnoreCase(subcommand)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { String ranges = tokens.nextToken(); if (ranges == null) { sendClient(commandId + " BAD missing range parameter"); } else { String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, ranges); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); try { handleFetch(message, uidRangeIterator.currentIndex, parameters); } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK UID FETCH completed"); } } } else if ("search".equalsIgnoreCase(subcommand)) { List<Long> uidList = handleSearch(tokens); for (long uid : uidList) { sendClient("* SEARCH " + uid); } sendClient(commandId + " OK SEARCH completed"); } else if ("store".equalsIgnoreCase(subcommand)) { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, uidRangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(subcommand)) { try { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); session.copyMessage(message, targetName); } sendClient(commandId + " OK copy completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("search".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { List<Long> uidList = handleSearch(tokens); int currentIndex = 0; for (ExchangeSession.Message message : currentFolder.messages) { currentIndex++; if (uidList.contains(message.getImapUid())) { sendClient("* SEARCH " + currentIndex); } } sendClient(commandId + " OK SEARCH completed"); } } else if ("fetch".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); try { handleFetch(message, rangeIterator.currentIndex, parameters); } catch (SocketException e) { // client closed connection, rethrow exception throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK FETCH completed"); } } else if ("store".equalsIgnoreCase(command)) { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, rangeIterator, action, flags); } else if ("append".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); HashMap<String, String> properties = new HashMap<String, String>(); String flags = null; String date = null; // handle optional flags String nextToken = tokens.nextQuotedToken(); if (nextToken.startsWith("(")) { flags = removeQuotes(nextToken); if (tokens.hasMoreTokens()) { nextToken = tokens.nextToken(); if (tokens.hasMoreTokens()) { date = nextToken; nextToken = tokens.nextToken(); } } } else if (tokens.hasMoreTokens()) { date = removeQuotes(nextToken); nextToken = tokens.nextToken(); } if (flags != null) { StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equals(flag)) { properties.put("read", "1"); } else if ("\\Flagged".equals(flag)) { properties.put("flagged", "2"); } else if ("\\Answered".equals(flag)) { properties.put("answered", "102"); } else if ("$Forwarded".equals(flag)) { properties.put("forwarded", "104"); } else if ("\\Draft".equals(flag)) { properties.put("draft", "9"); } else if ("Junk".equals(flag)) { properties.put("junk", "1"); } } } // handle optional date if (date != null) { SimpleDateFormat dateParser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH); Date dateReceived = dateParser.parse(date); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE); properties.put("datereceived", dateFormatter.format(dateReceived)); } int size = Integer.parseInt(nextToken); sendClient("+ send literal data"); char[] buffer = new char[size]; int index = 0; int count = 0; while (count >= 0 && index < size) { count = in.read(buffer, index, size - index); if (count >= 0) { index += count; } } // empty line readClient(); String messageName = UUID.randomUUID().toString(); session.createMessage(folderName, messageName, properties, new String(buffer)); sendClient(commandId + " OK APPEND completed"); } else if ("noop".equalsIgnoreCase(command) || "check".equalsIgnoreCase(command)) { if (currentFolder != null) { DavGatewayTray.debug(new BundleMessage("LOG_IMAP_COMMAND", command, currentFolder.folderName)); ExchangeSession.MessageList currentMessages = currentFolder.messages; if (session.refreshFolder(currentFolder)) { // build new uid set HashSet<Long> uidSet = new HashSet<Long>(); for (ExchangeSession.Message message : currentFolder.messages) { uidSet.add(message.getImapUid()); } // send expunge untagged response for removed IMAP message uids // note: some STORE commands trigger a uid change in Exchange, // thus those messages are expunged and reappear with a new uid int index = 1; for (ExchangeSession.Message message : currentMessages) { if (!uidSet.contains(message.getImapUid())) { sendClient("* " + index + " EXPUNGE"); } else { index++; } } sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.count() + " RECENT"); } } sendClient(commandId + " OK " + command + " completed"); } else if ("subscribe".equalsIgnoreCase(command) || "unsubscribe".equalsIgnoreCase(command)) { sendClient(commandId + " OK " + command + " completed"); } else if ("status".equalsIgnoreCase(command)) { try { String encodedFolderName = tokens.nextToken(); String folderName = BASE64MailboxDecoder.decode(encodedFolderName); ExchangeSession.Folder folder = session.getFolder(folderName); // must retrieve messages folder.loadMessages(); String parameters = tokens.nextToken(); StringBuilder answer = new StringBuilder(); StringTokenizer parametersTokens = new StringTokenizer(parameters); while (parametersTokens.hasMoreTokens()) { String token = parametersTokens.nextToken(); if ("MESSAGES".equalsIgnoreCase(token)) { answer.append("MESSAGES ").append(folder.count()).append(' '); } if ("RECENT".equalsIgnoreCase(token)) { answer.append("RECENT ").append(folder.count()).append(' '); } if ("UIDNEXT".equalsIgnoreCase(token)) { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { answer.append("UIDNEXT ").append(folder.getUidNext()).append(' '); } } } if ("UIDVALIDITY".equalsIgnoreCase(token)) { answer.append("UIDVALIDITY 1 "); } if ("UNSEEN".equalsIgnoreCase(token)) { answer.append("UNSEEN ").append(folder.unreadCount).append(' '); } } sendClient("* STATUS " + encodedFolderName + " (" + answer.toString().trim() + ')'); sendClient(commandId + " OK " + command + " completed"); } catch (HttpException e) { sendClient(commandId + " NO folder not found"); } } else { sendClient(commandId + " BAD command unrecognized"); } } } } else { sendClient(commandId + " BAD missing command"); } } else { sendClient("BAD Null command"); } DavGatewayTray.resetIcon(); } os.flush(); } catch (SocketTimeoutException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT")); try { sendClient("* BYE Closing connection"); } catch (IOException e1) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_CLOSING_CONNECTION_ON_TIMEOUT")); } } catch (SocketException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLIENT_CLOSED_CONNECTION")); } catch (Exception e) { DavGatewayTray.log(e); try { String message = ((e.getMessage() == null) ? e.toString() : e.getMessage()).replaceAll("\\n", " "); if (commandId != null) { sendClient(commandId + " BAD unable to handle request: " + message); } else { sendClient("* BYE unable to handle request: " + message); } } catch (IOException e2) { DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); }
public void run() { String line; String commandId = null; IMAPTokenizer tokens; try { ExchangeSessionFactory.checkConfig(); sendClient("* OK [CAPABILITY IMAP4REV1 AUTH=LOGIN] IMAP4rev1 DavMail server ready"); for (; ;) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new IMAPTokenizer(line); if (tokens.hasMoreTokens()) { commandId = tokens.nextToken(); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); if ("LOGOUT".equalsIgnoreCase(command)) { sendClient("* BYE Closing connection"); break; } if ("capability".equalsIgnoreCase(command)) { sendClient("* CAPABILITY IMAP4REV1 AUTH=LOGIN"); sendClient(commandId + " OK CAPABILITY completed"); } else if ("login".equalsIgnoreCase(command)) { parseCredentials(tokens); try { session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else if ("AUTHENTICATE".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String authenticationMethod = tokens.nextToken(); if ("LOGIN".equalsIgnoreCase(authenticationMethod)) { try { sendClient("+ " + base64Encode("Username:")); state = State.LOGIN; userName = base64Decode(readClient()); sendClient("+ " + base64Encode("Password:")); state = State.PASSWORD; password = base64Decode(readClient()); session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else { sendClient(commandId + " NO unsupported authentication method"); } } else { sendClient(commandId + " BAD authentication method required"); } } else { if (state != State.AUTHENTICATED) { sendClient(commandId + " BAD command authentication required"); } else { // check for expired session session = ExchangeSessionFactory.getInstance(session, userName, password); if ("lsub".equalsIgnoreCase(command) || "list".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderContext = BASE64MailboxDecoder.decode(tokens.nextToken()); if (tokens.hasMoreTokens()) { String folderQuery = folderContext + BASE64MailboxDecoder.decode(tokens.nextToken()); if (folderQuery.endsWith("%/%") && !"/%/%".equals(folderQuery)) { List<ExchangeSession.Folder> folders = session.getSubFolders(folderQuery.substring(0, folderQuery.length() - 3), false); for (ExchangeSession.Folder folder : folders) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendSubFolders(command, folder.folderPath, false); } sendClient(commandId + " OK " + command + " completed"); } else if (folderQuery.endsWith("%") || folderQuery.endsWith("*")) { if ("/*".equals(folderQuery) || "/%".equals(folderQuery) || "/%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(1); if ("%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(0, folderQuery.length() - 2); } sendClient("* " + command + " (\\HasChildren) \"/\" \"/public\""); } if ("*%".equals(folderQuery)) { folderQuery = "*"; } boolean recursive = folderQuery.endsWith("*") && !folderQuery.startsWith("/public"); sendSubFolders(command, folderQuery.substring(0, folderQuery.length() - 1), recursive); sendClient(commandId + " OK " + command + " completed"); } else { ExchangeSession.Folder folder = null; try { folder = session.getFolder(folderQuery); } catch (HttpForbiddenException e) { // access forbidden, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_FORBIDDEN", folderQuery)); } catch (HttpNotFoundException e) { // not found, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_NOT_FOUND", folderQuery)); } catch (HttpException e) { // other errors, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR", folderQuery, e.getMessage())); } if (folder != null) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendClient(commandId + " OK " + command + " completed"); } else { sendClient(commandId + " NO Folder not found"); } } } else { sendClient(commandId + " BAD missing folder argument"); } } else { sendClient(commandId + " BAD missing folder argument"); } } else if ("select".equalsIgnoreCase(command) || "examine".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { currentFolder = session.getFolder(folderName); currentFolder.loadMessages(); sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.count() + " RECENT"); sendClient("* OK [UIDVALIDITY 1]"); if (currentFolder.count() == 0) { sendClient("* OK [UIDNEXT 1]"); } else { sendClient("* OK [UIDNEXT " + currentFolder.getUidNext() + ']'); } sendClient("* FLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)"); sendClient("* OK [PERMANENTFLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk \\*)]"); if ("select".equalsIgnoreCase(command)) { sendClient(commandId + " OK [READ-WRITE] " + command + " completed"); } else { sendClient(commandId + " OK [READ-ONLY] " + command + " completed"); } } catch (HttpNotFoundException e) { sendClient(commandId + " NO Not found"); } catch (HttpForbiddenException e) { sendClient(commandId + " NO Forbidden"); } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("expunge".equalsIgnoreCase(command)) { expunge(false); // need to refresh folder to avoid 404 errors session.refreshFolder(currentFolder); sendClient(commandId + " OK " + command + " completed"); } else if ("close".equalsIgnoreCase(command)) { expunge(true); // deselect folder currentFolder = null; sendClient(commandId + " OK " + command + " completed"); } else if ("create".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); session.createMessageFolder(folderName); sendClient(commandId + " OK folder created"); } else { sendClient(commandId + " BAD missing create argument"); } } else if ("rename".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.moveFolder(folderName, targetName); sendClient(commandId + " OK rename completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("delete".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.deleteFolder(folderName); sendClient(commandId + " OK delete completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("uid".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String subcommand = tokens.nextToken(); if ("fetch".equalsIgnoreCase(subcommand)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { String ranges = tokens.nextToken(); if (ranges == null) { sendClient(commandId + " BAD missing range parameter"); } else { String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, ranges); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); try { handleFetch(message, uidRangeIterator.currentIndex, parameters); } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK UID FETCH completed"); } } } else if ("search".equalsIgnoreCase(subcommand)) { List<Long> uidList = handleSearch(tokens); for (long uid : uidList) { sendClient("* SEARCH " + uid); } sendClient(commandId + " OK SEARCH completed"); } else if ("store".equalsIgnoreCase(subcommand)) { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, uidRangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(subcommand)) { try { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); session.copyMessage(message, targetName); } sendClient(commandId + " OK copy completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("search".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { List<Long> uidList = handleSearch(tokens); int currentIndex = 0; for (ExchangeSession.Message message : currentFolder.messages) { currentIndex++; if (uidList.contains(message.getImapUid())) { sendClient("* SEARCH " + currentIndex); } } sendClient(commandId + " OK SEARCH completed"); } } else if ("fetch".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); try { handleFetch(message, rangeIterator.currentIndex, parameters); } catch (SocketException e) { // client closed connection, rethrow exception throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK FETCH completed"); } } else if ("store".equalsIgnoreCase(command)) { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, rangeIterator, action, flags); } else if ("append".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); HashMap<String, String> properties = new HashMap<String, String>(); String flags = null; String date = null; // handle optional flags String nextToken = tokens.nextQuotedToken(); if (nextToken.startsWith("(")) { flags = removeQuotes(nextToken); if (tokens.hasMoreTokens()) { nextToken = tokens.nextToken(); if (tokens.hasMoreTokens()) { date = nextToken; nextToken = tokens.nextToken(); } } } else if (tokens.hasMoreTokens()) { date = removeQuotes(nextToken); nextToken = tokens.nextToken(); } if (flags != null) { StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equals(flag)) { properties.put("read", "1"); } else if ("\\Flagged".equals(flag)) { properties.put("flagged", "2"); } else if ("\\Answered".equals(flag)) { properties.put("answered", "102"); } else if ("$Forwarded".equals(flag)) { properties.put("forwarded", "104"); } else if ("\\Draft".equals(flag)) { properties.put("draft", "9"); } else if ("Junk".equals(flag)) { properties.put("junk", "1"); } } } // handle optional date if (date != null) { SimpleDateFormat dateParser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH); Date dateReceived = dateParser.parse(date); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE); properties.put("datereceived", dateFormatter.format(dateReceived)); } int size = Integer.parseInt(nextToken); sendClient("+ send literal data"); char[] buffer = new char[size]; int index = 0; int count = 0; while (count >= 0 && index < size) { count = in.read(buffer, index, size - index); if (count >= 0) { index += count; } } // empty line readClient(); String messageName = UUID.randomUUID().toString(); session.createMessage(folderName, messageName, properties, new String(buffer)); sendClient(commandId + " OK APPEND completed"); } else if ("noop".equalsIgnoreCase(command) || "check".equalsIgnoreCase(command)) { if (currentFolder != null) { DavGatewayTray.debug(new BundleMessage("LOG_IMAP_COMMAND", command, currentFolder.folderName)); ExchangeSession.MessageList currentMessages = currentFolder.messages; if (session.refreshFolder(currentFolder)) { // build new uid set HashSet<Long> uidSet = new HashSet<Long>(); for (ExchangeSession.Message message : currentFolder.messages) { uidSet.add(message.getImapUid()); } // send expunge untagged response for removed IMAP message uids // note: some STORE commands trigger a uid change in Exchange, // thus those messages are expunged and reappear with a new uid int index = 1; for (ExchangeSession.Message message : currentMessages) { if (!uidSet.contains(message.getImapUid())) { sendClient("* " + index + " EXPUNGE"); } else { index++; } } sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.count() + " RECENT"); } } sendClient(commandId + " OK " + command + " completed"); } else if ("subscribe".equalsIgnoreCase(command) || "unsubscribe".equalsIgnoreCase(command)) { sendClient(commandId + " OK " + command + " completed"); } else if ("status".equalsIgnoreCase(command)) { try { String encodedFolderName = tokens.nextToken(); String folderName = BASE64MailboxDecoder.decode(encodedFolderName); ExchangeSession.Folder folder = session.getFolder(folderName); // must retrieve messages folder.loadMessages(); String parameters = tokens.nextToken(); StringBuilder answer = new StringBuilder(); StringTokenizer parametersTokens = new StringTokenizer(parameters); while (parametersTokens.hasMoreTokens()) { String token = parametersTokens.nextToken(); if ("MESSAGES".equalsIgnoreCase(token)) { answer.append("MESSAGES ").append(folder.count()).append(' '); } if ("RECENT".equalsIgnoreCase(token)) { answer.append("RECENT ").append(folder.count()).append(' '); } if ("UIDNEXT".equalsIgnoreCase(token)) { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { answer.append("UIDNEXT ").append(folder.getUidNext()).append(' '); } } } if ("UIDVALIDITY".equalsIgnoreCase(token)) { answer.append("UIDVALIDITY 1 "); } if ("UNSEEN".equalsIgnoreCase(token)) { answer.append("UNSEEN ").append(folder.unreadCount).append(' '); } } sendClient("* STATUS \"" + encodedFolderName + "\" (" + answer.toString().trim() + ')'); sendClient(commandId + " OK " + command + " completed"); } catch (HttpException e) { sendClient(commandId + " NO folder not found"); } } else { sendClient(commandId + " BAD command unrecognized"); } } } } else { sendClient(commandId + " BAD missing command"); } } else { sendClient("BAD Null command"); } DavGatewayTray.resetIcon(); } os.flush(); } catch (SocketTimeoutException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT")); try { sendClient("* BYE Closing connection"); } catch (IOException e1) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_CLOSING_CONNECTION_ON_TIMEOUT")); } } catch (SocketException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLIENT_CLOSED_CONNECTION")); } catch (Exception e) { DavGatewayTray.log(e); try { String message = ((e.getMessage() == null) ? e.toString() : e.getMessage()).replaceAll("\\n", " "); if (commandId != null) { sendClient(commandId + " BAD unable to handle request: " + message); } else { sendClient("* BYE unable to handle request: " + message); } } catch (IOException e2) { DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); }
diff --git a/org.rubypeople.rdt.launching.tests/src/org/rubypeople/rdt/internal/launching/TC_RunnerLaunching.java b/org.rubypeople.rdt.launching.tests/src/org/rubypeople/rdt/internal/launching/TC_RunnerLaunching.java index e7f265f8..2e902145 100644 --- a/org.rubypeople.rdt.launching.tests/src/org/rubypeople/rdt/internal/launching/TC_RunnerLaunching.java +++ b/org.rubypeople.rdt.launching.tests/src/org/rubypeople/rdt/internal/launching/TC_RunnerLaunching.java @@ -1,273 +1,273 @@ package org.rubypeople.rdt.internal.launching; import java.io.File; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.Launch; import org.eclipse.debug.core.model.IProcess; import org.rubypeople.eclipse.shams.debug.core.ShamLaunchConfigurationType; import org.rubypeople.rdt.core.IRubyProject; import org.rubypeople.rdt.core.tests.ModifyingResourceTest; import org.rubypeople.rdt.internal.debug.core.model.RubyDebugTarget; import org.rubypeople.rdt.launching.IRubyLaunchConfigurationConstants; import org.rubypeople.rdt.launching.IVMInstall; import org.rubypeople.rdt.launching.IVMInstallType; import org.rubypeople.rdt.launching.RubyRuntime; import org.rubypeople.rdt.launching.VMStandin; public class TC_RunnerLaunching extends ModifyingResourceTest { private final static String PROJECT_NAME = "Simple Project"; private final static String RUBY_LIB_DIR = "someRubyDir"; // dir inside // project private final static String RUBY_FILE_NAME = "rubyFile.rb"; private final static String INTERPRETER_ARGUMENTS = "interpreter Arguments"; private final static String PROGRAM_ARGUMENTS = "programArguments"; private static final String VM_TYPE_ID = "org.rubypeople.rdt.launching.TestVMType"; private IVMInstallType vmType; private IVMInstall interpreter; private IRubyProject project; public TC_RunnerLaunching(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); project = createRubyProject('/' + PROJECT_NAME); IFolder location = createFolder('/' + PROJECT_NAME + "/interpreterOne"); createFolder('/' + PROJECT_NAME + "/interpreterOne/lib"); createFolder('/' + PROJECT_NAME + "/interpreterOne/bin"); createFile('/' + PROJECT_NAME + "/interpreterOne/bin/ruby", ""); vmType = RubyRuntime.getVMInstallType(VM_TYPE_ID); VMStandin standin = new VMStandin(vmType, "fake"); standin.setName("fake"); standin.setInstallLocation(location.getLocation().toFile()); interpreter = standin.convertToRealVM(); RubyRuntime.setDefaultVMInstall(interpreter, null, true); } @Override protected void tearDown() throws Exception { super.tearDown(); deleteProject('/' + PROJECT_NAME); vmType.disposeVMInstall(interpreter.getId()); } protected ILaunchManager getLaunchManager() { return DebugPlugin.getDefault().getLaunchManager(); } protected String getCommandLine(IProject project, String debugFile, boolean debug) { StringBuffer buffer = new StringBuffer(); buffer.append(" \""); buffer.append(new Path(interpreter.getInstallLocation().getAbsolutePath()).append("bin").append("ruby").toOSString()); buffer.append("\" "); buffer.append(INTERPRETER_ARGUMENTS); - if (!debug) buffer.append(" -e STDOUT.sync=true -e STDERR.sync=true -e load(ARGV.shift)"); + if (!debug) buffer.append(" -e STDOUT.sync=true -e STDERR.sync=true -e load($0=ARGV.shift)"); buffer.append(" -I \""); buffer.append(project.getLocation().toOSString()); buffer.append("\""); if (debug) { buffer.append(" -I "); if (Platform.getOS().equals(Platform.OS_WIN32)) buffer.append("\""); buffer.append(new Path(StandardVMDebugger.getDirectoryOfRubyDebuggerFile()).toOSString()); if (Platform.getOS().equals(Platform.OS_WIN32)) buffer.append("\""); buffer.append(" -r"); buffer.append(debugFile); buffer.append(" -rclassic-debug"); } buffer.append(" -- "); buffer.append(RUBY_LIB_DIR); buffer.append(File.separator); buffer.append(RUBY_FILE_NAME); buffer.append(' '); buffer.append(PROGRAM_ARGUMENTS); return buffer.toString(); } public void testDebugEnabled() throws Exception { // check if debugging is enabled in plugin.xml ILaunchConfigurationType launchConfigurationType = getLaunchManager().getLaunchConfigurationType(RubyLaunchConfigurationAttribute.RUBY_LAUNCH_CONFIGURATION_TYPE); assertEquals("Ruby Application", launchConfigurationType.getName()); assertTrue("LaunchConfiguration supports debug", launchConfigurationType.supportsMode(ILaunchManager.DEBUG_MODE)); } public void launch(boolean debug) throws Exception { ILaunchConfiguration configuration = new ShamLaunchConfiguration(); ILaunch launch = new Launch(configuration, debug ? ILaunchManager.DEBUG_MODE : ILaunchManager.RUN_MODE, null); ILaunchConfigurationType launchConfigurationType = getLaunchManager().getLaunchConfigurationType(RubyLaunchConfigurationAttribute.RUBY_LAUNCH_CONFIGURATION_TYPE); launchConfigurationType.getDelegate(debug ? "debug" : "run").launch(configuration, debug ? ILaunchManager.DEBUG_MODE : ILaunchManager.RUN_MODE, launch, null); RubyDebugTarget debugTarget = (RubyDebugTarget) launch.getDebugTarget(); String debugFile = ""; if (debug) { debugFile = debugTarget.getDebugParameterFile().getAbsolutePath(); } assertEquals("Only one process should have been spawned", 1, launch.getProcesses().length); IProcess process = launch.getProcesses()[0]; String expected = getCommandLine(project.getProject(), debugFile, debug); assertEquals(expected, process.getAttribute(IProcess.ATTR_CMDLINE)); } public void testRunInDebugMode() throws Exception { launch(true); } public void testRunInRunMode() throws Exception { launch(false); } public class ShamLaunchConfiguration implements ILaunchConfiguration { public boolean contentsEqual(ILaunchConfiguration configuration) { return false; } public ILaunchConfigurationWorkingCopy copy(String name) throws CoreException { return null; } public void delete() throws CoreException {} public boolean exists() { return true; } public boolean getAttribute(String attributeName, boolean defaultValue) throws CoreException { return defaultValue; } public int getAttribute(String attributeName, int defaultValue) throws CoreException { return defaultValue; } public List getAttribute(String attributeName, List defaultValue) throws CoreException { return defaultValue; } public Map getAttribute(String attributeName, Map defaultValue) throws CoreException { return defaultValue; } public String getAttribute(String attributeName, String defaultValue) throws CoreException { if (attributeName.equals(RubyLaunchConfigurationAttribute.PROJECT_NAME)) { return PROJECT_NAME; } else if (attributeName.equals(RubyLaunchConfigurationAttribute.FILE_NAME)) { return RUBY_LIB_DIR + File.separator + RUBY_FILE_NAME; } else if (attributeName.equals(RubyLaunchConfigurationAttribute.WORKING_DIRECTORY)) { return '/' + PROJECT_NAME; } else if (attributeName.equals(RubyLaunchConfigurationAttribute.PROGRAM_ARGUMENTS)) { return PROGRAM_ARGUMENTS; } else if (attributeName.equals(IRubyLaunchConfigurationConstants.ATTR_VM_ARGUMENTS)) { return INTERPRETER_ARGUMENTS; } return defaultValue; } public IFile getFile() { return null; } public IPath getLocation() { return null; } public String getMemento() throws CoreException { return null; } public String getName() { return null; } public ILaunchConfigurationType getType() throws CoreException { return new ShamLaunchConfigurationType(); } public ILaunchConfigurationWorkingCopy getWorkingCopy() throws CoreException { return null; } public boolean isLocal() { return false; } public boolean isWorkingCopy() { return false; } public ILaunch launch(String mode, IProgressMonitor monitor) throws CoreException { return null; } public boolean supportsMode(String mode) throws CoreException { return false; } public Object getAdapter(Class adapter) { return null; } public String getCategory() throws CoreException { return null; } public Map getAttributes() throws CoreException { return null; } public ILaunch launch(String mode, IProgressMonitor monitor, boolean build) throws CoreException { return null; } /* * (non-Javadoc) * * @see org.eclipse.debug.core.ILaunchConfiguration#launch(java.lang.String, * org.eclipse.core.runtime.IProgressMonitor, boolean, boolean) */ public ILaunch launch(String mode, IProgressMonitor monitor, boolean build, boolean register) throws CoreException { // TODO Auto-generated method stub return null; } public IResource[] getMappedResources() throws CoreException { // TODO Auto-generated method stub return null; } public boolean isMigrationCandidate() throws CoreException { // TODO Auto-generated method stub return false; } public void migrate() throws CoreException { // TODO Auto-generated method stub } } }
true
true
protected String getCommandLine(IProject project, String debugFile, boolean debug) { StringBuffer buffer = new StringBuffer(); buffer.append(" \""); buffer.append(new Path(interpreter.getInstallLocation().getAbsolutePath()).append("bin").append("ruby").toOSString()); buffer.append("\" "); buffer.append(INTERPRETER_ARGUMENTS); if (!debug) buffer.append(" -e STDOUT.sync=true -e STDERR.sync=true -e load(ARGV.shift)"); buffer.append(" -I \""); buffer.append(project.getLocation().toOSString()); buffer.append("\""); if (debug) { buffer.append(" -I "); if (Platform.getOS().equals(Platform.OS_WIN32)) buffer.append("\""); buffer.append(new Path(StandardVMDebugger.getDirectoryOfRubyDebuggerFile()).toOSString()); if (Platform.getOS().equals(Platform.OS_WIN32)) buffer.append("\""); buffer.append(" -r"); buffer.append(debugFile); buffer.append(" -rclassic-debug"); } buffer.append(" -- "); buffer.append(RUBY_LIB_DIR); buffer.append(File.separator); buffer.append(RUBY_FILE_NAME); buffer.append(' '); buffer.append(PROGRAM_ARGUMENTS); return buffer.toString(); }
protected String getCommandLine(IProject project, String debugFile, boolean debug) { StringBuffer buffer = new StringBuffer(); buffer.append(" \""); buffer.append(new Path(interpreter.getInstallLocation().getAbsolutePath()).append("bin").append("ruby").toOSString()); buffer.append("\" "); buffer.append(INTERPRETER_ARGUMENTS); if (!debug) buffer.append(" -e STDOUT.sync=true -e STDERR.sync=true -e load($0=ARGV.shift)"); buffer.append(" -I \""); buffer.append(project.getLocation().toOSString()); buffer.append("\""); if (debug) { buffer.append(" -I "); if (Platform.getOS().equals(Platform.OS_WIN32)) buffer.append("\""); buffer.append(new Path(StandardVMDebugger.getDirectoryOfRubyDebuggerFile()).toOSString()); if (Platform.getOS().equals(Platform.OS_WIN32)) buffer.append("\""); buffer.append(" -r"); buffer.append(debugFile); buffer.append(" -rclassic-debug"); } buffer.append(" -- "); buffer.append(RUBY_LIB_DIR); buffer.append(File.separator); buffer.append(RUBY_FILE_NAME); buffer.append(' '); buffer.append(PROGRAM_ARGUMENTS); return buffer.toString(); }
diff --git a/ccalc/rpc/src/main/java/org/gwtapp/ccalc/rpc/proc/calculator/Calculator2.java b/ccalc/rpc/src/main/java/org/gwtapp/ccalc/rpc/proc/calculator/Calculator2.java index a2633767..4daded0f 100644 --- a/ccalc/rpc/src/main/java/org/gwtapp/ccalc/rpc/proc/calculator/Calculator2.java +++ b/ccalc/rpc/src/main/java/org/gwtapp/ccalc/rpc/proc/calculator/Calculator2.java @@ -1,190 +1,193 @@ package org.gwtapp.ccalc.rpc.proc.calculator; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.gwtapp.ccalc.rpc.data.book.Calculation; import org.gwtapp.ccalc.rpc.data.book.CalculationImpl; import org.gwtapp.ccalc.rpc.data.book.Currency; import org.gwtapp.ccalc.rpc.data.book.Operation; import org.gwtapp.ccalc.rpc.data.book.OperationImpl; public class Calculator2 { private final static List<String> FIELDS = new ArrayList<String>(); static { FIELDS.addAll(new CalculationImpl().getPropertyNames()); FIELDS.removeAll(new OperationImpl().getPropertyNames()); } private final List<Calculation> calculations = new ArrayList<Calculation>(); private final List<Calculation> summaries = new ArrayList<Calculation>(); private final Map<Currency, List<Edge>> edges = new HashMap<Currency, List<Edge>>(); { for (Currency currency : Currency.values()) { edges.put(currency, new ArrayList<Edge>()); } } private final Currency baseCurrency; private final List<Integer> summariesPoints; public Calculator2(Currency baseCurrency, List<Operation> operations) { this(baseCurrency, Arrays.asList(new Integer[] { operations.size() }), operations); } public Calculator2(Currency baseCurrency, List<Integer> summariesPoints, List<Operation> operations) { this.baseCurrency = baseCurrency; this.summariesPoints = summariesPoints; for (Operation operation : operations) { Calculation calculation = new CalculationImpl(operation); for (String property : FIELDS) { calculation.set(property, null); } calculations.add(calculation); } calculate(); } public List<Calculation> getCalculations() { return calculations; } public List<Calculation> getSummaries() { return summaries; } private class Point { public int i; public double v; public Point(int i, double v) { this.i = i; this.v = v; } } public static class Edge { public int x, y; public double v, r; public Edge(int x, int y, double v, double r) { this.x = x; this.y = y; this.v = v; this.r = r; } } public void calculate() { for (Currency currency : Currency.values()) { calculate(currency); } calculateSummary(); } private void calculateSummary() { Iterator<Calculation> it = calculations.iterator(); for (Integer count : summariesPoints) { Calculation S = new CalculationImpl(); while (count-- > 0) { Calculation c = r(it.next()); S.setFifoBase(o(S.getFifoBase()) + o(c.getFifoBase())); S.setIncome(o(S.getIncome()) + o(c.getIncome())); S.setCost(o(S.getCost()) + o(c.getCost())); } summaries.add(r(S)); } } private double o(Double v) { if (v == null) { return 0.0; } else { return v; } } public static Double r(Double v) { if (v == null) { return null; } return Math.round(v * 1e2) / 1e2; } public static Double q(Double v) { if (v == null) { return null; } return Math.round(v * 1e4) / 1e4; } public static Calculation r(Calculation c) { c.setFifoBase(r(c.getFifoBase())); c.setIncome(r(c.getIncome())); c.setCost(r(c.getCost())); return c; } private void calculate(Currency currency) { List<Point> plus = new ArrayList<Point>(); List<Point> minus = new ArrayList<Point>(); if (currency != baseCurrency) { double SP = 0.0; double SM = 0.0; for (int i = 0; i < calculations.size(); i++) { Calculation calculation = calculations.get(i); if (calculation.getValue() != null && calculation.getCurrency() == currency) { Double value = r(calculation.getValue()); Double signum = Math.signum(value); if (value >= 0 && signum > 0) { SP += +value; plus.add(new Point(i, value)); } else if (value < 0 && signum < 0) { SM += -value; minus.add(new Point(i, -value)); } } } double D = r(SP - SM); if (D < 0) { // add virtual point plus.add(new Point(plus.size(), -D)); } double sp = 0.0; double sm = 0.0; while (!plus.isEmpty() && !minus.isEmpty()) { while (!plus.isEmpty() && plus.get(0).v <= 0) { plus.remove(0); } while (!minus.isEmpty() && minus.get(0).v <= 0) { minus.remove(0); } if (!plus.isEmpty() && !minus.isEmpty()) { sp += plus.get(0).v; sm += minus.get(0).v; double v = r(Math.min(plus.get(0).v, minus.get(0).v)); plus.get(0).v = r(plus.get(0).v - v); minus.get(0).v = r(minus.get(0).v - v); double r = 0.0; if (r(sp - sm) >= 0) { r = +calculations.get(plus.get(0).i).getExchange(); } else { r = -calculations.get(minus.get(0).i).getExchange(); } Edge edge = new Edge(plus.get(0).i, minus.get(0).i, v, r); edges.get(currency).add(edge); } } + if (!plus.isEmpty() || minus.isEmpty()) { + throw new IllegalStateException("(PM) Calculator is wrong!"); + } System.out.println(currency + ": " + plus.isEmpty() + " " + minus.isEmpty()); } } }
true
true
private void calculate(Currency currency) { List<Point> plus = new ArrayList<Point>(); List<Point> minus = new ArrayList<Point>(); if (currency != baseCurrency) { double SP = 0.0; double SM = 0.0; for (int i = 0; i < calculations.size(); i++) { Calculation calculation = calculations.get(i); if (calculation.getValue() != null && calculation.getCurrency() == currency) { Double value = r(calculation.getValue()); Double signum = Math.signum(value); if (value >= 0 && signum > 0) { SP += +value; plus.add(new Point(i, value)); } else if (value < 0 && signum < 0) { SM += -value; minus.add(new Point(i, -value)); } } } double D = r(SP - SM); if (D < 0) { // add virtual point plus.add(new Point(plus.size(), -D)); } double sp = 0.0; double sm = 0.0; while (!plus.isEmpty() && !minus.isEmpty()) { while (!plus.isEmpty() && plus.get(0).v <= 0) { plus.remove(0); } while (!minus.isEmpty() && minus.get(0).v <= 0) { minus.remove(0); } if (!plus.isEmpty() && !minus.isEmpty()) { sp += plus.get(0).v; sm += minus.get(0).v; double v = r(Math.min(plus.get(0).v, minus.get(0).v)); plus.get(0).v = r(plus.get(0).v - v); minus.get(0).v = r(minus.get(0).v - v); double r = 0.0; if (r(sp - sm) >= 0) { r = +calculations.get(plus.get(0).i).getExchange(); } else { r = -calculations.get(minus.get(0).i).getExchange(); } Edge edge = new Edge(plus.get(0).i, minus.get(0).i, v, r); edges.get(currency).add(edge); } } System.out.println(currency + ": " + plus.isEmpty() + " " + minus.isEmpty()); } }
private void calculate(Currency currency) { List<Point> plus = new ArrayList<Point>(); List<Point> minus = new ArrayList<Point>(); if (currency != baseCurrency) { double SP = 0.0; double SM = 0.0; for (int i = 0; i < calculations.size(); i++) { Calculation calculation = calculations.get(i); if (calculation.getValue() != null && calculation.getCurrency() == currency) { Double value = r(calculation.getValue()); Double signum = Math.signum(value); if (value >= 0 && signum > 0) { SP += +value; plus.add(new Point(i, value)); } else if (value < 0 && signum < 0) { SM += -value; minus.add(new Point(i, -value)); } } } double D = r(SP - SM); if (D < 0) { // add virtual point plus.add(new Point(plus.size(), -D)); } double sp = 0.0; double sm = 0.0; while (!plus.isEmpty() && !minus.isEmpty()) { while (!plus.isEmpty() && plus.get(0).v <= 0) { plus.remove(0); } while (!minus.isEmpty() && minus.get(0).v <= 0) { minus.remove(0); } if (!plus.isEmpty() && !minus.isEmpty()) { sp += plus.get(0).v; sm += minus.get(0).v; double v = r(Math.min(plus.get(0).v, minus.get(0).v)); plus.get(0).v = r(plus.get(0).v - v); minus.get(0).v = r(minus.get(0).v - v); double r = 0.0; if (r(sp - sm) >= 0) { r = +calculations.get(plus.get(0).i).getExchange(); } else { r = -calculations.get(minus.get(0).i).getExchange(); } Edge edge = new Edge(plus.get(0).i, minus.get(0).i, v, r); edges.get(currency).add(edge); } } if (!plus.isEmpty() || minus.isEmpty()) { throw new IllegalStateException("(PM) Calculator is wrong!"); } System.out.println(currency + ": " + plus.isEmpty() + " " + minus.isEmpty()); } }
diff --git a/src/com/android/deskclock/stopwatch/StopwatchService.java b/src/com/android/deskclock/stopwatch/StopwatchService.java index 76e6522f1..a76b7ce81 100644 --- a/src/com/android/deskclock/stopwatch/StopwatchService.java +++ b/src/com/android/deskclock/stopwatch/StopwatchService.java @@ -1,438 +1,440 @@ package com.android.deskclock.stopwatch; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.preference.PreferenceManager; import android.view.View; import android.widget.RemoteViews; import com.android.deskclock.CircleTimerView; import com.android.deskclock.DeskClock; import com.android.deskclock.R; import com.android.deskclock.Utils; /** * TODO: Insert description here. (generated by sblitz) */ public class StopwatchService extends Service { // Member fields private int mNumLaps; private long mElapsedTime; private long mStartTime; private boolean mLoadApp; private NotificationManager mNotificationManager; // Constants for intent information // Make this a large number to avoid the alarm ID's which seem to be 1, 2, ... // Must also be different than TimerReceiver.IN_USE_NOTIFICATION_ID private static final int NOTIFICATION_ID = Integer.MAX_VALUE - 1; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { mNumLaps = 0; mElapsedTime = 0; mStartTime = 0; mLoadApp = false; mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent == null) { return Service.START_NOT_STICKY; } if (mStartTime == 0 || mElapsedTime == 0 || mNumLaps == 0) { // May not have the most recent values. readFromSharedPrefs(); } String actionType = intent.getAction(); long actionTime = intent.getLongExtra(Stopwatches.MESSAGE_TIME, Utils.getTimeNow()); boolean showNotif = intent.getBooleanExtra(Stopwatches.SHOW_NOTIF, true); boolean updateCircle = showNotif; // Don't save updates to the cirle if we're in the app. if (actionType.equals(Stopwatches.START_STOPWATCH)) { mStartTime = actionTime; writeSharedPrefsStarted(mStartTime, updateCircle); if (showNotif) { setNotification(mStartTime - mElapsedTime, true, mNumLaps); } else { saveNotification(mStartTime - mElapsedTime, true, mNumLaps); } } else if (actionType.equals(Stopwatches.LAP_STOPWATCH)) { mNumLaps++; long lapTimeElapsed = actionTime - mStartTime + mElapsedTime; writeSharedPrefsLap(lapTimeElapsed, updateCircle); if (showNotif) { setNotification(mStartTime - mElapsedTime, true, mNumLaps); } else { saveNotification(mStartTime - mElapsedTime, true, mNumLaps); } } else if (actionType.equals(Stopwatches.STOP_STOPWATCH)) { mElapsedTime = mElapsedTime + (actionTime - mStartTime); writeSharedPrefsStopped(mElapsedTime, updateCircle); if (showNotif) { setNotification(actionTime - mElapsedTime, false, mNumLaps); } else { saveNotification(mElapsedTime, false, mNumLaps); } } else if (actionType.equals(Stopwatches.RESET_STOPWATCH)) { mLoadApp = false; writeSharedPrefsReset(updateCircle); clearSavedNotification(); stopSelf(); } else if (actionType.equals(Stopwatches.RESET_AND_LAUNCH_STOPWATCH)) { mLoadApp = true; writeSharedPrefsReset(updateCircle); clearSavedNotification(); closeNotificationShade(); stopSelf(); } else if (actionType.equals(Stopwatches.SHARE_STOPWATCH)) { closeNotificationShade(); Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra( Intent.EXTRA_SUBJECT, Stopwatches.getShareTitle(getApplicationContext())); shareIntent.putExtra(Intent.EXTRA_TEXT, Stopwatches.buildShareResults( getApplicationContext(), mElapsedTime, readLapsFromPrefs())); Intent chooserIntent = Intent.createChooser(shareIntent, null); chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplication().startActivity(chooserIntent); } else if (actionType.equals(Stopwatches.SHOW_NOTIF)) { // SHOW_NOTIF sent from the DeskClock.onPause // If a notification is not displayed, this service's work is over if (!showSavedNotification()) { stopSelf(); } } else if (actionType.equals(Stopwatches.KILL_NOTIF)) { mNotificationManager.cancel(NOTIFICATION_ID); } // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } @Override public void onDestroy() { mNotificationManager.cancel(NOTIFICATION_ID); clearSavedNotification(); mNumLaps = 0; mElapsedTime = 0; mStartTime = 0; if (mLoadApp) { Intent activityIntent = new Intent(getApplicationContext(), DeskClock.class); activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activityIntent.putExtra( DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.STOPWATCH_TAB_INDEX); startActivity(activityIntent); mLoadApp = false; } } private void setNotification(long clockBaseTime, boolean clockRunning, int numLaps) { Context context = getApplicationContext(); // Intent to load the app for a non-button click. Intent intent = new Intent(context, DeskClock.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.STOPWATCH_TAB_INDEX); + // add category to distinguish between stopwatch intents and timer intents + intent.addCategory("stopwatch"); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); // Set up remoteviews for the notification. RemoteViews remoteViewsCollapsed = new RemoteViews(getPackageName(), R.layout.stopwatch_notif_collapsed); remoteViewsCollapsed.setOnClickPendingIntent(R.id.swn_collapsed_hitspace, pendingIntent); remoteViewsCollapsed.setChronometer( R.id.swn_collapsed_chronometer, clockBaseTime, null, clockRunning); remoteViewsCollapsed. setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch); RemoteViews remoteViewsExpanded = new RemoteViews(getPackageName(), R.layout.stopwatch_notif_expanded); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_expanded_hitspace, pendingIntent); remoteViewsExpanded.setChronometer( R.id.swn_expanded_chronometer, clockBaseTime, null, clockRunning); remoteViewsExpanded. setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch); if (clockRunning) { // Left button: lap remoteViewsExpanded.setTextViewText( R.id.swn_left_button, getResources().getText(R.string.sw_lap_button)); Intent leftButtonIntent = new Intent(context, StopwatchService.class); leftButtonIntent.setAction(Stopwatches.LAP_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_left_button, PendingIntent.getService(context, 0, leftButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_left_button, R.drawable.ic_notify_lap, 0, 0, 0); // Right button: stop clock remoteViewsExpanded.setTextViewText( R.id.swn_right_button, getResources().getText(R.string.sw_stop_button)); Intent rightButtonIntent = new Intent(context, StopwatchService.class); rightButtonIntent.setAction(Stopwatches.STOP_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_right_button, PendingIntent.getService(context, 0, rightButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_right_button, R.drawable.ic_notify_stop, 0, 0, 0); // Show the laps if applicable. if (numLaps > 0) { String lapText = String.format( context.getString(R.string.sw_notification_lap_number), numLaps); remoteViewsCollapsed.setTextViewText(R.id.swn_collapsed_laps, lapText); remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.VISIBLE); remoteViewsExpanded.setTextViewText(R.id.swn_expanded_laps, lapText); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.VISIBLE); } else { remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.GONE); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.GONE); } } else { // Left button: reset clock remoteViewsExpanded.setTextViewText( R.id.swn_left_button, getResources().getText(R.string.sw_reset_button)); Intent leftButtonIntent = new Intent(context, StopwatchService.class); leftButtonIntent.setAction(Stopwatches.RESET_AND_LAUNCH_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_left_button, PendingIntent.getService(context, 0, leftButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_left_button, R.drawable.ic_notify_reset, 0, 0, 0); // Right button: start clock remoteViewsExpanded.setTextViewText( R.id.swn_right_button, getResources().getText(R.string.sw_start_button)); Intent rightButtonIntent = new Intent(context, StopwatchService.class); rightButtonIntent.setAction(Stopwatches.START_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_right_button, PendingIntent.getService(context, 0, rightButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_right_button, R.drawable.ic_notify_start, 0, 0, 0); // Show stopped string. remoteViewsCollapsed. setTextViewText(R.id.swn_collapsed_laps, getString(R.string.swn_stopped)); remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.VISIBLE); remoteViewsExpanded. setTextViewText(R.id.swn_expanded_laps, getString(R.string.swn_stopped)); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.VISIBLE); } Intent dismissIntent = new Intent(context, StopwatchService.class); dismissIntent.setAction(Stopwatches.RESET_STOPWATCH); Notification notification = new Notification.Builder(context) .setAutoCancel(!clockRunning) .setContent(remoteViewsCollapsed) .setOngoing(clockRunning) .setDeleteIntent(PendingIntent.getService(context, 0, dismissIntent, 0)) .setSmallIcon(R.drawable.ic_tab_stopwatch_activated) .setPriority(Notification.PRIORITY_MAX).build(); notification.bigContentView = remoteViewsExpanded; mNotificationManager.notify(NOTIFICATION_ID, notification); } /** Save the notification to be shown when the app is closed. **/ private void saveNotification(long clockTime, boolean clockRunning, int numLaps) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); if (clockRunning) { editor.putLong(Stopwatches.NOTIF_CLOCK_BASE, clockTime); editor.putLong(Stopwatches.NOTIF_CLOCK_ELAPSED, -1); editor.putBoolean(Stopwatches.NOTIF_CLOCK_RUNNING, true); } else { editor.putLong(Stopwatches.NOTIF_CLOCK_ELAPSED, clockTime); editor.putLong(Stopwatches.NOTIF_CLOCK_BASE, -1); editor.putBoolean(Stopwatches.NOTIF_CLOCK_RUNNING, false); } editor.putBoolean(Stopwatches.PREF_UPDATE_CIRCLE, false); editor.apply(); } /** Show the most recently saved notification. **/ private boolean showSavedNotification() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); long clockBaseTime = prefs.getLong(Stopwatches.NOTIF_CLOCK_BASE, -1); long clockElapsedTime = prefs.getLong(Stopwatches.NOTIF_CLOCK_ELAPSED, -1); boolean clockRunning = prefs.getBoolean(Stopwatches.NOTIF_CLOCK_RUNNING, false); int numLaps = prefs.getInt(Stopwatches.PREF_LAP_NUM, -1); if (clockBaseTime == -1) { if (clockElapsedTime == -1) { return false; } else { // We don't have a clock base time, so the clock is stopped. // Use the elapsed time to figure out what time to show. mElapsedTime = clockElapsedTime; clockBaseTime = Utils.getTimeNow() - clockElapsedTime; } } setNotification(clockBaseTime, clockRunning, numLaps); return true; } private void clearSavedNotification() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); editor.remove(Stopwatches.NOTIF_CLOCK_BASE); editor.remove(Stopwatches.NOTIF_CLOCK_RUNNING); editor.remove(Stopwatches.NOTIF_CLOCK_ELAPSED); editor.apply(); } private void closeNotificationShade() { Intent intent = new Intent(); intent.setAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); sendBroadcast(intent); } private void readFromSharedPrefs() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); mStartTime = prefs.getLong(Stopwatches.PREF_START_TIME, 0); mElapsedTime = prefs.getLong(Stopwatches.PREF_ACCUM_TIME, 0); mNumLaps = prefs.getInt(Stopwatches.PREF_LAP_NUM, Stopwatches.STOPWATCH_RESET); } private long[] readLapsFromPrefs() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); int numLaps = prefs.getInt(Stopwatches.PREF_LAP_NUM, Stopwatches.STOPWATCH_RESET); long[] laps = new long[numLaps]; long prevLapElapsedTime = 0; for (int lap_i = 0; lap_i < numLaps; lap_i++) { String key = Stopwatches.PREF_LAP_TIME + Integer.toString(lap_i + 1); long lap = prefs.getLong(key, 0); if (lap == prevLapElapsedTime && lap_i == numLaps - 1) { lap = mElapsedTime; } laps[numLaps - lap_i - 1] = lap - prevLapElapsedTime; prevLapElapsedTime = lap; } return laps; } private void writeToSharedPrefs(Long startTime, Long lapTimeElapsed, Long elapsedTime, Integer state, boolean updateCircle) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); if (startTime != null) { editor.putLong(Stopwatches.PREF_START_TIME, startTime); mStartTime = startTime; } if (lapTimeElapsed != null) { int numLaps = prefs.getInt(Stopwatches.PREF_LAP_NUM, 0); if (numLaps == 0) { mNumLaps++; numLaps++; } editor.putLong(Stopwatches.PREF_LAP_TIME + Integer.toString(numLaps), lapTimeElapsed); numLaps++; editor.putLong(Stopwatches.PREF_LAP_TIME + Integer.toString(numLaps), lapTimeElapsed); editor.putInt(Stopwatches.PREF_LAP_NUM, numLaps); } if (elapsedTime != null) { editor.putLong(Stopwatches.PREF_ACCUM_TIME, elapsedTime); mElapsedTime = elapsedTime; } if (state != null) { if (state == Stopwatches.STOPWATCH_RESET) { editor.putInt(Stopwatches.PREF_STATE, Stopwatches.STOPWATCH_RESET); } else if (state == Stopwatches.STOPWATCH_RUNNING) { editor.putInt(Stopwatches.PREF_STATE, Stopwatches.STOPWATCH_RUNNING); } else if (state == Stopwatches.STOPWATCH_STOPPED) { editor.putInt(Stopwatches.PREF_STATE, Stopwatches.STOPWATCH_STOPPED); } } editor.putBoolean(Stopwatches.PREF_UPDATE_CIRCLE, updateCircle); editor.apply(); } private void writeSharedPrefsStarted(long startTime, boolean updateCircle) { writeToSharedPrefs(startTime, null, null, Stopwatches.STOPWATCH_RUNNING, updateCircle); if (updateCircle) { long time = Utils.getTimeNow(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); long intervalStartTime = prefs.getLong( Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL_START, -1); if (intervalStartTime != -1) { intervalStartTime = time; SharedPreferences.Editor editor = prefs.edit(); editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL_START, intervalStartTime); editor.putBoolean(Stopwatches.KEY + CircleTimerView.PREF_CTV_PAUSED, false); editor.apply(); } } } private void writeSharedPrefsLap(long lapTimeElapsed, boolean updateCircle) { writeToSharedPrefs(null, lapTimeElapsed, null, null, updateCircle); if (updateCircle) { long time = Utils.getTimeNow(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); long laps[] = readLapsFromPrefs(); int numLaps = laps.length; long lapTime = laps[1]; if (numLaps == 2) { // Have only hit lap once. editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL, lapTime); } else { editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_MARKER_TIME, lapTime); } editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_ACCUM_TIME, 0); if (numLaps < Stopwatches.MAX_LAPS) { editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL_START, time); editor.putBoolean(Stopwatches.KEY + CircleTimerView.PREF_CTV_PAUSED, false); } else { editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL_START, -1); } editor.apply(); } } private void writeSharedPrefsStopped(long elapsedTime, boolean updateCircle) { writeToSharedPrefs(null, null, elapsedTime, Stopwatches.STOPWATCH_STOPPED, updateCircle); if (updateCircle) { long time = Utils.getTimeNow(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); long accumulatedTime = prefs.getLong( Stopwatches.KEY + CircleTimerView.PREF_CTV_ACCUM_TIME, 0); long intervalStartTime = prefs.getLong( Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL_START, -1); accumulatedTime += time - intervalStartTime; SharedPreferences.Editor editor = prefs.edit(); editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_ACCUM_TIME, accumulatedTime); editor.putBoolean(Stopwatches.KEY + CircleTimerView.PREF_CTV_PAUSED, true); editor.putLong( Stopwatches.KEY + CircleTimerView.PREF_CTV_CURRENT_INTERVAL, accumulatedTime); editor.apply(); } } private void writeSharedPrefsReset(boolean updateCircle) { writeToSharedPrefs(null, null, null, Stopwatches.STOPWATCH_RESET, updateCircle); } }
true
true
private void setNotification(long clockBaseTime, boolean clockRunning, int numLaps) { Context context = getApplicationContext(); // Intent to load the app for a non-button click. Intent intent = new Intent(context, DeskClock.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.STOPWATCH_TAB_INDEX); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); // Set up remoteviews for the notification. RemoteViews remoteViewsCollapsed = new RemoteViews(getPackageName(), R.layout.stopwatch_notif_collapsed); remoteViewsCollapsed.setOnClickPendingIntent(R.id.swn_collapsed_hitspace, pendingIntent); remoteViewsCollapsed.setChronometer( R.id.swn_collapsed_chronometer, clockBaseTime, null, clockRunning); remoteViewsCollapsed. setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch); RemoteViews remoteViewsExpanded = new RemoteViews(getPackageName(), R.layout.stopwatch_notif_expanded); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_expanded_hitspace, pendingIntent); remoteViewsExpanded.setChronometer( R.id.swn_expanded_chronometer, clockBaseTime, null, clockRunning); remoteViewsExpanded. setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch); if (clockRunning) { // Left button: lap remoteViewsExpanded.setTextViewText( R.id.swn_left_button, getResources().getText(R.string.sw_lap_button)); Intent leftButtonIntent = new Intent(context, StopwatchService.class); leftButtonIntent.setAction(Stopwatches.LAP_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_left_button, PendingIntent.getService(context, 0, leftButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_left_button, R.drawable.ic_notify_lap, 0, 0, 0); // Right button: stop clock remoteViewsExpanded.setTextViewText( R.id.swn_right_button, getResources().getText(R.string.sw_stop_button)); Intent rightButtonIntent = new Intent(context, StopwatchService.class); rightButtonIntent.setAction(Stopwatches.STOP_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_right_button, PendingIntent.getService(context, 0, rightButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_right_button, R.drawable.ic_notify_stop, 0, 0, 0); // Show the laps if applicable. if (numLaps > 0) { String lapText = String.format( context.getString(R.string.sw_notification_lap_number), numLaps); remoteViewsCollapsed.setTextViewText(R.id.swn_collapsed_laps, lapText); remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.VISIBLE); remoteViewsExpanded.setTextViewText(R.id.swn_expanded_laps, lapText); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.VISIBLE); } else { remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.GONE); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.GONE); } } else { // Left button: reset clock remoteViewsExpanded.setTextViewText( R.id.swn_left_button, getResources().getText(R.string.sw_reset_button)); Intent leftButtonIntent = new Intent(context, StopwatchService.class); leftButtonIntent.setAction(Stopwatches.RESET_AND_LAUNCH_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_left_button, PendingIntent.getService(context, 0, leftButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_left_button, R.drawable.ic_notify_reset, 0, 0, 0); // Right button: start clock remoteViewsExpanded.setTextViewText( R.id.swn_right_button, getResources().getText(R.string.sw_start_button)); Intent rightButtonIntent = new Intent(context, StopwatchService.class); rightButtonIntent.setAction(Stopwatches.START_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_right_button, PendingIntent.getService(context, 0, rightButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_right_button, R.drawable.ic_notify_start, 0, 0, 0); // Show stopped string. remoteViewsCollapsed. setTextViewText(R.id.swn_collapsed_laps, getString(R.string.swn_stopped)); remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.VISIBLE); remoteViewsExpanded. setTextViewText(R.id.swn_expanded_laps, getString(R.string.swn_stopped)); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.VISIBLE); } Intent dismissIntent = new Intent(context, StopwatchService.class); dismissIntent.setAction(Stopwatches.RESET_STOPWATCH); Notification notification = new Notification.Builder(context) .setAutoCancel(!clockRunning) .setContent(remoteViewsCollapsed) .setOngoing(clockRunning) .setDeleteIntent(PendingIntent.getService(context, 0, dismissIntent, 0)) .setSmallIcon(R.drawable.ic_tab_stopwatch_activated) .setPriority(Notification.PRIORITY_MAX).build(); notification.bigContentView = remoteViewsExpanded; mNotificationManager.notify(NOTIFICATION_ID, notification); }
private void setNotification(long clockBaseTime, boolean clockRunning, int numLaps) { Context context = getApplicationContext(); // Intent to load the app for a non-button click. Intent intent = new Intent(context, DeskClock.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.STOPWATCH_TAB_INDEX); // add category to distinguish between stopwatch intents and timer intents intent.addCategory("stopwatch"); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); // Set up remoteviews for the notification. RemoteViews remoteViewsCollapsed = new RemoteViews(getPackageName(), R.layout.stopwatch_notif_collapsed); remoteViewsCollapsed.setOnClickPendingIntent(R.id.swn_collapsed_hitspace, pendingIntent); remoteViewsCollapsed.setChronometer( R.id.swn_collapsed_chronometer, clockBaseTime, null, clockRunning); remoteViewsCollapsed. setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch); RemoteViews remoteViewsExpanded = new RemoteViews(getPackageName(), R.layout.stopwatch_notif_expanded); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_expanded_hitspace, pendingIntent); remoteViewsExpanded.setChronometer( R.id.swn_expanded_chronometer, clockBaseTime, null, clockRunning); remoteViewsExpanded. setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch); if (clockRunning) { // Left button: lap remoteViewsExpanded.setTextViewText( R.id.swn_left_button, getResources().getText(R.string.sw_lap_button)); Intent leftButtonIntent = new Intent(context, StopwatchService.class); leftButtonIntent.setAction(Stopwatches.LAP_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_left_button, PendingIntent.getService(context, 0, leftButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_left_button, R.drawable.ic_notify_lap, 0, 0, 0); // Right button: stop clock remoteViewsExpanded.setTextViewText( R.id.swn_right_button, getResources().getText(R.string.sw_stop_button)); Intent rightButtonIntent = new Intent(context, StopwatchService.class); rightButtonIntent.setAction(Stopwatches.STOP_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_right_button, PendingIntent.getService(context, 0, rightButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_right_button, R.drawable.ic_notify_stop, 0, 0, 0); // Show the laps if applicable. if (numLaps > 0) { String lapText = String.format( context.getString(R.string.sw_notification_lap_number), numLaps); remoteViewsCollapsed.setTextViewText(R.id.swn_collapsed_laps, lapText); remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.VISIBLE); remoteViewsExpanded.setTextViewText(R.id.swn_expanded_laps, lapText); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.VISIBLE); } else { remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.GONE); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.GONE); } } else { // Left button: reset clock remoteViewsExpanded.setTextViewText( R.id.swn_left_button, getResources().getText(R.string.sw_reset_button)); Intent leftButtonIntent = new Intent(context, StopwatchService.class); leftButtonIntent.setAction(Stopwatches.RESET_AND_LAUNCH_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_left_button, PendingIntent.getService(context, 0, leftButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_left_button, R.drawable.ic_notify_reset, 0, 0, 0); // Right button: start clock remoteViewsExpanded.setTextViewText( R.id.swn_right_button, getResources().getText(R.string.sw_start_button)); Intent rightButtonIntent = new Intent(context, StopwatchService.class); rightButtonIntent.setAction(Stopwatches.START_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_right_button, PendingIntent.getService(context, 0, rightButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_right_button, R.drawable.ic_notify_start, 0, 0, 0); // Show stopped string. remoteViewsCollapsed. setTextViewText(R.id.swn_collapsed_laps, getString(R.string.swn_stopped)); remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.VISIBLE); remoteViewsExpanded. setTextViewText(R.id.swn_expanded_laps, getString(R.string.swn_stopped)); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.VISIBLE); } Intent dismissIntent = new Intent(context, StopwatchService.class); dismissIntent.setAction(Stopwatches.RESET_STOPWATCH); Notification notification = new Notification.Builder(context) .setAutoCancel(!clockRunning) .setContent(remoteViewsCollapsed) .setOngoing(clockRunning) .setDeleteIntent(PendingIntent.getService(context, 0, dismissIntent, 0)) .setSmallIcon(R.drawable.ic_tab_stopwatch_activated) .setPriority(Notification.PRIORITY_MAX).build(); notification.bigContentView = remoteViewsExpanded; mNotificationManager.notify(NOTIFICATION_ID, notification); }
diff --git a/src/core/SoundStore.java b/src/core/SoundStore.java index b4f27f3..e4f6a7d 100644 --- a/src/core/SoundStore.java +++ b/src/core/SoundStore.java @@ -1,236 +1,236 @@ package core; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; public class SoundStore { private static SoundStore soundStore; private float globalVolume = 1; public Map<String, Sound> sounds; private Map<String, Music> musics; private Set<String> playingSounds = new HashSet<String>(); /** * Private constructor, creates the singleton */ private SoundStore() { soundStore = this; sounds = new HashMap<String, Sound>(); musics = new HashMap<String, Music>(); try { initialize(); } catch (SlickException e) { System.err.println(e.getStackTrace()); } } /** * If soundstore doesn't exist, create it, otherwise just return it * @return the instance of soundstore */ public static SoundStore get() { if (soundStore == null) { soundStore = new SoundStore(); } return soundStore; } /** * Creates all the sounds so that there is no lag in making them later. * @throws SlickException */ private void initialize() throws SlickException { addToMusic("Crackling Fire", new Music("resources/sounds/crackling_fire.ogg")); addToMusic("GBU", new Music("resources/sounds/GBU.ogg")); addToMusic("River", new Music("resources/sounds/river.ogg")); addToSounds("Smooth", new Sound("resources/sounds/smooth.ogg")); addToSounds("Steps", new Sound("resources/sounds/steps.ogg")); addToSounds("Click", new Sound("resources/sounds/click.ogg")); addToSounds("ItemGet", new Sound("resources/sounds/itemGet.ogg")); addToSounds("WolfHowl", new Sound("resources/sounds/wolfHowl.ogg")); addToSounds("Rooster", new Sound("resources/sounds/rooster.ogg")); addToSounds("Splash", new Sound("resources/sounds/splash.ogg")); addToMusic("DayTheme", new Music("resources/sounds/walkingDaytimeMusic.ogg")); addToMusic("NightTheme", new Music("resources/sounds/Creepy Wind.ogg")); addToMusic("FFD", new Music("resources/sounds/FFD.ogg")); addToMusic("MS", new Music("resources/sounds/MagnificentSeven.ogg")); addToSounds("RK", new Sound("resources/sounds/RiverKwai.ogg")); addToSounds("CowMoo", new Sound("resources/sounds/CowMoo.ogg")); addToSounds("Donkey", new Sound("resources/sounds/Donkey.ogg")); addToSounds("HorseWhinny", new Sound("resources/sounds/HorseWhinny.ogg")); - addToMusic("FarewellCheyenne", new Music("resources/sounds/FarewellCheyenne.org")); - addToMusic("HangEmHigh", new Music("resources/sounds/HangEmHigh.org")); - addToMusic("HowTheWest", new Music("resources/sounds/HowTheWest.org")); - addToMusic("JesseJames", new Music("resources/sounds/JesseJames.org")); - addToMusic("MyNameIsNobody", new Music("resources/sounds/MyNameIsNobody.org")); - addToMusic("WanderingTrail", new Music("resources/sounds/WanderingTrail.org")); + addToMusic("FarewellCheyenne", new Music("resources/sounds/FarewellCheyenne.ogg")); + addToMusic("HangEmHigh", new Music("resources/sounds/HangEmHigh.ogg")); + addToMusic("HowTheWest", new Music("resources/sounds/HowTheWest.ogg")); + addToMusic("JesseJames", new Music("resources/sounds/JesseJames.ogg")); + addToMusic("MyNameIsNobody", new Music("resources/sounds/MyNameIsNobody.ogg")); + addToMusic("WanderingTrail", new Music("resources/sounds/WanderingTrail.ogg")); } public String getPlayingMusic() { for (String name : musics.keySet()) { if (musics.get(name).playing()) { return name; } } return null; } /** * Adds a music to the list of music in the store * @param name The name the music is referred to by * @param music The music itself */ private void addToMusic(String name, Music music) { musics.put(name, music); } /** * Sets the overall volume to a specific level (0 is mute, 1 is full volume) * @param volume The volume to set to. */ public void setVolume(float volume) { globalVolume = volume < 0 ? 0 : volume > 1 ? 1 : volume; setMusicVolume(1); } public float getVolume() { return globalVolume; } /** * Sets just the music volumes to a specific level. * Updates the current musics volume if it is playing * @param volume The volume to set to */ public void setMusicVolume(float volume) { if(getPlayingMusic() != null) { musics.get(getPlayingMusic()).setVolume(globalVolume * (volume < 0 ? 0 : volume > 1 ? 1 : volume)); } } /** * Plays the music, but on loop * @param name The key for the music. */ public void loopMusic(String name) { stopMusic(); musics.get(name).loop(); musics.get(name).setVolume(globalVolume); } /** * Plays the music not on loop * @param name The key for the music */ public void playMusic(String name) { stopMusic(); musics.get(name).play(); musics.get(name).setVolume(globalVolume); } /** * Plays the music at a specific volume * @param name * @param volume */ public void playMusic(String name, float volume) { stopMusic(); musics.get(name).play(); setMusicVolume(volume); } /** * Stops the currently playing music */ public void stopMusic() { for (String name : musics.keySet()) { if (musics.get(name).playing()) { musics.get(name).stop(); } } } /** * Adds a sound effect to the list * @param name The key for the sound * @param sound The sound itself */ private void addToSounds(String name, Sound sound) { sounds.put(name, sound); } /** * Plays a sound * @param name The key of the sound */ public void playSound(String name) { sounds.get(name).play(1, globalVolume); playingSounds.add(name); } public void playSound(String name, float volume) { sounds.get(name).play(1, globalVolume *volume); playingSounds.add(name); } /** * Stops the specific sound being played. * @param name The sound to stop */ public void stopSound(String name) { sounds.get(name).stop(); playingSounds.remove(name); } /** * Returns a list of all sounds currently playing * @return A list of all sounds currently playing */ public Set<String> getPlayingSounds() { Set<String> newSet = new HashSet<String>(); for (String name : playingSounds) { if (sounds.get(name).playing()) { newSet.add(name); } } return newSet; } /** * Stops all playing sounds */ public void stopAllSound() { for (String name : sounds.keySet()) { if (sounds.get(name).playing()) { sounds.get(name).stop(); } } playingSounds.clear(); } public void loopSound(String name) { sounds.get(name).loop(); } /** * Stop EVERYTHING */ public void stop() { stopAllSound(); stopMusic(); } }
true
true
private void initialize() throws SlickException { addToMusic("Crackling Fire", new Music("resources/sounds/crackling_fire.ogg")); addToMusic("GBU", new Music("resources/sounds/GBU.ogg")); addToMusic("River", new Music("resources/sounds/river.ogg")); addToSounds("Smooth", new Sound("resources/sounds/smooth.ogg")); addToSounds("Steps", new Sound("resources/sounds/steps.ogg")); addToSounds("Click", new Sound("resources/sounds/click.ogg")); addToSounds("ItemGet", new Sound("resources/sounds/itemGet.ogg")); addToSounds("WolfHowl", new Sound("resources/sounds/wolfHowl.ogg")); addToSounds("Rooster", new Sound("resources/sounds/rooster.ogg")); addToSounds("Splash", new Sound("resources/sounds/splash.ogg")); addToMusic("DayTheme", new Music("resources/sounds/walkingDaytimeMusic.ogg")); addToMusic("NightTheme", new Music("resources/sounds/Creepy Wind.ogg")); addToMusic("FFD", new Music("resources/sounds/FFD.ogg")); addToMusic("MS", new Music("resources/sounds/MagnificentSeven.ogg")); addToSounds("RK", new Sound("resources/sounds/RiverKwai.ogg")); addToSounds("CowMoo", new Sound("resources/sounds/CowMoo.ogg")); addToSounds("Donkey", new Sound("resources/sounds/Donkey.ogg")); addToSounds("HorseWhinny", new Sound("resources/sounds/HorseWhinny.ogg")); addToMusic("FarewellCheyenne", new Music("resources/sounds/FarewellCheyenne.org")); addToMusic("HangEmHigh", new Music("resources/sounds/HangEmHigh.org")); addToMusic("HowTheWest", new Music("resources/sounds/HowTheWest.org")); addToMusic("JesseJames", new Music("resources/sounds/JesseJames.org")); addToMusic("MyNameIsNobody", new Music("resources/sounds/MyNameIsNobody.org")); addToMusic("WanderingTrail", new Music("resources/sounds/WanderingTrail.org")); }
private void initialize() throws SlickException { addToMusic("Crackling Fire", new Music("resources/sounds/crackling_fire.ogg")); addToMusic("GBU", new Music("resources/sounds/GBU.ogg")); addToMusic("River", new Music("resources/sounds/river.ogg")); addToSounds("Smooth", new Sound("resources/sounds/smooth.ogg")); addToSounds("Steps", new Sound("resources/sounds/steps.ogg")); addToSounds("Click", new Sound("resources/sounds/click.ogg")); addToSounds("ItemGet", new Sound("resources/sounds/itemGet.ogg")); addToSounds("WolfHowl", new Sound("resources/sounds/wolfHowl.ogg")); addToSounds("Rooster", new Sound("resources/sounds/rooster.ogg")); addToSounds("Splash", new Sound("resources/sounds/splash.ogg")); addToMusic("DayTheme", new Music("resources/sounds/walkingDaytimeMusic.ogg")); addToMusic("NightTheme", new Music("resources/sounds/Creepy Wind.ogg")); addToMusic("FFD", new Music("resources/sounds/FFD.ogg")); addToMusic("MS", new Music("resources/sounds/MagnificentSeven.ogg")); addToSounds("RK", new Sound("resources/sounds/RiverKwai.ogg")); addToSounds("CowMoo", new Sound("resources/sounds/CowMoo.ogg")); addToSounds("Donkey", new Sound("resources/sounds/Donkey.ogg")); addToSounds("HorseWhinny", new Sound("resources/sounds/HorseWhinny.ogg")); addToMusic("FarewellCheyenne", new Music("resources/sounds/FarewellCheyenne.ogg")); addToMusic("HangEmHigh", new Music("resources/sounds/HangEmHigh.ogg")); addToMusic("HowTheWest", new Music("resources/sounds/HowTheWest.ogg")); addToMusic("JesseJames", new Music("resources/sounds/JesseJames.ogg")); addToMusic("MyNameIsNobody", new Music("resources/sounds/MyNameIsNobody.ogg")); addToMusic("WanderingTrail", new Music("resources/sounds/WanderingTrail.ogg")); }
diff --git a/rdfbean-sesame/src/main/java/com/mysema/rdfbean/sesame/RDFSource.java b/rdfbean-sesame/src/main/java/com/mysema/rdfbean/sesame/RDFSource.java index 3f35502c..a35f606d 100644 --- a/rdfbean-sesame/src/main/java/com/mysema/rdfbean/sesame/RDFSource.java +++ b/rdfbean-sesame/src/main/java/com/mysema/rdfbean/sesame/RDFSource.java @@ -1,81 +1,85 @@ /* * Copyright (c) 2009 Mysema Ltd. * All rights reserved. * */ package com.mysema.rdfbean.sesame; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import org.openrdf.repository.RepositoryConnection; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.openrdf.store.StoreException; import com.mysema.commons.lang.Assert; public class RDFSource { private String resource; private RDFFormat format; private String context = "http://semantics.mysema.com/example#"; public RDFSource() { } public RDFSource(String resource) { this.resource = resource; } public RDFSource(String resource, RDFFormat format, String context) { this.resource = resource; this.format = format; this.context = context; } public String getContext() { return context; } public RDFFormat getFormat() { return format; } public String getResource() { return resource; } public InputStream openStream() throws MalformedURLException, IOException { if (resource.startsWith("classpath:")){ - return getClass().getResourceAsStream(resource.substring(10)); + String name = resource.substring(10); + if (name.startsWith("/")) { + name = name.substring(1); + } + return RDFSource.class.getClassLoader().getResourceAsStream(name); }else{ return new URL(resource).openStream(); } } public void setContext(String context) { this.context = Assert.notNull(context); } public void setFormat(RDFFormat format) { this.format = Assert.notNull(format); } public void setResource(String resource) { this.resource = Assert.notNull(resource); } public void readInto(RepositoryConnection conn) throws RDFParseException, StoreException, IOException { if (format == null) { format = RDFFormat.forFileName(getResource()); } conn.add(openStream(), context, format); } }
true
true
public InputStream openStream() throws MalformedURLException, IOException { if (resource.startsWith("classpath:")){ return getClass().getResourceAsStream(resource.substring(10)); }else{ return new URL(resource).openStream(); } }
public InputStream openStream() throws MalformedURLException, IOException { if (resource.startsWith("classpath:")){ String name = resource.substring(10); if (name.startsWith("/")) { name = name.substring(1); } return RDFSource.class.getClassLoader().getResourceAsStream(name); }else{ return new URL(resource).openStream(); } }
diff --git a/cotrix/cotrix-web-demo/src/main/java/org/cotrix/web/demo/client/credential/CredentialsPopupController.java b/cotrix/cotrix-web-demo/src/main/java/org/cotrix/web/demo/client/credential/CredentialsPopupController.java index 979066e9..dca00f25 100644 --- a/cotrix/cotrix-web-demo/src/main/java/org/cotrix/web/demo/client/credential/CredentialsPopupController.java +++ b/cotrix/cotrix-web-demo/src/main/java/org/cotrix/web/demo/client/credential/CredentialsPopupController.java @@ -1,90 +1,90 @@ /** * */ package org.cotrix.web.demo.client.credential; import org.cotrix.web.common.client.event.CotrixBus; import org.cotrix.web.common.client.event.CotrixStartupEvent; import org.cotrix.web.common.client.event.ExtensibleComponentReadyEvent; import org.cotrix.web.demo.client.resources.CotrixDemoResources; import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.InlineHTML; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; import com.google.web.bindery.event.shared.binder.EventBinder; import com.google.web.bindery.event.shared.binder.EventHandler; /** * @author "Federico De Faveri [email protected]" * */ public class CredentialsPopupController { private static final String COOKIE_NAME = "COTRIX_SHOW_DEMO_CREDENTIAL"; interface CredentialPopupControllerEventBinder extends EventBinder<CredentialsPopupController>{}; @Inject CredentialsPopup credentialsPopup; @Inject CotrixDemoResources resources; @Inject private void bind(CredentialPopupControllerEventBinder binder, @CotrixBus EventBus eventBus) { binder.bindEventHandlers(this, eventBus); } public void init(){ } @EventHandler void onUserBarReady(ExtensibleComponentReadyEvent componentReadyEvent) { if (componentReadyEvent.getComponentName().equals("UserBar")) { Log.trace("UserBar Ready"); HasWidgets extensionArea = componentReadyEvent.getHasExtensionArea().getExtensionArea(); - InlineHTML demoLink = new InlineHTML("It's only a demo..."); + InlineHTML demoLink = new InlineHTML("It's just a demo..."); demoLink.setStyleName(resources.css().demoLabel()); extensionArea.add(demoLink); demoLink.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { credentialsPopup.showCentered(); } }); } } @EventHandler void onCotrixStartup(CotrixStartupEvent event){ Log.trace("Showing demo credentials"); boolean showPopup = shouldShowDemoCredential(); if (showPopup) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { credentialsPopup.showCentered(); } }); } } private boolean shouldShowDemoCredential() { String value = Cookies.getCookie(COOKIE_NAME); if (value == null) Cookies.setCookie(COOKIE_NAME, "TRUE"); return value == null; } }
true
true
void onUserBarReady(ExtensibleComponentReadyEvent componentReadyEvent) { if (componentReadyEvent.getComponentName().equals("UserBar")) { Log.trace("UserBar Ready"); HasWidgets extensionArea = componentReadyEvent.getHasExtensionArea().getExtensionArea(); InlineHTML demoLink = new InlineHTML("It's only a demo..."); demoLink.setStyleName(resources.css().demoLabel()); extensionArea.add(demoLink); demoLink.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { credentialsPopup.showCentered(); } }); } }
void onUserBarReady(ExtensibleComponentReadyEvent componentReadyEvent) { if (componentReadyEvent.getComponentName().equals("UserBar")) { Log.trace("UserBar Ready"); HasWidgets extensionArea = componentReadyEvent.getHasExtensionArea().getExtensionArea(); InlineHTML demoLink = new InlineHTML("It's just a demo..."); demoLink.setStyleName(resources.css().demoLabel()); extensionArea.add(demoLink); demoLink.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { credentialsPopup.showCentered(); } }); } }
diff --git a/src/java-server-framework/org/xins/server/Function.java b/src/java-server-framework/org/xins/server/Function.java index 135a49259..9c0c59aba 100644 --- a/src/java-server-framework/org/xins/server/Function.java +++ b/src/java-server-framework/org/xins/server/Function.java @@ -1,345 +1,345 @@ /* * $Id$ * * Copyright 2003-2005 Wanadoo Nederland B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.server; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.manageable.Manageable; import org.xins.logdoc.LogdocSerializable; /** * Base class for function implementation classes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>) * * @since XINS 1.0.0 */ public abstract class Function extends Manageable implements DefaultResultCodes { //------------------------------------------------------------------------- // Class fields //------------------------------------------------------------------------- /** * Call result to be returned when a function is currently disabled. See * {@link #isEnabled()}. */ private static final FunctionResult DISABLED_FUNCTION_RESULT = new FunctionResult("_DisabledFunction"); //------------------------------------------------------------------------- // Class functions //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Constructors //------------------------------------------------------------------------- /** * Constructs a new <code>Function</code>. * * @param api * the API to which this function belongs, not <code>null</code>. * * @param name * the name, not <code>null</code>. * * @param version * the version of the specification this function implements, not * <code>null</code>. * * @throws IllegalArgumentException * if <code>api == null || name == null || version == null</code>. */ protected Function(API api, String name, String version) throws IllegalArgumentException { // Check arguments MandatoryArgumentChecker.check("api", api, "name", name, "version", version); // Initialize fields _statistics = new FunctionStatistics(); _api = api; _name = name; _version = version; _enabled = true; // Notify the API that a Function has been added _api.functionAdded(this); } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- /** * The API implementation this function is part of. This field cannot be * <code>null</code>. */ private final API _api; /** * The name of this function. This field cannot be <code>null</code>. */ private final String _name; /** * The version of the specification this function implements. This field * cannot be <code>null</code>. */ private final String _version; /** * Flag that indicates if this function is currently accessible. */ private boolean _enabled; /** * Lock object for <code>_callCount</code>. This field cannot be * <code>null</code>. */ private final Object _callCountLock = new Object(); /** * The total number of calls executed up until now. */ private int _callCount; /** * Statistics object linked to this function. This field cannot be * <code>null</code>. */ private final FunctionStatistics _statistics; //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- /** * Returns the API that contains this function. * * @return * the {@link API}, not <code>null</code>. */ public final API getAPI() { return _api; } /** * Returns the name of this function. * * @return * the name, not <code>null</code>. */ final String getName() { return _name; } /** * Returns the specification version for this function. * * @return * the version, not <code>null</code>. */ final String getVersion() { return _version; } /** * Checks if this function is currently accessible. * * @return * <code>true</code> if this function is currently accessible, * <code>false</code> otherwise. */ public final boolean isEnabled() { return _enabled; } /** * Sets if this function is currently accessible. * * @param enabled * <code>true</code> if this function should be accessible, * <code>false</code> if not. */ public final void setEnabled(boolean enabled) { _enabled = enabled; } /** * Returns the call statistics for this function. * * @return * the statistics, never <code>null</code>. */ final FunctionStatistics getStatistics() { return _statistics; } /** * Assigns a new call ID for the caller. Every call to this method will * return an increasing number. * * @return * the assigned call ID, &gt;= 0. */ final int assignCallID() { int callID; synchronized (_callCountLock) { callID = _callCount++; } return callID; } /** * Handles a call to this function (wrapper method). This method will call * {@link #handleCall(CallContext context)}. * * @param start * the start time of the call, as milliseconds since midnight January 1, * 1970. * * @param functionRequest * the request, never <code>null</code>. * * @param ip * the IP address of the requester, never <code>null</code>. * * @return * the call result, never <code>null</code>. * * @throws IllegalStateException * if this object is currently not initialized. */ FunctionResult handleCall(long start, FunctionRequest functionRequest, String ip) throws IllegalStateException { // Check state first assertUsable(); // Assign a call ID int callID = assignCallID(); // Check if this function is enabled if (! _enabled) { performedCall(functionRequest, ip, start, callID, DISABLED_FUNCTION_RESULT); return DISABLED_FUNCTION_RESULT; } // Construct a CallContext object CallContext context = new CallContext(functionRequest, start, this, callID, ip); FunctionResult result; try { // Handle the call result = handleCall(context); // Make sure the result is valid InvalidResponseResult invalidResponse = result.checkOutputParameters(); if (invalidResponse != null) { result = invalidResponse; Log.log_3501(functionRequest.getFunctionName(), callID); } } catch (Throwable exception) { result = _api.handleFunctionException(start, functionRequest, ip, callID, exception); - } + } // Update function statistics // We assume that this method will never throw any exception performedCall(functionRequest, ip, start, callID, result); return result; } /** * Handles a call to this function. * * @param context * the context for this call, never <code>null</code>. * * @return * the result of the call, never <code>null</code>. * * @throws Throwable * if anything goes wrong. */ protected abstract FunctionResult handleCall(CallContext context) throws Throwable; /** * Callback method that should be called after a call to this function. * This method will update the statistics for this funciton and perform * transaction logging. * * <p />This method should <em>never</em> throw any * {@link RuntimeException}. If it does, then that should be considered a * serious bug. * * @param functionRequest * the request, should not be <code>null</code>. * * @param ip * the ip of the requester, should not be <code>null</code>. * * @param start * the start time, as a number of milliseconds since January 1, 1970. * * @param callID * the assigned call ID. * * @param result * the call result, should not be <code>null</code>. * * @throws NullPointerException * if <code>parameters == null || result == null</code>. */ private final void performedCall(FunctionRequest functionRequest, String ip, long start, int callID, FunctionResult result) throws NullPointerException { // NOTE: Since XINS 1.0.0-beta11, callID is ignored. // Get the error code String code = result.getErrorCode(); // Update statistics and determine the duration of the call boolean isSuccess = code == null; long duration = _statistics.recordCall(start, isSuccess, code); // Fallback is a zero character if (code == null) { code = "0"; } // Serialize the date, input parameters and output parameters LogdocSerializable serStart = new FormattedDate(start); LogdocSerializable inParams = new FormattedParameters(functionRequest.getParameters()); LogdocSerializable outParams = new FormattedParameters(result.getParameters()); // Perform transaction logging, with and without parameters Log.log_3540(serStart, ip, _name, duration, code, inParams, outParams); Log.log_3541(serStart, ip, _name, duration, code); } }
true
true
FunctionResult handleCall(long start, FunctionRequest functionRequest, String ip) throws IllegalStateException { // Check state first assertUsable(); // Assign a call ID int callID = assignCallID(); // Check if this function is enabled if (! _enabled) { performedCall(functionRequest, ip, start, callID, DISABLED_FUNCTION_RESULT); return DISABLED_FUNCTION_RESULT; } // Construct a CallContext object CallContext context = new CallContext(functionRequest, start, this, callID, ip); FunctionResult result; try { // Handle the call result = handleCall(context); // Make sure the result is valid InvalidResponseResult invalidResponse = result.checkOutputParameters(); if (invalidResponse != null) { result = invalidResponse; Log.log_3501(functionRequest.getFunctionName(), callID); } } catch (Throwable exception) { result = _api.handleFunctionException(start, functionRequest, ip, callID, exception); } // Update function statistics // We assume that this method will never throw any exception performedCall(functionRequest, ip, start, callID, result); return result; }
FunctionResult handleCall(long start, FunctionRequest functionRequest, String ip) throws IllegalStateException { // Check state first assertUsable(); // Assign a call ID int callID = assignCallID(); // Check if this function is enabled if (! _enabled) { performedCall(functionRequest, ip, start, callID, DISABLED_FUNCTION_RESULT); return DISABLED_FUNCTION_RESULT; } // Construct a CallContext object CallContext context = new CallContext(functionRequest, start, this, callID, ip); FunctionResult result; try { // Handle the call result = handleCall(context); // Make sure the result is valid InvalidResponseResult invalidResponse = result.checkOutputParameters(); if (invalidResponse != null) { result = invalidResponse; Log.log_3501(functionRequest.getFunctionName(), callID); } } catch (Throwable exception) { result = _api.handleFunctionException(start, functionRequest, ip, callID, exception); } // Update function statistics // We assume that this method will never throw any exception performedCall(functionRequest, ip, start, callID, result); return result; }
diff --git a/tests/src/org/hornetq/tests/integration/cluster/bridge/BridgeWithPagingTest.java b/tests/src/org/hornetq/tests/integration/cluster/bridge/BridgeWithPagingTest.java index 4c129bb80..cfed013ad 100644 --- a/tests/src/org/hornetq/tests/integration/cluster/bridge/BridgeWithPagingTest.java +++ b/tests/src/org/hornetq/tests/integration/cluster/bridge/BridgeWithPagingTest.java @@ -1,243 +1,244 @@ /* * Copyright 2010 Red Hat, Inc. * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.hornetq.tests.integration.cluster.bridge; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.hornetq.api.core.HornetQException; import org.hornetq.api.core.Pair; import org.hornetq.api.core.SimpleString; import org.hornetq.api.core.TransportConfiguration; import org.hornetq.api.core.client.ClientConsumer; import org.hornetq.api.core.client.ClientMessage; import org.hornetq.api.core.client.ClientProducer; import org.hornetq.api.core.client.ClientSession; import org.hornetq.api.core.client.ClientSessionFactory; import org.hornetq.api.core.client.HornetQClient; import org.hornetq.core.config.BridgeConfiguration; import org.hornetq.core.config.CoreQueueConfiguration; import org.hornetq.core.config.impl.ConfigurationImpl; import org.hornetq.core.logging.Logger; import org.hornetq.core.remoting.impl.invm.InVMConnector; import org.hornetq.core.remoting.impl.invm.InVMConnectorFactory; import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory; import org.hornetq.core.server.HornetQServer; import org.hornetq.core.server.cluster.Bridge; import org.hornetq.core.server.cluster.impl.BridgeImpl; import org.hornetq.core.settings.impl.AddressFullMessagePolicy; import org.hornetq.core.settings.impl.AddressSettings; import org.hornetq.spi.core.protocol.RemotingConnection; /** * A BridgeWithPagingTest * * @author <a href="mailto:[email protected]">Jeff Mesnil</a> */ public class BridgeWithPagingTest extends BridgeTestBase { private static final Logger log = Logger.getLogger(BridgeWithPagingTest.class); protected boolean isNetty() { return false; } private String getConnector() { if (isNetty()) { return NettyConnectorFactory.class.getName(); } else { return InVMConnectorFactory.class.getName(); } } public void testFoo() throws Exception { } // https://jira.jboss.org/browse/HORNETQ-382 public void _testReconnectWithPaging() throws Exception { final byte[] content = new byte[2048]; for (int i=0; i < content.length; ++i) { content[i] = (byte) i; } Map<String, Object> server0Params = new HashMap<String, Object>(); HornetQServer server0 = createHornetQServer(0, isNetty(), server0Params); Map<String, Object> server1Params = new HashMap<String, Object>(); HornetQServer server1 = createHornetQServer(1, isNetty(), server1Params); TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params, "server0tc"); Map<String, TransportConfiguration> connectors = new HashMap<String, TransportConfiguration>(); TransportConfiguration server1tc = new TransportConfiguration(getConnector(), server1Params, "server1tc"); connectors.put(server1tc.getName(), server1tc); server0.getConfiguration().setConnectorConfigurations(connectors); server1.getConfiguration().setConnectorConfigurations(connectors); final String bridgeName = "bridge1"; final String testAddress = "testAddress"; final String queueName0 = "queue0"; final String forwardAddress = "forwardAddress"; final long retryInterval = 50; final double retryIntervalMultiplier = 1d; final int reconnectAttempts = -1; final int confirmationWindowSize = 1024; Pair<String, String> connectorPair = new Pair<String, String>(server1tc.getName(), null); BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(bridgeName, queueName0, forwardAddress, null, null, retryInterval, retryIntervalMultiplier, reconnectAttempts, true, false, confirmationWindowSize, HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, connectorPair, ConfigurationImpl.DEFAULT_CLUSTER_USER, ConfigurationImpl.DEFAULT_CLUSTER_PASSWORD); List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true); List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); AddressSettings addressSettings = new AddressSettings(); addressSettings.setRedeliveryDelay(0); - addressSettings.setMaxSizeBytes(10485760); - addressSettings.setPageSizeBytes(1048576); + addressSettings.setMaxSizeBytes(1048576); + addressSettings.setPageSizeBytes(104857); addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); server0.getConfiguration().getAddressesSettings().put("#", addressSettings); CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName0, null, true); List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); server1.getConfiguration().getAddressesSettings().put("#", addressSettings); server1.start(); server0.start(); ClientSessionFactory csf0 = HornetQClient.createClientSessionFactory(server0tc); ClientSession session0 = csf0.createSession(false, true, true); ClientSessionFactory csf1 = HornetQClient.createClientSessionFactory(server1tc); ClientSession session1 = csf1.createSession(false, true, true); ClientProducer prod0 = session0.createProducer(testAddress); ClientConsumer cons1 = session1.createConsumer(queueName0); session1.start(); // Now we will simulate a failure of the bridge connection between server0 and server1 Bridge bridge = server0.getClusterManager().getBridges().get(bridgeName); final RemotingConnection forwardingConnection = getForwardingConnection(bridge); InVMConnector.failOnCreateConnection = true; InVMConnector.numberOfFailures = Integer.MAX_VALUE; Thread t = new Thread() { @Override public void run() { System.out.println("failing..."); forwardingConnection.fail(new HornetQException(HornetQException.NOT_CONNECTED)); System.out.println("reconnected!!!"); } }; t.start(); - final int numMessages = 5000; + final int numMessages = 500; SimpleString propKey = new SimpleString("propkey"); for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); message.getBodyBuffer().writeBytes(content); prod0.send(message); System.out.println(">>>> " + i); } InVMConnector.failOnCreateConnection = false; Thread.sleep(200); for (int i = 0; i < numMessages; i++) { System.out.println("<<< " + i); ClientMessage r1 = cons1.receive(1500); - Assert.assertNotNull(r1); + Assert.assertNotNull("did not receive message n�" + i, r1); Assert.assertEquals(i, r1.getObjectProperty(propKey)); + r1.acknowledge(); } session0.close(); session1.close(); server0.stop(); server1.stop(); Assert.assertEquals(0, server0.getRemotingService().getConnections().size()); Assert.assertEquals(0, server1.getRemotingService().getConnections().size()); } private RemotingConnection getForwardingConnection(final Bridge bridge) throws Exception { long start = System.currentTimeMillis(); do { RemotingConnection forwardingConnection = ((BridgeImpl)bridge).getForwardingConnection(); if (forwardingConnection != null) { return forwardingConnection; } Thread.sleep(10); } while (System.currentTimeMillis() - start < 50000); throw new IllegalStateException("Failed to get forwarding connection"); } }
false
true
public void _testReconnectWithPaging() throws Exception { final byte[] content = new byte[2048]; for (int i=0; i < content.length; ++i) { content[i] = (byte) i; } Map<String, Object> server0Params = new HashMap<String, Object>(); HornetQServer server0 = createHornetQServer(0, isNetty(), server0Params); Map<String, Object> server1Params = new HashMap<String, Object>(); HornetQServer server1 = createHornetQServer(1, isNetty(), server1Params); TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params, "server0tc"); Map<String, TransportConfiguration> connectors = new HashMap<String, TransportConfiguration>(); TransportConfiguration server1tc = new TransportConfiguration(getConnector(), server1Params, "server1tc"); connectors.put(server1tc.getName(), server1tc); server0.getConfiguration().setConnectorConfigurations(connectors); server1.getConfiguration().setConnectorConfigurations(connectors); final String bridgeName = "bridge1"; final String testAddress = "testAddress"; final String queueName0 = "queue0"; final String forwardAddress = "forwardAddress"; final long retryInterval = 50; final double retryIntervalMultiplier = 1d; final int reconnectAttempts = -1; final int confirmationWindowSize = 1024; Pair<String, String> connectorPair = new Pair<String, String>(server1tc.getName(), null); BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(bridgeName, queueName0, forwardAddress, null, null, retryInterval, retryIntervalMultiplier, reconnectAttempts, true, false, confirmationWindowSize, HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, connectorPair, ConfigurationImpl.DEFAULT_CLUSTER_USER, ConfigurationImpl.DEFAULT_CLUSTER_PASSWORD); List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true); List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); AddressSettings addressSettings = new AddressSettings(); addressSettings.setRedeliveryDelay(0); addressSettings.setMaxSizeBytes(10485760); addressSettings.setPageSizeBytes(1048576); addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); server0.getConfiguration().getAddressesSettings().put("#", addressSettings); CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName0, null, true); List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); server1.getConfiguration().getAddressesSettings().put("#", addressSettings); server1.start(); server0.start(); ClientSessionFactory csf0 = HornetQClient.createClientSessionFactory(server0tc); ClientSession session0 = csf0.createSession(false, true, true); ClientSessionFactory csf1 = HornetQClient.createClientSessionFactory(server1tc); ClientSession session1 = csf1.createSession(false, true, true); ClientProducer prod0 = session0.createProducer(testAddress); ClientConsumer cons1 = session1.createConsumer(queueName0); session1.start(); // Now we will simulate a failure of the bridge connection between server0 and server1 Bridge bridge = server0.getClusterManager().getBridges().get(bridgeName); final RemotingConnection forwardingConnection = getForwardingConnection(bridge); InVMConnector.failOnCreateConnection = true; InVMConnector.numberOfFailures = Integer.MAX_VALUE; Thread t = new Thread() { @Override public void run() { System.out.println("failing..."); forwardingConnection.fail(new HornetQException(HornetQException.NOT_CONNECTED)); System.out.println("reconnected!!!"); } }; t.start(); final int numMessages = 5000; SimpleString propKey = new SimpleString("propkey"); for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); message.getBodyBuffer().writeBytes(content); prod0.send(message); System.out.println(">>>> " + i); } InVMConnector.failOnCreateConnection = false; Thread.sleep(200); for (int i = 0; i < numMessages; i++) { System.out.println("<<< " + i); ClientMessage r1 = cons1.receive(1500); Assert.assertNotNull(r1); Assert.assertEquals(i, r1.getObjectProperty(propKey)); } session0.close(); session1.close(); server0.stop(); server1.stop(); Assert.assertEquals(0, server0.getRemotingService().getConnections().size()); Assert.assertEquals(0, server1.getRemotingService().getConnections().size()); }
public void _testReconnectWithPaging() throws Exception { final byte[] content = new byte[2048]; for (int i=0; i < content.length; ++i) { content[i] = (byte) i; } Map<String, Object> server0Params = new HashMap<String, Object>(); HornetQServer server0 = createHornetQServer(0, isNetty(), server0Params); Map<String, Object> server1Params = new HashMap<String, Object>(); HornetQServer server1 = createHornetQServer(1, isNetty(), server1Params); TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params, "server0tc"); Map<String, TransportConfiguration> connectors = new HashMap<String, TransportConfiguration>(); TransportConfiguration server1tc = new TransportConfiguration(getConnector(), server1Params, "server1tc"); connectors.put(server1tc.getName(), server1tc); server0.getConfiguration().setConnectorConfigurations(connectors); server1.getConfiguration().setConnectorConfigurations(connectors); final String bridgeName = "bridge1"; final String testAddress = "testAddress"; final String queueName0 = "queue0"; final String forwardAddress = "forwardAddress"; final long retryInterval = 50; final double retryIntervalMultiplier = 1d; final int reconnectAttempts = -1; final int confirmationWindowSize = 1024; Pair<String, String> connectorPair = new Pair<String, String>(server1tc.getName(), null); BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(bridgeName, queueName0, forwardAddress, null, null, retryInterval, retryIntervalMultiplier, reconnectAttempts, true, false, confirmationWindowSize, HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, connectorPair, ConfigurationImpl.DEFAULT_CLUSTER_USER, ConfigurationImpl.DEFAULT_CLUSTER_PASSWORD); List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>(); bridgeConfigs.add(bridgeConfiguration); server0.getConfiguration().setBridgeConfigurations(bridgeConfigs); CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true); List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>(); queueConfigs0.add(queueConfig0); server0.getConfiguration().setQueueConfigurations(queueConfigs0); AddressSettings addressSettings = new AddressSettings(); addressSettings.setRedeliveryDelay(0); addressSettings.setMaxSizeBytes(1048576); addressSettings.setPageSizeBytes(104857); addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); server0.getConfiguration().getAddressesSettings().put("#", addressSettings); CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName0, null, true); List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>(); queueConfigs1.add(queueConfig1); server1.getConfiguration().setQueueConfigurations(queueConfigs1); server1.getConfiguration().getAddressesSettings().put("#", addressSettings); server1.start(); server0.start(); ClientSessionFactory csf0 = HornetQClient.createClientSessionFactory(server0tc); ClientSession session0 = csf0.createSession(false, true, true); ClientSessionFactory csf1 = HornetQClient.createClientSessionFactory(server1tc); ClientSession session1 = csf1.createSession(false, true, true); ClientProducer prod0 = session0.createProducer(testAddress); ClientConsumer cons1 = session1.createConsumer(queueName0); session1.start(); // Now we will simulate a failure of the bridge connection between server0 and server1 Bridge bridge = server0.getClusterManager().getBridges().get(bridgeName); final RemotingConnection forwardingConnection = getForwardingConnection(bridge); InVMConnector.failOnCreateConnection = true; InVMConnector.numberOfFailures = Integer.MAX_VALUE; Thread t = new Thread() { @Override public void run() { System.out.println("failing..."); forwardingConnection.fail(new HornetQException(HornetQException.NOT_CONNECTED)); System.out.println("reconnected!!!"); } }; t.start(); final int numMessages = 500; SimpleString propKey = new SimpleString("propkey"); for (int i = 0; i < numMessages; i++) { ClientMessage message = session0.createMessage(false); message.putIntProperty(propKey, i); message.getBodyBuffer().writeBytes(content); prod0.send(message); System.out.println(">>>> " + i); } InVMConnector.failOnCreateConnection = false; Thread.sleep(200); for (int i = 0; i < numMessages; i++) { System.out.println("<<< " + i); ClientMessage r1 = cons1.receive(1500); Assert.assertNotNull("did not receive message n�" + i, r1); Assert.assertEquals(i, r1.getObjectProperty(propKey)); r1.acknowledge(); } session0.close(); session1.close(); server0.stop(); server1.stop(); Assert.assertEquals(0, server0.getRemotingService().getConnections().size()); Assert.assertEquals(0, server1.getRemotingService().getConnections().size()); }
diff --git a/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSonicListener.java b/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSonicListener.java index 062dcbe80..17b3c79c7 100644 --- a/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSonicListener.java +++ b/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSonicListener.java @@ -1,577 +1,578 @@ /* * Copyright (C) 2013 eccentric_nz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.eccentric_nz.TARDIS.listeners; import com.griefcraft.lwc.LWC; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.TARDIS.TARDISConstants; import me.eccentric_nz.TARDIS.commands.admin.TARDISAdminMenuInventory; import me.eccentric_nz.TARDIS.database.ResultSetBackLocation; import me.eccentric_nz.TARDIS.database.ResultSetDoors; import me.eccentric_nz.TARDIS.database.ResultSetTardis; import me.eccentric_nz.TARDIS.database.ResultSetTravellers; import static me.eccentric_nz.TARDIS.listeners.TARDISScannerListener.getNearbyEntities; import me.eccentric_nz.TARDIS.utility.TARDISVector3D; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.Button; import org.bukkit.material.DetectorRail; import org.bukkit.material.Door; import org.bukkit.material.Lever; import org.bukkit.material.PistonBaseMaterial; import org.bukkit.material.PoweredRail; import org.bukkit.scheduler.BukkitScheduler; import org.yi.acru.bukkit.Lockette.Lockette; /** * * @author eccentric_nz */ public class TARDISSonicListener implements Listener { private final TARDIS plugin; private final Material sonic; private final HashMap<String, Long> timeout = new HashMap<String, Long>(); private final HashMap<String, Long> cooldown = new HashMap<String, Long>(); private final List<Material> diamond = new ArrayList<Material>(); private final List<Material> distance = new ArrayList<Material>(); private final List<Material> doors = new ArrayList<Material>(); private final List<Material> redstone = new ArrayList<Material>(); private final List<String> frozenPlayers = new ArrayList<String>(); private final List<BlockFace> faces = new ArrayList<BlockFace>(); public TARDISSonicListener(TARDIS plugin) { this.plugin = plugin; String[] split = plugin.getRecipesConfig().getString("shaped.Sonic Screwdriver.result").split(":"); this.sonic = Material.valueOf(split[0]); diamond.add(Material.GLASS); diamond.add(Material.IRON_FENCE); diamond.add(Material.STAINED_GLASS); diamond.add(Material.STAINED_GLASS_PANE); diamond.add(Material.THIN_GLASS); diamond.add(Material.WEB); distance.add(Material.IRON_DOOR_BLOCK); distance.add(Material.LEVER); distance.add(Material.STONE_BUTTON); distance.add(Material.WOODEN_DOOR); distance.add(Material.WOOD_BUTTON); doors.add(Material.IRON_DOOR_BLOCK); doors.add(Material.TRAP_DOOR); doors.add(Material.WOODEN_DOOR); redstone.add(Material.DETECTOR_RAIL); redstone.add(Material.PISTON_BASE); redstone.add(Material.PISTON_STICKY_BASE); redstone.add(Material.POWERED_RAIL); redstone.add(Material.REDSTONE_LAMP_OFF); redstone.add(Material.REDSTONE_LAMP_ON); redstone.add(Material.REDSTONE_WIRE); faces.add(BlockFace.NORTH); faces.add(BlockFace.SOUTH); faces.add(BlockFace.EAST); faces.add(BlockFace.WEST); } @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.MONITOR) public void onInteract(PlayerInteractEvent event) { final Player player = event.getPlayer(); long now = System.currentTimeMillis(); final ItemStack is = player.getItemInHand(); if (is.getType().equals(sonic) && is.hasItemMeta()) { ItemMeta im = player.getItemInHand().getItemMeta(); if (im.getDisplayName().equals("Sonic Screwdriver")) { List<String> lore = im.getLore(); Action action = event.getAction(); if (action.equals(Action.RIGHT_CLICK_AIR)) { playSonicSound(player, now, 3050L, "sonic_screwdriver"); if (player.hasPermission("tardis.admin") && lore != null && lore.contains("Admin Upgrade")) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { ItemStack[] items = new TARDISAdminMenuInventory(plugin).getMenu(); Inventory menu = plugin.getServer().createInventory(player, 54, "§4Admin Menu"); menu.setContents(items); player.openInventory(menu); } }, 40L); return; } if (player.hasPermission("tardis.sonic.freeze") && lore != null && lore.contains("Bio-scanner Upgrade")) { long cool = System.currentTimeMillis(); if ((!cooldown.containsKey(player.getName()) || cooldown.get(player.getName()) < cool)) { cooldown.put(player.getName(), cool + (plugin.getConfig().getInt("preferences.freeze_cooldown") * 1000L)); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { Location observerPos = player.getEyeLocation(); TARDISVector3D observerDir = new TARDISVector3D(observerPos.getDirection()); TARDISVector3D observerStart = new TARDISVector3D(observerPos); TARDISVector3D observerEnd = observerStart.add(observerDir.multiply(16)); Player hit = null; // Get nearby entities for (Player target : player.getWorld().getPlayers()) { // Bounding box of the given player TARDISVector3D targetPos = new TARDISVector3D(target.getLocation()); TARDISVector3D minimum = targetPos.add(-0.5, 0, -0.5); TARDISVector3D maximum = targetPos.add(0.5, 1.67, 0.5); if (target != player && hasIntersection(observerStart, observerEnd, minimum, maximum)) { if (hit == null || hit.getLocation().distanceSquared(observerPos) > target.getLocation().distanceSquared(observerPos)) { hit = target; } } } // freeze the closest player if (hit != null) { hit.sendMessage(plugin.pluginName + player.getName() + " froze you with their Sonic Screwdriver!"); final String hitNme = hit.getName(); frozenPlayers.add(hitNme); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { frozenPlayers.remove(hitNme); } }, 100L); } } }, 20L); } else { player.sendMessage(plugin.pluginName + player.getName() + " You cannot freeze another player yet!"); } return; } if (player.hasPermission("tardis.sonic.standard")) { Block targetBlock = player.getTargetBlock(plugin.tardisCommand.transparent, 50).getLocation().getBlock(); Material blockType = targetBlock.getType(); if (distance.contains(blockType)) { final BlockState bs = targetBlock.getState(); switch (blockType) { case IRON_DOOR_BLOCK: case WOODEN_DOOR: Block lowerdoor; if (targetBlock.getData() >= 8) { lowerdoor = targetBlock.getRelative(BlockFace.DOWN); } else { lowerdoor = targetBlock; } boolean allow = true; // is Lockette or LWC on the server? if (plugin.pm.isPluginEnabled("Lockette")) { Lockette Lockette = (Lockette) plugin.pm.getPlugin("Lockette"); if (Lockette.isProtected(lowerdoor)) { allow = false; } } if (plugin.pm.isPluginEnabled("LWC")) { LWC lwc = (LWC) plugin.pm.getPlugin("LWC"); if (!lwc.canAccessProtection(player, lowerdoor)) { allow = false; } } if (allow) { BlockState bsl = lowerdoor.getState(); Door door = (Door) bsl.getData(); door.setOpen(!door.isOpen()); bsl.setData(door); bsl.update(true); } break; case LEVER: Lever lever = (Lever) bs.getData(); lever.setPowered(!lever.isPowered()); bs.setData(lever); bs.update(true); break; case STONE_BUTTON: case WOOD_BUTTON: final Button button = (Button) bs.getData(); button.setPowered(true); bs.setData(button); bs.update(true); long delay = (blockType.equals(Material.STONE_BUTTON)) ? 20L : 30L; plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { button.setPowered(false); bs.setData(button); bs.update(true); } }, delay); break; default: break; } } return; } } if (action.equals(Action.RIGHT_CLICK_BLOCK)) { final Block b = event.getClickedBlock(); if (doors.contains(b.getType()) && player.hasPermission("tardis.admin") && lore != null && lore.contains("Admin Upgrade")) { playSonicSound(player, now, 3050L, "sonic_screwdriver"); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { HashMap<String, Object> wheredoor = new HashMap<String, Object>(); Location loc = b.getLocation(); String bw = loc.getWorld().getName(); int bx = loc.getBlockX(); int by = loc.getBlockY(); int bz = loc.getBlockZ(); if (b.getData() >= 8 && !b.getType().equals(Material.TRAP_DOOR)) { by = (by - 1); } String doorloc = bw + ":" + bx + ":" + by + ":" + bz; wheredoor.put("door_location", doorloc); wheredoor.put("door_type", 0); ResultSetDoors rsd = new ResultSetDoors(plugin, wheredoor, false); if (rsd.resultSet()) { int id = rsd.getTardis_id(); // get the TARDIS owner's name HashMap<String, Object> wheren = new HashMap<String, Object>(); wheren.put("tardis_id", id); ResultSetTardis rsn = new ResultSetTardis(plugin, wheren, "", false); if (rsn.resultSet()) { player.sendMessage(plugin.pluginName + "This is " + rsn.getOwner() + "'s TARDIS"); int percent = Math.round((rsn.getArtron_level() * 100F) / plugin.getArtronConfig().getInt("full_charge")); player.sendMessage(plugin.pluginName + "The Artron Energy Capacitor is at " + percent + "%"); HashMap<String, Object> whereb = new HashMap<String, Object>(); whereb.put("tardis_id", id); ResultSetBackLocation rsb = new ResultSetBackLocation(plugin, whereb); if (rsb.resultSet()) { player.sendMessage(plugin.pluginName + "Its last location was: " + rsb.getWorld().getName() + " " + rsb.getX() + ":" + rsb.getY() + ":" + rsb.getZ()); } } HashMap<String, Object> whereid = new HashMap<String, Object>(); whereid.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, whereid, true); if (rst.resultSet()) { List<String> data = rst.getData(); player.sendMessage(plugin.pluginName + "The players inside this TARDIS are:"); for (String s : data) { player.sendMessage(s); } } else { player.sendMessage(plugin.pluginName + "The TARDIS is unoccupied."); } } } }, 60L); } if (!redstone.contains(b.getType()) && player.hasPermission("tardis.sonic.emerald") && lore != null && lore.contains("Emerald Upgrade")) { playSonicSound(player, now, 3050L, "sonic_screwdriver"); // scan environment this.scan(b.getLocation(), player); } if (redstone.contains(b.getType()) && player.hasPermission("tardis.sonic.redstone") && lore != null && lore.contains("Redstone Upgrade")) { playSonicSound(player, now, 600L, "sonic_short"); Material blockType = b.getType(); BlockState bs = b.getState(); // do redstone activation switch (blockType) { case DETECTOR_RAIL: DetectorRail drail = (DetectorRail) bs.getData(); if (plugin.redstoneListener.getRails().contains(b.getLocation().toString())) { plugin.redstoneListener.getRails().remove(b.getLocation().toString()); drail.setPressed(false); b.setData((byte) (drail.getData() - 8)); } else { plugin.redstoneListener.getRails().add(b.getLocation().toString()); drail.setPressed(true); b.setData((byte) (drail.getData() + 8)); } break; case POWERED_RAIL: PoweredRail rail = (PoweredRail) bs.getData(); if (plugin.redstoneListener.getRails().contains(b.getLocation().toString())) { plugin.redstoneListener.getRails().remove(b.getLocation().toString()); rail.setPowered(false); b.setData((byte) (rail.getData() - 8)); } else { plugin.redstoneListener.getRails().add(b.getLocation().toString()); rail.setPowered(true); b.setData((byte) (rail.getData() + 8)); } break; case PISTON_BASE: case PISTON_STICKY_BASE: PistonBaseMaterial piston = (PistonBaseMaterial) bs.getData(); // find the direction the piston is facing if (plugin.redstoneListener.getPistons().contains(b.getLocation().toString())) { plugin.redstoneListener.getPistons().remove(b.getLocation().toString()); for (BlockFace f : faces) { if (b.getRelative(f).getType().equals(Material.AIR)) { b.getRelative(f).setTypeIdAndData(20, (byte) 0, true); b.getRelative(f).setTypeIdAndData(0, (byte) 0, true); break; } } } else { plugin.redstoneListener.getPistons().add(b.getLocation().toString()); piston.setPowered(true); plugin.redstoneListener.setExtension(b); player.playSound(b.getLocation(), Sound.PISTON_EXTEND, 1.0f, 1.0f); } b.setData(piston.getData()); bs.update(true); break; case REDSTONE_LAMP_OFF: case REDSTONE_LAMP_ON: if (blockType.equals(Material.REDSTONE_LAMP_OFF)) { plugin.redstoneListener.getLamps().add(b.getLocation().toString()); b.setType(Material.REDSTONE_LAMP_ON); } else if (plugin.redstoneListener.getLamps().contains(b.getLocation().toString())) { plugin.redstoneListener.getLamps().remove(b.getLocation().toString()); b.setType(Material.REDSTONE_LAMP_OFF); } break; case REDSTONE_WIRE: if (plugin.redstoneListener.getWires().contains(b.getLocation().toString())) { plugin.redstoneListener.getWires().remove(b.getLocation().toString()); + b.setData((byte) 0); for (BlockFace f : faces) { if (b.getRelative(f).getType().equals(Material.REDSTONE_WIRE)) { b.setData((byte) 0); } } } else { plugin.redstoneListener.getWires().add(b.getLocation().toString()); b.setData((byte) 15); for (BlockFace f : faces) { if (b.getRelative(f).getType().equals(Material.REDSTONE_WIRE)) { b.setData((byte) 13); } } } break; default: break; } } } if (action.equals(Action.LEFT_CLICK_BLOCK)) { Block b = event.getClickedBlock(); if (diamond.contains(b.getType()) && player.hasPermission("tardis.sonic.diamond") && lore != null && lore.contains("Diamond Upgrade")) { playSonicSound(player, now, 600L, "sonic_short"); // drop appropriate material if (player.hasPermission("tardis.sonic.silktouch")) { Location l = b.getLocation(); switch (b.getType()) { case GLASS: l.getWorld().dropItemNaturally(l, new ItemStack(Material.GLASS, 1)); break; case IRON_FENCE: l.getWorld().dropItemNaturally(l, new ItemStack(Material.IRON_FENCE, 1)); break; case STAINED_GLASS: l.getWorld().dropItemNaturally(l, new ItemStack(Material.STAINED_GLASS, 1, b.getData())); break; case STAINED_GLASS_PANE: l.getWorld().dropItemNaturally(l, new ItemStack(Material.STAINED_GLASS_PANE, 1, b.getData())); break; case THIN_GLASS: l.getWorld().dropItemNaturally(l, new ItemStack(Material.THIN_GLASS, 1)); break; case WEB: l.getWorld().dropItemNaturally(l, new ItemStack(Material.WEB, 1)); break; default: break; } l.getWorld().playSound(l, Sound.SHEEP_SHEAR, 1.0F, 1.5F); // set the block to AIR b.setType(Material.AIR); } else { b.breakNaturally(); b.getLocation().getWorld().playSound(b.getLocation(), Sound.SHEEP_SHEAR, 1.0F, 1.5F); } } } } } } private void playSonicSound(final Player player, long now, long cooldown, String sound) { if ((!timeout.containsKey(player.getName()) || timeout.get(player.getName()) < now)) { ItemMeta im = player.getItemInHand().getItemMeta(); im.addEnchant(Enchantment.DURABILITY, 1, true); player.getItemInHand().setItemMeta(im); timeout.put(player.getName(), now + cooldown); plugin.utils.playTARDISSound(player.getLocation(), player, sound); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { for (Enchantment e : player.getItemInHand().getEnchantments().keySet()) { player.getItemInHand().removeEnchantment(e); } } }, (cooldown / 50L)); } } private boolean hasIntersection(TARDISVector3D p1, TARDISVector3D p2, TARDISVector3D min, TARDISVector3D max) { final double epsilon = 0.0001f; TARDISVector3D d = p2.subtract(p1).multiply(0.5); TARDISVector3D e = max.subtract(min).multiply(0.5); TARDISVector3D c = p1.add(d).subtract(min.add(max).multiply(0.5)); TARDISVector3D ad = d.abs(); if (Math.abs(c.x) > e.x + ad.x) { return false; } if (Math.abs(c.y) > e.y + ad.y) { return false; } if (Math.abs(c.z) > e.z + ad.z) { return false; } if (Math.abs(d.y * c.z - d.z * c.y) > e.y * ad.z + e.z * ad.y + epsilon) { return false; } if (Math.abs(d.z * c.x - d.x * c.z) > e.z * ad.x + e.x * ad.z + epsilon) { return false; } return Math.abs(d.x * c.y - d.y * c.x) <= e.x * ad.y + e.y * ad.x + epsilon; } @EventHandler public void onPlayerFrozenMove(PlayerMoveEvent event) { if (frozenPlayers.contains(event.getPlayer().getName())) { event.setCancelled(true); } } public void scan(final Location scan_loc, final Player player) { // record nearby entities final HashMap<EntityType, Integer> scannedentities = new HashMap<EntityType, Integer>(); final List<String> playernames = new ArrayList<String>(); for (Entity k : getNearbyEntities(scan_loc, 16)) { EntityType et = k.getType(); if (TARDISConstants.ENTITY_TYPES.contains(et)) { Integer entity_count = (scannedentities.containsKey(et)) ? scannedentities.get(et) : 0; boolean visible = true; if (et.equals(EntityType.PLAYER)) { Player entPlayer = (Player) k; if (player.canSee(entPlayer)) { playernames.add(entPlayer.getName()); } else { visible = false; } } if (visible) { scannedentities.put(et, entity_count + 1); } } } final long time = scan_loc.getWorld().getTime(); final String daynight = plugin.utils.getTime(time); // message the player player.sendMessage(plugin.pluginName + "Sonic Screwdriver environmental scan started..."); BukkitScheduler bsched = plugin.getServer().getScheduler(); bsched.scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.sendMessage("World: " + scan_loc.getWorld().getName()); player.sendMessage("Co-ordinates: " + scan_loc.getBlockX() + ":" + scan_loc.getBlockY() + ":" + scan_loc.getBlockZ()); } }, 20L); // get biome final Biome biome = scan_loc.getBlock().getBiome(); bsched.scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.sendMessage("Biome type: " + biome); } }, 40L); bsched.scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.sendMessage("Time of day: " + daynight + " / " + time + " ticks"); } }, 60L); // get weather final String weather; if (biome.equals(Biome.DESERT) || biome.equals(Biome.DESERT_HILLS) || biome.equals(Biome.SAVANNA) || biome.equals(Biome.SAVANNA_MOUNTAINS) || biome.equals(Biome.SAVANNA_PLATEAU) || biome.equals(Biome.SAVANNA_PLATEAU_MOUNTAINS) || biome.equals(Biome.MESA) || biome.equals(Biome.MESA_BRYCE) || biome.equals(Biome.MESA_PLATEAU) || biome.equals(Biome.MESA_PLATEAU_MOUNTAINS)) { weather = "dry as a bone"; } else if (biome.equals(Biome.ICE_PLAINS) || biome.equals(Biome.ICE_PLAINS_SPIKES) || biome.equals(Biome.FROZEN_OCEAN) || biome.equals(Biome.FROZEN_RIVER) || biome.equals(Biome.COLD_BEACH) || biome.equals(Biome.COLD_TAIGA) || biome.equals(Biome.COLD_TAIGA_HILLS) || biome.equals(Biome.COLD_TAIGA_MOUNTAINS)) { weather = (scan_loc.getWorld().hasStorm()) ? "snowing" : "clear, but cold"; } else { weather = (scan_loc.getWorld().hasStorm()) ? "raining" : "clear"; } bsched.scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.sendMessage("Weather: " + weather); } }, 80L); bsched.scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.sendMessage("Humidity: " + String.format("%.2f", scan_loc.getBlock().getHumidity())); } }, 100L); bsched.scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.sendMessage("Temperature: " + String.format("%.2f", scan_loc.getBlock().getTemperature())); } }, 120L); bsched.scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { if (scannedentities.size() > 0) { player.sendMessage("Nearby entities:"); for (Map.Entry<EntityType, Integer> entry : scannedentities.entrySet()) { String message = ""; StringBuilder buf = new StringBuilder(); if (entry.getKey().equals(EntityType.PLAYER) && playernames.size() > 0) { for (String p : playernames) { buf.append(", ").append(p); } message = " (" + buf.toString().substring(2) + ")"; } player.sendMessage(" " + entry.getKey() + ": " + entry.getValue() + message); } scannedentities.clear(); } else { player.sendMessage("Nearby entities: none"); } } }, 140L); } }
true
true
public void onInteract(PlayerInteractEvent event) { final Player player = event.getPlayer(); long now = System.currentTimeMillis(); final ItemStack is = player.getItemInHand(); if (is.getType().equals(sonic) && is.hasItemMeta()) { ItemMeta im = player.getItemInHand().getItemMeta(); if (im.getDisplayName().equals("Sonic Screwdriver")) { List<String> lore = im.getLore(); Action action = event.getAction(); if (action.equals(Action.RIGHT_CLICK_AIR)) { playSonicSound(player, now, 3050L, "sonic_screwdriver"); if (player.hasPermission("tardis.admin") && lore != null && lore.contains("Admin Upgrade")) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { ItemStack[] items = new TARDISAdminMenuInventory(plugin).getMenu(); Inventory menu = plugin.getServer().createInventory(player, 54, "§4Admin Menu"); menu.setContents(items); player.openInventory(menu); } }, 40L); return; } if (player.hasPermission("tardis.sonic.freeze") && lore != null && lore.contains("Bio-scanner Upgrade")) { long cool = System.currentTimeMillis(); if ((!cooldown.containsKey(player.getName()) || cooldown.get(player.getName()) < cool)) { cooldown.put(player.getName(), cool + (plugin.getConfig().getInt("preferences.freeze_cooldown") * 1000L)); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { Location observerPos = player.getEyeLocation(); TARDISVector3D observerDir = new TARDISVector3D(observerPos.getDirection()); TARDISVector3D observerStart = new TARDISVector3D(observerPos); TARDISVector3D observerEnd = observerStart.add(observerDir.multiply(16)); Player hit = null; // Get nearby entities for (Player target : player.getWorld().getPlayers()) { // Bounding box of the given player TARDISVector3D targetPos = new TARDISVector3D(target.getLocation()); TARDISVector3D minimum = targetPos.add(-0.5, 0, -0.5); TARDISVector3D maximum = targetPos.add(0.5, 1.67, 0.5); if (target != player && hasIntersection(observerStart, observerEnd, minimum, maximum)) { if (hit == null || hit.getLocation().distanceSquared(observerPos) > target.getLocation().distanceSquared(observerPos)) { hit = target; } } } // freeze the closest player if (hit != null) { hit.sendMessage(plugin.pluginName + player.getName() + " froze you with their Sonic Screwdriver!"); final String hitNme = hit.getName(); frozenPlayers.add(hitNme); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { frozenPlayers.remove(hitNme); } }, 100L); } } }, 20L); } else { player.sendMessage(plugin.pluginName + player.getName() + " You cannot freeze another player yet!"); } return; } if (player.hasPermission("tardis.sonic.standard")) { Block targetBlock = player.getTargetBlock(plugin.tardisCommand.transparent, 50).getLocation().getBlock(); Material blockType = targetBlock.getType(); if (distance.contains(blockType)) { final BlockState bs = targetBlock.getState(); switch (blockType) { case IRON_DOOR_BLOCK: case WOODEN_DOOR: Block lowerdoor; if (targetBlock.getData() >= 8) { lowerdoor = targetBlock.getRelative(BlockFace.DOWN); } else { lowerdoor = targetBlock; } boolean allow = true; // is Lockette or LWC on the server? if (plugin.pm.isPluginEnabled("Lockette")) { Lockette Lockette = (Lockette) plugin.pm.getPlugin("Lockette"); if (Lockette.isProtected(lowerdoor)) { allow = false; } } if (plugin.pm.isPluginEnabled("LWC")) { LWC lwc = (LWC) plugin.pm.getPlugin("LWC"); if (!lwc.canAccessProtection(player, lowerdoor)) { allow = false; } } if (allow) { BlockState bsl = lowerdoor.getState(); Door door = (Door) bsl.getData(); door.setOpen(!door.isOpen()); bsl.setData(door); bsl.update(true); } break; case LEVER: Lever lever = (Lever) bs.getData(); lever.setPowered(!lever.isPowered()); bs.setData(lever); bs.update(true); break; case STONE_BUTTON: case WOOD_BUTTON: final Button button = (Button) bs.getData(); button.setPowered(true); bs.setData(button); bs.update(true); long delay = (blockType.equals(Material.STONE_BUTTON)) ? 20L : 30L; plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { button.setPowered(false); bs.setData(button); bs.update(true); } }, delay); break; default: break; } } return; } } if (action.equals(Action.RIGHT_CLICK_BLOCK)) { final Block b = event.getClickedBlock(); if (doors.contains(b.getType()) && player.hasPermission("tardis.admin") && lore != null && lore.contains("Admin Upgrade")) { playSonicSound(player, now, 3050L, "sonic_screwdriver"); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { HashMap<String, Object> wheredoor = new HashMap<String, Object>(); Location loc = b.getLocation(); String bw = loc.getWorld().getName(); int bx = loc.getBlockX(); int by = loc.getBlockY(); int bz = loc.getBlockZ(); if (b.getData() >= 8 && !b.getType().equals(Material.TRAP_DOOR)) { by = (by - 1); } String doorloc = bw + ":" + bx + ":" + by + ":" + bz; wheredoor.put("door_location", doorloc); wheredoor.put("door_type", 0); ResultSetDoors rsd = new ResultSetDoors(plugin, wheredoor, false); if (rsd.resultSet()) { int id = rsd.getTardis_id(); // get the TARDIS owner's name HashMap<String, Object> wheren = new HashMap<String, Object>(); wheren.put("tardis_id", id); ResultSetTardis rsn = new ResultSetTardis(plugin, wheren, "", false); if (rsn.resultSet()) { player.sendMessage(plugin.pluginName + "This is " + rsn.getOwner() + "'s TARDIS"); int percent = Math.round((rsn.getArtron_level() * 100F) / plugin.getArtronConfig().getInt("full_charge")); player.sendMessage(plugin.pluginName + "The Artron Energy Capacitor is at " + percent + "%"); HashMap<String, Object> whereb = new HashMap<String, Object>(); whereb.put("tardis_id", id); ResultSetBackLocation rsb = new ResultSetBackLocation(plugin, whereb); if (rsb.resultSet()) { player.sendMessage(plugin.pluginName + "Its last location was: " + rsb.getWorld().getName() + " " + rsb.getX() + ":" + rsb.getY() + ":" + rsb.getZ()); } } HashMap<String, Object> whereid = new HashMap<String, Object>(); whereid.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, whereid, true); if (rst.resultSet()) { List<String> data = rst.getData(); player.sendMessage(plugin.pluginName + "The players inside this TARDIS are:"); for (String s : data) { player.sendMessage(s); } } else { player.sendMessage(plugin.pluginName + "The TARDIS is unoccupied."); } } } }, 60L); } if (!redstone.contains(b.getType()) && player.hasPermission("tardis.sonic.emerald") && lore != null && lore.contains("Emerald Upgrade")) { playSonicSound(player, now, 3050L, "sonic_screwdriver"); // scan environment this.scan(b.getLocation(), player); } if (redstone.contains(b.getType()) && player.hasPermission("tardis.sonic.redstone") && lore != null && lore.contains("Redstone Upgrade")) { playSonicSound(player, now, 600L, "sonic_short"); Material blockType = b.getType(); BlockState bs = b.getState(); // do redstone activation switch (blockType) { case DETECTOR_RAIL: DetectorRail drail = (DetectorRail) bs.getData(); if (plugin.redstoneListener.getRails().contains(b.getLocation().toString())) { plugin.redstoneListener.getRails().remove(b.getLocation().toString()); drail.setPressed(false); b.setData((byte) (drail.getData() - 8)); } else { plugin.redstoneListener.getRails().add(b.getLocation().toString()); drail.setPressed(true); b.setData((byte) (drail.getData() + 8)); } break; case POWERED_RAIL: PoweredRail rail = (PoweredRail) bs.getData(); if (plugin.redstoneListener.getRails().contains(b.getLocation().toString())) { plugin.redstoneListener.getRails().remove(b.getLocation().toString()); rail.setPowered(false); b.setData((byte) (rail.getData() - 8)); } else { plugin.redstoneListener.getRails().add(b.getLocation().toString()); rail.setPowered(true); b.setData((byte) (rail.getData() + 8)); } break; case PISTON_BASE: case PISTON_STICKY_BASE: PistonBaseMaterial piston = (PistonBaseMaterial) bs.getData(); // find the direction the piston is facing if (plugin.redstoneListener.getPistons().contains(b.getLocation().toString())) { plugin.redstoneListener.getPistons().remove(b.getLocation().toString()); for (BlockFace f : faces) { if (b.getRelative(f).getType().equals(Material.AIR)) { b.getRelative(f).setTypeIdAndData(20, (byte) 0, true); b.getRelative(f).setTypeIdAndData(0, (byte) 0, true); break; } } } else { plugin.redstoneListener.getPistons().add(b.getLocation().toString()); piston.setPowered(true); plugin.redstoneListener.setExtension(b); player.playSound(b.getLocation(), Sound.PISTON_EXTEND, 1.0f, 1.0f); } b.setData(piston.getData()); bs.update(true); break; case REDSTONE_LAMP_OFF: case REDSTONE_LAMP_ON: if (blockType.equals(Material.REDSTONE_LAMP_OFF)) { plugin.redstoneListener.getLamps().add(b.getLocation().toString()); b.setType(Material.REDSTONE_LAMP_ON); } else if (plugin.redstoneListener.getLamps().contains(b.getLocation().toString())) { plugin.redstoneListener.getLamps().remove(b.getLocation().toString()); b.setType(Material.REDSTONE_LAMP_OFF); } break; case REDSTONE_WIRE: if (plugin.redstoneListener.getWires().contains(b.getLocation().toString())) { plugin.redstoneListener.getWires().remove(b.getLocation().toString()); for (BlockFace f : faces) { if (b.getRelative(f).getType().equals(Material.REDSTONE_WIRE)) { b.setData((byte) 0); } } } else { plugin.redstoneListener.getWires().add(b.getLocation().toString()); b.setData((byte) 15); for (BlockFace f : faces) { if (b.getRelative(f).getType().equals(Material.REDSTONE_WIRE)) { b.setData((byte) 13); } } } break; default: break; } } } if (action.equals(Action.LEFT_CLICK_BLOCK)) { Block b = event.getClickedBlock(); if (diamond.contains(b.getType()) && player.hasPermission("tardis.sonic.diamond") && lore != null && lore.contains("Diamond Upgrade")) { playSonicSound(player, now, 600L, "sonic_short"); // drop appropriate material if (player.hasPermission("tardis.sonic.silktouch")) { Location l = b.getLocation(); switch (b.getType()) { case GLASS: l.getWorld().dropItemNaturally(l, new ItemStack(Material.GLASS, 1)); break; case IRON_FENCE: l.getWorld().dropItemNaturally(l, new ItemStack(Material.IRON_FENCE, 1)); break; case STAINED_GLASS: l.getWorld().dropItemNaturally(l, new ItemStack(Material.STAINED_GLASS, 1, b.getData())); break; case STAINED_GLASS_PANE: l.getWorld().dropItemNaturally(l, new ItemStack(Material.STAINED_GLASS_PANE, 1, b.getData())); break; case THIN_GLASS: l.getWorld().dropItemNaturally(l, new ItemStack(Material.THIN_GLASS, 1)); break; case WEB: l.getWorld().dropItemNaturally(l, new ItemStack(Material.WEB, 1)); break; default: break; } l.getWorld().playSound(l, Sound.SHEEP_SHEAR, 1.0F, 1.5F); // set the block to AIR b.setType(Material.AIR); } else { b.breakNaturally(); b.getLocation().getWorld().playSound(b.getLocation(), Sound.SHEEP_SHEAR, 1.0F, 1.5F); } } } } } }
public void onInteract(PlayerInteractEvent event) { final Player player = event.getPlayer(); long now = System.currentTimeMillis(); final ItemStack is = player.getItemInHand(); if (is.getType().equals(sonic) && is.hasItemMeta()) { ItemMeta im = player.getItemInHand().getItemMeta(); if (im.getDisplayName().equals("Sonic Screwdriver")) { List<String> lore = im.getLore(); Action action = event.getAction(); if (action.equals(Action.RIGHT_CLICK_AIR)) { playSonicSound(player, now, 3050L, "sonic_screwdriver"); if (player.hasPermission("tardis.admin") && lore != null && lore.contains("Admin Upgrade")) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { ItemStack[] items = new TARDISAdminMenuInventory(plugin).getMenu(); Inventory menu = plugin.getServer().createInventory(player, 54, "§4Admin Menu"); menu.setContents(items); player.openInventory(menu); } }, 40L); return; } if (player.hasPermission("tardis.sonic.freeze") && lore != null && lore.contains("Bio-scanner Upgrade")) { long cool = System.currentTimeMillis(); if ((!cooldown.containsKey(player.getName()) || cooldown.get(player.getName()) < cool)) { cooldown.put(player.getName(), cool + (plugin.getConfig().getInt("preferences.freeze_cooldown") * 1000L)); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { Location observerPos = player.getEyeLocation(); TARDISVector3D observerDir = new TARDISVector3D(observerPos.getDirection()); TARDISVector3D observerStart = new TARDISVector3D(observerPos); TARDISVector3D observerEnd = observerStart.add(observerDir.multiply(16)); Player hit = null; // Get nearby entities for (Player target : player.getWorld().getPlayers()) { // Bounding box of the given player TARDISVector3D targetPos = new TARDISVector3D(target.getLocation()); TARDISVector3D minimum = targetPos.add(-0.5, 0, -0.5); TARDISVector3D maximum = targetPos.add(0.5, 1.67, 0.5); if (target != player && hasIntersection(observerStart, observerEnd, minimum, maximum)) { if (hit == null || hit.getLocation().distanceSquared(observerPos) > target.getLocation().distanceSquared(observerPos)) { hit = target; } } } // freeze the closest player if (hit != null) { hit.sendMessage(plugin.pluginName + player.getName() + " froze you with their Sonic Screwdriver!"); final String hitNme = hit.getName(); frozenPlayers.add(hitNme); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { frozenPlayers.remove(hitNme); } }, 100L); } } }, 20L); } else { player.sendMessage(plugin.pluginName + player.getName() + " You cannot freeze another player yet!"); } return; } if (player.hasPermission("tardis.sonic.standard")) { Block targetBlock = player.getTargetBlock(plugin.tardisCommand.transparent, 50).getLocation().getBlock(); Material blockType = targetBlock.getType(); if (distance.contains(blockType)) { final BlockState bs = targetBlock.getState(); switch (blockType) { case IRON_DOOR_BLOCK: case WOODEN_DOOR: Block lowerdoor; if (targetBlock.getData() >= 8) { lowerdoor = targetBlock.getRelative(BlockFace.DOWN); } else { lowerdoor = targetBlock; } boolean allow = true; // is Lockette or LWC on the server? if (plugin.pm.isPluginEnabled("Lockette")) { Lockette Lockette = (Lockette) plugin.pm.getPlugin("Lockette"); if (Lockette.isProtected(lowerdoor)) { allow = false; } } if (plugin.pm.isPluginEnabled("LWC")) { LWC lwc = (LWC) plugin.pm.getPlugin("LWC"); if (!lwc.canAccessProtection(player, lowerdoor)) { allow = false; } } if (allow) { BlockState bsl = lowerdoor.getState(); Door door = (Door) bsl.getData(); door.setOpen(!door.isOpen()); bsl.setData(door); bsl.update(true); } break; case LEVER: Lever lever = (Lever) bs.getData(); lever.setPowered(!lever.isPowered()); bs.setData(lever); bs.update(true); break; case STONE_BUTTON: case WOOD_BUTTON: final Button button = (Button) bs.getData(); button.setPowered(true); bs.setData(button); bs.update(true); long delay = (blockType.equals(Material.STONE_BUTTON)) ? 20L : 30L; plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { button.setPowered(false); bs.setData(button); bs.update(true); } }, delay); break; default: break; } } return; } } if (action.equals(Action.RIGHT_CLICK_BLOCK)) { final Block b = event.getClickedBlock(); if (doors.contains(b.getType()) && player.hasPermission("tardis.admin") && lore != null && lore.contains("Admin Upgrade")) { playSonicSound(player, now, 3050L, "sonic_screwdriver"); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { HashMap<String, Object> wheredoor = new HashMap<String, Object>(); Location loc = b.getLocation(); String bw = loc.getWorld().getName(); int bx = loc.getBlockX(); int by = loc.getBlockY(); int bz = loc.getBlockZ(); if (b.getData() >= 8 && !b.getType().equals(Material.TRAP_DOOR)) { by = (by - 1); } String doorloc = bw + ":" + bx + ":" + by + ":" + bz; wheredoor.put("door_location", doorloc); wheredoor.put("door_type", 0); ResultSetDoors rsd = new ResultSetDoors(plugin, wheredoor, false); if (rsd.resultSet()) { int id = rsd.getTardis_id(); // get the TARDIS owner's name HashMap<String, Object> wheren = new HashMap<String, Object>(); wheren.put("tardis_id", id); ResultSetTardis rsn = new ResultSetTardis(plugin, wheren, "", false); if (rsn.resultSet()) { player.sendMessage(plugin.pluginName + "This is " + rsn.getOwner() + "'s TARDIS"); int percent = Math.round((rsn.getArtron_level() * 100F) / plugin.getArtronConfig().getInt("full_charge")); player.sendMessage(plugin.pluginName + "The Artron Energy Capacitor is at " + percent + "%"); HashMap<String, Object> whereb = new HashMap<String, Object>(); whereb.put("tardis_id", id); ResultSetBackLocation rsb = new ResultSetBackLocation(plugin, whereb); if (rsb.resultSet()) { player.sendMessage(plugin.pluginName + "Its last location was: " + rsb.getWorld().getName() + " " + rsb.getX() + ":" + rsb.getY() + ":" + rsb.getZ()); } } HashMap<String, Object> whereid = new HashMap<String, Object>(); whereid.put("tardis_id", id); ResultSetTravellers rst = new ResultSetTravellers(plugin, whereid, true); if (rst.resultSet()) { List<String> data = rst.getData(); player.sendMessage(plugin.pluginName + "The players inside this TARDIS are:"); for (String s : data) { player.sendMessage(s); } } else { player.sendMessage(plugin.pluginName + "The TARDIS is unoccupied."); } } } }, 60L); } if (!redstone.contains(b.getType()) && player.hasPermission("tardis.sonic.emerald") && lore != null && lore.contains("Emerald Upgrade")) { playSonicSound(player, now, 3050L, "sonic_screwdriver"); // scan environment this.scan(b.getLocation(), player); } if (redstone.contains(b.getType()) && player.hasPermission("tardis.sonic.redstone") && lore != null && lore.contains("Redstone Upgrade")) { playSonicSound(player, now, 600L, "sonic_short"); Material blockType = b.getType(); BlockState bs = b.getState(); // do redstone activation switch (blockType) { case DETECTOR_RAIL: DetectorRail drail = (DetectorRail) bs.getData(); if (plugin.redstoneListener.getRails().contains(b.getLocation().toString())) { plugin.redstoneListener.getRails().remove(b.getLocation().toString()); drail.setPressed(false); b.setData((byte) (drail.getData() - 8)); } else { plugin.redstoneListener.getRails().add(b.getLocation().toString()); drail.setPressed(true); b.setData((byte) (drail.getData() + 8)); } break; case POWERED_RAIL: PoweredRail rail = (PoweredRail) bs.getData(); if (plugin.redstoneListener.getRails().contains(b.getLocation().toString())) { plugin.redstoneListener.getRails().remove(b.getLocation().toString()); rail.setPowered(false); b.setData((byte) (rail.getData() - 8)); } else { plugin.redstoneListener.getRails().add(b.getLocation().toString()); rail.setPowered(true); b.setData((byte) (rail.getData() + 8)); } break; case PISTON_BASE: case PISTON_STICKY_BASE: PistonBaseMaterial piston = (PistonBaseMaterial) bs.getData(); // find the direction the piston is facing if (plugin.redstoneListener.getPistons().contains(b.getLocation().toString())) { plugin.redstoneListener.getPistons().remove(b.getLocation().toString()); for (BlockFace f : faces) { if (b.getRelative(f).getType().equals(Material.AIR)) { b.getRelative(f).setTypeIdAndData(20, (byte) 0, true); b.getRelative(f).setTypeIdAndData(0, (byte) 0, true); break; } } } else { plugin.redstoneListener.getPistons().add(b.getLocation().toString()); piston.setPowered(true); plugin.redstoneListener.setExtension(b); player.playSound(b.getLocation(), Sound.PISTON_EXTEND, 1.0f, 1.0f); } b.setData(piston.getData()); bs.update(true); break; case REDSTONE_LAMP_OFF: case REDSTONE_LAMP_ON: if (blockType.equals(Material.REDSTONE_LAMP_OFF)) { plugin.redstoneListener.getLamps().add(b.getLocation().toString()); b.setType(Material.REDSTONE_LAMP_ON); } else if (plugin.redstoneListener.getLamps().contains(b.getLocation().toString())) { plugin.redstoneListener.getLamps().remove(b.getLocation().toString()); b.setType(Material.REDSTONE_LAMP_OFF); } break; case REDSTONE_WIRE: if (plugin.redstoneListener.getWires().contains(b.getLocation().toString())) { plugin.redstoneListener.getWires().remove(b.getLocation().toString()); b.setData((byte) 0); for (BlockFace f : faces) { if (b.getRelative(f).getType().equals(Material.REDSTONE_WIRE)) { b.setData((byte) 0); } } } else { plugin.redstoneListener.getWires().add(b.getLocation().toString()); b.setData((byte) 15); for (BlockFace f : faces) { if (b.getRelative(f).getType().equals(Material.REDSTONE_WIRE)) { b.setData((byte) 13); } } } break; default: break; } } } if (action.equals(Action.LEFT_CLICK_BLOCK)) { Block b = event.getClickedBlock(); if (diamond.contains(b.getType()) && player.hasPermission("tardis.sonic.diamond") && lore != null && lore.contains("Diamond Upgrade")) { playSonicSound(player, now, 600L, "sonic_short"); // drop appropriate material if (player.hasPermission("tardis.sonic.silktouch")) { Location l = b.getLocation(); switch (b.getType()) { case GLASS: l.getWorld().dropItemNaturally(l, new ItemStack(Material.GLASS, 1)); break; case IRON_FENCE: l.getWorld().dropItemNaturally(l, new ItemStack(Material.IRON_FENCE, 1)); break; case STAINED_GLASS: l.getWorld().dropItemNaturally(l, new ItemStack(Material.STAINED_GLASS, 1, b.getData())); break; case STAINED_GLASS_PANE: l.getWorld().dropItemNaturally(l, new ItemStack(Material.STAINED_GLASS_PANE, 1, b.getData())); break; case THIN_GLASS: l.getWorld().dropItemNaturally(l, new ItemStack(Material.THIN_GLASS, 1)); break; case WEB: l.getWorld().dropItemNaturally(l, new ItemStack(Material.WEB, 1)); break; default: break; } l.getWorld().playSound(l, Sound.SHEEP_SHEAR, 1.0F, 1.5F); // set the block to AIR b.setType(Material.AIR); } else { b.breakNaturally(); b.getLocation().getWorld().playSound(b.getLocation(), Sound.SHEEP_SHEAR, 1.0F, 1.5F); } } } } } }
diff --git a/osiris2-client-ui/src/com/rameses/osiris2/common/ExplorerListViewController.java b/osiris2-client-ui/src/com/rameses/osiris2/common/ExplorerListViewController.java index 9b9b4c6d..42943ee5 100644 --- a/osiris2-client-ui/src/com/rameses/osiris2/common/ExplorerListViewController.java +++ b/osiris2-client-ui/src/com/rameses/osiris2/common/ExplorerListViewController.java @@ -1,251 +1,254 @@ package com.rameses.osiris2.common; import com.rameses.osiris2.client.InvokerFilter; import com.rameses.osiris2.client.InvokerProxy; import com.rameses.osiris2.client.InvokerUtil; import com.rameses.rcp.annotations.Binding; import com.rameses.rcp.annotations.Invoker; import com.rameses.rcp.common.Action; import com.rameses.rcp.common.Node; import com.rameses.rcp.common.Opener; import com.rameses.rcp.common.TreeNodeModel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class ExplorerListViewController implements ExplorerListViewModel { @Invoker protected com.rameses.osiris2.Invoker invoker; @Binding protected com.rameses.rcp.framework.Binding binding; private String name = "explorer"; private String type; private String serviceName; private Node selectedNode; // <editor-fold defaultstate="collapsed" desc=" Getter/Setter "> public String getTitle() { return (invoker == null? null: invoker.getCaption()); } public String getName() { return name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isRootVisible() { return false; } public String getIcon() { return "Tree.closedIcon"; } public Object getNodeModel() { return getTreeNodeModel(); } public List<Map> getNodes(Map params) { return getService().getNodes(params); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" ExplorerListViewModel implementation "> public String getServiceName() { return null; } public Node getSelectedNode() { return selectedNode; } public void setSelectedNode(Node selectedNode) { this.selectedNode = selectedNode; } public Object getSelectedNodeItem() { Node node = getSelectedNode(); return (node == null? null: node.getItem()); } private ExplorerListViewService service; public ExplorerListViewService getService() { String name = getServiceName(); if (name == null || name.trim().length() == 0) throw new RuntimeException("No service name specified"); if (service == null) { service = (ExplorerListViewService) InvokerProxy.getInstance().create(name, ExplorerListViewService.class); } return service; } public List<Action> lookupActions(String type) { List<Action> actions = new ArrayList(); try { actions = InvokerUtil.lookupActions(type, new InvokerFilter() { public boolean accept(com.rameses.osiris2.Invoker o) { return o.getWorkunitid().equals(invoker.getWorkunitid()); } }); } catch(Throwable t) { return actions; } for (int i=0; i<actions.size(); i++) { Action newAction = actions.get(i).clone(); actions.set(i, newAction); } return actions; } public List lookupOpeners(String type) { try { return InvokerUtil.lookupOpeners(type, null, new InvokerFilter() { public boolean accept(com.rameses.osiris2.Invoker o) { return o.getWorkunitid().equals(invoker.getWorkunitid()); } }); } catch(Throwable t) { return new ArrayList(); } } public List<Action> getNodeActions() { List<Action> actions = new ArrayList(); return getNodeActions(actions); } public List<Action> getNodeActions(List<Action> actions) { addActionOpeners(actions, lookupOpeners("formActions")); List<String> types = new ArrayList(); types.add(getType()); Node selNode = getSelectedNode(); - if (selNode != null) types.add(selNode.getPropertyString("type")); + if (selNode != null) { + String type = selNode.getPropertyString("type"); + if (type != null && !types.contains(type)) types.add(type); + } while (!types.isEmpty()) { String type = types.remove(0); if (type == null || type.length() == 0) continue; try { List openers = InvokerUtil.lookupOpeners(type+":formActions"); addActionOpeners(actions, openers); } catch(Throwable t) {;} } return actions; } private void addActionOpeners(List<Action> actions, List openers) { if (openers == null || openers.isEmpty()) return; while (!openers.isEmpty()) { Opener o = (Opener) openers.remove(0); actions.add(new ActionOpener(o)); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" event handling "> private Opener openerObj; public Opener getOpenerObject() { return openerObj; } public Object openFolder(Node node) { if (node == null) return null; Map params = new HashMap(); params.put("treeHandler", this); params.put("selectedNode", getSelectedNode()); String invokerType = getName() + "-listview:open"; openerObj = InvokerUtil.lookupOpener(invokerType, params); if (binding != null) binding.refresh("subform"); return null; } public Object openLeaf(Node node) { if (node == null) return null; Map params = new HashMap(); params.put("treeHandler", this); params.put("selectedNode", getSelectedNode()); String invokerType = getName() + "-listview:open"; openerObj = InvokerUtil.lookupOpener(invokerType, params); if (binding != null) binding.refresh("subform"); return null; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" TreeNodeModel helper and utilities "> private TreeNodeModel nodeModel; private final TreeNodeModel getTreeNodeModel() { if (nodeModel == null) { nodeModel = new TreeNodeModelImpl(); } return nodeModel; } private class TreeNodeModelImpl extends TreeNodeModel { ExplorerListViewController root = ExplorerListViewController.this; public boolean isRootVisible() { return root.isRootVisible(); } public String getIcon() { return root.getIcon(); } public List<Map> getNodeList(Node node) { Map params = new HashMap(); Object item = node.getItem(); if (item instanceof Map) params.putAll((Map) item); else params.put("item", node.getItem()); params.put("root", (node.getParent() == null)); params.put("caption", node.getCaption()); return root.getNodes(params); } public Object openFolder(Node node) { return root.openFolder(node); } public Object openLeaf(Node node) { return root.openLeaf(node); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" ActionOpener (class) "> private class ActionOpener extends Action { private Opener opener; ActionOpener(Opener opener) { this.opener = opener; setName(opener.getAction()); setCaption(opener.getCaption()); } public Object execute() { String target = opener.getTarget()+""; if (!target.matches("window|popup|process|_window|_popup|_process")) { opener.setTarget("popup"); } return opener; } } // </editor-fold> }
true
true
public List<Action> getNodeActions(List<Action> actions) { addActionOpeners(actions, lookupOpeners("formActions")); List<String> types = new ArrayList(); types.add(getType()); Node selNode = getSelectedNode(); if (selNode != null) types.add(selNode.getPropertyString("type")); while (!types.isEmpty()) { String type = types.remove(0); if (type == null || type.length() == 0) continue; try { List openers = InvokerUtil.lookupOpeners(type+":formActions"); addActionOpeners(actions, openers); } catch(Throwable t) {;} } return actions; }
public List<Action> getNodeActions(List<Action> actions) { addActionOpeners(actions, lookupOpeners("formActions")); List<String> types = new ArrayList(); types.add(getType()); Node selNode = getSelectedNode(); if (selNode != null) { String type = selNode.getPropertyString("type"); if (type != null && !types.contains(type)) types.add(type); } while (!types.isEmpty()) { String type = types.remove(0); if (type == null || type.length() == 0) continue; try { List openers = InvokerUtil.lookupOpeners(type+":formActions"); addActionOpeners(actions, openers); } catch(Throwable t) {;} } return actions; }
diff --git a/nuxeo-runtime/src/main/java/org/nuxeo/runtime/model/impl/ComponentManagerImpl.java b/nuxeo-runtime/src/main/java/org/nuxeo/runtime/model/impl/ComponentManagerImpl.java index 494836b2..4d33826a 100644 --- a/nuxeo-runtime/src/main/java/org/nuxeo/runtime/model/impl/ComponentManagerImpl.java +++ b/nuxeo-runtime/src/main/java/org/nuxeo/runtime/model/impl/ComponentManagerImpl.java @@ -1,463 +1,463 @@ /* * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Bogdan Stefanescu * Florent Guillaume */ package org.nuxeo.runtime.model.impl; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.common.collections.ListenerList; import org.nuxeo.runtime.ComponentEvent; import org.nuxeo.runtime.ComponentListener; import org.nuxeo.runtime.RuntimeService; import org.nuxeo.runtime.api.Framework; import org.nuxeo.runtime.model.ComponentInstance; import org.nuxeo.runtime.model.ComponentManager; import org.nuxeo.runtime.model.ComponentName; import org.nuxeo.runtime.model.Extension; import org.nuxeo.runtime.model.RegistrationInfo; import org.nuxeo.runtime.remoting.RemoteContext; /** * @author Bogdan Stefanescu * @author Florent Guillaume */ public class ComponentManagerImpl implements ComponentManager { private static final Log log = LogFactory.getLog(ComponentManager.class); protected final Map<ComponentName, Set<Extension>> pendingExtensions; private ListenerList listeners; private Map<ComponentName, RegistrationInfoImpl> registry; private Map<ComponentName, Set<RegistrationInfoImpl>> dependsOnMe; private final Map<String, RegistrationInfoImpl> services; public ComponentManagerImpl(RuntimeService runtime) { registry = new HashMap<ComponentName, RegistrationInfoImpl>(); dependsOnMe = new HashMap<ComponentName, Set<RegistrationInfoImpl>>(); pendingExtensions = new HashMap<ComponentName, Set<Extension>>(); listeners = new ListenerList(); services = new Hashtable<String, RegistrationInfoImpl>(); } public Collection<RegistrationInfo> getRegistrations() { return new ArrayList<RegistrationInfo>(registry.values()); } public Map<ComponentName, Set<ComponentName>> getPendingRegistrations() { Map<ComponentName, Set<ComponentName>> pending = new HashMap<ComponentName, Set<ComponentName>>(); for (RegistrationInfo ri : registry.values()) { if (ri.getState() == RegistrationInfo.REGISTERED) { pending.put(ri.getName(), ri.getRequiredComponents()); } } for (Map.Entry<ComponentName, Set<RegistrationInfoImpl>> e : dependsOnMe.entrySet()) { for (RegistrationInfo ri : e.getValue()) { Set<ComponentName> deps = new HashSet<ComponentName>(1); deps.add(e.getKey()); pending.put(ri.getName(), deps); } } return pending; } public Collection<ComponentName> getNeededRegistrations() { return pendingExtensions.keySet(); } public Collection<Extension> getPendingExtensions(ComponentName name) { return pendingExtensions.get(name); } public RegistrationInfo getRegistrationInfo(ComponentName name) { return registry.get(name); } public synchronized boolean isRegistered(ComponentName name) { return registry.containsKey(name); } public synchronized int size() { return registry.size(); } public ComponentInstance getComponent(ComponentName name) { RegistrationInfoImpl ri = registry.get(name); return ri != null ? ri.getComponent() : null; } public synchronized void shutdown() { // unregister me -> this will unregister all objects that depends on me List<RegistrationInfo> elems = new ArrayList<RegistrationInfo>( registry.values()); for (RegistrationInfo ri : elems) { try { unregister(ri); } catch (Exception e) { log.error("failed to shutdown component manager", e); } } try { listeners = null; registry.clear(); registry = null; dependsOnMe.clear(); dependsOnMe = null; } catch (Exception e) { log.error("Failed to shutdown registry manager"); } } public synchronized void register(RegistrationInfo regInfo) { _register((RegistrationInfoImpl) regInfo); } public final void _register(RegistrationInfoImpl ri) { ComponentName name = ri.getName(); if (isRegistered(name)) { if (name.getName().startsWith("org.nuxeo.runtime.")) { // XXX we hide the fact that nuxeo-runtime bundles are // registered twice // TODO fix the root cause and remove this return; } String msg = "Duplicate component name: '" + name + "'"; log.error(msg); Framework.getRuntime().getWarnings().add(msg); return; //throw new IllegalStateException("Component was already registered: " + name); } ri.manager = this; try { ri.register(); } catch (Exception e) { log.error("Failed to register component: " + ri.getName(), e); return; } // compute blocking dependencies boolean hasBlockingDeps = computeBlockingDependencies(ri); // check if blocking dependencies were found if (!hasBlockingDeps) { // check if there is any object waiting for me Set<RegistrationInfoImpl> pendings = removeDependencies(name); // update set the dependsOnMe member ri.dependsOnMe = pendings; // no blocking dependencies found - register it log.info("Registering component: " + ri.getName()); // create the component try { registry.put(ri.name, ri); ri.resolve(); // if some objects are waiting for me notify them about my registration if (ri.dependsOnMe != null) { // notify all components that deonds on me about my registration for (RegistrationInfoImpl pending : ri.dependsOnMe) { if (pending.waitsFor == null) { _register(pending); } else { // remove object dependence on me pending.waitsFor.remove(name); // if object has no more dependencies register it if (pending.waitsFor.isEmpty()) { pending.waitsFor = null; _register(pending); } } } } - } catch (Exception e) { + } catch (Throwable e) { log.error("Failed to create component: " + ri.name, e); } } else { log.info("Registration delayed for component: " + name + ". Waiting for: " + ri.waitsFor); } } public synchronized void unregister(RegistrationInfo regInfo) { _unregister((RegistrationInfoImpl) regInfo); } public final void _unregister(RegistrationInfoImpl ri) { // remove me as a dependent on other objects if (ri.requires != null) { for (ComponentName dep : ri.requires) { RegistrationInfoImpl depRi = registry.get(dep); if (depRi != null) { // can be null if comp is unresolved and waiting for this dep. if (depRi.dependsOnMe != null) { depRi.dependsOnMe.remove(ri); } } } } // unresolve also the dependent objects if (ri.dependsOnMe != null) { List<RegistrationInfoImpl> deps = new ArrayList<RegistrationInfoImpl>( ri.dependsOnMe); for (RegistrationInfoImpl dep : deps) { try { dep.unresolve(); // TODO ------------- keep waiting comp. in the registry - otherwise the unresolved comp will never be unregistered // add a blocking dependence on me if (dep.waitsFor == null) { dep.waitsFor = new HashSet<ComponentName>(); } dep.waitsFor.add(ri.name); addDependency(ri.name, dep); // remove from registry registry.remove(dep); // TODO ------------- } catch (Exception e) { log.error("Failed to unresolve component: " + dep.getName(), e); } } } log.info("Unregistering component: " + ri.name); try { if (registry.remove(ri.name) == null) { // may be a pending component //TODO -> put pendings in the registry } ri.unregister(); } catch (Exception e) { log.error("Failed to unregister component: " + ri.getName(), e); } } public synchronized void unregister(ComponentName name) { RegistrationInfoImpl ri = registry.get(name); if (ri != null) { _unregister(ri); } } public void addComponentListener(ComponentListener listener) { listeners.add(listener); } public void removeComponentListener(ComponentListener listener) { listeners.remove(listener); } void sendEvent(ComponentEvent event) { log.debug("Dispatching event: " + event); Object[] listeners = this.listeners.getListeners(); for (Object listener : listeners) { ((ComponentListener) listener).handleEvent(event); } } protected boolean computeBlockingDependencies(RegistrationInfoImpl ri) { if (ri.requires != null) { for (ComponentName dep : ri.requires) { RegistrationInfoImpl depRi = registry.get(dep); if (depRi == null) { // dep is not yet registered - add it to the blocking deps queue if (ri.waitsFor == null) { ri.waitsFor = new HashSet<ComponentName>(); } ri.waitsFor.add(dep); addDependency(dep, ri); } else { // we need this when unregistering depRi // to be able to unregister dependent components if (depRi.dependsOnMe == null) { depRi.dependsOnMe = new HashSet<RegistrationInfoImpl>(); } depRi.dependsOnMe.add(ri); } } } return ri.waitsFor != null; } protected synchronized void addDependency(ComponentName name, RegistrationInfoImpl dependent) { Set<RegistrationInfoImpl> pendings = dependsOnMe.get(name); if (pendings == null) { pendings = new HashSet<RegistrationInfoImpl>(); dependsOnMe.put(name, pendings); } pendings.add(dependent); } protected synchronized Set<RegistrationInfoImpl> removeDependencies( ComponentName name) { return dependsOnMe.remove(name); } public void registerExtension(Extension extension) throws Exception { ComponentName name = extension.getTargetComponent(); RegistrationInfoImpl ri = registry.get(name); if (ri != null) { if (log.isDebugEnabled()) { log.debug("Register contributed extension: " + extension); } loadContributions(ri, extension); ri.component.registerExtension(extension); if (!(extension.getContext() instanceof RemoteContext)) { // TODO avoid resending events when remoting extensions are registered // - temporary hack - find something better sendEvent(new ComponentEvent(ComponentEvent.EXTENSION_REGISTERED, ((ComponentInstanceImpl) extension.getComponent()).ri, extension)); } } else { // put the extension in the pending queue if (log.isDebugEnabled()) { log.debug("Enqueue contributed extension to pending queue: " + extension); } Set<Extension> extensions = pendingExtensions.get(name); if (extensions == null) { extensions = new HashSet<Extension>(); pendingExtensions.put(name, extensions); } extensions.add(extension); if (!(extension.getContext() instanceof RemoteContext)) { // TODO avoid resending events when remoting extensions are registered // - temporary hack - find something better sendEvent(new ComponentEvent(ComponentEvent.EXTENSION_PENDING, ((ComponentInstanceImpl) extension.getComponent()).ri, extension)); } } } public void unregisterExtension(Extension extension) throws Exception { if (log.isDebugEnabled()) { log.debug("Unregister contributed extension: " + extension); } ComponentName name = extension.getTargetComponent(); RegistrationInfo ri = registry.get(name); if (ri != null) { ComponentInstance co = ri.getComponent(); if (co != null) { co.unregisterExtension(extension); } } else { // maybe it's pending Set<Extension> extensions = pendingExtensions.get(name); if (extensions != null) { // FIXME: extensions is a set of Extensions, not ComponentNames. extensions.remove(name); if (extensions.isEmpty()) { pendingExtensions.remove(name); } } } if (!(extension.getContext() instanceof RemoteContext)) { // TODO avoid resending events when remoting extensions are // registered - temporary hack - find something better sendEvent(new ComponentEvent(ComponentEvent.EXTENSION_UNREGISTERED, ((ComponentInstanceImpl) extension.getComponent()).ri, extension)); } } public static void loadContributions(RegistrationInfoImpl ri, Extension xt) { ExtensionPointImpl xp = ri.getExtensionPoint(xt.getExtensionPoint()); if (xp != null && xp.contributions != null) { try { Object[] contribs = xp.loadContributions(ri, xt); xt.setContributions(contribs); } catch (Exception e) { log.error("Failed to create contribution objects", e); } } } public void registerServices(RegistrationInfoImpl ri) { if (ri.serviceDescriptor == null) { return; } for (String service : ri.serviceDescriptor.services) { log.info("Registering service: " + service); services.put(service, ri); // TODO: send notifications } } public void unregisterServices(RegistrationInfoImpl ri) { if (ri.serviceDescriptor == null) { return; } for (String service : ri.serviceDescriptor.services) { services.remove(service); // TODO: send notifications } } public String[] getServices() { return services.keySet().toArray(new String[services.size()]); } public <T> T getService(Class<T> serviceClass) { try { RegistrationInfoImpl ri = services.get(serviceClass.getName()); if (ri != null) { if (!ri.isActivated()) { if (ri.isResolved()) { ri.activate(); // activate the component if not yet activated } else { // Hack to avoid messages during TypeService activation if (!serviceClass.getSimpleName().equals("TypeProvider")) { log.debug("The component exposing the service " + serviceClass + " is not resolved"); } return null; } } return ri.getComponent().getAdapter(serviceClass); } } catch (Exception e) { log.error("Failed to get service: " + serviceClass); } return null; } public Collection<ComponentName> getActivatingRegistrations() { Collection<ComponentName> activating = new ArrayList<ComponentName>(); for (RegistrationInfo ri : registry.values()) { if (ri.getState() == RegistrationInfo.ACTIVATING) { activating.add(ri.getName()); } } return activating; } }
true
true
public final void _register(RegistrationInfoImpl ri) { ComponentName name = ri.getName(); if (isRegistered(name)) { if (name.getName().startsWith("org.nuxeo.runtime.")) { // XXX we hide the fact that nuxeo-runtime bundles are // registered twice // TODO fix the root cause and remove this return; } String msg = "Duplicate component name: '" + name + "'"; log.error(msg); Framework.getRuntime().getWarnings().add(msg); return; //throw new IllegalStateException("Component was already registered: " + name); } ri.manager = this; try { ri.register(); } catch (Exception e) { log.error("Failed to register component: " + ri.getName(), e); return; } // compute blocking dependencies boolean hasBlockingDeps = computeBlockingDependencies(ri); // check if blocking dependencies were found if (!hasBlockingDeps) { // check if there is any object waiting for me Set<RegistrationInfoImpl> pendings = removeDependencies(name); // update set the dependsOnMe member ri.dependsOnMe = pendings; // no blocking dependencies found - register it log.info("Registering component: " + ri.getName()); // create the component try { registry.put(ri.name, ri); ri.resolve(); // if some objects are waiting for me notify them about my registration if (ri.dependsOnMe != null) { // notify all components that deonds on me about my registration for (RegistrationInfoImpl pending : ri.dependsOnMe) { if (pending.waitsFor == null) { _register(pending); } else { // remove object dependence on me pending.waitsFor.remove(name); // if object has no more dependencies register it if (pending.waitsFor.isEmpty()) { pending.waitsFor = null; _register(pending); } } } } } catch (Exception e) { log.error("Failed to create component: " + ri.name, e); } } else { log.info("Registration delayed for component: " + name + ". Waiting for: " + ri.waitsFor); } }
public final void _register(RegistrationInfoImpl ri) { ComponentName name = ri.getName(); if (isRegistered(name)) { if (name.getName().startsWith("org.nuxeo.runtime.")) { // XXX we hide the fact that nuxeo-runtime bundles are // registered twice // TODO fix the root cause and remove this return; } String msg = "Duplicate component name: '" + name + "'"; log.error(msg); Framework.getRuntime().getWarnings().add(msg); return; //throw new IllegalStateException("Component was already registered: " + name); } ri.manager = this; try { ri.register(); } catch (Exception e) { log.error("Failed to register component: " + ri.getName(), e); return; } // compute blocking dependencies boolean hasBlockingDeps = computeBlockingDependencies(ri); // check if blocking dependencies were found if (!hasBlockingDeps) { // check if there is any object waiting for me Set<RegistrationInfoImpl> pendings = removeDependencies(name); // update set the dependsOnMe member ri.dependsOnMe = pendings; // no blocking dependencies found - register it log.info("Registering component: " + ri.getName()); // create the component try { registry.put(ri.name, ri); ri.resolve(); // if some objects are waiting for me notify them about my registration if (ri.dependsOnMe != null) { // notify all components that deonds on me about my registration for (RegistrationInfoImpl pending : ri.dependsOnMe) { if (pending.waitsFor == null) { _register(pending); } else { // remove object dependence on me pending.waitsFor.remove(name); // if object has no more dependencies register it if (pending.waitsFor.isEmpty()) { pending.waitsFor = null; _register(pending); } } } } } catch (Throwable e) { log.error("Failed to create component: " + ri.name, e); } } else { log.info("Registration delayed for component: " + name + ". Waiting for: " + ri.waitsFor); } }
diff --git a/ide/plugins/uml2/src/main/java/org/overture/prettyprinter/TypePrettyPrinterVisitor.java b/ide/plugins/uml2/src/main/java/org/overture/prettyprinter/TypePrettyPrinterVisitor.java index a078f22d86..cad275c30f 100644 --- a/ide/plugins/uml2/src/main/java/org/overture/prettyprinter/TypePrettyPrinterVisitor.java +++ b/ide/plugins/uml2/src/main/java/org/overture/prettyprinter/TypePrettyPrinterVisitor.java @@ -1,157 +1,157 @@ package org.overture.prettyprinter; import java.util.List; import java.util.Vector; import org.overture.ast.analysis.AnalysisException; import org.overture.ast.analysis.QuestionAnswerAdaptor; import org.overture.ast.intf.lex.ILexNameToken; import org.overture.ast.node.INode; import org.overture.ast.types.AInMapMapType; import org.overture.ast.types.AMapMapType; import org.overture.ast.types.ANamedInvariantType; import org.overture.ast.types.AOptionalType; import org.overture.ast.types.AProductType; import org.overture.ast.types.ARecordInvariantType; import org.overture.ast.types.ASeq1SeqType; import org.overture.ast.types.ASeqSeqType; import org.overture.ast.types.ASetType; import org.overture.ast.types.AUnionType; import org.overture.ast.types.AVoidReturnType; import org.overture.ast.types.AVoidType; import org.overture.ast.types.PType; import org.overture.ast.types.SBasicType; import org.overture.ast.types.SInvariantType; import org.overture.ast.util.Utils; public class TypePrettyPrinterVisitor extends QuestionAnswerAdaptor<PrettyPrinterEnv, String> { /** * */ private static final long serialVersionUID = -9082823353484822934L; @Override public String defaultSBasicType(SBasicType node, PrettyPrinterEnv question) throws AnalysisException { return node.toString(); } @Override public String defaultINode(INode node, PrettyPrinterEnv question) throws AnalysisException { return node.toString(); } @Override public String caseASetType(ASetType node, PrettyPrinterEnv question) throws AnalysisException { return "" + ""+(node.getEmpty() ? "{}" : "set of (" +node.getSetof().apply(this,question) + ")"); } @Override public String caseASeqSeqType(ASeqSeqType node, PrettyPrinterEnv question) throws AnalysisException { return "" + ""+(node.getEmpty() ? "[]" : "seq of (" + node.getSeqof().apply(this,question)+ ")" ); } @Override public String caseASeq1SeqType(ASeq1SeqType node, PrettyPrinterEnv question) throws AnalysisException { return "" + "seq1 of ("+node.getSeqof().apply(this,question)+")"; } @Override public String caseAMapMapType(AMapMapType node, PrettyPrinterEnv question) throws AnalysisException { return "" + "map ("+node.getFrom().apply(this,question)+") to ("+node.getTo().apply(this,question)+")"; } @Override public String caseAInMapMapType(AInMapMapType node, PrettyPrinterEnv question) throws AnalysisException { return "" + "inmap ("+node.getFrom().apply(this,question)+") to ("+node.getTo().apply(this,question)+")"; } @Override public String caseAProductType(AProductType node, PrettyPrinterEnv question) throws AnalysisException { List<String> types = new Vector<String>(); for (PType t : node.getTypes()) { types.add(t.apply(this,question)); } return "" + ""+Utils.listToString("(",types, " * ", ")"); } @Override public String caseAOptionalType(AOptionalType node, PrettyPrinterEnv question) throws AnalysisException { return "" + "["+node.getType().apply(this,question)+"]"; } @Override public String caseAUnionType(AUnionType node, PrettyPrinterEnv question) throws AnalysisException { List<String> types = new Vector<String>(); for (PType t : node.getTypes()) { types.add(t.apply(this,question)); } return "" + ""+(types.size() == 1?types.iterator().next().toString() : Utils.setToString(types, " | ")); } @Override public String defaultSInvariantType(SInvariantType node, PrettyPrinterEnv question) throws AnalysisException { ILexNameToken name = null; switch(node.kindSInvariantType()) { case ANamedInvariantType.kindSInvariantType: name = ((ANamedInvariantType)node).getName(); break; case ARecordInvariantType.kindSInvariantType: name = ((ARecordInvariantType)node).getName(); break; } if(name !=null) { if(name.getModule()!=null && !name.getModule().equals(question.getClassName())) { - return name.module+"`"+name.getFullName(); + return name.getModule()+"`"+name.getFullName(); } return name.getFullName(); } return "unresolved"; } @Override public String caseAVoidReturnType(AVoidReturnType node, PrettyPrinterEnv question) throws AnalysisException { return "()"; } @Override public String caseAVoidType(AVoidType node, PrettyPrinterEnv question) throws AnalysisException { return "()"; } }
true
true
public String defaultSInvariantType(SInvariantType node, PrettyPrinterEnv question) throws AnalysisException { ILexNameToken name = null; switch(node.kindSInvariantType()) { case ANamedInvariantType.kindSInvariantType: name = ((ANamedInvariantType)node).getName(); break; case ARecordInvariantType.kindSInvariantType: name = ((ARecordInvariantType)node).getName(); break; } if(name !=null) { if(name.getModule()!=null && !name.getModule().equals(question.getClassName())) { return name.module+"`"+name.getFullName(); } return name.getFullName(); } return "unresolved"; }
public String defaultSInvariantType(SInvariantType node, PrettyPrinterEnv question) throws AnalysisException { ILexNameToken name = null; switch(node.kindSInvariantType()) { case ANamedInvariantType.kindSInvariantType: name = ((ANamedInvariantType)node).getName(); break; case ARecordInvariantType.kindSInvariantType: name = ((ARecordInvariantType)node).getName(); break; } if(name !=null) { if(name.getModule()!=null && !name.getModule().equals(question.getClassName())) { return name.getModule()+"`"+name.getFullName(); } return name.getFullName(); } return "unresolved"; }
diff --git a/src/com/google/javascript/jscomp/DefaultPassConfig.java b/src/com/google/javascript/jscomp/DefaultPassConfig.java index 06e4c425..95b554bf 100644 --- a/src/com/google/javascript/jscomp/DefaultPassConfig.java +++ b/src/com/google/javascript/jscomp/DefaultPassConfig.java @@ -1,1834 +1,1834 @@ /* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** * Pass factories and meta-data for native JSCompiler passes. * * @author [email protected] (Nick Santos) */ // TODO(nicksantos): This needs state for a variety of reasons. Some of it // is to satisfy the existing API. Some of it is because passes really do // need to share state in non-trivial ways. This should be audited and // cleaned up. public class DefaultPassConfig extends PassConfig { /* For the --mark-as-compiled pass */ private static final String COMPILED_CONSTANT_NAME = "COMPILED"; /* Constant name for Closure's locale */ private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE"; // Compiler errors when invalid combinations of passes are run. static final DiagnosticType TIGHTEN_TYPES_WITHOUT_TYPE_CHECK = DiagnosticType.error("JSC_TIGHTEN_TYPES_WITHOUT_TYPE_CHECK", "TightenTypes requires type checking. Please use --check_types."); static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR = DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR", "Rename prototypes and inline variables cannot be used together"); // Miscellaneous errors. static final DiagnosticType REPORT_PATH_IO_ERROR = DiagnosticType.error("JSC_REPORT_PATH_IO_ERROR", "Error writing compiler report to {0}"); private static final DiagnosticType INPUT_MAP_PROP_PARSE = DiagnosticType.error("JSC_INPUT_MAP_PROP_PARSE", "Input property map parse error: {0}"); private static final DiagnosticType INPUT_MAP_VAR_PARSE = DiagnosticType.error("JSC_INPUT_MAP_VAR_PARSE", "Input variable map parse error: {0}"); /** * A global namespace to share across checking passes. * TODO(nicksantos): This is a hack until I can get the namespace into * the symbol table. */ private GlobalNamespace namespaceForChecks = null; /** * A type-tightener to share across optimization passes. */ private TightenTypes tightenTypes = null; /** Names exported by goog.exportSymbol. */ private Set<String> exportedNames = null; /** * Ids for cross-module method stubbing, so that each method has * a unique id. */ private CrossModuleMethodMotion.IdGenerator crossModuleIdGenerator = new CrossModuleMethodMotion.IdGenerator(); /** * Keys are arguments passed to getCssName() found during compilation; values * are the number of times the key appeared as an argument to getCssName(). */ private Map<String, Integer> cssNames = null; /** The variable renaming map */ private VariableMap variableMap = null; /** The property renaming map */ private VariableMap propertyMap = null; /** The naming map for anonymous functions */ private VariableMap anonymousFunctionNameMap = null; /** Fully qualified function names and globally unique ids */ private FunctionNames functionNames = null; public DefaultPassConfig(CompilerOptions options) { super(options); } @Override State getIntermediateState() { return new State( cssNames == null ? null : Maps.newHashMap(cssNames), exportedNames == null ? null : Collections.unmodifiableSet(exportedNames), crossModuleIdGenerator, variableMap, propertyMap, anonymousFunctionNameMap, functionNames); } @Override void setIntermediateState(State state) { this.cssNames = state.cssNames == null ? null : Maps.newHashMap(state.cssNames); this.exportedNames = state.exportedNames == null ? null : Sets.newHashSet(state.exportedNames); this.crossModuleIdGenerator = state.crossModuleIdGenerator; this.variableMap = state.variableMap; this.propertyMap = state.propertyMap; this.anonymousFunctionNameMap = state.anonymousFunctionNameMap; this.functionNames = state.functionNames; } @Override protected List<PassFactory> getChecks() { List<PassFactory> checks = Lists.newArrayList(); if (options.nameAnonymousFunctionsOnly) { if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { checks.add(nameMappedAnonymousFunctions); } else if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { checks.add(nameUnmappedAnonymousFunctions); } return checks; } if (options.checkSuspiciousCode) { checks.add(suspiciousCode); } if (options.checkControlStructures) { checks.add(checkControlStructures); } if (options.checkRequires.isOn()) { checks.add(checkRequires); } if (options.checkProvides.isOn()) { checks.add(checkProvides); } // The following passes are more like "preprocessor" passes. // It's important that they run before most checking passes. // Perhaps this method should be renamed? if (options.generateExports) { checks.add(generateExports); } if (options.exportTestFunctions) { checks.add(exportTestFunctions); } if (options.closurePass) { checks.add(closurePrimitives.makeOneTimePass()); } if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) { checks.add(closureCheckGetCssName); } if (options.closurePass) { checks.add(closureReplaceGetCssName); } if (options.syntheticBlockStartMarker != null) { // This pass must run before the first fold constants pass. checks.add(createSyntheticBlocks); } // All passes must run the variable check. This synthesizes // variables later so that the compiler doesn't crash. It also // checks the externs file for validity. If you don't want to warn // about missing variable declarations, we shut that specific // error off. WarningsGuard warningsGuard = options.getWarningsGuard(); if (!options.checkSymbols && (warningsGuard == null || !warningsGuard.disables( DiagnosticGroups.CHECK_VARIABLES))) { options.setWarningLevel(DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF); } checks.add(checkVars); if (options.checkShadowVars.isOn()) { checks.add(checkShadowVars); } if (options.aggressiveVarCheck.isOn()) { checks.add(checkVariableReferences); } // This pass should run before types are assigned. if (options.processObjectPropertyString) { checks.add(objectPropertyStringPreprocess); } // DiagnosticGroups override the plain checkTypes option. if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } // Type-checking already does more accurate method arity checking, so don't // do legacy method arity checking unless checkTypes is OFF. if (options.checkTypes) { checks.add(resolveTypes.makeOneTimePass()); checks.add(inferTypes.makeOneTimePass()); checks.add(checkTypes.makeOneTimePass()); } else { if (options.checkFunctions.isOn()) { checks.add(checkFunctions); } if (options.checkMethods.isOn()) { checks.add(checkMethods); } } if (options.checkUnreachableCode.isOn() || (options.checkTypes && options.checkMissingReturn.isOn())) { checks.add(checkControlFlow); } // CheckAccessControls only works if check types is on. if (options.enables(DiagnosticGroups.ACCESS_CONTROLS) && options.checkTypes) { checks.add(checkAccessControls); } if (options.checkGlobalNamesLevel.isOn()) { checks.add(checkGlobalNames); } if (options.checkUndefinedProperties.isOn() || options.checkUnusedPropertiesEarly) { checks.add(checkSuspiciousProperties); } if (options.checkCaja || options.checkEs5Strict) { checks.add(checkStrictMode); } // Defines in code always need to be processed. checks.add(processDefines); if (options.instrumentationTemplate != null || options.recordFunctionInformation) { checks.add(computeFunctionNames); } assertAllOneTimePasses(checks); return checks; } @Override protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (!options.idGenerators.isEmpty()) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Remove all parameters that are constants or unused. if (options.optimizeParameters) { passes.add(removeUselessParameters); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && options.removeAbstractMethods) { passes.add(removeAbstractMethods); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. if (options.removeUnusedVars) { passes.add(removeUnusedVars); } } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } if (options.collapseVariableDeclarations) { passes.add(collapseVariableDeclarations); } passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing - // local variables ("$$1") or constants ("$$constant"). + // local variables ("$$1"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } // Safety check if (options.checkSymbols) { passes.add(sanityCheckVars); } return passes; } /** Creates the passes for the main optimization loop. */ private List<PassFactory> getMainOptimizationLoop() { List<PassFactory> passes = Lists.newArrayList(); if (options.inlineGetters) { passes.add(inlineGetters); } passes.addAll(getCodeRemovingPasses()); if (options.inlineFunctions || options.inlineLocalFunctions) { passes.add(inlineFunctions); } if (options.removeUnusedVars) { if (options.deadAssignmentElimination) { passes.add(deadAssignmentsElimination); } passes.add(removeUnusedVars); } assertAllLoopablePasses(passes); return passes; } /** Creates several passes aimed at removing code. */ private List<PassFactory> getCodeRemovingPasses() { List<PassFactory> passes = Lists.newArrayList(); if (options.inlineVariables || options.inlineLocalVariables) { passes.add(inlineVariables); } else if (options.inlineConstantVars) { passes.add(inlineConstants); } if (options.removeConstantExpressions) { passes.add(removeConstantExpressions); } if (options.foldConstants) { // These used to be one pass. passes.add(minimizeExitPoints); passes.add(foldConstants); } if (options.removeDeadCode) { passes.add(removeUnreachableCode); } if (options.removeUnusedPrototypeProperties) { passes.add(removeUnusedPrototypeProperties); } assertAllLoopablePasses(passes); return passes; } /** * Checks for code that is probably wrong (such as stray expressions). */ // TODO(bolinfest): Write a CompilerPass for this. final PassFactory suspiciousCode = new PassFactory("suspiciousCode", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { List<Callback> sharedCallbacks = Lists.newArrayList(); sharedCallbacks.add(new CheckAccidentalSemicolon(CheckLevel.WARNING)); sharedCallbacks.add(new CheckSideEffects(CheckLevel.WARNING)); if (options.checkGlobalThisLevel.isOn()) { sharedCallbacks.add( new CheckGlobalThis(compiler, options.checkGlobalThisLevel)); } return combineChecks(compiler, sharedCallbacks); } }; /** Verify that all the passes are one-time passes. */ private void assertAllOneTimePasses(List<PassFactory> passes) { for (PassFactory pass : passes) { Preconditions.checkState(pass.isOneTimePass()); } } /** Verify that all the passes are multi-run passes. */ private void assertAllLoopablePasses(List<PassFactory> passes) { for (PassFactory pass : passes) { Preconditions.checkState(!pass.isOneTimePass()); } } /** Checks for validity of the control structures. */ private final PassFactory checkControlStructures = new PassFactory("checkControlStructures", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ControlStructureCheck(compiler); } }; /** Checks that all constructed classes are goog.require()d. */ private final PassFactory checkRequires = new PassFactory("checkRequires", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CheckRequiresForConstructors(compiler, options.checkRequires); } }; /** Makes sure @constructor is paired with goog.provides(). */ private final PassFactory checkProvides = new PassFactory("checkProvides", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CheckProvides(compiler, options.checkProvides); } }; private static final DiagnosticType GENERATE_EXPORTS_ERROR = DiagnosticType.error( "JSC_GENERATE_EXPORTS_ERROR", "Exports can only be generated if export symbol/property " + "functions are set."); /** Generates exports for @export annotations. */ private final PassFactory generateExports = new PassFactory("generateExports", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { CodingConvention convention = compiler.getCodingConvention(); if (convention.getExportSymbolFunction() != null && convention.getExportPropertyFunction() != null) { return new GenerateExports(compiler, convention.getExportSymbolFunction(), convention.getExportPropertyFunction()); } else { return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR); } } }; /** Generates exports for functions associated with JSUnit. */ private final PassFactory exportTestFunctions = new PassFactory("exportTestFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { CodingConvention convention = compiler.getCodingConvention(); if (convention.getExportSymbolFunction() != null) { return new ExportTestFunctions(compiler, convention.getExportSymbolFunction()); } else { return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR); } } }; /** Raw exports processing pass. */ final PassFactory gatherRawExports = new PassFactory("gatherRawExports", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { final GatherRawExports pass = new GatherRawExports( compiler); return new CompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); if (exportedNames == null) { exportedNames = Sets.newHashSet(); } exportedNames.addAll(pass.getExportedVariableNames()); } }; } }; /** Closure pre-processing pass. */ @SuppressWarnings("deprecation") final PassFactory closurePrimitives = new PassFactory("processProvidesAndRequires", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { final ProcessClosurePrimitives pass = new ProcessClosurePrimitives( compiler, options.brokenClosureRequiresLevel, options.rewriteNewDateGoogNow); return new CompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); exportedNames = pass.getExportedVariableNames(); } }; } }; /** Checks that CSS class names are wrapped in goog.getCssName */ private final PassFactory closureCheckGetCssName = new PassFactory("checkMissingGetCssName", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { String blacklist = options.checkMissingGetCssNameBlacklist; Preconditions.checkState(blacklist != null && !blacklist.isEmpty(), "Not checking use of goog.getCssName because of empty blacklist."); return new CheckMissingGetCssName( compiler, options.checkMissingGetCssNameLevel, blacklist); } }; /** * Processes goog.getCssName. The cssRenamingMap is used to lookup * replacement values for the classnames. If null, the raw class names are * inlined. */ private final PassFactory closureReplaceGetCssName = new PassFactory("renameCssNames", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { Map<String, Integer> newCssNames = null; if (options.gatherCssNames) { newCssNames = Maps.newHashMap(); } (new ReplaceCssNames(compiler, newCssNames)).process( externs, jsRoot); cssNames = newCssNames; } }; } }; /** * Creates synthetic blocks to prevent FoldConstants from moving code * past markers in the source. */ private final PassFactory createSyntheticBlocks = new PassFactory("createSyntheticBlocks", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CreateSyntheticBlocks(compiler, options.syntheticBlockStartMarker, options.syntheticBlockEndMarker); } }; /** Local constant folding */ static final PassFactory foldConstants = new PassFactory("foldConstants", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FoldConstants(compiler); } }; /** Checks that all variables are defined. */ private final PassFactory checkVars = new PassFactory("checkVars", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VarCheck(compiler); } }; /** Checks that no vars are illegally shadowed. */ private final PassFactory checkShadowVars = new PassFactory("variableShadowDeclarationCheck", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VariableShadowDeclarationCheck( compiler, options.checkShadowVars); } }; /** Checks that references to variables look reasonable. */ private final PassFactory checkVariableReferences = new PassFactory("checkVariableReferences", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VariableReferenceCheck( compiler, options.aggressiveVarCheck); } }; /** Pre-process goog.testing.ObjectPropertyString. */ private final PassFactory objectPropertyStringPreprocess = new PassFactory("ObjectPropertyStringPreprocess", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ObjectPropertyStringPreprocess(compiler); } }; /** Checks number of args passed to functions. */ private final PassFactory checkFunctions = new PassFactory("checkFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FunctionCheck(compiler, options.checkFunctions); } }; /** Checks number of args passed to methods. */ private final PassFactory checkMethods = new PassFactory("checkMethods", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MethodCheck(compiler, options.checkMethods); } }; /** Creates a typed scope and adds types to the type registry. */ final PassFactory resolveTypes = new PassFactory("resolveTypes", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new GlobalTypeResolver(compiler); } }; /** Rusn type inference. */ private final PassFactory inferTypes = new PassFactory("inferTypes", false) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(typedScopeCreator); makeTypeInference(compiler).process(externs, root); } }; } }; /** Checks type usage */ private final PassFactory checkTypes = new PassFactory("checkTypes", false) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(typedScopeCreator); TypeCheck check = makeTypeCheck(compiler); check.process(externs, root); compiler.getErrorManager().setTypedPercent(check.getTypedPercent()); } }; } }; /** * Checks possible execution paths of the program for problems: missing return * statements and dead code. */ private final PassFactory checkControlFlow = new PassFactory("checkControlFlow", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { List<Callback> callbacks = Lists.newArrayList(); if (options.checkUnreachableCode.isOn()) { callbacks.add( new CheckUnreachableCode(compiler, options.checkUnreachableCode)); } if (options.checkMissingReturn.isOn() && options.checkTypes) { callbacks.add( new CheckMissingReturn(compiler, options.checkMissingReturn)); } return combineChecks(compiler, callbacks); } }; /** Checks access controls. Depends on type-inference. */ private final PassFactory checkAccessControls = new PassFactory("checkAccessControls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CheckAccessControls(compiler); } }; /** Executes the given callbacks with a {@link CombinedCompilerPass}. */ private static CompilerPass combineChecks(AbstractCompiler compiler, List<Callback> callbacks) { Preconditions.checkArgument(callbacks.size() > 0); Callback[] array = callbacks.toArray(new Callback[callbacks.size()]); return new CombinedCompilerPass(compiler, array); } /** A compiler pass that resolves types in the global scope. */ private class GlobalTypeResolver implements CompilerPass { private final AbstractCompiler compiler; GlobalTypeResolver(AbstractCompiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { if (topScope == null) { typedScopeCreator = new MemoizedScopeCreator(new TypedScopeCreator(compiler)); topScope = typedScopeCreator.createScope(root.getParent(), null); } else { compiler.getTypeRegistry().resolveTypesInScope(topScope); } } } /** Checks global name usage. */ private final PassFactory checkGlobalNames = new PassFactory("Check names", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { // Create a global namespace for analysis by check passes. // Note that this class does all heavy computation lazily, // so it's OK to create it here. namespaceForChecks = new GlobalNamespace(compiler, jsRoot); new CheckGlobalNames(compiler, options.checkGlobalNamesLevel) .injectNamespace(namespaceForChecks).process(externs, jsRoot); } }; } }; /** Checks for properties that are not read or written */ private final PassFactory checkSuspiciousProperties = new PassFactory("checkSuspiciousProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new SuspiciousPropertiesCheck( compiler, options.checkUndefinedProperties, options.checkUnusedPropertiesEarly ? CheckLevel.WARNING : CheckLevel.OFF); } }; /** Checks that the code is ES5 or Caja compliant. */ private final PassFactory checkStrictMode = new PassFactory("checkStrictMode", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new StrictModeCheck(compiler, !options.checkSymbols, // don't check variables twice !options.checkCaja); // disable eval check if not Caja } }; /** Override @define-annotated constants. */ final PassFactory processDefines = new PassFactory("processDefines", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { Map<String, Node> replacements = getAdditionalReplacements(options); replacements.putAll(options.getDefineReplacements()); new ProcessDefines(compiler, replacements) .injectNamespace(namespaceForChecks).process(externs, jsRoot); // Kill the namespace in the other class // so that it can be garbage collected after all passes // are through with it. namespaceForChecks = null; } }; } }; /** Checks that all constants are not modified */ private final PassFactory checkConsts = new PassFactory("checkConsts", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ConstCheck(compiler); } }; /** Computes the names of functions for later analysis. */ private final PassFactory computeFunctionNames = new PassFactory("computeFunctionNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return ((functionNames = new FunctionNames(compiler))); } }; /** Skips Caja-private properties in for-in loops */ private final PassFactory ignoreCajaProperties = new PassFactory("ignoreCajaProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new IgnoreCajaProperties(compiler); } }; /** Inserts runtime type assertions for debugging. */ private final PassFactory runtimeTypeCheck = new PassFactory("runtimeTypeCheck", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RuntimeTypeCheck(compiler, options.runtimeTypeCheckLogFunction); } }; /** Generates unique ids. */ private final PassFactory replaceIdGenerators = new PassFactory("replaceIdGenerators", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ReplaceIdGenerators(compiler, options.idGenerators); } }; /** Optimizes the "arguments" array. */ private final PassFactory optimizeArgumentsArray = new PassFactory("optimizeArgumentsArray", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new OptimizeArgumentsArray(compiler); } }; /** Removes unused or constant formal parameters. */ private final PassFactory removeUselessParameters = new PassFactory("optimizeParameters", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameReferenceGraphConstruction c = new NameReferenceGraphConstruction(compiler); c.process(externs, root); (new OptimizeParameters(compiler, c.getNameReferenceGraph())).process( externs, root); } }; } }; /** Remove variables set to goog.abstractMethod. */ private final PassFactory removeAbstractMethods = new PassFactory("removeAbstractMethods", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new GoogleCodeRemoval(compiler); } }; /** Collapses names in the global scope. */ private final PassFactory collapseProperties = new PassFactory("collapseProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseProperties( compiler, options.collapsePropertiesOnExternTypes, !isInliningForbidden()); } }; /** * Try to infer the actual types, which may be narrower * than the declared types. */ private final PassFactory tightenTypesBuilder = new PassFactory("tightenTypes", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (!options.checkTypes) { return new ErrorPass(compiler, TIGHTEN_TYPES_WITHOUT_TYPE_CHECK); } tightenTypes = new TightenTypes(compiler); return tightenTypes; } }; /** Devirtualize property names based on type information. */ private final PassFactory disambiguateProperties = new PassFactory("disambiguateProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (tightenTypes == null) { return DisambiguateProperties.forJSTypeSystem(compiler); } else { return DisambiguateProperties.forConcreteTypeSystem( compiler, tightenTypes); } } }; /** * Chain calls to functions that return this. */ private final PassFactory chainCalls = new PassFactory("chainCalls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ChainCalls(compiler); } }; /** * Rewrite instance methods as static methods, to make them easier * to inline. */ private final PassFactory devirtualizePrototypeMethods = new PassFactory("devirtualizePrototypeMethods", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new DevirtualizePrototypeMethods(compiler); } }; /** * Look for function calls that are pure, and annotate them * that way. */ private final PassFactory markPureFunctions = new PassFactory("markPureFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PureFunctionMarker( compiler, options.debugFunctionSideEffectsPath, false); } }; /** * Look for function calls that have no side effects, and annotate them * that way. */ private final PassFactory markNoSideEffectCalls = new PassFactory("markNoSideEffectCalls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MarkNoSideEffectCalls(compiler); } }; /** Inlines variables heuristically. */ private final PassFactory inlineVariables = new PassFactory("inlineVariables", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (isInliningForbidden()) { // In old renaming schemes, inlining a variable can change whether // or not a property is renamed. This is bad, and those old renaming // schemes need to die. return new ErrorPass(compiler, CANNOT_USE_PROTOTYPE_AND_VAR); } else { InlineVariables.Mode mode; if (options.inlineVariables) { mode = InlineVariables.Mode.ALL; } else if (options.inlineLocalVariables) { mode = InlineVariables.Mode.LOCALS_ONLY; } else { throw new IllegalStateException("No variable inlining option set."); } return new InlineVariables(compiler, mode, true); } } }; /** Inlines variables that are marked as constants. */ private final PassFactory inlineConstants = new PassFactory("inlineConstants", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineVariables( compiler, InlineVariables.Mode.CONSTANTS_ONLY, true); } }; /** * Simplify expressions by removing the parts that have no side effects. */ private final PassFactory removeConstantExpressions = new PassFactory("removeConstantExpressions", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RemoveConstantExpressions(compiler); } }; /** * Perform local control flow optimizations. */ private final PassFactory minimizeExitPoints = new PassFactory("minimizeExitPoints", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MinimizeExitPoints(compiler); } }; /** * Use data flow analysis to remove dead branches. */ private final PassFactory removeUnreachableCode = new PassFactory("removeUnreachableCode", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new UnreachableCodeElimination(compiler, true); } }; /** * Remove prototype properties that do not appear to be used. */ private final PassFactory removeUnusedPrototypeProperties = new PassFactory("removeUnusedPrototypeProperties", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RemoveUnusedPrototypeProperties( compiler, options.removeUnusedPrototypePropertiesInExterns, !options.removeUnusedVars); } }; /** * Process smart name processing - removes unused classes and does referencing * starting with minimum set of names. */ private final PassFactory smartNamePass = new PassFactory("smartNamePass", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnalyzer na = new NameAnalyzer(compiler, false); na.process(externs, root); String reportPath = options.reportPath; if (reportPath != null) { try { Files.write(na.getHtmlReport(), new File(reportPath), Charsets.UTF_8); } catch (IOException e) { compiler.report(JSError.make(REPORT_PATH_IO_ERROR, reportPath)); } } if (options.smartNameRemoval) { na.removeUnreferenced(); } } }; } }; /** Inlines simple methods, like getters */ private PassFactory inlineGetters = new PassFactory("inlineGetters", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineGetters(compiler); } }; /** Kills dead assignments. */ private PassFactory deadAssignmentsElimination = new PassFactory("deadAssignmentsElimination", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new DeadAssignmentsElimination(compiler); } }; /** Inlines function calls. */ private PassFactory inlineFunctions = new PassFactory("inlineFunctions", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { boolean enableBlockInlining = !isInliningForbidden(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), options.inlineFunctions, options.inlineLocalFunctions, options.inlineAnonymousFunctionExpressions, enableBlockInlining, options.decomposeExpressions); } }; /** Removes variables that are never used. */ private PassFactory removeUnusedVars = new PassFactory("removeUnusedVars", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; return new RemoveUnusedVars( compiler, options.removeUnusedVarsInGlobalScope, preserveAnonymousFunctionNames); } }; /** * Move global symbols to a deeper common module */ private PassFactory crossModuleCodeMotion = new PassFactory("crossModuleCodeMotion", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CrossModuleCodeMotion(compiler, compiler.getModuleGraph()); } }; /** * Move methods to a deeper common module */ private PassFactory crossModuleMethodMotion = new PassFactory("crossModuleMethodMotion", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CrossModuleMethodMotion( compiler, crossModuleIdGenerator, // Only move properties in externs if we're not treating // them as exports. options.removeUnusedPrototypePropertiesInExterns); } }; /** A data-flow based variable inliner. */ private final PassFactory flowSensitiveInlineVariables = new PassFactory("flowSensitiveInlineVariables", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FlowSensitiveInlineVariables(compiler); } }; /** Uses register-allocation algorithms to use fewer variables. */ private final PassFactory coalesceVariableNames = new PassFactory("coalesceVariableNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CoalesceVariableNames(compiler, options.generatePseudoNames); } }; /** * Some simple, local collapses (e.g., {@code var x; var y;} becomes * {@code var x,y;}. */ private final PassFactory collapseVariableDeclarations = new PassFactory("collapseVariableDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { compiler.setUnnormalized(); return new CollapseVariableDeclarations(compiler); } }; /** * Extracts common sub-expressions. */ private final PassFactory extractPrototypeMemberDeclarations = new PassFactory("extractPrototypeMemberDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ExtractPrototypeMemberDeclarations(compiler); } }; /** Rewrites common function definitions to be more compact. */ private final PassFactory rewriteFunctionExpressions = new PassFactory("rewriteFunctionExpressions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FunctionRewriter(compiler); } }; /** Collapses functions to not use the VAR keyword. */ private final PassFactory collapseAnonymousFunctions = new PassFactory("collapseAnonymousFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseAnonymousFunctions(compiler); } }; /** Moves function declarations to the top, to simulate actual hoisting. */ private final PassFactory moveFunctionDeclarations = new PassFactory("moveFunctionDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MoveFunctionDeclarations(compiler); } }; private final PassFactory nameUnmappedAnonymousFunctions = new PassFactory("nameAnonymousFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new NameAnonymousFunctions(compiler); } }; private final PassFactory nameMappedAnonymousFunctions = new PassFactory("nameAnonymousFunctions", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnonymousFunctionsMapped naf = new NameAnonymousFunctionsMapped(compiler); naf.process(externs, root); anonymousFunctionNameMap = naf.getFunctionMap(); } }; } }; /** Alias external symbols. */ private final PassFactory aliasExternals = new PassFactory("aliasExternals", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasExternals(compiler, compiler.getModuleGraph(), options.unaliasableGlobals, options.aliasableGlobals); } }; /** * Alias string literals with global variables, to avoid creating lots of * transient objects. */ private final PassFactory aliasStrings = new PassFactory("aliasStrings", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasStrings( compiler, compiler.getModuleGraph(), options.aliasAllStrings ? null : options.aliasableStrings, options.aliasStringsBlacklist, options.outputJsStringUsage); } }; /** Aliases common keywords (true, false) */ private final PassFactory aliasKeywords = new PassFactory("aliasKeywords", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasKeywords(compiler); } }; /** Handling for the ObjectPropertyString primitive. */ private final PassFactory objectPropertyStringPostprocess = new PassFactory("ObjectPropertyStringPostprocess", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ObjectPropertyStringPostprocess(compiler); } }; /** * Renames properties so that the two properties that never appear on * the same object get the same name. */ private final PassFactory ambiguateProperties = new PassFactory("ambiguateProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AmbiguateProperties( compiler, options.anonymousFunctionNaming.getReservedCharacters()); } }; /** Denormalize the AST for code generation. */ private final PassFactory denormalize = new PassFactory("denormalize", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { compiler.setUnnormalized(); return new Denormalize(compiler); } }; /** Inverting name normalization. */ private final PassFactory invertContextualRenaming = new PassFactory("invertNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler); } }; /** * Renames properties. */ private final PassFactory renameProperties = new PassFactory("renameProperties", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { VariableMap map = null; if (options.inputPropertyMapSerialized != null) { try { map = VariableMap.fromBytes(options.inputPropertyMapSerialized); } catch (ParseException e) { return new ErrorPass(compiler, JSError.make(INPUT_MAP_PROP_PARSE, e.getMessage())); } } final VariableMap prevPropertyMap = map; return new CompilerPass() { @Override public void process(Node externs, Node root) { propertyMap = runPropertyRenaming( compiler, prevPropertyMap, externs, root); } }; } }; private VariableMap runPropertyRenaming( AbstractCompiler compiler, VariableMap prevPropertyMap, Node externs, Node root) { char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters(); switch (options.propertyRenaming) { case HEURISTIC: RenamePrototypes rproto = new RenamePrototypes(compiler, false, reservedChars, prevPropertyMap); rproto.process(externs, root); return rproto.getPropertyMap(); case AGGRESSIVE_HEURISTIC: RenamePrototypes rproto2 = new RenamePrototypes(compiler, true, reservedChars, prevPropertyMap); rproto2.process(externs, root); return rproto2.getPropertyMap(); case ALL_UNQUOTED: RenameProperties rprop = new RenameProperties( compiler, options.generatePseudoNames, prevPropertyMap, reservedChars); rprop.process(externs, root); return rprop.getPropertyMap(); default: throw new IllegalStateException( "Unrecognized property renaming policy"); } } /** Renames variables. */ private final PassFactory renameVars = new PassFactory("renameVars", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { VariableMap map = null; if (options.inputVariableMapSerialized != null) { try { map = VariableMap.fromBytes(options.inputVariableMapSerialized); } catch (ParseException e) { return new ErrorPass(compiler, JSError.make(INPUT_MAP_VAR_PARSE, e.getMessage())); } } final VariableMap prevVariableMap = map; return new CompilerPass() { @Override public void process(Node externs, Node root) { variableMap = runVariableRenaming( compiler, prevVariableMap, externs, root); } }; } }; private VariableMap runVariableRenaming( AbstractCompiler compiler, VariableMap prevVariableMap, Node externs, Node root) { char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters(); boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; RenameVars rn = new RenameVars( compiler, options.renamePrefix, options.variableRenaming == VariableRenamingPolicy.LOCAL, preserveAnonymousFunctionNames, options.generatePseudoNames, prevVariableMap, reservedChars, exportedNames); rn.process(externs, root); return rn.getVariableMap(); } /** Renames labels */ private final PassFactory renameLabels = new PassFactory("renameLabels", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RenameLabels(compiler); } }; /** Convert bracket access to dot access */ private final PassFactory convertToDottedProperties = new PassFactory("convertToDottedProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ConvertToDottedProperties(compiler); } }; /** Checks that all variables are defined. */ private final PassFactory sanityCheckVars = new PassFactory("sanityCheckVars", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VarCheck(compiler, true); } }; /** Adds instrumentations according to an instrumentation template. */ private final PassFactory instrumentFunctions = new PassFactory("instrumentFunctions", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { try { FileReader templateFile = new FileReader(options.instrumentationTemplate); (new InstrumentFunctions( compiler, functionNames, options.instrumentationTemplate, options.appNameStr, templateFile)).process(externs, root); } catch (IOException e) { compiler.report( JSError.make(AbstractCompiler.READ_ERROR, options.instrumentationTemplate)); } } }; } }; /** * Create a no-op pass that can only run once. Used to break up loops. */ private static PassFactory createEmptyPass(String name) { return new PassFactory(name, true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return runInSerial(); } }; } /** * Runs custom passes that are designated to run at a particular time. */ private PassFactory getCustomPasses( final CustomPassExecutionTime executionTime) { return new PassFactory("runCustomPasses", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return runInSerial(options.customPasses.get(executionTime)); } }; } /** * All inlining is forbidden in heuristic renaming mode, because inlining * will ruin the invariants that it depends on. */ private boolean isInliningForbidden() { return options.propertyRenaming == PropertyRenamingPolicy.HEURISTIC || options.propertyRenaming == PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC; } /** Create a compiler pass that runs the given passes in serial. */ private static CompilerPass runInSerial(final CompilerPass ... passes) { return runInSerial(Lists.newArrayList(passes)); } /** Create a compiler pass that runs the given passes in serial. */ private static CompilerPass runInSerial( final Collection<CompilerPass> passes) { return new CompilerPass() { @Override public void process(Node externs, Node root) { for (CompilerPass pass : passes) { pass.process(externs, root); } } }; } @VisibleForTesting static Map<String, Node> getAdditionalReplacements( CompilerOptions options) { Map<String, Node> additionalReplacements = Maps.newHashMap(); if (options.markAsCompiled || options.closurePass) { additionalReplacements.put(COMPILED_CONSTANT_NAME, new Node(Token.TRUE)); } if (options.closurePass && options.locale != null) { additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME, Node.newString(options.locale)); } return additionalReplacements; } /** A compiler pass that marks pure functions. */ private static class PureFunctionMarker implements CompilerPass { private final AbstractCompiler compiler; private final String reportPath; private final boolean useNameReferenceGraph; PureFunctionMarker(AbstractCompiler compiler, String reportPath, boolean useNameReferenceGraph) { this.compiler = compiler; this.reportPath = reportPath; this.useNameReferenceGraph = useNameReferenceGraph; } @Override public void process(Node externs, Node root) { DefinitionProvider definitionProvider = null; if (useNameReferenceGraph) { NameReferenceGraphConstruction graphBuilder = new NameReferenceGraphConstruction(compiler); graphBuilder.process(externs, root); definitionProvider = graphBuilder.getNameReferenceGraph(); } else { SimpleDefinitionFinder defFinder = new SimpleDefinitionFinder(compiler); defFinder.process(externs, root); definitionProvider = defFinder; } PureFunctionIdentifier pureFunctionIdentifier = new PureFunctionIdentifier(compiler, definitionProvider); pureFunctionIdentifier.process(externs, root); if (reportPath != null) { try { Files.write(pureFunctionIdentifier.getDebugReport(), new File(reportPath), Charsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } } } }
true
true
protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (!options.idGenerators.isEmpty()) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Remove all parameters that are constants or unused. if (options.optimizeParameters) { passes.add(removeUselessParameters); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && options.removeAbstractMethods) { passes.add(removeAbstractMethods); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. if (options.removeUnusedVars) { passes.add(removeUnusedVars); } } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } if (options.collapseVariableDeclarations) { passes.add(collapseVariableDeclarations); } passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing // local variables ("$$1") or constants ("$$constant"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } // Safety check if (options.checkSymbols) { passes.add(sanityCheckVars); } return passes; }
protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (!options.idGenerators.isEmpty()) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Remove all parameters that are constants or unused. if (options.optimizeParameters) { passes.add(removeUselessParameters); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && options.removeAbstractMethods) { passes.add(removeAbstractMethods); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. if (options.removeUnusedVars) { passes.add(removeUnusedVars); } } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } if (options.collapseVariableDeclarations) { passes.add(collapseVariableDeclarations); } passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing // local variables ("$$1"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } // Safety check if (options.checkSymbols) { passes.add(sanityCheckVars); } return passes; }
diff --git a/bundles/coffeescript/src/main/java/de/matrixweb/smaller/coffeescript/CoffeescriptProcessor.java b/bundles/coffeescript/src/main/java/de/matrixweb/smaller/coffeescript/CoffeescriptProcessor.java index 6f01d24..596810e 100644 --- a/bundles/coffeescript/src/main/java/de/matrixweb/smaller/coffeescript/CoffeescriptProcessor.java +++ b/bundles/coffeescript/src/main/java/de/matrixweb/smaller/coffeescript/CoffeescriptProcessor.java @@ -1,86 +1,86 @@ package de.matrixweb.smaller.coffeescript; import java.io.IOException; import java.util.Map; import org.apache.commons.io.FilenameUtils; import de.matrixweb.nodejs.NodeJsExecutor; import de.matrixweb.smaller.common.SmallerException; import de.matrixweb.smaller.resource.Processor; import de.matrixweb.smaller.resource.Resource; import de.matrixweb.smaller.resource.Type; import de.matrixweb.vfs.VFS; /** * @author marwol */ public class CoffeescriptProcessor implements Processor { private final String version; private NodeJsExecutor node; /** * */ public CoffeescriptProcessor() { this("1.6.3"); } /** * @param version */ public CoffeescriptProcessor(final String version) { this.version = version; } /** * @see de.matrixweb.smaller.resource.Processor#supportsType(de.matrixweb.smaller.resource.Type) */ @Override public boolean supportsType(final Type type) { return type == Type.JS; } /** * @see de.matrixweb.smaller.resource.Processor#execute(de.matrixweb.vfs.VFS, * de.matrixweb.smaller.resource.Resource, java.util.Map) */ @Override public Resource execute(final VFS vfs, final Resource resource, final Map<String, String> options) throws IOException { if (this.node == null) { try { this.node = new NodeJsExecutor(); this.node.setModule(getClass().getClassLoader(), "coffeescript-" + this.version, "coffeescript.js"); } catch (final IOException e) { - throw new SmallerException("Failed to setup node for browserify", e); + throw new SmallerException("Failed to setup node for coffeescript", e); } } final String outfile = this.node.run(vfs, resource != null ? resource.getPath() : null, options); Resource result = resource; if (resource != null) { if (outfile != null) { result = resource.getResolver().resolve(outfile); } else { result = resource.getResolver().resolve( FilenameUtils.removeExtension(resource.getPath()) + ".js"); } } return result; } /** * @see de.matrixweb.smaller.resource.Processor#dispose() */ @Override public void dispose() { if (this.node != null) { this.node.dispose(); } } }
true
true
public Resource execute(final VFS vfs, final Resource resource, final Map<String, String> options) throws IOException { if (this.node == null) { try { this.node = new NodeJsExecutor(); this.node.setModule(getClass().getClassLoader(), "coffeescript-" + this.version, "coffeescript.js"); } catch (final IOException e) { throw new SmallerException("Failed to setup node for browserify", e); } } final String outfile = this.node.run(vfs, resource != null ? resource.getPath() : null, options); Resource result = resource; if (resource != null) { if (outfile != null) { result = resource.getResolver().resolve(outfile); } else { result = resource.getResolver().resolve( FilenameUtils.removeExtension(resource.getPath()) + ".js"); } } return result; }
public Resource execute(final VFS vfs, final Resource resource, final Map<String, String> options) throws IOException { if (this.node == null) { try { this.node = new NodeJsExecutor(); this.node.setModule(getClass().getClassLoader(), "coffeescript-" + this.version, "coffeescript.js"); } catch (final IOException e) { throw new SmallerException("Failed to setup node for coffeescript", e); } } final String outfile = this.node.run(vfs, resource != null ? resource.getPath() : null, options); Resource result = resource; if (resource != null) { if (outfile != null) { result = resource.getResolver().resolve(outfile); } else { result = resource.getResolver().resolve( FilenameUtils.removeExtension(resource.getPath()) + ".js"); } } return result; }
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/AddListenerAction.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/AddListenerAction.java index 8509aed4f..2292c3ce2 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/AddListenerAction.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/AddListenerAction.java @@ -1,69 +1,69 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.EventListener; /** Adds a listener to an actor. * @author Nathan Sweet */ public class AddListenerAction extends Action { private Actor targetActor; private EventListener listener; private boolean capture; public boolean act (float delta) { Actor actor = (targetActor != null ? targetActor : this.actor); if (capture) - targetActor.addCaptureListener(listener); + actor.addCaptureListener(listener); else - targetActor.addListener(listener); + actor.addListener(listener); return true; } public Actor getTargetActor () { return targetActor; } /** Sets the actor to add a listneer to. If null (the default), the {@link #getActor() actor} will be used. */ public void setTargetActor (Actor actor) { this.targetActor = actor; } public EventListener getListener () { return listener; } public void setListener (EventListener listener) { this.listener = listener; } public boolean getCapture () { return capture; } public void setCapture (boolean capture) { this.capture = capture; } public void reset () { super.reset(); targetActor = null; listener = null; } }
false
true
public boolean act (float delta) { Actor actor = (targetActor != null ? targetActor : this.actor); if (capture) targetActor.addCaptureListener(listener); else targetActor.addListener(listener); return true; }
public boolean act (float delta) { Actor actor = (targetActor != null ? targetActor : this.actor); if (capture) actor.addCaptureListener(listener); else actor.addListener(listener); return true; }
diff --git a/core/src/com/censoredsoftware/Demigods/Engine/Tracked/TrackedModelFactory.java b/core/src/com/censoredsoftware/Demigods/Engine/Tracked/TrackedModelFactory.java index c4fbc05d..a7d96ccd 100644 --- a/core/src/com/censoredsoftware/Demigods/Engine/Tracked/TrackedModelFactory.java +++ b/core/src/com/censoredsoftware/Demigods/Engine/Tracked/TrackedModelFactory.java @@ -1,123 +1,123 @@ package com.censoredsoftware.Demigods.Engine.Tracked; import java.util.HashMap; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import com.censoredsoftware.Demigods.Engine.PlayerCharacter.PlayerCharacter; public class TrackedModelFactory { public static TrackedLocation createTrackedLocation(String world, double X, double Y, double Z, float yaw, float pitch) { TrackedLocation trackedLocation = new TrackedLocation(); trackedLocation.setWorld(world); trackedLocation.setX(X); trackedLocation.setY(Y); trackedLocation.setZ(Z); trackedLocation.setYaw(yaw); trackedLocation.setPitch(pitch); TrackedLocation.save(trackedLocation); return trackedLocation; } public static TrackedLocation createUnsavedTrackedLocation(String world, double X, double Y, double Z, float yaw, float pitch) { TrackedLocation trackedLocation = new TrackedLocation(); trackedLocation.setWorld(world); trackedLocation.setX(X); trackedLocation.setY(Y); trackedLocation.setZ(Z); trackedLocation.setYaw(yaw); trackedLocation.setPitch(pitch); return trackedLocation; } public static TrackedLocation createTrackedLocation(Location location) { return createTrackedLocation(location.getWorld().getName(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } public static TrackedLocation createUnsavedTrackedLocation(Location location) { return createUnsavedTrackedLocation(location.getWorld().getName(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } public static TrackedPlayer createTrackedPlayer(OfflinePlayer player) { TrackedPlayer trackedPlayer = new TrackedPlayer(); trackedPlayer.setPlayer(player.getName()); trackedPlayer.setLastLoginTime(player.getLastPlayed()); TrackedPlayer.save(trackedPlayer); return trackedPlayer; } public static TrackedPlayerInventory createTrackedPlayerInventory(PlayerInventory inventory) { TrackedPlayerInventory trackedInventory = new TrackedPlayerInventory(); trackedInventory.setHelmet(createTrackedItemStack(inventory.getHelmet())); trackedInventory.setChestplate(createTrackedItemStack(inventory.getChestplate())); trackedInventory.setLeggings(createTrackedItemStack(inventory.getLeggings())); trackedInventory.setBoots(createTrackedItemStack(inventory.getBoots())); trackedInventory.setItems(new HashMap<Integer, TrackedItemStack>()); TrackedPlayerInventory.save(trackedInventory.processInventory(inventory)); return trackedInventory; } public static TrackedItemStack createTrackedItemStack(ItemStack item) { TrackedItemStack trackedItem = new TrackedItemStack(); trackedItem.setTypeId(item.getTypeId()); trackedItem.setByteId(item.getData().getData()); trackedItem.setAmount(item.getAmount()); trackedItem.setDurability(item.getDurability()); if(item.getItemMeta().hasDisplayName()) trackedItem.setName(item.getItemMeta().getDisplayName()); if(item.getItemMeta().hasLore()) trackedItem.setLore(item.getItemMeta().getLore()); trackedItem.setEnchantments(item); trackedItem.setBookMeta(item); TrackedItemStack.save(trackedItem); return trackedItem; } public static TrackedBlock createTrackedBlock(Location location, String type, Material material, byte matByte) { - TrackedLocation trackedLocation = TrackedModelFactory.createUnsavedTrackedLocation(location); + TrackedLocation trackedLocation = TrackedModelFactory.createTrackedLocation(location); TrackedBlock trackedBlock = new TrackedBlock(); trackedBlock.setLocation(trackedLocation); trackedBlock.setType(type); trackedBlock.setMaterial(material); trackedBlock.setMaterialByte(matByte); trackedBlock.setPreviousMaterial(Material.getMaterial(location.getBlock().getTypeId())); trackedBlock.setPreviousMaterialByte(location.getBlock().getData()); location.getBlock().setType(material); location.getBlock().setData(matByte); TrackedBlock.save(trackedBlock); return trackedBlock; } public static TrackedBlock createTrackedBlock(Location location, String type, Material material) { return createTrackedBlock(location, type, material, (byte) 0); } public static TrackedBattle createTrackedBattle(PlayerCharacter attacking, PlayerCharacter defending, final Long startTime) { TrackedBattle battle = new TrackedBattle(); Location startedLocation = ((Player) attacking.getOwner()).getLocation(); battle.setWhoStarted(attacking); battle.setStartLocation(TrackedModelFactory.createUnsavedTrackedLocation(startedLocation)); battle.setStartTime(startTime); battle.addCharacter(attacking); battle.addCharacter(defending); battle.setActive(true); TrackedBattle.save(battle); return battle; } }
true
true
public static TrackedBlock createTrackedBlock(Location location, String type, Material material, byte matByte) { TrackedLocation trackedLocation = TrackedModelFactory.createUnsavedTrackedLocation(location); TrackedBlock trackedBlock = new TrackedBlock(); trackedBlock.setLocation(trackedLocation); trackedBlock.setType(type); trackedBlock.setMaterial(material); trackedBlock.setMaterialByte(matByte); trackedBlock.setPreviousMaterial(Material.getMaterial(location.getBlock().getTypeId())); trackedBlock.setPreviousMaterialByte(location.getBlock().getData()); location.getBlock().setType(material); location.getBlock().setData(matByte); TrackedBlock.save(trackedBlock); return trackedBlock; }
public static TrackedBlock createTrackedBlock(Location location, String type, Material material, byte matByte) { TrackedLocation trackedLocation = TrackedModelFactory.createTrackedLocation(location); TrackedBlock trackedBlock = new TrackedBlock(); trackedBlock.setLocation(trackedLocation); trackedBlock.setType(type); trackedBlock.setMaterial(material); trackedBlock.setMaterialByte(matByte); trackedBlock.setPreviousMaterial(Material.getMaterial(location.getBlock().getTypeId())); trackedBlock.setPreviousMaterialByte(location.getBlock().getData()); location.getBlock().setType(material); location.getBlock().setData(matByte); TrackedBlock.save(trackedBlock); return trackedBlock; }
diff --git a/AttributesImpl/src/org/gephi/data/attributes/AttributeFactoryImpl.java b/AttributesImpl/src/org/gephi/data/attributes/AttributeFactoryImpl.java index 578f4337e..13add384f 100644 --- a/AttributesImpl/src/org/gephi/data/attributes/AttributeFactoryImpl.java +++ b/AttributesImpl/src/org/gephi/data/attributes/AttributeFactoryImpl.java @@ -1,67 +1,70 @@ /* Copyright 2008 WebAtlas Authors : Mathieu Bastian, Mathieu Jacomy, Julian Bilcke Website : http://www.gephi.org This file is part of Gephi. Gephi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gephi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Gephi. If not, see <http://www.gnu.org/licenses/>. */ package org.gephi.data.attributes; import org.gephi.data.attributes.api.AttributeColumn; import org.gephi.data.attributes.api.AttributeRowFactory; import org.gephi.data.attributes.api.AttributeValueFactory; import org.gephi.data.attributes.api.AttributeValue; /** * * @author Mathieu Bastian */ public class AttributeFactoryImpl implements AttributeValueFactory, AttributeRowFactory { private AbstractAttributeModel model; public AttributeFactoryImpl(AbstractAttributeModel model) { this.model = model; } public AttributeValue newValue(AttributeColumn column, Object value) { + if (value == null) { + return new AttributeValueImpl((AttributeColumnImpl) column, null); + } if (value.getClass() != column.getType().getType() && value.getClass() == String.class) { value = column.getType().parse((String) value); } Object managedValue = model.getManagedValue(value, column.getType()); return new AttributeValueImpl((AttributeColumnImpl) column, managedValue); } public AttributeRowImpl newNodeRow() { return new AttributeRowImpl(model.getNodeTable()); } public AttributeRowImpl newEdgeRow() { return new AttributeRowImpl(model.getEdgeTable()); } public AttributeRowImpl newRowForTable(String tableName) { AttributeTableImpl attTable = model.getTable(tableName); if (attTable != null) { return new AttributeRowImpl(attTable); } return null; } public void setModel(AbstractAttributeModel model) { this.model = model; } }
true
true
public AttributeValue newValue(AttributeColumn column, Object value) { if (value.getClass() != column.getType().getType() && value.getClass() == String.class) { value = column.getType().parse((String) value); } Object managedValue = model.getManagedValue(value, column.getType()); return new AttributeValueImpl((AttributeColumnImpl) column, managedValue); }
public AttributeValue newValue(AttributeColumn column, Object value) { if (value == null) { return new AttributeValueImpl((AttributeColumnImpl) column, null); } if (value.getClass() != column.getType().getType() && value.getClass() == String.class) { value = column.getType().parse((String) value); } Object managedValue = model.getManagedValue(value, column.getType()); return new AttributeValueImpl((AttributeColumnImpl) column, managedValue); }
diff --git a/jglfw/src/com/badlogic/jglfw/GlfwCallbacks.java b/jglfw/src/com/badlogic/jglfw/GlfwCallbacks.java index 8b2f295..25fdece 100644 --- a/jglfw/src/com/badlogic/jglfw/GlfwCallbacks.java +++ b/jglfw/src/com/badlogic/jglfw/GlfwCallbacks.java @@ -1,87 +1,87 @@ package com.badlogic.jglfw; import java.util.ArrayList; public class GlfwCallbacks implements GlfwCallback { private ArrayList<GlfwCallback> processors = new ArrayList(4); public void add (GlfwCallback callback) { processors.add(callback); } public void remove (GlfwCallback callback) { processors.remove(callback); } public void error (int error, String description) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).error(error, description); } public void monitor (long monitor, boolean connected) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).monitor(monitor, connected); } public void windowPos (long window, int x, int y) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).windowPos(window, x, y); } public void windowSize (long window, int width, int height) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).windowSize(window, width, height); } public boolean windowClose (long window) { for (int i = 0, n = processors.size(); i < n; i++) - if (processors.get(i).windowClose(window)) return true; - return false; + if (!processors.get(i).windowClose(window)) return false; + return true; } public void windowRefresh (long window) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).windowRefresh(window); } public void windowFocus (long window, boolean focused) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).windowFocus(window, focused); } public void windowIconify (long window, boolean iconified) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).windowIconify(window, iconified); } public void key (long window, int key, int action) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).key(window, key, action); } public void character (long window, char character) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).character(window, character); } public void mouseButton (long window, int button, boolean pressed) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).mouseButton(window, button, pressed); } public void cursorPos (long window, int x, int y) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).cursorPos(window, x, y); } public void cursorEnter (long window, boolean entered) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).cursorEnter(window, entered); } public void scroll (long window, double scrollX, double scrollY) { for (int i = 0, n = processors.size(); i < n; i++) processors.get(i).scroll(window, scrollX, scrollY); } }
true
true
public boolean windowClose (long window) { for (int i = 0, n = processors.size(); i < n; i++) if (processors.get(i).windowClose(window)) return true; return false; }
public boolean windowClose (long window) { for (int i = 0, n = processors.size(); i < n; i++) if (!processors.get(i).windowClose(window)) return false; return true; }
diff --git a/org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/RepositoryFilter.java b/org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/RepositoryFilter.java index 14625938..d1bd9024 100644 --- a/org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/RepositoryFilter.java +++ b/org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/RepositoryFilter.java @@ -1,206 +1,206 @@ /* * Copyright (C) 2009-2010, Google Inc. * and other copyright owners as documented in the project's IP log. * * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Eclipse Foundation, Inc. nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.eclipse.jgit.http.server; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static org.eclipse.jgit.http.server.ServletUtils.ATTRIBUTE_REPOSITORY; import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT; import java.io.IOException; import java.text.MessageFormat; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.PacketLineOut; import org.eclipse.jgit.transport.resolver.RepositoryResolver; import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException; import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException; /** * Opens a repository named by the path info through {@link RepositoryResolver}. * <p> * This filter assumes it is invoked by {@link GitServlet} and is likely to not * work as expected if called from any other class. This filter assumes the path * info of the current request is a repository name which can be used by the * configured {@link RepositoryResolver} to open a {@link Repository} and attach * it to the current request. * <p> * This filter sets request attribute {@link ServletUtils#ATTRIBUTE_REPOSITORY} * when it discovers the repository, and automatically closes and removes the * attribute when the request is complete. */ public class RepositoryFilter implements Filter { private final RepositoryResolver<HttpServletRequest> resolver; private ServletContext context; /** * Create a new filter. * * @param resolver * the resolver which will be used to translate the URL name * component to the actual {@link Repository} instance for the * current web request. */ public RepositoryFilter(final RepositoryResolver<HttpServletRequest> resolver) { this.resolver = resolver; } public void init(final FilterConfig config) throws ServletException { context = config.getServletContext(); } public void destroy() { context = null; } public void doFilter(final ServletRequest request, final ServletResponse rsp, final FilterChain chain) throws IOException, ServletException { if (request.getAttribute(ATTRIBUTE_REPOSITORY) != null) { context.log(MessageFormat.format(HttpServerText.get().internalServerErrorRequestAttributeWasAlreadySet , ATTRIBUTE_REPOSITORY , getClass().getName())); ((HttpServletResponse) rsp).sendError(SC_INTERNAL_SERVER_ERROR); return; } final HttpServletRequest req = (HttpServletRequest) request; String name = req.getPathInfo(); + while (name != null && 0 < name.length() && name.charAt(0) == '/') + name = name.substring(1); if (name == null || name.length() == 0) { ((HttpServletResponse) rsp).sendError(SC_NOT_FOUND); return; } - if (name.startsWith("/")) - name = name.substring(1); final Repository db; try { db = resolver.open(req, name); } catch (RepositoryNotFoundException e) { sendError(SC_NOT_FOUND, req, (HttpServletResponse) rsp); return; } catch (ServiceNotEnabledException e) { sendError(SC_FORBIDDEN, req, (HttpServletResponse) rsp); return; } catch (ServiceNotAuthorizedException e) { ((HttpServletResponse) rsp).sendError(SC_UNAUTHORIZED); return; } try { request.setAttribute(ATTRIBUTE_REPOSITORY, db); chain.doFilter(request, rsp); } finally { request.removeAttribute(ATTRIBUTE_REPOSITORY); db.close(); } } static void sendError(int statusCode, HttpServletRequest req, HttpServletResponse rsp) throws IOException { String svc = req.getParameter("service"); if (req.getRequestURI().endsWith("/info/refs") && isService(svc)) { // Smart HTTP service request, use an ERR response. rsp.setContentType("application/x-" + svc + "-advertisement"); SmartOutputStream buf = new SmartOutputStream(req, rsp); PacketLineOut out = new PacketLineOut(buf); out.writeString("# service=" + svc + "\n"); out.end(); out.writeString("ERR " + translate(statusCode)); buf.close(); return; } String accept = req.getHeader(HDR_ACCEPT); if (accept != null && accept.contains(UploadPackServlet.RSP_TYPE)) { // An upload-pack wants ACK or NAK, return ERR // and the client will print this instead. rsp.setContentType(UploadPackServlet.RSP_TYPE); SmartOutputStream buf = new SmartOutputStream(req, rsp); PacketLineOut out = new PacketLineOut(buf); out.writeString("ERR " + translate(statusCode)); buf.close(); return; } // Otherwise fail with an HTTP error code instead of an // application level message. This may not be as pretty // of a result for the user, but its better than nothing. // rsp.sendError(statusCode); } private static boolean isService(String svc) { return "git-upload-pack".equals(svc) || "git-receive-pack".equals(svc); } private static String translate(int statusCode) { switch (statusCode) { case SC_NOT_FOUND: return HttpServerText.get().repositoryNotFound; case SC_FORBIDDEN: return HttpServerText.get().repositoryAccessForbidden; default: return String.valueOf(statusCode); } } }
false
true
public void doFilter(final ServletRequest request, final ServletResponse rsp, final FilterChain chain) throws IOException, ServletException { if (request.getAttribute(ATTRIBUTE_REPOSITORY) != null) { context.log(MessageFormat.format(HttpServerText.get().internalServerErrorRequestAttributeWasAlreadySet , ATTRIBUTE_REPOSITORY , getClass().getName())); ((HttpServletResponse) rsp).sendError(SC_INTERNAL_SERVER_ERROR); return; } final HttpServletRequest req = (HttpServletRequest) request; String name = req.getPathInfo(); if (name == null || name.length() == 0) { ((HttpServletResponse) rsp).sendError(SC_NOT_FOUND); return; } if (name.startsWith("/")) name = name.substring(1); final Repository db; try { db = resolver.open(req, name); } catch (RepositoryNotFoundException e) { sendError(SC_NOT_FOUND, req, (HttpServletResponse) rsp); return; } catch (ServiceNotEnabledException e) { sendError(SC_FORBIDDEN, req, (HttpServletResponse) rsp); return; } catch (ServiceNotAuthorizedException e) { ((HttpServletResponse) rsp).sendError(SC_UNAUTHORIZED); return; } try { request.setAttribute(ATTRIBUTE_REPOSITORY, db); chain.doFilter(request, rsp); } finally { request.removeAttribute(ATTRIBUTE_REPOSITORY); db.close(); } }
public void doFilter(final ServletRequest request, final ServletResponse rsp, final FilterChain chain) throws IOException, ServletException { if (request.getAttribute(ATTRIBUTE_REPOSITORY) != null) { context.log(MessageFormat.format(HttpServerText.get().internalServerErrorRequestAttributeWasAlreadySet , ATTRIBUTE_REPOSITORY , getClass().getName())); ((HttpServletResponse) rsp).sendError(SC_INTERNAL_SERVER_ERROR); return; } final HttpServletRequest req = (HttpServletRequest) request; String name = req.getPathInfo(); while (name != null && 0 < name.length() && name.charAt(0) == '/') name = name.substring(1); if (name == null || name.length() == 0) { ((HttpServletResponse) rsp).sendError(SC_NOT_FOUND); return; } final Repository db; try { db = resolver.open(req, name); } catch (RepositoryNotFoundException e) { sendError(SC_NOT_FOUND, req, (HttpServletResponse) rsp); return; } catch (ServiceNotEnabledException e) { sendError(SC_FORBIDDEN, req, (HttpServletResponse) rsp); return; } catch (ServiceNotAuthorizedException e) { ((HttpServletResponse) rsp).sendError(SC_UNAUTHORIZED); return; } try { request.setAttribute(ATTRIBUTE_REPOSITORY, db); chain.doFilter(request, rsp); } finally { request.removeAttribute(ATTRIBUTE_REPOSITORY); db.close(); } }
diff --git a/tool/src/java/org/sakaiproject/profile2/tool/pages/ViewProfile.java b/tool/src/java/org/sakaiproject/profile2/tool/pages/ViewProfile.java index 9fae0847..502d07a8 100644 --- a/tool/src/java/org/sakaiproject/profile2/tool/pages/ViewProfile.java +++ b/tool/src/java/org/sakaiproject/profile2/tool/pages/ViewProfile.java @@ -1,621 +1,621 @@ /** * Copyright (c) 2008-2010 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sakaiproject.profile2.tool.pages; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Date; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.PageParameters; import org.apache.wicket.RestartResponseException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.EmptyPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.model.StringResourceModel; import org.sakaiproject.api.common.edu.person.SakaiPerson; import org.sakaiproject.profile2.exception.ProfilePrototypeNotDefinedException; import org.sakaiproject.profile2.model.ProfilePrivacy; import org.sakaiproject.profile2.tool.components.ProfileImageRenderer; import org.sakaiproject.profile2.tool.components.ProfileStatusRenderer; import org.sakaiproject.profile2.tool.models.FriendAction; import org.sakaiproject.profile2.tool.pages.panels.FriendsFeed; import org.sakaiproject.profile2.tool.pages.panels.GalleryFeed; import org.sakaiproject.profile2.tool.pages.windows.AddFriend; import org.sakaiproject.profile2.util.ProfileConstants; import org.sakaiproject.profile2.util.ProfileUtils; import org.sakaiproject.user.api.User; public class ViewProfile extends BasePage { private static final Logger log = Logger.getLogger(ViewProfile.class); public ViewProfile(final String userUuid) { log.debug("ViewProfile()"); //setup model to store the actions in the modal windows final FriendAction friendActionModel = new FriendAction(); //get current user info User currentUser = sakaiProxy.getUserQuietly(sakaiProxy.getCurrentUserId()); final String currentUserId = currentUser.getId(); String currentUserType = currentUser.getType(); //double check, if somehow got to own ViewPage, redirect to MyProfile instead if(userUuid.equals(currentUserId)) { log.warn("ViewProfile: user " + userUuid + " accessed ViewProfile for self. Redirecting..."); throw new RestartResponseException(new MyProfile()); } //check if super user, to grant editing rights to another user's profile if(sakaiProxy.isSuperUser()) { log.warn("ViewProfile: superUser " + currentUserId + " accessed ViewProfile for " + userUuid + ". Redirecting to allow edit."); throw new RestartResponseException(new MyProfile(userUuid)); } //post view event sakaiProxy.postEvent(ProfileConstants.EVENT_PROFILE_VIEW_OTHER, "/profile/"+userUuid, false); /* DEPRECATED via PRFL-24 when privacy was relaxed if(!isProfileAllowed) { throw new ProfileIllegalAccessException("User: " + currentUserId + " is not allowed to view profile for: " + userUuid); } */ //holds number of profile containers that are visible int visibleContainerCount = 0; //get SakaiPerson for the person who's profile we are viewing SakaiPerson sakaiPerson = sakaiProxy.getSakaiPerson(userUuid); //if null, they have no profile so just get a prototype if(sakaiPerson == null) { log.info("No SakaiPerson for " + userUuid); sakaiPerson = sakaiProxy.getSakaiPersonPrototype(); //if its still null, throw exception if(sakaiPerson == null) { throw new ProfilePrototypeNotDefinedException("Couldn't create a SakaiPerson prototype for " + userUuid); } } //get some values from SakaiPerson or SakaiProxy if empty //SakaiPerson returns NULL strings if value is not set, not blank ones User user = sakaiProxy.getUserQuietly(userUuid); String userDisplayName = user.getDisplayName(); String userType = user.getType(); //init boolean friend = false; boolean friendRequestToThisPerson = false; boolean friendRequestFromThisPerson = false; //friend? friend = profileLogic.isUserXFriendOfUserY(userUuid, currentUserId); //if not friend, has a friend request already been made to this person? if(!friend) { friendRequestToThisPerson = profileLogic.isFriendRequestPending(currentUserId, userUuid); } //if not friend and no friend request to this person, has a friend request been made from this person to the current user? if(!friend && !friendRequestToThisPerson) { friendRequestFromThisPerson = profileLogic.isFriendRequestPending(userUuid, currentUserId); } //privacy checks ProfilePrivacy privacy = profileLogic.getPrivacyRecordForUser(userUuid); boolean isProfileImageAllowed = profileLogic.isUserXProfileImageVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isBasicInfoAllowed = profileLogic.isUserXBasicInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isContactInfoAllowed = profileLogic.isUserXContactInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isAcademicInfoAllowed = profileLogic.isUserXAcademicInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isPersonalInfoAllowed = profileLogic.isUserXPersonalInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isFriendsListVisible = profileLogic.isUserXFriendsListVisibleByUserY(userUuid, privacy, currentUserId, friend); final boolean isGalleryVisible = profileLogic.isUserXGalleryVisibleByUser(userUuid, privacy, currentUserId, friend); boolean isConnectionAllowed = sakaiProxy.isConnectionAllowedBetweenUserTypes(currentUserType, userType); /* IMAGE */ add(new ProfileImageRenderer("photo", userUuid, isProfileImageAllowed, ProfileConstants.PROFILE_IMAGE_MAIN, true)); /* NAME */ Label profileName = new Label("profileName", userDisplayName); add(profileName); /*STATUS PANEL */ ProfileStatusRenderer status = new ProfileStatusRenderer("status", userUuid, privacy, currentUserId, friend, null, "tiny"); status.setOutputMarkupId(true); add(status); /* BASIC INFO */ WebMarkupContainer basicInfoContainer = new WebMarkupContainer("mainSectionContainer_basic"); basicInfoContainer.setOutputMarkupId(true); //get info String nickname = sakaiPerson.getNickname(); Date dateOfBirth = sakaiPerson.getDateOfBirth(); String birthday = ""; int visibleFieldCount_basic = 0; if(dateOfBirth != null) { if(profileLogic.isBirthYearVisible(userUuid)) { birthday = ProfileUtils.convertDateToString(dateOfBirth, ProfileConstants.DEFAULT_DATE_FORMAT); } else { birthday = ProfileUtils.convertDateToString(dateOfBirth, ProfileConstants.DEFAULT_DATE_FORMAT_HIDE_YEAR); } } //heading basicInfoContainer.add(new Label("mainSectionHeading_basic", new ResourceModel("heading.basic"))); //nickname WebMarkupContainer nicknameContainer = new WebMarkupContainer("nicknameContainer"); nicknameContainer.add(new Label("nicknameLabel", new ResourceModel("profile.nickname"))); nicknameContainer.add(new Label("nickname", nickname)); basicInfoContainer.add(nicknameContainer); if(StringUtils.isBlank(nickname)) { nickname=""; //for the 'add friend' link nicknameContainer.setVisible(false); } else { visibleFieldCount_basic++; } //birthday WebMarkupContainer birthdayContainer = new WebMarkupContainer("birthdayContainer"); birthdayContainer.add(new Label("birthdayLabel", new ResourceModel("profile.birthday"))); birthdayContainer.add(new Label("birthday", birthday)); basicInfoContainer.add(birthdayContainer); if(StringUtils.isBlank(birthday)) { birthdayContainer.setVisible(false); } else { visibleFieldCount_basic++; } add(basicInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_basic == 0 || !isBasicInfoAllowed) { basicInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* CONTACT INFO */ WebMarkupContainer contactInfoContainer = new WebMarkupContainer("mainSectionContainer_contact"); contactInfoContainer.setOutputMarkupId(true); //get info String email = sakaiProxy.getUserEmail(userUuid); //must come from SakaiProxy String homepage = sakaiPerson.getLabeledURI(); String workphone = sakaiPerson.getTelephoneNumber(); String homephone = sakaiPerson.getHomePhone(); String mobilephone = sakaiPerson.getMobile(); String facsimile = sakaiPerson.getFacsimileTelephoneNumber(); int visibleFieldCount_contact = 0; //heading contactInfoContainer.add(new Label("mainSectionHeading_contact", new ResourceModel("heading.contact"))); //email WebMarkupContainer emailContainer = new WebMarkupContainer("emailContainer"); emailContainer.add(new Label("emailLabel", new ResourceModel("profile.email"))); emailContainer.add(new Label("email", email)); contactInfoContainer.add(emailContainer); if(StringUtils.isBlank(email)) { emailContainer.setVisible(false); } else { visibleFieldCount_contact++; } //homepage WebMarkupContainer homepageContainer = new WebMarkupContainer("homepageContainer"); homepageContainer.add(new Label("homepageLabel", new ResourceModel("profile.homepage"))); homepageContainer.add(new Label("homepage", homepage)); contactInfoContainer.add(homepageContainer); if(StringUtils.isBlank(homepage)) { homepageContainer.setVisible(false); } else { visibleFieldCount_contact++; } //work phone WebMarkupContainer workphoneContainer = new WebMarkupContainer("workphoneContainer"); workphoneContainer.add(new Label("workphoneLabel", new ResourceModel("profile.phone.work"))); workphoneContainer.add(new Label("workphone", workphone)); contactInfoContainer.add(workphoneContainer); if(StringUtils.isBlank(workphone)) { workphoneContainer.setVisible(false); } else { visibleFieldCount_contact++; } //home phone WebMarkupContainer homephoneContainer = new WebMarkupContainer("homephoneContainer"); homephoneContainer.add(new Label("homephoneLabel", new ResourceModel("profile.phone.home"))); homephoneContainer.add(new Label("homephone", homephone)); contactInfoContainer.add(homephoneContainer); if(StringUtils.isBlank(homephone)) { homephoneContainer.setVisible(false); } else { visibleFieldCount_contact++; } //mobile phone WebMarkupContainer mobilephoneContainer = new WebMarkupContainer("mobilephoneContainer"); mobilephoneContainer.add(new Label("mobilephoneLabel", new ResourceModel("profile.phone.mobile"))); mobilephoneContainer.add(new Label("mobilephone", mobilephone)); contactInfoContainer.add(mobilephoneContainer); if(StringUtils.isBlank(mobilephone)) { mobilephoneContainer.setVisible(false); } else { visibleFieldCount_contact++; } //facsimile WebMarkupContainer facsimileContainer = new WebMarkupContainer("facsimileContainer"); facsimileContainer.add(new Label("facsimileLabel", new ResourceModel("profile.phone.facsimile"))); facsimileContainer.add(new Label("facsimile", facsimile)); contactInfoContainer.add(facsimileContainer); if(StringUtils.isBlank(facsimile)) { facsimileContainer.setVisible(false); } else { visibleFieldCount_contact++; } add(contactInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_contact == 0 || !isContactInfoAllowed) { contactInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* ACADEMIC INFO */ WebMarkupContainer academicInfoContainer = new WebMarkupContainer("mainSectionContainer_academic"); academicInfoContainer.setOutputMarkupId(true); //get info String department = sakaiPerson.getOrganizationalUnit(); String position = sakaiPerson.getTitle(); String school = sakaiPerson.getCampus(); String room = sakaiPerson.getRoomNumber(); String course = sakaiPerson.getEducationCourse(); String subjects = sakaiPerson.getEducationSubjects(); int visibleFieldCount_academic = 0; //heading academicInfoContainer.add(new Label("mainSectionHeading_academic", new ResourceModel("heading.academic"))); //department WebMarkupContainer departmentContainer = new WebMarkupContainer("departmentContainer"); departmentContainer.add(new Label("departmentLabel", new ResourceModel("profile.department"))); departmentContainer.add(new Label("department", department)); academicInfoContainer.add(departmentContainer); if(StringUtils.isBlank(department)) { departmentContainer.setVisible(false); } else { visibleFieldCount_academic++; } //position WebMarkupContainer positionContainer = new WebMarkupContainer("positionContainer"); positionContainer.add(new Label("positionLabel", new ResourceModel("profile.position"))); positionContainer.add(new Label("position", position)); academicInfoContainer.add(positionContainer); if(StringUtils.isBlank(position)) { positionContainer.setVisible(false); } else { visibleFieldCount_academic++; } //school WebMarkupContainer schoolContainer = new WebMarkupContainer("schoolContainer"); schoolContainer.add(new Label("schoolLabel", new ResourceModel("profile.school"))); schoolContainer.add(new Label("school", school)); academicInfoContainer.add(schoolContainer); if(StringUtils.isBlank(school)) { schoolContainer.setVisible(false); } else { visibleFieldCount_academic++; } //room WebMarkupContainer roomContainer = new WebMarkupContainer("roomContainer"); roomContainer.add(new Label("roomLabel", new ResourceModel("profile.room"))); roomContainer.add(new Label("room", room)); academicInfoContainer.add(roomContainer); if(StringUtils.isBlank(room)) { roomContainer.setVisible(false); } else { visibleFieldCount_academic++; } //course WebMarkupContainer courseContainer = new WebMarkupContainer("courseContainer"); courseContainer.add(new Label("courseLabel", new ResourceModel("profile.course"))); courseContainer.add(new Label("course", course)); academicInfoContainer.add(courseContainer); if(StringUtils.isBlank(course)) { courseContainer.setVisible(false); } else { visibleFieldCount_academic++; } //subjects WebMarkupContainer subjectsContainer = new WebMarkupContainer("subjectsContainer"); subjectsContainer.add(new Label("subjectsLabel", new ResourceModel("profile.subjects"))); subjectsContainer.add(new Label("subjects", subjects)); academicInfoContainer.add(subjectsContainer); if(StringUtils.isBlank(subjects)) { subjectsContainer.setVisible(false); } else { visibleFieldCount_academic++; } add(academicInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_academic == 0 || !isAcademicInfoAllowed) { academicInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* PERSONAL INFO */ WebMarkupContainer personalInfoContainer = new WebMarkupContainer("mainSectionContainer_personal"); personalInfoContainer.setOutputMarkupId(true); //setup info String favouriteBooks = sakaiPerson.getFavouriteBooks(); String favouriteTvShows = sakaiPerson.getFavouriteTvShows(); String favouriteMovies = sakaiPerson.getFavouriteMovies(); String favouriteQuotes = sakaiPerson.getFavouriteQuotes(); String otherInformation = sakaiPerson.getNotes(); int visibleFieldCount_personal = 0; //heading personalInfoContainer.add(new Label("mainSectionHeading_personal", new ResourceModel("heading.interests"))); //favourite books WebMarkupContainer booksContainer = new WebMarkupContainer("booksContainer"); booksContainer.add(new Label("booksLabel", new ResourceModel("profile.favourite.books"))); booksContainer.add(new Label("favouriteBooks", favouriteBooks)); personalInfoContainer.add(booksContainer); if(StringUtils.isBlank(favouriteBooks)) { booksContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite tv shows WebMarkupContainer tvContainer = new WebMarkupContainer("tvContainer"); tvContainer.add(new Label("tvLabel", new ResourceModel("profile.favourite.tv"))); tvContainer.add(new Label("favouriteTvShows", favouriteTvShows)); personalInfoContainer.add(tvContainer); if(StringUtils.isBlank(favouriteTvShows)) { tvContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite movies WebMarkupContainer moviesContainer = new WebMarkupContainer("moviesContainer"); moviesContainer.add(new Label("moviesLabel", new ResourceModel("profile.favourite.movies"))); moviesContainer.add(new Label("favouriteMovies", favouriteMovies)); personalInfoContainer.add(moviesContainer); if(StringUtils.isBlank(favouriteMovies)) { moviesContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite quotes WebMarkupContainer quotesContainer = new WebMarkupContainer("quotesContainer"); quotesContainer.add(new Label("quotesLabel", new ResourceModel("profile.favourite.quotes"))); quotesContainer.add(new Label("favouriteQuotes", favouriteQuotes)); personalInfoContainer.add(quotesContainer); if(StringUtils.isBlank(favouriteQuotes)) { quotesContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite quotes WebMarkupContainer otherContainer = new WebMarkupContainer("otherContainer"); otherContainer.add(new Label("otherLabel", new ResourceModel("profile.other"))); - otherContainer.add(new Label("otherInformation", otherInformation)); + otherContainer.add(new Label("otherInformation", ProfileUtils.escapeHtmlForDisplay(otherInformation)).setEscapeModelStrings(false)); personalInfoContainer.add(otherContainer); if(StringUtils.isBlank(otherInformation)) { otherContainer.setVisible(false); } else { visibleFieldCount_personal++; } add(personalInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_personal == 0 || !isPersonalInfoAllowed) { personalInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* NO INFO VISIBLE MESSAGE (hide if some visible) */ Label noContainersVisible = new Label ("noContainersVisible", new ResourceModel("text.view.profile.nothing")); noContainersVisible.setOutputMarkupId(true); add(noContainersVisible); if(visibleContainerCount > 0) { noContainersVisible.setVisible(false); } /* SIDELINKS */ WebMarkupContainer sideLinks = new WebMarkupContainer("sideLinks"); int visibleSideLinksCount = 0; WebMarkupContainer addFriendContainer = new WebMarkupContainer("addFriendContainer"); //ADD FRIEND MODAL WINDOW final ModalWindow addFriendWindow = new ModalWindow("addFriendWindow"); //FRIEND LINK/STATUS final AjaxLink<Void> addFriendLink = new AjaxLink<Void>("addFriendLink") { private static final long serialVersionUID = 1L; public void onClick(AjaxRequestTarget target) { addFriendWindow.show(target); } }; final Label addFriendLabel = new Label("addFriendLabel"); addFriendLink.add(addFriendLabel); addFriendContainer.add(addFriendLink); //setup link/label and windows if(friend) { addFriendLabel.setDefaultModel(new ResourceModel("text.friend.confirmed")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); } else if (friendRequestToThisPerson) { addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); } else if (friendRequestFromThisPerson) { //TODO (confirm pending friend request link) //could be done by setting the content off the addFriendWindow. //will need to rename some links to make more generic and set the onClick and setContent in here for link and window addFriendLabel.setDefaultModel(new ResourceModel("text.friend.pending")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); } else { addFriendLabel.setDefaultModel(new StringResourceModel("link.friend.add.name", null, new Object[]{ nickname } )); addFriendWindow.setContent(new AddFriend(addFriendWindow.getContentId(), addFriendWindow, friendActionModel, currentUserId, userUuid)); } sideLinks.add(addFriendContainer); //ADD FRIEND MODAL WINDOW HANDLER addFriendWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { private static final long serialVersionUID = 1L; public void onClose(AjaxRequestTarget target){ if(friendActionModel.isRequested()) { //friend was successfully requested, update label and link addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); target.addComponent(addFriendLink); } } }); add(addFriendWindow); //hide connection link if not allowed if(!isConnectionAllowed) { addFriendContainer.setVisible(false); } else { visibleSideLinksCount++; } //hide entire list if no links to show if(visibleSideLinksCount == 0) { sideLinks.setVisible(false); } add(sideLinks); /* FRIENDS FEED PANEL */ if(isFriendsListVisible) { add(new AjaxLazyLoadPanel("friendsFeed") { private static final long serialVersionUID = 1L; @Override public Component getLazyLoadComponent(String id) { return new FriendsFeed(id, userUuid, currentUserId); } }); } else { add(new EmptyPanel("friendsFeed")).setVisible(false); } /* GALLERY FEED PANEL */ add(new AjaxLazyLoadPanel("galleryFeed") { private static final long serialVersionUID = 1L; @Override public Component getLazyLoadComponent(String markupId) { if (sakaiProxy.isProfileGalleryEnabledGlobally() && isGalleryVisible) { return new GalleryFeed(markupId, userUuid, currentUserId) .setOutputMarkupId(true); } else { return new EmptyPanel(markupId).setVisible(false); } } }); } /** * This constructor is called if we have a pageParameters object containing the userUuid as an id parameter * Just redirects to normal ViewProfile(String userUuid) * @param parameters */ public ViewProfile(PageParameters parameters) { this(parameters.getString("id")); } /* reinit for deserialisation (ie back button) */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); log.debug("ViewProfile has been deserialized."); //re-init our transient objects profileLogic = getProfileLogic(); sakaiProxy = getSakaiProxy(); } }
true
true
public ViewProfile(final String userUuid) { log.debug("ViewProfile()"); //setup model to store the actions in the modal windows final FriendAction friendActionModel = new FriendAction(); //get current user info User currentUser = sakaiProxy.getUserQuietly(sakaiProxy.getCurrentUserId()); final String currentUserId = currentUser.getId(); String currentUserType = currentUser.getType(); //double check, if somehow got to own ViewPage, redirect to MyProfile instead if(userUuid.equals(currentUserId)) { log.warn("ViewProfile: user " + userUuid + " accessed ViewProfile for self. Redirecting..."); throw new RestartResponseException(new MyProfile()); } //check if super user, to grant editing rights to another user's profile if(sakaiProxy.isSuperUser()) { log.warn("ViewProfile: superUser " + currentUserId + " accessed ViewProfile for " + userUuid + ". Redirecting to allow edit."); throw new RestartResponseException(new MyProfile(userUuid)); } //post view event sakaiProxy.postEvent(ProfileConstants.EVENT_PROFILE_VIEW_OTHER, "/profile/"+userUuid, false); /* DEPRECATED via PRFL-24 when privacy was relaxed if(!isProfileAllowed) { throw new ProfileIllegalAccessException("User: " + currentUserId + " is not allowed to view profile for: " + userUuid); } */ //holds number of profile containers that are visible int visibleContainerCount = 0; //get SakaiPerson for the person who's profile we are viewing SakaiPerson sakaiPerson = sakaiProxy.getSakaiPerson(userUuid); //if null, they have no profile so just get a prototype if(sakaiPerson == null) { log.info("No SakaiPerson for " + userUuid); sakaiPerson = sakaiProxy.getSakaiPersonPrototype(); //if its still null, throw exception if(sakaiPerson == null) { throw new ProfilePrototypeNotDefinedException("Couldn't create a SakaiPerson prototype for " + userUuid); } } //get some values from SakaiPerson or SakaiProxy if empty //SakaiPerson returns NULL strings if value is not set, not blank ones User user = sakaiProxy.getUserQuietly(userUuid); String userDisplayName = user.getDisplayName(); String userType = user.getType(); //init boolean friend = false; boolean friendRequestToThisPerson = false; boolean friendRequestFromThisPerson = false; //friend? friend = profileLogic.isUserXFriendOfUserY(userUuid, currentUserId); //if not friend, has a friend request already been made to this person? if(!friend) { friendRequestToThisPerson = profileLogic.isFriendRequestPending(currentUserId, userUuid); } //if not friend and no friend request to this person, has a friend request been made from this person to the current user? if(!friend && !friendRequestToThisPerson) { friendRequestFromThisPerson = profileLogic.isFriendRequestPending(userUuid, currentUserId); } //privacy checks ProfilePrivacy privacy = profileLogic.getPrivacyRecordForUser(userUuid); boolean isProfileImageAllowed = profileLogic.isUserXProfileImageVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isBasicInfoAllowed = profileLogic.isUserXBasicInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isContactInfoAllowed = profileLogic.isUserXContactInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isAcademicInfoAllowed = profileLogic.isUserXAcademicInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isPersonalInfoAllowed = profileLogic.isUserXPersonalInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isFriendsListVisible = profileLogic.isUserXFriendsListVisibleByUserY(userUuid, privacy, currentUserId, friend); final boolean isGalleryVisible = profileLogic.isUserXGalleryVisibleByUser(userUuid, privacy, currentUserId, friend); boolean isConnectionAllowed = sakaiProxy.isConnectionAllowedBetweenUserTypes(currentUserType, userType); /* IMAGE */ add(new ProfileImageRenderer("photo", userUuid, isProfileImageAllowed, ProfileConstants.PROFILE_IMAGE_MAIN, true)); /* NAME */ Label profileName = new Label("profileName", userDisplayName); add(profileName); /*STATUS PANEL */ ProfileStatusRenderer status = new ProfileStatusRenderer("status", userUuid, privacy, currentUserId, friend, null, "tiny"); status.setOutputMarkupId(true); add(status); /* BASIC INFO */ WebMarkupContainer basicInfoContainer = new WebMarkupContainer("mainSectionContainer_basic"); basicInfoContainer.setOutputMarkupId(true); //get info String nickname = sakaiPerson.getNickname(); Date dateOfBirth = sakaiPerson.getDateOfBirth(); String birthday = ""; int visibleFieldCount_basic = 0; if(dateOfBirth != null) { if(profileLogic.isBirthYearVisible(userUuid)) { birthday = ProfileUtils.convertDateToString(dateOfBirth, ProfileConstants.DEFAULT_DATE_FORMAT); } else { birthday = ProfileUtils.convertDateToString(dateOfBirth, ProfileConstants.DEFAULT_DATE_FORMAT_HIDE_YEAR); } } //heading basicInfoContainer.add(new Label("mainSectionHeading_basic", new ResourceModel("heading.basic"))); //nickname WebMarkupContainer nicknameContainer = new WebMarkupContainer("nicknameContainer"); nicknameContainer.add(new Label("nicknameLabel", new ResourceModel("profile.nickname"))); nicknameContainer.add(new Label("nickname", nickname)); basicInfoContainer.add(nicknameContainer); if(StringUtils.isBlank(nickname)) { nickname=""; //for the 'add friend' link nicknameContainer.setVisible(false); } else { visibleFieldCount_basic++; } //birthday WebMarkupContainer birthdayContainer = new WebMarkupContainer("birthdayContainer"); birthdayContainer.add(new Label("birthdayLabel", new ResourceModel("profile.birthday"))); birthdayContainer.add(new Label("birthday", birthday)); basicInfoContainer.add(birthdayContainer); if(StringUtils.isBlank(birthday)) { birthdayContainer.setVisible(false); } else { visibleFieldCount_basic++; } add(basicInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_basic == 0 || !isBasicInfoAllowed) { basicInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* CONTACT INFO */ WebMarkupContainer contactInfoContainer = new WebMarkupContainer("mainSectionContainer_contact"); contactInfoContainer.setOutputMarkupId(true); //get info String email = sakaiProxy.getUserEmail(userUuid); //must come from SakaiProxy String homepage = sakaiPerson.getLabeledURI(); String workphone = sakaiPerson.getTelephoneNumber(); String homephone = sakaiPerson.getHomePhone(); String mobilephone = sakaiPerson.getMobile(); String facsimile = sakaiPerson.getFacsimileTelephoneNumber(); int visibleFieldCount_contact = 0; //heading contactInfoContainer.add(new Label("mainSectionHeading_contact", new ResourceModel("heading.contact"))); //email WebMarkupContainer emailContainer = new WebMarkupContainer("emailContainer"); emailContainer.add(new Label("emailLabel", new ResourceModel("profile.email"))); emailContainer.add(new Label("email", email)); contactInfoContainer.add(emailContainer); if(StringUtils.isBlank(email)) { emailContainer.setVisible(false); } else { visibleFieldCount_contact++; } //homepage WebMarkupContainer homepageContainer = new WebMarkupContainer("homepageContainer"); homepageContainer.add(new Label("homepageLabel", new ResourceModel("profile.homepage"))); homepageContainer.add(new Label("homepage", homepage)); contactInfoContainer.add(homepageContainer); if(StringUtils.isBlank(homepage)) { homepageContainer.setVisible(false); } else { visibleFieldCount_contact++; } //work phone WebMarkupContainer workphoneContainer = new WebMarkupContainer("workphoneContainer"); workphoneContainer.add(new Label("workphoneLabel", new ResourceModel("profile.phone.work"))); workphoneContainer.add(new Label("workphone", workphone)); contactInfoContainer.add(workphoneContainer); if(StringUtils.isBlank(workphone)) { workphoneContainer.setVisible(false); } else { visibleFieldCount_contact++; } //home phone WebMarkupContainer homephoneContainer = new WebMarkupContainer("homephoneContainer"); homephoneContainer.add(new Label("homephoneLabel", new ResourceModel("profile.phone.home"))); homephoneContainer.add(new Label("homephone", homephone)); contactInfoContainer.add(homephoneContainer); if(StringUtils.isBlank(homephone)) { homephoneContainer.setVisible(false); } else { visibleFieldCount_contact++; } //mobile phone WebMarkupContainer mobilephoneContainer = new WebMarkupContainer("mobilephoneContainer"); mobilephoneContainer.add(new Label("mobilephoneLabel", new ResourceModel("profile.phone.mobile"))); mobilephoneContainer.add(new Label("mobilephone", mobilephone)); contactInfoContainer.add(mobilephoneContainer); if(StringUtils.isBlank(mobilephone)) { mobilephoneContainer.setVisible(false); } else { visibleFieldCount_contact++; } //facsimile WebMarkupContainer facsimileContainer = new WebMarkupContainer("facsimileContainer"); facsimileContainer.add(new Label("facsimileLabel", new ResourceModel("profile.phone.facsimile"))); facsimileContainer.add(new Label("facsimile", facsimile)); contactInfoContainer.add(facsimileContainer); if(StringUtils.isBlank(facsimile)) { facsimileContainer.setVisible(false); } else { visibleFieldCount_contact++; } add(contactInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_contact == 0 || !isContactInfoAllowed) { contactInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* ACADEMIC INFO */ WebMarkupContainer academicInfoContainer = new WebMarkupContainer("mainSectionContainer_academic"); academicInfoContainer.setOutputMarkupId(true); //get info String department = sakaiPerson.getOrganizationalUnit(); String position = sakaiPerson.getTitle(); String school = sakaiPerson.getCampus(); String room = sakaiPerson.getRoomNumber(); String course = sakaiPerson.getEducationCourse(); String subjects = sakaiPerson.getEducationSubjects(); int visibleFieldCount_academic = 0; //heading academicInfoContainer.add(new Label("mainSectionHeading_academic", new ResourceModel("heading.academic"))); //department WebMarkupContainer departmentContainer = new WebMarkupContainer("departmentContainer"); departmentContainer.add(new Label("departmentLabel", new ResourceModel("profile.department"))); departmentContainer.add(new Label("department", department)); academicInfoContainer.add(departmentContainer); if(StringUtils.isBlank(department)) { departmentContainer.setVisible(false); } else { visibleFieldCount_academic++; } //position WebMarkupContainer positionContainer = new WebMarkupContainer("positionContainer"); positionContainer.add(new Label("positionLabel", new ResourceModel("profile.position"))); positionContainer.add(new Label("position", position)); academicInfoContainer.add(positionContainer); if(StringUtils.isBlank(position)) { positionContainer.setVisible(false); } else { visibleFieldCount_academic++; } //school WebMarkupContainer schoolContainer = new WebMarkupContainer("schoolContainer"); schoolContainer.add(new Label("schoolLabel", new ResourceModel("profile.school"))); schoolContainer.add(new Label("school", school)); academicInfoContainer.add(schoolContainer); if(StringUtils.isBlank(school)) { schoolContainer.setVisible(false); } else { visibleFieldCount_academic++; } //room WebMarkupContainer roomContainer = new WebMarkupContainer("roomContainer"); roomContainer.add(new Label("roomLabel", new ResourceModel("profile.room"))); roomContainer.add(new Label("room", room)); academicInfoContainer.add(roomContainer); if(StringUtils.isBlank(room)) { roomContainer.setVisible(false); } else { visibleFieldCount_academic++; } //course WebMarkupContainer courseContainer = new WebMarkupContainer("courseContainer"); courseContainer.add(new Label("courseLabel", new ResourceModel("profile.course"))); courseContainer.add(new Label("course", course)); academicInfoContainer.add(courseContainer); if(StringUtils.isBlank(course)) { courseContainer.setVisible(false); } else { visibleFieldCount_academic++; } //subjects WebMarkupContainer subjectsContainer = new WebMarkupContainer("subjectsContainer"); subjectsContainer.add(new Label("subjectsLabel", new ResourceModel("profile.subjects"))); subjectsContainer.add(new Label("subjects", subjects)); academicInfoContainer.add(subjectsContainer); if(StringUtils.isBlank(subjects)) { subjectsContainer.setVisible(false); } else { visibleFieldCount_academic++; } add(academicInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_academic == 0 || !isAcademicInfoAllowed) { academicInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* PERSONAL INFO */ WebMarkupContainer personalInfoContainer = new WebMarkupContainer("mainSectionContainer_personal"); personalInfoContainer.setOutputMarkupId(true); //setup info String favouriteBooks = sakaiPerson.getFavouriteBooks(); String favouriteTvShows = sakaiPerson.getFavouriteTvShows(); String favouriteMovies = sakaiPerson.getFavouriteMovies(); String favouriteQuotes = sakaiPerson.getFavouriteQuotes(); String otherInformation = sakaiPerson.getNotes(); int visibleFieldCount_personal = 0; //heading personalInfoContainer.add(new Label("mainSectionHeading_personal", new ResourceModel("heading.interests"))); //favourite books WebMarkupContainer booksContainer = new WebMarkupContainer("booksContainer"); booksContainer.add(new Label("booksLabel", new ResourceModel("profile.favourite.books"))); booksContainer.add(new Label("favouriteBooks", favouriteBooks)); personalInfoContainer.add(booksContainer); if(StringUtils.isBlank(favouriteBooks)) { booksContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite tv shows WebMarkupContainer tvContainer = new WebMarkupContainer("tvContainer"); tvContainer.add(new Label("tvLabel", new ResourceModel("profile.favourite.tv"))); tvContainer.add(new Label("favouriteTvShows", favouriteTvShows)); personalInfoContainer.add(tvContainer); if(StringUtils.isBlank(favouriteTvShows)) { tvContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite movies WebMarkupContainer moviesContainer = new WebMarkupContainer("moviesContainer"); moviesContainer.add(new Label("moviesLabel", new ResourceModel("profile.favourite.movies"))); moviesContainer.add(new Label("favouriteMovies", favouriteMovies)); personalInfoContainer.add(moviesContainer); if(StringUtils.isBlank(favouriteMovies)) { moviesContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite quotes WebMarkupContainer quotesContainer = new WebMarkupContainer("quotesContainer"); quotesContainer.add(new Label("quotesLabel", new ResourceModel("profile.favourite.quotes"))); quotesContainer.add(new Label("favouriteQuotes", favouriteQuotes)); personalInfoContainer.add(quotesContainer); if(StringUtils.isBlank(favouriteQuotes)) { quotesContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite quotes WebMarkupContainer otherContainer = new WebMarkupContainer("otherContainer"); otherContainer.add(new Label("otherLabel", new ResourceModel("profile.other"))); otherContainer.add(new Label("otherInformation", otherInformation)); personalInfoContainer.add(otherContainer); if(StringUtils.isBlank(otherInformation)) { otherContainer.setVisible(false); } else { visibleFieldCount_personal++; } add(personalInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_personal == 0 || !isPersonalInfoAllowed) { personalInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* NO INFO VISIBLE MESSAGE (hide if some visible) */ Label noContainersVisible = new Label ("noContainersVisible", new ResourceModel("text.view.profile.nothing")); noContainersVisible.setOutputMarkupId(true); add(noContainersVisible); if(visibleContainerCount > 0) { noContainersVisible.setVisible(false); } /* SIDELINKS */ WebMarkupContainer sideLinks = new WebMarkupContainer("sideLinks"); int visibleSideLinksCount = 0; WebMarkupContainer addFriendContainer = new WebMarkupContainer("addFriendContainer"); //ADD FRIEND MODAL WINDOW final ModalWindow addFriendWindow = new ModalWindow("addFriendWindow"); //FRIEND LINK/STATUS final AjaxLink<Void> addFriendLink = new AjaxLink<Void>("addFriendLink") { private static final long serialVersionUID = 1L; public void onClick(AjaxRequestTarget target) { addFriendWindow.show(target); } }; final Label addFriendLabel = new Label("addFriendLabel"); addFriendLink.add(addFriendLabel); addFriendContainer.add(addFriendLink); //setup link/label and windows if(friend) { addFriendLabel.setDefaultModel(new ResourceModel("text.friend.confirmed")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); } else if (friendRequestToThisPerson) { addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); } else if (friendRequestFromThisPerson) { //TODO (confirm pending friend request link) //could be done by setting the content off the addFriendWindow. //will need to rename some links to make more generic and set the onClick and setContent in here for link and window addFriendLabel.setDefaultModel(new ResourceModel("text.friend.pending")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); } else { addFriendLabel.setDefaultModel(new StringResourceModel("link.friend.add.name", null, new Object[]{ nickname } )); addFriendWindow.setContent(new AddFriend(addFriendWindow.getContentId(), addFriendWindow, friendActionModel, currentUserId, userUuid)); } sideLinks.add(addFriendContainer); //ADD FRIEND MODAL WINDOW HANDLER addFriendWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { private static final long serialVersionUID = 1L; public void onClose(AjaxRequestTarget target){ if(friendActionModel.isRequested()) { //friend was successfully requested, update label and link addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); target.addComponent(addFriendLink); } } }); add(addFriendWindow); //hide connection link if not allowed if(!isConnectionAllowed) { addFriendContainer.setVisible(false); } else { visibleSideLinksCount++; } //hide entire list if no links to show if(visibleSideLinksCount == 0) { sideLinks.setVisible(false); } add(sideLinks); /* FRIENDS FEED PANEL */ if(isFriendsListVisible) { add(new AjaxLazyLoadPanel("friendsFeed") { private static final long serialVersionUID = 1L; @Override public Component getLazyLoadComponent(String id) { return new FriendsFeed(id, userUuid, currentUserId); } }); } else { add(new EmptyPanel("friendsFeed")).setVisible(false); } /* GALLERY FEED PANEL */ add(new AjaxLazyLoadPanel("galleryFeed") { private static final long serialVersionUID = 1L; @Override public Component getLazyLoadComponent(String markupId) { if (sakaiProxy.isProfileGalleryEnabledGlobally() && isGalleryVisible) { return new GalleryFeed(markupId, userUuid, currentUserId) .setOutputMarkupId(true); } else { return new EmptyPanel(markupId).setVisible(false); } } }); }
public ViewProfile(final String userUuid) { log.debug("ViewProfile()"); //setup model to store the actions in the modal windows final FriendAction friendActionModel = new FriendAction(); //get current user info User currentUser = sakaiProxy.getUserQuietly(sakaiProxy.getCurrentUserId()); final String currentUserId = currentUser.getId(); String currentUserType = currentUser.getType(); //double check, if somehow got to own ViewPage, redirect to MyProfile instead if(userUuid.equals(currentUserId)) { log.warn("ViewProfile: user " + userUuid + " accessed ViewProfile for self. Redirecting..."); throw new RestartResponseException(new MyProfile()); } //check if super user, to grant editing rights to another user's profile if(sakaiProxy.isSuperUser()) { log.warn("ViewProfile: superUser " + currentUserId + " accessed ViewProfile for " + userUuid + ". Redirecting to allow edit."); throw new RestartResponseException(new MyProfile(userUuid)); } //post view event sakaiProxy.postEvent(ProfileConstants.EVENT_PROFILE_VIEW_OTHER, "/profile/"+userUuid, false); /* DEPRECATED via PRFL-24 when privacy was relaxed if(!isProfileAllowed) { throw new ProfileIllegalAccessException("User: " + currentUserId + " is not allowed to view profile for: " + userUuid); } */ //holds number of profile containers that are visible int visibleContainerCount = 0; //get SakaiPerson for the person who's profile we are viewing SakaiPerson sakaiPerson = sakaiProxy.getSakaiPerson(userUuid); //if null, they have no profile so just get a prototype if(sakaiPerson == null) { log.info("No SakaiPerson for " + userUuid); sakaiPerson = sakaiProxy.getSakaiPersonPrototype(); //if its still null, throw exception if(sakaiPerson == null) { throw new ProfilePrototypeNotDefinedException("Couldn't create a SakaiPerson prototype for " + userUuid); } } //get some values from SakaiPerson or SakaiProxy if empty //SakaiPerson returns NULL strings if value is not set, not blank ones User user = sakaiProxy.getUserQuietly(userUuid); String userDisplayName = user.getDisplayName(); String userType = user.getType(); //init boolean friend = false; boolean friendRequestToThisPerson = false; boolean friendRequestFromThisPerson = false; //friend? friend = profileLogic.isUserXFriendOfUserY(userUuid, currentUserId); //if not friend, has a friend request already been made to this person? if(!friend) { friendRequestToThisPerson = profileLogic.isFriendRequestPending(currentUserId, userUuid); } //if not friend and no friend request to this person, has a friend request been made from this person to the current user? if(!friend && !friendRequestToThisPerson) { friendRequestFromThisPerson = profileLogic.isFriendRequestPending(userUuid, currentUserId); } //privacy checks ProfilePrivacy privacy = profileLogic.getPrivacyRecordForUser(userUuid); boolean isProfileImageAllowed = profileLogic.isUserXProfileImageVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isBasicInfoAllowed = profileLogic.isUserXBasicInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isContactInfoAllowed = profileLogic.isUserXContactInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isAcademicInfoAllowed = profileLogic.isUserXAcademicInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isPersonalInfoAllowed = profileLogic.isUserXPersonalInfoVisibleByUserY(userUuid, privacy, currentUserId, friend); boolean isFriendsListVisible = profileLogic.isUserXFriendsListVisibleByUserY(userUuid, privacy, currentUserId, friend); final boolean isGalleryVisible = profileLogic.isUserXGalleryVisibleByUser(userUuid, privacy, currentUserId, friend); boolean isConnectionAllowed = sakaiProxy.isConnectionAllowedBetweenUserTypes(currentUserType, userType); /* IMAGE */ add(new ProfileImageRenderer("photo", userUuid, isProfileImageAllowed, ProfileConstants.PROFILE_IMAGE_MAIN, true)); /* NAME */ Label profileName = new Label("profileName", userDisplayName); add(profileName); /*STATUS PANEL */ ProfileStatusRenderer status = new ProfileStatusRenderer("status", userUuid, privacy, currentUserId, friend, null, "tiny"); status.setOutputMarkupId(true); add(status); /* BASIC INFO */ WebMarkupContainer basicInfoContainer = new WebMarkupContainer("mainSectionContainer_basic"); basicInfoContainer.setOutputMarkupId(true); //get info String nickname = sakaiPerson.getNickname(); Date dateOfBirth = sakaiPerson.getDateOfBirth(); String birthday = ""; int visibleFieldCount_basic = 0; if(dateOfBirth != null) { if(profileLogic.isBirthYearVisible(userUuid)) { birthday = ProfileUtils.convertDateToString(dateOfBirth, ProfileConstants.DEFAULT_DATE_FORMAT); } else { birthday = ProfileUtils.convertDateToString(dateOfBirth, ProfileConstants.DEFAULT_DATE_FORMAT_HIDE_YEAR); } } //heading basicInfoContainer.add(new Label("mainSectionHeading_basic", new ResourceModel("heading.basic"))); //nickname WebMarkupContainer nicknameContainer = new WebMarkupContainer("nicknameContainer"); nicknameContainer.add(new Label("nicknameLabel", new ResourceModel("profile.nickname"))); nicknameContainer.add(new Label("nickname", nickname)); basicInfoContainer.add(nicknameContainer); if(StringUtils.isBlank(nickname)) { nickname=""; //for the 'add friend' link nicknameContainer.setVisible(false); } else { visibleFieldCount_basic++; } //birthday WebMarkupContainer birthdayContainer = new WebMarkupContainer("birthdayContainer"); birthdayContainer.add(new Label("birthdayLabel", new ResourceModel("profile.birthday"))); birthdayContainer.add(new Label("birthday", birthday)); basicInfoContainer.add(birthdayContainer); if(StringUtils.isBlank(birthday)) { birthdayContainer.setVisible(false); } else { visibleFieldCount_basic++; } add(basicInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_basic == 0 || !isBasicInfoAllowed) { basicInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* CONTACT INFO */ WebMarkupContainer contactInfoContainer = new WebMarkupContainer("mainSectionContainer_contact"); contactInfoContainer.setOutputMarkupId(true); //get info String email = sakaiProxy.getUserEmail(userUuid); //must come from SakaiProxy String homepage = sakaiPerson.getLabeledURI(); String workphone = sakaiPerson.getTelephoneNumber(); String homephone = sakaiPerson.getHomePhone(); String mobilephone = sakaiPerson.getMobile(); String facsimile = sakaiPerson.getFacsimileTelephoneNumber(); int visibleFieldCount_contact = 0; //heading contactInfoContainer.add(new Label("mainSectionHeading_contact", new ResourceModel("heading.contact"))); //email WebMarkupContainer emailContainer = new WebMarkupContainer("emailContainer"); emailContainer.add(new Label("emailLabel", new ResourceModel("profile.email"))); emailContainer.add(new Label("email", email)); contactInfoContainer.add(emailContainer); if(StringUtils.isBlank(email)) { emailContainer.setVisible(false); } else { visibleFieldCount_contact++; } //homepage WebMarkupContainer homepageContainer = new WebMarkupContainer("homepageContainer"); homepageContainer.add(new Label("homepageLabel", new ResourceModel("profile.homepage"))); homepageContainer.add(new Label("homepage", homepage)); contactInfoContainer.add(homepageContainer); if(StringUtils.isBlank(homepage)) { homepageContainer.setVisible(false); } else { visibleFieldCount_contact++; } //work phone WebMarkupContainer workphoneContainer = new WebMarkupContainer("workphoneContainer"); workphoneContainer.add(new Label("workphoneLabel", new ResourceModel("profile.phone.work"))); workphoneContainer.add(new Label("workphone", workphone)); contactInfoContainer.add(workphoneContainer); if(StringUtils.isBlank(workphone)) { workphoneContainer.setVisible(false); } else { visibleFieldCount_contact++; } //home phone WebMarkupContainer homephoneContainer = new WebMarkupContainer("homephoneContainer"); homephoneContainer.add(new Label("homephoneLabel", new ResourceModel("profile.phone.home"))); homephoneContainer.add(new Label("homephone", homephone)); contactInfoContainer.add(homephoneContainer); if(StringUtils.isBlank(homephone)) { homephoneContainer.setVisible(false); } else { visibleFieldCount_contact++; } //mobile phone WebMarkupContainer mobilephoneContainer = new WebMarkupContainer("mobilephoneContainer"); mobilephoneContainer.add(new Label("mobilephoneLabel", new ResourceModel("profile.phone.mobile"))); mobilephoneContainer.add(new Label("mobilephone", mobilephone)); contactInfoContainer.add(mobilephoneContainer); if(StringUtils.isBlank(mobilephone)) { mobilephoneContainer.setVisible(false); } else { visibleFieldCount_contact++; } //facsimile WebMarkupContainer facsimileContainer = new WebMarkupContainer("facsimileContainer"); facsimileContainer.add(new Label("facsimileLabel", new ResourceModel("profile.phone.facsimile"))); facsimileContainer.add(new Label("facsimile", facsimile)); contactInfoContainer.add(facsimileContainer); if(StringUtils.isBlank(facsimile)) { facsimileContainer.setVisible(false); } else { visibleFieldCount_contact++; } add(contactInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_contact == 0 || !isContactInfoAllowed) { contactInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* ACADEMIC INFO */ WebMarkupContainer academicInfoContainer = new WebMarkupContainer("mainSectionContainer_academic"); academicInfoContainer.setOutputMarkupId(true); //get info String department = sakaiPerson.getOrganizationalUnit(); String position = sakaiPerson.getTitle(); String school = sakaiPerson.getCampus(); String room = sakaiPerson.getRoomNumber(); String course = sakaiPerson.getEducationCourse(); String subjects = sakaiPerson.getEducationSubjects(); int visibleFieldCount_academic = 0; //heading academicInfoContainer.add(new Label("mainSectionHeading_academic", new ResourceModel("heading.academic"))); //department WebMarkupContainer departmentContainer = new WebMarkupContainer("departmentContainer"); departmentContainer.add(new Label("departmentLabel", new ResourceModel("profile.department"))); departmentContainer.add(new Label("department", department)); academicInfoContainer.add(departmentContainer); if(StringUtils.isBlank(department)) { departmentContainer.setVisible(false); } else { visibleFieldCount_academic++; } //position WebMarkupContainer positionContainer = new WebMarkupContainer("positionContainer"); positionContainer.add(new Label("positionLabel", new ResourceModel("profile.position"))); positionContainer.add(new Label("position", position)); academicInfoContainer.add(positionContainer); if(StringUtils.isBlank(position)) { positionContainer.setVisible(false); } else { visibleFieldCount_academic++; } //school WebMarkupContainer schoolContainer = new WebMarkupContainer("schoolContainer"); schoolContainer.add(new Label("schoolLabel", new ResourceModel("profile.school"))); schoolContainer.add(new Label("school", school)); academicInfoContainer.add(schoolContainer); if(StringUtils.isBlank(school)) { schoolContainer.setVisible(false); } else { visibleFieldCount_academic++; } //room WebMarkupContainer roomContainer = new WebMarkupContainer("roomContainer"); roomContainer.add(new Label("roomLabel", new ResourceModel("profile.room"))); roomContainer.add(new Label("room", room)); academicInfoContainer.add(roomContainer); if(StringUtils.isBlank(room)) { roomContainer.setVisible(false); } else { visibleFieldCount_academic++; } //course WebMarkupContainer courseContainer = new WebMarkupContainer("courseContainer"); courseContainer.add(new Label("courseLabel", new ResourceModel("profile.course"))); courseContainer.add(new Label("course", course)); academicInfoContainer.add(courseContainer); if(StringUtils.isBlank(course)) { courseContainer.setVisible(false); } else { visibleFieldCount_academic++; } //subjects WebMarkupContainer subjectsContainer = new WebMarkupContainer("subjectsContainer"); subjectsContainer.add(new Label("subjectsLabel", new ResourceModel("profile.subjects"))); subjectsContainer.add(new Label("subjects", subjects)); academicInfoContainer.add(subjectsContainer); if(StringUtils.isBlank(subjects)) { subjectsContainer.setVisible(false); } else { visibleFieldCount_academic++; } add(academicInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_academic == 0 || !isAcademicInfoAllowed) { academicInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* PERSONAL INFO */ WebMarkupContainer personalInfoContainer = new WebMarkupContainer("mainSectionContainer_personal"); personalInfoContainer.setOutputMarkupId(true); //setup info String favouriteBooks = sakaiPerson.getFavouriteBooks(); String favouriteTvShows = sakaiPerson.getFavouriteTvShows(); String favouriteMovies = sakaiPerson.getFavouriteMovies(); String favouriteQuotes = sakaiPerson.getFavouriteQuotes(); String otherInformation = sakaiPerson.getNotes(); int visibleFieldCount_personal = 0; //heading personalInfoContainer.add(new Label("mainSectionHeading_personal", new ResourceModel("heading.interests"))); //favourite books WebMarkupContainer booksContainer = new WebMarkupContainer("booksContainer"); booksContainer.add(new Label("booksLabel", new ResourceModel("profile.favourite.books"))); booksContainer.add(new Label("favouriteBooks", favouriteBooks)); personalInfoContainer.add(booksContainer); if(StringUtils.isBlank(favouriteBooks)) { booksContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite tv shows WebMarkupContainer tvContainer = new WebMarkupContainer("tvContainer"); tvContainer.add(new Label("tvLabel", new ResourceModel("profile.favourite.tv"))); tvContainer.add(new Label("favouriteTvShows", favouriteTvShows)); personalInfoContainer.add(tvContainer); if(StringUtils.isBlank(favouriteTvShows)) { tvContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite movies WebMarkupContainer moviesContainer = new WebMarkupContainer("moviesContainer"); moviesContainer.add(new Label("moviesLabel", new ResourceModel("profile.favourite.movies"))); moviesContainer.add(new Label("favouriteMovies", favouriteMovies)); personalInfoContainer.add(moviesContainer); if(StringUtils.isBlank(favouriteMovies)) { moviesContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite quotes WebMarkupContainer quotesContainer = new WebMarkupContainer("quotesContainer"); quotesContainer.add(new Label("quotesLabel", new ResourceModel("profile.favourite.quotes"))); quotesContainer.add(new Label("favouriteQuotes", favouriteQuotes)); personalInfoContainer.add(quotesContainer); if(StringUtils.isBlank(favouriteQuotes)) { quotesContainer.setVisible(false); } else { visibleFieldCount_personal++; } //favourite quotes WebMarkupContainer otherContainer = new WebMarkupContainer("otherContainer"); otherContainer.add(new Label("otherLabel", new ResourceModel("profile.other"))); otherContainer.add(new Label("otherInformation", ProfileUtils.escapeHtmlForDisplay(otherInformation)).setEscapeModelStrings(false)); personalInfoContainer.add(otherContainer); if(StringUtils.isBlank(otherInformation)) { otherContainer.setVisible(false); } else { visibleFieldCount_personal++; } add(personalInfoContainer); //if nothing/not allowed, hide whole panel if(visibleFieldCount_personal == 0 || !isPersonalInfoAllowed) { personalInfoContainer.setVisible(false); } else { visibleContainerCount++; } /* NO INFO VISIBLE MESSAGE (hide if some visible) */ Label noContainersVisible = new Label ("noContainersVisible", new ResourceModel("text.view.profile.nothing")); noContainersVisible.setOutputMarkupId(true); add(noContainersVisible); if(visibleContainerCount > 0) { noContainersVisible.setVisible(false); } /* SIDELINKS */ WebMarkupContainer sideLinks = new WebMarkupContainer("sideLinks"); int visibleSideLinksCount = 0; WebMarkupContainer addFriendContainer = new WebMarkupContainer("addFriendContainer"); //ADD FRIEND MODAL WINDOW final ModalWindow addFriendWindow = new ModalWindow("addFriendWindow"); //FRIEND LINK/STATUS final AjaxLink<Void> addFriendLink = new AjaxLink<Void>("addFriendLink") { private static final long serialVersionUID = 1L; public void onClick(AjaxRequestTarget target) { addFriendWindow.show(target); } }; final Label addFriendLabel = new Label("addFriendLabel"); addFriendLink.add(addFriendLabel); addFriendContainer.add(addFriendLink); //setup link/label and windows if(friend) { addFriendLabel.setDefaultModel(new ResourceModel("text.friend.confirmed")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); } else if (friendRequestToThisPerson) { addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); } else if (friendRequestFromThisPerson) { //TODO (confirm pending friend request link) //could be done by setting the content off the addFriendWindow. //will need to rename some links to make more generic and set the onClick and setContent in here for link and window addFriendLabel.setDefaultModel(new ResourceModel("text.friend.pending")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); } else { addFriendLabel.setDefaultModel(new StringResourceModel("link.friend.add.name", null, new Object[]{ nickname } )); addFriendWindow.setContent(new AddFriend(addFriendWindow.getContentId(), addFriendWindow, friendActionModel, currentUserId, userUuid)); } sideLinks.add(addFriendContainer); //ADD FRIEND MODAL WINDOW HANDLER addFriendWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { private static final long serialVersionUID = 1L; public void onClose(AjaxRequestTarget target){ if(friendActionModel.isRequested()) { //friend was successfully requested, update label and link addFriendLabel.setDefaultModel(new ResourceModel("text.friend.requested")); addFriendLink.add(new AttributeModifier("class", true, new Model<String>("instruction"))); addFriendLink.setEnabled(false); target.addComponent(addFriendLink); } } }); add(addFriendWindow); //hide connection link if not allowed if(!isConnectionAllowed) { addFriendContainer.setVisible(false); } else { visibleSideLinksCount++; } //hide entire list if no links to show if(visibleSideLinksCount == 0) { sideLinks.setVisible(false); } add(sideLinks); /* FRIENDS FEED PANEL */ if(isFriendsListVisible) { add(new AjaxLazyLoadPanel("friendsFeed") { private static final long serialVersionUID = 1L; @Override public Component getLazyLoadComponent(String id) { return new FriendsFeed(id, userUuid, currentUserId); } }); } else { add(new EmptyPanel("friendsFeed")).setVisible(false); } /* GALLERY FEED PANEL */ add(new AjaxLazyLoadPanel("galleryFeed") { private static final long serialVersionUID = 1L; @Override public Component getLazyLoadComponent(String markupId) { if (sakaiProxy.isProfileGalleryEnabledGlobally() && isGalleryVisible) { return new GalleryFeed(markupId, userUuid, currentUserId) .setOutputMarkupId(true); } else { return new EmptyPanel(markupId).setVisible(false); } } }); }
diff --git a/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/TopicController.java b/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/TopicController.java index 3dce38f8..3295963c 100644 --- a/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/TopicController.java +++ b/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/TopicController.java @@ -1,447 +1,447 @@ package com.computas.sublima.app.controller.admin; import com.computas.sublima.query.SparqlDispatcher; import com.computas.sublima.query.SparulDispatcher; import com.computas.sublima.query.service.AdminService; import static com.computas.sublima.query.service.SettingsService.getProperty; import com.hp.hpl.jena.sparql.util.StringUtils; import org.apache.cocoon.components.flow.apples.AppleRequest; import org.apache.cocoon.components.flow.apples.AppleResponse; import org.apache.cocoon.components.flow.apples.StatelessAppleController; import org.apache.cocoon.environment.Request; import org.apache.log4j.Logger; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; /** * @author: mha * Date: 31.mar.2008 */ public class TopicController implements StatelessAppleController { private SparqlDispatcher sparqlDispatcher; private SparulDispatcher sparulDispatcher; AdminService adminService = new AdminService(); private String mode; private String submode; String[] completePrefixArray = { "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>", "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>", "PREFIX owl: <http://www.w3.org/2002/07/owl#>", "PREFIX foaf: <http://xmlns.com/foaf/0.1/>", "PREFIX lingvoj: <http://www.lingvoj.org/ontology#>", "PREFIX dcmitype: <http://purl.org/dc/dcmitype/>", "PREFIX dct: <http://purl.org/dc/terms/>", "PREFIX sub: <http://xmlns.computas.com/sublima#>", "PREFIX wdr: <http://www.w3.org/2007/05/powder#>", "PREFIX sioc: <http://rdfs.org/sioc/ns#>", "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>", "PREFIX topic: <topic/>", "PREFIX skos: <http://www.w3.org/2004/02/skos/core#>"}; String completePrefixes = StringUtils.join("\n", completePrefixArray); String[] prefixArray = { "dct: <http://purl.org/dc/terms/>", "foaf: <http://xmlns.com/foaf/0.1/>", "sub: <http://xmlns.computas.com/sublima#>", "rdfs: <http://www.w3.org/2000/01/rdf-schema#>", "wdr: <http://www.w3.org/2007/05/powder#>", "skos: <http://www.w3.org/2004/02/skos/core#>", "lingvoj: <http://www.lingvoj.org/ontology#>"}; String prefixes = StringUtils.join("\n", prefixArray); private static Logger logger = Logger.getLogger(AdminController.class); @SuppressWarnings("unchecked") public void process(AppleRequest req, AppleResponse res) throws Exception { this.mode = req.getSitemapParameter("mode"); this.submode = req.getSitemapParameter("submode"); if ("emner".equalsIgnoreCase(mode)) { if ("".equalsIgnoreCase(submode) || submode == null) { res.sendPage("xml2/emner", null); return; } else if ("nytt".equalsIgnoreCase(submode)) { editTopic(res, req, "nytt", null); return; } else if ("alle".equalsIgnoreCase(submode)) { showTopics(res, req); return; } else if ("emne".equalsIgnoreCase(submode)) { editTopic(res, req, "edit", null); return; } else if ("koble".equalsIgnoreCase(submode)) { mergeTopics(res, req); return; } else if ("tema".equalsIgnoreCase(submode)) { setThemeTopics(res, req); return; } else { res.sendStatus(404); return; } } else if ("browse".equalsIgnoreCase(mode)) { showTopicBrowsing(res, req); return; } } private void showTopicBrowsing(AppleResponse res, AppleRequest req) { Map<String, Object> bizData = new HashMap<String, Object>(); bizData.put("themetopics", adminService.getThemeTopics()); bizData.put("mode", "browse"); res.sendPage("xml/browse", bizData); } private void mergeTopics(AppleResponse res, AppleRequest req) { StringBuffer messageBuffer = new StringBuffer(); messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\">\n"); Map<String, Object> bizData = new HashMap<String, Object>(); if ("GET".equalsIgnoreCase(req.getCocoonRequest().getMethod())) { bizData.put("tempvalues", "<empty></empty>"); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("mode", "topicjoin"); bizData.put("messages", "<empty></empty>"); res.sendPage("xml2/koble", bizData); } else if ("POST".equalsIgnoreCase(req.getCocoonRequest().getMethod())) { // Lage ny URI for emne // Legge til URI i alle emner hvor gamle URI finnes // Slette alle gamle URIer StringBuffer topicBuffer = new StringBuffer(); String uri = req.getCocoonRequest().getParameter("skos:Concept/skos:prefLabel").replace(" ", "_"); uri = uri.replace(",", "_"); uri = uri.replace(".", "_"); uri = getProperty("sublima.base.url") + "topic/" + uri + "_" + uri.hashCode(); String insertNewTopicString = completePrefixes + "\nINSERT\n{\n" + "<" + uri + "> a skos:Concept ;\n" + " skos:prefLabel \"" + req.getCocoonRequest().getParameter("skos:Concept/skos:prefLabel") + "\"@no .\n" + "}"; logger.trace("TopicController.mergeTopics --> INSERT NEW TOPIC QUERY:\n" + insertNewTopicString); boolean insertNewSuccess = sparulDispatcher.query(insertNewTopicString); for (String s : req.getCocoonRequest().getParameterValues("skos:Concept")) { topicBuffer.append("?resource skos:Concept <" + s + "> .\n"); } messageBuffer.append("</c:messages>\n"); bizData.put("messages", messageBuffer.toString()); res.sendPage("xml2/koble", bizData); } } private void setThemeTopics(AppleResponse res, AppleRequest req) { StringBuffer messageBuffer = new StringBuffer(); messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\">\n"); Map<String, Object> bizData = new HashMap<String, Object>(); if ("GET".equalsIgnoreCase(req.getCocoonRequest().getMethod())) { bizData.put("themetopics", adminService.getThemeTopics()); bizData.put("tempvalues", "<empty></empty>"); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("mode", "theme"); bizData.put("messages", "<empty></empty>"); res.sendPage("xml2/tema", bizData); } else if ("POST".equalsIgnoreCase(req.getCocoonRequest().getMethod())) { Map<String, String[]> requestMap = createParametersMap(req.getCocoonRequest()); StringBuffer deleteString = new StringBuffer(); StringBuffer whereString = new StringBuffer(); StringBuffer insertString = new StringBuffer(); deleteString.append(completePrefixes); deleteString.append("\nDELETE\n{\n"); whereString.append("\nWHERE\n{\n"); deleteString.append("?topic sub:theme ?theme .\n"); deleteString.append("}\n"); whereString.append("?topic sub:theme ?theme.\n"); whereString.append("}\n"); insertString.append(completePrefixes); insertString.append("\nINSERT\n{\n"); for (String s : requestMap.keySet()) { if (!requestMap.get(s)[0].equalsIgnoreCase("")) { insertString.append("<" + requestMap.get(s)[0] + "> sub:theme \"true\"^^xsd:boolean .\n"); } } insertString.append("}\n"); deleteString.append(whereString.toString()); logger.trace("TopicController.setThemeTopics --> DELETE QUERY:\n" + deleteString.toString()); logger.trace("TopicController.setThemeTopics --> INSERT QUERY:\n" + insertString.toString()); boolean deleteSuccess = sparulDispatcher.query(deleteString.toString()); boolean insertSuccess = sparulDispatcher.query(insertString.toString()); logger.trace("TopicController.setThemeTopics --> DELETE QUERY RESULT: " + deleteSuccess); logger.trace("TopicController.setThemeTopics --> INSERT QUERY RESULT: " + insertSuccess); if (deleteSuccess && insertSuccess) { messageBuffer.append("<c:message>Emnene satt som temaemner</c:message>\n"); } else { messageBuffer.append("<c:message>Feil ved merking av temaemner</c:message>\n"); bizData.put("themetopics", "<empty></empty>"); } if (deleteSuccess && insertSuccess) { bizData.put("themetopics", adminService.getThemeTopics()); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "theme"); bizData.put("alltopics", adminService.getAllTopics()); } else { bizData.put("themetopics", adminService.getThemeTopics()); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "theme"); bizData.put("alltopics", adminService.getAllTopics()); } messageBuffer.append("</c:messages>\n"); bizData.put("messages", messageBuffer.toString()); res.sendPage("xml2/tema", bizData); } } private void showTopics(AppleResponse res, AppleRequest req) { Map<String, Object> bizData = new HashMap<String, Object>(); bizData.put("all_topics", adminService.getAllTopics()); res.sendPage("xml2/emner_alle", bizData); } private void editTopic(AppleResponse res, AppleRequest req, String type, String messages) { StringBuffer messageBuffer = new StringBuffer(); messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\">\n"); messageBuffer.append(messages); Map<String, Object> bizData = new HashMap<String, Object>(); if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) { bizData.put("tempvalues", "<empty></empty>"); if ("nytt".equalsIgnoreCase(type)) { bizData.put("topicdetails", "<empty></empty>"); bizData.put("topicresources", "<empty></empty>"); bizData.put("tempvalues", "<empty></empty>"); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("status", adminService.getAllStatuses()); bizData.put("mode", "topicedit"); } else { bizData.put("topicdetails", adminService.getTopicByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("status", adminService.getAllStatuses()); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "topicedit"); } bizData.put("messages", "<empty></empty>"); res.sendPage("xml2/emne", bizData); // When POST try to save the resource. Return error messages upon failure, and success message upon great success } else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) { // 1. Mellomlagre alle verdier // 2. Valider alle verdier // 3. Fors�k � lagre StringBuffer tempValues = getTempValues(req); String tempPrefixes = "<c:tempvalues \n" + "xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\"\n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" + "xmlns:c=\"http://xmlns.computas.com/cocoon\">\n"; String validationMessages = validateRequest(req); if (!"".equalsIgnoreCase(validationMessages)) { messageBuffer.append(validationMessages + "\n"); messageBuffer.append("</c:messages>\n"); bizData.put("topicdetails", "<empty></empty>"); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("tempvalues", tempPrefixes + tempValues.toString() + "</c:tempvalues>"); bizData.put("messages", messageBuffer.toString()); bizData.put("status", adminService.getAllStatuses()); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("mode", "topictemp"); res.sendPage("xml2/emne", bizData); } else { // Generate an identifier if a uri is not given String uri; if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("uri")) || req.getCocoonRequest().getParameter("uri") == null) { uri = req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:prefLabel").replace(" ", "_"); uri = uri.replace(",", "_"); uri = uri.replace(".", "_"); uri = getProperty("sublima.base.url") + "topic/" + uri + "_" + uri.hashCode(); } else { uri = req.getCocoonRequest().getParameter("uri"); } StringBuffer deleteString = new StringBuffer(); StringBuffer whereString = new StringBuffer(); deleteString.append(completePrefixes); deleteString.append("\nDELETE\n{\n"); whereString.append("\nWHERE\n{\n"); deleteString.append("<" + uri + "> a skos:Concept .\n"); deleteString.append("}\n"); whereString.append("<" + uri + "> a skos:Concept .\n"); whereString.append("}\n"); StringBuffer insertString = new StringBuffer(); insertString.append(completePrefixes); insertString.append("\nINSERT\n{\n"); insertString.append("<" + uri + "> a skos:Concept ;\n"); insertString.append("skos:prefLabel \"" + req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:prefLabel") + "\"@no ;\n"); insertString.append("wdr:describedBy <" + req.getCocoonRequest().getParameter("wdr:describedBy") + "> ;\n"); - insertString.append("skos:definition \"" + req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:definition") + "\"@no .\n"); + insertString.append("skos:definition \"" + req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:definition") + "\"@no ;\n"); insertString.append("skos:note \"" + req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:note") + "\"@no .\n"); if (req.getCocoonRequest().getParameterValues("dct:subject/skos:Concept/skos:broader/rdf:resource") != null) { for (String s : req.getCocoonRequest().getParameterValues("dct:subject/skos:Concept/skos:broader/rdf:resource")) { insertString.append("<" + uri + "> skos:broader <" + s + "> .\n"); } } insertString.append("}"); deleteString.append(whereString.toString()); boolean deleteSuccess = sparulDispatcher.query(deleteString.toString()); boolean insertSuccess = sparulDispatcher.query(insertString.toString()); logger.trace("TopicController.editTopic --> DELETE QUERY:\n" + deleteString.toString()); logger.trace("TopicController.editTopic --> INSERT QUERY:\n" + insertString.toString()); logger.trace("TopicController.editTopic --> DELETE QUERY RESULT: " + deleteSuccess); logger.trace("TopicController.editTopic --> INSERT QUERY RESULT: " + insertSuccess); if (deleteSuccess && insertSuccess) { messageBuffer.append("<c:message>Nytt emne lagt til!</c:message>\n"); } else { messageBuffer.append("<c:message>Feil ved lagring av nytt emne</c:message>\n"); bizData.put("topicdetails", "<empty></empty>"); } if (deleteSuccess && insertSuccess) { bizData.put("topicdetails", adminService.getTopicByURI(uri)); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("status", adminService.getAllStatuses()); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "topicedit"); bizData.put("alltopics", adminService.getAllTopics()); } else { bizData.put("topicdetails", adminService.getTopicByURI(uri)); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("status", adminService.getAllStatuses()); bizData.put("tempvalues", tempPrefixes + tempValues.toString() + "</c:tempvalues>"); bizData.put("mode", "topictemp"); bizData.put("alltopics", adminService.getAllTopics()); } messageBuffer.append("</c:messages>\n"); bizData.put("messages", messageBuffer.toString()); res.sendPage("xml2/emne", bizData); } } } private StringBuffer getTempValues(AppleRequest req) { //Keep all selected values in case of validation error String temp_title = req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:prefLabel"); String[] temp_broader = req.getCocoonRequest().getParameterValues("dct:subject/skos:Concept/skos:broader/rdf:resource"); String temp_status = req.getCocoonRequest().getParameter("wdr:describedBy"); String temp_description = req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:definition"); String temp_note = req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:note"); //Create an XML structure for the selected values, to use in the JX template StringBuffer xmlStructureBuffer = new StringBuffer(); xmlStructureBuffer.append("<skos:prefLabel>" + temp_title + "</skos:prefLabel>\n"); if (temp_broader != null) { for (String s : temp_broader) { //xmlStructureBuffer.append("<language>" + s + "</language>\n"); xmlStructureBuffer.append("<skos:broader rdf:resource=\"" + s + "\"/>\n"); } } xmlStructureBuffer.append("<wdr:describedBy rdf:resource=\"" + temp_status + "\"/>\n"); xmlStructureBuffer.append("<skos:description>" + temp_description + "</skos:description>\n"); xmlStructureBuffer.append("<skos:note>" + temp_note + "</skos:note>\n"); return xmlStructureBuffer; } /** * Method to validate the request upon insert of new resource. * Checks all parameters and gives error message if one or more required values are null * * @param req * @return */ private String validateRequest(AppleRequest req) { StringBuffer validationMessages = new StringBuffer(); if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:prefLabel")) || req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:prefLabel") == null) { validationMessages.append("<c:message>Emnets tittel kan ikke v�re blank</c:message>\n"); } if (req.getCocoonRequest().getParameter("wdr:describedBy") == null) { validationMessages.append("<c:message>En status m� velges</c:message>\n"); } return validationMessages.toString(); } public void setSparqlDispatcher (SparqlDispatcher sparqlDispatcher) { this.sparqlDispatcher = sparqlDispatcher; } public void setSparulDispatcher (SparulDispatcher sparulDispatcher) { this.sparulDispatcher = sparulDispatcher; } //todo Move to a Service-class private Map<String, String[]> createParametersMap (Request request) { Map<String, String[]> result = new HashMap<String, String[]>(); Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String paramName = (String) parameterNames.nextElement(); result.put(paramName, request.getParameterValues(paramName)); } return result; } }
true
true
private void editTopic(AppleResponse res, AppleRequest req, String type, String messages) { StringBuffer messageBuffer = new StringBuffer(); messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\">\n"); messageBuffer.append(messages); Map<String, Object> bizData = new HashMap<String, Object>(); if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) { bizData.put("tempvalues", "<empty></empty>"); if ("nytt".equalsIgnoreCase(type)) { bizData.put("topicdetails", "<empty></empty>"); bizData.put("topicresources", "<empty></empty>"); bizData.put("tempvalues", "<empty></empty>"); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("status", adminService.getAllStatuses()); bizData.put("mode", "topicedit"); } else { bizData.put("topicdetails", adminService.getTopicByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("status", adminService.getAllStatuses()); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "topicedit"); } bizData.put("messages", "<empty></empty>"); res.sendPage("xml2/emne", bizData); // When POST try to save the resource. Return error messages upon failure, and success message upon great success } else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) { // 1. Mellomlagre alle verdier // 2. Valider alle verdier // 3. Fors�k � lagre StringBuffer tempValues = getTempValues(req); String tempPrefixes = "<c:tempvalues \n" + "xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\"\n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" + "xmlns:c=\"http://xmlns.computas.com/cocoon\">\n"; String validationMessages = validateRequest(req); if (!"".equalsIgnoreCase(validationMessages)) { messageBuffer.append(validationMessages + "\n"); messageBuffer.append("</c:messages>\n"); bizData.put("topicdetails", "<empty></empty>"); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("tempvalues", tempPrefixes + tempValues.toString() + "</c:tempvalues>"); bizData.put("messages", messageBuffer.toString()); bizData.put("status", adminService.getAllStatuses()); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("mode", "topictemp"); res.sendPage("xml2/emne", bizData); } else { // Generate an identifier if a uri is not given String uri; if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("uri")) || req.getCocoonRequest().getParameter("uri") == null) { uri = req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:prefLabel").replace(" ", "_"); uri = uri.replace(",", "_"); uri = uri.replace(".", "_"); uri = getProperty("sublima.base.url") + "topic/" + uri + "_" + uri.hashCode(); } else { uri = req.getCocoonRequest().getParameter("uri"); } StringBuffer deleteString = new StringBuffer(); StringBuffer whereString = new StringBuffer(); deleteString.append(completePrefixes); deleteString.append("\nDELETE\n{\n"); whereString.append("\nWHERE\n{\n"); deleteString.append("<" + uri + "> a skos:Concept .\n"); deleteString.append("}\n"); whereString.append("<" + uri + "> a skos:Concept .\n"); whereString.append("}\n"); StringBuffer insertString = new StringBuffer(); insertString.append(completePrefixes); insertString.append("\nINSERT\n{\n"); insertString.append("<" + uri + "> a skos:Concept ;\n"); insertString.append("skos:prefLabel \"" + req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:prefLabel") + "\"@no ;\n"); insertString.append("wdr:describedBy <" + req.getCocoonRequest().getParameter("wdr:describedBy") + "> ;\n"); insertString.append("skos:definition \"" + req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:definition") + "\"@no .\n"); insertString.append("skos:note \"" + req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:note") + "\"@no .\n"); if (req.getCocoonRequest().getParameterValues("dct:subject/skos:Concept/skos:broader/rdf:resource") != null) { for (String s : req.getCocoonRequest().getParameterValues("dct:subject/skos:Concept/skos:broader/rdf:resource")) { insertString.append("<" + uri + "> skos:broader <" + s + "> .\n"); } } insertString.append("}"); deleteString.append(whereString.toString()); boolean deleteSuccess = sparulDispatcher.query(deleteString.toString()); boolean insertSuccess = sparulDispatcher.query(insertString.toString()); logger.trace("TopicController.editTopic --> DELETE QUERY:\n" + deleteString.toString()); logger.trace("TopicController.editTopic --> INSERT QUERY:\n" + insertString.toString()); logger.trace("TopicController.editTopic --> DELETE QUERY RESULT: " + deleteSuccess); logger.trace("TopicController.editTopic --> INSERT QUERY RESULT: " + insertSuccess); if (deleteSuccess && insertSuccess) { messageBuffer.append("<c:message>Nytt emne lagt til!</c:message>\n"); } else { messageBuffer.append("<c:message>Feil ved lagring av nytt emne</c:message>\n"); bizData.put("topicdetails", "<empty></empty>"); } if (deleteSuccess && insertSuccess) { bizData.put("topicdetails", adminService.getTopicByURI(uri)); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("status", adminService.getAllStatuses()); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "topicedit"); bizData.put("alltopics", adminService.getAllTopics()); } else { bizData.put("topicdetails", adminService.getTopicByURI(uri)); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("status", adminService.getAllStatuses()); bizData.put("tempvalues", tempPrefixes + tempValues.toString() + "</c:tempvalues>"); bizData.put("mode", "topictemp"); bizData.put("alltopics", adminService.getAllTopics()); } messageBuffer.append("</c:messages>\n"); bizData.put("messages", messageBuffer.toString()); res.sendPage("xml2/emne", bizData); } } }
private void editTopic(AppleResponse res, AppleRequest req, String type, String messages) { StringBuffer messageBuffer = new StringBuffer(); messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\">\n"); messageBuffer.append(messages); Map<String, Object> bizData = new HashMap<String, Object>(); if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) { bizData.put("tempvalues", "<empty></empty>"); if ("nytt".equalsIgnoreCase(type)) { bizData.put("topicdetails", "<empty></empty>"); bizData.put("topicresources", "<empty></empty>"); bizData.put("tempvalues", "<empty></empty>"); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("status", adminService.getAllStatuses()); bizData.put("mode", "topicedit"); } else { bizData.put("topicdetails", adminService.getTopicByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("status", adminService.getAllStatuses()); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "topicedit"); } bizData.put("messages", "<empty></empty>"); res.sendPage("xml2/emne", bizData); // When POST try to save the resource. Return error messages upon failure, and success message upon great success } else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) { // 1. Mellomlagre alle verdier // 2. Valider alle verdier // 3. Fors�k � lagre StringBuffer tempValues = getTempValues(req); String tempPrefixes = "<c:tempvalues \n" + "xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\"\n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" + "xmlns:c=\"http://xmlns.computas.com/cocoon\">\n"; String validationMessages = validateRequest(req); if (!"".equalsIgnoreCase(validationMessages)) { messageBuffer.append(validationMessages + "\n"); messageBuffer.append("</c:messages>\n"); bizData.put("topicdetails", "<empty></empty>"); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("tempvalues", tempPrefixes + tempValues.toString() + "</c:tempvalues>"); bizData.put("messages", messageBuffer.toString()); bizData.put("status", adminService.getAllStatuses()); bizData.put("alltopics", adminService.getAllTopics()); bizData.put("mode", "topictemp"); res.sendPage("xml2/emne", bizData); } else { // Generate an identifier if a uri is not given String uri; if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("uri")) || req.getCocoonRequest().getParameter("uri") == null) { uri = req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:prefLabel").replace(" ", "_"); uri = uri.replace(",", "_"); uri = uri.replace(".", "_"); uri = getProperty("sublima.base.url") + "topic/" + uri + "_" + uri.hashCode(); } else { uri = req.getCocoonRequest().getParameter("uri"); } StringBuffer deleteString = new StringBuffer(); StringBuffer whereString = new StringBuffer(); deleteString.append(completePrefixes); deleteString.append("\nDELETE\n{\n"); whereString.append("\nWHERE\n{\n"); deleteString.append("<" + uri + "> a skos:Concept .\n"); deleteString.append("}\n"); whereString.append("<" + uri + "> a skos:Concept .\n"); whereString.append("}\n"); StringBuffer insertString = new StringBuffer(); insertString.append(completePrefixes); insertString.append("\nINSERT\n{\n"); insertString.append("<" + uri + "> a skos:Concept ;\n"); insertString.append("skos:prefLabel \"" + req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:prefLabel") + "\"@no ;\n"); insertString.append("wdr:describedBy <" + req.getCocoonRequest().getParameter("wdr:describedBy") + "> ;\n"); insertString.append("skos:definition \"" + req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:definition") + "\"@no ;\n"); insertString.append("skos:note \"" + req.getCocoonRequest().getParameter("dct:subject/skos:Concept/skos:note") + "\"@no .\n"); if (req.getCocoonRequest().getParameterValues("dct:subject/skos:Concept/skos:broader/rdf:resource") != null) { for (String s : req.getCocoonRequest().getParameterValues("dct:subject/skos:Concept/skos:broader/rdf:resource")) { insertString.append("<" + uri + "> skos:broader <" + s + "> .\n"); } } insertString.append("}"); deleteString.append(whereString.toString()); boolean deleteSuccess = sparulDispatcher.query(deleteString.toString()); boolean insertSuccess = sparulDispatcher.query(insertString.toString()); logger.trace("TopicController.editTopic --> DELETE QUERY:\n" + deleteString.toString()); logger.trace("TopicController.editTopic --> INSERT QUERY:\n" + insertString.toString()); logger.trace("TopicController.editTopic --> DELETE QUERY RESULT: " + deleteSuccess); logger.trace("TopicController.editTopic --> INSERT QUERY RESULT: " + insertSuccess); if (deleteSuccess && insertSuccess) { messageBuffer.append("<c:message>Nytt emne lagt til!</c:message>\n"); } else { messageBuffer.append("<c:message>Feil ved lagring av nytt emne</c:message>\n"); bizData.put("topicdetails", "<empty></empty>"); } if (deleteSuccess && insertSuccess) { bizData.put("topicdetails", adminService.getTopicByURI(uri)); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("status", adminService.getAllStatuses()); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "topicedit"); bizData.put("alltopics", adminService.getAllTopics()); } else { bizData.put("topicdetails", adminService.getTopicByURI(uri)); bizData.put("topicresources", adminService.getTopicResourcesByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("status", adminService.getAllStatuses()); bizData.put("tempvalues", tempPrefixes + tempValues.toString() + "</c:tempvalues>"); bizData.put("mode", "topictemp"); bizData.put("alltopics", adminService.getAllTopics()); } messageBuffer.append("</c:messages>\n"); bizData.put("messages", messageBuffer.toString()); res.sendPage("xml2/emne", bizData); } } }
diff --git a/CubicTestSeleniumExporter/src/main/java/org/cubictest/exporters/selenium/launch/converters/CustomTestStepConverter.java b/CubicTestSeleniumExporter/src/main/java/org/cubictest/exporters/selenium/launch/converters/CustomTestStepConverter.java index ae8d976b..91de574a 100644 --- a/CubicTestSeleniumExporter/src/main/java/org/cubictest/exporters/selenium/launch/converters/CustomTestStepConverter.java +++ b/CubicTestSeleniumExporter/src/main/java/org/cubictest/exporters/selenium/launch/converters/CustomTestStepConverter.java @@ -1,58 +1,58 @@ /******************************************************************************* * Copyright (c) 2005, 2008 Christian Schwarz and Stein K. Skytteren * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Christian Schwarz and Stein K. Skytteren - initial API and implementation *******************************************************************************/ package org.cubictest.exporters.selenium.launch.converters; import java.util.ArrayList; import java.util.List; import org.cubictest.export.converters.ICustomTestStepConverter; import org.cubictest.export.exceptions.ExporterException; import org.cubictest.exporters.selenium.runner.CubicTestRemoteRunnerClient; import org.cubictest.exporters.selenium.runner.holders.SeleniumHolder; import org.cubictest.model.ICustomTestStepHolder; import org.cubictest.model.TestPartStatus; import org.cubictest.model.customstep.CustomTestStepParameter; import org.cubictest.model.customstep.data.CustomTestStepData; /** * Selenium custom test step converter. * * @author chr_schwarz */ public class CustomTestStepConverter implements ICustomTestStepConverter<SeleniumHolder> { public String getDataKey() { return "org.cubictest.seleniumexporter"; } public void handleCustomStep(SeleniumHolder t, ICustomTestStepHolder cts, CustomTestStepData data) { //throw new ExporterException("Custom test step not supported in Selenium runner yet"); CubicTestRemoteRunnerClient runner = t.getCustomStepRunner(); List<String> attributes = new ArrayList<String>(); attributes.add(data.getDisplayText()); for(CustomTestStepParameter param : cts.getCustomTestStepParameters()){ attributes.add(param.getKey()); attributes.add(cts.getValue(param).getValue()); } String result = runner.executeOnServer("cubicTestCustomStep", attributes.toArray(new String[attributes.size()])); if(result.startsWith("Error")){ - cts.setStatus(TestPartStatus.EXCEPTION); + t.updateStatus(cts, TestPartStatus.EXCEPTION); throw new ExporterException(result.replaceFirst("Error: ", result)); }else - cts.setStatus(TestPartStatus.PASS); + t.updateStatus(cts,TestPartStatus.PASS); } }
false
true
public void handleCustomStep(SeleniumHolder t, ICustomTestStepHolder cts, CustomTestStepData data) { //throw new ExporterException("Custom test step not supported in Selenium runner yet"); CubicTestRemoteRunnerClient runner = t.getCustomStepRunner(); List<String> attributes = new ArrayList<String>(); attributes.add(data.getDisplayText()); for(CustomTestStepParameter param : cts.getCustomTestStepParameters()){ attributes.add(param.getKey()); attributes.add(cts.getValue(param).getValue()); } String result = runner.executeOnServer("cubicTestCustomStep", attributes.toArray(new String[attributes.size()])); if(result.startsWith("Error")){ cts.setStatus(TestPartStatus.EXCEPTION); throw new ExporterException(result.replaceFirst("Error: ", result)); }else cts.setStatus(TestPartStatus.PASS); }
public void handleCustomStep(SeleniumHolder t, ICustomTestStepHolder cts, CustomTestStepData data) { //throw new ExporterException("Custom test step not supported in Selenium runner yet"); CubicTestRemoteRunnerClient runner = t.getCustomStepRunner(); List<String> attributes = new ArrayList<String>(); attributes.add(data.getDisplayText()); for(CustomTestStepParameter param : cts.getCustomTestStepParameters()){ attributes.add(param.getKey()); attributes.add(cts.getValue(param).getValue()); } String result = runner.executeOnServer("cubicTestCustomStep", attributes.toArray(new String[attributes.size()])); if(result.startsWith("Error")){ t.updateStatus(cts, TestPartStatus.EXCEPTION); throw new ExporterException(result.replaceFirst("Error: ", result)); }else t.updateStatus(cts,TestPartStatus.PASS); }
diff --git a/lucene/src/java/org/apache/lucene/index/LogMergePolicy.java b/lucene/src/java/org/apache/lucene/index/LogMergePolicy.java index f50287f7..31791d4b 100644 --- a/lucene/src/java/org/apache/lucene/index/LogMergePolicy.java +++ b/lucene/src/java/org/apache/lucene/index/LogMergePolicy.java @@ -1,671 +1,672 @@ package org.apache.lucene.index; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; /** <p>This class implements a {@link MergePolicy} that tries * to merge segments into levels of exponentially * increasing size, where each level has fewer segments than * the value of the merge factor. Whenever extra segments * (beyond the merge factor upper bound) are encountered, * all segments within the level are merged. You can get or * set the merge factor using {@link #getMergeFactor()} and * {@link #setMergeFactor(int)} respectively.</p> * * <p>This class is abstract and requires a subclass to * define the {@link #size} method which specifies how a * segment's size is determined. {@link LogDocMergePolicy} * is one subclass that measures size by document count in * the segment. {@link LogByteSizeMergePolicy} is another * subclass that measures size as the total byte size of the * file(s) for the segment.</p> */ public abstract class LogMergePolicy extends MergePolicy { /** Defines the allowed range of log(size) for each * level. A level is computed by taking the max segment * log size, minus LEVEL_LOG_SPAN, and finding all * segments falling within that range. */ public static final double LEVEL_LOG_SPAN = 0.75; /** Default merge factor, which is how many segments are * merged at a time */ public static final int DEFAULT_MERGE_FACTOR = 10; /** Default maximum segment size. A segment of this size * or larger will never be merged. @see setMaxMergeDocs */ public static final int DEFAULT_MAX_MERGE_DOCS = Integer.MAX_VALUE; /** Default noCFSRatio. If a merge's size is >= 10% of * the index, then we disable compound file for it. * @see #setNoCFSRatio */ public static final double DEFAULT_NO_CFS_RATIO = 0.1; protected int mergeFactor = DEFAULT_MERGE_FACTOR; protected long minMergeSize; protected long maxMergeSize; // Although the core MPs set it explicitly, we must default in case someone // out there wrote his own LMP ... protected long maxMergeSizeForOptimize = Long.MAX_VALUE; protected int maxMergeDocs = DEFAULT_MAX_MERGE_DOCS; protected boolean requireContiguousMerge = true; protected double noCFSRatio = DEFAULT_NO_CFS_RATIO; protected boolean calibrateSizeByDeletes = true; protected boolean useCompoundFile = true; public LogMergePolicy() { super(); } protected boolean verbose() { IndexWriter w = writer.get(); return w != null && w.verbose(); } /** @see #setNoCFSRatio */ public double getNoCFSRatio() { return noCFSRatio; } /** If a merged segment will be more than this percentage * of the total size of the index, leave the segment as * non-compound file even if compound file is enabled. * Set to 1.0 to always use CFS regardless of merge * size. */ public void setNoCFSRatio(double noCFSRatio) { if (noCFSRatio < 0.0 || noCFSRatio > 1.0) { throw new IllegalArgumentException("noCFSRatio must be 0.0 to 1.0 inclusive; got " + noCFSRatio); } this.noCFSRatio = noCFSRatio; } protected void message(String message) { if (verbose()) writer.get().message("LMP: " + message); } /** If true, merges must be in-order slice of the * segments. If false, then the merge policy is free to * pick any segments. The default is false, which is * in general more efficient than true since it gives the * merge policy more freedom to pick closely sized * segments. */ public void setRequireContiguousMerge(boolean v) { requireContiguousMerge = v; } /** See {@link #setRequireContiguousMerge}. */ public boolean getRequireContiguousMerge() { return requireContiguousMerge; } /** <p>Returns the number of segments that are merged at * once and also controls the total number of segments * allowed to accumulate in the index.</p> */ public int getMergeFactor() { return mergeFactor; } /** Determines how often segment indices are merged by * addDocument(). With smaller values, less RAM is used * while indexing, and searches on unoptimized indices are * faster, but indexing speed is slower. With larger * values, more RAM is used during indexing, and while * searches on unoptimized indices are slower, indexing is * faster. Thus larger values (> 10) are best for batch * index creation, and smaller values (< 10) for indices * that are interactively maintained. */ public void setMergeFactor(int mergeFactor) { if (mergeFactor < 2) throw new IllegalArgumentException("mergeFactor cannot be less than 2"); this.mergeFactor = mergeFactor; } // Javadoc inherited @Override public boolean useCompoundFile(SegmentInfos infos, SegmentInfo mergedInfo) throws IOException { final boolean doCFS; if (!useCompoundFile) { doCFS = false; } else if (noCFSRatio == 1.0) { doCFS = true; } else { long totalSize = 0; for (SegmentInfo info : infos) totalSize += size(info); doCFS = size(mergedInfo) <= noCFSRatio * totalSize; } return doCFS; } /** Sets whether compound file format should be used for * newly flushed and newly merged segments. */ public void setUseCompoundFile(boolean useCompoundFile) { this.useCompoundFile = useCompoundFile; } /** Returns true if newly flushed and newly merge segments * are written in compound file format. @see * #setUseCompoundFile */ public boolean getUseCompoundFile() { return useCompoundFile; } /** Sets whether the segment size should be calibrated by * the number of deletes when choosing segments for merge. */ public void setCalibrateSizeByDeletes(boolean calibrateSizeByDeletes) { this.calibrateSizeByDeletes = calibrateSizeByDeletes; } /** Returns true if the segment size should be calibrated * by the number of deletes when choosing segments for merge. */ public boolean getCalibrateSizeByDeletes() { return calibrateSizeByDeletes; } @Override public void close() {} abstract protected long size(SegmentInfo info) throws IOException; protected long sizeDocs(SegmentInfo info) throws IOException { if (calibrateSizeByDeletes) { int delCount = writer.get().numDeletedDocs(info); assert delCount <= info.docCount; return (info.docCount - (long)delCount); } else { return info.docCount; } } protected long sizeBytes(SegmentInfo info) throws IOException { long byteSize = info.sizeInBytes(true); if (calibrateSizeByDeletes) { int delCount = writer.get().numDeletedDocs(info); double delRatio = (info.docCount <= 0 ? 0.0f : ((float)delCount / (float)info.docCount)); assert delRatio <= 1.0; return (info.docCount <= 0 ? byteSize : (long)(byteSize * (1.0 - delRatio))); } else { return byteSize; } } protected boolean isOptimized(SegmentInfos infos, int maxNumSegments, Set<SegmentInfo> segmentsToOptimize) throws IOException { final int numSegments = infos.size(); int numToOptimize = 0; SegmentInfo optimizeInfo = null; for(int i=0;i<numSegments && numToOptimize <= maxNumSegments;i++) { final SegmentInfo info = infos.info(i); if (segmentsToOptimize.contains(info)) { numToOptimize++; optimizeInfo = info; } } return numToOptimize <= maxNumSegments && (numToOptimize != 1 || isOptimized(optimizeInfo)); } /** Returns true if this single info is optimized (has no * pending norms or deletes, is in the same dir as the * writer, and matches the current compound file setting */ protected boolean isOptimized(SegmentInfo info) throws IOException { IndexWriter w = writer.get(); assert w != null; boolean hasDeletions = w.numDeletedDocs(info) > 0; return !hasDeletions && !info.hasSeparateNorms() && info.dir == w.getDirectory() && (info.getUseCompoundFile() == useCompoundFile || noCFSRatio < 1.0); } /** * Returns the merges necessary to optimize the index, taking the max merge * size or max merge docs into consideration. This method attempts to respect * the {@code maxNumSegments} parameter, however it might be, due to size * constraints, that more than that number of segments will remain in the * index. Also, this method does not guarantee that exactly {@code * maxNumSegments} will remain, but &lt;= that number. */ private MergeSpecification findMergesForOptimizeSizeLimit( SegmentInfos infos, int maxNumSegments, int last) throws IOException { MergeSpecification spec = new MergeSpecification(); int start = last - 1; while (start >= 0) { SegmentInfo info = infos.info(start); if (size(info) > maxMergeSizeForOptimize || sizeDocs(info) > maxMergeDocs) { if (verbose()) { message("optimize: skip segment=" + info + ": size is > maxMergeSize (" + maxMergeSizeForOptimize + ") or sizeDocs is > maxMergeDocs (" + maxMergeDocs + ")"); } // need to skip that segment + add a merge for the 'right' segments, // unless there is only 1 which is optimized. if (last - start - 1 > 1 || (start != last - 1 && !isOptimized(infos.info(start + 1)))) { // there is more than 1 segment to the right of this one, or an unoptimized single segment. spec.add(new OneMerge(infos.range(start + 1, last))); } last = start; } else if (last - start == mergeFactor) { // mergeFactor eligible segments were found, add them as a merge. spec.add(new OneMerge(infos.range(start, last))); last = start; } --start; } // Add any left-over segments, unless there is just 1 already optimized. if (last > 0 && (++start + 1 < last || !isOptimized(infos.info(start)))) { spec.add(new OneMerge(infos.range(start, last))); } return spec.merges.size() == 0 ? null : spec; } /** * Returns the merges necessary to optimize the index. This method constraints * the returned merges only by the {@code maxNumSegments} parameter, and * guaranteed that exactly that number of segments will remain in the index. */ private MergeSpecification findMergesForOptimizeMaxNumSegments(SegmentInfos infos, int maxNumSegments, int last) throws IOException { MergeSpecification spec = new MergeSpecification(); // First, enroll all "full" merges (size // mergeFactor) to potentially be run concurrently: while (last - maxNumSegments + 1 >= mergeFactor) { spec.add(new OneMerge(infos.range(last-mergeFactor, last))); last -= mergeFactor; } // Only if there are no full merges pending do we // add a final partial (< mergeFactor segments) merge: if (0 == spec.merges.size()) { if (maxNumSegments == 1) { // Since we must optimize down to 1 segment, the // choice is simple: if (last > 1 || !isOptimized(infos.info(0))) { spec.add(new OneMerge(infos.range(0, last))); } } else if (last > maxNumSegments) { // Take care to pick a partial merge that is // least cost, but does not make the index too // lopsided. If we always just picked the // partial tail then we could produce a highly // lopsided index over time: // We must merge this many segments to leave // maxNumSegments in the index (from when // optimize was first kicked off): final int finalMergeSize = last - maxNumSegments + 1; // Consider all possible starting points: long bestSize = 0; int bestStart = 0; for(int i=0;i<last-finalMergeSize+1;i++) { long sumSize = 0; for(int j=0;j<finalMergeSize;j++) sumSize += size(infos.info(j+i)); if (i == 0 || (sumSize < 2*size(infos.info(i-1)) && sumSize < bestSize)) { bestStart = i; bestSize = sumSize; } } spec.add(new OneMerge(infos.range(bestStart, bestStart+finalMergeSize))); } } return spec.merges.size() == 0 ? null : spec; } /** Returns the merges necessary to optimize the index. * This merge policy defines "optimized" to mean only the * requested number of segments is left in the index, and * respects the {@link #maxMergeSizeForOptimize} setting. * By default, and assuming {@code maxNumSegments=1}, only * one segment will be left in the index, where that segment * has no deletions pending nor separate norms, and it is in * compound file format if the current useCompoundFile * setting is true. This method returns multiple merges * (mergeFactor at a time) so the {@link MergeScheduler} * in use may make use of concurrency. */ @Override public MergeSpecification findMergesForOptimize(SegmentInfos infos, int maxNumSegments, Set<SegmentInfo> segmentsToOptimize) throws IOException { assert maxNumSegments > 0; // If the segments are already optimized (e.g. there's only 1 segment), or // there are <maxNumSegements, all optimized, nothing to do. if (isOptimized(infos, maxNumSegments, segmentsToOptimize)) return null; // TODO: handle non-contiguous merge case differently? // Find the newest (rightmost) segment that needs to // be optimized (other segments may have been flushed // since optimize started): int last = infos.size(); while (last > 0) { final SegmentInfo info = infos.info(--last); if (segmentsToOptimize.contains(info)) { last++; break; } } if (last == 0) return null; // There is only one segment already, and it is optimized if (maxNumSegments == 1 && last == 1 && isOptimized(infos.info(0))) return null; // Check if there are any segments above the threshold boolean anyTooLarge = false; for (int i = 0; i < last; i++) { SegmentInfo info = infos.info(i); if (size(info) > maxMergeSizeForOptimize || sizeDocs(info) > maxMergeDocs) { anyTooLarge = true; break; } } if (anyTooLarge) { return findMergesForOptimizeSizeLimit(infos, maxNumSegments, last); } else { return findMergesForOptimizeMaxNumSegments(infos, maxNumSegments, last); } } /** * Finds merges necessary to expunge all deletes from the * index. We simply merge adjacent segments that have * deletes, up to mergeFactor at a time. */ @Override public MergeSpecification findMergesToExpungeDeletes(SegmentInfos segmentInfos) throws CorruptIndexException, IOException { final int numSegments = segmentInfos.size(); if (verbose()) message("findMergesToExpungeDeletes: " + numSegments + " segments"); MergeSpecification spec = new MergeSpecification(); int firstSegmentWithDeletions = -1; IndexWriter w = writer.get(); assert w != null; for(int i=0;i<numSegments;i++) { final SegmentInfo info = segmentInfos.info(i); int delCount = w.numDeletedDocs(info); if (delCount > 0) { if (verbose()) message(" segment " + info.name + " has deletions"); if (firstSegmentWithDeletions == -1) firstSegmentWithDeletions = i; else if (i - firstSegmentWithDeletions == mergeFactor) { // We've seen mergeFactor segments in a row with // deletions, so force a merge now: if (verbose()) message(" add merge " + firstSegmentWithDeletions + " to " + (i-1) + " inclusive"); spec.add(new OneMerge(segmentInfos.range(firstSegmentWithDeletions, i))); firstSegmentWithDeletions = i; } } else if (firstSegmentWithDeletions != -1) { // End of a sequence of segments with deletions, so, // merge those past segments even if it's fewer than // mergeFactor segments if (verbose()) message(" add merge " + firstSegmentWithDeletions + " to " + (i-1) + " inclusive"); spec.add(new OneMerge(segmentInfos.range(firstSegmentWithDeletions, i))); firstSegmentWithDeletions = -1; } } if (firstSegmentWithDeletions != -1) { if (verbose()) message(" add merge " + firstSegmentWithDeletions + " to " + (numSegments-1) + " inclusive"); spec.add(new OneMerge(segmentInfos.range(firstSegmentWithDeletions, numSegments))); } return spec; } private static class SegmentInfoAndLevel implements Comparable<SegmentInfoAndLevel> { SegmentInfo info; float level; int index; public SegmentInfoAndLevel(SegmentInfo info, float level, int index) { this.info = info; this.level = level; this.index = index; } // Sorts largest to smallest public int compareTo(SegmentInfoAndLevel other) { if (level < other.level) return 1; else if (level > other.level) return -1; else return 0; } } private static class SortByIndex implements Comparator<SegmentInfoAndLevel> { public int compare(SegmentInfoAndLevel o1, SegmentInfoAndLevel o2) { return o1.index - o2.index; } } private static final SortByIndex sortByIndex = new SortByIndex(); /** Checks if any merges are now necessary and returns a * {@link MergePolicy.MergeSpecification} if so. A merge * is necessary when there are more than {@link * #setMergeFactor} segments at a given level. When * multiple levels have too many segments, this method * will return multiple merges, allowing the {@link * MergeScheduler} to use concurrency. */ @Override public MergeSpecification findMerges(SegmentInfos infos) throws IOException { final int numSegments = infos.size(); if (verbose()) message("findMerges: " + numSegments + " segments"); // Compute levels, which is just log (base mergeFactor) // of the size of each segment final List<SegmentInfoAndLevel> levels = new ArrayList<SegmentInfoAndLevel>(); final float norm = (float) Math.log(mergeFactor); final Collection<SegmentInfo> mergingSegments = writer.get().getMergingSegments(); for(int i=0;i<numSegments;i++) { final SegmentInfo info = infos.info(i); long size = size(info); // When we require contiguous merge, we still add the // segment to levels to avoid merging "across" a set // of segment being merged: if (!requireContiguousMerge && mergingSegments.contains(info)) { if (verbose()) { message("seg " + info.name + " already being merged; skip"); } continue; } // Floor tiny segments if (size < 1) { size = 1; } - levels.add(new SegmentInfoAndLevel(info, (float) Math.log(size)/norm, i)); + final SegmentInfoAndLevel infoLevel = new SegmentInfoAndLevel(info, (float) Math.log(size)/norm, i); + levels.add(infoLevel); if (verbose()) { - message("seg " + info.name + " level=" + levels.get(i).level + " size=" + size); + message("seg " + info.name + " level=" + infoLevel.level + " size=" + size); } } if (!requireContiguousMerge) { Collections.sort(levels); } final float levelFloor; if (minMergeSize <= 0) levelFloor = (float) 0.0; else levelFloor = (float) (Math.log(minMergeSize)/norm); // Now, we quantize the log values into levels. The // first level is any segment whose log size is within // LEVEL_LOG_SPAN of the max size, or, who has such as // segment "to the right". Then, we find the max of all // other segments and use that to define the next level // segment, etc. MergeSpecification spec = null; final int numMergeableSegments = levels.size(); int start = 0; while(start < numMergeableSegments) { // Find max level of all segments not already // quantized. float maxLevel = levels.get(start).level; for(int i=1+start;i<numMergeableSegments;i++) { final float level = levels.get(i).level; if (level > maxLevel) maxLevel = level; } // Now search backwards for the rightmost segment that // falls into this level: float levelBottom; if (maxLevel <= levelFloor) // All remaining segments fall into the min level levelBottom = -1.0F; else { levelBottom = (float) (maxLevel - LEVEL_LOG_SPAN); // Force a boundary at the level floor if (levelBottom < levelFloor && maxLevel >= levelFloor) levelBottom = levelFloor; } int upto = numMergeableSegments-1; while(upto >= start) { if (levels.get(upto).level >= levelBottom) { break; } upto--; } if (verbose()) message(" level " + levelBottom + " to " + maxLevel + ": " + (1+upto-start) + " segments"); // Finally, record all merges that are viable at this level: int end = start + mergeFactor; while(end <= 1+upto) { boolean anyTooLarge = false; for(int i=start;i<end;i++) { final SegmentInfo info = levels.get(i).info; anyTooLarge |= (size(info) >= maxMergeSize || sizeDocs(info) >= maxMergeDocs); } if (!anyTooLarge) { if (spec == null) spec = new MergeSpecification(); if (verbose()) { message(" " + start + " to " + end + ": add this merge"); } Collections.sort(levels.subList(start, end), sortByIndex); final SegmentInfos mergeInfos = new SegmentInfos(); for(int i=start;i<end;i++) { mergeInfos.add(levels.get(i).info); assert infos.contains(levels.get(i).info); } spec.add(new OneMerge(mergeInfos)); } else if (verbose()) { message(" " + start + " to " + end + ": contains segment over maxMergeSize or maxMergeDocs; skipping"); } start = end; end = start + mergeFactor; } start = 1+upto; } return spec; } /** <p>Determines the largest segment (measured by * document count) that may be merged with other segments. * Small values (e.g., less than 10,000) are best for * interactive indexing, as this limits the length of * pauses while indexing to a few seconds. Larger values * are best for batched indexing and speedier * searches.</p> * * <p>The default value is {@link Integer#MAX_VALUE}.</p> * * <p>The default merge policy ({@link * LogByteSizeMergePolicy}) also allows you to set this * limit by net size (in MB) of the segment, using {@link * LogByteSizeMergePolicy#setMaxMergeMB}.</p> */ public void setMaxMergeDocs(int maxMergeDocs) { this.maxMergeDocs = maxMergeDocs; } /** Returns the largest segment (measured by document * count) that may be merged with other segments. * @see #setMaxMergeDocs */ public int getMaxMergeDocs() { return maxMergeDocs; } @Override public String toString() { StringBuilder sb = new StringBuilder("[" + getClass().getSimpleName() + ": "); sb.append("minMergeSize=").append(minMergeSize).append(", "); sb.append("mergeFactor=").append(mergeFactor).append(", "); sb.append("maxMergeSize=").append(maxMergeSize).append(", "); sb.append("maxMergeSizeForOptimize=").append(maxMergeSizeForOptimize).append(", "); sb.append("calibrateSizeByDeletes=").append(calibrateSizeByDeletes).append(", "); sb.append("maxMergeDocs=").append(maxMergeDocs).append(", "); sb.append("useCompoundFile=").append(useCompoundFile).append(", "); sb.append("requireContiguousMerge=").append(requireContiguousMerge); sb.append("]"); return sb.toString(); } }
false
true
public MergeSpecification findMerges(SegmentInfos infos) throws IOException { final int numSegments = infos.size(); if (verbose()) message("findMerges: " + numSegments + " segments"); // Compute levels, which is just log (base mergeFactor) // of the size of each segment final List<SegmentInfoAndLevel> levels = new ArrayList<SegmentInfoAndLevel>(); final float norm = (float) Math.log(mergeFactor); final Collection<SegmentInfo> mergingSegments = writer.get().getMergingSegments(); for(int i=0;i<numSegments;i++) { final SegmentInfo info = infos.info(i); long size = size(info); // When we require contiguous merge, we still add the // segment to levels to avoid merging "across" a set // of segment being merged: if (!requireContiguousMerge && mergingSegments.contains(info)) { if (verbose()) { message("seg " + info.name + " already being merged; skip"); } continue; } // Floor tiny segments if (size < 1) { size = 1; } levels.add(new SegmentInfoAndLevel(info, (float) Math.log(size)/norm, i)); if (verbose()) { message("seg " + info.name + " level=" + levels.get(i).level + " size=" + size); } } if (!requireContiguousMerge) { Collections.sort(levels); } final float levelFloor; if (minMergeSize <= 0) levelFloor = (float) 0.0; else levelFloor = (float) (Math.log(minMergeSize)/norm); // Now, we quantize the log values into levels. The // first level is any segment whose log size is within // LEVEL_LOG_SPAN of the max size, or, who has such as // segment "to the right". Then, we find the max of all // other segments and use that to define the next level // segment, etc. MergeSpecification spec = null; final int numMergeableSegments = levels.size(); int start = 0; while(start < numMergeableSegments) { // Find max level of all segments not already // quantized. float maxLevel = levels.get(start).level; for(int i=1+start;i<numMergeableSegments;i++) { final float level = levels.get(i).level; if (level > maxLevel) maxLevel = level; } // Now search backwards for the rightmost segment that // falls into this level: float levelBottom; if (maxLevel <= levelFloor) // All remaining segments fall into the min level levelBottom = -1.0F; else { levelBottom = (float) (maxLevel - LEVEL_LOG_SPAN); // Force a boundary at the level floor if (levelBottom < levelFloor && maxLevel >= levelFloor) levelBottom = levelFloor; } int upto = numMergeableSegments-1; while(upto >= start) { if (levels.get(upto).level >= levelBottom) { break; } upto--; } if (verbose()) message(" level " + levelBottom + " to " + maxLevel + ": " + (1+upto-start) + " segments"); // Finally, record all merges that are viable at this level: int end = start + mergeFactor; while(end <= 1+upto) { boolean anyTooLarge = false; for(int i=start;i<end;i++) { final SegmentInfo info = levels.get(i).info; anyTooLarge |= (size(info) >= maxMergeSize || sizeDocs(info) >= maxMergeDocs); } if (!anyTooLarge) { if (spec == null) spec = new MergeSpecification(); if (verbose()) { message(" " + start + " to " + end + ": add this merge"); } Collections.sort(levels.subList(start, end), sortByIndex); final SegmentInfos mergeInfos = new SegmentInfos(); for(int i=start;i<end;i++) { mergeInfos.add(levels.get(i).info); assert infos.contains(levels.get(i).info); } spec.add(new OneMerge(mergeInfos)); } else if (verbose()) { message(" " + start + " to " + end + ": contains segment over maxMergeSize or maxMergeDocs; skipping"); } start = end; end = start + mergeFactor; } start = 1+upto; } return spec; }
public MergeSpecification findMerges(SegmentInfos infos) throws IOException { final int numSegments = infos.size(); if (verbose()) message("findMerges: " + numSegments + " segments"); // Compute levels, which is just log (base mergeFactor) // of the size of each segment final List<SegmentInfoAndLevel> levels = new ArrayList<SegmentInfoAndLevel>(); final float norm = (float) Math.log(mergeFactor); final Collection<SegmentInfo> mergingSegments = writer.get().getMergingSegments(); for(int i=0;i<numSegments;i++) { final SegmentInfo info = infos.info(i); long size = size(info); // When we require contiguous merge, we still add the // segment to levels to avoid merging "across" a set // of segment being merged: if (!requireContiguousMerge && mergingSegments.contains(info)) { if (verbose()) { message("seg " + info.name + " already being merged; skip"); } continue; } // Floor tiny segments if (size < 1) { size = 1; } final SegmentInfoAndLevel infoLevel = new SegmentInfoAndLevel(info, (float) Math.log(size)/norm, i); levels.add(infoLevel); if (verbose()) { message("seg " + info.name + " level=" + infoLevel.level + " size=" + size); } } if (!requireContiguousMerge) { Collections.sort(levels); } final float levelFloor; if (minMergeSize <= 0) levelFloor = (float) 0.0; else levelFloor = (float) (Math.log(minMergeSize)/norm); // Now, we quantize the log values into levels. The // first level is any segment whose log size is within // LEVEL_LOG_SPAN of the max size, or, who has such as // segment "to the right". Then, we find the max of all // other segments and use that to define the next level // segment, etc. MergeSpecification spec = null; final int numMergeableSegments = levels.size(); int start = 0; while(start < numMergeableSegments) { // Find max level of all segments not already // quantized. float maxLevel = levels.get(start).level; for(int i=1+start;i<numMergeableSegments;i++) { final float level = levels.get(i).level; if (level > maxLevel) maxLevel = level; } // Now search backwards for the rightmost segment that // falls into this level: float levelBottom; if (maxLevel <= levelFloor) // All remaining segments fall into the min level levelBottom = -1.0F; else { levelBottom = (float) (maxLevel - LEVEL_LOG_SPAN); // Force a boundary at the level floor if (levelBottom < levelFloor && maxLevel >= levelFloor) levelBottom = levelFloor; } int upto = numMergeableSegments-1; while(upto >= start) { if (levels.get(upto).level >= levelBottom) { break; } upto--; } if (verbose()) message(" level " + levelBottom + " to " + maxLevel + ": " + (1+upto-start) + " segments"); // Finally, record all merges that are viable at this level: int end = start + mergeFactor; while(end <= 1+upto) { boolean anyTooLarge = false; for(int i=start;i<end;i++) { final SegmentInfo info = levels.get(i).info; anyTooLarge |= (size(info) >= maxMergeSize || sizeDocs(info) >= maxMergeDocs); } if (!anyTooLarge) { if (spec == null) spec = new MergeSpecification(); if (verbose()) { message(" " + start + " to " + end + ": add this merge"); } Collections.sort(levels.subList(start, end), sortByIndex); final SegmentInfos mergeInfos = new SegmentInfos(); for(int i=start;i<end;i++) { mergeInfos.add(levels.get(i).info); assert infos.contains(levels.get(i).info); } spec.add(new OneMerge(mergeInfos)); } else if (verbose()) { message(" " + start + " to " + end + ": contains segment over maxMergeSize or maxMergeDocs; skipping"); } start = end; end = start + mergeFactor; } start = 1+upto; } return spec; }
diff --git a/om/src/main/java/de/escidoc/core/om/business/renderer/VelocityXmlContainerRenderer.java b/om/src/main/java/de/escidoc/core/om/business/renderer/VelocityXmlContainerRenderer.java index aacab183c..ac14b56a1 100644 --- a/om/src/main/java/de/escidoc/core/om/business/renderer/VelocityXmlContainerRenderer.java +++ b/om/src/main/java/de/escidoc/core/om/business/renderer/VelocityXmlContainerRenderer.java @@ -1,663 +1,660 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at license/ESCIDOC.LICENSE * or http://www.escidoc.de/license. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at license/ESCIDOC.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2006-2008 Fachinformationszentrum Karlsruhe Gesellschaft * fuer wissenschaftlich-technische Information mbH and Max-Planck- * Gesellschaft zur Foerderung der Wissenschaft e.V. * All rights reserved. Use is subject to license terms. */ package de.escidoc.core.om.business.renderer; import de.escidoc.core.common.business.Constants; import de.escidoc.core.common.business.PropertyMapKeys; import de.escidoc.core.common.business.fedora.TripleStoreUtility; import de.escidoc.core.common.business.fedora.datastream.Datastream; import de.escidoc.core.common.business.fedora.resources.Container; import de.escidoc.core.common.business.fedora.resources.interfaces.FedoraResource; import de.escidoc.core.common.exceptions.application.missing.MissingMethodParameterException; import de.escidoc.core.common.exceptions.application.notfound.StreamNotFoundException; import de.escidoc.core.common.exceptions.system.EncodingSystemException; import de.escidoc.core.common.exceptions.system.FedoraSystemException; import de.escidoc.core.common.exceptions.system.IntegritySystemException; import de.escidoc.core.common.exceptions.system.SystemException; import de.escidoc.core.common.exceptions.system.TripleStoreSystemException; import de.escidoc.core.common.exceptions.system.WebserverSystemException; import de.escidoc.core.common.exceptions.system.XmlParserSystemException; import de.escidoc.core.common.util.xml.Elements; import de.escidoc.core.common.util.xml.XmlUtility; import de.escidoc.core.common.util.xml.factory.ContainerXmlProvider; import de.escidoc.core.common.util.xml.factory.MetadataRecordsXmlProvider; import de.escidoc.core.common.util.xml.factory.RelationsXmlProvider; import de.escidoc.core.common.util.xml.factory.XmlTemplateProviderConstants; import de.escidoc.core.om.business.renderer.interfaces.ContainerRendererInterface; import de.escidoc.core.om.business.security.UserFilter; import org.joda.time.DateTimeZone; import org.joda.time.format.ISODateTimeFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Render XML representations of a Container. */ @Service public class VelocityXmlContainerRenderer implements ContainerRendererInterface { private static final Logger LOGGER = LoggerFactory.getLogger(VelocityXmlContainerRenderer.class); private static final int THREE = 3; @Autowired private VelocityXmlCommonRenderer commonRenderer; @Autowired @Qualifier("business.TripleStoreUtility") private TripleStoreUtility tripleStoreUtility; /** * Protected constructor to prevent instantiation outside of the Spring-context. */ protected VelocityXmlContainerRenderer() { } /** * See Interface for functional description. * * @param container Container * @return XML Container representation. * @throws SystemException If an error occurs. */ @Override public String render(final Container container) throws SystemException { // Container container = containerHandler.getContainer(); final Map<String, Object> values = new HashMap<String, Object>(); commonRenderer.addCommonValues(container, values); addNamespaceValues(values); values.put("containerTitle", container.getTitle()); values.put("containerHref", container.getHref()); values.put("containerId", container.getId()); addPropertiesValus(values, container); // addOrganizationDetailsValues(organizationalUnit, values); addResourcesValues(container, values); addStructMapValus(container, values); addMdRecordsValues(container, values); final List<Map<String, String>> relations = container.getRelations(); commonRenderer.addRelationsValues(relations, container.getHref(), values); VelocityXmlCommonRenderer.addRelationsNamespaceValues(values); values.put("contentRelationsTitle", "Relations of Container"); return ContainerXmlProvider.getInstance().getContainerXml(values); } /* * (non-Javadoc) * * @see * de.escidoc.core.om.business.renderer.interfaces.ContainerRendererInterface * # * renderProperties(de.escidoc.core.common.business.fedora.resources.Container * ) */ @Override public String renderProperties(final Container container) throws WebserverSystemException, TripleStoreSystemException, EncodingSystemException, IntegritySystemException, FedoraSystemException { final Map<String, Object> values = new HashMap<String, Object>(); commonRenderer.addCommonValues(container, values); addNamespaceValues(values); values.put("isRootProperties", XmlTemplateProviderConstants.TRUE); addPropertiesValus(values, container); return ContainerXmlProvider.getInstance().getPropertiesXml(values); } /* * (non-Javadoc) * * @see * de.escidoc.core.om.business.renderer.interfaces.ContainerRendererInterface * # * renderResources(de.escidoc.core.common.business.fedora.resources.Container * ) */ @Override public String renderResources(final Container container) throws WebserverSystemException { final Map<String, Object> values = new HashMap<String, Object>(); commonRenderer.addCommonValues(container, values); addNamespaceValues(values); values.put("isRootResources", XmlTemplateProviderConstants.TRUE); addResourcesValues(container, values); return ContainerXmlProvider.getInstance().getResourcesXml(values); } /** * Gets the representation of the sub resource {@code relations} of an item/container. * * @param container The Container. * @return Returns the XML representation of the sub resource {@code ou-parents} of an organizational unit. */ @Override public String renderRelations(final Container container) throws WebserverSystemException, TripleStoreSystemException, IntegritySystemException, FedoraSystemException, XmlParserSystemException { final Map<String, Object> values = new HashMap<String, Object>(); commonRenderer.addCommonValues(container, values); values.put("isRootRelations", XmlTemplateProviderConstants.TRUE); commonRenderer.addRelationsValues(container.getRelations(), container.getHref(), values); values.put("contentRelationsTitle", "Relations of Container"); VelocityXmlCommonRenderer.addRelationsNamespaceValues(values); return RelationsXmlProvider.getInstance().getRelationsXml(values); } /** * Gets the representation of the virtual resource {@code parents} of an item/container. * * @param containerId The Container. * @return Returns the XML representation of the virtual resource {@code parents} of an container. */ @Override public String renderParents(final String containerId) throws WebserverSystemException, TripleStoreSystemException { final Map<String, Object> values = new HashMap<String, Object>(); VelocityXmlCommonRenderer.addXlinkValues(values); VelocityXmlCommonRenderer.addStructuralRelationsValues(values); values.put(XmlTemplateProviderConstants.VAR_LAST_MODIFICATION_DATE, ISODateTimeFormat.dateTime().withZone( DateTimeZone.UTC).print(System.currentTimeMillis())); values.put("isRootParents", XmlTemplateProviderConstants.TRUE); addParentsValues(containerId, values); VelocityXmlCommonRenderer.addParentsNamespaceValues(values); return ContainerXmlProvider.getInstance().getParentsXml(values); } /** * Adds the parents values to the provided map. * * @param containerId The container for that data shall be created. * @param values The map to add values to. * @throws de.escidoc.core.common.exceptions.system.TripleStoreSystemException */ private void addParentsValues(final String containerId, final Map<String, Object> values) throws TripleStoreSystemException { values.put("parentsHref", XmlUtility.getContainerParentsHref(XmlUtility.getContainerHref(containerId))); values.put("parentsTitle", "parents of container " + containerId); final StringBuffer query = this.tripleStoreUtility.getRetrieveSelectClause(true, TripleStoreUtility.PROP_MEMBER); if (query.length() > 0) { query.append(this.tripleStoreUtility.getRetrieveWhereClause(true, TripleStoreUtility.PROP_MEMBER, XmlUtility.getObjidWithoutVersion(containerId), null, null, null)); List<String> ids = new ArrayList<String>(); try { ids = this.tripleStoreUtility.retrieve(query.toString()); } catch (final TripleStoreSystemException e) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Error on quering triple store."); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Error on quering triple store.", e); } } final Iterator<String> idIter = ids.iterator(); final Collection<Map<String, String>> entries = new ArrayList<Map<String, String>>(ids.size()); while (idIter.hasNext()) { final Map<String, String> entry = new HashMap<String, String>(THREE); final String id = idIter.next(); entry.put("id", id); entry.put("href", XmlUtility.getContainerHref(id)); entry.put("title", this.tripleStoreUtility.getTitle(id)); entries.add(entry); } if (!entries.isEmpty()) { values.put(XmlTemplateProviderConstants.VAR_PARENTS, entries); } } } /** * Adds values for namespace declaration. * * @param values Already added values. * @throws WebserverSystemException If an error occurs. */ private static void addNamespaceValues(final Map<String, Object> values) { values.put("containerNamespacePrefix", Constants.CONTAINER_NAMESPACE_PREFIX); values.put("containerNamespace", Constants.CONTAINER_NAMESPACE_URI); values.put(XmlTemplateProviderConstants.ESCIDOC_PROPERTIES_NS_PREFIX, Constants.PROPERTIES_NS_PREFIX); values.put(XmlTemplateProviderConstants.ESCIDOC_PROPERTIES_NS, Constants.PROPERTIES_NS_URI); values.put(XmlTemplateProviderConstants.ESCIDOC_SREL_NS_PREFIX, Constants.STRUCTURAL_RELATIONS_NS_PREFIX); values.put(XmlTemplateProviderConstants.ESCIDOC_SREL_NS, Constants.STRUCTURAL_RELATIONS_NS_URI); values.put("versionNamespacePrefix", Constants.VERSION_NS_PREFIX); values.put("versionNamespace", Constants.VERSION_NS_URI); values.put("releaseNamespacePrefix", Constants.RELEASE_NS_PREFIX); values.put("releaseNamespace", Constants.RELEASE_NS_URI); values.put("structmapNamespacePrefix", Constants.STRUCT_MAP_PREFIX); values.put("structmapNamespace", Constants.STRUCT_MAP_NAMESPACE_URI); } /** * Adds the properties values to the provided map. * * @param values The map to add values to. * @param container The Container. * @throws de.escidoc.core.common.exceptions.system.WebserverSystemException * @throws de.escidoc.core.common.exceptions.system.TripleStoreSystemException * @throws de.escidoc.core.common.exceptions.system.FedoraSystemException * @throws de.escidoc.core.common.exceptions.system.IntegritySystemException * @throws de.escidoc.core.common.exceptions.system.EncodingSystemException */ private static void addPropertiesValus(final Map<String, Object> values, final Container container) throws TripleStoreSystemException, EncodingSystemException, IntegritySystemException, FedoraSystemException, WebserverSystemException { final String id = container.getId(); values.put(XmlTemplateProviderConstants.VAR_PROPERTIES_TITLE, "Properties"); values.put(XmlTemplateProviderConstants.VAR_PROPERTIES_HREF, XmlUtility.getContainerPropertiesHref(container .getHref())); // status values.put("containerStatus", container.getStatus()); values.put("containerCreationDate", container.getCreationDate()); values.put(XmlTemplateProviderConstants.VAR_CONTAINER_STATUS_COMMENT, XmlUtility .escapeForbiddenXmlCharacters(container.getProperty(PropertyMapKeys.PUBLIC_STATUS_COMMENT))); // name values.put("containerName", container.getTitle()); // description final String description = container.getDescription(); if (description != null) { values.put("containerDescription", PropertyMapKeys.CURRENT_VERSION_DESCRIPTION); } // context values.put("containerContextId", container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTEXT_ID)); values.put("containerContextHref", Constants.CONTEXT_URL_BASE + container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTEXT_ID)); values.put("containerContextTitle", container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTEXT_TITLE)); // content model final String contentModelId = container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTENT_MODEL_ID); values.put("containerContentModelId", contentModelId); values.put("containerContentModelHref", XmlUtility.getContentModelHref(contentModelId)); values.put("containerContentModelTitle", container .getProperty(PropertyMapKeys.CURRENT_VERSION_CONTENT_MODEL_TITLE)); // created-by ----------- final String createdById = container.getProperty(PropertyMapKeys.CREATED_BY_ID); values.put("containerCreatedById", createdById); values.put("containerCreatedByHref", XmlUtility.getUserAccountHref(createdById)); values.put("containerCreatedByTitle", container.getProperty(PropertyMapKeys.CREATED_BY_TITLE)); // lock -status, -owner, -date if (container.isLocked()) { values.put("containerLocked", XmlTemplateProviderConstants.TRUE); final String lockOwnerId = container.getLockOwner(); values.put("containerLockStatus", "locked"); values.put("containerLockDate", container.getLockDate()); values.put("containerLockOwnerHref", XmlUtility.getUserAccountHref(lockOwnerId)); values.put("containerLockOwnerId", lockOwnerId); values.put("containerLockOwnerTitle", container.getLockOwnerTitle()); } else { values.put("containerLocked", XmlTemplateProviderConstants.FALSE); values.put("containerLockStatus", "unlocked"); } final String currentVersionId = container.getFullId(); final String latestVersionNumber = container.getProperty(PropertyMapKeys.LATEST_VERSION_NUMBER); String curVersionNumber = container.getVersionId(); if (curVersionNumber == null) { curVersionNumber = latestVersionNumber; } // pid --------------- final String pid = container.getObjectPid(); if (pid != null && pid.length() > 0) { values.put("containerPid", pid); } // current version values.put("containerCurrentVersionHref", container.getVersionHref()); values.put("containerCurrentVersionTitle", "current version"); values.put("containerCurrentVersionId", currentVersionId); values.put("containerCurrentVersionNumber", curVersionNumber); values.put("containerCurrentVersionComment", XmlUtility.escapeForbiddenXmlCharacters(container .getProperty(PropertyMapKeys.CURRENT_VERSION_VERSION_COMMENT))); // modified by final String modifiedById = container.getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_ID); values.put("containerCurrentVersionModifiedByTitle", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_TITLE)); values.put("containerCurrentVersionModifiedByHref", XmlUtility.getUserAccountHref(modifiedById)); values.put("containerCurrentVersionModifiedById", modifiedById); final String versionPid = container.getVersionPid(); // container if (versionPid != null && versionPid.length() != 0) { values.put("containerCurrentVersionPID", versionPid); } values.put("containerCurrentVersionDate", container.getVersionDate()); if (curVersionNumber.equals(latestVersionNumber)) { final String latestVersionStatus = container.getProperty(PropertyMapKeys.LATEST_VERSION_VERSION_STATUS); values.put("containerCurrentVersionStatus", latestVersionStatus); if (latestVersionStatus.equals(Constants.STATUS_RELEASED)) { final String latestReleasePid = container.getProperty(PropertyMapKeys.LATEST_RELEASE_PID); if (latestReleasePid != null && latestReleasePid.length() != 0) { values.put("containerCurrentVersionPID", latestReleasePid); } } } else { values.put("containerCurrentVersionStatus", container.getProperty(PropertyMapKeys.CURRENT_VERSION_STATUS)); values.put("containerCurrentVersionComment", XmlUtility.escapeForbiddenXmlCharacters(container .getProperty(PropertyMapKeys.CURRENT_VERSION_VERSION_COMMENT))); values.put("containerCurrentVersionModifiedById", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_ID)); values.put("containerCurrentVersionModifiedByHref", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_HREF)); values.put("containerCurrentVersionModifiedByTitle", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_TITLE)); } // latest version values.put("containerLatestVersionHref", container.getLatestVersionHref()); values.put("containerLatestVersionId", container.getLatestVersionId()); values.put("containerLatestVersionTitle", "latest version"); values.put("containerLatestVersionDate", container.getProperty(PropertyMapKeys.LATEST_VERSION_DATE)); values.put("containerLatestVersionNumber", latestVersionNumber); // latest release final String containerStatus = container.getStatus(); if (containerStatus.equals(Constants.STATUS_RELEASED) || containerStatus.equals(Constants.STATUS_WITHDRAWN)) { values.put("containerLatestReleaseHref", container.getHrefWithoutVersionNumber() + ':' + container.getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_NUMBER)); values.put("containerLatestReleaseId", id + ':' + container.getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_NUMBER)); values.put("containerLatestReleaseTitle", "latest release"); values.put("containerLatestReleaseNumber", container .getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_NUMBER)); values .put("containerLatestReleaseDate", container.getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_DATE)); final String latestReleasePid = container.getProperty(PropertyMapKeys.LATEST_RELEASE_PID); if (latestReleasePid != null && latestReleasePid.length() != 0) { values.put("containerLatestReleasePid", latestReleasePid); } } // content model specific try { final Datastream cmsDs = container.getCts(); final String xml = cmsDs.toStringUTF8(); values.put(XmlTemplateProviderConstants.CONTAINER_CONTENT_MODEL_SPECIFIC, xml); } catch (final StreamNotFoundException e) { // This element is now optional. - if (LOGGER.isWarnEnabled()) { - LOGGER.warn("Error on getting container content model."); - } if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Error on getting container content model.", e); + LOGGER.debug("Error on getting container content model specific.", e); } } } /** * Adds the struct-map values to the provided map. * * @param container The Container. * @param values The map to add values to. * @throws SystemException Thrown in case of an internal error. */ private void addStructMapValus(final Container container, final Map<String, Object> values) throws SystemException { values.put("structMapTitle", "StructMap of Container"); values.put("structMapHref", container.getHref() + "/struct-map"); try { addMemberRefs(container, values); } catch (final MissingMethodParameterException e) { throw new WebserverSystemException(e); } } /** * * @param container * @param values * @throws SystemException * @throws MissingMethodParameterException * @throws de.escidoc.core.common.exceptions.system.WebserverSystemException * @throws de.escidoc.core.common.exceptions.system.XmlParserSystemException * @throws de.escidoc.core.common.exceptions.system.TripleStoreSystemException */ private void addMemberRefs(final Container container, final Map<String, Object> values) throws SystemException, MissingMethodParameterException { final UserFilter ufilter = new UserFilter(); final List<String> ids = ufilter.getMemberRefList(container); final Iterator<String> idIter = ids.iterator(); final Collection<Map<String, String>> items = new ArrayList<Map<String, String>>(); final Collection<Map<String, String>> containers = new ArrayList<Map<String, String>>(); while (idIter.hasNext()) { final Map<String, String> entry = new HashMap<String, String>(3); final String id = idIter.next(); final String objectType = this.tripleStoreUtility.getObjectType(id); if (Constants.ITEM_OBJECT_TYPE.equals(objectType) || Constants.CONTAINER_OBJECT_TYPE.equals(objectType)) { entry.put("memberId", id); entry.put("memberTitle", this.tripleStoreUtility.getTitle(id)); if (objectType.equals(Constants.ITEM_OBJECT_TYPE)) { items.add(entry); entry.put("memberHref", XmlUtility.BASE_OM + "item/" + id); entry.put("elementName", "item-ref"); } else { containers.add(entry); entry.put("memberHref", XmlUtility.BASE_OM + "container/" + id); entry.put("elementName", "container-ref"); } } else { final String msg = "FedoraContainerHandler.getMemberRefs: can not " + "write member entry to struct-map for " + "object with unknown type: " + id + '.'; LOGGER.error(msg); } } if (!items.isEmpty()) { values.put("items", items); } if (!containers.isEmpty()) { values.put("containers", containers); } } /** * Adds the resource values to the provided map. * * @param container The Container for that data shall be created. * @param values The map to add values to. * @throws WebserverSystemException If an error occurs. */ private void addResourcesValues(final FedoraResource container, final Map<String, Object> values) throws WebserverSystemException { values.put(XmlTemplateProviderConstants.RESOURCES_TITLE, "Resources"); values.put("resourcesHref", XmlUtility.getContainerResourcesHref(container.getHref())); values.put("membersHref", container.getHref() + "/resources/members"); values.put("membersTitle", "Members "); values.put("versionHistoryTitle", "Version History"); values.put("versionHistoryHref", XmlUtility.getContainerResourcesHref(container.getHref()) + '/' + Elements.ELEMENT_RESOURCES_VERSION_HISTORY); // add operations from Fedora service definitions // FIXME use container properties instead of triplestore util try { values.put("resourceOperationNames", this.tripleStoreUtility.getMethodNames(container.getId())); } catch (final TripleStoreSystemException e) { throw new WebserverSystemException(e); } } /** * Adds values for metadata XML of the container. * * @param container The container object. * @param values Already added values. * @throws EncodingSystemException If an encoding error occurs. * @throws FedoraSystemException If Fedora throws an exception. * @throws WebserverSystemException If an error occurs. * @throws IntegritySystemException If the repository integrity is violated. */ private void addMdRecordsValues(final Container container, final Map<String, Object> values) throws EncodingSystemException, FedoraSystemException, WebserverSystemException, IntegritySystemException { values.put(XmlTemplateProviderConstants.MD_RECRORDS_NAMESPACE_PREFIX, Constants.METADATARECORDS_NAMESPACE_PREFIX); values.put(XmlTemplateProviderConstants.MD_RECORDS_NAMESPACE, Constants.METADATARECORDS_NAMESPACE_URI); values.put("mdRecordsHref", XmlUtility.getContainerMdRecordsHref(container.getHref())); values.put("mdRecordsTitle", "Metadata Records of Container " + container.getId()); final HashMap<String, Datastream> mdRecords = (HashMap<String, Datastream>) container.getMdRecords(); final Collection<Datastream> mdRecordsDatastreams = mdRecords.values(); final Iterator<Datastream> it = mdRecordsDatastreams.iterator(); final StringBuilder content = new StringBuilder(); while (it.hasNext()) { final Datastream mdRecord = it.next(); final String md = renderMetadataRecord(container, mdRecord, false); content.append(md); } values.put(XmlTemplateProviderConstants.VAR_MD_RECORDS_CONTENT, content.toString()); } /** * Renders a single meta data record to XML representation. * * @param container The Container. * @param mdRecord The to render md record. * @param isRootMdRecord Set true if md-record is to render with root elements. * @return Returns the XML representation of the metadata records. * @throws EncodingSystemException If an encoding error occurs. * @throws FedoraSystemException If Fedora throws an exception. * @throws WebserverSystemException If an error occurs. */ @Override public String renderMetadataRecord( final Container container, final Datastream mdRecord, final boolean isRootMdRecord) throws EncodingSystemException, FedoraSystemException, WebserverSystemException { if (mdRecord.isDeleted()) { return ""; } final Map<String, Object> values = new HashMap<String, Object>(); commonRenderer.addCommonValues(container, values); values.put("mdRecordHref", XmlUtility.getContainerMdRecordsHref(container.getHref()) + "/md-record/" + mdRecord.getName()); values.put(XmlTemplateProviderConstants.MD_RECORD_NAME, mdRecord.getName()); values.put("mdRecordTitle", mdRecord.getName()); values.put(XmlTemplateProviderConstants.IS_ROOT_MD_RECORD, isRootMdRecord); values.put(XmlTemplateProviderConstants.MD_RECRORDS_NAMESPACE_PREFIX, Constants.METADATARECORDS_NAMESPACE_PREFIX); values.put(XmlTemplateProviderConstants.MD_RECORDS_NAMESPACE, Constants.METADATARECORDS_NAMESPACE_URI); final String mdRecordContent = mdRecord.toStringUTF8(); values.put(XmlTemplateProviderConstants.MD_RECORD_CONTENT, mdRecordContent); final List<String> altIds = mdRecord.getAlternateIDs(); if (!Constants.UNKNOWN.equals(altIds.get(1))) { values.put(XmlTemplateProviderConstants.MD_RECORD_TYPE, altIds.get(1)); } if (!Constants.UNKNOWN.equals(altIds.get(2))) { values.put(XmlTemplateProviderConstants.MD_RECORD_SCHEMA, altIds.get(2)); } return MetadataRecordsXmlProvider.getInstance().getMdRecordXml(values); } /** * @param container The Container. * @return Returns the XML representation of the metadata records. * @throws EncodingSystemException If an encoding error occurs. * @throws FedoraSystemException If Fedora throws an exception. * @throws WebserverSystemException If an error occurs. * @throws IntegritySystemException If the repository integrity is violated. */ @Override public String renderMetadataRecords(final Container container) throws EncodingSystemException, FedoraSystemException, WebserverSystemException, IntegritySystemException { final Map<String, Object> values = new HashMap<String, Object>(); commonRenderer.addCommonValues(container, values); values.put(XmlTemplateProviderConstants.IS_ROOT_SUB_RESOURCE, XmlTemplateProviderConstants.TRUE); addMdRecordsValues(container, values); return MetadataRecordsXmlProvider.getInstance().getMdRecordsXml(values); } /** * Gets the representation of the virtual sub resource {@code struct-map} of an organizational unit. * * @param container The Container. * @return Returns the XML representation of the virtual sub resource {@code children} of an organizational * unit. * @throws SystemException Thrown in case of an internal error. */ @Override public String renderStructMap(final Container container) throws SystemException { final Map<String, Object> values = new HashMap<String, Object>(); commonRenderer.addCommonValues(container, values); addNamespaceValues(values); values.put("isRootStructMap", XmlTemplateProviderConstants.TRUE); values.put("isSrelNeeded", XmlTemplateProviderConstants.TRUE); addStructMapValus(container, values); return ContainerXmlProvider.getInstance().getStructMapXml(values); } }
false
true
private static void addPropertiesValus(final Map<String, Object> values, final Container container) throws TripleStoreSystemException, EncodingSystemException, IntegritySystemException, FedoraSystemException, WebserverSystemException { final String id = container.getId(); values.put(XmlTemplateProviderConstants.VAR_PROPERTIES_TITLE, "Properties"); values.put(XmlTemplateProviderConstants.VAR_PROPERTIES_HREF, XmlUtility.getContainerPropertiesHref(container .getHref())); // status values.put("containerStatus", container.getStatus()); values.put("containerCreationDate", container.getCreationDate()); values.put(XmlTemplateProviderConstants.VAR_CONTAINER_STATUS_COMMENT, XmlUtility .escapeForbiddenXmlCharacters(container.getProperty(PropertyMapKeys.PUBLIC_STATUS_COMMENT))); // name values.put("containerName", container.getTitle()); // description final String description = container.getDescription(); if (description != null) { values.put("containerDescription", PropertyMapKeys.CURRENT_VERSION_DESCRIPTION); } // context values.put("containerContextId", container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTEXT_ID)); values.put("containerContextHref", Constants.CONTEXT_URL_BASE + container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTEXT_ID)); values.put("containerContextTitle", container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTEXT_TITLE)); // content model final String contentModelId = container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTENT_MODEL_ID); values.put("containerContentModelId", contentModelId); values.put("containerContentModelHref", XmlUtility.getContentModelHref(contentModelId)); values.put("containerContentModelTitle", container .getProperty(PropertyMapKeys.CURRENT_VERSION_CONTENT_MODEL_TITLE)); // created-by ----------- final String createdById = container.getProperty(PropertyMapKeys.CREATED_BY_ID); values.put("containerCreatedById", createdById); values.put("containerCreatedByHref", XmlUtility.getUserAccountHref(createdById)); values.put("containerCreatedByTitle", container.getProperty(PropertyMapKeys.CREATED_BY_TITLE)); // lock -status, -owner, -date if (container.isLocked()) { values.put("containerLocked", XmlTemplateProviderConstants.TRUE); final String lockOwnerId = container.getLockOwner(); values.put("containerLockStatus", "locked"); values.put("containerLockDate", container.getLockDate()); values.put("containerLockOwnerHref", XmlUtility.getUserAccountHref(lockOwnerId)); values.put("containerLockOwnerId", lockOwnerId); values.put("containerLockOwnerTitle", container.getLockOwnerTitle()); } else { values.put("containerLocked", XmlTemplateProviderConstants.FALSE); values.put("containerLockStatus", "unlocked"); } final String currentVersionId = container.getFullId(); final String latestVersionNumber = container.getProperty(PropertyMapKeys.LATEST_VERSION_NUMBER); String curVersionNumber = container.getVersionId(); if (curVersionNumber == null) { curVersionNumber = latestVersionNumber; } // pid --------------- final String pid = container.getObjectPid(); if (pid != null && pid.length() > 0) { values.put("containerPid", pid); } // current version values.put("containerCurrentVersionHref", container.getVersionHref()); values.put("containerCurrentVersionTitle", "current version"); values.put("containerCurrentVersionId", currentVersionId); values.put("containerCurrentVersionNumber", curVersionNumber); values.put("containerCurrentVersionComment", XmlUtility.escapeForbiddenXmlCharacters(container .getProperty(PropertyMapKeys.CURRENT_VERSION_VERSION_COMMENT))); // modified by final String modifiedById = container.getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_ID); values.put("containerCurrentVersionModifiedByTitle", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_TITLE)); values.put("containerCurrentVersionModifiedByHref", XmlUtility.getUserAccountHref(modifiedById)); values.put("containerCurrentVersionModifiedById", modifiedById); final String versionPid = container.getVersionPid(); // container if (versionPid != null && versionPid.length() != 0) { values.put("containerCurrentVersionPID", versionPid); } values.put("containerCurrentVersionDate", container.getVersionDate()); if (curVersionNumber.equals(latestVersionNumber)) { final String latestVersionStatus = container.getProperty(PropertyMapKeys.LATEST_VERSION_VERSION_STATUS); values.put("containerCurrentVersionStatus", latestVersionStatus); if (latestVersionStatus.equals(Constants.STATUS_RELEASED)) { final String latestReleasePid = container.getProperty(PropertyMapKeys.LATEST_RELEASE_PID); if (latestReleasePid != null && latestReleasePid.length() != 0) { values.put("containerCurrentVersionPID", latestReleasePid); } } } else { values.put("containerCurrentVersionStatus", container.getProperty(PropertyMapKeys.CURRENT_VERSION_STATUS)); values.put("containerCurrentVersionComment", XmlUtility.escapeForbiddenXmlCharacters(container .getProperty(PropertyMapKeys.CURRENT_VERSION_VERSION_COMMENT))); values.put("containerCurrentVersionModifiedById", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_ID)); values.put("containerCurrentVersionModifiedByHref", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_HREF)); values.put("containerCurrentVersionModifiedByTitle", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_TITLE)); } // latest version values.put("containerLatestVersionHref", container.getLatestVersionHref()); values.put("containerLatestVersionId", container.getLatestVersionId()); values.put("containerLatestVersionTitle", "latest version"); values.put("containerLatestVersionDate", container.getProperty(PropertyMapKeys.LATEST_VERSION_DATE)); values.put("containerLatestVersionNumber", latestVersionNumber); // latest release final String containerStatus = container.getStatus(); if (containerStatus.equals(Constants.STATUS_RELEASED) || containerStatus.equals(Constants.STATUS_WITHDRAWN)) { values.put("containerLatestReleaseHref", container.getHrefWithoutVersionNumber() + ':' + container.getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_NUMBER)); values.put("containerLatestReleaseId", id + ':' + container.getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_NUMBER)); values.put("containerLatestReleaseTitle", "latest release"); values.put("containerLatestReleaseNumber", container .getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_NUMBER)); values .put("containerLatestReleaseDate", container.getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_DATE)); final String latestReleasePid = container.getProperty(PropertyMapKeys.LATEST_RELEASE_PID); if (latestReleasePid != null && latestReleasePid.length() != 0) { values.put("containerLatestReleasePid", latestReleasePid); } } // content model specific try { final Datastream cmsDs = container.getCts(); final String xml = cmsDs.toStringUTF8(); values.put(XmlTemplateProviderConstants.CONTAINER_CONTENT_MODEL_SPECIFIC, xml); } catch (final StreamNotFoundException e) { // This element is now optional. if (LOGGER.isWarnEnabled()) { LOGGER.warn("Error on getting container content model."); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Error on getting container content model.", e); } } }
private static void addPropertiesValus(final Map<String, Object> values, final Container container) throws TripleStoreSystemException, EncodingSystemException, IntegritySystemException, FedoraSystemException, WebserverSystemException { final String id = container.getId(); values.put(XmlTemplateProviderConstants.VAR_PROPERTIES_TITLE, "Properties"); values.put(XmlTemplateProviderConstants.VAR_PROPERTIES_HREF, XmlUtility.getContainerPropertiesHref(container .getHref())); // status values.put("containerStatus", container.getStatus()); values.put("containerCreationDate", container.getCreationDate()); values.put(XmlTemplateProviderConstants.VAR_CONTAINER_STATUS_COMMENT, XmlUtility .escapeForbiddenXmlCharacters(container.getProperty(PropertyMapKeys.PUBLIC_STATUS_COMMENT))); // name values.put("containerName", container.getTitle()); // description final String description = container.getDescription(); if (description != null) { values.put("containerDescription", PropertyMapKeys.CURRENT_VERSION_DESCRIPTION); } // context values.put("containerContextId", container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTEXT_ID)); values.put("containerContextHref", Constants.CONTEXT_URL_BASE + container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTEXT_ID)); values.put("containerContextTitle", container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTEXT_TITLE)); // content model final String contentModelId = container.getProperty(PropertyMapKeys.CURRENT_VERSION_CONTENT_MODEL_ID); values.put("containerContentModelId", contentModelId); values.put("containerContentModelHref", XmlUtility.getContentModelHref(contentModelId)); values.put("containerContentModelTitle", container .getProperty(PropertyMapKeys.CURRENT_VERSION_CONTENT_MODEL_TITLE)); // created-by ----------- final String createdById = container.getProperty(PropertyMapKeys.CREATED_BY_ID); values.put("containerCreatedById", createdById); values.put("containerCreatedByHref", XmlUtility.getUserAccountHref(createdById)); values.put("containerCreatedByTitle", container.getProperty(PropertyMapKeys.CREATED_BY_TITLE)); // lock -status, -owner, -date if (container.isLocked()) { values.put("containerLocked", XmlTemplateProviderConstants.TRUE); final String lockOwnerId = container.getLockOwner(); values.put("containerLockStatus", "locked"); values.put("containerLockDate", container.getLockDate()); values.put("containerLockOwnerHref", XmlUtility.getUserAccountHref(lockOwnerId)); values.put("containerLockOwnerId", lockOwnerId); values.put("containerLockOwnerTitle", container.getLockOwnerTitle()); } else { values.put("containerLocked", XmlTemplateProviderConstants.FALSE); values.put("containerLockStatus", "unlocked"); } final String currentVersionId = container.getFullId(); final String latestVersionNumber = container.getProperty(PropertyMapKeys.LATEST_VERSION_NUMBER); String curVersionNumber = container.getVersionId(); if (curVersionNumber == null) { curVersionNumber = latestVersionNumber; } // pid --------------- final String pid = container.getObjectPid(); if (pid != null && pid.length() > 0) { values.put("containerPid", pid); } // current version values.put("containerCurrentVersionHref", container.getVersionHref()); values.put("containerCurrentVersionTitle", "current version"); values.put("containerCurrentVersionId", currentVersionId); values.put("containerCurrentVersionNumber", curVersionNumber); values.put("containerCurrentVersionComment", XmlUtility.escapeForbiddenXmlCharacters(container .getProperty(PropertyMapKeys.CURRENT_VERSION_VERSION_COMMENT))); // modified by final String modifiedById = container.getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_ID); values.put("containerCurrentVersionModifiedByTitle", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_TITLE)); values.put("containerCurrentVersionModifiedByHref", XmlUtility.getUserAccountHref(modifiedById)); values.put("containerCurrentVersionModifiedById", modifiedById); final String versionPid = container.getVersionPid(); // container if (versionPid != null && versionPid.length() != 0) { values.put("containerCurrentVersionPID", versionPid); } values.put("containerCurrentVersionDate", container.getVersionDate()); if (curVersionNumber.equals(latestVersionNumber)) { final String latestVersionStatus = container.getProperty(PropertyMapKeys.LATEST_VERSION_VERSION_STATUS); values.put("containerCurrentVersionStatus", latestVersionStatus); if (latestVersionStatus.equals(Constants.STATUS_RELEASED)) { final String latestReleasePid = container.getProperty(PropertyMapKeys.LATEST_RELEASE_PID); if (latestReleasePid != null && latestReleasePid.length() != 0) { values.put("containerCurrentVersionPID", latestReleasePid); } } } else { values.put("containerCurrentVersionStatus", container.getProperty(PropertyMapKeys.CURRENT_VERSION_STATUS)); values.put("containerCurrentVersionComment", XmlUtility.escapeForbiddenXmlCharacters(container .getProperty(PropertyMapKeys.CURRENT_VERSION_VERSION_COMMENT))); values.put("containerCurrentVersionModifiedById", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_ID)); values.put("containerCurrentVersionModifiedByHref", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_HREF)); values.put("containerCurrentVersionModifiedByTitle", container .getProperty(PropertyMapKeys.CURRENT_VERSION_MODIFIED_BY_TITLE)); } // latest version values.put("containerLatestVersionHref", container.getLatestVersionHref()); values.put("containerLatestVersionId", container.getLatestVersionId()); values.put("containerLatestVersionTitle", "latest version"); values.put("containerLatestVersionDate", container.getProperty(PropertyMapKeys.LATEST_VERSION_DATE)); values.put("containerLatestVersionNumber", latestVersionNumber); // latest release final String containerStatus = container.getStatus(); if (containerStatus.equals(Constants.STATUS_RELEASED) || containerStatus.equals(Constants.STATUS_WITHDRAWN)) { values.put("containerLatestReleaseHref", container.getHrefWithoutVersionNumber() + ':' + container.getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_NUMBER)); values.put("containerLatestReleaseId", id + ':' + container.getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_NUMBER)); values.put("containerLatestReleaseTitle", "latest release"); values.put("containerLatestReleaseNumber", container .getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_NUMBER)); values .put("containerLatestReleaseDate", container.getProperty(PropertyMapKeys.LATEST_RELEASE_VERSION_DATE)); final String latestReleasePid = container.getProperty(PropertyMapKeys.LATEST_RELEASE_PID); if (latestReleasePid != null && latestReleasePid.length() != 0) { values.put("containerLatestReleasePid", latestReleasePid); } } // content model specific try { final Datastream cmsDs = container.getCts(); final String xml = cmsDs.toStringUTF8(); values.put(XmlTemplateProviderConstants.CONTAINER_CONTENT_MODEL_SPECIFIC, xml); } catch (final StreamNotFoundException e) { // This element is now optional. if (LOGGER.isDebugEnabled()) { LOGGER.debug("Error on getting container content model specific.", e); } } }
diff --git a/src/main/java/com/feefighers/TransactionHelper.java b/src/main/java/com/feefighers/TransactionHelper.java index c4bdf54..980ec17 100644 --- a/src/main/java/com/feefighers/TransactionHelper.java +++ b/src/main/java/com/feefighers/TransactionHelper.java @@ -1,32 +1,33 @@ package com.feefighers; import org.apache.commons.lang.StringUtils; import com.feefighers.model.Options; import com.feefighers.model.Transaction; import com.feefighers.model.Transaction.TransactionRequestType; public class TransactionHelper { public static Transaction generateTransactionAndSetOptions(Options options, boolean defaultCurrency) { Transaction transaction = new Transaction(TransactionRequestType.purchase); if(options != null) { if(options.get("amount") != null) { transaction.setAmount(String.valueOf(options.get("amount"))); } transaction.setPaymentMethodToken(options.get("payment_method_token")); transaction.setDescriptor(options.get("descriptor")); transaction.setCustom(options.get("custom")); transaction.setCustomerReference(options.get("customer_reference")); transaction.setBillingReference(options.get("billing_reference")); + transaction.setCurrencyCode(options.get("currency_code")); } if(defaultCurrency && StringUtils.isBlank(transaction.getCurrencyCode())) { transaction.setCurrencyCode("USD"); } return transaction; } }
true
true
public static Transaction generateTransactionAndSetOptions(Options options, boolean defaultCurrency) { Transaction transaction = new Transaction(TransactionRequestType.purchase); if(options != null) { if(options.get("amount") != null) { transaction.setAmount(String.valueOf(options.get("amount"))); } transaction.setPaymentMethodToken(options.get("payment_method_token")); transaction.setDescriptor(options.get("descriptor")); transaction.setCustom(options.get("custom")); transaction.setCustomerReference(options.get("customer_reference")); transaction.setBillingReference(options.get("billing_reference")); } if(defaultCurrency && StringUtils.isBlank(transaction.getCurrencyCode())) { transaction.setCurrencyCode("USD"); } return transaction; }
public static Transaction generateTransactionAndSetOptions(Options options, boolean defaultCurrency) { Transaction transaction = new Transaction(TransactionRequestType.purchase); if(options != null) { if(options.get("amount") != null) { transaction.setAmount(String.valueOf(options.get("amount"))); } transaction.setPaymentMethodToken(options.get("payment_method_token")); transaction.setDescriptor(options.get("descriptor")); transaction.setCustom(options.get("custom")); transaction.setCustomerReference(options.get("customer_reference")); transaction.setBillingReference(options.get("billing_reference")); transaction.setCurrencyCode(options.get("currency_code")); } if(defaultCurrency && StringUtils.isBlank(transaction.getCurrencyCode())) { transaction.setCurrencyCode("USD"); } return transaction; }
diff --git a/src/main/java/org/programmerplanet/sshtunnel/model/Tunnel.java b/src/main/java/org/programmerplanet/sshtunnel/model/Tunnel.java index 59c6e6a..c18d74c 100644 --- a/src/main/java/org/programmerplanet/sshtunnel/model/Tunnel.java +++ b/src/main/java/org/programmerplanet/sshtunnel/model/Tunnel.java @@ -1,96 +1,96 @@ /* * Copyright 2009 Joseph Fifield * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.programmerplanet.sshtunnel.model; /** * Represents a tunnel (port forward) over an ssh connection. * * @author <a href="[email protected]">Joseph Fifield</a> */ public class Tunnel implements Comparable<Tunnel> { private String localAddress; private int localPort; private String remoteAddress; private int remotePort; private boolean local = true; private transient Exception exception; public String getLocalAddress() { return localAddress; } public void setLocalAddress(String localAddress) { this.localAddress = localAddress; } public int getLocalPort() { return localPort; } public void setLocalPort(int localPort) { this.localPort = localPort; } public String getRemoteAddress() { return remoteAddress; } public void setRemoteAddress(String remoteAddress) { this.remoteAddress = remoteAddress; } public int getRemotePort() { return remotePort; } public void setRemotePort(int remotePort) { this.remotePort = remotePort; } public void setLocal(boolean local) { this.local = local; } public boolean getLocal() { return local; } public void setException(Exception exception) { this.exception = exception; } public Exception getException() { return exception; } public String toString() { String localName = getLocalAddress() + ":" + getLocalPort(); String direction = getLocal() ? "->" : "<-"; String remoteName = getRemoteAddress() + ":" + getRemotePort(); return "Tunnel (" + localName + direction + remoteName + ")"; } public int compareTo(Tunnel other) { - int i = localAddress.compareTo(localAddress); + int i = localAddress.compareTo(other.localAddress); if (i == 0) { i = Integer.valueOf(localPort).compareTo(Integer.valueOf(other.localPort)); } return i; } }
true
true
public int compareTo(Tunnel other) { int i = localAddress.compareTo(localAddress); if (i == 0) { i = Integer.valueOf(localPort).compareTo(Integer.valueOf(other.localPort)); } return i; }
public int compareTo(Tunnel other) { int i = localAddress.compareTo(other.localAddress); if (i == 0) { i = Integer.valueOf(localPort).compareTo(Integer.valueOf(other.localPort)); } return i; }
diff --git a/src/main/java/blackboard/plugin/hayabusa/provider/ThemeProvider.java b/src/main/java/blackboard/plugin/hayabusa/provider/ThemeProvider.java index f871d57..28be97f 100644 --- a/src/main/java/blackboard/plugin/hayabusa/provider/ThemeProvider.java +++ b/src/main/java/blackboard/plugin/hayabusa/provider/ThemeProvider.java @@ -1,143 +1,148 @@ /* * Copyright (c) 2013, Blackboard, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the * name of the Blackboard Inc. nor the names of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * BLACKBOARD MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON- * INFRINGEMENT. BLACKBOARD SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package blackboard.plugin.hayabusa.provider; import java.util.HashMap; import java.util.List; import java.util.Set; import blackboard.data.navigation.NavigationItem; import blackboard.data.navigation.NavigationItemControl; import blackboard.persist.PersistenceRuntimeException; import blackboard.persist.navigation.NavigationItemDbLoader; import blackboard.platform.branding.BrandingUtil; import blackboard.platform.branding.common.Branding; import blackboard.platform.branding.common.ColorPalette; import blackboard.platform.branding.common.Theme; import blackboard.platform.branding.service.BrandingManager; import blackboard.platform.branding.service.ColorPaletteManager; import blackboard.platform.branding.service.ColorPaletteManagerFactory; import blackboard.platform.branding.service.ThemeManagerFactory; import blackboard.platform.context.Context; import blackboard.platform.context.ContextManagerFactory; import blackboard.platform.security.NonceUtil; import blackboard.plugin.hayabusa.command.Category; import blackboard.plugin.hayabusa.command.Command; import blackboard.plugin.hayabusa.command.PostCommand; import blackboard.portal.data.PortalBranding; import blackboard.portal.persist.PortalBrandingDbLoader; import com.google.common.collect.Sets; /** * A {@link Provider} for courses * * @author Zhaoxia Yang * @since 1.0 */ public class ThemeProvider implements Provider { public static final String NONCE_ID = "blackboard.webapps.portal.brands.struts.CustomizeBrandForm"; public static final String NONCE_CONTEXT = "/webapps/portal"; public static final String URI = "/webapps/portal/execute/brands/customizeBrand"; @Override public Iterable<Command> getCommands() { List<Theme> themes = ThemeManagerFactory.getInstance().getAllThemes(); Set<Command> commands = Sets.newTreeSet(); Context bbCtxt = ContextManagerFactory.getInstance().getContext(); NavigationItem ni = null; List<PortalBranding> portalBrandings = null; PortalBranding currentPortalBranding = null; Branding branding = null; ColorPalette colorPalette = null; Theme currentTheme = null; try { NavigationItemDbLoader niDbLoader = NavigationItemDbLoader.Default.getInstance(); ni = niDbLoader.loadByInternalHandle( "pa_customize_brand" ); NavigationItemControl nic = NavigationItemControl.createInstance( ni ); if ( !nic.userHasAccess() ) { return commands; } currentTheme = BrandingUtil.getCurrentBrandTheme( bbCtxt.getHostName() ); branding = BrandingManager.Factory.getInstance().getBrandingByHostNameAndRole( bbCtxt.getHostName(), null ); ColorPaletteManager colorPaletteManager = ColorPaletteManagerFactory.getInstance(); colorPalette = colorPaletteManager.getColorPaletteByBrandingId( branding.getId() ); PortalBrandingDbLoader pbLoader = PortalBrandingDbLoader.Default.getInstance(); portalBrandings = pbLoader.loadByThemeId( currentTheme.getId() ); } catch ( Exception e ) { throw new PersistenceRuntimeException( e ); } for ( PortalBranding pb : portalBrandings ) { if ( pb.isDefault() ) { currentPortalBranding = pb; break; } } for ( Theme theme : themes ) { String themeExtRef = theme.getExtRef(); HashMap<String, String> params = new HashMap<String, String>(); params.put( "cmd", "save" ); params.put( "brand_id", branding.getId().getExternalString() ); params.put( "pageType", "Navigation" ); params.put( "usesCustomBrand", "true" ); params.put( "startThemeExtRef", currentTheme.getExtRef() ); - params.put( "startPaletteExtRef", colorPalette.getExtRef() ); + String colorExtRef = ""; + if ( colorPalette != null ) + { + colorExtRef = colorPalette.getExtRef(); + } + params.put( "startPaletteExtRef", colorExtRef ); + params.put( "color_palette_extRef", colorExtRef ); params.put( "theme_extRef", themeExtRef ); - params.put( "color_palette_extRef", colorPalette.getExtRef() ); params.put( "deleteBrandCss", "false" ); params.put( "tabStyle", currentTheme.getTabStyle().getAbbrevString() ); params.put( "tabAlign", currentTheme.getTabAlignment().toString() ); params.put( "frameSize", currentTheme.getFrameSize().toString() ); params.put( "bannerImage_attachmentType", "AL" ); params.put( "bannerImage_fileId", currentPortalBranding.getBannerImage() ); params.put( "bannerImage_LocalFile0", "" ); params.put( "bannerImageLink", currentPortalBranding.getBannerUrl() ); params.put( "bannerAltText", currentPortalBranding.getBannerText() ); params.put( "pde_institution_role", bbCtxt.getUser().getPortalRoleId().toExternalString() ); params.put( "courseNameUsage", branding.getCourseNameUsage().toExternalString() ); params.put( NonceUtil.NONCE_KEY, NonceUtil.create( bbCtxt.getSession(), NONCE_ID, NONCE_CONTEXT ) ); commands.add( new PostCommand( themeExtRef, URI, Category.THEME, params, "multipart/form-data" ) ); } return commands; } }
false
true
public Iterable<Command> getCommands() { List<Theme> themes = ThemeManagerFactory.getInstance().getAllThemes(); Set<Command> commands = Sets.newTreeSet(); Context bbCtxt = ContextManagerFactory.getInstance().getContext(); NavigationItem ni = null; List<PortalBranding> portalBrandings = null; PortalBranding currentPortalBranding = null; Branding branding = null; ColorPalette colorPalette = null; Theme currentTheme = null; try { NavigationItemDbLoader niDbLoader = NavigationItemDbLoader.Default.getInstance(); ni = niDbLoader.loadByInternalHandle( "pa_customize_brand" ); NavigationItemControl nic = NavigationItemControl.createInstance( ni ); if ( !nic.userHasAccess() ) { return commands; } currentTheme = BrandingUtil.getCurrentBrandTheme( bbCtxt.getHostName() ); branding = BrandingManager.Factory.getInstance().getBrandingByHostNameAndRole( bbCtxt.getHostName(), null ); ColorPaletteManager colorPaletteManager = ColorPaletteManagerFactory.getInstance(); colorPalette = colorPaletteManager.getColorPaletteByBrandingId( branding.getId() ); PortalBrandingDbLoader pbLoader = PortalBrandingDbLoader.Default.getInstance(); portalBrandings = pbLoader.loadByThemeId( currentTheme.getId() ); } catch ( Exception e ) { throw new PersistenceRuntimeException( e ); } for ( PortalBranding pb : portalBrandings ) { if ( pb.isDefault() ) { currentPortalBranding = pb; break; } } for ( Theme theme : themes ) { String themeExtRef = theme.getExtRef(); HashMap<String, String> params = new HashMap<String, String>(); params.put( "cmd", "save" ); params.put( "brand_id", branding.getId().getExternalString() ); params.put( "pageType", "Navigation" ); params.put( "usesCustomBrand", "true" ); params.put( "startThemeExtRef", currentTheme.getExtRef() ); params.put( "startPaletteExtRef", colorPalette.getExtRef() ); params.put( "theme_extRef", themeExtRef ); params.put( "color_palette_extRef", colorPalette.getExtRef() ); params.put( "deleteBrandCss", "false" ); params.put( "tabStyle", currentTheme.getTabStyle().getAbbrevString() ); params.put( "tabAlign", currentTheme.getTabAlignment().toString() ); params.put( "frameSize", currentTheme.getFrameSize().toString() ); params.put( "bannerImage_attachmentType", "AL" ); params.put( "bannerImage_fileId", currentPortalBranding.getBannerImage() ); params.put( "bannerImage_LocalFile0", "" ); params.put( "bannerImageLink", currentPortalBranding.getBannerUrl() ); params.put( "bannerAltText", currentPortalBranding.getBannerText() ); params.put( "pde_institution_role", bbCtxt.getUser().getPortalRoleId().toExternalString() ); params.put( "courseNameUsage", branding.getCourseNameUsage().toExternalString() ); params.put( NonceUtil.NONCE_KEY, NonceUtil.create( bbCtxt.getSession(), NONCE_ID, NONCE_CONTEXT ) ); commands.add( new PostCommand( themeExtRef, URI, Category.THEME, params, "multipart/form-data" ) ); } return commands; }
public Iterable<Command> getCommands() { List<Theme> themes = ThemeManagerFactory.getInstance().getAllThemes(); Set<Command> commands = Sets.newTreeSet(); Context bbCtxt = ContextManagerFactory.getInstance().getContext(); NavigationItem ni = null; List<PortalBranding> portalBrandings = null; PortalBranding currentPortalBranding = null; Branding branding = null; ColorPalette colorPalette = null; Theme currentTheme = null; try { NavigationItemDbLoader niDbLoader = NavigationItemDbLoader.Default.getInstance(); ni = niDbLoader.loadByInternalHandle( "pa_customize_brand" ); NavigationItemControl nic = NavigationItemControl.createInstance( ni ); if ( !nic.userHasAccess() ) { return commands; } currentTheme = BrandingUtil.getCurrentBrandTheme( bbCtxt.getHostName() ); branding = BrandingManager.Factory.getInstance().getBrandingByHostNameAndRole( bbCtxt.getHostName(), null ); ColorPaletteManager colorPaletteManager = ColorPaletteManagerFactory.getInstance(); colorPalette = colorPaletteManager.getColorPaletteByBrandingId( branding.getId() ); PortalBrandingDbLoader pbLoader = PortalBrandingDbLoader.Default.getInstance(); portalBrandings = pbLoader.loadByThemeId( currentTheme.getId() ); } catch ( Exception e ) { throw new PersistenceRuntimeException( e ); } for ( PortalBranding pb : portalBrandings ) { if ( pb.isDefault() ) { currentPortalBranding = pb; break; } } for ( Theme theme : themes ) { String themeExtRef = theme.getExtRef(); HashMap<String, String> params = new HashMap<String, String>(); params.put( "cmd", "save" ); params.put( "brand_id", branding.getId().getExternalString() ); params.put( "pageType", "Navigation" ); params.put( "usesCustomBrand", "true" ); params.put( "startThemeExtRef", currentTheme.getExtRef() ); String colorExtRef = ""; if ( colorPalette != null ) { colorExtRef = colorPalette.getExtRef(); } params.put( "startPaletteExtRef", colorExtRef ); params.put( "color_palette_extRef", colorExtRef ); params.put( "theme_extRef", themeExtRef ); params.put( "deleteBrandCss", "false" ); params.put( "tabStyle", currentTheme.getTabStyle().getAbbrevString() ); params.put( "tabAlign", currentTheme.getTabAlignment().toString() ); params.put( "frameSize", currentTheme.getFrameSize().toString() ); params.put( "bannerImage_attachmentType", "AL" ); params.put( "bannerImage_fileId", currentPortalBranding.getBannerImage() ); params.put( "bannerImage_LocalFile0", "" ); params.put( "bannerImageLink", currentPortalBranding.getBannerUrl() ); params.put( "bannerAltText", currentPortalBranding.getBannerText() ); params.put( "pde_institution_role", bbCtxt.getUser().getPortalRoleId().toExternalString() ); params.put( "courseNameUsage", branding.getCourseNameUsage().toExternalString() ); params.put( NonceUtil.NONCE_KEY, NonceUtil.create( bbCtxt.getSession(), NONCE_ID, NONCE_CONTEXT ) ); commands.add( new PostCommand( themeExtRef, URI, Category.THEME, params, "multipart/form-data" ) ); } return commands; }
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Coordinator.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Coordinator.java index 85d1fd1b..12c86413 100644 --- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Coordinator.java +++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Coordinator.java @@ -1,1324 +1,1324 @@ /******************************************************************************* * Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management * Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. ******************************************************************************/ package de.tuilmenau.ics.fog.routing.hierarchical.management; import java.io.Serializable; import java.math.BigInteger; import java.util.LinkedList; import java.util.List; import de.tuilmenau.ics.fog.FoGEntity; import de.tuilmenau.ics.fog.facade.Connection; import de.tuilmenau.ics.fog.facade.Description; import de.tuilmenau.ics.fog.facade.Name; import de.tuilmenau.ics.fog.packets.hierarchical.DiscoveryEntry; import de.tuilmenau.ics.fog.packets.hierarchical.AnnounceRemoteCluster; import de.tuilmenau.ics.fog.packets.hierarchical.addressing.AssignHRMID; import de.tuilmenau.ics.fog.packets.hierarchical.clustering.ClusterDiscovery; import de.tuilmenau.ics.fog.packets.hierarchical.clustering.ClusterDiscovery.NestedDiscovery; import de.tuilmenau.ics.fog.packets.hierarchical.election.BullyAnnounce; import de.tuilmenau.ics.fog.packets.hierarchical.election.BullyLeave; import de.tuilmenau.ics.fog.packets.hierarchical.topology.RoutingInformation; import de.tuilmenau.ics.fog.routing.Route; import de.tuilmenau.ics.fog.routing.hierarchical.*; import de.tuilmenau.ics.fog.routing.hierarchical.election.BullyPriority; import de.tuilmenau.ics.fog.routing.hierarchical.properties.RequestClusterParticipationProperty; import de.tuilmenau.ics.fog.routing.hierarchical.properties.RequestClusterParticipationProperty.ClusterMemberDescription; import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID; import de.tuilmenau.ics.fog.routing.naming.hierarchical.L2Address; import de.tuilmenau.ics.fog.ui.Logging; import de.tuilmenau.ics.fog.util.Tuple; /** * This class is used for a coordinator instance and can be used on all hierarchy levels. * A cluster's elector instance is responsible for creating instances of this class. */ public class Coordinator extends ControlEntity implements ICluster, Localization { /** * This is the GUI specific cluster counter, which allows for globally unique cluster IDs. * It's only used within the GUI. */ private static int sGUICoordinatorID = 0; /** * List of already known neighbor coordinators */ private LinkedList<Name> mConnectedNeighborCoordinators = new LinkedList<Name>(); /** * Stores the simulation timestamp of the last "share phase" */ private double mTimeOfLastSharePhase = 0; /** * Stores the routes which should be shared with cluster members. */ private LinkedList<RoutingEntry> mSharedRoutes = new LinkedList<RoutingEntry>(); /** * Stores whether the data of the "shared phase" has changed or not. */ private boolean mSharedRoutesHaveChanged = false; /** * Stores the parent cluster, which is managed by this coordinator instance. */ private Cluster mParentCluster = null;; /** * Stores if the initial clustering has already finished */ private boolean mInitialClusteringFinished = false; /** * This is the coordinator counter, which allows for globally (related to a physical simulation machine) unique coordinator IDs. */ private static long sNextFreeCoordinatorID = 1; /** * Count the outgoing connections */ private int mCounterOutgoingConnections = 0; private Name mCoordinatorName = null; private LinkedList<Long> mBouncedAnnounces = new LinkedList<Long>(); private LinkedList<AnnounceRemoteCluster> mReceivedAnnouncements; /** * */ private static final long serialVersionUID = 6824959379284820010L; /** * The constructor for a cluster object. Usually, it is called by a cluster's elector instance * * @param pCluster the parent cluster instance */ public Coordinator(Cluster pCluster) { // use the HRMController reference and the hierarchy level from the cluster super(pCluster.mHRMController, pCluster.getHierarchyLevel()); mParentCluster = pCluster; // create an ID for the cluster setCoordinatorID((int)createCoordinatorID()); // clone the HRMID of the managed cluster because it can already contain the needed HRMID prefix address setHRMID(this, mParentCluster.getHRMID().clone()); // register itself as coordinator for the managed cluster mParentCluster.setCoordinator(this); // register at HRMController's internal database mHRMController.registerCoordinator(this); Logging.log(this, "CREATED"); } /** * Generates a new ClusterID * * @return the ClusterID */ static private synchronized long createCoordinatorID() { // get the current unique ID counter long tResult = sNextFreeCoordinatorID * idMachineMultiplier(); // make sure the next ID isn't equal sNextFreeCoordinatorID++; return tResult; } /** * Creates a new HRMID for a cluster member depending on the given member number. * * @param pMemberNumber the member number * @return the new HRMID for the cluster member */ private HRMID createClusterMemberAddress(int pMemberNumber) { HRMID tHRMID = getHRMID().clone(); // transform the member number to a BigInteger BigInteger tAddress = BigInteger.valueOf(pMemberNumber); // set the member number for the given hierarchy level tHRMID.setLevelAddress(super.getHierarchyLevel(), tAddress); // some debug outputs if (HRMConfig.DebugOutput.GUI_HRMID_UPDATES){ Logging.log(this, "Set " + tAddress + " on hierarchy level " + super.getHierarchyLevel().getValue() + " for HRMID " + tHRMID.toString()); Logging.log(this, "Created for a cluster member the NEW HRMID=" + tHRMID.toString()); } return tHRMID; } /** * Returns the machine-local CoordinatorID (excluding the machine specific multiplier) * * @return the machine-local CoordinatorID */ public long getGUICoordinatorID() { return getCoordinatorID() / idMachineMultiplier(); } /** * This function is called for distributing HRMIDs among the cluster members. */ public void signalAddressDistribution() { /** * The following value is used to assign monotonously growing addresses to all cluster members. * The addressing has to start with "1". */ int tNextClusterMemberAddress = 1; Logging.log(this, "DISTRIBUTING ADDRESSES to entities on level " + (getHierarchyLevel().getValue() - 1) + "/" + (HRMConfig.Hierarchy.HEIGHT - 1)); /** * Assign ourself an HRMID address */ // are we at the base level? if(super.getHierarchyLevel().isBaseLevel()) { // create new HRMID for ourself HRMID tOwnAddress = createClusterMemberAddress(tNextClusterMemberAddress++); Logging.log(this, " ..setting local HRMID " + tOwnAddress.toString()); //HINT: don't update the HRMID of the coordinator here! // update the HRMID of the managed cluster by direct call and avoid additional communication overhead mParentCluster.setHRMID(this, tOwnAddress); } /** * Distribute AssignHRMID packets among the cluster members */ LinkedList<ComChannel> tComChannels = mParentCluster.getComChannels(); Logging.log(this, " ..distributing HRMIDs among cluster members: " + tComChannels); for(ComChannel tComChannel : tComChannels) { //TODO: don't send this update in a loop to ourself! //TODO: check if cluster members already have an address and distribute only free addresses here // create new HRMID for cluster member HRMID tHRMID = createClusterMemberAddress(tNextClusterMemberAddress++); // store the HRMID under which the peer will be addressable from now tComChannel.setPeerHRMID(tHRMID); if ((tComChannel.getPeerHRMID() != null) && (!tComChannel.getPeerHRMID().equals(tHRMID))){ Logging.log(this, " ..replacing HRMID " + tComChannel.getPeerHRMID().toString() + " and assign new HRMID " + tHRMID.toString() + " to " + tComChannel.getPeerL2Address()); }else Logging.log(this, " ..assigning new HRMID " + tHRMID.toString() + " to " + tComChannel.getPeerL2Address()); // create new AssignHRMID packet for the cluster member AssignHRMID tAssignHRMID = new AssignHRMID(mHRMController.getNodeName(), tComChannel.getPeerHRMID(), tHRMID); // register this new HRMID in the local HRS and create a mapping to the right L2Address Logging.log(this, " ..creating MAPPING " + tHRMID.toString() + " to " + tComChannel.getPeerL2Address()); mHRMController.getHRS().mapHRMIDToL2Address(tHRMID, tComChannel.getPeerL2Address()); // share the route to this cluster member with all other cluster members shareRouteToClusterMember(tComChannel); // send the packet tComChannel.sendPacket(tAssignHRMID); } } /** * Shares a route to a cluster cluster member with other cluster members * * @param pClusterMemberChannel the cluster member to whom we have a sharable route */ private void shareRouteToClusterMember(ComChannel pClusterMemberChannel) { // determine the HRMID of the cluster member HRMID tMemberHRMID = pClusterMemberChannel.getPeerHRMID(); // are we on base hierarchy level? if (getHierarchyLevel().getValue() == 1){ // TODO: isBaseLevel()){ // create the new routing table entry RoutingEntry tRoutingEntry = RoutingEntry.createRouteToDirectNeighbor(tMemberHRMID, 0 /* TODO */, 1 /* TODO */, RoutingEntry.INFINITE_DATARATE /* TODO */); // define the L2 address of the next hop in order to let "addHRMRoute" trigger the HRS instance the creation of new HRMID-to-L2ADDRESS mapping entry tRoutingEntry.setNextHopL2Address(pClusterMemberChannel.getPeerL2Address()); Logging.log(this, "SHARING ROUTE: " + tRoutingEntry); // add the entry to the local routing table mHRMController.addHRMRoute(tRoutingEntry); // store the entry for route sharing with cluster members synchronized (mSharedRoutes){ /** * Check for duplicates */ if (HRMConfig.Routing.AVOID_DUPLICATES_IN_ROUTING_TABLES){ boolean tRestartNeeded; do{ tRestartNeeded = false; for (RoutingEntry tEntry: mSharedRoutes){ // have we found a route to the same destination which uses the same next hop? //TODO: what about multiple links to the same next hop? if ((tEntry.getDest().equals(tRoutingEntry.getDest())) /* same destination? */ && (tEntry.getNextHop().equals(tRoutingEntry.getNextHop())) /* same next hop? */){ Logging.log(this, "REMOVING DUPLICATE: " + tEntry); // remove the route mSharedRoutes.remove(tEntry); // mark "shared phase" data as changed mSharedRoutesHaveChanged = true; // force a restart at the beginning of the routing table tRestartNeeded = true; //TODO: use a better(scalable) method here for removing duplicates break; } } }while(tRestartNeeded); } /** * Add the entry to the shared routing table */ mSharedRoutes.add(tRoutingEntry);//TODO: use a database per cluster member here // mark "shared phase" data as changed mSharedRoutesHaveChanged = true; } }else{ //TODO Logging.log(this, "IMPLEMENT ME - SHARING ROUTE TO: " + pClusterMemberChannel); } } /** * Checks if the "share phase" should be started or not * * @return true if the "share phase" should be started, otherwise false */ private boolean sharePhaseHasTimeout() { // determine the time between two "share phases" double tDesiredTimePeriod = mHRMController.getPeriodSharePhase(getHierarchyLevel().getValue() - 1); // determine the time when a "share phase" has to be started double tTimeNextSharePhase = mTimeOfLastSharePhase + tDesiredTimePeriod; // determine the current simulation time from the HRMCotnroller instance double tCurrentSimulationTime = mHRMController.getSimulationTime(); if (HRMConfig.DebugOutput.GUI_SHOW_TIMING_ROUTE_DISTRIBUTION){ Logging.log(this, "Checking for timeout of \"share phase\": desired time period is " + tDesiredTimePeriod + ", " + tCurrentSimulationTime + " > " + tTimeNextSharePhase + "? -> " + (tCurrentSimulationTime >= tTimeNextSharePhase)); } return (tCurrentSimulationTime >= tTimeNextSharePhase); } /** * Determines if new "share phase" data is available * * @return true if new data is available, otherwise false */ private boolean hasNewSharePhaseData() { boolean tResult = false; synchronized (mSharedRoutes){ tResult = mSharedRoutesHaveChanged; } return tResult; } /** * This function implements the "share phase". * It distributes locally stored sharable routing data among the known cluster members */ public void sharePhase() { // should we start the "share phase"? if (sharePhaseHasTimeout()){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE with cluster members on level " + (getHierarchyLevel().getValue() - 1) + "/" + (HRMConfig.Hierarchy.HEIGHT - 1)); } // store the time of this "share phase" mTimeOfLastSharePhase = mHRMController.getSimulationTime(); if ((!HRMConfig.Routing.PERIODIC_SHARE_PHASES) && (!hasNewSharePhaseData())){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE skipped because routing data hasn't changed since last signaling round"); } return; } /** * SHARE PHASE */ // determine own local cluster address HRMID tOwnClusterAddress = mParentCluster.getHRMID(); if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, " ..distributing as " + tOwnClusterAddress.toString() + " aggregated ROUTES among cluster members: " + mParentCluster.getComChannels()); } synchronized (mSharedRoutes){ // send the routing information to cluster members for(ComChannel tClusterMember : mParentCluster.getComChannels()) { RoutingInformation tRoutingInformationPacket = new RoutingInformation(tOwnClusterAddress, tClusterMember.getPeerHRMID()); // are we on base hierarchy level? if (getHierarchyLevel().getValue() == 1){ // TODO: isBaseLevel()){ /** * ADD ROUTES: routes from the cluster member to this node for every registered local HRMID. */ // determine the L2 address of this physical node L2Address tPhysNodeL2Address = mHRMController.getHRS().getCentralFNL2Address(); // iterate over all HRMIDs which are registered for this physical node for (HRMID tHRMID : mHRMController.getOwnHRMIDs()){ // create entry for cluster internal routing towards us RoutingEntry tRouteFromClusterMemberToHere = RoutingEntry.createRouteToDirectNeighbor(tHRMID, 0 /* TODO */, 1 /* TODO */, RoutingEntry.INFINITE_DATARATE /* TODO */); // define the L2 address of the next hop in order to let the receiver store it in its HRMID-to-L2ADDRESS mapping tRouteFromClusterMemberToHere.setNextHopL2Address(tPhysNodeL2Address); // add the route in the "share phase" signaling tRoutingInformationPacket.addRoute(tRouteFromClusterMemberToHere); } //TODO: need routing graph here! //TODO: routes to other cluster members }else{ //TODO: implement me } /** * Send the routing data to the cluster member */ // do we have interesting routing information? if (tRoutingInformationPacket.getRoutes().size() > 0){ tClusterMember.sendPacket(tRoutingInformationPacket); }else{ // no routing information -> no packet is sent } } /** * mark "share phase" data as known */ mSharedRoutesHaveChanged = false; } }else{ // share phase shouldn't be started, we have to wait until next trigger } } /** * This function implements the "report phase". * It sends locally stored sharable routing data to the superior coordinator */ public void reportPhase() { if (!getHierarchyLevel().isHighest()){ }else{ // we are the highest hierarchy level, no one to send topology reports to } } /** * EVENT: "eventCoordinatorRoleInvalid", triggered by the Elector, the reaction is: * 1.) create signaling packet "BullyLeave" * 2.) send the packet to the superior coordinator */ public void eventCoordinatorRoleInvalid() { Logging.log(this, "============ EVENT: Coordinator_Role_Invalid"); /** * Inform all superior clusters about the event and trigger the invalidation of this coordinator instance -> we leave all Bully elections because we are no longer a possible election winner */ if (!getHierarchyLevel().isHighest()){ // create signaling packet for signaling that we leave the Bully group BullyLeave tBullyLeavePacket = new BullyLeave(mHRMController.getNodeName(), getPriority()); sendAllSuperiorClusters(tBullyLeavePacket, true); }else{ Logging.log(this, "eventCoordinatorRoleInvalid() skips further signaling because hierarchy end is already reached at: " + (getHierarchyLevel().getValue() - 1)); } /** * Unregister from local databases */ Logging.log(this, "============ Destroying this coordinator now..."); // unregister itself as coordinator for the managed cluster mParentCluster.setCoordinator(null); // unregister from HRMController's internal database mHRMController.unregisterCoordinator(this); } /** * @param pBullyLeavePacket */ private void sendAllSuperiorClusters(Serializable pPacket, boolean pIncludeLoopback) { // get all communication channels LinkedList<ComChannel> tComChannels = getComChannels(); // get the L2Addres of the local host L2Address tLocalL2Address = mHRMController.getHRS().getCentralFNL2Address(); Logging.log(this, "Sending BROADCASTS from " + tLocalL2Address + " the packet " + pPacket + " to " + tComChannels.size() + " communication channels"); for(ComChannel tComChannel : tComChannels) { boolean tIsLoopback = tLocalL2Address.equals(tComChannel.getPeerL2Address()); if (!tIsLoopback){ Logging.log(this, " ..to " + tComChannel); }else{ Logging.log(this, " ..to LOOPBACK " + tComChannel); } if ((HRMConfig.Hierarchy.SIGNALING_INCLUDES_LOCALHOST) || (pIncludeLoopback) || (!tIsLoopback)){ // send the packet to one of the possible cluster members tComChannel.sendPacket(pPacket); }else{ Logging.log(this, " ..skipping " + (tIsLoopback ? "LOOPBACK CHANNEL" : "")); } } } /** * EVENT: "announced", triggered by Elector if the election was won and this coordinator was announced to all cluster members */ public void eventAnnouncedAsCoordinator() { /** * AUTO ADDRESS DISTRIBUTION */ if (HRMConfig.Addressing.ASSIGN_AUTOMATICALLY){ Logging.log(this, "EVENT ANNOUNCED - triggering address assignment for " + getComChannels().size() + " cluster members"); signalAddressDistribution(); } //TODO: ?? mHRMController.setSourceIntermediateCluster(this, getCluster()); /** * AUTO CLUSTERING */ if(!getHierarchyLevel().isHighest()) { if (HRMConfig.Hierarchy.CONTINUE_AUTOMATICALLY){ Logging.log(this, "EVENT ANNOUNCED - triggering clustering of this cluster's coordinator and its neighbors"); // start the clustering of this cluster's coordinator and its neighbors if it wasn't already triggered by another coordinator if (!isClustered()){ cluster(); }else{ Logging.warn(this, "Clustering is already finished for this hierarchy level, skipping cluster-request"); } } } } /** * Clusters the superior hierarchy level or tries to join an already existing superior cluster */ public void cluster() { Logging.log(this, "\n\n\n################ CLUSTERING STARTED"); /** * Try to find a matching local cluster on the superior hierarchy level */ boolean tSuperiorClusterFound = false; for(Cluster tCluster : mHRMController.getAllClusters(getHierarchyLevel())) { if (joinSuperiorCluster(tCluster)){ // we joined the superior cluster and should end the search for a superior coordinator tSuperiorClusterFound = true; break; } } /** * Explore the neighborhood and create a new superior cluster */ if (!tSuperiorClusterFound){ exploreNeighborhodAndCreateSuperiorCluster(); } } /** * Tries to join a superior cluster * * @param pSuperiorCluster the possible new superior cluster * * @return true or false to indicate success/error */ private boolean joinSuperiorCluster(ControlEntity pSuperiorCluster) { Logging.log(this, "\n\n\n################ JOINING EXISTING SUPERIOR CLUSTER " + pSuperiorCluster); return false; } /** * EVENT: initial clustering has finished */ private void eventInitialClusteringFinished() { // mark initial clustering as "finished" mInitialClusteringFinished = true; } /** * Returns if the initial clustering has already finished * * @return true or false */ public boolean isClustered() { return mInitialClusteringFinished; } //TODO: fix this +1 stuff @Override public HierarchyLevel getHierarchyLevel() { return new HierarchyLevel(this, super.getHierarchyLevel().getValue() + 1); } /** * Returns the Bully priority of the parent cluster * * @return the Bully priority */ @Override public BullyPriority getPriority() { // return the Bully priority of the managed cluster object return mParentCluster.getPriority(); } /** * Sets a new Bully priority * * @param pPriority the new Bully priority */ @Override public void setPriority(BullyPriority pPriority) { if (!getPriority().equals(pPriority)){ Logging.err(this, "Updating Bully priority from " + getPriority() + " to " + pPriority); }else{ Logging.log(this, "Trying to set same Bully priority " + getPriority()); } // update the Bully priority of the parent cluster, which is managed by this coordinator mParentCluster.setPriority(pPriority); } /** * Returns a reference to the cluster, which this coordinator manages. * * @return the managed cluster */ public Cluster getCluster() { return mParentCluster; } /** * Returns the unique ID of the parental cluster * * @return the unique cluster ID */ @Override public Long getClusterID() { return mParentCluster.getClusterID(); } /** * Checks if there already exists a connection to a neighbor coordinator * * @param pCoordinatorName the name of the neighbor coordinator * * @return true or false */ private boolean isConnectedToNeighborCoordinator(Name pCoordinatorName) { boolean tResult = false; synchronized (mConnectedNeighborCoordinators) { tResult = mConnectedNeighborCoordinators.contains(pCoordinatorName); } return tResult; } /** * Registers an already existing connection to a neighbor coordinator in order to avoid connection duplicates * * @param pCoordinatorName the name of the neighbor coordinator */ private void registerConnectionToNeighborCoordinator(Name pCoordinatorName) { synchronized (mConnectedNeighborCoordinators) { mConnectedNeighborCoordinators.add(pCoordinatorName); } } /** * Creates a cluster consisting of this coordinator and neighbor coordinators by the following steps: * 1.) querying the ARG from the HRMController for neighbor clusters within the given max. radius * 2.) trigger event "detectedNeighborCoordinator" with increasing radius */ private void exploreNeighborhodAndCreateSuperiorCluster() { Logging.log(this, "\n\n\n################ EXPLORATION STARTED on hierarchy level " + getHierarchyLevel().getValue()); // was the clustering already triggered? if (!isClustered()){ // are we already at the highest hierarchy level? if (!getHierarchyLevel().isHighest()){ int tMaxRadius = HRMConfig.Routing.EXPANSION_RADIUS; Logging.log(this, "Maximum radius is " + tMaxRadius); /** * Create the cluster ID for the new cluster, which should consist of the control entities we connect to in the next steps */ Long tIDFutureCluster = Cluster.createClusterID(); // get all known neighbor clusters ordered by their radius to the parent cluster List<AbstractRoutingGraphNode> tNeighborClustersForClustering = mHRMController.getNeighborClustersOrderedByRadiusInARG(mParentCluster); Logging.log(this, " ..neighborhood ordered by radius: " + tNeighborClustersForClustering); /** * count from radius 1 to max. radius and connect to each cluster candidate */ for(int tRadius = 1; tRadius <= tMaxRadius; tRadius++) { Logging.log(this, "\n>>> Exploring neighbors with radius (" + tRadius + "/" + tMaxRadius + ")"); // create list for storing the found neighbor clusters, which have a cluster distance equal to the current radius value List<AbstractRoutingGraphNode> tSelectedNeighborClusters = new LinkedList<AbstractRoutingGraphNode>(); List<AbstractRoutingGraphNode> tNeighborClustersForClustering_RemoveList = new LinkedList<AbstractRoutingGraphNode>(); /** * Iterate over all cluster candidates and determines the logical distance of each found candidate */ for(AbstractRoutingGraphNode tClusterCandidate : tNeighborClustersForClustering) { // is the found neighbor a Cluster object? if(tClusterCandidate instanceof Cluster) { if (tRadius == 1){ // add this Cluster object as cluster candidate because it obviously has a logical distance of 1 Logging.log(this, " ..[r=" + tRadius + "]: found Cluster candidate: " + tClusterCandidate); tSelectedNeighborClusters.add(tClusterCandidate); // remove this candidate from the global list tNeighborClustersForClustering_RemoveList.add(tClusterCandidate); }else{ // found a Cluster object but the radius is already beyond 1 } } else { // is the found neighbor a ClusterProxy object? if (tClusterCandidate instanceof ClusterProxy){ // get the proxy for this cluster ClusterProxy tClusterCandidateProxy = (ClusterProxy)tClusterCandidate; // are we already connected to this candidate? if (!isConnectedToNeighborCoordinator(tClusterCandidateProxy.getCoordinatorHostName())){ // get the logical distance to the neighbor int tNeighborClusterDistance = mHRMController.getClusterDistance(tClusterCandidateProxy); // should we connect to the found cluster candidate? if ((tNeighborClusterDistance > 0) && (tNeighborClusterDistance <= tRadius)) { // add this candidate to the list of connection targets Logging.log(this, " ..[r=" + tRadius + "]: found ClusterProxy candidate: " + tClusterCandidate); tSelectedNeighborClusters.add(tClusterCandidateProxy); // remove this candidate from the global list tNeighborClustersForClustering_RemoveList.add(tClusterCandidate); }else{ // the logical distance doesn't equal to the current radius value if (tNeighborClusterDistance > tRadius){ // we have already passed the last possible candidate -> we continue the for-loop continue; } } } }else{ Logging.err(this, "Found unsupported neighbor: " + tClusterCandidate); } } } /** * Remove all processed cluster candidates from the global candidate list in order to reduce processing time */ for (AbstractRoutingGraphNode tRemoveCandidate : tNeighborClustersForClustering_RemoveList){ tNeighborClustersForClustering.remove(tRemoveCandidate); } /** * Connect to all found cluster candidates */ for(AbstractRoutingGraphNode tNeighborCluster : tSelectedNeighborClusters) { if(tNeighborCluster instanceof ControlEntity) { ControlEntity tNeighborClusterControlEntity = (ControlEntity)tNeighborCluster; eventDetectedNeighborCoordinator(tNeighborClusterControlEntity, tIDFutureCluster); }else{ Logging.err(this, "Unsupported neighbor object: " + tNeighborCluster); } } } /** * Mark all local coordinators for this hierarchy level as "clustered" */ for(Coordinator tLocalCoordinator : mHRMController.getAllCoordinators(getHierarchyLevel())) { // trigger event "finished clustering" tLocalCoordinator.eventInitialClusteringFinished(); } }else{ Logging.warn(this, "CLUSTERING SKIPPED, no clustering on highest hierarchy level " + getHierarchyLevel().getValue() + " needed"); } }else{ Logging.warn(this, "Clustering was already triggered, clustering will be maintained"); } } /** * EVENT: detected a neighbor coordinator, we react on this event by the following steps: * 1.) use "RequestClusterParticipationProperty" for every connection to inform about the new cluster * * @param pNeighborCluster the found neighbor cluster whose coordinator is a neighbor of this one * @param pIDForFutureCluster the clusterID for the common cluster */ private void eventDetectedNeighborCoordinator(ControlEntity pNeighborCluster, Long pIDForFutureCluster) { // get the recursive FoG layer FoGEntity tFoGLayer = (FoGEntity) mHRMController.getNode().getLayer(FoGEntity.class); // get the central FN of this node L2Address tThisHostL2Address = mHRMController.getHRS().getL2AddressFor(tFoGLayer.getCentralFN()); Logging.info(this, "\n\n\n############## FOUND INFERIOR NEIGHBOR CLUSTER " + pNeighborCluster + " FOR " + tThisHostL2Address); /** * get the name of the target coordinator name */ - Name tTargetCoordinatorHostName = ((ICluster)pNeighborCluster).getCoordinatorHostName(); + Name tNeighborCoordinatorHostName = ((ICluster)pNeighborCluster).getCoordinatorHostName(); - if(!isConnectedToNeighborCoordinator(tTargetCoordinatorHostName)) { + if(!isConnectedToNeighborCoordinator(tNeighborCoordinatorHostName)) { // store the connection to avoid connection duplicates during later processing - registerConnectionToNeighborCoordinator(tTargetCoordinatorHostName); + registerConnectionToNeighborCoordinator(tNeighborCoordinatorHostName); HierarchyLevel tTargetClusterHierLvl = new HierarchyLevel(this, pNeighborCluster.getHierarchyLevel().getValue() + 1); ControlEntity tNeighborClusterControlEntity = (ControlEntity)pNeighborCluster; /** * Describe the common cluster */ Logging.log(this, " ..creating cluster description"); // create the cluster description RequestClusterParticipationProperty tRequestClusterParticipationProperty = new RequestClusterParticipationProperty(pIDForFutureCluster, tTargetClusterHierLvl, pNeighborCluster.getCoordinatorID()); /** * Create communication session */ Logging.log(this, " ..creating new communication session"); ComSession tComSession = new ComSession(mHRMController, false, getHierarchyLevel()); /** * Iterate over all local coordinators on this hierarchy level and add them as already known cluster members to the cluster description */ Logging.log(this, " ..iterate over all coordinators on hierarchy level: " + (getHierarchyLevel().getValue() - 1)); // store how many local coordinators on this hierarchy level were found int tKnownLocalCoordinatorsOnThisHierarchyLevel = 0; for(Coordinator tLocalCoordinator : mHRMController.getAllCoordinators(getHierarchyLevel())) { tKnownLocalCoordinatorsOnThisHierarchyLevel++; Logging.log(this, " ..found [" + tKnownLocalCoordinatorsOnThisHierarchyLevel + "] : " + tLocalCoordinator); /** * Create communication channel */ Logging.log(this, " ..creating new communication channel"); ComChannel tComChannel = new ComChannel(mHRMController, ComChannel.Direction.OUT, tLocalCoordinator, tComSession); tComChannel.setRemoteClusterName(new ClusterName(mHRMController, pNeighborCluster.getHierarchyLevel(), pNeighborCluster.getCoordinatorID(), pIDForFutureCluster /* HINT: we communicate with the new cluster -> us clusterID of new cluster */)); tComChannel.setPeerPriority(pNeighborCluster.getPriority()); // do we know the neighbor coordinator? (we check for a known coordinator of the neighbor cluster) if(tNeighborClusterControlEntity.superiorCoordinatorHostL2Address() != null) { Cluster tCoordinatorCluster = tLocalCoordinator.getCluster(); /** * Describe the cluster member */ Logging.log(this, " ..creating cluster member description for the found cluster " + tCoordinatorCluster); ClusterMemberDescription tClusterMemberDescription = tRequestClusterParticipationProperty.addClusterMember(tCoordinatorCluster.getClusterID(), tCoordinatorCluster.getCoordinatorID(), tCoordinatorCluster.getPriority()); tClusterMemberDescription.setSourceName(mHRMController.getNodeName()); tClusterMemberDescription.setSourceL2Address(tThisHostL2Address); /** * Iterate over all known neighbors of the current cluster member: we inform the connection target about this neighborhood topology */ for(ControlEntity tClusterMemberNeighbor: tLocalCoordinator.getCluster().getNeighborsARG()) { ICluster tIClusterNeighbor = (ICluster)tClusterMemberNeighbor; DiscoveryEntry tDiscoveryEntry = new DiscoveryEntry(tClusterMemberNeighbor.getCoordinatorID(), tIClusterNeighbor.getCoordinatorHostName(), tClusterMemberNeighbor.getClusterID(), tClusterMemberNeighbor.superiorCoordinatorHostL2Address(), tClusterMemberNeighbor.getHierarchyLevel()); tDiscoveryEntry.setPriority(tClusterMemberNeighbor.getPriority()); if(tLocalCoordinator.getPathToCoordinator(tLocalCoordinator.getCluster(), tIClusterNeighbor) != null) { for(RoutingServiceLinkVector tVector : tLocalCoordinator.getPathToCoordinator(tLocalCoordinator.getCluster(), tIClusterNeighbor)) { tDiscoveryEntry.addRoutingVectors(tVector); } } tClusterMemberDescription.addDiscoveryEntry(tDiscoveryEntry); } }else{ Logging.err(this, "eventDetectedNeighborCoordinator() didn't found the L2Address of the coordinator for: " + tNeighborClusterControlEntity); } } /** * Create connection requirements */ Description tConnectionRequirements = mHRMController.createHRMControllerDestinationDescription(); tConnectionRequirements.set(tRequestClusterParticipationProperty); ClusterDiscovery tBigDiscovery = new ClusterDiscovery(mHRMController.getNodeName()); /** * Connect to the neighbor coordinator */ Connection tConnection = null; - Logging.log(this, " ..CONNECTING to: " + tTargetCoordinatorHostName + " with requirements: " + tConnectionRequirements); - tConnection = tFoGLayer.connect(tTargetCoordinatorHostName, tConnectionRequirements, mHRMController.getNode().getIdentity()); + Logging.log(this, " ..CONNECTING to: " + tNeighborCoordinatorHostName + " with requirements: " + tConnectionRequirements); + tConnection = tFoGLayer.connect(tNeighborCoordinatorHostName, tConnectionRequirements, mHRMController.getNode().getIdentity()); Logging.log(this, " ..connect() FINISHED"); if (tConnection != null){ mCounterOutgoingConnections++; Logging.log(this, " ..starting this OUTGOING CONNECTION as nr. " + mCounterOutgoingConnections); tComSession.startConnection(null, tConnection); /** * Create and send ClusterDiscovery */ for(Coordinator tCoordinator : mHRMController.getAllCoordinators(new HierarchyLevel(this, getHierarchyLevel().getValue() - 1))) { LinkedList<Integer> tCoordinatorIDs = new LinkedList<Integer>(); for(ControlEntity tNeighbor : tCoordinator.getCluster().getNeighborsARG()) { if(tNeighbor.getHierarchyLevel().getValue() == tCoordinator.getHierarchyLevel().getValue() - 1) { tCoordinatorIDs.add(((ICluster) tNeighbor).getCoordinatorID()); } } tCoordinatorIDs.add(tCoordinator.getCluster().getCoordinatorID()); - if(!tTargetCoordinatorHostName.equals(mHRMController.getNodeName())) { + if(!tNeighborCoordinatorHostName.equals(mHRMController.getNodeName())) { int tDistance = 0; if (pNeighborCluster instanceof ClusterProxy){ ClusterProxy tClusterProxy = (ClusterProxy) pNeighborCluster; tDistance = mHRMController.getClusterDistance(tClusterProxy); } NestedDiscovery tNestedDiscovery = tBigDiscovery.new NestedDiscovery(tCoordinatorIDs, pNeighborCluster.getClusterID(), pNeighborCluster.getCoordinatorID(), pNeighborCluster.getHierarchyLevel(), tDistance); Logging.log(this, "Created " + tNestedDiscovery + " for " + pNeighborCluster); tNestedDiscovery.setOrigin(tCoordinator.getClusterID()); tNestedDiscovery.setTargetClusterID(tNeighborClusterControlEntity.superiorCoordinatorHostL2Address().getComplexAddress().longValue()); tBigDiscovery.addNestedDiscovery(tNestedDiscovery); } } // send the ClusterDiscovery to peer tComSession.write(tBigDiscovery); for(NestedDiscovery tDiscovery : tBigDiscovery.getDiscoveries()) { String tClusters = new String(); for(Cluster tCluster : mHRMController.getAllClusters()) { tClusters += tCluster + ", "; } String tDiscoveries = new String(); for(DiscoveryEntry tEntry : tDiscovery.getDiscoveryEntries()) { tDiscoveries += ", " + tEntry; } if(tDiscovery.getNeighborRelations() != null) { for(Tuple<ClusterName, ClusterName> tTuple : tDiscovery.getNeighborRelations()) { if(!mHRMController.isLinkedARG(tTuple.getFirst(), tTuple.getSecond())) { Cluster tFirstCluster = mHRMController.getClusterByID(tTuple.getFirst()); Cluster tSecondCluster = mHRMController.getClusterByID(tTuple.getSecond()); if(tFirstCluster != null && tSecondCluster != null ) { tFirstCluster.registerNeighborARG(tSecondCluster); Logging.log(this, "Connecting " + tFirstCluster + " with " + tSecondCluster); } else { Logging.warn(this, "Unable to find cluster " + tTuple.getFirst() + ":" + tFirstCluster + " or " + tTuple.getSecond() + ":" + tSecondCluster + " out of \"" + tClusters + "\", cluster discovery contained " + tDiscoveries + " and CEP is " + tComSession); } } } } else { Logging.warn(this, tDiscovery + "does not contain any neighbor relations"); } } }else{ - Logging.err(this, "eventDetectedNeighborCoordinator() wasn't able to connect to: " + tTargetCoordinatorHostName); + Logging.err(this, "eventDetectedNeighborCoordinator() wasn't able to connect to: " + tNeighborCoordinatorHostName); } }else{ - Logging.warn(this, "eventDetectedNeighborCoordinator() skips this connection request because there exist already a connection to: " + tTargetCoordinatorHostName); + Logging.warn(this, "eventDetectedNeighborCoordinator() skips this connection request because there exist already a connection to: " + tNeighborCoordinatorHostName); } } /** * EVENT: "superior cluster coordinator was announced", triggered by Elector */ public void eventSuperiorClusterCoordinatorAnnounced(BullyAnnounce pAnnouncePacket, ComChannel pComChannel) { // store superior coordinator data setSuperiorCoordinator(pComChannel, pAnnouncePacket.getSenderName(), pAnnouncePacket.getCoordinatorID(), pComChannel.getPeerL2Address()); } public void storeAnnouncement(AnnounceRemoteCluster pAnnounce) { Logging.log(this, "Storing " + pAnnounce); if(mReceivedAnnouncements == null) { mReceivedAnnouncements = new LinkedList<AnnounceRemoteCluster>(); } pAnnounce.setNegotiatorIdentification(new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.superiorCoordinatorID(), mParentCluster.getClusterID())); mReceivedAnnouncements.add(pAnnounce); } public LinkedList<Long> getBounces() { return mBouncedAnnounces; } private LinkedList<RoutingServiceLinkVector> getPathToCoordinator(ICluster pSourceCluster, ICluster pDestinationCluster) { List<Route> tCoordinatorPath = mHRMController.getHRS().getCoordinatorRoutingMap().getRoute(((ControlEntity)pSourceCluster).superiorCoordinatorHostL2Address(), ((ControlEntity)pDestinationCluster).superiorCoordinatorHostL2Address()); LinkedList<RoutingServiceLinkVector> tVectorList = new LinkedList<RoutingServiceLinkVector>(); if(tCoordinatorPath != null) { for(Route tPath : tCoordinatorPath) { tVectorList.add(new RoutingServiceLinkVector(tPath, mHRMController.getHRS().getCoordinatorRoutingMap().getSource(tPath), mHRMController.getHRS().getCoordinatorRoutingMap().getDest(tPath))); } } return tVectorList; } @Override public Name getCoordinatorHostName() { return mCoordinatorName; } @Override public void setCoordinatorHostName(Name pCoordName) { mCoordinatorName = pCoordName; } public void eventClusterCoordinatorAnnounced(BullyAnnounce pAnnounce, ComChannel pCEP) { /** * the name of the cluster, which is managed by this coordinator */ ClusterName tLocalManagedClusterName = new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.superiorCoordinatorID(), mParentCluster.getClusterID()); /* * check whether old priority was lower than new priority */ // if(pAnnounce.getSenderPriority().isHigher(this, getCoordinatorPriority())) { /* * check whether a coordinator is already set */ if(superiorCoordinatorComChannel() != null) { if(getCoordinatorHostName() != null && !pAnnounce.getSenderName().equals(getCoordinatorHostName())) { /* * a coordinator was set earlier -> therefore inter-cluster communicatino is necessary * * find the route from the managed cluster to the cluster this entity got to know the higher cluster */ List<AbstractRoutingGraphLink> tRouteARG = mHRMController.getRouteARG(mParentCluster, pCEP.getRemoteClusterName()); if(tRouteARG.size() > 0) { if(mHRMController.getOtherEndOfLinkARG(pCEP.getRemoteClusterName(), tRouteARG.get(tRouteARG.size() - 1)) instanceof Cluster) { Logging.warn(this, "Not sending neighbor zone announce because another intermediate cluster has a shorter route to target"); if(tRouteARG != null) { String tClusterRoute = new String(); AbstractRoutingGraphNode tRouteARGNode = mParentCluster; for(AbstractRoutingGraphLink tConnection : tRouteARG) { tClusterRoute += tRouteARGNode + "\n"; tRouteARGNode = mHRMController.getOtherEndOfLinkARG(tRouteARGNode, tConnection); } Logging.log(this, "cluster route to other entity:\n" + tClusterRoute); } } else { /* * This is for the new coordinator - he is being notified about the fact that this cluster belongs to another coordinator * * If there are intermediate clusters between the managed cluster of this cluster manager we do not send the announcement because in that case * the forwarding would get inconsistent * * If this is a rejection the forwarding cluster as to be calculated by the receiver of this neighbor zone announcement */ AnnounceRemoteCluster tOldCovered = new AnnounceRemoteCluster(getCoordinatorHostName(), getHierarchyLevel(), superiorCoordinatorHostL2Address(),getCoordinatorID(), superiorCoordinatorHostL2Address().getComplexAddress().longValue()); tOldCovered.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority()); tOldCovered.setNegotiatorIdentification(tLocalManagedClusterName); DiscoveryEntry tOldCoveredEntry = new DiscoveryEntry(mParentCluster.getCoordinatorID(), mParentCluster.getCoordinatorHostName(), mParentCluster.superiorCoordinatorHostL2Address().getComplexAddress().longValue(), mParentCluster.superiorCoordinatorHostL2Address(), mParentCluster.getHierarchyLevel()); /* * the forwarding cluster to the newly discovered cluster has to be one level lower so it is forwarded on the correct cluster * * calculation of the predecessor is because the cluster identification on the remote site is multiplexed */ tRouteARG = mHRMController.getRouteARG(mParentCluster, superiorCoordinatorComChannel().getRemoteClusterName()); tOldCoveredEntry.setPriority(superiorCoordinatorComChannel().getPeerPriority()); tOldCoveredEntry.setRoutingVectors(pCEP.getPath(mParentCluster.superiorCoordinatorHostL2Address())); tOldCovered.setCoveringClusterEntry(tOldCoveredEntry); //tOldCovered.setAnnouncer(getCoordinator().getHRS().getCoordinatorRoutingMap().getDest(tPathToCoordinator.get(0))); pCEP.sendPacket(tOldCovered); /* * now the old cluster is notified about the new cluster */ AnnounceRemoteCluster tNewCovered = new AnnounceRemoteCluster(pAnnounce.getSenderName(), getHierarchyLevel(), pCEP.getPeerL2Address(), pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address().getComplexAddress().longValue()); tNewCovered.setCoordinatorsPriority(pAnnounce.getSenderPriority()); tNewCovered.setNegotiatorIdentification(tLocalManagedClusterName); DiscoveryEntry tCoveredEntry = new DiscoveryEntry(pAnnounce.getCoordinatorID(), pAnnounce.getSenderName(), (pCEP.getPeerL2Address()).getComplexAddress().longValue(), pCEP.getPeerL2Address(), getHierarchyLevel()); tCoveredEntry.setRoutingVectors(pCEP.getPath(pCEP.getPeerL2Address())); tNewCovered.setCoveringClusterEntry(tCoveredEntry); tCoveredEntry.setPriority(pAnnounce.getSenderPriority()); Logging.warn(this, "Rejecting " + (superiorCoordinatorComChannel().getPeerL2Address()).getDescr() + " in favor of " + pAnnounce.getSenderName()); tNewCovered.setRejection(); superiorCoordinatorComChannel().sendPacket(tNewCovered); for(ComChannel tCEP : getComChannels()) { if(pAnnounce.getCoveredNodes().contains(tCEP.getPeerL2Address())) { tCEP.setAsParticipantOfMyCluster(true); } else { tCEP.setAsParticipantOfMyCluster(false); } } setSuperiorCoordinatorID(pAnnounce.getCoordinatorID()); setSuperiorCoordinator(pCEP, pAnnounce.getSenderName(),pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address()); mHRMController.setClusterWithCoordinator(getHierarchyLevel(), this); superiorCoordinatorComChannel().sendPacket(tNewCovered); } } } } else { if (pAnnounce.getCoveredNodes() != null){ for(ComChannel tCEP : getComChannels()) { if(pAnnounce.getCoveredNodes().contains(tCEP.getPeerL2Address())) { tCEP.setAsParticipantOfMyCluster(true); } else { tCEP.setAsParticipantOfMyCluster(false); } } } setSuperiorCoordinatorID(pAnnounce.getCoordinatorID()); mHRMController.setClusterWithCoordinator(getHierarchyLevel(), this); setSuperiorCoordinator(pCEP, pAnnounce.getSenderName(), pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address()); } // } else { // /* // * this part is for the coordinator that intended to announce itself -> send rejection and send acting coordinator along with // * the announcement that is just gained a neighbor zone // */ // // NeighborClusterAnnounce tUncoveredAnnounce = new NeighborClusterAnnounce(getCoordinatorName(), getHierarchyLevel(), superiorCoordinatorL2Address(), getToken(), superiorCoordinatorL2Address().getComplexAddress().longValue()); // tUncoveredAnnounce.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority()); // /* // * the routing service address of the announcer is set once the neighbor zone announce arrives at the rejected coordinator because this // * entity is already covered // */ // // tUncoveredAnnounce.setNegotiatorIdentification(tLocalManagedClusterName); // // DiscoveryEntry tUncoveredEntry = new DiscoveryEntry(mParentCluster.getToken(), mParentCluster.getCoordinatorName(), mParentCluster.superiorCoordinatorL2Address().getComplexAddress().longValue(), mParentCluster.superiorCoordinatorL2Address(), mParentCluster.getHierarchyLevel()); // List<RoutableClusterGraphLink> tClusterList = mHRMController.getRoutableClusterGraph().getRoute(mParentCluster, pCEP.getRemoteClusterName()); // if(!tClusterList.isEmpty()) { // ICluster tPredecessor = (ICluster) mHRMController.getRoutableClusterGraph().getLinkEndNode(mParentCluster, tClusterList.get(0)); // tUncoveredEntry.setPredecessor(new ClusterName(tPredecessor.getToken(), tPredecessor.getClusterID(), tPredecessor.getHierarchyLevel())); // } // tUncoveredEntry.setPriority(getCoordinatorPriority()); // tUncoveredEntry.setRoutingVectors(pCEP.getPath(mParentCluster.superiorCoordinatorL2Address())); // tUncoveredAnnounce.setCoveringClusterEntry(tUncoveredEntry); // Logging.warn(this, "Rejecting " + (superiorCoordinatorComChannel().getPeerL2Address()).getDescr() + " in favour of " + pAnnounce.getSenderName()); // tUncoveredAnnounce.setRejection(); // pCEP.sendPacket(tUncoveredAnnounce); // // /* // * this part is for the acting coordinator, so NeighborZoneAnnounce is sent in order to announce the cluster that was just rejected // */ // // NeighborClusterAnnounce tCoveredAnnounce = new NeighborClusterAnnounce(pAnnounce.getSenderName(), getHierarchyLevel(), pCEP.getPeerL2Address(), pAnnounce.getToken(), (pCEP.getPeerL2Address()).getComplexAddress().longValue()); // tCoveredAnnounce.setCoordinatorsPriority(pAnnounce.getSenderPriority()); // //// List<Route> tPathToCoordinator = getCoordinator().getHRS().getCoordinatorRoutingMap().getRoute(pCEP.getSourceName(), pCEP.getPeerName()); // // //tCoveredAnnounce.setAnnouncer(getCoordinator().getHRS().getCoordinatorRoutingMap().getDest(tPathToCoordinator.get(0))); // tCoveredAnnounce.setNegotiatorIdentification(tLocalManagedClusterName); // DiscoveryEntry tCoveredEntry = new DiscoveryEntry(pAnnounce.getToken(), pAnnounce.getSenderName(), (pCEP.getPeerL2Address()).getComplexAddress().longValue(), pCEP.getPeerL2Address(), getHierarchyLevel()); // tCoveredEntry.setRoutingVectors(pCEP.getPath(pCEP.getPeerL2Address())); // tCoveredAnnounce.setCoveringClusterEntry(tCoveredEntry); // tCoveredEntry.setPriority(pAnnounce.getSenderPriority()); // tCoveredAnnounce.setCoordinatorsPriority(pAnnounce.getSenderPriority()); // // List<RoutableClusterGraphLink> tClusters = mHRMController.getRoutableClusterGraph().getRoute(mParentCluster, superiorCoordinatorComChannel().getRemoteClusterName()); // if(!tClusters.isEmpty()) { // ICluster tNewPredecessor = (ICluster) mHRMController.getRoutableClusterGraph().getLinkEndNode(mParentCluster, tClusters.get(0)); // tUncoveredEntry.setPredecessor(new ClusterName(tNewPredecessor.getToken(), tNewPredecessor.getClusterID(), tNewPredecessor.getHierarchyLevel())); // } // Logging.log(this, "Coordinator CEP is " + superiorCoordinatorComChannel()); // superiorCoordinatorComChannel().sendPacket(tCoveredAnnounce); // } } private ICluster addAnnouncedCluster(AnnounceRemoteCluster pAnnounce, ComChannel pCEP) { if(pAnnounce.getRoutingVectors() != null) { for(RoutingServiceLinkVector tVector : pAnnounce.getRoutingVectors()) { mHRMController.getHRS().registerRoute(tVector.getSource(), tVector.getDestination(), tVector.getPath()); } } ClusterProxy tCluster = null; if(pAnnounce.isAnnouncementFromForeign()) { Logging.log(this, " ..creating cluster proxy"); tCluster = new ClusterProxy(mParentCluster.mHRMController, pAnnounce.getCoordAddress().getComplexAddress().longValue() /* TODO: als clusterID den Wert? */, new HierarchyLevel(this, super.getHierarchyLevel().getValue() + 2), pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress(), pAnnounce.getToken()); mHRMController.setSourceIntermediateCluster(tCluster, mHRMController.getSourceIntermediateCluster(this)); tCluster.setSuperiorCoordinatorID(pAnnounce.getToken()); tCluster.setPriority(pAnnounce.getCoordinatorsPriority()); //mParentCluster.addNeighborCluster(tCluster); } else { Logging.log(this, "Cluster announced by " + pAnnounce + " is an intermediate neighbor "); } if(pAnnounce.getCoordinatorName() != null) { mHRMController.getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress()); } return tCluster; } @Override public void handleNeighborAnnouncement(AnnounceRemoteCluster pAnnounce, ComChannel pCEP) { if(pAnnounce.getCoveringClusterEntry() != null) { if(pAnnounce.isRejected()) { Logging.log(this, "Removing " + this + " as participating CEP from " + this); getComChannels().remove(this); } if(pAnnounce.getCoordinatorName() != null) { mHRMController.getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress()); } pCEP.handleDiscoveryEntry(pAnnounce.getCoveringClusterEntry()); } } @Override public void setSuperiorCoordinator(ComChannel pCoordinatorComChannel, Name pCoordinatorName, int pCoordToken, L2Address pCoordinatorL2Address) { super.setSuperiorCoordinator(pCoordinatorComChannel, pCoordinatorName, pCoordToken, pCoordinatorL2Address); Logging.log(this, "Setting channel to superior coordinator to " + pCoordinatorComChannel + " for coordinator " + pCoordinatorName + " with routing address " + pCoordinatorL2Address); Logging.log(this, "Previous channel to superior coordinator was " + superiorCoordinatorComChannel() + " with name " + mCoordinatorName); setSuperiorCoordinatorComChannel(pCoordinatorComChannel); mCoordinatorName = pCoordinatorName; synchronized(this) { notifyAll(); } // LinkedList<CoordinatorCEP> tEntitiesToNotify = new LinkedList<CoordinatorCEP> (); ClusterName tLocalManagedClusterName = new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.getCoordinatorID(), mParentCluster.getClusterID()); for(AbstractRoutingGraphNode tNeighbor: mHRMController.getNeighborsARG(mParentCluster)) { if(tNeighbor instanceof ICluster) { for(ComChannel tComChannel : getComChannels()) { if(((ControlEntity)tNeighbor).superiorCoordinatorHostL2Address().equals(tComChannel.getPeerL2Address()) && !tComChannel.isPartOfMyCluster()) { Logging.info(this, "Informing " + tComChannel + " about existence of neighbor zone "); AnnounceRemoteCluster tAnnounce = new AnnounceRemoteCluster(pCoordinatorName, getHierarchyLevel(), pCoordinatorL2Address, getCoordinatorID(), pCoordinatorL2Address.getComplexAddress().longValue()); tAnnounce.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority()); LinkedList<RoutingServiceLinkVector> tVectorList = tComChannel.getPath(pCoordinatorL2Address); tAnnounce.setRoutingVectors(tVectorList); tAnnounce.setNegotiatorIdentification(tLocalManagedClusterName); tComChannel.sendPacket(tAnnounce); } Logging.log(this, "Informed " + tComChannel + " about new neighbor zone"); } } } if(mReceivedAnnouncements != null) { for(AnnounceRemoteCluster tAnnounce : mReceivedAnnouncements) { superiorCoordinatorComChannel().sendPacket(tAnnounce); } } } /** * Generates a descriptive string about this object * * @return the descriptive string */ public String toString() { //return getClass().getSimpleName() + (mParentCluster != null ? "(" + mParentCluster.toString() + ")" : "" ) + "TK(" +mToken + ")COORD(" + mCoordinatorSignature + ")@" + mLevel; return toLocation() + "(" + (mParentCluster != null ? "Cluster" + mParentCluster.getGUIClusterID() + ", " : "") + idToString() + ")"; } @Override public String toLocation() { String tResult = getClass().getSimpleName() + getGUICoordinatorID() + "@" + mHRMController.getNodeGUIName() + "@" + (getHierarchyLevel().getValue() - 1); return tResult; } private String idToString() { if (getHRMID() == null){ return "ID=" + getClusterID() + ", CordID=" + getCoordinatorID() + ", NodePrio=" + getPriority().getValue(); }else{ return "HRMID=" + getHRMID().toString(); } } }
false
true
private void shareRouteToClusterMember(ComChannel pClusterMemberChannel) { // determine the HRMID of the cluster member HRMID tMemberHRMID = pClusterMemberChannel.getPeerHRMID(); // are we on base hierarchy level? if (getHierarchyLevel().getValue() == 1){ // TODO: isBaseLevel()){ // create the new routing table entry RoutingEntry tRoutingEntry = RoutingEntry.createRouteToDirectNeighbor(tMemberHRMID, 0 /* TODO */, 1 /* TODO */, RoutingEntry.INFINITE_DATARATE /* TODO */); // define the L2 address of the next hop in order to let "addHRMRoute" trigger the HRS instance the creation of new HRMID-to-L2ADDRESS mapping entry tRoutingEntry.setNextHopL2Address(pClusterMemberChannel.getPeerL2Address()); Logging.log(this, "SHARING ROUTE: " + tRoutingEntry); // add the entry to the local routing table mHRMController.addHRMRoute(tRoutingEntry); // store the entry for route sharing with cluster members synchronized (mSharedRoutes){ /** * Check for duplicates */ if (HRMConfig.Routing.AVOID_DUPLICATES_IN_ROUTING_TABLES){ boolean tRestartNeeded; do{ tRestartNeeded = false; for (RoutingEntry tEntry: mSharedRoutes){ // have we found a route to the same destination which uses the same next hop? //TODO: what about multiple links to the same next hop? if ((tEntry.getDest().equals(tRoutingEntry.getDest())) /* same destination? */ && (tEntry.getNextHop().equals(tRoutingEntry.getNextHop())) /* same next hop? */){ Logging.log(this, "REMOVING DUPLICATE: " + tEntry); // remove the route mSharedRoutes.remove(tEntry); // mark "shared phase" data as changed mSharedRoutesHaveChanged = true; // force a restart at the beginning of the routing table tRestartNeeded = true; //TODO: use a better(scalable) method here for removing duplicates break; } } }while(tRestartNeeded); } /** * Add the entry to the shared routing table */ mSharedRoutes.add(tRoutingEntry);//TODO: use a database per cluster member here // mark "shared phase" data as changed mSharedRoutesHaveChanged = true; } }else{ //TODO Logging.log(this, "IMPLEMENT ME - SHARING ROUTE TO: " + pClusterMemberChannel); } } /** * Checks if the "share phase" should be started or not * * @return true if the "share phase" should be started, otherwise false */ private boolean sharePhaseHasTimeout() { // determine the time between two "share phases" double tDesiredTimePeriod = mHRMController.getPeriodSharePhase(getHierarchyLevel().getValue() - 1); // determine the time when a "share phase" has to be started double tTimeNextSharePhase = mTimeOfLastSharePhase + tDesiredTimePeriod; // determine the current simulation time from the HRMCotnroller instance double tCurrentSimulationTime = mHRMController.getSimulationTime(); if (HRMConfig.DebugOutput.GUI_SHOW_TIMING_ROUTE_DISTRIBUTION){ Logging.log(this, "Checking for timeout of \"share phase\": desired time period is " + tDesiredTimePeriod + ", " + tCurrentSimulationTime + " > " + tTimeNextSharePhase + "? -> " + (tCurrentSimulationTime >= tTimeNextSharePhase)); } return (tCurrentSimulationTime >= tTimeNextSharePhase); } /** * Determines if new "share phase" data is available * * @return true if new data is available, otherwise false */ private boolean hasNewSharePhaseData() { boolean tResult = false; synchronized (mSharedRoutes){ tResult = mSharedRoutesHaveChanged; } return tResult; } /** * This function implements the "share phase". * It distributes locally stored sharable routing data among the known cluster members */ public void sharePhase() { // should we start the "share phase"? if (sharePhaseHasTimeout()){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE with cluster members on level " + (getHierarchyLevel().getValue() - 1) + "/" + (HRMConfig.Hierarchy.HEIGHT - 1)); } // store the time of this "share phase" mTimeOfLastSharePhase = mHRMController.getSimulationTime(); if ((!HRMConfig.Routing.PERIODIC_SHARE_PHASES) && (!hasNewSharePhaseData())){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE skipped because routing data hasn't changed since last signaling round"); } return; } /** * SHARE PHASE */ // determine own local cluster address HRMID tOwnClusterAddress = mParentCluster.getHRMID(); if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, " ..distributing as " + tOwnClusterAddress.toString() + " aggregated ROUTES among cluster members: " + mParentCluster.getComChannels()); } synchronized (mSharedRoutes){ // send the routing information to cluster members for(ComChannel tClusterMember : mParentCluster.getComChannels()) { RoutingInformation tRoutingInformationPacket = new RoutingInformation(tOwnClusterAddress, tClusterMember.getPeerHRMID()); // are we on base hierarchy level? if (getHierarchyLevel().getValue() == 1){ // TODO: isBaseLevel()){ /** * ADD ROUTES: routes from the cluster member to this node for every registered local HRMID. */ // determine the L2 address of this physical node L2Address tPhysNodeL2Address = mHRMController.getHRS().getCentralFNL2Address(); // iterate over all HRMIDs which are registered for this physical node for (HRMID tHRMID : mHRMController.getOwnHRMIDs()){ // create entry for cluster internal routing towards us RoutingEntry tRouteFromClusterMemberToHere = RoutingEntry.createRouteToDirectNeighbor(tHRMID, 0 /* TODO */, 1 /* TODO */, RoutingEntry.INFINITE_DATARATE /* TODO */); // define the L2 address of the next hop in order to let the receiver store it in its HRMID-to-L2ADDRESS mapping tRouteFromClusterMemberToHere.setNextHopL2Address(tPhysNodeL2Address); // add the route in the "share phase" signaling tRoutingInformationPacket.addRoute(tRouteFromClusterMemberToHere); } //TODO: need routing graph here! //TODO: routes to other cluster members }else{ //TODO: implement me } /** * Send the routing data to the cluster member */ // do we have interesting routing information? if (tRoutingInformationPacket.getRoutes().size() > 0){ tClusterMember.sendPacket(tRoutingInformationPacket); }else{ // no routing information -> no packet is sent } } /** * mark "share phase" data as known */ mSharedRoutesHaveChanged = false; } }else{ // share phase shouldn't be started, we have to wait until next trigger } } /** * This function implements the "report phase". * It sends locally stored sharable routing data to the superior coordinator */ public void reportPhase() { if (!getHierarchyLevel().isHighest()){ }else{ // we are the highest hierarchy level, no one to send topology reports to } } /** * EVENT: "eventCoordinatorRoleInvalid", triggered by the Elector, the reaction is: * 1.) create signaling packet "BullyLeave" * 2.) send the packet to the superior coordinator */ public void eventCoordinatorRoleInvalid() { Logging.log(this, "============ EVENT: Coordinator_Role_Invalid"); /** * Inform all superior clusters about the event and trigger the invalidation of this coordinator instance -> we leave all Bully elections because we are no longer a possible election winner */ if (!getHierarchyLevel().isHighest()){ // create signaling packet for signaling that we leave the Bully group BullyLeave tBullyLeavePacket = new BullyLeave(mHRMController.getNodeName(), getPriority()); sendAllSuperiorClusters(tBullyLeavePacket, true); }else{ Logging.log(this, "eventCoordinatorRoleInvalid() skips further signaling because hierarchy end is already reached at: " + (getHierarchyLevel().getValue() - 1)); } /** * Unregister from local databases */ Logging.log(this, "============ Destroying this coordinator now..."); // unregister itself as coordinator for the managed cluster mParentCluster.setCoordinator(null); // unregister from HRMController's internal database mHRMController.unregisterCoordinator(this); } /** * @param pBullyLeavePacket */ private void sendAllSuperiorClusters(Serializable pPacket, boolean pIncludeLoopback) { // get all communication channels LinkedList<ComChannel> tComChannels = getComChannels(); // get the L2Addres of the local host L2Address tLocalL2Address = mHRMController.getHRS().getCentralFNL2Address(); Logging.log(this, "Sending BROADCASTS from " + tLocalL2Address + " the packet " + pPacket + " to " + tComChannels.size() + " communication channels"); for(ComChannel tComChannel : tComChannels) { boolean tIsLoopback = tLocalL2Address.equals(tComChannel.getPeerL2Address()); if (!tIsLoopback){ Logging.log(this, " ..to " + tComChannel); }else{ Logging.log(this, " ..to LOOPBACK " + tComChannel); } if ((HRMConfig.Hierarchy.SIGNALING_INCLUDES_LOCALHOST) || (pIncludeLoopback) || (!tIsLoopback)){ // send the packet to one of the possible cluster members tComChannel.sendPacket(pPacket); }else{ Logging.log(this, " ..skipping " + (tIsLoopback ? "LOOPBACK CHANNEL" : "")); } } } /** * EVENT: "announced", triggered by Elector if the election was won and this coordinator was announced to all cluster members */ public void eventAnnouncedAsCoordinator() { /** * AUTO ADDRESS DISTRIBUTION */ if (HRMConfig.Addressing.ASSIGN_AUTOMATICALLY){ Logging.log(this, "EVENT ANNOUNCED - triggering address assignment for " + getComChannels().size() + " cluster members"); signalAddressDistribution(); } //TODO: ?? mHRMController.setSourceIntermediateCluster(this, getCluster()); /** * AUTO CLUSTERING */ if(!getHierarchyLevel().isHighest()) { if (HRMConfig.Hierarchy.CONTINUE_AUTOMATICALLY){ Logging.log(this, "EVENT ANNOUNCED - triggering clustering of this cluster's coordinator and its neighbors"); // start the clustering of this cluster's coordinator and its neighbors if it wasn't already triggered by another coordinator if (!isClustered()){ cluster(); }else{ Logging.warn(this, "Clustering is already finished for this hierarchy level, skipping cluster-request"); } } } } /** * Clusters the superior hierarchy level or tries to join an already existing superior cluster */ public void cluster() { Logging.log(this, "\n\n\n################ CLUSTERING STARTED"); /** * Try to find a matching local cluster on the superior hierarchy level */ boolean tSuperiorClusterFound = false; for(Cluster tCluster : mHRMController.getAllClusters(getHierarchyLevel())) { if (joinSuperiorCluster(tCluster)){ // we joined the superior cluster and should end the search for a superior coordinator tSuperiorClusterFound = true; break; } } /** * Explore the neighborhood and create a new superior cluster */ if (!tSuperiorClusterFound){ exploreNeighborhodAndCreateSuperiorCluster(); } } /** * Tries to join a superior cluster * * @param pSuperiorCluster the possible new superior cluster * * @return true or false to indicate success/error */ private boolean joinSuperiorCluster(ControlEntity pSuperiorCluster) { Logging.log(this, "\n\n\n################ JOINING EXISTING SUPERIOR CLUSTER " + pSuperiorCluster); return false; } /** * EVENT: initial clustering has finished */ private void eventInitialClusteringFinished() { // mark initial clustering as "finished" mInitialClusteringFinished = true; } /** * Returns if the initial clustering has already finished * * @return true or false */ public boolean isClustered() { return mInitialClusteringFinished; } //TODO: fix this +1 stuff @Override public HierarchyLevel getHierarchyLevel() { return new HierarchyLevel(this, super.getHierarchyLevel().getValue() + 1); } /** * Returns the Bully priority of the parent cluster * * @return the Bully priority */ @Override public BullyPriority getPriority() { // return the Bully priority of the managed cluster object return mParentCluster.getPriority(); } /** * Sets a new Bully priority * * @param pPriority the new Bully priority */ @Override public void setPriority(BullyPriority pPriority) { if (!getPriority().equals(pPriority)){ Logging.err(this, "Updating Bully priority from " + getPriority() + " to " + pPriority); }else{ Logging.log(this, "Trying to set same Bully priority " + getPriority()); } // update the Bully priority of the parent cluster, which is managed by this coordinator mParentCluster.setPriority(pPriority); } /** * Returns a reference to the cluster, which this coordinator manages. * * @return the managed cluster */ public Cluster getCluster() { return mParentCluster; } /** * Returns the unique ID of the parental cluster * * @return the unique cluster ID */ @Override public Long getClusterID() { return mParentCluster.getClusterID(); } /** * Checks if there already exists a connection to a neighbor coordinator * * @param pCoordinatorName the name of the neighbor coordinator * * @return true or false */ private boolean isConnectedToNeighborCoordinator(Name pCoordinatorName) { boolean tResult = false; synchronized (mConnectedNeighborCoordinators) { tResult = mConnectedNeighborCoordinators.contains(pCoordinatorName); } return tResult; } /** * Registers an already existing connection to a neighbor coordinator in order to avoid connection duplicates * * @param pCoordinatorName the name of the neighbor coordinator */ private void registerConnectionToNeighborCoordinator(Name pCoordinatorName) { synchronized (mConnectedNeighborCoordinators) { mConnectedNeighborCoordinators.add(pCoordinatorName); } } /** * Creates a cluster consisting of this coordinator and neighbor coordinators by the following steps: * 1.) querying the ARG from the HRMController for neighbor clusters within the given max. radius * 2.) trigger event "detectedNeighborCoordinator" with increasing radius */ private void exploreNeighborhodAndCreateSuperiorCluster() { Logging.log(this, "\n\n\n################ EXPLORATION STARTED on hierarchy level " + getHierarchyLevel().getValue()); // was the clustering already triggered? if (!isClustered()){ // are we already at the highest hierarchy level? if (!getHierarchyLevel().isHighest()){ int tMaxRadius = HRMConfig.Routing.EXPANSION_RADIUS; Logging.log(this, "Maximum radius is " + tMaxRadius); /** * Create the cluster ID for the new cluster, which should consist of the control entities we connect to in the next steps */ Long tIDFutureCluster = Cluster.createClusterID(); // get all known neighbor clusters ordered by their radius to the parent cluster List<AbstractRoutingGraphNode> tNeighborClustersForClustering = mHRMController.getNeighborClustersOrderedByRadiusInARG(mParentCluster); Logging.log(this, " ..neighborhood ordered by radius: " + tNeighborClustersForClustering); /** * count from radius 1 to max. radius and connect to each cluster candidate */ for(int tRadius = 1; tRadius <= tMaxRadius; tRadius++) { Logging.log(this, "\n>>> Exploring neighbors with radius (" + tRadius + "/" + tMaxRadius + ")"); // create list for storing the found neighbor clusters, which have a cluster distance equal to the current radius value List<AbstractRoutingGraphNode> tSelectedNeighborClusters = new LinkedList<AbstractRoutingGraphNode>(); List<AbstractRoutingGraphNode> tNeighborClustersForClustering_RemoveList = new LinkedList<AbstractRoutingGraphNode>(); /** * Iterate over all cluster candidates and determines the logical distance of each found candidate */ for(AbstractRoutingGraphNode tClusterCandidate : tNeighborClustersForClustering) { // is the found neighbor a Cluster object? if(tClusterCandidate instanceof Cluster) { if (tRadius == 1){ // add this Cluster object as cluster candidate because it obviously has a logical distance of 1 Logging.log(this, " ..[r=" + tRadius + "]: found Cluster candidate: " + tClusterCandidate); tSelectedNeighborClusters.add(tClusterCandidate); // remove this candidate from the global list tNeighborClustersForClustering_RemoveList.add(tClusterCandidate); }else{ // found a Cluster object but the radius is already beyond 1 } } else { // is the found neighbor a ClusterProxy object? if (tClusterCandidate instanceof ClusterProxy){ // get the proxy for this cluster ClusterProxy tClusterCandidateProxy = (ClusterProxy)tClusterCandidate; // are we already connected to this candidate? if (!isConnectedToNeighborCoordinator(tClusterCandidateProxy.getCoordinatorHostName())){ // get the logical distance to the neighbor int tNeighborClusterDistance = mHRMController.getClusterDistance(tClusterCandidateProxy); // should we connect to the found cluster candidate? if ((tNeighborClusterDistance > 0) && (tNeighborClusterDistance <= tRadius)) { // add this candidate to the list of connection targets Logging.log(this, " ..[r=" + tRadius + "]: found ClusterProxy candidate: " + tClusterCandidate); tSelectedNeighborClusters.add(tClusterCandidateProxy); // remove this candidate from the global list tNeighborClustersForClustering_RemoveList.add(tClusterCandidate); }else{ // the logical distance doesn't equal to the current radius value if (tNeighborClusterDistance > tRadius){ // we have already passed the last possible candidate -> we continue the for-loop continue; } } } }else{ Logging.err(this, "Found unsupported neighbor: " + tClusterCandidate); } } } /** * Remove all processed cluster candidates from the global candidate list in order to reduce processing time */ for (AbstractRoutingGraphNode tRemoveCandidate : tNeighborClustersForClustering_RemoveList){ tNeighborClustersForClustering.remove(tRemoveCandidate); } /** * Connect to all found cluster candidates */ for(AbstractRoutingGraphNode tNeighborCluster : tSelectedNeighborClusters) { if(tNeighborCluster instanceof ControlEntity) { ControlEntity tNeighborClusterControlEntity = (ControlEntity)tNeighborCluster; eventDetectedNeighborCoordinator(tNeighborClusterControlEntity, tIDFutureCluster); }else{ Logging.err(this, "Unsupported neighbor object: " + tNeighborCluster); } } } /** * Mark all local coordinators for this hierarchy level as "clustered" */ for(Coordinator tLocalCoordinator : mHRMController.getAllCoordinators(getHierarchyLevel())) { // trigger event "finished clustering" tLocalCoordinator.eventInitialClusteringFinished(); } }else{ Logging.warn(this, "CLUSTERING SKIPPED, no clustering on highest hierarchy level " + getHierarchyLevel().getValue() + " needed"); } }else{ Logging.warn(this, "Clustering was already triggered, clustering will be maintained"); } } /** * EVENT: detected a neighbor coordinator, we react on this event by the following steps: * 1.) use "RequestClusterParticipationProperty" for every connection to inform about the new cluster * * @param pNeighborCluster the found neighbor cluster whose coordinator is a neighbor of this one * @param pIDForFutureCluster the clusterID for the common cluster */ private void eventDetectedNeighborCoordinator(ControlEntity pNeighborCluster, Long pIDForFutureCluster) { // get the recursive FoG layer FoGEntity tFoGLayer = (FoGEntity) mHRMController.getNode().getLayer(FoGEntity.class); // get the central FN of this node L2Address tThisHostL2Address = mHRMController.getHRS().getL2AddressFor(tFoGLayer.getCentralFN()); Logging.info(this, "\n\n\n############## FOUND INFERIOR NEIGHBOR CLUSTER " + pNeighborCluster + " FOR " + tThisHostL2Address); /** * get the name of the target coordinator name */ Name tTargetCoordinatorHostName = ((ICluster)pNeighborCluster).getCoordinatorHostName(); if(!isConnectedToNeighborCoordinator(tTargetCoordinatorHostName)) { // store the connection to avoid connection duplicates during later processing registerConnectionToNeighborCoordinator(tTargetCoordinatorHostName); HierarchyLevel tTargetClusterHierLvl = new HierarchyLevel(this, pNeighborCluster.getHierarchyLevel().getValue() + 1); ControlEntity tNeighborClusterControlEntity = (ControlEntity)pNeighborCluster; /** * Describe the common cluster */ Logging.log(this, " ..creating cluster description"); // create the cluster description RequestClusterParticipationProperty tRequestClusterParticipationProperty = new RequestClusterParticipationProperty(pIDForFutureCluster, tTargetClusterHierLvl, pNeighborCluster.getCoordinatorID()); /** * Create communication session */ Logging.log(this, " ..creating new communication session"); ComSession tComSession = new ComSession(mHRMController, false, getHierarchyLevel()); /** * Iterate over all local coordinators on this hierarchy level and add them as already known cluster members to the cluster description */ Logging.log(this, " ..iterate over all coordinators on hierarchy level: " + (getHierarchyLevel().getValue() - 1)); // store how many local coordinators on this hierarchy level were found int tKnownLocalCoordinatorsOnThisHierarchyLevel = 0; for(Coordinator tLocalCoordinator : mHRMController.getAllCoordinators(getHierarchyLevel())) { tKnownLocalCoordinatorsOnThisHierarchyLevel++; Logging.log(this, " ..found [" + tKnownLocalCoordinatorsOnThisHierarchyLevel + "] : " + tLocalCoordinator); /** * Create communication channel */ Logging.log(this, " ..creating new communication channel"); ComChannel tComChannel = new ComChannel(mHRMController, ComChannel.Direction.OUT, tLocalCoordinator, tComSession); tComChannel.setRemoteClusterName(new ClusterName(mHRMController, pNeighborCluster.getHierarchyLevel(), pNeighborCluster.getCoordinatorID(), pIDForFutureCluster /* HINT: we communicate with the new cluster -> us clusterID of new cluster */)); tComChannel.setPeerPriority(pNeighborCluster.getPriority()); // do we know the neighbor coordinator? (we check for a known coordinator of the neighbor cluster) if(tNeighborClusterControlEntity.superiorCoordinatorHostL2Address() != null) { Cluster tCoordinatorCluster = tLocalCoordinator.getCluster(); /** * Describe the cluster member */ Logging.log(this, " ..creating cluster member description for the found cluster " + tCoordinatorCluster); ClusterMemberDescription tClusterMemberDescription = tRequestClusterParticipationProperty.addClusterMember(tCoordinatorCluster.getClusterID(), tCoordinatorCluster.getCoordinatorID(), tCoordinatorCluster.getPriority()); tClusterMemberDescription.setSourceName(mHRMController.getNodeName()); tClusterMemberDescription.setSourceL2Address(tThisHostL2Address); /** * Iterate over all known neighbors of the current cluster member: we inform the connection target about this neighborhood topology */ for(ControlEntity tClusterMemberNeighbor: tLocalCoordinator.getCluster().getNeighborsARG()) { ICluster tIClusterNeighbor = (ICluster)tClusterMemberNeighbor; DiscoveryEntry tDiscoveryEntry = new DiscoveryEntry(tClusterMemberNeighbor.getCoordinatorID(), tIClusterNeighbor.getCoordinatorHostName(), tClusterMemberNeighbor.getClusterID(), tClusterMemberNeighbor.superiorCoordinatorHostL2Address(), tClusterMemberNeighbor.getHierarchyLevel()); tDiscoveryEntry.setPriority(tClusterMemberNeighbor.getPriority()); if(tLocalCoordinator.getPathToCoordinator(tLocalCoordinator.getCluster(), tIClusterNeighbor) != null) { for(RoutingServiceLinkVector tVector : tLocalCoordinator.getPathToCoordinator(tLocalCoordinator.getCluster(), tIClusterNeighbor)) { tDiscoveryEntry.addRoutingVectors(tVector); } } tClusterMemberDescription.addDiscoveryEntry(tDiscoveryEntry); } }else{ Logging.err(this, "eventDetectedNeighborCoordinator() didn't found the L2Address of the coordinator for: " + tNeighborClusterControlEntity); } } /** * Create connection requirements */ Description tConnectionRequirements = mHRMController.createHRMControllerDestinationDescription(); tConnectionRequirements.set(tRequestClusterParticipationProperty); ClusterDiscovery tBigDiscovery = new ClusterDiscovery(mHRMController.getNodeName()); /** * Connect to the neighbor coordinator */ Connection tConnection = null; Logging.log(this, " ..CONNECTING to: " + tTargetCoordinatorHostName + " with requirements: " + tConnectionRequirements); tConnection = tFoGLayer.connect(tTargetCoordinatorHostName, tConnectionRequirements, mHRMController.getNode().getIdentity()); Logging.log(this, " ..connect() FINISHED"); if (tConnection != null){ mCounterOutgoingConnections++; Logging.log(this, " ..starting this OUTGOING CONNECTION as nr. " + mCounterOutgoingConnections); tComSession.startConnection(null, tConnection); /** * Create and send ClusterDiscovery */ for(Coordinator tCoordinator : mHRMController.getAllCoordinators(new HierarchyLevel(this, getHierarchyLevel().getValue() - 1))) { LinkedList<Integer> tCoordinatorIDs = new LinkedList<Integer>(); for(ControlEntity tNeighbor : tCoordinator.getCluster().getNeighborsARG()) { if(tNeighbor.getHierarchyLevel().getValue() == tCoordinator.getHierarchyLevel().getValue() - 1) { tCoordinatorIDs.add(((ICluster) tNeighbor).getCoordinatorID()); } } tCoordinatorIDs.add(tCoordinator.getCluster().getCoordinatorID()); if(!tTargetCoordinatorHostName.equals(mHRMController.getNodeName())) { int tDistance = 0; if (pNeighborCluster instanceof ClusterProxy){ ClusterProxy tClusterProxy = (ClusterProxy) pNeighborCluster; tDistance = mHRMController.getClusterDistance(tClusterProxy); } NestedDiscovery tNestedDiscovery = tBigDiscovery.new NestedDiscovery(tCoordinatorIDs, pNeighborCluster.getClusterID(), pNeighborCluster.getCoordinatorID(), pNeighborCluster.getHierarchyLevel(), tDistance); Logging.log(this, "Created " + tNestedDiscovery + " for " + pNeighborCluster); tNestedDiscovery.setOrigin(tCoordinator.getClusterID()); tNestedDiscovery.setTargetClusterID(tNeighborClusterControlEntity.superiorCoordinatorHostL2Address().getComplexAddress().longValue()); tBigDiscovery.addNestedDiscovery(tNestedDiscovery); } } // send the ClusterDiscovery to peer tComSession.write(tBigDiscovery); for(NestedDiscovery tDiscovery : tBigDiscovery.getDiscoveries()) { String tClusters = new String(); for(Cluster tCluster : mHRMController.getAllClusters()) { tClusters += tCluster + ", "; } String tDiscoveries = new String(); for(DiscoveryEntry tEntry : tDiscovery.getDiscoveryEntries()) { tDiscoveries += ", " + tEntry; } if(tDiscovery.getNeighborRelations() != null) { for(Tuple<ClusterName, ClusterName> tTuple : tDiscovery.getNeighborRelations()) { if(!mHRMController.isLinkedARG(tTuple.getFirst(), tTuple.getSecond())) { Cluster tFirstCluster = mHRMController.getClusterByID(tTuple.getFirst()); Cluster tSecondCluster = mHRMController.getClusterByID(tTuple.getSecond()); if(tFirstCluster != null && tSecondCluster != null ) { tFirstCluster.registerNeighborARG(tSecondCluster); Logging.log(this, "Connecting " + tFirstCluster + " with " + tSecondCluster); } else { Logging.warn(this, "Unable to find cluster " + tTuple.getFirst() + ":" + tFirstCluster + " or " + tTuple.getSecond() + ":" + tSecondCluster + " out of \"" + tClusters + "\", cluster discovery contained " + tDiscoveries + " and CEP is " + tComSession); } } } } else { Logging.warn(this, tDiscovery + "does not contain any neighbor relations"); } } }else{ Logging.err(this, "eventDetectedNeighborCoordinator() wasn't able to connect to: " + tTargetCoordinatorHostName); } }else{ Logging.warn(this, "eventDetectedNeighborCoordinator() skips this connection request because there exist already a connection to: " + tTargetCoordinatorHostName); } } /** * EVENT: "superior cluster coordinator was announced", triggered by Elector */ public void eventSuperiorClusterCoordinatorAnnounced(BullyAnnounce pAnnouncePacket, ComChannel pComChannel) { // store superior coordinator data setSuperiorCoordinator(pComChannel, pAnnouncePacket.getSenderName(), pAnnouncePacket.getCoordinatorID(), pComChannel.getPeerL2Address()); } public void storeAnnouncement(AnnounceRemoteCluster pAnnounce) { Logging.log(this, "Storing " + pAnnounce); if(mReceivedAnnouncements == null) { mReceivedAnnouncements = new LinkedList<AnnounceRemoteCluster>(); } pAnnounce.setNegotiatorIdentification(new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.superiorCoordinatorID(), mParentCluster.getClusterID())); mReceivedAnnouncements.add(pAnnounce); } public LinkedList<Long> getBounces() { return mBouncedAnnounces; } private LinkedList<RoutingServiceLinkVector> getPathToCoordinator(ICluster pSourceCluster, ICluster pDestinationCluster) { List<Route> tCoordinatorPath = mHRMController.getHRS().getCoordinatorRoutingMap().getRoute(((ControlEntity)pSourceCluster).superiorCoordinatorHostL2Address(), ((ControlEntity)pDestinationCluster).superiorCoordinatorHostL2Address()); LinkedList<RoutingServiceLinkVector> tVectorList = new LinkedList<RoutingServiceLinkVector>(); if(tCoordinatorPath != null) { for(Route tPath : tCoordinatorPath) { tVectorList.add(new RoutingServiceLinkVector(tPath, mHRMController.getHRS().getCoordinatorRoutingMap().getSource(tPath), mHRMController.getHRS().getCoordinatorRoutingMap().getDest(tPath))); } } return tVectorList; } @Override public Name getCoordinatorHostName() { return mCoordinatorName; } @Override public void setCoordinatorHostName(Name pCoordName) { mCoordinatorName = pCoordName; } public void eventClusterCoordinatorAnnounced(BullyAnnounce pAnnounce, ComChannel pCEP) { /** * the name of the cluster, which is managed by this coordinator */ ClusterName tLocalManagedClusterName = new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.superiorCoordinatorID(), mParentCluster.getClusterID()); /* * check whether old priority was lower than new priority */ // if(pAnnounce.getSenderPriority().isHigher(this, getCoordinatorPriority())) { /* * check whether a coordinator is already set */ if(superiorCoordinatorComChannel() != null) { if(getCoordinatorHostName() != null && !pAnnounce.getSenderName().equals(getCoordinatorHostName())) { /* * a coordinator was set earlier -> therefore inter-cluster communicatino is necessary * * find the route from the managed cluster to the cluster this entity got to know the higher cluster */ List<AbstractRoutingGraphLink> tRouteARG = mHRMController.getRouteARG(mParentCluster, pCEP.getRemoteClusterName()); if(tRouteARG.size() > 0) { if(mHRMController.getOtherEndOfLinkARG(pCEP.getRemoteClusterName(), tRouteARG.get(tRouteARG.size() - 1)) instanceof Cluster) { Logging.warn(this, "Not sending neighbor zone announce because another intermediate cluster has a shorter route to target"); if(tRouteARG != null) { String tClusterRoute = new String(); AbstractRoutingGraphNode tRouteARGNode = mParentCluster; for(AbstractRoutingGraphLink tConnection : tRouteARG) { tClusterRoute += tRouteARGNode + "\n"; tRouteARGNode = mHRMController.getOtherEndOfLinkARG(tRouteARGNode, tConnection); } Logging.log(this, "cluster route to other entity:\n" + tClusterRoute); } } else { /* * This is for the new coordinator - he is being notified about the fact that this cluster belongs to another coordinator * * If there are intermediate clusters between the managed cluster of this cluster manager we do not send the announcement because in that case * the forwarding would get inconsistent * * If this is a rejection the forwarding cluster as to be calculated by the receiver of this neighbor zone announcement */ AnnounceRemoteCluster tOldCovered = new AnnounceRemoteCluster(getCoordinatorHostName(), getHierarchyLevel(), superiorCoordinatorHostL2Address(),getCoordinatorID(), superiorCoordinatorHostL2Address().getComplexAddress().longValue()); tOldCovered.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority()); tOldCovered.setNegotiatorIdentification(tLocalManagedClusterName); DiscoveryEntry tOldCoveredEntry = new DiscoveryEntry(mParentCluster.getCoordinatorID(), mParentCluster.getCoordinatorHostName(), mParentCluster.superiorCoordinatorHostL2Address().getComplexAddress().longValue(), mParentCluster.superiorCoordinatorHostL2Address(), mParentCluster.getHierarchyLevel()); /* * the forwarding cluster to the newly discovered cluster has to be one level lower so it is forwarded on the correct cluster * * calculation of the predecessor is because the cluster identification on the remote site is multiplexed */ tRouteARG = mHRMController.getRouteARG(mParentCluster, superiorCoordinatorComChannel().getRemoteClusterName()); tOldCoveredEntry.setPriority(superiorCoordinatorComChannel().getPeerPriority()); tOldCoveredEntry.setRoutingVectors(pCEP.getPath(mParentCluster.superiorCoordinatorHostL2Address())); tOldCovered.setCoveringClusterEntry(tOldCoveredEntry); //tOldCovered.setAnnouncer(getCoordinator().getHRS().getCoordinatorRoutingMap().getDest(tPathToCoordinator.get(0))); pCEP.sendPacket(tOldCovered); /* * now the old cluster is notified about the new cluster */ AnnounceRemoteCluster tNewCovered = new AnnounceRemoteCluster(pAnnounce.getSenderName(), getHierarchyLevel(), pCEP.getPeerL2Address(), pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address().getComplexAddress().longValue()); tNewCovered.setCoordinatorsPriority(pAnnounce.getSenderPriority()); tNewCovered.setNegotiatorIdentification(tLocalManagedClusterName); DiscoveryEntry tCoveredEntry = new DiscoveryEntry(pAnnounce.getCoordinatorID(), pAnnounce.getSenderName(), (pCEP.getPeerL2Address()).getComplexAddress().longValue(), pCEP.getPeerL2Address(), getHierarchyLevel()); tCoveredEntry.setRoutingVectors(pCEP.getPath(pCEP.getPeerL2Address())); tNewCovered.setCoveringClusterEntry(tCoveredEntry); tCoveredEntry.setPriority(pAnnounce.getSenderPriority()); Logging.warn(this, "Rejecting " + (superiorCoordinatorComChannel().getPeerL2Address()).getDescr() + " in favor of " + pAnnounce.getSenderName()); tNewCovered.setRejection(); superiorCoordinatorComChannel().sendPacket(tNewCovered); for(ComChannel tCEP : getComChannels()) { if(pAnnounce.getCoveredNodes().contains(tCEP.getPeerL2Address())) { tCEP.setAsParticipantOfMyCluster(true); } else { tCEP.setAsParticipantOfMyCluster(false); } } setSuperiorCoordinatorID(pAnnounce.getCoordinatorID()); setSuperiorCoordinator(pCEP, pAnnounce.getSenderName(),pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address()); mHRMController.setClusterWithCoordinator(getHierarchyLevel(), this); superiorCoordinatorComChannel().sendPacket(tNewCovered); } } } } else { if (pAnnounce.getCoveredNodes() != null){ for(ComChannel tCEP : getComChannels()) { if(pAnnounce.getCoveredNodes().contains(tCEP.getPeerL2Address())) { tCEP.setAsParticipantOfMyCluster(true); } else { tCEP.setAsParticipantOfMyCluster(false); } } } setSuperiorCoordinatorID(pAnnounce.getCoordinatorID()); mHRMController.setClusterWithCoordinator(getHierarchyLevel(), this); setSuperiorCoordinator(pCEP, pAnnounce.getSenderName(), pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address()); } // } else { // /* // * this part is for the coordinator that intended to announce itself -> send rejection and send acting coordinator along with // * the announcement that is just gained a neighbor zone // */ // // NeighborClusterAnnounce tUncoveredAnnounce = new NeighborClusterAnnounce(getCoordinatorName(), getHierarchyLevel(), superiorCoordinatorL2Address(), getToken(), superiorCoordinatorL2Address().getComplexAddress().longValue()); // tUncoveredAnnounce.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority()); // /* // * the routing service address of the announcer is set once the neighbor zone announce arrives at the rejected coordinator because this // * entity is already covered // */ // // tUncoveredAnnounce.setNegotiatorIdentification(tLocalManagedClusterName); // // DiscoveryEntry tUncoveredEntry = new DiscoveryEntry(mParentCluster.getToken(), mParentCluster.getCoordinatorName(), mParentCluster.superiorCoordinatorL2Address().getComplexAddress().longValue(), mParentCluster.superiorCoordinatorL2Address(), mParentCluster.getHierarchyLevel()); // List<RoutableClusterGraphLink> tClusterList = mHRMController.getRoutableClusterGraph().getRoute(mParentCluster, pCEP.getRemoteClusterName()); // if(!tClusterList.isEmpty()) { // ICluster tPredecessor = (ICluster) mHRMController.getRoutableClusterGraph().getLinkEndNode(mParentCluster, tClusterList.get(0)); // tUncoveredEntry.setPredecessor(new ClusterName(tPredecessor.getToken(), tPredecessor.getClusterID(), tPredecessor.getHierarchyLevel())); // } // tUncoveredEntry.setPriority(getCoordinatorPriority()); // tUncoveredEntry.setRoutingVectors(pCEP.getPath(mParentCluster.superiorCoordinatorL2Address())); // tUncoveredAnnounce.setCoveringClusterEntry(tUncoveredEntry); // Logging.warn(this, "Rejecting " + (superiorCoordinatorComChannel().getPeerL2Address()).getDescr() + " in favour of " + pAnnounce.getSenderName()); // tUncoveredAnnounce.setRejection(); // pCEP.sendPacket(tUncoveredAnnounce); // // /* // * this part is for the acting coordinator, so NeighborZoneAnnounce is sent in order to announce the cluster that was just rejected // */ // // NeighborClusterAnnounce tCoveredAnnounce = new NeighborClusterAnnounce(pAnnounce.getSenderName(), getHierarchyLevel(), pCEP.getPeerL2Address(), pAnnounce.getToken(), (pCEP.getPeerL2Address()).getComplexAddress().longValue()); // tCoveredAnnounce.setCoordinatorsPriority(pAnnounce.getSenderPriority()); // //// List<Route> tPathToCoordinator = getCoordinator().getHRS().getCoordinatorRoutingMap().getRoute(pCEP.getSourceName(), pCEP.getPeerName()); // // //tCoveredAnnounce.setAnnouncer(getCoordinator().getHRS().getCoordinatorRoutingMap().getDest(tPathToCoordinator.get(0))); // tCoveredAnnounce.setNegotiatorIdentification(tLocalManagedClusterName); // DiscoveryEntry tCoveredEntry = new DiscoveryEntry(pAnnounce.getToken(), pAnnounce.getSenderName(), (pCEP.getPeerL2Address()).getComplexAddress().longValue(), pCEP.getPeerL2Address(), getHierarchyLevel()); // tCoveredEntry.setRoutingVectors(pCEP.getPath(pCEP.getPeerL2Address())); // tCoveredAnnounce.setCoveringClusterEntry(tCoveredEntry); // tCoveredEntry.setPriority(pAnnounce.getSenderPriority()); // tCoveredAnnounce.setCoordinatorsPriority(pAnnounce.getSenderPriority()); // // List<RoutableClusterGraphLink> tClusters = mHRMController.getRoutableClusterGraph().getRoute(mParentCluster, superiorCoordinatorComChannel().getRemoteClusterName()); // if(!tClusters.isEmpty()) { // ICluster tNewPredecessor = (ICluster) mHRMController.getRoutableClusterGraph().getLinkEndNode(mParentCluster, tClusters.get(0)); // tUncoveredEntry.setPredecessor(new ClusterName(tNewPredecessor.getToken(), tNewPredecessor.getClusterID(), tNewPredecessor.getHierarchyLevel())); // } // Logging.log(this, "Coordinator CEP is " + superiorCoordinatorComChannel()); // superiorCoordinatorComChannel().sendPacket(tCoveredAnnounce); // } } private ICluster addAnnouncedCluster(AnnounceRemoteCluster pAnnounce, ComChannel pCEP) { if(pAnnounce.getRoutingVectors() != null) { for(RoutingServiceLinkVector tVector : pAnnounce.getRoutingVectors()) { mHRMController.getHRS().registerRoute(tVector.getSource(), tVector.getDestination(), tVector.getPath()); } } ClusterProxy tCluster = null; if(pAnnounce.isAnnouncementFromForeign()) { Logging.log(this, " ..creating cluster proxy"); tCluster = new ClusterProxy(mParentCluster.mHRMController, pAnnounce.getCoordAddress().getComplexAddress().longValue() /* TODO: als clusterID den Wert? */, new HierarchyLevel(this, super.getHierarchyLevel().getValue() + 2), pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress(), pAnnounce.getToken()); mHRMController.setSourceIntermediateCluster(tCluster, mHRMController.getSourceIntermediateCluster(this)); tCluster.setSuperiorCoordinatorID(pAnnounce.getToken()); tCluster.setPriority(pAnnounce.getCoordinatorsPriority()); //mParentCluster.addNeighborCluster(tCluster); } else { Logging.log(this, "Cluster announced by " + pAnnounce + " is an intermediate neighbor "); } if(pAnnounce.getCoordinatorName() != null) { mHRMController.getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress()); } return tCluster; } @Override public void handleNeighborAnnouncement(AnnounceRemoteCluster pAnnounce, ComChannel pCEP) { if(pAnnounce.getCoveringClusterEntry() != null) { if(pAnnounce.isRejected()) { Logging.log(this, "Removing " + this + " as participating CEP from " + this); getComChannels().remove(this); } if(pAnnounce.getCoordinatorName() != null) { mHRMController.getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress()); } pCEP.handleDiscoveryEntry(pAnnounce.getCoveringClusterEntry()); } } @Override public void setSuperiorCoordinator(ComChannel pCoordinatorComChannel, Name pCoordinatorName, int pCoordToken, L2Address pCoordinatorL2Address) { super.setSuperiorCoordinator(pCoordinatorComChannel, pCoordinatorName, pCoordToken, pCoordinatorL2Address); Logging.log(this, "Setting channel to superior coordinator to " + pCoordinatorComChannel + " for coordinator " + pCoordinatorName + " with routing address " + pCoordinatorL2Address); Logging.log(this, "Previous channel to superior coordinator was " + superiorCoordinatorComChannel() + " with name " + mCoordinatorName); setSuperiorCoordinatorComChannel(pCoordinatorComChannel); mCoordinatorName = pCoordinatorName; synchronized(this) { notifyAll(); } // LinkedList<CoordinatorCEP> tEntitiesToNotify = new LinkedList<CoordinatorCEP> (); ClusterName tLocalManagedClusterName = new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.getCoordinatorID(), mParentCluster.getClusterID()); for(AbstractRoutingGraphNode tNeighbor: mHRMController.getNeighborsARG(mParentCluster)) { if(tNeighbor instanceof ICluster) { for(ComChannel tComChannel : getComChannels()) { if(((ControlEntity)tNeighbor).superiorCoordinatorHostL2Address().equals(tComChannel.getPeerL2Address()) && !tComChannel.isPartOfMyCluster()) { Logging.info(this, "Informing " + tComChannel + " about existence of neighbor zone "); AnnounceRemoteCluster tAnnounce = new AnnounceRemoteCluster(pCoordinatorName, getHierarchyLevel(), pCoordinatorL2Address, getCoordinatorID(), pCoordinatorL2Address.getComplexAddress().longValue()); tAnnounce.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority()); LinkedList<RoutingServiceLinkVector> tVectorList = tComChannel.getPath(pCoordinatorL2Address); tAnnounce.setRoutingVectors(tVectorList); tAnnounce.setNegotiatorIdentification(tLocalManagedClusterName); tComChannel.sendPacket(tAnnounce); } Logging.log(this, "Informed " + tComChannel + " about new neighbor zone"); } } } if(mReceivedAnnouncements != null) { for(AnnounceRemoteCluster tAnnounce : mReceivedAnnouncements) { superiorCoordinatorComChannel().sendPacket(tAnnounce); } } } /** * Generates a descriptive string about this object * * @return the descriptive string */ public String toString() { //return getClass().getSimpleName() + (mParentCluster != null ? "(" + mParentCluster.toString() + ")" : "" ) + "TK(" +mToken + ")COORD(" + mCoordinatorSignature + ")@" + mLevel; return toLocation() + "(" + (mParentCluster != null ? "Cluster" + mParentCluster.getGUIClusterID() + ", " : "") + idToString() + ")"; } @Override public String toLocation() { String tResult = getClass().getSimpleName() + getGUICoordinatorID() + "@" + mHRMController.getNodeGUIName() + "@" + (getHierarchyLevel().getValue() - 1); return tResult; } private String idToString() { if (getHRMID() == null){ return "ID=" + getClusterID() + ", CordID=" + getCoordinatorID() + ", NodePrio=" + getPriority().getValue(); }else{ return "HRMID=" + getHRMID().toString(); } } }
private void shareRouteToClusterMember(ComChannel pClusterMemberChannel) { // determine the HRMID of the cluster member HRMID tMemberHRMID = pClusterMemberChannel.getPeerHRMID(); // are we on base hierarchy level? if (getHierarchyLevel().getValue() == 1){ // TODO: isBaseLevel()){ // create the new routing table entry RoutingEntry tRoutingEntry = RoutingEntry.createRouteToDirectNeighbor(tMemberHRMID, 0 /* TODO */, 1 /* TODO */, RoutingEntry.INFINITE_DATARATE /* TODO */); // define the L2 address of the next hop in order to let "addHRMRoute" trigger the HRS instance the creation of new HRMID-to-L2ADDRESS mapping entry tRoutingEntry.setNextHopL2Address(pClusterMemberChannel.getPeerL2Address()); Logging.log(this, "SHARING ROUTE: " + tRoutingEntry); // add the entry to the local routing table mHRMController.addHRMRoute(tRoutingEntry); // store the entry for route sharing with cluster members synchronized (mSharedRoutes){ /** * Check for duplicates */ if (HRMConfig.Routing.AVOID_DUPLICATES_IN_ROUTING_TABLES){ boolean tRestartNeeded; do{ tRestartNeeded = false; for (RoutingEntry tEntry: mSharedRoutes){ // have we found a route to the same destination which uses the same next hop? //TODO: what about multiple links to the same next hop? if ((tEntry.getDest().equals(tRoutingEntry.getDest())) /* same destination? */ && (tEntry.getNextHop().equals(tRoutingEntry.getNextHop())) /* same next hop? */){ Logging.log(this, "REMOVING DUPLICATE: " + tEntry); // remove the route mSharedRoutes.remove(tEntry); // mark "shared phase" data as changed mSharedRoutesHaveChanged = true; // force a restart at the beginning of the routing table tRestartNeeded = true; //TODO: use a better(scalable) method here for removing duplicates break; } } }while(tRestartNeeded); } /** * Add the entry to the shared routing table */ mSharedRoutes.add(tRoutingEntry);//TODO: use a database per cluster member here // mark "shared phase" data as changed mSharedRoutesHaveChanged = true; } }else{ //TODO Logging.log(this, "IMPLEMENT ME - SHARING ROUTE TO: " + pClusterMemberChannel); } } /** * Checks if the "share phase" should be started or not * * @return true if the "share phase" should be started, otherwise false */ private boolean sharePhaseHasTimeout() { // determine the time between two "share phases" double tDesiredTimePeriod = mHRMController.getPeriodSharePhase(getHierarchyLevel().getValue() - 1); // determine the time when a "share phase" has to be started double tTimeNextSharePhase = mTimeOfLastSharePhase + tDesiredTimePeriod; // determine the current simulation time from the HRMCotnroller instance double tCurrentSimulationTime = mHRMController.getSimulationTime(); if (HRMConfig.DebugOutput.GUI_SHOW_TIMING_ROUTE_DISTRIBUTION){ Logging.log(this, "Checking for timeout of \"share phase\": desired time period is " + tDesiredTimePeriod + ", " + tCurrentSimulationTime + " > " + tTimeNextSharePhase + "? -> " + (tCurrentSimulationTime >= tTimeNextSharePhase)); } return (tCurrentSimulationTime >= tTimeNextSharePhase); } /** * Determines if new "share phase" data is available * * @return true if new data is available, otherwise false */ private boolean hasNewSharePhaseData() { boolean tResult = false; synchronized (mSharedRoutes){ tResult = mSharedRoutesHaveChanged; } return tResult; } /** * This function implements the "share phase". * It distributes locally stored sharable routing data among the known cluster members */ public void sharePhase() { // should we start the "share phase"? if (sharePhaseHasTimeout()){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE with cluster members on level " + (getHierarchyLevel().getValue() - 1) + "/" + (HRMConfig.Hierarchy.HEIGHT - 1)); } // store the time of this "share phase" mTimeOfLastSharePhase = mHRMController.getSimulationTime(); if ((!HRMConfig.Routing.PERIODIC_SHARE_PHASES) && (!hasNewSharePhaseData())){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE skipped because routing data hasn't changed since last signaling round"); } return; } /** * SHARE PHASE */ // determine own local cluster address HRMID tOwnClusterAddress = mParentCluster.getHRMID(); if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, " ..distributing as " + tOwnClusterAddress.toString() + " aggregated ROUTES among cluster members: " + mParentCluster.getComChannels()); } synchronized (mSharedRoutes){ // send the routing information to cluster members for(ComChannel tClusterMember : mParentCluster.getComChannels()) { RoutingInformation tRoutingInformationPacket = new RoutingInformation(tOwnClusterAddress, tClusterMember.getPeerHRMID()); // are we on base hierarchy level? if (getHierarchyLevel().getValue() == 1){ // TODO: isBaseLevel()){ /** * ADD ROUTES: routes from the cluster member to this node for every registered local HRMID. */ // determine the L2 address of this physical node L2Address tPhysNodeL2Address = mHRMController.getHRS().getCentralFNL2Address(); // iterate over all HRMIDs which are registered for this physical node for (HRMID tHRMID : mHRMController.getOwnHRMIDs()){ // create entry for cluster internal routing towards us RoutingEntry tRouteFromClusterMemberToHere = RoutingEntry.createRouteToDirectNeighbor(tHRMID, 0 /* TODO */, 1 /* TODO */, RoutingEntry.INFINITE_DATARATE /* TODO */); // define the L2 address of the next hop in order to let the receiver store it in its HRMID-to-L2ADDRESS mapping tRouteFromClusterMemberToHere.setNextHopL2Address(tPhysNodeL2Address); // add the route in the "share phase" signaling tRoutingInformationPacket.addRoute(tRouteFromClusterMemberToHere); } //TODO: need routing graph here! //TODO: routes to other cluster members }else{ //TODO: implement me } /** * Send the routing data to the cluster member */ // do we have interesting routing information? if (tRoutingInformationPacket.getRoutes().size() > 0){ tClusterMember.sendPacket(tRoutingInformationPacket); }else{ // no routing information -> no packet is sent } } /** * mark "share phase" data as known */ mSharedRoutesHaveChanged = false; } }else{ // share phase shouldn't be started, we have to wait until next trigger } } /** * This function implements the "report phase". * It sends locally stored sharable routing data to the superior coordinator */ public void reportPhase() { if (!getHierarchyLevel().isHighest()){ }else{ // we are the highest hierarchy level, no one to send topology reports to } } /** * EVENT: "eventCoordinatorRoleInvalid", triggered by the Elector, the reaction is: * 1.) create signaling packet "BullyLeave" * 2.) send the packet to the superior coordinator */ public void eventCoordinatorRoleInvalid() { Logging.log(this, "============ EVENT: Coordinator_Role_Invalid"); /** * Inform all superior clusters about the event and trigger the invalidation of this coordinator instance -> we leave all Bully elections because we are no longer a possible election winner */ if (!getHierarchyLevel().isHighest()){ // create signaling packet for signaling that we leave the Bully group BullyLeave tBullyLeavePacket = new BullyLeave(mHRMController.getNodeName(), getPriority()); sendAllSuperiorClusters(tBullyLeavePacket, true); }else{ Logging.log(this, "eventCoordinatorRoleInvalid() skips further signaling because hierarchy end is already reached at: " + (getHierarchyLevel().getValue() - 1)); } /** * Unregister from local databases */ Logging.log(this, "============ Destroying this coordinator now..."); // unregister itself as coordinator for the managed cluster mParentCluster.setCoordinator(null); // unregister from HRMController's internal database mHRMController.unregisterCoordinator(this); } /** * @param pBullyLeavePacket */ private void sendAllSuperiorClusters(Serializable pPacket, boolean pIncludeLoopback) { // get all communication channels LinkedList<ComChannel> tComChannels = getComChannels(); // get the L2Addres of the local host L2Address tLocalL2Address = mHRMController.getHRS().getCentralFNL2Address(); Logging.log(this, "Sending BROADCASTS from " + tLocalL2Address + " the packet " + pPacket + " to " + tComChannels.size() + " communication channels"); for(ComChannel tComChannel : tComChannels) { boolean tIsLoopback = tLocalL2Address.equals(tComChannel.getPeerL2Address()); if (!tIsLoopback){ Logging.log(this, " ..to " + tComChannel); }else{ Logging.log(this, " ..to LOOPBACK " + tComChannel); } if ((HRMConfig.Hierarchy.SIGNALING_INCLUDES_LOCALHOST) || (pIncludeLoopback) || (!tIsLoopback)){ // send the packet to one of the possible cluster members tComChannel.sendPacket(pPacket); }else{ Logging.log(this, " ..skipping " + (tIsLoopback ? "LOOPBACK CHANNEL" : "")); } } } /** * EVENT: "announced", triggered by Elector if the election was won and this coordinator was announced to all cluster members */ public void eventAnnouncedAsCoordinator() { /** * AUTO ADDRESS DISTRIBUTION */ if (HRMConfig.Addressing.ASSIGN_AUTOMATICALLY){ Logging.log(this, "EVENT ANNOUNCED - triggering address assignment for " + getComChannels().size() + " cluster members"); signalAddressDistribution(); } //TODO: ?? mHRMController.setSourceIntermediateCluster(this, getCluster()); /** * AUTO CLUSTERING */ if(!getHierarchyLevel().isHighest()) { if (HRMConfig.Hierarchy.CONTINUE_AUTOMATICALLY){ Logging.log(this, "EVENT ANNOUNCED - triggering clustering of this cluster's coordinator and its neighbors"); // start the clustering of this cluster's coordinator and its neighbors if it wasn't already triggered by another coordinator if (!isClustered()){ cluster(); }else{ Logging.warn(this, "Clustering is already finished for this hierarchy level, skipping cluster-request"); } } } } /** * Clusters the superior hierarchy level or tries to join an already existing superior cluster */ public void cluster() { Logging.log(this, "\n\n\n################ CLUSTERING STARTED"); /** * Try to find a matching local cluster on the superior hierarchy level */ boolean tSuperiorClusterFound = false; for(Cluster tCluster : mHRMController.getAllClusters(getHierarchyLevel())) { if (joinSuperiorCluster(tCluster)){ // we joined the superior cluster and should end the search for a superior coordinator tSuperiorClusterFound = true; break; } } /** * Explore the neighborhood and create a new superior cluster */ if (!tSuperiorClusterFound){ exploreNeighborhodAndCreateSuperiorCluster(); } } /** * Tries to join a superior cluster * * @param pSuperiorCluster the possible new superior cluster * * @return true or false to indicate success/error */ private boolean joinSuperiorCluster(ControlEntity pSuperiorCluster) { Logging.log(this, "\n\n\n################ JOINING EXISTING SUPERIOR CLUSTER " + pSuperiorCluster); return false; } /** * EVENT: initial clustering has finished */ private void eventInitialClusteringFinished() { // mark initial clustering as "finished" mInitialClusteringFinished = true; } /** * Returns if the initial clustering has already finished * * @return true or false */ public boolean isClustered() { return mInitialClusteringFinished; } //TODO: fix this +1 stuff @Override public HierarchyLevel getHierarchyLevel() { return new HierarchyLevel(this, super.getHierarchyLevel().getValue() + 1); } /** * Returns the Bully priority of the parent cluster * * @return the Bully priority */ @Override public BullyPriority getPriority() { // return the Bully priority of the managed cluster object return mParentCluster.getPriority(); } /** * Sets a new Bully priority * * @param pPriority the new Bully priority */ @Override public void setPriority(BullyPriority pPriority) { if (!getPriority().equals(pPriority)){ Logging.err(this, "Updating Bully priority from " + getPriority() + " to " + pPriority); }else{ Logging.log(this, "Trying to set same Bully priority " + getPriority()); } // update the Bully priority of the parent cluster, which is managed by this coordinator mParentCluster.setPriority(pPriority); } /** * Returns a reference to the cluster, which this coordinator manages. * * @return the managed cluster */ public Cluster getCluster() { return mParentCluster; } /** * Returns the unique ID of the parental cluster * * @return the unique cluster ID */ @Override public Long getClusterID() { return mParentCluster.getClusterID(); } /** * Checks if there already exists a connection to a neighbor coordinator * * @param pCoordinatorName the name of the neighbor coordinator * * @return true or false */ private boolean isConnectedToNeighborCoordinator(Name pCoordinatorName) { boolean tResult = false; synchronized (mConnectedNeighborCoordinators) { tResult = mConnectedNeighborCoordinators.contains(pCoordinatorName); } return tResult; } /** * Registers an already existing connection to a neighbor coordinator in order to avoid connection duplicates * * @param pCoordinatorName the name of the neighbor coordinator */ private void registerConnectionToNeighborCoordinator(Name pCoordinatorName) { synchronized (mConnectedNeighborCoordinators) { mConnectedNeighborCoordinators.add(pCoordinatorName); } } /** * Creates a cluster consisting of this coordinator and neighbor coordinators by the following steps: * 1.) querying the ARG from the HRMController for neighbor clusters within the given max. radius * 2.) trigger event "detectedNeighborCoordinator" with increasing radius */ private void exploreNeighborhodAndCreateSuperiorCluster() { Logging.log(this, "\n\n\n################ EXPLORATION STARTED on hierarchy level " + getHierarchyLevel().getValue()); // was the clustering already triggered? if (!isClustered()){ // are we already at the highest hierarchy level? if (!getHierarchyLevel().isHighest()){ int tMaxRadius = HRMConfig.Routing.EXPANSION_RADIUS; Logging.log(this, "Maximum radius is " + tMaxRadius); /** * Create the cluster ID for the new cluster, which should consist of the control entities we connect to in the next steps */ Long tIDFutureCluster = Cluster.createClusterID(); // get all known neighbor clusters ordered by their radius to the parent cluster List<AbstractRoutingGraphNode> tNeighborClustersForClustering = mHRMController.getNeighborClustersOrderedByRadiusInARG(mParentCluster); Logging.log(this, " ..neighborhood ordered by radius: " + tNeighborClustersForClustering); /** * count from radius 1 to max. radius and connect to each cluster candidate */ for(int tRadius = 1; tRadius <= tMaxRadius; tRadius++) { Logging.log(this, "\n>>> Exploring neighbors with radius (" + tRadius + "/" + tMaxRadius + ")"); // create list for storing the found neighbor clusters, which have a cluster distance equal to the current radius value List<AbstractRoutingGraphNode> tSelectedNeighborClusters = new LinkedList<AbstractRoutingGraphNode>(); List<AbstractRoutingGraphNode> tNeighborClustersForClustering_RemoveList = new LinkedList<AbstractRoutingGraphNode>(); /** * Iterate over all cluster candidates and determines the logical distance of each found candidate */ for(AbstractRoutingGraphNode tClusterCandidate : tNeighborClustersForClustering) { // is the found neighbor a Cluster object? if(tClusterCandidate instanceof Cluster) { if (tRadius == 1){ // add this Cluster object as cluster candidate because it obviously has a logical distance of 1 Logging.log(this, " ..[r=" + tRadius + "]: found Cluster candidate: " + tClusterCandidate); tSelectedNeighborClusters.add(tClusterCandidate); // remove this candidate from the global list tNeighborClustersForClustering_RemoveList.add(tClusterCandidate); }else{ // found a Cluster object but the radius is already beyond 1 } } else { // is the found neighbor a ClusterProxy object? if (tClusterCandidate instanceof ClusterProxy){ // get the proxy for this cluster ClusterProxy tClusterCandidateProxy = (ClusterProxy)tClusterCandidate; // are we already connected to this candidate? if (!isConnectedToNeighborCoordinator(tClusterCandidateProxy.getCoordinatorHostName())){ // get the logical distance to the neighbor int tNeighborClusterDistance = mHRMController.getClusterDistance(tClusterCandidateProxy); // should we connect to the found cluster candidate? if ((tNeighborClusterDistance > 0) && (tNeighborClusterDistance <= tRadius)) { // add this candidate to the list of connection targets Logging.log(this, " ..[r=" + tRadius + "]: found ClusterProxy candidate: " + tClusterCandidate); tSelectedNeighborClusters.add(tClusterCandidateProxy); // remove this candidate from the global list tNeighborClustersForClustering_RemoveList.add(tClusterCandidate); }else{ // the logical distance doesn't equal to the current radius value if (tNeighborClusterDistance > tRadius){ // we have already passed the last possible candidate -> we continue the for-loop continue; } } } }else{ Logging.err(this, "Found unsupported neighbor: " + tClusterCandidate); } } } /** * Remove all processed cluster candidates from the global candidate list in order to reduce processing time */ for (AbstractRoutingGraphNode tRemoveCandidate : tNeighborClustersForClustering_RemoveList){ tNeighborClustersForClustering.remove(tRemoveCandidate); } /** * Connect to all found cluster candidates */ for(AbstractRoutingGraphNode tNeighborCluster : tSelectedNeighborClusters) { if(tNeighborCluster instanceof ControlEntity) { ControlEntity tNeighborClusterControlEntity = (ControlEntity)tNeighborCluster; eventDetectedNeighborCoordinator(tNeighborClusterControlEntity, tIDFutureCluster); }else{ Logging.err(this, "Unsupported neighbor object: " + tNeighborCluster); } } } /** * Mark all local coordinators for this hierarchy level as "clustered" */ for(Coordinator tLocalCoordinator : mHRMController.getAllCoordinators(getHierarchyLevel())) { // trigger event "finished clustering" tLocalCoordinator.eventInitialClusteringFinished(); } }else{ Logging.warn(this, "CLUSTERING SKIPPED, no clustering on highest hierarchy level " + getHierarchyLevel().getValue() + " needed"); } }else{ Logging.warn(this, "Clustering was already triggered, clustering will be maintained"); } } /** * EVENT: detected a neighbor coordinator, we react on this event by the following steps: * 1.) use "RequestClusterParticipationProperty" for every connection to inform about the new cluster * * @param pNeighborCluster the found neighbor cluster whose coordinator is a neighbor of this one * @param pIDForFutureCluster the clusterID for the common cluster */ private void eventDetectedNeighborCoordinator(ControlEntity pNeighborCluster, Long pIDForFutureCluster) { // get the recursive FoG layer FoGEntity tFoGLayer = (FoGEntity) mHRMController.getNode().getLayer(FoGEntity.class); // get the central FN of this node L2Address tThisHostL2Address = mHRMController.getHRS().getL2AddressFor(tFoGLayer.getCentralFN()); Logging.info(this, "\n\n\n############## FOUND INFERIOR NEIGHBOR CLUSTER " + pNeighborCluster + " FOR " + tThisHostL2Address); /** * get the name of the target coordinator name */ Name tNeighborCoordinatorHostName = ((ICluster)pNeighborCluster).getCoordinatorHostName(); if(!isConnectedToNeighborCoordinator(tNeighborCoordinatorHostName)) { // store the connection to avoid connection duplicates during later processing registerConnectionToNeighborCoordinator(tNeighborCoordinatorHostName); HierarchyLevel tTargetClusterHierLvl = new HierarchyLevel(this, pNeighborCluster.getHierarchyLevel().getValue() + 1); ControlEntity tNeighborClusterControlEntity = (ControlEntity)pNeighborCluster; /** * Describe the common cluster */ Logging.log(this, " ..creating cluster description"); // create the cluster description RequestClusterParticipationProperty tRequestClusterParticipationProperty = new RequestClusterParticipationProperty(pIDForFutureCluster, tTargetClusterHierLvl, pNeighborCluster.getCoordinatorID()); /** * Create communication session */ Logging.log(this, " ..creating new communication session"); ComSession tComSession = new ComSession(mHRMController, false, getHierarchyLevel()); /** * Iterate over all local coordinators on this hierarchy level and add them as already known cluster members to the cluster description */ Logging.log(this, " ..iterate over all coordinators on hierarchy level: " + (getHierarchyLevel().getValue() - 1)); // store how many local coordinators on this hierarchy level were found int tKnownLocalCoordinatorsOnThisHierarchyLevel = 0; for(Coordinator tLocalCoordinator : mHRMController.getAllCoordinators(getHierarchyLevel())) { tKnownLocalCoordinatorsOnThisHierarchyLevel++; Logging.log(this, " ..found [" + tKnownLocalCoordinatorsOnThisHierarchyLevel + "] : " + tLocalCoordinator); /** * Create communication channel */ Logging.log(this, " ..creating new communication channel"); ComChannel tComChannel = new ComChannel(mHRMController, ComChannel.Direction.OUT, tLocalCoordinator, tComSession); tComChannel.setRemoteClusterName(new ClusterName(mHRMController, pNeighborCluster.getHierarchyLevel(), pNeighborCluster.getCoordinatorID(), pIDForFutureCluster /* HINT: we communicate with the new cluster -> us clusterID of new cluster */)); tComChannel.setPeerPriority(pNeighborCluster.getPriority()); // do we know the neighbor coordinator? (we check for a known coordinator of the neighbor cluster) if(tNeighborClusterControlEntity.superiorCoordinatorHostL2Address() != null) { Cluster tCoordinatorCluster = tLocalCoordinator.getCluster(); /** * Describe the cluster member */ Logging.log(this, " ..creating cluster member description for the found cluster " + tCoordinatorCluster); ClusterMemberDescription tClusterMemberDescription = tRequestClusterParticipationProperty.addClusterMember(tCoordinatorCluster.getClusterID(), tCoordinatorCluster.getCoordinatorID(), tCoordinatorCluster.getPriority()); tClusterMemberDescription.setSourceName(mHRMController.getNodeName()); tClusterMemberDescription.setSourceL2Address(tThisHostL2Address); /** * Iterate over all known neighbors of the current cluster member: we inform the connection target about this neighborhood topology */ for(ControlEntity tClusterMemberNeighbor: tLocalCoordinator.getCluster().getNeighborsARG()) { ICluster tIClusterNeighbor = (ICluster)tClusterMemberNeighbor; DiscoveryEntry tDiscoveryEntry = new DiscoveryEntry(tClusterMemberNeighbor.getCoordinatorID(), tIClusterNeighbor.getCoordinatorHostName(), tClusterMemberNeighbor.getClusterID(), tClusterMemberNeighbor.superiorCoordinatorHostL2Address(), tClusterMemberNeighbor.getHierarchyLevel()); tDiscoveryEntry.setPriority(tClusterMemberNeighbor.getPriority()); if(tLocalCoordinator.getPathToCoordinator(tLocalCoordinator.getCluster(), tIClusterNeighbor) != null) { for(RoutingServiceLinkVector tVector : tLocalCoordinator.getPathToCoordinator(tLocalCoordinator.getCluster(), tIClusterNeighbor)) { tDiscoveryEntry.addRoutingVectors(tVector); } } tClusterMemberDescription.addDiscoveryEntry(tDiscoveryEntry); } }else{ Logging.err(this, "eventDetectedNeighborCoordinator() didn't found the L2Address of the coordinator for: " + tNeighborClusterControlEntity); } } /** * Create connection requirements */ Description tConnectionRequirements = mHRMController.createHRMControllerDestinationDescription(); tConnectionRequirements.set(tRequestClusterParticipationProperty); ClusterDiscovery tBigDiscovery = new ClusterDiscovery(mHRMController.getNodeName()); /** * Connect to the neighbor coordinator */ Connection tConnection = null; Logging.log(this, " ..CONNECTING to: " + tNeighborCoordinatorHostName + " with requirements: " + tConnectionRequirements); tConnection = tFoGLayer.connect(tNeighborCoordinatorHostName, tConnectionRequirements, mHRMController.getNode().getIdentity()); Logging.log(this, " ..connect() FINISHED"); if (tConnection != null){ mCounterOutgoingConnections++; Logging.log(this, " ..starting this OUTGOING CONNECTION as nr. " + mCounterOutgoingConnections); tComSession.startConnection(null, tConnection); /** * Create and send ClusterDiscovery */ for(Coordinator tCoordinator : mHRMController.getAllCoordinators(new HierarchyLevel(this, getHierarchyLevel().getValue() - 1))) { LinkedList<Integer> tCoordinatorIDs = new LinkedList<Integer>(); for(ControlEntity tNeighbor : tCoordinator.getCluster().getNeighborsARG()) { if(tNeighbor.getHierarchyLevel().getValue() == tCoordinator.getHierarchyLevel().getValue() - 1) { tCoordinatorIDs.add(((ICluster) tNeighbor).getCoordinatorID()); } } tCoordinatorIDs.add(tCoordinator.getCluster().getCoordinatorID()); if(!tNeighborCoordinatorHostName.equals(mHRMController.getNodeName())) { int tDistance = 0; if (pNeighborCluster instanceof ClusterProxy){ ClusterProxy tClusterProxy = (ClusterProxy) pNeighborCluster; tDistance = mHRMController.getClusterDistance(tClusterProxy); } NestedDiscovery tNestedDiscovery = tBigDiscovery.new NestedDiscovery(tCoordinatorIDs, pNeighborCluster.getClusterID(), pNeighborCluster.getCoordinatorID(), pNeighborCluster.getHierarchyLevel(), tDistance); Logging.log(this, "Created " + tNestedDiscovery + " for " + pNeighborCluster); tNestedDiscovery.setOrigin(tCoordinator.getClusterID()); tNestedDiscovery.setTargetClusterID(tNeighborClusterControlEntity.superiorCoordinatorHostL2Address().getComplexAddress().longValue()); tBigDiscovery.addNestedDiscovery(tNestedDiscovery); } } // send the ClusterDiscovery to peer tComSession.write(tBigDiscovery); for(NestedDiscovery tDiscovery : tBigDiscovery.getDiscoveries()) { String tClusters = new String(); for(Cluster tCluster : mHRMController.getAllClusters()) { tClusters += tCluster + ", "; } String tDiscoveries = new String(); for(DiscoveryEntry tEntry : tDiscovery.getDiscoveryEntries()) { tDiscoveries += ", " + tEntry; } if(tDiscovery.getNeighborRelations() != null) { for(Tuple<ClusterName, ClusterName> tTuple : tDiscovery.getNeighborRelations()) { if(!mHRMController.isLinkedARG(tTuple.getFirst(), tTuple.getSecond())) { Cluster tFirstCluster = mHRMController.getClusterByID(tTuple.getFirst()); Cluster tSecondCluster = mHRMController.getClusterByID(tTuple.getSecond()); if(tFirstCluster != null && tSecondCluster != null ) { tFirstCluster.registerNeighborARG(tSecondCluster); Logging.log(this, "Connecting " + tFirstCluster + " with " + tSecondCluster); } else { Logging.warn(this, "Unable to find cluster " + tTuple.getFirst() + ":" + tFirstCluster + " or " + tTuple.getSecond() + ":" + tSecondCluster + " out of \"" + tClusters + "\", cluster discovery contained " + tDiscoveries + " and CEP is " + tComSession); } } } } else { Logging.warn(this, tDiscovery + "does not contain any neighbor relations"); } } }else{ Logging.err(this, "eventDetectedNeighborCoordinator() wasn't able to connect to: " + tNeighborCoordinatorHostName); } }else{ Logging.warn(this, "eventDetectedNeighborCoordinator() skips this connection request because there exist already a connection to: " + tNeighborCoordinatorHostName); } } /** * EVENT: "superior cluster coordinator was announced", triggered by Elector */ public void eventSuperiorClusterCoordinatorAnnounced(BullyAnnounce pAnnouncePacket, ComChannel pComChannel) { // store superior coordinator data setSuperiorCoordinator(pComChannel, pAnnouncePacket.getSenderName(), pAnnouncePacket.getCoordinatorID(), pComChannel.getPeerL2Address()); } public void storeAnnouncement(AnnounceRemoteCluster pAnnounce) { Logging.log(this, "Storing " + pAnnounce); if(mReceivedAnnouncements == null) { mReceivedAnnouncements = new LinkedList<AnnounceRemoteCluster>(); } pAnnounce.setNegotiatorIdentification(new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.superiorCoordinatorID(), mParentCluster.getClusterID())); mReceivedAnnouncements.add(pAnnounce); } public LinkedList<Long> getBounces() { return mBouncedAnnounces; } private LinkedList<RoutingServiceLinkVector> getPathToCoordinator(ICluster pSourceCluster, ICluster pDestinationCluster) { List<Route> tCoordinatorPath = mHRMController.getHRS().getCoordinatorRoutingMap().getRoute(((ControlEntity)pSourceCluster).superiorCoordinatorHostL2Address(), ((ControlEntity)pDestinationCluster).superiorCoordinatorHostL2Address()); LinkedList<RoutingServiceLinkVector> tVectorList = new LinkedList<RoutingServiceLinkVector>(); if(tCoordinatorPath != null) { for(Route tPath : tCoordinatorPath) { tVectorList.add(new RoutingServiceLinkVector(tPath, mHRMController.getHRS().getCoordinatorRoutingMap().getSource(tPath), mHRMController.getHRS().getCoordinatorRoutingMap().getDest(tPath))); } } return tVectorList; } @Override public Name getCoordinatorHostName() { return mCoordinatorName; } @Override public void setCoordinatorHostName(Name pCoordName) { mCoordinatorName = pCoordName; } public void eventClusterCoordinatorAnnounced(BullyAnnounce pAnnounce, ComChannel pCEP) { /** * the name of the cluster, which is managed by this coordinator */ ClusterName tLocalManagedClusterName = new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.superiorCoordinatorID(), mParentCluster.getClusterID()); /* * check whether old priority was lower than new priority */ // if(pAnnounce.getSenderPriority().isHigher(this, getCoordinatorPriority())) { /* * check whether a coordinator is already set */ if(superiorCoordinatorComChannel() != null) { if(getCoordinatorHostName() != null && !pAnnounce.getSenderName().equals(getCoordinatorHostName())) { /* * a coordinator was set earlier -> therefore inter-cluster communicatino is necessary * * find the route from the managed cluster to the cluster this entity got to know the higher cluster */ List<AbstractRoutingGraphLink> tRouteARG = mHRMController.getRouteARG(mParentCluster, pCEP.getRemoteClusterName()); if(tRouteARG.size() > 0) { if(mHRMController.getOtherEndOfLinkARG(pCEP.getRemoteClusterName(), tRouteARG.get(tRouteARG.size() - 1)) instanceof Cluster) { Logging.warn(this, "Not sending neighbor zone announce because another intermediate cluster has a shorter route to target"); if(tRouteARG != null) { String tClusterRoute = new String(); AbstractRoutingGraphNode tRouteARGNode = mParentCluster; for(AbstractRoutingGraphLink tConnection : tRouteARG) { tClusterRoute += tRouteARGNode + "\n"; tRouteARGNode = mHRMController.getOtherEndOfLinkARG(tRouteARGNode, tConnection); } Logging.log(this, "cluster route to other entity:\n" + tClusterRoute); } } else { /* * This is for the new coordinator - he is being notified about the fact that this cluster belongs to another coordinator * * If there are intermediate clusters between the managed cluster of this cluster manager we do not send the announcement because in that case * the forwarding would get inconsistent * * If this is a rejection the forwarding cluster as to be calculated by the receiver of this neighbor zone announcement */ AnnounceRemoteCluster tOldCovered = new AnnounceRemoteCluster(getCoordinatorHostName(), getHierarchyLevel(), superiorCoordinatorHostL2Address(),getCoordinatorID(), superiorCoordinatorHostL2Address().getComplexAddress().longValue()); tOldCovered.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority()); tOldCovered.setNegotiatorIdentification(tLocalManagedClusterName); DiscoveryEntry tOldCoveredEntry = new DiscoveryEntry(mParentCluster.getCoordinatorID(), mParentCluster.getCoordinatorHostName(), mParentCluster.superiorCoordinatorHostL2Address().getComplexAddress().longValue(), mParentCluster.superiorCoordinatorHostL2Address(), mParentCluster.getHierarchyLevel()); /* * the forwarding cluster to the newly discovered cluster has to be one level lower so it is forwarded on the correct cluster * * calculation of the predecessor is because the cluster identification on the remote site is multiplexed */ tRouteARG = mHRMController.getRouteARG(mParentCluster, superiorCoordinatorComChannel().getRemoteClusterName()); tOldCoveredEntry.setPriority(superiorCoordinatorComChannel().getPeerPriority()); tOldCoveredEntry.setRoutingVectors(pCEP.getPath(mParentCluster.superiorCoordinatorHostL2Address())); tOldCovered.setCoveringClusterEntry(tOldCoveredEntry); //tOldCovered.setAnnouncer(getCoordinator().getHRS().getCoordinatorRoutingMap().getDest(tPathToCoordinator.get(0))); pCEP.sendPacket(tOldCovered); /* * now the old cluster is notified about the new cluster */ AnnounceRemoteCluster tNewCovered = new AnnounceRemoteCluster(pAnnounce.getSenderName(), getHierarchyLevel(), pCEP.getPeerL2Address(), pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address().getComplexAddress().longValue()); tNewCovered.setCoordinatorsPriority(pAnnounce.getSenderPriority()); tNewCovered.setNegotiatorIdentification(tLocalManagedClusterName); DiscoveryEntry tCoveredEntry = new DiscoveryEntry(pAnnounce.getCoordinatorID(), pAnnounce.getSenderName(), (pCEP.getPeerL2Address()).getComplexAddress().longValue(), pCEP.getPeerL2Address(), getHierarchyLevel()); tCoveredEntry.setRoutingVectors(pCEP.getPath(pCEP.getPeerL2Address())); tNewCovered.setCoveringClusterEntry(tCoveredEntry); tCoveredEntry.setPriority(pAnnounce.getSenderPriority()); Logging.warn(this, "Rejecting " + (superiorCoordinatorComChannel().getPeerL2Address()).getDescr() + " in favor of " + pAnnounce.getSenderName()); tNewCovered.setRejection(); superiorCoordinatorComChannel().sendPacket(tNewCovered); for(ComChannel tCEP : getComChannels()) { if(pAnnounce.getCoveredNodes().contains(tCEP.getPeerL2Address())) { tCEP.setAsParticipantOfMyCluster(true); } else { tCEP.setAsParticipantOfMyCluster(false); } } setSuperiorCoordinatorID(pAnnounce.getCoordinatorID()); setSuperiorCoordinator(pCEP, pAnnounce.getSenderName(),pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address()); mHRMController.setClusterWithCoordinator(getHierarchyLevel(), this); superiorCoordinatorComChannel().sendPacket(tNewCovered); } } } } else { if (pAnnounce.getCoveredNodes() != null){ for(ComChannel tCEP : getComChannels()) { if(pAnnounce.getCoveredNodes().contains(tCEP.getPeerL2Address())) { tCEP.setAsParticipantOfMyCluster(true); } else { tCEP.setAsParticipantOfMyCluster(false); } } } setSuperiorCoordinatorID(pAnnounce.getCoordinatorID()); mHRMController.setClusterWithCoordinator(getHierarchyLevel(), this); setSuperiorCoordinator(pCEP, pAnnounce.getSenderName(), pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address()); } // } else { // /* // * this part is for the coordinator that intended to announce itself -> send rejection and send acting coordinator along with // * the announcement that is just gained a neighbor zone // */ // // NeighborClusterAnnounce tUncoveredAnnounce = new NeighborClusterAnnounce(getCoordinatorName(), getHierarchyLevel(), superiorCoordinatorL2Address(), getToken(), superiorCoordinatorL2Address().getComplexAddress().longValue()); // tUncoveredAnnounce.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority()); // /* // * the routing service address of the announcer is set once the neighbor zone announce arrives at the rejected coordinator because this // * entity is already covered // */ // // tUncoveredAnnounce.setNegotiatorIdentification(tLocalManagedClusterName); // // DiscoveryEntry tUncoveredEntry = new DiscoveryEntry(mParentCluster.getToken(), mParentCluster.getCoordinatorName(), mParentCluster.superiorCoordinatorL2Address().getComplexAddress().longValue(), mParentCluster.superiorCoordinatorL2Address(), mParentCluster.getHierarchyLevel()); // List<RoutableClusterGraphLink> tClusterList = mHRMController.getRoutableClusterGraph().getRoute(mParentCluster, pCEP.getRemoteClusterName()); // if(!tClusterList.isEmpty()) { // ICluster tPredecessor = (ICluster) mHRMController.getRoutableClusterGraph().getLinkEndNode(mParentCluster, tClusterList.get(0)); // tUncoveredEntry.setPredecessor(new ClusterName(tPredecessor.getToken(), tPredecessor.getClusterID(), tPredecessor.getHierarchyLevel())); // } // tUncoveredEntry.setPriority(getCoordinatorPriority()); // tUncoveredEntry.setRoutingVectors(pCEP.getPath(mParentCluster.superiorCoordinatorL2Address())); // tUncoveredAnnounce.setCoveringClusterEntry(tUncoveredEntry); // Logging.warn(this, "Rejecting " + (superiorCoordinatorComChannel().getPeerL2Address()).getDescr() + " in favour of " + pAnnounce.getSenderName()); // tUncoveredAnnounce.setRejection(); // pCEP.sendPacket(tUncoveredAnnounce); // // /* // * this part is for the acting coordinator, so NeighborZoneAnnounce is sent in order to announce the cluster that was just rejected // */ // // NeighborClusterAnnounce tCoveredAnnounce = new NeighborClusterAnnounce(pAnnounce.getSenderName(), getHierarchyLevel(), pCEP.getPeerL2Address(), pAnnounce.getToken(), (pCEP.getPeerL2Address()).getComplexAddress().longValue()); // tCoveredAnnounce.setCoordinatorsPriority(pAnnounce.getSenderPriority()); // //// List<Route> tPathToCoordinator = getCoordinator().getHRS().getCoordinatorRoutingMap().getRoute(pCEP.getSourceName(), pCEP.getPeerName()); // // //tCoveredAnnounce.setAnnouncer(getCoordinator().getHRS().getCoordinatorRoutingMap().getDest(tPathToCoordinator.get(0))); // tCoveredAnnounce.setNegotiatorIdentification(tLocalManagedClusterName); // DiscoveryEntry tCoveredEntry = new DiscoveryEntry(pAnnounce.getToken(), pAnnounce.getSenderName(), (pCEP.getPeerL2Address()).getComplexAddress().longValue(), pCEP.getPeerL2Address(), getHierarchyLevel()); // tCoveredEntry.setRoutingVectors(pCEP.getPath(pCEP.getPeerL2Address())); // tCoveredAnnounce.setCoveringClusterEntry(tCoveredEntry); // tCoveredEntry.setPriority(pAnnounce.getSenderPriority()); // tCoveredAnnounce.setCoordinatorsPriority(pAnnounce.getSenderPriority()); // // List<RoutableClusterGraphLink> tClusters = mHRMController.getRoutableClusterGraph().getRoute(mParentCluster, superiorCoordinatorComChannel().getRemoteClusterName()); // if(!tClusters.isEmpty()) { // ICluster tNewPredecessor = (ICluster) mHRMController.getRoutableClusterGraph().getLinkEndNode(mParentCluster, tClusters.get(0)); // tUncoveredEntry.setPredecessor(new ClusterName(tNewPredecessor.getToken(), tNewPredecessor.getClusterID(), tNewPredecessor.getHierarchyLevel())); // } // Logging.log(this, "Coordinator CEP is " + superiorCoordinatorComChannel()); // superiorCoordinatorComChannel().sendPacket(tCoveredAnnounce); // } } private ICluster addAnnouncedCluster(AnnounceRemoteCluster pAnnounce, ComChannel pCEP) { if(pAnnounce.getRoutingVectors() != null) { for(RoutingServiceLinkVector tVector : pAnnounce.getRoutingVectors()) { mHRMController.getHRS().registerRoute(tVector.getSource(), tVector.getDestination(), tVector.getPath()); } } ClusterProxy tCluster = null; if(pAnnounce.isAnnouncementFromForeign()) { Logging.log(this, " ..creating cluster proxy"); tCluster = new ClusterProxy(mParentCluster.mHRMController, pAnnounce.getCoordAddress().getComplexAddress().longValue() /* TODO: als clusterID den Wert? */, new HierarchyLevel(this, super.getHierarchyLevel().getValue() + 2), pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress(), pAnnounce.getToken()); mHRMController.setSourceIntermediateCluster(tCluster, mHRMController.getSourceIntermediateCluster(this)); tCluster.setSuperiorCoordinatorID(pAnnounce.getToken()); tCluster.setPriority(pAnnounce.getCoordinatorsPriority()); //mParentCluster.addNeighborCluster(tCluster); } else { Logging.log(this, "Cluster announced by " + pAnnounce + " is an intermediate neighbor "); } if(pAnnounce.getCoordinatorName() != null) { mHRMController.getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress()); } return tCluster; } @Override public void handleNeighborAnnouncement(AnnounceRemoteCluster pAnnounce, ComChannel pCEP) { if(pAnnounce.getCoveringClusterEntry() != null) { if(pAnnounce.isRejected()) { Logging.log(this, "Removing " + this + " as participating CEP from " + this); getComChannels().remove(this); } if(pAnnounce.getCoordinatorName() != null) { mHRMController.getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress()); } pCEP.handleDiscoveryEntry(pAnnounce.getCoveringClusterEntry()); } } @Override public void setSuperiorCoordinator(ComChannel pCoordinatorComChannel, Name pCoordinatorName, int pCoordToken, L2Address pCoordinatorL2Address) { super.setSuperiorCoordinator(pCoordinatorComChannel, pCoordinatorName, pCoordToken, pCoordinatorL2Address); Logging.log(this, "Setting channel to superior coordinator to " + pCoordinatorComChannel + " for coordinator " + pCoordinatorName + " with routing address " + pCoordinatorL2Address); Logging.log(this, "Previous channel to superior coordinator was " + superiorCoordinatorComChannel() + " with name " + mCoordinatorName); setSuperiorCoordinatorComChannel(pCoordinatorComChannel); mCoordinatorName = pCoordinatorName; synchronized(this) { notifyAll(); } // LinkedList<CoordinatorCEP> tEntitiesToNotify = new LinkedList<CoordinatorCEP> (); ClusterName tLocalManagedClusterName = new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.getCoordinatorID(), mParentCluster.getClusterID()); for(AbstractRoutingGraphNode tNeighbor: mHRMController.getNeighborsARG(mParentCluster)) { if(tNeighbor instanceof ICluster) { for(ComChannel tComChannel : getComChannels()) { if(((ControlEntity)tNeighbor).superiorCoordinatorHostL2Address().equals(tComChannel.getPeerL2Address()) && !tComChannel.isPartOfMyCluster()) { Logging.info(this, "Informing " + tComChannel + " about existence of neighbor zone "); AnnounceRemoteCluster tAnnounce = new AnnounceRemoteCluster(pCoordinatorName, getHierarchyLevel(), pCoordinatorL2Address, getCoordinatorID(), pCoordinatorL2Address.getComplexAddress().longValue()); tAnnounce.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority()); LinkedList<RoutingServiceLinkVector> tVectorList = tComChannel.getPath(pCoordinatorL2Address); tAnnounce.setRoutingVectors(tVectorList); tAnnounce.setNegotiatorIdentification(tLocalManagedClusterName); tComChannel.sendPacket(tAnnounce); } Logging.log(this, "Informed " + tComChannel + " about new neighbor zone"); } } } if(mReceivedAnnouncements != null) { for(AnnounceRemoteCluster tAnnounce : mReceivedAnnouncements) { superiorCoordinatorComChannel().sendPacket(tAnnounce); } } } /** * Generates a descriptive string about this object * * @return the descriptive string */ public String toString() { //return getClass().getSimpleName() + (mParentCluster != null ? "(" + mParentCluster.toString() + ")" : "" ) + "TK(" +mToken + ")COORD(" + mCoordinatorSignature + ")@" + mLevel; return toLocation() + "(" + (mParentCluster != null ? "Cluster" + mParentCluster.getGUIClusterID() + ", " : "") + idToString() + ")"; } @Override public String toLocation() { String tResult = getClass().getSimpleName() + getGUICoordinatorID() + "@" + mHRMController.getNodeGUIName() + "@" + (getHierarchyLevel().getValue() - 1); return tResult; } private String idToString() { if (getHRMID() == null){ return "ID=" + getClusterID() + ", CordID=" + getCoordinatorID() + ", NodePrio=" + getPriority().getValue(); }else{ return "HRMID=" + getHRMID().toString(); } } }