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/org.apache.felix.dependencymanager/src/main/java/org/apache/felix/dependencymanager/ServiceRegistrationImpl.java b/org.apache.felix.dependencymanager/src/main/java/org/apache/felix/dependencymanager/ServiceRegistrationImpl.java index dc15d5f84..38eadcca5 100644 --- a/org.apache.felix.dependencymanager/src/main/java/org/apache/felix/dependencymanager/ServiceRegistrationImpl.java +++ b/org.apache.felix.dependencymanager/src/main/java/org/apache/felix/dependencymanager/ServiceRegistrationImpl.java @@ -1,89 +1,89 @@ /* * Copyright 2006 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.felix.dependencymanager; import java.util.Dictionary; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; /** * A wrapper around a service registration that blocks until the * service registration is available. * * @author <a href="mailto:[email protected]">Felix Project Team</a> */ public class ServiceRegistrationImpl implements ServiceRegistration { public static final ServiceRegistrationImpl ILLEGAL_STATE = new ServiceRegistrationImpl(); private ServiceRegistration m_registration; public ServiceRegistrationImpl() { m_registration = null; } public ServiceReference getReference() { ensureRegistration(); return m_registration.getReference(); } public void setProperties(Dictionary dictionary) { ensureRegistration(); m_registration.setProperties(dictionary); } public void unregister() { ensureRegistration(); m_registration.unregister(); } public boolean equals(Object obj) { ensureRegistration(); return m_registration.equals(obj); } public int hashCode() { ensureRegistration(); return m_registration.hashCode(); } public String toString() { ensureRegistration(); return m_registration.toString(); } private synchronized void ensureRegistration() { while (m_registration == null) { try { wait(); } catch (InterruptedException ie) { // we were interrupted so hopefully we will now have a // service registration ready; if not we wait again } } - if (ILLEGAL_STATE.equals(m_registration)) { + if (ILLEGAL_STATE == m_registration) { throw new IllegalStateException("Service is not registered."); } } void setServiceRegistration(ServiceRegistration registration) { m_registration = registration; synchronized (this) { notifyAll(); } } }
true
true
private synchronized void ensureRegistration() { while (m_registration == null) { try { wait(); } catch (InterruptedException ie) { // we were interrupted so hopefully we will now have a // service registration ready; if not we wait again } } if (ILLEGAL_STATE.equals(m_registration)) { throw new IllegalStateException("Service is not registered."); } }
private synchronized void ensureRegistration() { while (m_registration == null) { try { wait(); } catch (InterruptedException ie) { // we were interrupted so hopefully we will now have a // service registration ready; if not we wait again } } if (ILLEGAL_STATE == m_registration) { throw new IllegalStateException("Service is not registered."); } }
diff --git a/bennu-core/src/myorg/_development/PropertiesManager.java b/bennu-core/src/myorg/_development/PropertiesManager.java index a1a39464..07793812 100755 --- a/bennu-core/src/myorg/_development/PropertiesManager.java +++ b/bennu-core/src/myorg/_development/PropertiesManager.java @@ -1,117 +1,117 @@ /* * @(#)PropertiesManager.java * * Copyright 2009 Instituto Superior Tecnico * Founding Authors: João Figueiredo, Luis Cruz, Paulo Abrantes, Susana Fernandes * * https://fenix-ashes.ist.utl.pt/ * * This file is part of the MyOrg web application infrastructure. * * MyOrg 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.* * * MyOrg 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 MyOrg. If not, see <http://www.gnu.org/licenses/>. * */ package myorg._development; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Properties; import myorg.domain.MyOrg; import pt.ist.fenixWebFramework.Config; import pt.ist.fenixWebFramework.Config.CasConfig; /** * The <code>PropertiesManager</code> class is a application wide utility for * accessing the applications configuration and properties. * * @author João Figueiredo * @author Luis Cruz * @author Paulo Abrantes * @author Susana Fernandes * * @version 1.0 */ public class PropertiesManager extends pt.utl.ist.fenix.tools.util.PropertiesManager { private static final Properties properties = new Properties(); static { try { loadProperties(properties, "/configuration.properties"); } catch (IOException e) { throw new RuntimeException("Unable to load properties files.", e); } } public static String getProperty(final String key) { return properties.getProperty(key); } public static boolean getBooleanProperty(final String key) { return Boolean.parseBoolean(properties.getProperty(key)); } public static Integer getIntegerProperty(final String key) { return Integer.valueOf(properties.getProperty(key)); } public static void setProperty(final String key, final String value) { properties.setProperty(key, value); } public static Config getFenixFrameworkConfig(final String[] domainModels) { final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>(); for (final Object key : properties.keySet()) { final String property = (String) key; int i = property.indexOf(".cas.enable"); if (i >= 0) { final String hostname = property.substring(0, i); if (getBooleanProperty(property)) { final String casLoginUrl = getProperty(hostname + ".cas.loginUrl"); final String casLogoutUrl = getProperty(hostname + ".cas.logoutUrl"); final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl"); final String serviceUrl = getProperty(hostname + ".cas.serviceUrl"); final CasConfig casConfig = new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl); casConfigMap.put(hostname, casConfig); } } } return new Config() {{ domainModelPaths = domainModels; dbAlias = getProperty("db.alias"); dbUsername = getProperty("db.user"); dbPassword = getProperty("db.pass"); appName = getProperty("app.name"); appContext = getProperty("app.context"); filterRequestWithDigest = getBooleanProperty("filter.request.with.digest"); tamperingRedirect = getProperty("digest.tampering.url"); errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object"); defaultLanguage = getProperty("language"); defaultLocation = getProperty("location"); defaultVariant = getProperty("variant"); updateDataRepositoryStructure = true; updateRepositoryStructureIfNeeded = true; casConfigByHost = Collections.unmodifiableMap(casConfigMap); rootClass = MyOrg.class; - javascriptValidationEnabled = true; + javascriptValidationEnabled = false; }}; } }
true
true
public static Config getFenixFrameworkConfig(final String[] domainModels) { final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>(); for (final Object key : properties.keySet()) { final String property = (String) key; int i = property.indexOf(".cas.enable"); if (i >= 0) { final String hostname = property.substring(0, i); if (getBooleanProperty(property)) { final String casLoginUrl = getProperty(hostname + ".cas.loginUrl"); final String casLogoutUrl = getProperty(hostname + ".cas.logoutUrl"); final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl"); final String serviceUrl = getProperty(hostname + ".cas.serviceUrl"); final CasConfig casConfig = new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl); casConfigMap.put(hostname, casConfig); } } } return new Config() {{ domainModelPaths = domainModels; dbAlias = getProperty("db.alias"); dbUsername = getProperty("db.user"); dbPassword = getProperty("db.pass"); appName = getProperty("app.name"); appContext = getProperty("app.context"); filterRequestWithDigest = getBooleanProperty("filter.request.with.digest"); tamperingRedirect = getProperty("digest.tampering.url"); errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object"); defaultLanguage = getProperty("language"); defaultLocation = getProperty("location"); defaultVariant = getProperty("variant"); updateDataRepositoryStructure = true; updateRepositoryStructureIfNeeded = true; casConfigByHost = Collections.unmodifiableMap(casConfigMap); rootClass = MyOrg.class; javascriptValidationEnabled = true; }}; }
public static Config getFenixFrameworkConfig(final String[] domainModels) { final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>(); for (final Object key : properties.keySet()) { final String property = (String) key; int i = property.indexOf(".cas.enable"); if (i >= 0) { final String hostname = property.substring(0, i); if (getBooleanProperty(property)) { final String casLoginUrl = getProperty(hostname + ".cas.loginUrl"); final String casLogoutUrl = getProperty(hostname + ".cas.logoutUrl"); final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl"); final String serviceUrl = getProperty(hostname + ".cas.serviceUrl"); final CasConfig casConfig = new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl); casConfigMap.put(hostname, casConfig); } } } return new Config() {{ domainModelPaths = domainModels; dbAlias = getProperty("db.alias"); dbUsername = getProperty("db.user"); dbPassword = getProperty("db.pass"); appName = getProperty("app.name"); appContext = getProperty("app.context"); filterRequestWithDigest = getBooleanProperty("filter.request.with.digest"); tamperingRedirect = getProperty("digest.tampering.url"); errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object"); defaultLanguage = getProperty("language"); defaultLocation = getProperty("location"); defaultVariant = getProperty("variant"); updateDataRepositoryStructure = true; updateRepositoryStructureIfNeeded = true; casConfigByHost = Collections.unmodifiableMap(casConfigMap); rootClass = MyOrg.class; javascriptValidationEnabled = false; }}; }
diff --git a/components/dotnet-executable/src/main/java/npanday/executable/compiler/impl/DefaultCompiler.java b/components/dotnet-executable/src/main/java/npanday/executable/compiler/impl/DefaultCompiler.java index 0e971bf7..0bc2e0ef 100644 --- a/components/dotnet-executable/src/main/java/npanday/executable/compiler/impl/DefaultCompiler.java +++ b/components/dotnet-executable/src/main/java/npanday/executable/compiler/impl/DefaultCompiler.java @@ -1,343 +1,353 @@ /* * 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 npanday.executable.compiler.impl; import org.apache.maven.artifact.Artifact; import org.codehaus.plexus.util.FileUtils; import java.util.Date; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.io.File; import npanday.executable.CommandFilter; import npanday.executable.ExecutionException; import npanday.vendor.Vendor; import npanday.executable.compiler.CompilerConfig; /** * A default compiler that can be used in most cases. * * @author Shane Isbell */ public final class DefaultCompiler extends BaseCompiler { public boolean failOnErrorOutput() { //MONO writes warnings to standard error: this turns off failing builds on warnings for MONO return !compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MONO ); } public List<String> getCommands() throws ExecutionException { if ( compilerContext == null ) { throw new ExecutionException( "NPANDAY-068-000: Compiler has not been initialized with a context" ); } CompilerConfig config = compilerContext.getNetCompilerConfig(); // references uses directLibraryDependencies for non transitive dependencies List<Artifact> references = compilerContext.getDirectLibraryDependencies(); List<Artifact> modules = compilerContext.getDirectModuleDependencies(); String sourceDirectory = compilerContext.getSourceDirectoryName(); String artifactFilePath = compilerContext.getArtifact().getAbsolutePath(); String targetArtifactType = config.getArtifactType().getTargetCompileType(); compilerContext.getCompilerRequirement().getFrameworkVersion(); List<String> commands = new ArrayList<String>(); if(config.getOutputDirectory() != null) { File f = new File(config.getOutputDirectory(), compilerContext.getArtifact().getName()); artifactFilePath = f.getAbsolutePath(); } if(artifactFilePath!=null && artifactFilePath.toLowerCase().endsWith(".zip")) { artifactFilePath = artifactFilePath.substring(0, artifactFilePath.length() - 3) + "dll"; } commands.add( "/out:" + artifactFilePath); commands.add( "/target:" + targetArtifactType ); if(config.getIncludeSources() == null || config.getIncludeSources().isEmpty() ) { commands.add( "/recurse:" + sourceDirectory + File.separator + "**"); } if ( modules != null && !modules.isEmpty() ) { StringBuffer sb = new StringBuffer(); for ( Iterator i = modules.iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); String path = artifact.getFile().getAbsolutePath(); sb.append( path ); if ( i.hasNext() ) { sb.append( ";" ); } } commands.add( "/addmodule:" + sb.toString() ); } if ( !references.isEmpty() ) { for ( Artifact artifact : references ) { String path = artifact.getFile().getAbsolutePath(); if( !path.contains( ".jar" ) ) { commands.add( "/reference:" + path ); } } } for ( String arg : compilerContext.getEmbeddedResourceArgs() ) { if (logger.isDebugEnabled()) { logger.debug( "NPANDAY-168-001 add resource: " + arg ); } commands.add( "/resource:" + arg ); } for ( File file : compilerContext.getLinkedResources() ) { commands.add( "/linkresource:" + file.getAbsolutePath() ); } for ( File file : compilerContext.getWin32Resources() ) { commands.add( "/win32res:" + file.getAbsolutePath() ); } if ( compilerContext.getWin32Icon() != null ) { commands.add( "/win32icon:" + compilerContext.getWin32Icon().getAbsolutePath() ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) ) { commands.add( "/nologo" ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) && compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.0" ) ) { String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) + "\\Microsoft.NET\\Framework\\v3.0\\Windows Communication Foundation\\"; //TODO: This is a hard-coded path: Don't have a registry value either. //commands.add( wcfRef + "System.ServiceModel.dll" ); commands.add( wcfRef + "Microsoft.Transactions.Bridge.dll" ); commands.add( wcfRef + "Microsoft.Transactions.Bridge.Dtc.dll" ); commands.add( wcfRef + "System.ServiceModel.Install.dll" ); commands.add( wcfRef + "System.ServiceModel.WasHosting.dll" ); //commands.add( wcfRef + "System.Runtime.Serialization.dll" ); commands.add( wcfRef + "SMDiagnostics.dll" ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) && compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.5" ) ) { String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) + "\\Microsoft.NET\\Framework\\v3.5\\"; //TODO: This is a hard-coded path: Don't have a registry value either. commands.add( wcfRef + "Microsoft.Build.Tasks.v3.5.dll" ); String cfBuildTasks = wcfRef + "Microsoft.CompactFramework.Build.Tasks.dll"; if (new File( cfBuildTasks ).exists()) { commands.add( cfBuildTasks ); } commands.add( wcfRef + "Microsoft.Data.Entity.Build.Tasks.dll" ); commands.add( wcfRef + "Microsoft.VisualC.STLCLR.dll" ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) && compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "4.0" ) ) { String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) + "\\Microsoft.NET\\Framework\\v4.0.30319\\"; //TODO: This is a hard-coded path: Don't have a registry value either. commands.add( wcfRef + "Microsoft.Build.Tasks.v4.0.dll" ); commands.add( wcfRef + "Microsoft.Data.Entity.Build.Tasks.dll" ); commands.add( wcfRef + "Microsoft.VisualC.STLCLR.dll" ); } if ( compilerContext.getKeyInfo().getKeyFileUri() != null ) { commands.add( "/keyfile:" + compilerContext.getKeyInfo().getKeyFileUri() ); } else if ( compilerContext.getKeyInfo().getKeyContainerName() != null ) { commands.add( "/keycontainer:" + compilerContext.getKeyInfo().getKeyContainerName() ); } if ( config.getCommands() != null ) { commands.addAll( config.getCommands() ); } commands.add( "/warnaserror-" ); //commands.add( "/nowarn" ); -// if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MONO ) ) -// { -// commands.add( "/reference:System.Drawing" ); -// commands.add( "/reference:System.Windows.Forms" ); -// commands.add( "/reference:System.Web.Services" ); -// } + if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MONO ) ) + { + commands.add( "/nostdlib" ); + commands.add( "/noconfig" ); + commands.add( "/reference:mscorlib" ); + commands.add( "/reference:System.Data" ); + commands.add( "/reference:System" ); + commands.add( "/reference:System.Drawing" ); + commands.add( "/reference:System.Messaging" ); + commands.add( "/reference:System.Web.Services" ); + commands.add( "/reference:System.Windows.Forms" ); + commands.add( "/reference:System.Xml" ); + commands.add( "/reference:System.Core" ); + commands.add( "/reference:System.Data.DataSetExtensions" ); + commands.add( "/reference:System.Xml.Linq" ); + } if ( !compilerContext.getNetCompilerConfig().isTestCompile() ) { commands.add( "/doc:" + new File( compilerContext.getTargetDirectory(), "comments.xml" ).getAbsolutePath() ); } CommandFilter filter = compilerContext.getCommandFilter(); List<String> filteredCommands = filter.filter( commands ); //Include Sources code is being copied to temporary folder for the recurse option String fileExt = ""; String frameWorkVer = ""+compilerContext.getCompilerRequirement().getFrameworkVersion(); String TempDir = ""; String targetDir = ""+compilerContext.getTargetDirectory(); Date date = new Date(); String Now =""+date.getDate()+date.getHours()+date.getMinutes()+date.getSeconds(); TempDir = targetDir+File.separator+Now; try { FileUtils.deleteDirectory( TempDir ); } catch(Exception e) { //Does Precautionary delete for tempDir } FileUtils.mkdir(TempDir); if(config.getIncludeSources() != null && !config.getIncludeSources().isEmpty() ) { int folderCtr=0; for(String includeSource : config.getIncludeSources()) { String[] sourceTokens = includeSource.replace('\\', '/').split("/"); String lastToken = sourceTokens[sourceTokens.length-1]; if(fileExt=="") { String[] extToken = lastToken.split( "\\." ); fileExt = "."+extToken[extToken.length-1]; } try { String fileToCheck = TempDir+File.separator+lastToken; if(FileUtils.fileExists( fileToCheck )) { String subTempDir = TempDir+File.separator+folderCtr+File.separator; FileUtils.mkdir( subTempDir ); FileUtils.copyFileToDirectory( includeSource, subTempDir); folderCtr++; } else { FileUtils.copyFileToDirectory( includeSource, TempDir); } } catch(Exception e) { System.out.println(e.getMessage()); } //part of original code. //filteredCommands.add(includeSource); } String recurseCmd = "/recurse:" + TempDir+File.separator + "*" + fileExt + ""; filteredCommands.add(recurseCmd); } if ( logger.isDebugEnabled() ) { logger.debug( "commands: " + filteredCommands ); } String responseFilePath = TempDir + File.separator + "responsefile.rsp"; try { for(String command : filteredCommands) { FileUtils.fileAppend(responseFilePath, escapeCmdParams(command) + " "); } } catch (java.io.IOException e) { throw new ExecutionException( "Error while creating response file for the commands.", e ); } filteredCommands.clear(); responseFilePath = "@" + responseFilePath; if ( responseFilePath.indexOf( " " ) > 0) { responseFilePath = "\"" + responseFilePath + "\""; } filteredCommands.add( responseFilePath ); return filteredCommands; } public void resetCommands( List<String> commands ) { } // escaped to make use of dotnet style of command escapes . // Eg. /define:"CONFIG=\"Debug\",DEBUG=-1,TRACE=-1,_MyType=\"Windows\",PLATFORM=\"AnyCPU\"" private String escapeCmdParams(String param) { if(param == null) return null; String str = param; if((param.startsWith("/") || param.startsWith("@")) && param.indexOf(":") > 0) { int delem = param.indexOf(":") + 1; String command = param.substring(0, delem); String value = param.substring(delem); if(value.indexOf(" ") > 0 || value.indexOf("\"") > 0) { value = "\"" + value.replaceAll("\"", "\\\\\"") + "\""; } str = command + value; } else if(param.indexOf(" ") > 0) { str = "\"" + param + "\""; } return str; } }
true
true
public List<String> getCommands() throws ExecutionException { if ( compilerContext == null ) { throw new ExecutionException( "NPANDAY-068-000: Compiler has not been initialized with a context" ); } CompilerConfig config = compilerContext.getNetCompilerConfig(); // references uses directLibraryDependencies for non transitive dependencies List<Artifact> references = compilerContext.getDirectLibraryDependencies(); List<Artifact> modules = compilerContext.getDirectModuleDependencies(); String sourceDirectory = compilerContext.getSourceDirectoryName(); String artifactFilePath = compilerContext.getArtifact().getAbsolutePath(); String targetArtifactType = config.getArtifactType().getTargetCompileType(); compilerContext.getCompilerRequirement().getFrameworkVersion(); List<String> commands = new ArrayList<String>(); if(config.getOutputDirectory() != null) { File f = new File(config.getOutputDirectory(), compilerContext.getArtifact().getName()); artifactFilePath = f.getAbsolutePath(); } if(artifactFilePath!=null && artifactFilePath.toLowerCase().endsWith(".zip")) { artifactFilePath = artifactFilePath.substring(0, artifactFilePath.length() - 3) + "dll"; } commands.add( "/out:" + artifactFilePath); commands.add( "/target:" + targetArtifactType ); if(config.getIncludeSources() == null || config.getIncludeSources().isEmpty() ) { commands.add( "/recurse:" + sourceDirectory + File.separator + "**"); } if ( modules != null && !modules.isEmpty() ) { StringBuffer sb = new StringBuffer(); for ( Iterator i = modules.iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); String path = artifact.getFile().getAbsolutePath(); sb.append( path ); if ( i.hasNext() ) { sb.append( ";" ); } } commands.add( "/addmodule:" + sb.toString() ); } if ( !references.isEmpty() ) { for ( Artifact artifact : references ) { String path = artifact.getFile().getAbsolutePath(); if( !path.contains( ".jar" ) ) { commands.add( "/reference:" + path ); } } } for ( String arg : compilerContext.getEmbeddedResourceArgs() ) { if (logger.isDebugEnabled()) { logger.debug( "NPANDAY-168-001 add resource: " + arg ); } commands.add( "/resource:" + arg ); } for ( File file : compilerContext.getLinkedResources() ) { commands.add( "/linkresource:" + file.getAbsolutePath() ); } for ( File file : compilerContext.getWin32Resources() ) { commands.add( "/win32res:" + file.getAbsolutePath() ); } if ( compilerContext.getWin32Icon() != null ) { commands.add( "/win32icon:" + compilerContext.getWin32Icon().getAbsolutePath() ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) ) { commands.add( "/nologo" ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) && compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.0" ) ) { String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) + "\\Microsoft.NET\\Framework\\v3.0\\Windows Communication Foundation\\"; //TODO: This is a hard-coded path: Don't have a registry value either. //commands.add( wcfRef + "System.ServiceModel.dll" ); commands.add( wcfRef + "Microsoft.Transactions.Bridge.dll" ); commands.add( wcfRef + "Microsoft.Transactions.Bridge.Dtc.dll" ); commands.add( wcfRef + "System.ServiceModel.Install.dll" ); commands.add( wcfRef + "System.ServiceModel.WasHosting.dll" ); //commands.add( wcfRef + "System.Runtime.Serialization.dll" ); commands.add( wcfRef + "SMDiagnostics.dll" ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) && compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.5" ) ) { String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) + "\\Microsoft.NET\\Framework\\v3.5\\"; //TODO: This is a hard-coded path: Don't have a registry value either. commands.add( wcfRef + "Microsoft.Build.Tasks.v3.5.dll" ); String cfBuildTasks = wcfRef + "Microsoft.CompactFramework.Build.Tasks.dll"; if (new File( cfBuildTasks ).exists()) { commands.add( cfBuildTasks ); } commands.add( wcfRef + "Microsoft.Data.Entity.Build.Tasks.dll" ); commands.add( wcfRef + "Microsoft.VisualC.STLCLR.dll" ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) && compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "4.0" ) ) { String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) + "\\Microsoft.NET\\Framework\\v4.0.30319\\"; //TODO: This is a hard-coded path: Don't have a registry value either. commands.add( wcfRef + "Microsoft.Build.Tasks.v4.0.dll" ); commands.add( wcfRef + "Microsoft.Data.Entity.Build.Tasks.dll" ); commands.add( wcfRef + "Microsoft.VisualC.STLCLR.dll" ); } if ( compilerContext.getKeyInfo().getKeyFileUri() != null ) { commands.add( "/keyfile:" + compilerContext.getKeyInfo().getKeyFileUri() ); } else if ( compilerContext.getKeyInfo().getKeyContainerName() != null ) { commands.add( "/keycontainer:" + compilerContext.getKeyInfo().getKeyContainerName() ); } if ( config.getCommands() != null ) { commands.addAll( config.getCommands() ); } commands.add( "/warnaserror-" ); //commands.add( "/nowarn" ); // if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MONO ) ) // { // commands.add( "/reference:System.Drawing" ); // commands.add( "/reference:System.Windows.Forms" ); // commands.add( "/reference:System.Web.Services" ); // } if ( !compilerContext.getNetCompilerConfig().isTestCompile() ) { commands.add( "/doc:" + new File( compilerContext.getTargetDirectory(), "comments.xml" ).getAbsolutePath() ); } CommandFilter filter = compilerContext.getCommandFilter(); List<String> filteredCommands = filter.filter( commands ); //Include Sources code is being copied to temporary folder for the recurse option String fileExt = ""; String frameWorkVer = ""+compilerContext.getCompilerRequirement().getFrameworkVersion(); String TempDir = ""; String targetDir = ""+compilerContext.getTargetDirectory(); Date date = new Date(); String Now =""+date.getDate()+date.getHours()+date.getMinutes()+date.getSeconds(); TempDir = targetDir+File.separator+Now; try { FileUtils.deleteDirectory( TempDir ); } catch(Exception e) { //Does Precautionary delete for tempDir } FileUtils.mkdir(TempDir); if(config.getIncludeSources() != null && !config.getIncludeSources().isEmpty() ) { int folderCtr=0; for(String includeSource : config.getIncludeSources()) { String[] sourceTokens = includeSource.replace('\\', '/').split("/"); String lastToken = sourceTokens[sourceTokens.length-1]; if(fileExt=="") { String[] extToken = lastToken.split( "\\." ); fileExt = "."+extToken[extToken.length-1]; } try { String fileToCheck = TempDir+File.separator+lastToken; if(FileUtils.fileExists( fileToCheck )) { String subTempDir = TempDir+File.separator+folderCtr+File.separator; FileUtils.mkdir( subTempDir ); FileUtils.copyFileToDirectory( includeSource, subTempDir); folderCtr++; } else { FileUtils.copyFileToDirectory( includeSource, TempDir); } } catch(Exception e) { System.out.println(e.getMessage()); } //part of original code. //filteredCommands.add(includeSource); } String recurseCmd = "/recurse:" + TempDir+File.separator + "*" + fileExt + ""; filteredCommands.add(recurseCmd); } if ( logger.isDebugEnabled() ) { logger.debug( "commands: " + filteredCommands ); } String responseFilePath = TempDir + File.separator + "responsefile.rsp"; try { for(String command : filteredCommands) { FileUtils.fileAppend(responseFilePath, escapeCmdParams(command) + " "); } } catch (java.io.IOException e) { throw new ExecutionException( "Error while creating response file for the commands.", e ); } filteredCommands.clear(); responseFilePath = "@" + responseFilePath; if ( responseFilePath.indexOf( " " ) > 0) { responseFilePath = "\"" + responseFilePath + "\""; } filteredCommands.add( responseFilePath ); return filteredCommands; }
public List<String> getCommands() throws ExecutionException { if ( compilerContext == null ) { throw new ExecutionException( "NPANDAY-068-000: Compiler has not been initialized with a context" ); } CompilerConfig config = compilerContext.getNetCompilerConfig(); // references uses directLibraryDependencies for non transitive dependencies List<Artifact> references = compilerContext.getDirectLibraryDependencies(); List<Artifact> modules = compilerContext.getDirectModuleDependencies(); String sourceDirectory = compilerContext.getSourceDirectoryName(); String artifactFilePath = compilerContext.getArtifact().getAbsolutePath(); String targetArtifactType = config.getArtifactType().getTargetCompileType(); compilerContext.getCompilerRequirement().getFrameworkVersion(); List<String> commands = new ArrayList<String>(); if(config.getOutputDirectory() != null) { File f = new File(config.getOutputDirectory(), compilerContext.getArtifact().getName()); artifactFilePath = f.getAbsolutePath(); } if(artifactFilePath!=null && artifactFilePath.toLowerCase().endsWith(".zip")) { artifactFilePath = artifactFilePath.substring(0, artifactFilePath.length() - 3) + "dll"; } commands.add( "/out:" + artifactFilePath); commands.add( "/target:" + targetArtifactType ); if(config.getIncludeSources() == null || config.getIncludeSources().isEmpty() ) { commands.add( "/recurse:" + sourceDirectory + File.separator + "**"); } if ( modules != null && !modules.isEmpty() ) { StringBuffer sb = new StringBuffer(); for ( Iterator i = modules.iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); String path = artifact.getFile().getAbsolutePath(); sb.append( path ); if ( i.hasNext() ) { sb.append( ";" ); } } commands.add( "/addmodule:" + sb.toString() ); } if ( !references.isEmpty() ) { for ( Artifact artifact : references ) { String path = artifact.getFile().getAbsolutePath(); if( !path.contains( ".jar" ) ) { commands.add( "/reference:" + path ); } } } for ( String arg : compilerContext.getEmbeddedResourceArgs() ) { if (logger.isDebugEnabled()) { logger.debug( "NPANDAY-168-001 add resource: " + arg ); } commands.add( "/resource:" + arg ); } for ( File file : compilerContext.getLinkedResources() ) { commands.add( "/linkresource:" + file.getAbsolutePath() ); } for ( File file : compilerContext.getWin32Resources() ) { commands.add( "/win32res:" + file.getAbsolutePath() ); } if ( compilerContext.getWin32Icon() != null ) { commands.add( "/win32icon:" + compilerContext.getWin32Icon().getAbsolutePath() ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) ) { commands.add( "/nologo" ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) && compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.0" ) ) { String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) + "\\Microsoft.NET\\Framework\\v3.0\\Windows Communication Foundation\\"; //TODO: This is a hard-coded path: Don't have a registry value either. //commands.add( wcfRef + "System.ServiceModel.dll" ); commands.add( wcfRef + "Microsoft.Transactions.Bridge.dll" ); commands.add( wcfRef + "Microsoft.Transactions.Bridge.Dtc.dll" ); commands.add( wcfRef + "System.ServiceModel.Install.dll" ); commands.add( wcfRef + "System.ServiceModel.WasHosting.dll" ); //commands.add( wcfRef + "System.Runtime.Serialization.dll" ); commands.add( wcfRef + "SMDiagnostics.dll" ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) && compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.5" ) ) { String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) + "\\Microsoft.NET\\Framework\\v3.5\\"; //TODO: This is a hard-coded path: Don't have a registry value either. commands.add( wcfRef + "Microsoft.Build.Tasks.v3.5.dll" ); String cfBuildTasks = wcfRef + "Microsoft.CompactFramework.Build.Tasks.dll"; if (new File( cfBuildTasks ).exists()) { commands.add( cfBuildTasks ); } commands.add( wcfRef + "Microsoft.Data.Entity.Build.Tasks.dll" ); commands.add( wcfRef + "Microsoft.VisualC.STLCLR.dll" ); } if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) && compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "4.0" ) ) { String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) + "\\Microsoft.NET\\Framework\\v4.0.30319\\"; //TODO: This is a hard-coded path: Don't have a registry value either. commands.add( wcfRef + "Microsoft.Build.Tasks.v4.0.dll" ); commands.add( wcfRef + "Microsoft.Data.Entity.Build.Tasks.dll" ); commands.add( wcfRef + "Microsoft.VisualC.STLCLR.dll" ); } if ( compilerContext.getKeyInfo().getKeyFileUri() != null ) { commands.add( "/keyfile:" + compilerContext.getKeyInfo().getKeyFileUri() ); } else if ( compilerContext.getKeyInfo().getKeyContainerName() != null ) { commands.add( "/keycontainer:" + compilerContext.getKeyInfo().getKeyContainerName() ); } if ( config.getCommands() != null ) { commands.addAll( config.getCommands() ); } commands.add( "/warnaserror-" ); //commands.add( "/nowarn" ); if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MONO ) ) { commands.add( "/nostdlib" ); commands.add( "/noconfig" ); commands.add( "/reference:mscorlib" ); commands.add( "/reference:System.Data" ); commands.add( "/reference:System" ); commands.add( "/reference:System.Drawing" ); commands.add( "/reference:System.Messaging" ); commands.add( "/reference:System.Web.Services" ); commands.add( "/reference:System.Windows.Forms" ); commands.add( "/reference:System.Xml" ); commands.add( "/reference:System.Core" ); commands.add( "/reference:System.Data.DataSetExtensions" ); commands.add( "/reference:System.Xml.Linq" ); } if ( !compilerContext.getNetCompilerConfig().isTestCompile() ) { commands.add( "/doc:" + new File( compilerContext.getTargetDirectory(), "comments.xml" ).getAbsolutePath() ); } CommandFilter filter = compilerContext.getCommandFilter(); List<String> filteredCommands = filter.filter( commands ); //Include Sources code is being copied to temporary folder for the recurse option String fileExt = ""; String frameWorkVer = ""+compilerContext.getCompilerRequirement().getFrameworkVersion(); String TempDir = ""; String targetDir = ""+compilerContext.getTargetDirectory(); Date date = new Date(); String Now =""+date.getDate()+date.getHours()+date.getMinutes()+date.getSeconds(); TempDir = targetDir+File.separator+Now; try { FileUtils.deleteDirectory( TempDir ); } catch(Exception e) { //Does Precautionary delete for tempDir } FileUtils.mkdir(TempDir); if(config.getIncludeSources() != null && !config.getIncludeSources().isEmpty() ) { int folderCtr=0; for(String includeSource : config.getIncludeSources()) { String[] sourceTokens = includeSource.replace('\\', '/').split("/"); String lastToken = sourceTokens[sourceTokens.length-1]; if(fileExt=="") { String[] extToken = lastToken.split( "\\." ); fileExt = "."+extToken[extToken.length-1]; } try { String fileToCheck = TempDir+File.separator+lastToken; if(FileUtils.fileExists( fileToCheck )) { String subTempDir = TempDir+File.separator+folderCtr+File.separator; FileUtils.mkdir( subTempDir ); FileUtils.copyFileToDirectory( includeSource, subTempDir); folderCtr++; } else { FileUtils.copyFileToDirectory( includeSource, TempDir); } } catch(Exception e) { System.out.println(e.getMessage()); } //part of original code. //filteredCommands.add(includeSource); } String recurseCmd = "/recurse:" + TempDir+File.separator + "*" + fileExt + ""; filteredCommands.add(recurseCmd); } if ( logger.isDebugEnabled() ) { logger.debug( "commands: " + filteredCommands ); } String responseFilePath = TempDir + File.separator + "responsefile.rsp"; try { for(String command : filteredCommands) { FileUtils.fileAppend(responseFilePath, escapeCmdParams(command) + " "); } } catch (java.io.IOException e) { throw new ExecutionException( "Error while creating response file for the commands.", e ); } filteredCommands.clear(); responseFilePath = "@" + responseFilePath; if ( responseFilePath.indexOf( " " ) > 0) { responseFilePath = "\"" + responseFilePath + "\""; } filteredCommands.add( responseFilePath ); return filteredCommands; }
diff --git a/src/drbd/data/CRMXML.java b/src/drbd/data/CRMXML.java index 126e39a7..ab51a997 100644 --- a/src/drbd/data/CRMXML.java +++ b/src/drbd/data/CRMXML.java @@ -1,2259 +1,2260 @@ /* * This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH * written by Rasto Levrinc. * * Copyright (C) 2009, LINBIT HA-Solutions GmbH. * * DRBD Management Console 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, or (at your option) * any later version. * * DRBD Management Console 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 drbd; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ package drbd.data; import drbd.utilities.Tools; import drbd.utilities.ConvertCmdCallback; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Comparator; import java.util.Set; import java.util.HashSet; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.Collections; import org.apache.commons.collections.map.MultiKeyMap; /** * This class parses ocf crm xml, stores information like * short and long description, data types etc. for defined types * of services in the hashes and provides methods to get this * information. * * @author Rasto Levrinc * @version $Id$ * */ public class CRMXML extends XML { /** Host. */ private final Host host; /** List of global parameters. */ private final List<String> globalParams = new ArrayList<String>(); /** List of required global parameters. */ private final List<String> globalRequiredParams = new ArrayList<String>(); /** Map from class to the list of all crm services. */ private final Map<String, List<ResourceAgent>> classToServicesMap = new HashMap<String, List<ResourceAgent>>(); /** Map from global parameter to its short description. */ private final Map<String, String> paramGlobalShortDescMap = new HashMap<String, String>(); /** Map from global parameter to its long description. */ private final Map<String, String> paramGlobalLongDescMap = new HashMap<String, String>(); /** Map from global parameter to its default value. */ private final Map<String, String> paramGlobalDefaultMap = new HashMap<String, String>(); /** Map from global parameter to its preferred value. */ private final Map<String, String> paramGlobalPreferredMap = new HashMap<String, String>(); /** Map from global parameter to its type. */ private final Map<String, String> paramGlobalTypeMap = new HashMap<String, String>(); /** Map from global parameter to the array of possible choices. */ private final Map<String, String[]> paramGlobalPossibleChoices = new HashMap<String, String[]>(); /** List of parameters for colocations. */ private final List<String> colParams = new ArrayList<String>(); /** List of required parameters for colocations. */ private final List<String> colRequiredParams = new ArrayList<String>(); /** Map from colocation parameter to its short description. */ private final Map<String, String> paramColShortDescMap = new HashMap<String, String>(); /** Map from colocation parameter to its long description. */ private final Map<String, String> paramColLongDescMap = new HashMap<String, String>(); /** Map from colocation parameter to its default value. */ private final Map<String, String> paramColDefaultMap = new HashMap<String, String>(); /** Map from colocation parameter to its preferred value. */ private final Map<String, String> paramColPreferredMap = new HashMap<String, String>(); /** Map from colocation parameter to its type. */ private final Map<String, String> paramColTypeMap = new HashMap<String, String>(); /** Map from colocation parameter to the array of possible choices. */ private final Map<String, String[]> paramColPossibleChoices = new HashMap<String, String[]>(); /** Map from colocation parameter to the array of possible choices for * master/slave resource. */ private final Map<String, String[]> paramColPossibleChoicesMS = new HashMap<String, String[]>(); /** List of parameters for order. */ private final List<String> ordParams = new ArrayList<String>(); /** List of required parameters for orders. */ private final List<String> ordRequiredParams = new ArrayList<String>(); /** Map from order parameter to its short description. */ private final Map<String, String> paramOrdShortDescMap = new HashMap<String, String>(); /** Map from order parameter to its long description. */ private final Map<String, String> paramOrdLongDescMap = new HashMap<String, String>(); /** Map from order parameter to its default value. */ private final Map<String, String> paramOrdDefaultMap = new HashMap<String, String>(); /** Map from order parameter to its preferred value. */ private final Map<String, String> paramOrdPreferredMap = new HashMap<String, String>(); /** Map from order parameter to its type. */ private final Map<String, String> paramOrdTypeMap = new HashMap<String, String>(); /** Map from order parameter to the array of possible choices. */ private final Map<String, String[]> paramOrdPossibleChoices = new HashMap<String, String[]>(); /** Map from order parameter to the array of possible choices for * master/slave resource. */ private final Map<String, String[]> paramOrdPossibleChoicesMS = new HashMap<String, String[]>(); /** Predefined group as heartbeat service. */ private final ResourceAgent hbGroup = new ResourceAgent(Tools.getConfigData().PM_GROUP_NAME, "", "group"); /** Predefined clone as heartbeat service. */ private final ResourceAgent hbClone; /** Predefined drbddisk as heartbeat service. */ private final ResourceAgent hbDrbddisk = new ResourceAgent("drbddisk", "heartbeat", "heartbeat"); /** Predefined linbit::drbd as pacemaker service. */ private final ResourceAgent hbLinbitDrbd = new ResourceAgent("drbd", "linbit", "ocf"); /** Mapfrom heartbeat service defined by name and class to the hearbeat * service object. */ private final MultiKeyMap serviceToResourceAgentMap = new MultiKeyMap(); /** Whether drbddisk ra is present. */ private boolean drbddiskPresent = false; /** Whether linbit::drbd ra is present. */ private boolean linbitDrbdPresent = false; /** Boolean parameter type. */ private static final String PARAM_TYPE_BOOLEAN = "boolean"; /** Integer parameter type. */ private static final String PARAM_TYPE_INTEGER = "integer"; /** String parameter type. */ private static final String PARAM_TYPE_STRING = "string"; /** Time parameter type. */ private static final String PARAM_TYPE_TIME = "time"; /** Fail count prefix. */ private static final String FAIL_COUNT_PREFIX = "fail-count-"; /** Attribute roles. */ private static final String[] ATTRIBUTE_ROLES = {null, "Stopped", "Started"}; /** Atribute roles for master/slave resource. */ private static final String[] ATTRIBUTE_ROLES_MS = {null, "Stopped", "Started", "Master", "Slave"}; /** Attribute actions. */ private static final String[] ATTRIBUTE_ACTIONS = {null, "start", "stop"}; /** Attribute actions for master/slave. */ private static final String[] ATTRIBUTE_ACTIONS_MS = {null, "start", "promote", "demote", "stop"}; /** * Prepares a new <code>CRMXML</code> object. */ public CRMXML(final Host host) { super(); this.host = host; String command = null; final String hbV = host.getHeartbeatVersion(); final String[] booleanValues = getGlobalCheckBoxChoices(); final String[] integerValues = getIntegerValues(); final String hbBooleanTrue = booleanValues[0]; final String hbBooleanFalse = booleanValues[1]; hbClone = new ResourceAgent(Tools.getConfigData().PM_CLONE_SET_NAME, "", "clone"); if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { setMetaAttributes(hbClone, "target_role", "is_managed"); } /* clone-max */ hbClone.addParameter("clone-max"); hbClone.setParamIsMetaAttr("clone-max", true); hbClone.setParamShortDesc("clone-max", "M/S Clone Max"); hbClone.setParamDefault("clone-max", ""); hbClone.setParamPreferred("clone-max", "2"); hbClone.setParamType("clone-max", PARAM_TYPE_INTEGER); hbClone.setParamPossibleChoices("clone-max", integerValues); /* clone-node-max */ hbClone.addParameter("clone-node-max"); hbClone.setParamIsMetaAttr("clone-node-max", true); hbClone.setParamShortDesc("clone-node-max", "M/S Clone Node Max"); hbClone.setParamDefault("clone-node-max", "1"); hbClone.setParamType("clone-node-max", PARAM_TYPE_INTEGER); hbClone.setParamPossibleChoices("clone-node-max", integerValues); /* notify */ hbClone.addParameter("notify"); hbClone.setParamIsMetaAttr("notify", true); hbClone.setParamShortDesc("notify", "M/S Notify"); hbClone.setParamDefault("notify", hbBooleanFalse); hbClone.setParamPreferred("notify", hbBooleanTrue); hbClone.setParamPossibleChoices("notify", booleanValues); /* globally-unique */ hbClone.addParameter("globally-unique"); hbClone.setParamIsMetaAttr("globally-unique", true); hbClone.setParamShortDesc("globally-unique", "M/S Globally-Unique"); hbClone.setParamDefault("globally-unique", hbBooleanFalse); hbClone.setParamPossibleChoices("globally-unique", booleanValues); /* ordered */ hbClone.addParameter("ordered"); hbClone.setParamIsMetaAttr("ordered", true); hbClone.setParamShortDesc("ordered", "M/S Ordered"); hbClone.setParamDefault("ordered", hbBooleanFalse); hbClone.setParamPossibleChoices("ordered", booleanValues); /* interleave */ hbClone.addParameter("interleave"); hbClone.setParamIsMetaAttr("interleave", true); hbClone.setParamShortDesc("interleave", "M/S Interleave"); hbClone.setParamDefault("interleave", hbBooleanFalse); hbClone.setParamPossibleChoices("interleave", booleanValues); if (Tools.compareVersions(hbV, "2.1.3") <= 0) { command = host.getDistCommand("Heartbeat.2.1.3.getOCFParameters", (ConvertCmdCallback) null); } if (command == null && Tools.compareVersions(hbV, "2.1.4") <= 0) { command = host.getDistCommand("Heartbeat.2.1.4.getOCFParameters", (ConvertCmdCallback) null); } if (command == null) { command = host.getDistCommand("Heartbeat.getOCFParameters", (ConvertCmdCallback) null); } final String output = Tools.execCommandProgressIndicator( host, command, null, /* ExecCallback */ false, /* outputVisible */ Tools.getString("CRMXML.GetOCFParameters")); if (output == null) { //Tools.appError("heartbeat ocf output is null"); return; } final String[] lines = output.split("\\r?\\n"); final Pattern pp = Pattern.compile("^provider:\\s*(.*?)\\s*$"); final Pattern mp = Pattern.compile("^master:\\s*(.*?)\\s*$"); final Pattern bp = Pattern.compile("^<resource-agent name=\"(.*?)\".*"); final Pattern ep = Pattern.compile("^</resource-agent>$"); final StringBuffer xml = new StringBuffer(""); String provider = null; String serviceName = null; boolean masterSlave = false; /* is probably m/s ...*/ for (int i = 0; i < lines.length; i++) { //<resource-agent name="AudibleAlarm"> // ... //</resource-agent> final Matcher pm = pp.matcher(lines[i]); if (pm.matches()) { provider = pm.group(1); continue; } final Matcher mm = mp.matcher(lines[i]); if (mm.matches()) { if ("".equals(mm.group(1))) { masterSlave = false; } else { masterSlave = true; } continue; } final Matcher m = bp.matcher(lines[i]); if (m.matches()) { serviceName = m.group(1); } if (serviceName != null) { xml.append(lines[i]); xml.append('\n'); final Matcher m2 = ep.matcher(lines[i]); if (m2.matches()) { if ("drbddisk".equals(serviceName)) { drbddiskPresent = true; } else if ("drbd".equals(serviceName) && "linbit".equals(provider)) { linbitDrbdPresent = true; } parseMetaData(serviceName, provider, xml.toString(), masterSlave); serviceName = null; xml.delete(0, xml.length() - 1); } } } if (!drbddiskPresent) { Tools.appWarning("drbddisk heartbeat script is not present"); } if (!linbitDrbdPresent) { Tools.appWarning("linbit::drbd ocf ra is not present"); } /* Hardcoding global params */ /* symmetric cluster */ globalParams.add("symmetric-cluster"); paramGlobalShortDescMap.put("symmetric-cluster", "Symmetric Cluster"); paramGlobalLongDescMap.put("symmetric-cluster", "Symmetric Cluster"); paramGlobalTypeMap.put("symmetric-cluster", PARAM_TYPE_BOOLEAN); paramGlobalDefaultMap.put("symmetric-cluster", hbBooleanFalse); paramGlobalPossibleChoices.put("symmetric-cluster", booleanValues); globalRequiredParams.add("symmetric-cluster"); /* stonith enabled */ globalParams.add("stonith-enabled"); paramGlobalShortDescMap.put("stonith-enabled", "Stonith Enabled"); paramGlobalLongDescMap.put("stonith-enabled", "Stonith Enabled"); paramGlobalTypeMap.put("stonith-enabled", PARAM_TYPE_BOOLEAN); paramGlobalDefaultMap.put("stonith-enabled", hbBooleanTrue); //paramGlobalPreferredMap.put("stonith-enabled", hbBooleanFalse); paramGlobalPossibleChoices.put("stonith-enabled", booleanValues); globalRequiredParams.add("stonith-enabled"); /* transition timeout */ globalParams.add("default-action-timeout"); paramGlobalShortDescMap.put("default-action-timeout", "Transition Timeout"); paramGlobalLongDescMap.put("default-action-timeout", "Transition Timeout"); paramGlobalTypeMap.put("default-action-timeout", PARAM_TYPE_INTEGER); paramGlobalDefaultMap.put("default-action-timeout", "20s"); paramGlobalPossibleChoices.put("default-action-timeout", integerValues); globalRequiredParams.add("default-action-timeout"); /* resource stickiness */ globalParams.add("default-resource-stickiness"); paramGlobalShortDescMap.put("default-resource-stickiness", "Resource Stickiness"); paramGlobalLongDescMap.put("default-resource-stickiness", "Resource Stickiness"); paramGlobalTypeMap.put("default-resource-stickiness", PARAM_TYPE_INTEGER); paramGlobalPossibleChoices.put("default-resource-stickiness", integerValues); paramGlobalDefaultMap.put("default-resource-stickiness", "0"); //paramGlobalPreferredMap.put("default-resource-stickiness", "100"); globalRequiredParams.add("default-resource-stickiness"); /* no quorum policy */ globalParams.add("no-quorum-policy"); paramGlobalShortDescMap.put("no-quorum-policy", "No Quorum Policy"); paramGlobalLongDescMap.put("no-quorum-policy", "No Quorum Policy"); // TODO: ignore, stop, freeze, there is more paramGlobalTypeMap.put("no-quorum-policy", PARAM_TYPE_STRING); paramGlobalDefaultMap.put("no-quorum-policy", "stop"); paramGlobalPossibleChoices.put("no-quorum-policy", new String[]{"ignore", "stop", "freeze"}); globalRequiredParams.add("no-quorum-policy"); /* resource failure stickiness */ globalParams.add("default-resource-failure-stickiness"); paramGlobalShortDescMap.put("default-resource-failure-stickiness", "Resource Failure Stickiness"); paramGlobalLongDescMap.put("default-resource-failure-stickiness", "Resource Failure Stickiness"); paramGlobalTypeMap.put("default-resource-failure-stickiness", PARAM_TYPE_INTEGER); paramGlobalPossibleChoices.put("default-resource-failure-stickiness", integerValues); paramGlobalDefaultMap.put("default-resource-failure-stickiness", "0"); globalRequiredParams.add("default-resource-failure-stickiness"); if (Tools.compareVersions(hbV, "2.1.3") >= 0) { final String[] params = { "stonith-action", "is-managed-default", "cluster-delay", "batch-limit", "stop-orphan-resources", "stop-orphan-actions", "remove-after-stop", "pe-error-series-max", "pe-warn-series-max", "pe-input-series-max", "startup-fencing", "start-failure-is-fatal", "dc_deadtime", "cluster_recheck_interval", "election_timeout", "shutdown_escalation", "crmd-integration-timeout", "crmd-finalization-timeout" }; for (String param : params) { globalParams.add(param); String[] parts = param.split("[-_]"); for (int i = 0; i < parts.length; i++) { if ("dc".equals(parts[i])) { parts[i] = "DC"; } if ("crmd".equals(parts[i])) { parts[i] = "CRMD"; } else { parts[i] = Tools.ucfirst(parts[i]); } } final String name = Tools.join(" ", parts); paramGlobalShortDescMap.put(param, name); paramGlobalLongDescMap.put(param, name); paramGlobalTypeMap.put(param, PARAM_TYPE_STRING); paramGlobalDefaultMap.put(param, ""); } paramGlobalDefaultMap.put("stonith-action", "reboot"); paramGlobalPossibleChoices.put("stonith-action", new String[]{"reboot", "poweroff"}); paramGlobalTypeMap.put("is-managed-default", PARAM_TYPE_BOOLEAN); paramGlobalDefaultMap.put("is-managed-default", hbBooleanFalse); paramGlobalPossibleChoices.put("is-managed-default", booleanValues); paramGlobalTypeMap.put("stop-orphan-resources", PARAM_TYPE_BOOLEAN); paramGlobalDefaultMap.put("stop-orphan-resources", hbBooleanFalse); paramGlobalPossibleChoices.put("stop-orphan-resources", booleanValues); paramGlobalTypeMap.put("stop-orphan-actions", PARAM_TYPE_BOOLEAN); paramGlobalDefaultMap.put("stop-orphan-actions", hbBooleanFalse); paramGlobalPossibleChoices.put("stop-orphan-actions", booleanValues); paramGlobalTypeMap.put("remove-after-stop", PARAM_TYPE_BOOLEAN); paramGlobalDefaultMap.put("remove-after-stop", hbBooleanFalse); paramGlobalPossibleChoices.put("remove-after-stop", booleanValues); paramGlobalTypeMap.put("startup-fencing", PARAM_TYPE_BOOLEAN); paramGlobalDefaultMap.put("startup-fencing", hbBooleanFalse); paramGlobalPossibleChoices.put("startup-fencing", booleanValues); paramGlobalTypeMap.put("start-failure-is-fatal", PARAM_TYPE_BOOLEAN); paramGlobalDefaultMap.put("start-failure-is-fatal", hbBooleanFalse); paramGlobalPossibleChoices.put("start-failure-is-fatal", booleanValues); } /* Hardcoding colocation params */ colParams.add("with-rsc-role"); paramColShortDescMap.put("with-rsc-role", "rsc1 col role"); paramColLongDescMap.put("with-rsc-role", "@WITH-RSC@ colocation role"); paramColTypeMap.put("with-rsc-role", PARAM_TYPE_STRING); paramColPossibleChoices.put("with-rsc-role", ATTRIBUTE_ROLES); paramColPossibleChoicesMS.put("with-rsc-role", ATTRIBUTE_ROLES_MS); colParams.add("rsc-role"); paramColShortDescMap.put("rsc-role", "rsc2 col role"); paramColLongDescMap.put("rsc-role", "@RSC@ colocation role"); paramColTypeMap.put("rsc-role", PARAM_TYPE_STRING); paramColPossibleChoices.put("rsc-role", ATTRIBUTE_ROLES); paramColPossibleChoicesMS.put("rsc-role", ATTRIBUTE_ROLES_MS); colParams.add("score"); paramColShortDescMap.put("score", "Score"); paramColLongDescMap.put("score", "Score"); paramColTypeMap.put("score", PARAM_TYPE_INTEGER); paramColDefaultMap.put("score", null); //paramColPreferredMap.put("score", "INFINITY"); paramColPossibleChoices.put("score", integerValues); /* Hardcoding order params */ ordParams.add("first-action"); paramOrdShortDescMap.put("first-action", "rsc1 order action"); paramOrdLongDescMap.put("first-action", "@FIRST-RSC@ order action"); paramOrdTypeMap.put("first-action", PARAM_TYPE_STRING); paramOrdPossibleChoices.put("first-action", ATTRIBUTE_ACTIONS); paramOrdPossibleChoicesMS.put("first-action", ATTRIBUTE_ACTIONS_MS); paramOrdDefaultMap.put("first-action", null); ordParams.add("then-action"); paramOrdShortDescMap.put("then-action", "rsc2 order action"); paramOrdLongDescMap.put("then-action", "@THEN-RSC@ order action"); paramOrdTypeMap.put("then-action", PARAM_TYPE_STRING); paramOrdPossibleChoices.put("then-action", ATTRIBUTE_ACTIONS); paramOrdPossibleChoicesMS.put("then-action", ATTRIBUTE_ACTIONS_MS); paramOrdDefaultMap.put("then-action", null); ordParams.add("symmetrical"); paramOrdShortDescMap.put("symmetrical", "Symmetrical"); paramOrdLongDescMap.put("symmetrical", "Symmetrical"); paramOrdTypeMap.put("symmetrical", PARAM_TYPE_BOOLEAN); paramOrdDefaultMap.put("symmetrical", hbBooleanTrue); paramOrdPossibleChoices.put("symmetrical", booleanValues); ordParams.add("score"); paramOrdShortDescMap.put("score", "Score"); paramOrdLongDescMap.put("score", "Score"); paramOrdTypeMap.put("score", PARAM_TYPE_INTEGER); //paramOrdPreferredMap.put("score", "INFINITY"); paramOrdPossibleChoices.put("score", integerValues); paramOrdDefaultMap.put("score", null); } /** * Returns choices for check boxes in the global config. (True, False). */ public final String[] getGlobalCheckBoxChoices() { final String hbV = host.getHeartbeatVersion(); if (Tools.compareVersions(hbV, "2.1.3") >= 0) { return new String[]{ Tools.getString("Heartbeat.2.1.3.Boolean.True"), Tools.getString("Heartbeat.2.1.3.Boolean.False")}; } else { return new String[]{ Tools.getString("Heartbeat.Boolean.True"), Tools.getString("Heartbeat.Boolean.False")}; } } /** * Returns choices for integer fields. */ public final String[] getIntegerValues() { return new String[]{null, "0", "INFINITY", "-INFINITY"}; } /** * Returns choices for check box. (True, False). * The problem is, that heartbeat kept changing the lower and upper case in * the true and false values. */ public final String[] getCheckBoxChoices(final ResourceAgent ra, final String param) { final String paramDefault = getParamDefault(ra, param); if (paramDefault != null) { if ("yes".equals(paramDefault) || "no".equals(paramDefault)) { return new String[]{"yes", "no"}; } else if ("Yes".equals(paramDefault) || "No".equals(paramDefault)) { return new String[]{"Yes", "No"}; } else if ("true".equals(paramDefault) || "false".equals(paramDefault)) { return new String[]{"true", "false"}; } else if ("True".equals(paramDefault) || "False".equals(paramDefault)) { return new String[]{"True", "False"}; } } final String hbV = host.getHeartbeatVersion(); if (Tools.compareVersions(hbV, "2.1.3") >= 0) { return new String[]{ Tools.getString("Heartbeat.2.1.3.Boolean.True"), Tools.getString("Heartbeat.2.1.3.Boolean.False")}; } else { return new String[]{ Tools.getString("Heartbeat.Boolean.True"), Tools.getString("Heartbeat.Boolean.False")}; } } /** * Returns all services as array of strings, sorted, with filesystem and * ipaddr in the begining. */ public final List<ResourceAgent> getServices(final String cl) { final List<ResourceAgent> services = classToServicesMap.get(cl); if (services == null) { return new ArrayList<ResourceAgent>(); } Collections.sort(services, new Comparator<ResourceAgent>() { public int compare(final ResourceAgent s1, final ResourceAgent s2) { return s1.getName().compareToIgnoreCase( s2.getName()); } }); return services; } /** * Returns parameters for service. Parameters are obtained from * ocf meta-data. */ public final String[] getParameters(final ResourceAgent ra) { /* return cached values */ return ra.getParameters(); } /** * Returns global parameters. */ public final String[] getGlobalParameters() { if (globalParams != null) { return globalParams.toArray(new String[globalParams.size()]); } return null; } /** * Return version of the service ocf script. */ public final String getVersion(final ResourceAgent ra) { return ra.getVersion(); } /** * Return short description of the service. */ public final String getShortDesc(final ResourceAgent ra) { return ra.getShortDesc(); } /** * Return long description of the service. */ public final String getLongDesc(final ResourceAgent ra) { return ra.getLongDesc(); } /** * Returns short description of the global parameter. */ public final String getGlobalParamShortDesc(final String param) { String shortDesc = paramGlobalShortDescMap.get(param); if (shortDesc == null) { shortDesc = param; } return shortDesc; } /** * Returns short description of the service parameter. */ public final String getParamShortDesc(final ResourceAgent ra, final String param) { return ra.getParamShortDesc(param); } /** * Returns long description of the global parameter. */ public final String getGlobalParamLongDesc(final String param) { final String shortDesc = getGlobalParamShortDesc(param); String longDesc = paramGlobalLongDescMap.get(param); if (longDesc == null) { longDesc = ""; } return Tools.html("<b>" + shortDesc + "</b>\n" + longDesc); } /** * Returns long description of the parameter and service. */ public final String getParamLongDesc(final ResourceAgent ra, final String param) { final String shortDesc = getParamShortDesc(ra, param); String longDesc = ra.getParamLongDesc(param); if (longDesc == null) { longDesc = ""; } return Tools.html("<b>" + shortDesc + "</b>\n" + longDesc); } /** * Returns type of a global parameter. It can be string, integer, boolean... */ public final String getGlobalParamType(final String param) { return paramGlobalTypeMap.get(param); } /** * Returns type of the parameter. It can be string, integer, boolean... */ public final String getParamType(final ResourceAgent ra, final String param) { return ra.getParamType(param); } /** * Returns default value for the global parameter. */ public final String getGlobalParamDefault(final String param) { return paramGlobalDefaultMap.get(param); } /** * Returns the preferred value for the global parameter. */ public final String getGlobalParamPreferred(final String param) { return paramGlobalPreferredMap.get(param); } /** * Returns the preferred value for this parameter. */ public final String getParamPreferred(final ResourceAgent ra, final String param) { return ra.getParamPreferred(param); } /** * Returns default value for this parameter. */ public final String getParamDefault(final ResourceAgent ra, final String param) { return ra.getParamDefault(param); } /** * Returns possible choices for a global parameter, that will be displayed * in the combo box. */ public final String[] getGlobalParamPossibleChoices(final String param) { return paramGlobalPossibleChoices.get(param); } /** * Returns possible choices for a parameter, that will be displayed in * the combo box. */ public final String[] getParamPossibleChoices(final ResourceAgent ra, final String param) { return ra.getParamPossibleChoices(param); } /** * Checks if parameter is required or not. */ public final boolean isGlobalRequired(final String param) { return globalRequiredParams.contains(param); } /** * Checks if parameter is required or not. */ public final boolean isRequired(final ResourceAgent ra, final String param) { return ra.isRequired(param); } /** * Returns whether the parameter is meta attribute or not. */ public final boolean isMetaAttr(final ResourceAgent ra, final String param) { return ra.isParamMetaAttr(param); } /** * Returns whether the parameter expects an integer value. */ public final boolean isInteger(final ResourceAgent ra, final String param) { final String type = getParamType(ra, param); return PARAM_TYPE_INTEGER.equals(type); } /** * Returns whether the parameter expects a boolean value. */ public final boolean isBoolean(final ResourceAgent ra, final String param) { final String type = getParamType(ra, param); return PARAM_TYPE_BOOLEAN.equals(type); } /** * Returns whether the global parameter expects an integer value. */ public final boolean isGlobalInteger(final String param) { final String type = getGlobalParamType(param); return PARAM_TYPE_INTEGER.equals(type); } /** * Returns whether the global parameter expects a boolean value. */ public final boolean isGlobalBoolean(final String param) { final String type = getGlobalParamType(param); return PARAM_TYPE_BOOLEAN.equals(type); } /** * Whether the service parameter is of the time type. */ public final boolean isTimeType(final ResourceAgent ra, final String param) { final String type = getParamType(ra, param); return PARAM_TYPE_TIME.equals(type); } /** * Whether the global parameter is of the time type. */ public final boolean isGlobalTimeType(final String param) { final String type = getGlobalParamType(param); return PARAM_TYPE_TIME.equals(type); } /** * Returns name of the section for service and parameter that will be * displayed. */ public final String getSection(final ResourceAgent ra, final String param) { if (isMetaAttr(ra, param)) { return Tools.getString("CRMXML.MetaAttrOptions"); } else if (isRequired(ra, param)) { return Tools.getString("CRMXML.RequiredOptions"); } else { return Tools.getString("CRMXML.OptionalOptions"); } } /** * Returns name of the section global parameter that will be * displayed. */ public final String getGlobalSection(final String param) { if (isGlobalRequired(param)) { return Tools.getString("CRMXML.RequiredOptions"); } else { return Tools.getString("CRMXML.OptionalOptions"); } } /** * Checks parameter according to its type. Returns false if value does * not fit the type. */ public final boolean checkParam(final ResourceAgent ra, final String param, final String value) { final String type = getParamType(ra, param); boolean correctValue = true; if (PARAM_TYPE_BOOLEAN.equals(type)) { if (!"yes".equals(value) && !"no".equals(value) && !Tools.getString("Heartbeat.Boolean.True").equals(value) && !Tools.getString("Heartbeat.Boolean.False").equals(value) && !Tools.getString( "Heartbeat.2.1.3.Boolean.True").equals(value) && !Tools.getString( "Heartbeat.2.1.3.Boolean.False").equals(value)) { correctValue = false; } } else if (PARAM_TYPE_INTEGER.equals(type)) { final Pattern p = Pattern.compile("^-?(\\d*|INFINITY)$"); final Matcher m = p.matcher(value); if (!m.matches()) { correctValue = false; } } else if (PARAM_TYPE_TIME.equals(type)) { final Pattern p = Pattern.compile("^-?\\d*(ms|msec|us|usec|s|sec|m|min|h|hr)?$"); final Matcher m = p.matcher(value); if (!m.matches()) { correctValue = false; } } else if ((value == null || "".equals(value)) && isRequired(ra, param)) { correctValue = false; } return correctValue; } /** * Checks global parameter according to its type. Returns false if value * does not fit the type. */ public final boolean checkGlobalParam(final String param, final String value) { final String type = getGlobalParamType(param); boolean correctValue = true; if (PARAM_TYPE_BOOLEAN.equals(type)) { if (!"yes".equals(value) && !"no".equals(value) && !Tools.getString("Heartbeat.Boolean.True").equals(value) && !Tools.getString("Heartbeat.Boolean.False").equals(value) && !Tools.getString( "Heartbeat.2.1.3.Boolean.True").equals(value) && !Tools.getString( "Heartbeat.2.1.3.Boolean.False").equals(value)) { correctValue = false; } } else if (PARAM_TYPE_INTEGER.equals(type)) { final Pattern p = Pattern.compile("^-?(\\d*|INFINITY)$"); final Matcher m = p.matcher(value); if (!m.matches()) { correctValue = false; } } else if (PARAM_TYPE_TIME.equals(type)) { final Pattern p = Pattern.compile("^-?\\d*(ms|msec|us|usec|s|sec|m|min|h|hr)?$"); final Matcher m = p.matcher(value); if (!m.matches()) { correctValue = false; } } else if ((value == null || "".equals(value)) && isGlobalRequired(param)) { correctValue = false; } return correctValue; } /** * Sets meta attributes for resource agent. */ private void setMetaAttributes(final ResourceAgent ra, final String targetRoleParam, final String isManagedParam) { ra.addParameter(targetRoleParam); // TODO: Master, Slave ra.setParamPossibleChoices(targetRoleParam, new String[]{"started", "stopped"}); ra.setParamIsMetaAttr(targetRoleParam, true); ra.setParamRequired(targetRoleParam, false); ra.setParamShortDesc(targetRoleParam, Tools.getString("CRMXML.TargetRole.ShortDesc")); ra.setParamLongDesc(targetRoleParam, Tools.getString("CRMXML.TargetRole.LongDesc")); // TODO: default is different in some prev hb */ ra.setParamDefault(targetRoleParam, "started"); ra.addParameter(isManagedParam); ra.setParamPossibleChoices(isManagedParam, new String[]{"true", "false"}); ra.setParamIsMetaAttr(isManagedParam, true); ra.setParamRequired(isManagedParam, true); ra.setParamShortDesc(isManagedParam, Tools.getString("CRMXML.IsManaged.ShortDesc")); ra.setParamLongDesc( isManagedParam, Tools.getString("CRMXML.IsManaged.LongDesc")); ra.setParamDefault(isManagedParam, "true"); } /** * Parses the parameters. */ private void parseParameters(final ResourceAgent ra, final Node parametersNode) { final String hbV = host.getHeartbeatVersion(); if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { setMetaAttributes(ra, "target_role", "is_managed"); } else { setMetaAttributes(ra, "target-role", "is-managed"); } final NodeList parameters = parametersNode.getChildNodes(); for (int i = 0; i < parameters.getLength(); i++) { final Node parameterNode = parameters.item(i); if (parameterNode.getNodeName().equals("parameter")) { final String param = getAttribute(parameterNode, "name"); final String required = getAttribute(parameterNode, "required"); ra.addParameter(param); if (required != null && required.equals("1")) { ra.setParamRequired(param, true); } /* <longdesc lang="en"> */ final Node longdescParamNode = getChildNode(parameterNode, "longdesc"); if (longdescParamNode != null) { final String longDesc = getText(longdescParamNode); ra.setParamLongDesc(param, longDesc); } /* <shortdesc lang="en"> */ final Node shortdescParamNode = getChildNode(parameterNode, "shortdesc"); if (shortdescParamNode != null) { final String shortDesc = getText(shortdescParamNode); ra.setParamShortDesc(param, shortDesc); } /* <content> */ final Node contentParamNode = getChildNode(parameterNode, "content"); if (contentParamNode != null) { final String type = getAttribute(contentParamNode, "type"); final String defaultValue = getAttribute(contentParamNode, "default"); ra.setParamType(param, type); ra.setParamDefault(param, defaultValue); } } } } /** * Parses the actions node. */ private void parseActions(final ResourceAgent ra, final Node actionsNode) { final NodeList actions = actionsNode.getChildNodes(); for (int i = 0; i < actions.getLength(); i++) { final Node actionNode = actions.item(i); if (actionNode.getNodeName().equals("action")) { final String name = getAttribute(actionNode, "name"); final String depth = getAttribute(actionNode, "depth"); final String timeout = getAttribute(actionNode, "timeout"); final String interval = getAttribute(actionNode, "interval"); final String startDelay = getAttribute(actionNode, "start-delay"); final String role = getAttribute(actionNode, "role"); ra.addOperationDefault(name, "depth", depth); ra.addOperationDefault(name, "timeout", timeout); ra.addOperationDefault(name, "interval", interval); ra.addOperationDefault(name, "start-delay", startDelay); ra.addOperationDefault(name, "role", role); } } } /** * Parses meta-data xml for parameters for service and fills up the hashes * "CRM Daemon"s are global config options. */ public final void parseMetaData(final String serviceName, final String provider, final String xml, final boolean masterSlave) { final Document document = getXMLDocument(xml); if (document == null) { return; } /* get root <resource-agent> */ final Node raNode = getChildNode(document, "resource-agent"); if (raNode == null) { return; } /* class */ String resourceClass = getAttribute(raNode, "class"); if (resourceClass == null) { resourceClass = "ocf"; } List<ResourceAgent> raList = classToServicesMap.get(resourceClass); if (raList == null) { raList = new ArrayList<ResourceAgent>(); classToServicesMap.put(resourceClass, raList); } ResourceAgent ra; if ("drbddisk".equals(serviceName) && "heartbeat".equals(resourceClass)) { ra = hbDrbddisk; } else if ("drbd".equals(serviceName) && "ocf".equals(resourceClass) && "linbit".equals(provider)) { ra = hbLinbitDrbd; } else { ra = new ResourceAgent(serviceName, provider, resourceClass); } serviceToResourceAgentMap.put(serviceName, provider, resourceClass, ra); raList.add(ra); /* <version> */ final Node versionNode = getChildNode(raNode, "version"); if (versionNode != null) { ra.setVersion(getText(versionNode)); } /* <longdesc lang="en"> */ final Node longdescNode = getChildNode(raNode, "longdesc"); if (longdescNode != null) { ra.setLongDesc(getText(longdescNode)); } /* <shortdesc lang="en"> */ final Node shortdescNode = getChildNode(raNode, "shortdesc"); if (shortdescNode != null) { ra.setShortDesc(getText(shortdescNode)); } /* <parameters> */ final Node parametersNode = getChildNode(raNode, "parameters"); if (parametersNode != null) { parseParameters(ra, parametersNode); } /* <actions> */ final Node actionsNode = getChildNode(raNode, "actions"); if (actionsNode != null) { parseActions(ra, actionsNode); } ra.setMasterSlave(masterSlave); } /** * Parses crm meta data, only to get long descriptions and default values * for advanced options. * Strange stuff * * which can be pengine or crmd */ public final void parseClusterMetaData(final String xml) { final Document document = getXMLDocument(xml); if (document == null) { return; } /* get root <metadata> */ final Node metadataNode = getChildNode(document, "metadata"); if (metadataNode == null) { return; } /* get <resource-agent> */ final NodeList resAgents = metadataNode.getChildNodes(); final String[] booleanValues = getGlobalCheckBoxChoices(); final String[] integerValues = getIntegerValues(); for (int i = 0; i < resAgents.getLength(); i++) { final Node resAgentNode = resAgents.item(i); if (!resAgentNode.getNodeName().equals("resource-agent")) { continue; } /* <parameters> */ final Node parametersNode = getChildNode(resAgentNode, "parameters"); if (parametersNode == null) { return; } final NodeList parameters = parametersNode.getChildNodes(); for (int j = 0; j < parameters.getLength(); j++) { final Node parameterNode = parameters.item(j); if (parameterNode.getNodeName().equals("parameter")) { final String param = getAttribute(parameterNode, "name"); final String required = getAttribute(parameterNode, "required"); if (!globalParams.contains(param)) { globalParams.add(param); } if (required != null && required.equals("1") && !globalRequiredParams.contains(param)) { globalRequiredParams.add(param); } /* <longdesc lang="en"> */ final Node longdescParamNode = getChildNode(parameterNode, "longdesc"); if (longdescParamNode != null) { final String longDesc = getText(longdescParamNode); paramGlobalLongDescMap.put(param, longDesc); } /* <content> */ final Node contentParamNode = getChildNode(parameterNode, "content"); if (contentParamNode != null) { final String type = getAttribute(contentParamNode, "type"); final String defaultValue = getAttribute(contentParamNode, "default"); paramGlobalTypeMap.put(param, type); if (!"expected-quorum-votes".equals(param)) { // TODO: workaround paramGlobalDefaultMap.put(param, defaultValue); } if (PARAM_TYPE_BOOLEAN.equals(type)) { paramGlobalPossibleChoices.put(param, booleanValues); } if (PARAM_TYPE_INTEGER.equals(type)) { paramGlobalPossibleChoices.put(param, integerValues); } } } } } /* stonith timeout, workaround, because of param type comming wrong * from pacemaker */ paramGlobalTypeMap.put("stonith-timeout", PARAM_TYPE_TIME); } /** * Returns the heartbeat service object for the specified service name and * heartbeat class. */ public final ResourceAgent getResourceAgent(final String serviceName, final String provider, final String raClass) { return (ResourceAgent) serviceToResourceAgentMap.get(serviceName, provider, raClass); } /** * Returns the heartbeat service object of the drbddisk service. */ public final ResourceAgent getHbDrbddisk() { return hbDrbddisk; } /** * Returns the heartbeat service object of the linbit::drbd service. */ public final ResourceAgent getHbLinbitDrbd() { return hbLinbitDrbd; } /** * Returns the heartbeat service object of the hearbeat group. */ public final ResourceAgent getHbGroup() { return hbGroup; } /** * Returns the heartbeat service object of the hearbeat clone set. */ public final ResourceAgent getHbClone() { return hbClone; } /** /** * Parses attributes, operations etc. from primitives and clones. */ private void parseAttributes( final Node resourceNode, final String hbId, final Map<String, Map<String, String>> parametersMap, final Map<String, Map<String, String>> parametersNvpairsIdsMap, final Map<String, String> resourceInstanceAttrIdMap, final MultiKeyMap operationsMap, final Map<String, String> operationsIdMap, final Map<String, Map<String, String>> resOpIdsMap) { final Map<String, String> params = new HashMap<String, String>(); parametersMap.put(hbId, params); final Map<String, String> nvpairIds = new HashMap<String, String>(); parametersNvpairsIdsMap.put(hbId, nvpairIds); final String hbV = host.getHeartbeatVersion(); /* <instance_attributes> */ final Node instanceAttrNode = getChildNode(resourceNode, "instance_attributes"); /* <nvpair...> */ if (instanceAttrNode != null) { final String iAId = getAttribute(instanceAttrNode, "id"); resourceInstanceAttrIdMap.put(hbId, iAId); NodeList nvpairsRes; if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { /* <attributtes> only til 2.1.4 */ final Node attrNode = getChildNode(instanceAttrNode, "attributes"); nvpairsRes = attrNode.getChildNodes(); } else { nvpairsRes = instanceAttrNode.getChildNodes(); } for (int j = 0; j < nvpairsRes.getLength(); j++) { final Node optionNode = nvpairsRes.item(j); if (optionNode.getNodeName().equals("nvpair")) { final String nvpairId = getAttribute(optionNode, "id"); final String name = getAttribute(optionNode, "name"); final String value = getAttribute(optionNode, "value"); params.put(name, value); nvpairIds.put(name, nvpairId); } } } /* <operations> */ final Node operationsNode = getChildNode(resourceNode, "operations"); if (operationsNode != null) { final String operationsId = getAttribute(operationsNode, "id"); operationsIdMap.put(hbId, operationsId); final Map<String, String> opIds = new HashMap<String, String>(); resOpIdsMap.put(hbId, opIds); /* <op> */ final NodeList ops = operationsNode.getChildNodes(); for (int k = 0; k < ops.getLength(); k++) { final Node opNode = ops.item(k); if (opNode.getNodeName().equals("op")) { final String opId = getAttribute(opNode, "id"); final String name = getAttribute(opNode, "name"); final String timeout = getAttribute(opNode, "timeout"); final String interval = getAttribute(opNode, "interval"); final String startDelay = getAttribute(opNode, "start-delay"); operationsMap.put(hbId, name, "interval", interval); operationsMap.put(hbId, name, "timeout", timeout); operationsMap.put(hbId, name, "start-delay", startDelay); opIds.put(name, opId); } } } /* <meta_attributtes> */ final Node metaAttrsNode = getChildNode(resourceNode, "meta_attributes"); if (metaAttrsNode != null) { final String metaAttrsId = getAttribute(metaAttrsNode, "id"); /* <attributtes> only til 2.1.4 */ NodeList nvpairsMA; if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { final Node attrsNode = getChildNode(metaAttrsNode, "attributes"); nvpairsMA = attrsNode.getChildNodes(); } else { nvpairsMA = metaAttrsNode.getChildNodes(); } /* <nvpair...> */ /* target-role and is-managed */ for (int l = 0; l < nvpairsMA.getLength(); l++) { final Node maNode = nvpairsMA.item(l); if (maNode.getNodeName().equals("nvpair")) { final String nvpairId = getAttribute(maNode, "id"); final String name = getAttribute(maNode, "name"); final String value = getAttribute(maNode, "value"); params.put(name, value); nvpairIds.put(name, nvpairId); } } } } /** * Parses the "primitive" node. */ private void parsePrimitive( final Node primitiveNode, final List<String> groupResList, final Map<String, ResourceAgent> resourceTypeMap, final Map<String, Map<String, String>> parametersMap, final Map<String, Map<String, String>> parametersNvpairsIdsMap, final Map<String, String> resourceInstanceAttrIdMap, final MultiKeyMap operationsMap, final Map<String, String> operationsIdMap, final Map<String, Map<String, String>> resOpIdsMap) { final String raClass = getAttribute(primitiveNode, "class"); final String hbId = getAttribute(primitiveNode, "id"); String provider = getAttribute(primitiveNode, "provider"); if (provider == null) { provider = "heartbeat"; } final String type = getAttribute(primitiveNode, "type"); resourceTypeMap.put(hbId, getResourceAgent(type, provider, raClass)); groupResList.add(hbId); parseAttributes(primitiveNode, hbId, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); } /** * This class holds parsed status of resource, m/s set, or clone set. */ class ResStatus { /** On which nodes the resource runs, or is master. */ private final List<String> runningOnNodes; /** On which nodes the resource is slave if it is m/s resource. */ private final List<String> slaveOnNodes; /** * Creates a new ResStatus object. */ public ResStatus(final List<String> runningOnNodes, final List<String> slaveOnNodes) { this.runningOnNodes = runningOnNodes; this.slaveOnNodes = slaveOnNodes; } /** * Gets on which nodes the resource runs, or is master. */ public final List<String> getRunningOnNodes() { return runningOnNodes; } /** * Gets on which nodes the resource is slave if it is m/s resource. */ public final List<String> getSlaveOnNodes() { return slaveOnNodes; } } /** * Returns a hash with resource information. (running_on) */ public final Map<String, ResStatus> parseResStatus(final String resStatus) { final Map<String, ResStatus> resStatusMap = new HashMap<String, ResStatus>(); final Document document = getXMLDocument(resStatus); if (document == null) { return null; } /* get root <resource_status> */ final Node statusNode = getChildNode(document, "resource_status"); if (statusNode == null) { return null; } /* <resource...> */ final NodeList resources = statusNode.getChildNodes(); for (int i = 0; i < resources.getLength(); i++) { final Node resourceNode = resources.item(i); if (resourceNode.getNodeName().equals("resource")) { final String id = getAttribute(resourceNode, "id"); final String runningOn = getAttribute(resourceNode, "running_on"); if (runningOn != null && !"".equals(runningOn)) { final List<String> rList = new ArrayList<String>(); rList.add(runningOn); resStatusMap.put(id, new ResStatus(rList, null)); } } else if (resourceNode.getNodeName().equals("set")) { final String id = getAttribute(resourceNode, "id"); final NodeList statusList = resourceNode.getChildNodes(); List<String> runningOnList = null; List<String> slaveOnList = null; for (int j = 0; j < statusList.getLength(); j++) { final Node setNode = statusList.item(j); if (setNode.getNodeName().equals("master") || setNode.getNodeName().equals("started")) { final String node = getText(setNode); if (runningOnList == null) { runningOnList = new ArrayList<String>(); } runningOnList.add(node); } else if (setNode.getNodeName().equals("slave")) { final String node = getText(setNode); if (slaveOnList == null) { slaveOnList = new ArrayList<String>(); } slaveOnList.add(node); } } resStatusMap.put(id, new ResStatus(runningOnList, slaveOnList)); } } return resStatusMap; } /** * Parses the transient attributes. */ private void parseTransientAttributes(final String uname, final Node transientAttrNode, final MultiKeyMap failedMap, final String hbV) { /* <instance_attributes> */ final Node instanceAttrNode = getChildNode(transientAttrNode, "instance_attributes"); /* <nvpair...> */ if (instanceAttrNode != null) { final String iAId = getAttribute(instanceAttrNode, "id"); NodeList nvpairsRes; if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { /* <attributtes> only til 2.1.4 */ final Node attrNode = getChildNode(instanceAttrNode, "attributes"); nvpairsRes = attrNode.getChildNodes(); } else { nvpairsRes = instanceAttrNode.getChildNodes(); } for (int j = 0; j < nvpairsRes.getLength(); j++) { final Node optionNode = nvpairsRes.item(j); if (optionNode.getNodeName().equals("nvpair")) { final String name = getAttribute(optionNode, "name"); final String value = getAttribute(optionNode, "value"); /* TODO: last-failure-" */ if (name.indexOf(FAIL_COUNT_PREFIX) == 0) { final String resId = name.substring(FAIL_COUNT_PREFIX.length()); final Pattern p = Pattern.compile("(.*):(\\d+)$"); final Matcher m = p.matcher(resId); if (m.matches()) { failedMap.put(uname, m.group(1), value); } else { failedMap.put(uname, resId, value); } } } } } } /** * Returns CibQuery object with information from the cib node. */ public final CibQuery parseCibQuery(final String query) { final Document document = getXMLDocument(query); final CibQuery cibQueryData = new CibQuery(); if (document == null) { return cibQueryData; } /* get root <cib> */ final Node cibNode = getChildNode(document, "cib"); if (cibNode == null) { return cibQueryData; } /* Designated Co-ordinator */ final String dcUuid = getAttribute(cibNode, "dc-uuid"); //TODO: more attributes are here /* <configuration> */ final Node confNode = getChildNode(cibNode, "configuration"); if (confNode == null) { return cibQueryData; } /* <crm_config> */ final Node crmConfNode = getChildNode(confNode, "crm_config"); if (crmConfNode == null) { return cibQueryData; } /* <cluster_property_set> */ final Node cpsNode = getChildNode(crmConfNode, "cluster_property_set"); if (cpsNode == null) { return cibQueryData; } NodeList nvpairs; final String hbV = host.getHeartbeatVersion(); if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { /* <attributtes> only til 2.1.4 */ final Node attrNode = getChildNode(cpsNode, "attributes"); nvpairs = attrNode.getChildNodes(); } else { nvpairs = cpsNode.getChildNodes(); } final Map<String, String> crmConfMap = new HashMap<String, String>(); /* <nvpair...> */ for (int i = 0; i < nvpairs.getLength(); i++) { final Node optionNode = nvpairs.item(i); if (optionNode.getNodeName().equals("nvpair")) { final String name = getAttribute(optionNode, "name"); final String value = getAttribute(optionNode, "value"); crmConfMap.put(name, value); } } cibQueryData.setCrmConfig(crmConfMap); /* <nodes> */ /* xml node with cluster node make stupid variable names, but let's * keep the convention. */ String dc = null; final Node nodesNode = getChildNode(confNode, "nodes"); if (nodesNode != null) { final NodeList nodes = nodesNode.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { final Node nodeNode = nodes.item(i); if (nodeNode.getNodeName().equals("node")) { /* TODO: doing nothing with the info, just getting the dc, * for now. */ final String uuid = getAttribute(nodeNode, "id"); final String uname = getAttribute(nodeNode, "uname"); if (dcUuid != null && dcUuid.equals(uuid)) { dc = uname; } } } } /* <resources> */ final Node resourcesNode = getChildNode(confNode, "resources"); if (resourcesNode == null) { return cibQueryData; } /* <primitive> */ //Map<String,String> resourceItemTypeMap = new HashMap<String,String>(); final Map<String, Map<String, String>> parametersMap = new HashMap<String, Map<String, String>>(); final Map<String, Map<String, String>> parametersNvpairsIdsMap = new HashMap<String, Map<String, String>>(); final Map<String, ResourceAgent> resourceTypeMap = new HashMap<String, ResourceAgent>(); final Map<String, String> resourceInstanceAttrIdMap = new HashMap<String, String>(); final MultiKeyMap operationsMap = new MultiKeyMap(); final Map<String, String> operationsIdMap = new HashMap<String, String>(); final Map<String, Map<String, String>> resOpIdsMap = new HashMap<String, Map<String, String>>(); final Map<String, List<String>> groupsToResourcesMap = new HashMap<String, List<String>>(); final Map<String, String> cloneToResourceMap = new HashMap<String, String>(); final List<String> masterList = new ArrayList<String>(); final MultiKeyMap failedMap = new MultiKeyMap(); groupsToResourcesMap.put("none", new ArrayList<String>()); final NodeList primitivesGroups = resourcesNode.getChildNodes(); for (int i = 0; i < primitivesGroups.getLength(); i++) { final Node primitiveGroupNode = primitivesGroups.item(i); final String nodeName = primitiveGroupNode.getNodeName(); if ("primitive".equals(nodeName)) { final List<String> resList = groupsToResourcesMap.get("none"); parsePrimitive(primitiveGroupNode, resList, resourceTypeMap, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); } else if ("group".equals(nodeName)) { final NodeList primitives = primitiveGroupNode.getChildNodes(); final String groupId = getAttribute(primitiveGroupNode, "id"); parametersMap.put(groupId, new HashMap<String, String>()); List<String> resList = groupsToResourcesMap.get(groupId); if (resList == null) { resList = new ArrayList<String>(); groupsToResourcesMap.put(groupId, resList); } for (int j = 0; j < primitives.getLength(); j++) { final Node primitiveNode = primitives.item(j); if (primitiveNode.getNodeName().equals("primitive")) { parsePrimitive(primitiveNode, resList, resourceTypeMap, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); } } } else if ("master".equals(nodeName) || "master_slave".equals(nodeName) || "clone".equals(nodeName)) { final NodeList primitives = primitiveGroupNode.getChildNodes(); final String cloneId = getAttribute(primitiveGroupNode, "id"); parametersMap.put(cloneId, new HashMap<String, String>()); List<String> resList = groupsToResourcesMap.get(cloneId); if (resList == null) { resList = new ArrayList<String>(); groupsToResourcesMap.put(cloneId, resList); } parseAttributes(primitiveGroupNode, cloneId, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); for (int j = 0; j < primitives.getLength(); j++) { final Node primitiveNode = primitives.item(j); if (primitiveNode.getNodeName().equals("primitive")) { parsePrimitive(primitiveNode, resList, resourceTypeMap, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); } } if (!resList.isEmpty()) { cloneToResourceMap.put(cloneId, resList.get(0)); if ("master".equals(nodeName) || "master_slave".equals(nodeName)) { masterList.add(cloneId); } } } } /* <constraints> */ final Map<String, List<String>> colocationMap = new HashMap<String, List<String>>(); final MultiKeyMap colocationIdMap = new MultiKeyMap(); final MultiKeyMap colocationScoreMap = new MultiKeyMap(); final MultiKeyMap colocationRscRoleMap = new MultiKeyMap(); final MultiKeyMap colocationWithRscRoleMap = new MultiKeyMap(); final Map<String, List<String>> orderMap = new HashMap<String, List<String>>(); final MultiKeyMap orderIdMap = new MultiKeyMap(); final MultiKeyMap orderFirstActionMap = new MultiKeyMap(); final MultiKeyMap orderThenActionMap = new MultiKeyMap(); final MultiKeyMap orderDirectionMap = new MultiKeyMap(); final MultiKeyMap orderScoreMap = new MultiKeyMap(); final MultiKeyMap orderSymmetricalMap = new MultiKeyMap(); final Map<String, Map<String, String>> locationMap = new HashMap<String, Map<String, String>>(); final Map<String, List<String>> locationsIdMap = new HashMap<String, List<String>>(); final MultiKeyMap resHostToLocIdMap = new MultiKeyMap(); final Node constraintsNode = getChildNode(confNode, "constraints"); if (constraintsNode != null) { final NodeList constraints = constraintsNode.getChildNodes(); String rscString = "rsc"; String rscRoleString = "rsc-role"; String withRscString = "with-rsc"; String withRscRoleString = "with-rsc-role"; String firstString = "first"; String thenString = "then"; String firstActionString = "first-action"; String thenActionString = "then-action"; if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { rscString = "from"; rscRoleString = "from_role"; //TODO: just guessing withRscString = "to"; withRscRoleString = "to_role"; //TODO: just guessing firstString = "from"; thenString = "to"; firstActionString = "action"; thenActionString = "to_action"; } for (int i = 0; i < constraints.getLength(); i++) { final Node constraintNode = constraints.item(i); if (constraintNode.getNodeName().equals("rsc_colocation")) { final String colId = getAttribute(constraintNode, "id"); final String rsc = getAttribute(constraintNode, rscString); final String rscRole = getAttribute(constraintNode, rscRoleString); final String withRsc = getAttribute(constraintNode, withRscString); final String withRscRole = getAttribute(constraintNode, withRscRoleString); final String score = getAttribute(constraintNode, "score"); List<String> tos = colocationMap.get(rsc); if (tos == null) { tos = new ArrayList<String>(); } tos.add(withRsc); colocationMap.put(rsc, tos); colocationScoreMap.put(rsc, withRsc, score); colocationRscRoleMap.put(rsc, withRsc, rscRole); colocationWithRscRoleMap.put(rsc, withRsc, withRscRole); colocationIdMap.put(rsc, withRsc, colId); // TODO: node-attribute } else if (constraintNode.getNodeName().equals("rsc_order")) { final String ordId = getAttribute(constraintNode, "id"); final String rscFrom = getAttribute(constraintNode, firstString); final String rscTo = getAttribute(constraintNode, thenString); final String score = getAttribute(constraintNode, "score"); final String symmetrical = getAttribute(constraintNode, "symmetrical"); final String firstAction = getAttribute(constraintNode, firstActionString); final String thenAction = getAttribute(constraintNode, thenActionString); List<String> tos = orderMap.get(rscFrom); if (tos == null) { tos = new ArrayList<String>(); } tos.add(rscTo); orderMap.put(rscFrom, tos); //TODO: before is not needed in pacemaker anymore orderDirectionMap.put(rscFrom, rscTo, "before"); orderScoreMap.put(rscFrom, rscTo, score); orderSymmetricalMap.put(rscFrom, rscTo, symmetrical); orderIdMap.put(rscFrom, rscTo, ordId); orderFirstActionMap.put(rscFrom, rscTo, firstAction); orderThenActionMap.put(rscFrom, rscTo, thenAction); } else if ("rsc_location".equals( constraintNode.getNodeName())) { final String locId = getAttribute(constraintNode, "id"); final String node = getAttribute(constraintNode, "node"); final String rsc = getAttribute(constraintNode, "rsc"); final String score = getAttribute(constraintNode, "score"); List<String> locs = locationsIdMap.get(rsc); if (locs == null) { locs = new ArrayList<String>(); locationsIdMap.put(rsc, locs); } Map<String, String> hostScoreMap = locationMap.get(rsc); if (hostScoreMap == null) { hostScoreMap = new HashMap<String, String>(); locationMap.put(rsc, hostScoreMap); } if (node != null) { resHostToLocIdMap.put(rsc, node, locId); } if (score != null) { hostScoreMap.put(node, score); } locs.add(locId); final Node ruleNode = getChildNode(constraintNode, "rule"); if (ruleNode != null) { final String score2 = getAttribute(ruleNode, "score"); final String booleanOp = getAttribute(ruleNode, "boolean-op"); // TODO: I know only "and", ignoring everything we // don't know. final Node expNode = getChildNode(ruleNode, "expression"); if (expNode != null) { if ("expression".equals(expNode.getNodeName())) { final String attr = getAttribute(expNode, "attribute"); final String op = getAttribute(expNode, "operation"); final String type = getAttribute(expNode, "type"); final String node2 = getAttribute(expNode, "value"); - if ("and".equals(booleanOp) + if ((booleanOp == null + || "and".equals(booleanOp)) && "#uname".equals(attr) && "string".equals(type) && "eq".equals(op)) { hostScoreMap.put(node2, score2); } } } } } } } /* <status> */ final Set<String> activeNodes = new HashSet<String>(); final Node statusNode = getChildNode(cibNode, "status"); if (statusNode != null) { /* <node_state ...> */ final NodeList nodes = statusNode.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { final Node nodeStateNode = nodes.item(i); if ("node_state".equals(nodeStateNode.getNodeName())) { final String uname = getAttribute(nodeStateNode, "uname"); final String ha = getAttribute(nodeStateNode, "ha"); //final String id = getAttribute(nodeStateNode, "id"); //final String crmd = getAttribute(nodeStateNode, "crmd"); //final String shutdown = // getAttribute(nodeStateNode, "shutdown"); //final String inCcm = // getAttribute(nodeStateNode, "in_ccm"); ///* active / dead */ //final String join = getAttribute(nodeStateNode, "join"); //final String expected = // getAttribute(nodeStateNode, "expected"); /* TODO: check and use other stuff too. */ if ("active".equals(ha)) { activeNodes.add(uname); } final NodeList nodeStates = nodeStateNode.getChildNodes(); for (int j = 0; j < nodeStates.getLength(); j++) { final Node nodeStateChild = nodeStates.item(j); if ("transient_attributes".equals( nodeStateChild.getNodeName())) { parseTransientAttributes(uname, nodeStateChild, failedMap, hbV); } } } } } cibQueryData.setDC(dc); cibQueryData.setParameters(parametersMap); cibQueryData.setParametersNvpairsIds(parametersNvpairsIdsMap); cibQueryData.setResourceType(resourceTypeMap); cibQueryData.setResourceInstanceAttrId(resourceInstanceAttrIdMap); cibQueryData.setColocation(colocationMap); cibQueryData.setColocationScore(colocationScoreMap); cibQueryData.setColocationRscRole(colocationRscRoleMap); cibQueryData.setColocationWithRscRole(colocationWithRscRoleMap); cibQueryData.setColocationId(colocationIdMap); cibQueryData.setOrder(orderMap); cibQueryData.setOrderId(orderIdMap); cibQueryData.setOrderFirstAction(orderFirstActionMap); cibQueryData.setOrderThenAction(orderThenActionMap); cibQueryData.setOrderScore(orderScoreMap); cibQueryData.setOrderSymmetrical(orderSymmetricalMap); cibQueryData.setOrderDirection(orderDirectionMap); cibQueryData.setLocation(locationMap); cibQueryData.setLocationsId(locationsIdMap); cibQueryData.setResHostToLocId(resHostToLocIdMap); cibQueryData.setOperations(operationsMap); cibQueryData.setOperationsId(operationsIdMap); cibQueryData.setResOpIds(resOpIdsMap); cibQueryData.setActiveNodes(activeNodes); cibQueryData.setGroupsToResources(groupsToResourcesMap); cibQueryData.setCloneToResource(cloneToResourceMap); cibQueryData.setMasterList(masterList); cibQueryData.setFailed(failedMap); return cibQueryData; } /** * Returns order parameters. */ public final String[] getOrderParameters() { if (ordParams != null) { return ordParams.toArray(new String[ordParams.size()]); } return null; } /** * Checks if parameter is required or not. */ public final boolean isOrderRequired(final String param) { return ordRequiredParams.contains(param); } /** * Returns short description of the order parameter. */ public final String getOrderParamShortDesc(final String param) { String shortDesc = paramOrdShortDescMap.get(param); if (shortDesc == null) { shortDesc = param; } return shortDesc; } /** * Returns long description of the order parameter. */ public final String getOrderParamLongDesc(final String param) { final String shortDesc = getOrderParamShortDesc(param); String longDesc = paramOrdLongDescMap.get(param); if (longDesc == null) { longDesc = ""; } return Tools.html("<b>" + shortDesc + "</b>\n" + longDesc); } /** * Returns type of a order parameter. It can be string, integer, boolean... */ public final String getOrderParamType(final String param) { return paramOrdTypeMap.get(param); } /** * Returns default value for the order parameter. */ public final String getOrderParamDefault(final String param) { return paramOrdDefaultMap.get(param); } /** * Returns the preferred value for the order parameter. */ public final String getOrderParamPreferred(final String param) { return paramOrdPreferredMap.get(param); } /** * Returns possible choices for a order parameter, that will be displayed * in the combo box. */ public final String[] getOrderParamPossibleChoices(final String param, final boolean ms) { if (ms) { return paramOrdPossibleChoicesMS.get(param); } else { return paramOrdPossibleChoices.get(param); } } /** * Returns whether the order parameter expects an integer value. */ public final boolean isOrderInteger(final String param) { final String type = getOrderParamType(param); return PARAM_TYPE_INTEGER.equals(type); } /** * Returns whether the order parameter expects a boolean value. */ public final boolean isOrderBoolean(final String param) { final String type = getOrderParamType(param); return PARAM_TYPE_BOOLEAN.equals(type); } /** * Whether the order parameter is of the time type. */ public final boolean isOrderTimeType(final String param) { final String type = getOrderParamType(param); return PARAM_TYPE_TIME.equals(type); } /** * Returns name of the section order parameter that will be * displayed. */ public final String getOrderSection(final String param) { return Tools.getString("CRMXML.OrderSectionParams"); } /** * Checks order parameter according to its type. Returns false if value * does not fit the type. */ public final boolean checkOrderParam(final String param, final String value) { final String type = getOrderParamType(param); boolean correctValue = true; if (PARAM_TYPE_BOOLEAN.equals(type)) { if (!"yes".equals(value) && !"no".equals(value) && !Tools.getString("Heartbeat.Boolean.True").equals(value) && !Tools.getString("Heartbeat.Boolean.False").equals(value) && !Tools.getString( "Heartbeat.2.1.3.Boolean.True").equals(value) && !Tools.getString( "Heartbeat.2.1.3.Boolean.False").equals(value)) { correctValue = false; } } else if (PARAM_TYPE_INTEGER.equals(type)) { final Pattern p = Pattern.compile("^-?(\\d*|INFINITY)$"); final Matcher m = p.matcher(value); if (!m.matches()) { correctValue = false; } } else if (PARAM_TYPE_TIME.equals(type)) { final Pattern p = Pattern.compile("^-?\\d*(ms|msec|us|usec|s|sec|m|min|h|hr)?$"); final Matcher m = p.matcher(value); if (!m.matches()) { correctValue = false; } } else if ((value == null || "".equals(value)) && isOrderRequired(param)) { correctValue = false; } return correctValue; } /** * Returns colocation parameters. */ public final String[] getColocationParameters() { if (colParams != null) { return colParams.toArray(new String[colParams.size()]); } return null; } /** * Checks if parameter is required or not. */ public final boolean isColocationRequired(final String param) { return colRequiredParams.contains(param); } /** * Returns short description of the colocation parameter. */ public final String getColocationParamShortDesc(final String param) { String shortDesc = paramColShortDescMap.get(param); if (shortDesc == null) { shortDesc = param; } return shortDesc; } /** * Returns long description of the colocation parameter. */ public final String getColocationParamLongDesc(final String param) { final String shortDesc = getColocationParamShortDesc(param); String longDesc = paramColLongDescMap.get(param); if (longDesc == null) { longDesc = ""; } return Tools.html("<b>" + shortDesc + "</b>\n" + longDesc); } /** * Returns type of a colocation parameter. It can be string, integer... */ public final String getColocationParamType(final String param) { return paramColTypeMap.get(param); } /** * Returns default value for the colocation parameter. */ public final String getColocationParamDefault(final String param) { return paramColDefaultMap.get(param); } /** * Returns the preferred value for the colocation parameter. */ public final String getColocationParamPreferred(final String param) { return paramColPreferredMap.get(param); } /** * Returns possible choices for a colocation parameter, that will be * displayed in the combo box. */ public final String[] getColocationParamPossibleChoices(final String param, final boolean ms) { if (ms) { return paramColPossibleChoicesMS.get(param); } else { return paramColPossibleChoices.get(param); } } /** * Returns whether the colocation parameter expects an integer value. */ public final boolean isColocationInteger(final String param) { final String type = getColocationParamType(param); return PARAM_TYPE_INTEGER.equals(type); } /** * Returns whether the colocation parameter expects a boolean value. */ public final boolean isColocationBoolean(final String param) { final String type = getOrderParamType(param); return PARAM_TYPE_BOOLEAN.equals(type); } /** * Whether the colocation parameter is of the time type. */ public final boolean isColocationTimeType(final String param) { final String type = getColocationParamType(param); return PARAM_TYPE_TIME.equals(type); } /** * Returns name of the section colocation parameter that will be * displayed. */ public final String getColocationSection(final String param) { return Tools.getString("CRMXML.ColocationSectionParams"); } /** * Checks colocation parameter according to its type. Returns false if value * does not fit the type. */ public final boolean checkColocationParam(final String param, final String value) { final String type = getColocationParamType(param); boolean correctValue = true; if (PARAM_TYPE_BOOLEAN.equals(type)) { if (!"yes".equals(value) && !"no".equals(value) && !Tools.getString("Heartbeat.Boolean.True").equals(value) && !Tools.getString("Heartbeat.Boolean.False").equals(value) && !Tools.getString( "Heartbeat.2.1.3.Boolean.True").equals(value) && !Tools.getString( "Heartbeat.2.1.3.Boolean.False").equals(value)) { correctValue = false; } } else if (PARAM_TYPE_INTEGER.equals(type)) { final Pattern p = Pattern.compile("^-?(\\d*|INFINITY)$"); final Matcher m = p.matcher(value); if (!m.matches()) { correctValue = false; } } else if (PARAM_TYPE_TIME.equals(type)) { final Pattern p = Pattern.compile("^-?\\d*(ms|msec|us|usec|s|sec|m|min|h|hr)?$"); final Matcher m = p.matcher(value); if (!m.matches()) { correctValue = false; } } else if ((value == null || "".equals(value)) && isColocationRequired(param)) { correctValue = false; } return correctValue; } /** Returns whether drbddisk ra is present. */ public final boolean isDrbddiskPresent() { return drbddiskPresent; } /** Returns whether linbit::drbd ra is present. */ public final boolean isLinbitDrbdPresent() { return linbitDrbdPresent; } }
true
true
public final CibQuery parseCibQuery(final String query) { final Document document = getXMLDocument(query); final CibQuery cibQueryData = new CibQuery(); if (document == null) { return cibQueryData; } /* get root <cib> */ final Node cibNode = getChildNode(document, "cib"); if (cibNode == null) { return cibQueryData; } /* Designated Co-ordinator */ final String dcUuid = getAttribute(cibNode, "dc-uuid"); //TODO: more attributes are here /* <configuration> */ final Node confNode = getChildNode(cibNode, "configuration"); if (confNode == null) { return cibQueryData; } /* <crm_config> */ final Node crmConfNode = getChildNode(confNode, "crm_config"); if (crmConfNode == null) { return cibQueryData; } /* <cluster_property_set> */ final Node cpsNode = getChildNode(crmConfNode, "cluster_property_set"); if (cpsNode == null) { return cibQueryData; } NodeList nvpairs; final String hbV = host.getHeartbeatVersion(); if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { /* <attributtes> only til 2.1.4 */ final Node attrNode = getChildNode(cpsNode, "attributes"); nvpairs = attrNode.getChildNodes(); } else { nvpairs = cpsNode.getChildNodes(); } final Map<String, String> crmConfMap = new HashMap<String, String>(); /* <nvpair...> */ for (int i = 0; i < nvpairs.getLength(); i++) { final Node optionNode = nvpairs.item(i); if (optionNode.getNodeName().equals("nvpair")) { final String name = getAttribute(optionNode, "name"); final String value = getAttribute(optionNode, "value"); crmConfMap.put(name, value); } } cibQueryData.setCrmConfig(crmConfMap); /* <nodes> */ /* xml node with cluster node make stupid variable names, but let's * keep the convention. */ String dc = null; final Node nodesNode = getChildNode(confNode, "nodes"); if (nodesNode != null) { final NodeList nodes = nodesNode.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { final Node nodeNode = nodes.item(i); if (nodeNode.getNodeName().equals("node")) { /* TODO: doing nothing with the info, just getting the dc, * for now. */ final String uuid = getAttribute(nodeNode, "id"); final String uname = getAttribute(nodeNode, "uname"); if (dcUuid != null && dcUuid.equals(uuid)) { dc = uname; } } } } /* <resources> */ final Node resourcesNode = getChildNode(confNode, "resources"); if (resourcesNode == null) { return cibQueryData; } /* <primitive> */ //Map<String,String> resourceItemTypeMap = new HashMap<String,String>(); final Map<String, Map<String, String>> parametersMap = new HashMap<String, Map<String, String>>(); final Map<String, Map<String, String>> parametersNvpairsIdsMap = new HashMap<String, Map<String, String>>(); final Map<String, ResourceAgent> resourceTypeMap = new HashMap<String, ResourceAgent>(); final Map<String, String> resourceInstanceAttrIdMap = new HashMap<String, String>(); final MultiKeyMap operationsMap = new MultiKeyMap(); final Map<String, String> operationsIdMap = new HashMap<String, String>(); final Map<String, Map<String, String>> resOpIdsMap = new HashMap<String, Map<String, String>>(); final Map<String, List<String>> groupsToResourcesMap = new HashMap<String, List<String>>(); final Map<String, String> cloneToResourceMap = new HashMap<String, String>(); final List<String> masterList = new ArrayList<String>(); final MultiKeyMap failedMap = new MultiKeyMap(); groupsToResourcesMap.put("none", new ArrayList<String>()); final NodeList primitivesGroups = resourcesNode.getChildNodes(); for (int i = 0; i < primitivesGroups.getLength(); i++) { final Node primitiveGroupNode = primitivesGroups.item(i); final String nodeName = primitiveGroupNode.getNodeName(); if ("primitive".equals(nodeName)) { final List<String> resList = groupsToResourcesMap.get("none"); parsePrimitive(primitiveGroupNode, resList, resourceTypeMap, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); } else if ("group".equals(nodeName)) { final NodeList primitives = primitiveGroupNode.getChildNodes(); final String groupId = getAttribute(primitiveGroupNode, "id"); parametersMap.put(groupId, new HashMap<String, String>()); List<String> resList = groupsToResourcesMap.get(groupId); if (resList == null) { resList = new ArrayList<String>(); groupsToResourcesMap.put(groupId, resList); } for (int j = 0; j < primitives.getLength(); j++) { final Node primitiveNode = primitives.item(j); if (primitiveNode.getNodeName().equals("primitive")) { parsePrimitive(primitiveNode, resList, resourceTypeMap, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); } } } else if ("master".equals(nodeName) || "master_slave".equals(nodeName) || "clone".equals(nodeName)) { final NodeList primitives = primitiveGroupNode.getChildNodes(); final String cloneId = getAttribute(primitiveGroupNode, "id"); parametersMap.put(cloneId, new HashMap<String, String>()); List<String> resList = groupsToResourcesMap.get(cloneId); if (resList == null) { resList = new ArrayList<String>(); groupsToResourcesMap.put(cloneId, resList); } parseAttributes(primitiveGroupNode, cloneId, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); for (int j = 0; j < primitives.getLength(); j++) { final Node primitiveNode = primitives.item(j); if (primitiveNode.getNodeName().equals("primitive")) { parsePrimitive(primitiveNode, resList, resourceTypeMap, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); } } if (!resList.isEmpty()) { cloneToResourceMap.put(cloneId, resList.get(0)); if ("master".equals(nodeName) || "master_slave".equals(nodeName)) { masterList.add(cloneId); } } } } /* <constraints> */ final Map<String, List<String>> colocationMap = new HashMap<String, List<String>>(); final MultiKeyMap colocationIdMap = new MultiKeyMap(); final MultiKeyMap colocationScoreMap = new MultiKeyMap(); final MultiKeyMap colocationRscRoleMap = new MultiKeyMap(); final MultiKeyMap colocationWithRscRoleMap = new MultiKeyMap(); final Map<String, List<String>> orderMap = new HashMap<String, List<String>>(); final MultiKeyMap orderIdMap = new MultiKeyMap(); final MultiKeyMap orderFirstActionMap = new MultiKeyMap(); final MultiKeyMap orderThenActionMap = new MultiKeyMap(); final MultiKeyMap orderDirectionMap = new MultiKeyMap(); final MultiKeyMap orderScoreMap = new MultiKeyMap(); final MultiKeyMap orderSymmetricalMap = new MultiKeyMap(); final Map<String, Map<String, String>> locationMap = new HashMap<String, Map<String, String>>(); final Map<String, List<String>> locationsIdMap = new HashMap<String, List<String>>(); final MultiKeyMap resHostToLocIdMap = new MultiKeyMap(); final Node constraintsNode = getChildNode(confNode, "constraints"); if (constraintsNode != null) { final NodeList constraints = constraintsNode.getChildNodes(); String rscString = "rsc"; String rscRoleString = "rsc-role"; String withRscString = "with-rsc"; String withRscRoleString = "with-rsc-role"; String firstString = "first"; String thenString = "then"; String firstActionString = "first-action"; String thenActionString = "then-action"; if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { rscString = "from"; rscRoleString = "from_role"; //TODO: just guessing withRscString = "to"; withRscRoleString = "to_role"; //TODO: just guessing firstString = "from"; thenString = "to"; firstActionString = "action"; thenActionString = "to_action"; } for (int i = 0; i < constraints.getLength(); i++) { final Node constraintNode = constraints.item(i); if (constraintNode.getNodeName().equals("rsc_colocation")) { final String colId = getAttribute(constraintNode, "id"); final String rsc = getAttribute(constraintNode, rscString); final String rscRole = getAttribute(constraintNode, rscRoleString); final String withRsc = getAttribute(constraintNode, withRscString); final String withRscRole = getAttribute(constraintNode, withRscRoleString); final String score = getAttribute(constraintNode, "score"); List<String> tos = colocationMap.get(rsc); if (tos == null) { tos = new ArrayList<String>(); } tos.add(withRsc); colocationMap.put(rsc, tos); colocationScoreMap.put(rsc, withRsc, score); colocationRscRoleMap.put(rsc, withRsc, rscRole); colocationWithRscRoleMap.put(rsc, withRsc, withRscRole); colocationIdMap.put(rsc, withRsc, colId); // TODO: node-attribute } else if (constraintNode.getNodeName().equals("rsc_order")) { final String ordId = getAttribute(constraintNode, "id"); final String rscFrom = getAttribute(constraintNode, firstString); final String rscTo = getAttribute(constraintNode, thenString); final String score = getAttribute(constraintNode, "score"); final String symmetrical = getAttribute(constraintNode, "symmetrical"); final String firstAction = getAttribute(constraintNode, firstActionString); final String thenAction = getAttribute(constraintNode, thenActionString); List<String> tos = orderMap.get(rscFrom); if (tos == null) { tos = new ArrayList<String>(); } tos.add(rscTo); orderMap.put(rscFrom, tos); //TODO: before is not needed in pacemaker anymore orderDirectionMap.put(rscFrom, rscTo, "before"); orderScoreMap.put(rscFrom, rscTo, score); orderSymmetricalMap.put(rscFrom, rscTo, symmetrical); orderIdMap.put(rscFrom, rscTo, ordId); orderFirstActionMap.put(rscFrom, rscTo, firstAction); orderThenActionMap.put(rscFrom, rscTo, thenAction); } else if ("rsc_location".equals( constraintNode.getNodeName())) { final String locId = getAttribute(constraintNode, "id"); final String node = getAttribute(constraintNode, "node"); final String rsc = getAttribute(constraintNode, "rsc"); final String score = getAttribute(constraintNode, "score"); List<String> locs = locationsIdMap.get(rsc); if (locs == null) { locs = new ArrayList<String>(); locationsIdMap.put(rsc, locs); } Map<String, String> hostScoreMap = locationMap.get(rsc); if (hostScoreMap == null) { hostScoreMap = new HashMap<String, String>(); locationMap.put(rsc, hostScoreMap); } if (node != null) { resHostToLocIdMap.put(rsc, node, locId); } if (score != null) { hostScoreMap.put(node, score); } locs.add(locId); final Node ruleNode = getChildNode(constraintNode, "rule"); if (ruleNode != null) { final String score2 = getAttribute(ruleNode, "score"); final String booleanOp = getAttribute(ruleNode, "boolean-op"); // TODO: I know only "and", ignoring everything we // don't know. final Node expNode = getChildNode(ruleNode, "expression"); if (expNode != null) { if ("expression".equals(expNode.getNodeName())) { final String attr = getAttribute(expNode, "attribute"); final String op = getAttribute(expNode, "operation"); final String type = getAttribute(expNode, "type"); final String node2 = getAttribute(expNode, "value"); if ("and".equals(booleanOp) && "#uname".equals(attr) && "string".equals(type) && "eq".equals(op)) { hostScoreMap.put(node2, score2); } } } } } } } /* <status> */ final Set<String> activeNodes = new HashSet<String>(); final Node statusNode = getChildNode(cibNode, "status"); if (statusNode != null) { /* <node_state ...> */ final NodeList nodes = statusNode.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { final Node nodeStateNode = nodes.item(i); if ("node_state".equals(nodeStateNode.getNodeName())) { final String uname = getAttribute(nodeStateNode, "uname"); final String ha = getAttribute(nodeStateNode, "ha"); //final String id = getAttribute(nodeStateNode, "id"); //final String crmd = getAttribute(nodeStateNode, "crmd"); //final String shutdown = // getAttribute(nodeStateNode, "shutdown"); //final String inCcm = // getAttribute(nodeStateNode, "in_ccm"); ///* active / dead */ //final String join = getAttribute(nodeStateNode, "join"); //final String expected = // getAttribute(nodeStateNode, "expected"); /* TODO: check and use other stuff too. */ if ("active".equals(ha)) { activeNodes.add(uname); } final NodeList nodeStates = nodeStateNode.getChildNodes(); for (int j = 0; j < nodeStates.getLength(); j++) { final Node nodeStateChild = nodeStates.item(j); if ("transient_attributes".equals( nodeStateChild.getNodeName())) { parseTransientAttributes(uname, nodeStateChild, failedMap, hbV); } } } } } cibQueryData.setDC(dc); cibQueryData.setParameters(parametersMap); cibQueryData.setParametersNvpairsIds(parametersNvpairsIdsMap); cibQueryData.setResourceType(resourceTypeMap); cibQueryData.setResourceInstanceAttrId(resourceInstanceAttrIdMap); cibQueryData.setColocation(colocationMap); cibQueryData.setColocationScore(colocationScoreMap); cibQueryData.setColocationRscRole(colocationRscRoleMap); cibQueryData.setColocationWithRscRole(colocationWithRscRoleMap); cibQueryData.setColocationId(colocationIdMap); cibQueryData.setOrder(orderMap); cibQueryData.setOrderId(orderIdMap); cibQueryData.setOrderFirstAction(orderFirstActionMap); cibQueryData.setOrderThenAction(orderThenActionMap); cibQueryData.setOrderScore(orderScoreMap); cibQueryData.setOrderSymmetrical(orderSymmetricalMap); cibQueryData.setOrderDirection(orderDirectionMap); cibQueryData.setLocation(locationMap); cibQueryData.setLocationsId(locationsIdMap); cibQueryData.setResHostToLocId(resHostToLocIdMap); cibQueryData.setOperations(operationsMap); cibQueryData.setOperationsId(operationsIdMap); cibQueryData.setResOpIds(resOpIdsMap); cibQueryData.setActiveNodes(activeNodes); cibQueryData.setGroupsToResources(groupsToResourcesMap); cibQueryData.setCloneToResource(cloneToResourceMap); cibQueryData.setMasterList(masterList); cibQueryData.setFailed(failedMap); return cibQueryData; }
public final CibQuery parseCibQuery(final String query) { final Document document = getXMLDocument(query); final CibQuery cibQueryData = new CibQuery(); if (document == null) { return cibQueryData; } /* get root <cib> */ final Node cibNode = getChildNode(document, "cib"); if (cibNode == null) { return cibQueryData; } /* Designated Co-ordinator */ final String dcUuid = getAttribute(cibNode, "dc-uuid"); //TODO: more attributes are here /* <configuration> */ final Node confNode = getChildNode(cibNode, "configuration"); if (confNode == null) { return cibQueryData; } /* <crm_config> */ final Node crmConfNode = getChildNode(confNode, "crm_config"); if (crmConfNode == null) { return cibQueryData; } /* <cluster_property_set> */ final Node cpsNode = getChildNode(crmConfNode, "cluster_property_set"); if (cpsNode == null) { return cibQueryData; } NodeList nvpairs; final String hbV = host.getHeartbeatVersion(); if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { /* <attributtes> only til 2.1.4 */ final Node attrNode = getChildNode(cpsNode, "attributes"); nvpairs = attrNode.getChildNodes(); } else { nvpairs = cpsNode.getChildNodes(); } final Map<String, String> crmConfMap = new HashMap<String, String>(); /* <nvpair...> */ for (int i = 0; i < nvpairs.getLength(); i++) { final Node optionNode = nvpairs.item(i); if (optionNode.getNodeName().equals("nvpair")) { final String name = getAttribute(optionNode, "name"); final String value = getAttribute(optionNode, "value"); crmConfMap.put(name, value); } } cibQueryData.setCrmConfig(crmConfMap); /* <nodes> */ /* xml node with cluster node make stupid variable names, but let's * keep the convention. */ String dc = null; final Node nodesNode = getChildNode(confNode, "nodes"); if (nodesNode != null) { final NodeList nodes = nodesNode.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { final Node nodeNode = nodes.item(i); if (nodeNode.getNodeName().equals("node")) { /* TODO: doing nothing with the info, just getting the dc, * for now. */ final String uuid = getAttribute(nodeNode, "id"); final String uname = getAttribute(nodeNode, "uname"); if (dcUuid != null && dcUuid.equals(uuid)) { dc = uname; } } } } /* <resources> */ final Node resourcesNode = getChildNode(confNode, "resources"); if (resourcesNode == null) { return cibQueryData; } /* <primitive> */ //Map<String,String> resourceItemTypeMap = new HashMap<String,String>(); final Map<String, Map<String, String>> parametersMap = new HashMap<String, Map<String, String>>(); final Map<String, Map<String, String>> parametersNvpairsIdsMap = new HashMap<String, Map<String, String>>(); final Map<String, ResourceAgent> resourceTypeMap = new HashMap<String, ResourceAgent>(); final Map<String, String> resourceInstanceAttrIdMap = new HashMap<String, String>(); final MultiKeyMap operationsMap = new MultiKeyMap(); final Map<String, String> operationsIdMap = new HashMap<String, String>(); final Map<String, Map<String, String>> resOpIdsMap = new HashMap<String, Map<String, String>>(); final Map<String, List<String>> groupsToResourcesMap = new HashMap<String, List<String>>(); final Map<String, String> cloneToResourceMap = new HashMap<String, String>(); final List<String> masterList = new ArrayList<String>(); final MultiKeyMap failedMap = new MultiKeyMap(); groupsToResourcesMap.put("none", new ArrayList<String>()); final NodeList primitivesGroups = resourcesNode.getChildNodes(); for (int i = 0; i < primitivesGroups.getLength(); i++) { final Node primitiveGroupNode = primitivesGroups.item(i); final String nodeName = primitiveGroupNode.getNodeName(); if ("primitive".equals(nodeName)) { final List<String> resList = groupsToResourcesMap.get("none"); parsePrimitive(primitiveGroupNode, resList, resourceTypeMap, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); } else if ("group".equals(nodeName)) { final NodeList primitives = primitiveGroupNode.getChildNodes(); final String groupId = getAttribute(primitiveGroupNode, "id"); parametersMap.put(groupId, new HashMap<String, String>()); List<String> resList = groupsToResourcesMap.get(groupId); if (resList == null) { resList = new ArrayList<String>(); groupsToResourcesMap.put(groupId, resList); } for (int j = 0; j < primitives.getLength(); j++) { final Node primitiveNode = primitives.item(j); if (primitiveNode.getNodeName().equals("primitive")) { parsePrimitive(primitiveNode, resList, resourceTypeMap, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); } } } else if ("master".equals(nodeName) || "master_slave".equals(nodeName) || "clone".equals(nodeName)) { final NodeList primitives = primitiveGroupNode.getChildNodes(); final String cloneId = getAttribute(primitiveGroupNode, "id"); parametersMap.put(cloneId, new HashMap<String, String>()); List<String> resList = groupsToResourcesMap.get(cloneId); if (resList == null) { resList = new ArrayList<String>(); groupsToResourcesMap.put(cloneId, resList); } parseAttributes(primitiveGroupNode, cloneId, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); for (int j = 0; j < primitives.getLength(); j++) { final Node primitiveNode = primitives.item(j); if (primitiveNode.getNodeName().equals("primitive")) { parsePrimitive(primitiveNode, resList, resourceTypeMap, parametersMap, parametersNvpairsIdsMap, resourceInstanceAttrIdMap, operationsMap, operationsIdMap, resOpIdsMap); } } if (!resList.isEmpty()) { cloneToResourceMap.put(cloneId, resList.get(0)); if ("master".equals(nodeName) || "master_slave".equals(nodeName)) { masterList.add(cloneId); } } } } /* <constraints> */ final Map<String, List<String>> colocationMap = new HashMap<String, List<String>>(); final MultiKeyMap colocationIdMap = new MultiKeyMap(); final MultiKeyMap colocationScoreMap = new MultiKeyMap(); final MultiKeyMap colocationRscRoleMap = new MultiKeyMap(); final MultiKeyMap colocationWithRscRoleMap = new MultiKeyMap(); final Map<String, List<String>> orderMap = new HashMap<String, List<String>>(); final MultiKeyMap orderIdMap = new MultiKeyMap(); final MultiKeyMap orderFirstActionMap = new MultiKeyMap(); final MultiKeyMap orderThenActionMap = new MultiKeyMap(); final MultiKeyMap orderDirectionMap = new MultiKeyMap(); final MultiKeyMap orderScoreMap = new MultiKeyMap(); final MultiKeyMap orderSymmetricalMap = new MultiKeyMap(); final Map<String, Map<String, String>> locationMap = new HashMap<String, Map<String, String>>(); final Map<String, List<String>> locationsIdMap = new HashMap<String, List<String>>(); final MultiKeyMap resHostToLocIdMap = new MultiKeyMap(); final Node constraintsNode = getChildNode(confNode, "constraints"); if (constraintsNode != null) { final NodeList constraints = constraintsNode.getChildNodes(); String rscString = "rsc"; String rscRoleString = "rsc-role"; String withRscString = "with-rsc"; String withRscRoleString = "with-rsc-role"; String firstString = "first"; String thenString = "then"; String firstActionString = "first-action"; String thenActionString = "then-action"; if (hbV != null && Tools.compareVersions(hbV, "2.99.0") < 0) { rscString = "from"; rscRoleString = "from_role"; //TODO: just guessing withRscString = "to"; withRscRoleString = "to_role"; //TODO: just guessing firstString = "from"; thenString = "to"; firstActionString = "action"; thenActionString = "to_action"; } for (int i = 0; i < constraints.getLength(); i++) { final Node constraintNode = constraints.item(i); if (constraintNode.getNodeName().equals("rsc_colocation")) { final String colId = getAttribute(constraintNode, "id"); final String rsc = getAttribute(constraintNode, rscString); final String rscRole = getAttribute(constraintNode, rscRoleString); final String withRsc = getAttribute(constraintNode, withRscString); final String withRscRole = getAttribute(constraintNode, withRscRoleString); final String score = getAttribute(constraintNode, "score"); List<String> tos = colocationMap.get(rsc); if (tos == null) { tos = new ArrayList<String>(); } tos.add(withRsc); colocationMap.put(rsc, tos); colocationScoreMap.put(rsc, withRsc, score); colocationRscRoleMap.put(rsc, withRsc, rscRole); colocationWithRscRoleMap.put(rsc, withRsc, withRscRole); colocationIdMap.put(rsc, withRsc, colId); // TODO: node-attribute } else if (constraintNode.getNodeName().equals("rsc_order")) { final String ordId = getAttribute(constraintNode, "id"); final String rscFrom = getAttribute(constraintNode, firstString); final String rscTo = getAttribute(constraintNode, thenString); final String score = getAttribute(constraintNode, "score"); final String symmetrical = getAttribute(constraintNode, "symmetrical"); final String firstAction = getAttribute(constraintNode, firstActionString); final String thenAction = getAttribute(constraintNode, thenActionString); List<String> tos = orderMap.get(rscFrom); if (tos == null) { tos = new ArrayList<String>(); } tos.add(rscTo); orderMap.put(rscFrom, tos); //TODO: before is not needed in pacemaker anymore orderDirectionMap.put(rscFrom, rscTo, "before"); orderScoreMap.put(rscFrom, rscTo, score); orderSymmetricalMap.put(rscFrom, rscTo, symmetrical); orderIdMap.put(rscFrom, rscTo, ordId); orderFirstActionMap.put(rscFrom, rscTo, firstAction); orderThenActionMap.put(rscFrom, rscTo, thenAction); } else if ("rsc_location".equals( constraintNode.getNodeName())) { final String locId = getAttribute(constraintNode, "id"); final String node = getAttribute(constraintNode, "node"); final String rsc = getAttribute(constraintNode, "rsc"); final String score = getAttribute(constraintNode, "score"); List<String> locs = locationsIdMap.get(rsc); if (locs == null) { locs = new ArrayList<String>(); locationsIdMap.put(rsc, locs); } Map<String, String> hostScoreMap = locationMap.get(rsc); if (hostScoreMap == null) { hostScoreMap = new HashMap<String, String>(); locationMap.put(rsc, hostScoreMap); } if (node != null) { resHostToLocIdMap.put(rsc, node, locId); } if (score != null) { hostScoreMap.put(node, score); } locs.add(locId); final Node ruleNode = getChildNode(constraintNode, "rule"); if (ruleNode != null) { final String score2 = getAttribute(ruleNode, "score"); final String booleanOp = getAttribute(ruleNode, "boolean-op"); // TODO: I know only "and", ignoring everything we // don't know. final Node expNode = getChildNode(ruleNode, "expression"); if (expNode != null) { if ("expression".equals(expNode.getNodeName())) { final String attr = getAttribute(expNode, "attribute"); final String op = getAttribute(expNode, "operation"); final String type = getAttribute(expNode, "type"); final String node2 = getAttribute(expNode, "value"); if ((booleanOp == null || "and".equals(booleanOp)) && "#uname".equals(attr) && "string".equals(type) && "eq".equals(op)) { hostScoreMap.put(node2, score2); } } } } } } } /* <status> */ final Set<String> activeNodes = new HashSet<String>(); final Node statusNode = getChildNode(cibNode, "status"); if (statusNode != null) { /* <node_state ...> */ final NodeList nodes = statusNode.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { final Node nodeStateNode = nodes.item(i); if ("node_state".equals(nodeStateNode.getNodeName())) { final String uname = getAttribute(nodeStateNode, "uname"); final String ha = getAttribute(nodeStateNode, "ha"); //final String id = getAttribute(nodeStateNode, "id"); //final String crmd = getAttribute(nodeStateNode, "crmd"); //final String shutdown = // getAttribute(nodeStateNode, "shutdown"); //final String inCcm = // getAttribute(nodeStateNode, "in_ccm"); ///* active / dead */ //final String join = getAttribute(nodeStateNode, "join"); //final String expected = // getAttribute(nodeStateNode, "expected"); /* TODO: check and use other stuff too. */ if ("active".equals(ha)) { activeNodes.add(uname); } final NodeList nodeStates = nodeStateNode.getChildNodes(); for (int j = 0; j < nodeStates.getLength(); j++) { final Node nodeStateChild = nodeStates.item(j); if ("transient_attributes".equals( nodeStateChild.getNodeName())) { parseTransientAttributes(uname, nodeStateChild, failedMap, hbV); } } } } } cibQueryData.setDC(dc); cibQueryData.setParameters(parametersMap); cibQueryData.setParametersNvpairsIds(parametersNvpairsIdsMap); cibQueryData.setResourceType(resourceTypeMap); cibQueryData.setResourceInstanceAttrId(resourceInstanceAttrIdMap); cibQueryData.setColocation(colocationMap); cibQueryData.setColocationScore(colocationScoreMap); cibQueryData.setColocationRscRole(colocationRscRoleMap); cibQueryData.setColocationWithRscRole(colocationWithRscRoleMap); cibQueryData.setColocationId(colocationIdMap); cibQueryData.setOrder(orderMap); cibQueryData.setOrderId(orderIdMap); cibQueryData.setOrderFirstAction(orderFirstActionMap); cibQueryData.setOrderThenAction(orderThenActionMap); cibQueryData.setOrderScore(orderScoreMap); cibQueryData.setOrderSymmetrical(orderSymmetricalMap); cibQueryData.setOrderDirection(orderDirectionMap); cibQueryData.setLocation(locationMap); cibQueryData.setLocationsId(locationsIdMap); cibQueryData.setResHostToLocId(resHostToLocIdMap); cibQueryData.setOperations(operationsMap); cibQueryData.setOperationsId(operationsIdMap); cibQueryData.setResOpIds(resOpIdsMap); cibQueryData.setActiveNodes(activeNodes); cibQueryData.setGroupsToResources(groupsToResourcesMap); cibQueryData.setCloneToResource(cloneToResourceMap); cibQueryData.setMasterList(masterList); cibQueryData.setFailed(failedMap); return cibQueryData; }
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PreferenceInitializer.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PreferenceInitializer.java index f5695c544..558135749 100644 --- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PreferenceInitializer.java +++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PreferenceInitializer.java @@ -1,56 +1,56 @@ /******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.internal.resources; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.preferences.*; /** * @since 3.1 */ public class PreferenceInitializer extends AbstractPreferenceInitializer { public PreferenceInitializer() { super(); } /* (non-Javadoc) * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences() */ public void initializeDefaultPreferences() { IEclipsePreferences node = new DefaultScope().getNode(ResourcesPlugin.PI_RESOURCES); // auto-refresh default node.putBoolean(ResourcesPlugin.PREF_AUTO_REFRESH, false); // linked resources default -// node.putBoolean(ResourcesPlugin.PREF_DISABLE_LINKING, false); + node.putBoolean(ResourcesPlugin.PREF_DISABLE_LINKING, false); // build manager defaults // node.putBoolean(ResourcesPlugin.PREF_AUTO_BUILDING, true); // node.put(ResourcesPlugin.PREF_BUILD_ORDER, ""); //$NON-NLS-1$ // node.put(ResourcesPlugin.PREF_MAX_BUILD_ITERATIONS, ""); //$NON-NLS-1$ // node.put(ResourcesPlugin.PREF_DEFAULT_BUILD_ORDER, ""); //$NON-NLS-1$ // history store defaults // node.putLong(ResourcesPlugin.PREF_FILE_STATE_LONGEVITY, 7 * 24 * 3600 * 1000l); // 7 days // node.putLong(ResourcesPlugin.PREF_MAX_FILE_STATE_SIZE, 1024 * 1024l); // 1 MB // node.putInt(ResourcesPlugin.PREF_MAX_FILE_STATES, 50); // save manager defaults // node.put(ResourcesPlugin.PREF_ENCODING, ""); //$NON-NLS-1$ // node.putLong(ResourcesPlugin.PREF_MAX_NOTIFICATION_DELAY, 10000l); // 10 seconds // encoding defaults // node.putLong(ResourcesPlugin.PREF_SNAPSHOT_INTERVAL, 5 * 60 * 1000l); // 5 min } }
true
true
public void initializeDefaultPreferences() { IEclipsePreferences node = new DefaultScope().getNode(ResourcesPlugin.PI_RESOURCES); // auto-refresh default node.putBoolean(ResourcesPlugin.PREF_AUTO_REFRESH, false); // linked resources default // node.putBoolean(ResourcesPlugin.PREF_DISABLE_LINKING, false); // build manager defaults // node.putBoolean(ResourcesPlugin.PREF_AUTO_BUILDING, true); // node.put(ResourcesPlugin.PREF_BUILD_ORDER, ""); //$NON-NLS-1$ // node.put(ResourcesPlugin.PREF_MAX_BUILD_ITERATIONS, ""); //$NON-NLS-1$ // node.put(ResourcesPlugin.PREF_DEFAULT_BUILD_ORDER, ""); //$NON-NLS-1$ // history store defaults // node.putLong(ResourcesPlugin.PREF_FILE_STATE_LONGEVITY, 7 * 24 * 3600 * 1000l); // 7 days // node.putLong(ResourcesPlugin.PREF_MAX_FILE_STATE_SIZE, 1024 * 1024l); // 1 MB // node.putInt(ResourcesPlugin.PREF_MAX_FILE_STATES, 50); // save manager defaults // node.put(ResourcesPlugin.PREF_ENCODING, ""); //$NON-NLS-1$ // node.putLong(ResourcesPlugin.PREF_MAX_NOTIFICATION_DELAY, 10000l); // 10 seconds // encoding defaults // node.putLong(ResourcesPlugin.PREF_SNAPSHOT_INTERVAL, 5 * 60 * 1000l); // 5 min }
public void initializeDefaultPreferences() { IEclipsePreferences node = new DefaultScope().getNode(ResourcesPlugin.PI_RESOURCES); // auto-refresh default node.putBoolean(ResourcesPlugin.PREF_AUTO_REFRESH, false); // linked resources default node.putBoolean(ResourcesPlugin.PREF_DISABLE_LINKING, false); // build manager defaults // node.putBoolean(ResourcesPlugin.PREF_AUTO_BUILDING, true); // node.put(ResourcesPlugin.PREF_BUILD_ORDER, ""); //$NON-NLS-1$ // node.put(ResourcesPlugin.PREF_MAX_BUILD_ITERATIONS, ""); //$NON-NLS-1$ // node.put(ResourcesPlugin.PREF_DEFAULT_BUILD_ORDER, ""); //$NON-NLS-1$ // history store defaults // node.putLong(ResourcesPlugin.PREF_FILE_STATE_LONGEVITY, 7 * 24 * 3600 * 1000l); // 7 days // node.putLong(ResourcesPlugin.PREF_MAX_FILE_STATE_SIZE, 1024 * 1024l); // 1 MB // node.putInt(ResourcesPlugin.PREF_MAX_FILE_STATES, 50); // save manager defaults // node.put(ResourcesPlugin.PREF_ENCODING, ""); //$NON-NLS-1$ // node.putLong(ResourcesPlugin.PREF_MAX_NOTIFICATION_DELAY, 10000l); // 10 seconds // encoding defaults // node.putLong(ResourcesPlugin.PREF_SNAPSHOT_INTERVAL, 5 * 60 * 1000l); // 5 min }
diff --git a/Dimmer/src/giraffine/dimmer/DimmerService.java b/Dimmer/src/giraffine/dimmer/DimmerService.java index c80ce38..4a1f8c2 100644 --- a/Dimmer/src/giraffine/dimmer/DimmerService.java +++ b/Dimmer/src/giraffine/dimmer/DimmerService.java @@ -1,517 +1,517 @@ package giraffine.dimmer; import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.RunningTaskInfo; import android.app.AlarmManager; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager.NameNotFoundException; import android.database.ContentObserver; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Process; import android.os.SystemClock; import android.provider.Settings; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.view.View; import android.widget.RemoteViews; import android.widget.Toast; public class DimmerService extends Service implements LightSensor.EventCallback{ public static boolean DebugMode = false; public static String PACKAGENAME = "giraffine.dimmer"; public static String ACTIONNOTIFICATION = "giraffine.dimmer.Dimmer.action.notification"; public static ComponentName COMPONENT = new ComponentName(PACKAGENAME, PACKAGENAME+".DimmerService"); public static String ADJUSTLEVEL = "adjustLevel"; public static String FINISHLEVEL = "finishLevel"; public static String RESETLEVEL = "resetLevel"; public static String PAUSEFUNCTION = "pauseFunction"; public static String LAYOUTCHANGE = "layoutChange"; public static String STEPLEVELUP = "stepLevelUp"; public static String STEPLEVELDOWN = "stepLevelDown"; public static String SWITCHAUTOMODE = "switchAutoMode"; public static String SWITCHDIM = "switchDim"; public static String SENSITIVECHANGE = "sensitiveChange"; public static String ALARMMODE = "alarmMode"; public static String ALARMCHANGE = "alarmChange"; public static String BOOT = "boot"; public static final int MSG_RESET_LEVEL = 0; public static final int MSG_RESET_LEVEL_RESTORE = 1; public static final int MSG_RESET_LEVEL_RESTORE_KEEP_NOTIFY = 2; public static final int MSG_RESET_ACTING = 3; public static final int MSG_ENTER_DIMM = 4; public static final int DEFAULTLEVEL = 1000; public static int lastLevel = DEFAULTLEVEL; private boolean mActing = false; private Notification mNotification; private RemoteViews mNotiRemoteView = null; private Mask mMask = null; private boolean mInDimMode = false; private LightSensor mLightSensor = null; private AlarmUtil mAlarmUtil = null; private boolean mKeepSticky = false; private boolean mIsPaused = false; private boolean mLayoutChanged = true; private boolean mLayoutUpdateOnly = false; @Override public IBinder onBind(Intent arg0) { return null; } public void postNotification(int levelHint, boolean dim) { if(mNotiRemoteView == null) initNotification(); if(mLayoutChanged) { relayoutNotification(); mLayoutChanged = false; } if(!mLayoutUpdateOnly) { mNotiRemoteView.setTextViewText(R.id.noti_text, levelHint + ""); for(int i=0; i<4; i++) { if(dim) mNotiRemoteView.setImageViewResource(SettingNotifyLayout.getNotifyButtonID(i, 2), R.drawable.ic_pause); else mNotiRemoteView.setImageViewResource(SettingNotifyLayout.getNotifyButtonID(i, 2), R.drawable.ic_start); } } if(mNotification == null) { Intent intent = new Intent(ACTIONNOTIFICATION); intent.setClassName(PACKAGENAME, PACKAGENAME+".SettingsActivity"); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0); mNotification = new NotificationCompat.Builder(this) .setContent(mNotiRemoteView) .setSmallIcon(R.drawable.ic_launcher) .setContentIntent(pi) .build(); } if(DebugMode) mNotification.tickerText = mLightSensor.getCurrentLux() + ""; mNotification.number = 1; startForeground(999, mNotification); } public void removeNotification() { if(mNotification != null) mNotification.number = 0; stopForeground(true); } public void initNotification() { Intent stepUpIntent = new Intent(this, DimmerService.class); stepUpIntent.setAction(STEPLEVELUP); PendingIntent piStepUp = PendingIntent.getService(this, 0, stepUpIntent, 0); Intent stepDownIntent = new Intent(this, DimmerService.class); stepDownIntent.setAction(STEPLEVELDOWN); PendingIntent piStepDown = PendingIntent.getService(this, 0, stepDownIntent, 0); Intent pauseIntent = new Intent(this, DimmerService.class); pauseIntent.setAction(PAUSEFUNCTION); PendingIntent piPause = PendingIntent.getService(this, 0, pauseIntent, 0); Intent resetIntent = new Intent(this, DimmerService.class); resetIntent.setAction(RESETLEVEL); PendingIntent piReset = PendingIntent.getService(this, 0, resetIntent, 0); // Customization for notification button: // Design A: Dynamically add Remoteivew. // Design B: Dynamically set visible/invisible Button. // Problem A: Fast click button will trigger notification content intent. // Problem B: Need list all permutations and combinations (4x4). mNotiRemoteView = new RemoteViews(PACKAGENAME, R.layout.notification); for(int i=0; i<4; i++) { for(int j=0; j<4; j++) { PendingIntent pi = null; switch(j) { case 0: pi = piStepUp; break; case 1: pi = piStepDown; break; case 2: pi = piPause; break; case 3: pi = piReset; break; } mNotiRemoteView.setOnClickPendingIntent(SettingNotifyLayout.getNotifyButtonID(i, j), pi); } } } public void relayoutNotification() { for(int i=0; i<4; i++) for(int j=0; j<4; j++) mNotiRemoteView.setViewVisibility(SettingNotifyLayout.getNotifyButtonID(i, j), View.GONE); String order = Prefs.getNotifyLayout(); Log.e(Dimmer.TAG, "relayoutNotification: order=" + order); for(int i=0; i<4; i++) { if(order.charAt(i+4) == '1') mNotiRemoteView.setViewVisibility(SettingNotifyLayout.getNotifyButtonID(i, Integer.valueOf(String.valueOf(order.charAt(i)))), View.VISIBLE); } } @Override public void onCreate() { BrightnessUtil.init(this); Prefs.init(this); // lastLevel = BrightnessUtil.getPreferLevel(); int currentBrightness = BrightnessUtil.getBrightness(); lastLevel = (int)(((float)currentBrightness)/255*500 + 500); sendBroadcast(new Intent(Dimmer.REFRESH_INDEX)); mMask = new Mask(this); mLightSensor = new LightSensor(this, this); mAlarmUtil = new AlarmUtil(this); ContentResolver resolver = getContentResolver(); resolver.registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS), true, new ContentObserver(null){ public void onChange(boolean selfChange) { if(mActing == false) mHandler.sendEmptyMessage(MSG_RESET_LEVEL); return; } }); resolver.registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE), true, new ContentObserver(null){ public void onChange(boolean selfChange) { if(mActing == false) mHandler.sendEmptyMessage(MSG_RESET_LEVEL); return; } }); registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { if(Prefs.isAutoMode()) mLightSensor.monitor(true); } }, new IntentFilter(Intent.ACTION_SCREEN_ON)); registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { mLightSensor.monitor(false); } }, new IntentFilter(Intent.ACTION_SCREEN_OFF)); if(Prefs.isAutoMode()) { mLightSensor.monitor(true); mKeepSticky = true; } mAlarmUtil.update(); } public String getForegroundActivity() { ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> Info = am.getRunningTasks(1); ComponentName topActivity = Info.get(0).topActivity; return topActivity.getPackageName(); } @Override public void onDestroy() { Log.e(Dimmer.TAG, "onDestroy()"); // need restart ASAP: 60 secs if(mKeepSticky) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setComponent(COMPONENT); PendingIntent pi = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 60000, pi); } } @Override public void onLightChanged(int lux) { if(DebugMode) postNotification(lastLevel/10, false); if(SettingsActivity.showSettings) sendBroadcast(new Intent(SettingsFragment.REFRESH_LUX).putExtra("lux", lux)); } @Override public void onEnterDarkLight() { // Log.e(Dimmer.TAG, "onDarkLight() mIsAutoMode=" + Prefs.isAutoMode() + ", mInDimmMode=" + mInDimmMode); if(!Prefs.isAutoMode() || getDimMode() || (Prefs.getApList() != null && Prefs.getApList().size() != 0 && Prefs.getApList().contains(getForegroundActivity())) || mIsPaused) return; mLightSensor.setFreezeLux(); mHandler.sendEmptyMessage(MSG_ENTER_DIMM); } @Override public void onLeaveDarkLight() { // Log.e(Dimmer.TAG, "onOverDarkLight() mIsAutoMode=" + Prefs.isAutoMode() + ", mInDimmMode=" + mInDimmMode); if(!Prefs.isAutoMode() || !getDimMode()) return; mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null && intent.getAction() != null) { if(intent.getAction().equals(ADJUSTLEVEL)) { mHandler.removeMessages(MSG_RESET_ACTING); mActing = true; adjustLevel(intent.getIntExtra(ADJUSTLEVEL, DEFAULTLEVEL), false, false); } else if(intent.getAction().equals(FINISHLEVEL)) { int i = intent.getIntExtra(FINISHLEVEL, DEFAULTLEVEL); adjustLevel(intent.getIntExtra(FINISHLEVEL, DEFAULTLEVEL), true, true); lastLevel = i; if(lastLevel < 500) { mLightSensor.setFreezeLux(); Prefs.setFavorMaskValue(lastLevel); } // Log.e(Dimmer.TAG, "" + LuxUtil.dumpLuxLevel()); } else if(intent.getAction().equals(PAUSEFUNCTION)) { if(getDimMode()) mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE_KEEP_NOTIFY); else { mLightSensor.setFreezeLux(); mHandler.sendEmptyMessage(MSG_ENTER_DIMM); } } else if(intent.getAction().equals(RESETLEVEL)) { mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE); } else if(intent.getAction().equals(LAYOUTCHANGE)) { mLayoutChanged = true; - if(mNotification.number == 1) + if(mNotification != null && mNotification.number == 1) { mLayoutUpdateOnly = true; postNotification(0, false); mLayoutUpdateOnly = false; } } else if(intent.getAction().equals(STEPLEVELUP)) { stepLevel(false); } else if(intent.getAction().equals(STEPLEVELDOWN)) { stepLevel(true); } else if(intent.getAction().equals(SWITCHAUTOMODE)) { boolean on = intent.getBooleanExtra(SWITCHAUTOMODE, false); mLightSensor.monitor(on); mKeepSticky = on; } else if(intent.getAction().equals(SWITCHDIM)) { if(getDimMode()) mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE); else { mLightSensor.setFreezeLux(); mHandler.sendEmptyMessage(MSG_ENTER_DIMM); } } else if(intent.getAction().equals(SENSITIVECHANGE)) { mLightSensor.updateSensitive(); } else if(intent.getAction().equals(ALARMCHANGE)) { mAlarmUtil.update(); } else if(intent.getAction().equals(ALARMMODE)) { if(!mAlarmUtil.nowToDim()) mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE); else { mLightSensor.setFreezeLux(); mHandler.sendEmptyMessage(MSG_ENTER_DIMM); } mAlarmUtil.update(); } else if(intent.getAction().equals(BOOT)) { if(!mKeepSticky) trySuicide(); } } // Only tf700t: If killed, next launch will NOT result in Activity/Service OnCreate. if(android.os.Build.DEVICE.equalsIgnoreCase("tf700t")) return START_STICKY; // Log.e(Dimmer.TAG, "onStartCommand(): " + lastLevel); // return Prefs.isAutoMode() ? START_STICKY : (lastLevel>500 ? START_NOT_STICKY : START_STICKY); return mKeepSticky ? START_STICKY : (lastLevel>500 ? START_NOT_STICKY : START_STICKY); // return START_STICKY; //sticky for continuous alive } private void adjustLevel(int i, boolean setBrightness, boolean postNotify) { if(postNotify) mIsPaused = false; if(i > 500) { if(i > 10*Prefs.getNotify(Prefs.PREF_NOTIFY_UPPER)) removeNotification(); else { if(postNotify) postNotification(i/10, false); } setDimMode(false); } else { if(postNotify) postNotification(i/10, true); setDimMode(true); } if(setBrightness) triggerActingSession(); mMask.adjustLevel(i, setBrightness); } public void resetLevel(boolean restoreBrighnessState, boolean removeNotification) { Log.e(Dimmer.TAG, "resetLevel() lastLevel: " + lastLevel); mIsPaused = !removeNotification; if(restoreBrighnessState) { triggerActingSession(); BrightnessUtil.restoreState(); } int currentBrightness = BrightnessUtil.getBrightness(); lastLevel = (int)(((float)currentBrightness)/255*500 + 500); mMask.removeMask(); boolean needSuicide = true; if(removeNotification) removeNotification(); else { postNotification(lastLevel/10, false); needSuicide = false; } setDimMode(false); sendBroadcast(new Intent(Dimmer.REFRESH_INDEX)); Dimmer.collectState = false; if(!mKeepSticky && needSuicide) trySuicide(); } public void stepLevel(boolean darker) { Log.e(Dimmer.TAG, "stepLevel() lastLevel: " + lastLevel + ", darker=" + darker); int step = 10*Prefs.getNotify(Prefs.PREF_NOTIFY_STEP); int lowerbound = 10*Prefs.getNotify(Prefs.PREF_NOTIFY_LOWER); int upperbound = 10*Prefs.getNotify(Prefs.PREF_NOTIFY_UPPER); if(darker) lastLevel -= step; else lastLevel += step; if(lastLevel > upperbound) lastLevel = upperbound; if(lastLevel < lowerbound) lastLevel = lowerbound; if(lastLevel >= 500) // if > 50, need call Mask.maskBrightness to set screenBrightness adjustLevel(lastLevel, false, false); adjustLevel(lastLevel, true, true); if(lastLevel < 500) { mLightSensor.setFreezeLux(); Prefs.setFavorMaskValue(lastLevel); } sendBroadcast(new Intent(Dimmer.REFRESH_INDEX)); } Handler mHandler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case MSG_RESET_LEVEL: resetLevel(false, true); break; case MSG_RESET_LEVEL_RESTORE: resetLevel(true, true); break; case MSG_RESET_LEVEL_RESTORE_KEEP_NOTIFY: resetLevel(true, false); break; case MSG_RESET_ACTING: mActing = false; break; case MSG_ENTER_DIMM: mMask.removeMask(); Dimmer.collectState = true; BrightnessUtil.collectState(); int favorvalue = Prefs.getFavorMaskValue(); adjustLevel(favorvalue, true, true); lastLevel = favorvalue; sendBroadcast(new Intent(Dimmer.REFRESH_INDEX)); showHint(); break; } } }; public void triggerActingSession() { mActing = true; mHandler.removeMessages(MSG_RESET_ACTING); mHandler.sendEmptyMessageDelayed(MSG_RESET_ACTING, 1000); } private void setDimMode(boolean dim) { mInDimMode = dim; mLightSensor.setDimState(dim); } private boolean getDimMode() { return mInDimMode; } private void trySuicide() { // Only tf700t: If killed, next launch will NOT result in Activity/Service OnCreate. if(android.os.Build.DEVICE.equalsIgnoreCase("tf700t")) return; if(SettingsActivity.showSettings || Dimmer.showMainApp) return; stopSelf(); Process.killProcess(Process.myPid()); } private void showHint() { try { String version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; if(version == null || !version.equalsIgnoreCase(Prefs.getAbout())) Toast.makeText(this, R.string.pref_widget_hint, Toast.LENGTH_LONG).show(); } catch (NameNotFoundException e) { e.printStackTrace(); } } }
true
true
public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null && intent.getAction() != null) { if(intent.getAction().equals(ADJUSTLEVEL)) { mHandler.removeMessages(MSG_RESET_ACTING); mActing = true; adjustLevel(intent.getIntExtra(ADJUSTLEVEL, DEFAULTLEVEL), false, false); } else if(intent.getAction().equals(FINISHLEVEL)) { int i = intent.getIntExtra(FINISHLEVEL, DEFAULTLEVEL); adjustLevel(intent.getIntExtra(FINISHLEVEL, DEFAULTLEVEL), true, true); lastLevel = i; if(lastLevel < 500) { mLightSensor.setFreezeLux(); Prefs.setFavorMaskValue(lastLevel); } // Log.e(Dimmer.TAG, "" + LuxUtil.dumpLuxLevel()); } else if(intent.getAction().equals(PAUSEFUNCTION)) { if(getDimMode()) mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE_KEEP_NOTIFY); else { mLightSensor.setFreezeLux(); mHandler.sendEmptyMessage(MSG_ENTER_DIMM); } } else if(intent.getAction().equals(RESETLEVEL)) { mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE); } else if(intent.getAction().equals(LAYOUTCHANGE)) { mLayoutChanged = true; if(mNotification.number == 1) { mLayoutUpdateOnly = true; postNotification(0, false); mLayoutUpdateOnly = false; } } else if(intent.getAction().equals(STEPLEVELUP)) { stepLevel(false); } else if(intent.getAction().equals(STEPLEVELDOWN)) { stepLevel(true); } else if(intent.getAction().equals(SWITCHAUTOMODE)) { boolean on = intent.getBooleanExtra(SWITCHAUTOMODE, false); mLightSensor.monitor(on); mKeepSticky = on; } else if(intent.getAction().equals(SWITCHDIM)) { if(getDimMode()) mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE); else { mLightSensor.setFreezeLux(); mHandler.sendEmptyMessage(MSG_ENTER_DIMM); } } else if(intent.getAction().equals(SENSITIVECHANGE)) { mLightSensor.updateSensitive(); } else if(intent.getAction().equals(ALARMCHANGE)) { mAlarmUtil.update(); } else if(intent.getAction().equals(ALARMMODE)) { if(!mAlarmUtil.nowToDim()) mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE); else { mLightSensor.setFreezeLux(); mHandler.sendEmptyMessage(MSG_ENTER_DIMM); } mAlarmUtil.update(); } else if(intent.getAction().equals(BOOT)) { if(!mKeepSticky) trySuicide(); } } // Only tf700t: If killed, next launch will NOT result in Activity/Service OnCreate. if(android.os.Build.DEVICE.equalsIgnoreCase("tf700t")) return START_STICKY; // Log.e(Dimmer.TAG, "onStartCommand(): " + lastLevel); // return Prefs.isAutoMode() ? START_STICKY : (lastLevel>500 ? START_NOT_STICKY : START_STICKY); return mKeepSticky ? START_STICKY : (lastLevel>500 ? START_NOT_STICKY : START_STICKY); // return START_STICKY; //sticky for continuous alive }
public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null && intent.getAction() != null) { if(intent.getAction().equals(ADJUSTLEVEL)) { mHandler.removeMessages(MSG_RESET_ACTING); mActing = true; adjustLevel(intent.getIntExtra(ADJUSTLEVEL, DEFAULTLEVEL), false, false); } else if(intent.getAction().equals(FINISHLEVEL)) { int i = intent.getIntExtra(FINISHLEVEL, DEFAULTLEVEL); adjustLevel(intent.getIntExtra(FINISHLEVEL, DEFAULTLEVEL), true, true); lastLevel = i; if(lastLevel < 500) { mLightSensor.setFreezeLux(); Prefs.setFavorMaskValue(lastLevel); } // Log.e(Dimmer.TAG, "" + LuxUtil.dumpLuxLevel()); } else if(intent.getAction().equals(PAUSEFUNCTION)) { if(getDimMode()) mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE_KEEP_NOTIFY); else { mLightSensor.setFreezeLux(); mHandler.sendEmptyMessage(MSG_ENTER_DIMM); } } else if(intent.getAction().equals(RESETLEVEL)) { mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE); } else if(intent.getAction().equals(LAYOUTCHANGE)) { mLayoutChanged = true; if(mNotification != null && mNotification.number == 1) { mLayoutUpdateOnly = true; postNotification(0, false); mLayoutUpdateOnly = false; } } else if(intent.getAction().equals(STEPLEVELUP)) { stepLevel(false); } else if(intent.getAction().equals(STEPLEVELDOWN)) { stepLevel(true); } else if(intent.getAction().equals(SWITCHAUTOMODE)) { boolean on = intent.getBooleanExtra(SWITCHAUTOMODE, false); mLightSensor.monitor(on); mKeepSticky = on; } else if(intent.getAction().equals(SWITCHDIM)) { if(getDimMode()) mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE); else { mLightSensor.setFreezeLux(); mHandler.sendEmptyMessage(MSG_ENTER_DIMM); } } else if(intent.getAction().equals(SENSITIVECHANGE)) { mLightSensor.updateSensitive(); } else if(intent.getAction().equals(ALARMCHANGE)) { mAlarmUtil.update(); } else if(intent.getAction().equals(ALARMMODE)) { if(!mAlarmUtil.nowToDim()) mHandler.sendEmptyMessage(MSG_RESET_LEVEL_RESTORE); else { mLightSensor.setFreezeLux(); mHandler.sendEmptyMessage(MSG_ENTER_DIMM); } mAlarmUtil.update(); } else if(intent.getAction().equals(BOOT)) { if(!mKeepSticky) trySuicide(); } } // Only tf700t: If killed, next launch will NOT result in Activity/Service OnCreate. if(android.os.Build.DEVICE.equalsIgnoreCase("tf700t")) return START_STICKY; // Log.e(Dimmer.TAG, "onStartCommand(): " + lastLevel); // return Prefs.isAutoMode() ? START_STICKY : (lastLevel>500 ? START_NOT_STICKY : START_STICKY); return mKeepSticky ? START_STICKY : (lastLevel>500 ? START_NOT_STICKY : START_STICKY); // return START_STICKY; //sticky for continuous alive }
diff --git a/src/main/java/org/uncertweb/aquacrop/AquaCropRunner.java b/src/main/java/org/uncertweb/aquacrop/AquaCropRunner.java index 4bfe85a..c9a3125 100644 --- a/src/main/java/org/uncertweb/aquacrop/AquaCropRunner.java +++ b/src/main/java/org/uncertweb/aquacrop/AquaCropRunner.java @@ -1,188 +1,195 @@ package org.uncertweb.aquacrop; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.Reader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.uncertweb.aquacrop.data.Output; import org.uncertweb.aquacrop.data.Project; import org.uncertweb.io.StreamGobbler; /** * Okay... * * The AquaCrop plug-in program has no UI, but creates an application window when it runs * (containing nothing, disappears upon program termination). * * Therefore running the plug-in program with Wine results in the following: * - Application tried to create a window, but no driver could be loaded. * - Make sure that your X server is running and that $DISPLAY is set correctly. * * As we want to run the program behind a web service interface, on a server somewhere, which * may or may not have X server running or a display, this poses an issue! * * The solution is Xvfb. * * The xvfb-run script creates... * * * * @author Richard Jones * */ public class AquaCropRunner { private final Logger logger = LoggerFactory.getLogger(AquaCropRunner.class); private String basePath; private String prefixCommand; private String basePathOverride; public AquaCropRunner(String basePath) { this.basePath = basePath; } /** * * * * @param basePath * @param prefixCommand */ public AquaCropRunner(String basePath, String prefixCommand, String basePathOverride) { this(basePath); this.prefixCommand = prefixCommand; this.basePathOverride = basePathOverride; } public Output run(Project project) throws AquaCropException { // generate an id final String runId = String.valueOf(System.currentTimeMillis()); // serialize project and run try { // this will create all data files logger.debug("Serializing project."); AquaCropSerializer.serializeProject(project, basePath, basePathOverride, runId); // get runtime - logger.debug("Getting runtime"); + logger.debug("Getting runtime."); Runtime runtime = Runtime.getRuntime(); // for monitoring and reading File outputFile = new File(basePath, "ACsaV31plus/OUTP/" + runId + "PRO.OUT"); // run program try { // start aquacrop process logger.debug("Starting process."); Process process = runtime.exec((prefixCommand != null ? prefixCommand + " " : "") + basePath + "/ACsaV31plus/ACsaV31plus.exe"); // consume streams StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream()); StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream()); errorGobbler.start(); outputGobbler.start(); // wait for process // we could be waiting forever if there's been an error... - logger.debug("Waiting for process to end..."); - process.waitFor(); +// boolean done = false; +// while (!done) { +// if (outputFile.exists() && outputFile.length() >= 512) { +// done = true; +// process.destroy(); // force required if error +// } +// } + logger.debug("Waiting for process to end."); + process.waitFor(); } catch (IOException e) { throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage()); } catch (InterruptedException e) { throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage()); } // parse output - logger.debug("Process finished, parsing output."); + logger.debug("Process finished, parsing output..."); FileReader reader = new FileReader(outputFile); Output output = AquaCropRunner.deserializeOutput(reader); reader.close(); // remove output file logger.debug("Removing output file."); outputFile.delete(); if (output == null) { // must be a problem running AquaCrop, but unfortunately it only gives error messages in dialogs! String message = "Couldn't parse AquaCrop empty output, parameters may be invalid."; logger.error(message); throw new AquaCropException(message); } else { logger.debug("Parsed output successfully."); return output; } } catch (IOException e) { // will be from creating the project file, or reading the output file String message = "Error reading input/output files: " + e.getMessage(); logger.error(message); throw new AquaCropException(message); } finally { // clean up input files File dataDir = new File(basePath, "AquaCrop/DATA/"); for (File dataFile : dataDir.listFiles(new FilenameFilter() { public boolean accept(File arg0, String arg1) { return (arg1.startsWith(runId)); } })) { dataFile.delete(); } new File(basePath, "ACsaV31plus/LIST/" + runId + ".PRO").delete(); } } private static Output deserializeOutput(Reader reader) throws FileNotFoundException, IOException { BufferedReader bufReader = new BufferedReader(reader); bufReader.readLine(); // skip first line containing aquacrop version, creation date bufReader.readLine(); // skip following empty line bufReader.readLine(); // skip column headings bufReader.readLine(); // skip column headings units String line; while ((line = bufReader.readLine()) != null && line.length() > 0) { // could be blank line at bottom // split on whitespace String[] tokens = line.trim().split("\\s+"); // totals is all we want if (tokens[0].startsWith("Tot")) { // parse results double rain = Double.parseDouble(tokens[4]); double eto = Double.parseDouble(tokens[5]); double gdd = Double.parseDouble(tokens[6]); double co2 = Double.parseDouble(tokens[7]); double irri = Double.parseDouble(tokens[8]); double infilt = Double.parseDouble(tokens[9]); double e = Double.parseDouble(tokens[10]); double eEx = Double.parseDouble(tokens[11]); double tr = Double.parseDouble(tokens[12]); double trTrx = Double.parseDouble(tokens[13]); double drain = Double.parseDouble(tokens[14]); double bioMass = Double.parseDouble(tokens[15]); double brW = Double.parseDouble(tokens[16]); double brWsf = Double.parseDouble(tokens[17]); double wPetB = Double.parseDouble(tokens[18]); double hi = Double.parseDouble(tokens[19]); double yield = Double.parseDouble(tokens[20]); double wPetY = Double.parseDouble(tokens[21]); // and return return new Output(rain, eto, gdd, co2, irri, infilt, e, eEx, tr, trTrx, drain, bioMass, brW, brWsf, wPetB, hi, yield, wPetY); } } return null; } }
false
true
public Output run(Project project) throws AquaCropException { // generate an id final String runId = String.valueOf(System.currentTimeMillis()); // serialize project and run try { // this will create all data files logger.debug("Serializing project."); AquaCropSerializer.serializeProject(project, basePath, basePathOverride, runId); // get runtime logger.debug("Getting runtime"); Runtime runtime = Runtime.getRuntime(); // for monitoring and reading File outputFile = new File(basePath, "ACsaV31plus/OUTP/" + runId + "PRO.OUT"); // run program try { // start aquacrop process logger.debug("Starting process."); Process process = runtime.exec((prefixCommand != null ? prefixCommand + " " : "") + basePath + "/ACsaV31plus/ACsaV31plus.exe"); // consume streams StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream()); StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream()); errorGobbler.start(); outputGobbler.start(); // wait for process // we could be waiting forever if there's been an error... logger.debug("Waiting for process to end..."); process.waitFor(); } catch (IOException e) { throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage()); } catch (InterruptedException e) { throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage()); } // parse output logger.debug("Process finished, parsing output."); FileReader reader = new FileReader(outputFile); Output output = AquaCropRunner.deserializeOutput(reader); reader.close(); // remove output file logger.debug("Removing output file."); outputFile.delete(); if (output == null) { // must be a problem running AquaCrop, but unfortunately it only gives error messages in dialogs! String message = "Couldn't parse AquaCrop empty output, parameters may be invalid."; logger.error(message); throw new AquaCropException(message); } else { logger.debug("Parsed output successfully."); return output; } } catch (IOException e) { // will be from creating the project file, or reading the output file String message = "Error reading input/output files: " + e.getMessage(); logger.error(message); throw new AquaCropException(message); } finally { // clean up input files File dataDir = new File(basePath, "AquaCrop/DATA/"); for (File dataFile : dataDir.listFiles(new FilenameFilter() { public boolean accept(File arg0, String arg1) { return (arg1.startsWith(runId)); } })) { dataFile.delete(); } new File(basePath, "ACsaV31plus/LIST/" + runId + ".PRO").delete(); } }
public Output run(Project project) throws AquaCropException { // generate an id final String runId = String.valueOf(System.currentTimeMillis()); // serialize project and run try { // this will create all data files logger.debug("Serializing project."); AquaCropSerializer.serializeProject(project, basePath, basePathOverride, runId); // get runtime logger.debug("Getting runtime."); Runtime runtime = Runtime.getRuntime(); // for monitoring and reading File outputFile = new File(basePath, "ACsaV31plus/OUTP/" + runId + "PRO.OUT"); // run program try { // start aquacrop process logger.debug("Starting process."); Process process = runtime.exec((prefixCommand != null ? prefixCommand + " " : "") + basePath + "/ACsaV31plus/ACsaV31plus.exe"); // consume streams StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream()); StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream()); errorGobbler.start(); outputGobbler.start(); // wait for process // we could be waiting forever if there's been an error... // boolean done = false; // while (!done) { // if (outputFile.exists() && outputFile.length() >= 512) { // done = true; // process.destroy(); // force required if error // } // } logger.debug("Waiting for process to end."); process.waitFor(); } catch (IOException e) { throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage()); } catch (InterruptedException e) { throw new AquaCropException("Couldn't run AquaCrop: " + e.getMessage()); } // parse output logger.debug("Process finished, parsing output..."); FileReader reader = new FileReader(outputFile); Output output = AquaCropRunner.deserializeOutput(reader); reader.close(); // remove output file logger.debug("Removing output file."); outputFile.delete(); if (output == null) { // must be a problem running AquaCrop, but unfortunately it only gives error messages in dialogs! String message = "Couldn't parse AquaCrop empty output, parameters may be invalid."; logger.error(message); throw new AquaCropException(message); } else { logger.debug("Parsed output successfully."); return output; } } catch (IOException e) { // will be from creating the project file, or reading the output file String message = "Error reading input/output files: " + e.getMessage(); logger.error(message); throw new AquaCropException(message); } finally { // clean up input files File dataDir = new File(basePath, "AquaCrop/DATA/"); for (File dataFile : dataDir.listFiles(new FilenameFilter() { public boolean accept(File arg0, String arg1) { return (arg1.startsWith(runId)); } })) { dataFile.delete(); } new File(basePath, "ACsaV31plus/LIST/" + runId + ".PRO").delete(); } }
diff --git a/src/org/apache/sandesha2/msgprocessors/CreateSeqMsgProcessor.java b/src/org/apache/sandesha2/msgprocessors/CreateSeqMsgProcessor.java index 45c45f2e..8191a4fe 100644 --- a/src/org/apache/sandesha2/msgprocessors/CreateSeqMsgProcessor.java +++ b/src/org/apache/sandesha2/msgprocessors/CreateSeqMsgProcessor.java @@ -1,356 +1,358 @@ /* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package org.apache.sandesha2.msgprocessors; import java.util.Collection; import org.apache.axiom.om.OMElement; import org.apache.axiom.soap.SOAP11Constants; import org.apache.axiom.soap.SOAP12Constants; import org.apache.axis2.AxisFault; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.OperationContext; import org.apache.axis2.engine.AxisEngine; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.sandesha2.RMMsgContext; import org.apache.sandesha2.Sandesha2Constants; import org.apache.sandesha2.SandeshaException; import org.apache.sandesha2.client.SandeshaClientConstants; import org.apache.sandesha2.client.SandeshaListener; import org.apache.sandesha2.i18n.SandeshaMessageHelper; import org.apache.sandesha2.i18n.SandeshaMessageKeys; import org.apache.sandesha2.security.SecurityManager; import org.apache.sandesha2.security.SecurityToken; import org.apache.sandesha2.storage.StorageManager; import org.apache.sandesha2.storage.beanmanagers.RMSBeanMgr; import org.apache.sandesha2.storage.beans.RMDBean; import org.apache.sandesha2.storage.beans.RMSBean; import org.apache.sandesha2.util.FaultManager; import org.apache.sandesha2.util.MsgInitializer; import org.apache.sandesha2.util.RMMsgCreator; import org.apache.sandesha2.util.RangeString; import org.apache.sandesha2.util.SandeshaUtil; import org.apache.sandesha2.util.SequenceManager; import org.apache.sandesha2.util.TerminateManager; import org.apache.sandesha2.wsrm.Accept; import org.apache.sandesha2.wsrm.CreateSequence; import org.apache.sandesha2.wsrm.CreateSequenceResponse; import org.apache.sandesha2.wsrm.Endpoint; import org.apache.sandesha2.wsrm.SequenceOffer; /** * Responsible for processing an incoming Create Sequence message. */ public class CreateSeqMsgProcessor implements MsgProcessor { private static final Log log = LogFactory.getLog(CreateSeqMsgProcessor.class); public boolean processInMessage(RMMsgContext createSeqRMMsg) throws AxisFault { if (log.isDebugEnabled()) log.debug("Enter: CreateSeqMsgProcessor::processInMessage"); try { CreateSequence createSeqPart = (CreateSequence) createSeqRMMsg .getMessagePart(Sandesha2Constants.MessageParts.CREATE_SEQ); if (createSeqPart == null) { if (log.isDebugEnabled()) log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noCreateSeqParts)); FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noCreateSeqParts), new Exception()); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } MessageContext createSeqMsg = createSeqRMMsg.getMessageContext(); ConfigurationContext context = createSeqMsg.getConfigurationContext(); StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(context, context.getAxisConfiguration()); // If the inbound CreateSequence includes a SecurityTokenReference then // ask the security manager to resolve that to a token for us. We also // check that the Create was secured using the token. SecurityManager secManager = SandeshaUtil.getSecurityManager(context); OMElement theSTR = createSeqPart.getSecurityTokenReference(); SecurityToken token = null; if(theSTR != null) { MessageContext msgcontext = createSeqRMMsg.getMessageContext(); token = secManager.getSecurityToken(theSTR, msgcontext); // The create must be the body part of this message, so we check the // security of that element. OMElement body = msgcontext.getEnvelope().getBody(); secManager.checkProofOfPossession(token, body, msgcontext); } MessageContext outMessage = null; // Create the new sequence id, as well as establishing the beans that handle the // sequence state. RMDBean rmdBean = SequenceManager.setupNewSequence(createSeqRMMsg, storageManager, secManager, token); RMMsgContext createSeqResponse = RMMsgCreator.createCreateSeqResponseMsg(createSeqRMMsg, rmdBean); outMessage = createSeqResponse.getMessageContext(); + // Set a message ID for this Create Sequence Response message + outMessage.setMessageID(SandeshaUtil.getUUID()); createSeqResponse.setFlow(MessageContext.OUT_FLOW); // for making sure that this won't be processed again createSeqResponse.setProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE, "true"); CreateSequenceResponse createSeqResPart = (CreateSequenceResponse) createSeqResponse .getMessagePart(Sandesha2Constants.MessageParts.CREATE_SEQ_RESPONSE); // OFFER PROCESSING SequenceOffer offer = createSeqPart.getSequenceOffer(); if (offer != null) { Accept accept = createSeqResPart.getAccept(); if (accept == null) { if (log.isDebugEnabled()) log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noAcceptPart)); FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noAcceptPart), new Exception()); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } // offered seq id String offeredSequenceID = offer.getIdentifer().getIdentifier(); boolean offerEcepted = offerAccepted(offeredSequenceID, context, createSeqRMMsg, storageManager); if (offerEcepted) { // Setting the CreateSequence table entry for the outgoing // side. RMSBean rMSBean = new RMSBean(); rMSBean.setSequenceID(offeredSequenceID); String outgoingSideInternalSequenceId = SandeshaUtil .getOutgoingSideInternalSequenceID(rmdBean.getSequenceID()); rMSBean.setInternalSequenceID(outgoingSideInternalSequenceId); // this is a dummy value rMSBean.setCreateSeqMsgID(SandeshaUtil.getUUID()); rMSBean.setToEPR(rmdBean.getToEPR()); rMSBean.setAcksToEPR(rmdBean.getToEPR()); // The acks need to flow back into this endpoint rMSBean.setReplyToEPR(rmdBean.getReplyToEPR()); rMSBean.setLastActivatedTime(System.currentTimeMillis()); rMSBean.setRMVersion(rmdBean.getRMVersion()); rMSBean.setClientCompletedMessages(new RangeString()); // Setting sequence properties for the outgoing sequence. // Only will be used by the server side response path. Will // be wasted properties for the client side. Endpoint endpoint = offer.getEndpoint(); if (endpoint!=null) { // setting the OfferedEndpoint rMSBean.setOfferedEndPoint(endpoint.getEPR().getAddress()); } RMSBeanMgr rmsBeanMgr = storageManager.getRMSBeanMgr(); // Store the inbound token (if any) with the new sequence rMSBean.setSecurityTokenData(rmdBean.getSecurityTokenData()); // If this new sequence has anonymous acksTo, then we must poll for the acks // If the inbound sequence is targetted at the WSRM anonymous URI, we need to start // polling for this sequence. String acksTo = rMSBean.getAcksToEPR(); EndpointReference reference = new EndpointReference(acksTo); if ((acksTo == null || reference.hasAnonymousAddress()) && Sandesha2Constants.SPEC_VERSIONS.v1_1.equals(createSeqRMMsg.getRMSpecVersion())) { rMSBean.setPollingMode(true); } rmsBeanMgr.insert(rMSBean); SandeshaUtil.startWorkersForSequence(context, rMSBean); } else { // removing the accept part. createSeqResPart.setAccept(null); createSeqResponse.addSOAPEnvelope(); } } //TODO add createSequenceResponse message as the referenceMessage to the RMDBean. outMessage.setResponseWritten(true); rmdBean.setLastActivatedTime(System.currentTimeMillis()); // If the inbound sequence is targetted at the anonymous URI, we need to start // polling for this sequence. EndpointReference toEPR = createSeqMsg.getTo(); if (toEPR.hasAnonymousAddress()) { if (Sandesha2Constants.SPEC_VERSIONS.v1_1.equals(createSeqRMMsg.getRMSpecVersion())) { rmdBean.setPollingMode(true); } } storageManager.getRMDBeanMgr().update(rmdBean); SandeshaUtil.startWorkersForSequence(context, rmdBean); AxisEngine engine = new AxisEngine(context); try{ engine.send(outMessage); } catch(AxisFault e){ FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.couldNotSendCreateSeqResponse, SandeshaUtil.getStackTraceFromException(e)), e); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } EndpointReference replyTo = createSeqMsg.getReplyTo(); if(replyTo == null || replyTo.hasAnonymousAddress()) { createSeqMsg.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "true"); } else { createSeqMsg.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "false"); } // SequencePropertyBean findBean = new SequencePropertyBean (); // findBean.setName (Sandesha2Constants.SequenceProperties.TERMINATE_ON_CREATE_SEQUENCE); // findBean.setValue(createSeqMsg.getTo().getAddress()); //if toAddress is RMAnon we may need to terminate the request side sequence here. if (toEPR.hasAnonymousAddress()) { RMSBean findBean = new RMSBean (); findBean.setReplyToEPR(toEPR.getAddress()); findBean.setTerminationPauserForCS(true); //TODO recheck RMSBean rmsBean = storageManager.getRMSBeanMgr().findUnique(findBean); if (rmsBean!=null) { //AckManager hs not done the termination. Do the termination here. MessageContext requestSideRefMessage = storageManager.retrieveMessageContext(rmsBean.getReferenceMessageStoreKey(),context); if (requestSideRefMessage==null) { FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.referencedMessageNotFound, rmsBean.getInternalSequenceID()), new Exception()); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } RMMsgContext requestSideRefRMMessage = MsgInitializer.initializeMessage(requestSideRefMessage); TerminateManager.addTerminateSequenceMessage(requestSideRefRMMessage, rmsBean.getInternalSequenceID(), rmsBean.getSequenceID(), storageManager); } } createSeqRMMsg.pause(); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Caught an exception processing CreateSequence message", e); // Does the message context already contain a fault ? // If it doesn't then we can add the CreateSequenceRefusedFault. if (createSeqRMMsg.getMessageContext().getProperty(SOAP12Constants.SOAP_FAULT_CODE_LOCAL_NAME) == null && createSeqRMMsg.getMessageContext().getProperty(SOAP11Constants.SOAP_FAULT_CODE_LOCAL_NAME) == null) { // Add the fault details to the message FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaUtil.getStackTraceFromException(e), e); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } // If we are SOAP12 and we have already processed the fault - rethrow the exception if (createSeqRMMsg.getMessageContext().getProperty(SOAP12Constants.SOAP_FAULT_CODE_LOCAL_NAME) != null) { // throw the original exception if (e instanceof AxisFault) throw (AxisFault)e; throw new SandeshaException(e); } } if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.TRUE); return true; } private boolean offerAccepted(String sequenceId, ConfigurationContext configCtx, RMMsgContext createSeqRMMsg, StorageManager storageManager) throws SandeshaException { if (log.isDebugEnabled()) log.debug("Enter: CreateSeqMsgProcessor::offerAccepted, " + sequenceId); if ("".equals(sequenceId)) { if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::offerAccepted, " + false); return false; } RMSBeanMgr createSeqMgr = storageManager.getRMSBeanMgr(); RMSBean createSeqFindBean = new RMSBean(); createSeqFindBean.setSequenceID(sequenceId); Collection arr = createSeqMgr.find(createSeqFindBean); if (arr.size() > 0) { if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::offerAccepted, " + false); return false; } if (sequenceId.length() <= 1) { if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::offerAccepted, " + false); return false; // Single character offers are NOT accepted. } if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::offerAccepted, " + true); return true; } public boolean processOutMessage(RMMsgContext rmMsgCtx) { if (log.isDebugEnabled()) log.debug("Enter: CreateSeqMsgProcessor::processOutMessage"); MessageContext msgCtx = rmMsgCtx.getMessageContext(); // adding the SANDESHA_LISTENER SandeshaListener faultCallback = (SandeshaListener) msgCtx.getOptions().getProperty( SandeshaClientConstants.SANDESHA_LISTENER); if (faultCallback != null) { OperationContext operationContext = msgCtx.getOperationContext(); if (operationContext != null) { operationContext.setProperty(SandeshaClientConstants.SANDESHA_LISTENER, faultCallback); } } if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processOutMessage " + Boolean.FALSE); return false; } }
true
true
public boolean processInMessage(RMMsgContext createSeqRMMsg) throws AxisFault { if (log.isDebugEnabled()) log.debug("Enter: CreateSeqMsgProcessor::processInMessage"); try { CreateSequence createSeqPart = (CreateSequence) createSeqRMMsg .getMessagePart(Sandesha2Constants.MessageParts.CREATE_SEQ); if (createSeqPart == null) { if (log.isDebugEnabled()) log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noCreateSeqParts)); FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noCreateSeqParts), new Exception()); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } MessageContext createSeqMsg = createSeqRMMsg.getMessageContext(); ConfigurationContext context = createSeqMsg.getConfigurationContext(); StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(context, context.getAxisConfiguration()); // If the inbound CreateSequence includes a SecurityTokenReference then // ask the security manager to resolve that to a token for us. We also // check that the Create was secured using the token. SecurityManager secManager = SandeshaUtil.getSecurityManager(context); OMElement theSTR = createSeqPart.getSecurityTokenReference(); SecurityToken token = null; if(theSTR != null) { MessageContext msgcontext = createSeqRMMsg.getMessageContext(); token = secManager.getSecurityToken(theSTR, msgcontext); // The create must be the body part of this message, so we check the // security of that element. OMElement body = msgcontext.getEnvelope().getBody(); secManager.checkProofOfPossession(token, body, msgcontext); } MessageContext outMessage = null; // Create the new sequence id, as well as establishing the beans that handle the // sequence state. RMDBean rmdBean = SequenceManager.setupNewSequence(createSeqRMMsg, storageManager, secManager, token); RMMsgContext createSeqResponse = RMMsgCreator.createCreateSeqResponseMsg(createSeqRMMsg, rmdBean); outMessage = createSeqResponse.getMessageContext(); createSeqResponse.setFlow(MessageContext.OUT_FLOW); // for making sure that this won't be processed again createSeqResponse.setProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE, "true"); CreateSequenceResponse createSeqResPart = (CreateSequenceResponse) createSeqResponse .getMessagePart(Sandesha2Constants.MessageParts.CREATE_SEQ_RESPONSE); // OFFER PROCESSING SequenceOffer offer = createSeqPart.getSequenceOffer(); if (offer != null) { Accept accept = createSeqResPart.getAccept(); if (accept == null) { if (log.isDebugEnabled()) log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noAcceptPart)); FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noAcceptPart), new Exception()); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } // offered seq id String offeredSequenceID = offer.getIdentifer().getIdentifier(); boolean offerEcepted = offerAccepted(offeredSequenceID, context, createSeqRMMsg, storageManager); if (offerEcepted) { // Setting the CreateSequence table entry for the outgoing // side. RMSBean rMSBean = new RMSBean(); rMSBean.setSequenceID(offeredSequenceID); String outgoingSideInternalSequenceId = SandeshaUtil .getOutgoingSideInternalSequenceID(rmdBean.getSequenceID()); rMSBean.setInternalSequenceID(outgoingSideInternalSequenceId); // this is a dummy value rMSBean.setCreateSeqMsgID(SandeshaUtil.getUUID()); rMSBean.setToEPR(rmdBean.getToEPR()); rMSBean.setAcksToEPR(rmdBean.getToEPR()); // The acks need to flow back into this endpoint rMSBean.setReplyToEPR(rmdBean.getReplyToEPR()); rMSBean.setLastActivatedTime(System.currentTimeMillis()); rMSBean.setRMVersion(rmdBean.getRMVersion()); rMSBean.setClientCompletedMessages(new RangeString()); // Setting sequence properties for the outgoing sequence. // Only will be used by the server side response path. Will // be wasted properties for the client side. Endpoint endpoint = offer.getEndpoint(); if (endpoint!=null) { // setting the OfferedEndpoint rMSBean.setOfferedEndPoint(endpoint.getEPR().getAddress()); } RMSBeanMgr rmsBeanMgr = storageManager.getRMSBeanMgr(); // Store the inbound token (if any) with the new sequence rMSBean.setSecurityTokenData(rmdBean.getSecurityTokenData()); // If this new sequence has anonymous acksTo, then we must poll for the acks // If the inbound sequence is targetted at the WSRM anonymous URI, we need to start // polling for this sequence. String acksTo = rMSBean.getAcksToEPR(); EndpointReference reference = new EndpointReference(acksTo); if ((acksTo == null || reference.hasAnonymousAddress()) && Sandesha2Constants.SPEC_VERSIONS.v1_1.equals(createSeqRMMsg.getRMSpecVersion())) { rMSBean.setPollingMode(true); } rmsBeanMgr.insert(rMSBean); SandeshaUtil.startWorkersForSequence(context, rMSBean); } else { // removing the accept part. createSeqResPart.setAccept(null); createSeqResponse.addSOAPEnvelope(); } } //TODO add createSequenceResponse message as the referenceMessage to the RMDBean. outMessage.setResponseWritten(true); rmdBean.setLastActivatedTime(System.currentTimeMillis()); // If the inbound sequence is targetted at the anonymous URI, we need to start // polling for this sequence. EndpointReference toEPR = createSeqMsg.getTo(); if (toEPR.hasAnonymousAddress()) { if (Sandesha2Constants.SPEC_VERSIONS.v1_1.equals(createSeqRMMsg.getRMSpecVersion())) { rmdBean.setPollingMode(true); } } storageManager.getRMDBeanMgr().update(rmdBean); SandeshaUtil.startWorkersForSequence(context, rmdBean); AxisEngine engine = new AxisEngine(context); try{ engine.send(outMessage); } catch(AxisFault e){ FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.couldNotSendCreateSeqResponse, SandeshaUtil.getStackTraceFromException(e)), e); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } EndpointReference replyTo = createSeqMsg.getReplyTo(); if(replyTo == null || replyTo.hasAnonymousAddress()) { createSeqMsg.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "true"); } else { createSeqMsg.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "false"); } // SequencePropertyBean findBean = new SequencePropertyBean (); // findBean.setName (Sandesha2Constants.SequenceProperties.TERMINATE_ON_CREATE_SEQUENCE); // findBean.setValue(createSeqMsg.getTo().getAddress()); //if toAddress is RMAnon we may need to terminate the request side sequence here. if (toEPR.hasAnonymousAddress()) { RMSBean findBean = new RMSBean (); findBean.setReplyToEPR(toEPR.getAddress()); findBean.setTerminationPauserForCS(true); //TODO recheck RMSBean rmsBean = storageManager.getRMSBeanMgr().findUnique(findBean); if (rmsBean!=null) { //AckManager hs not done the termination. Do the termination here. MessageContext requestSideRefMessage = storageManager.retrieveMessageContext(rmsBean.getReferenceMessageStoreKey(),context); if (requestSideRefMessage==null) { FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.referencedMessageNotFound, rmsBean.getInternalSequenceID()), new Exception()); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } RMMsgContext requestSideRefRMMessage = MsgInitializer.initializeMessage(requestSideRefMessage); TerminateManager.addTerminateSequenceMessage(requestSideRefRMMessage, rmsBean.getInternalSequenceID(), rmsBean.getSequenceID(), storageManager); } } createSeqRMMsg.pause(); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Caught an exception processing CreateSequence message", e); // Does the message context already contain a fault ? // If it doesn't then we can add the CreateSequenceRefusedFault. if (createSeqRMMsg.getMessageContext().getProperty(SOAP12Constants.SOAP_FAULT_CODE_LOCAL_NAME) == null && createSeqRMMsg.getMessageContext().getProperty(SOAP11Constants.SOAP_FAULT_CODE_LOCAL_NAME) == null) { // Add the fault details to the message FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaUtil.getStackTraceFromException(e), e); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } // If we are SOAP12 and we have already processed the fault - rethrow the exception if (createSeqRMMsg.getMessageContext().getProperty(SOAP12Constants.SOAP_FAULT_CODE_LOCAL_NAME) != null) { // throw the original exception if (e instanceof AxisFault) throw (AxisFault)e; throw new SandeshaException(e); } } if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.TRUE); return true; }
public boolean processInMessage(RMMsgContext createSeqRMMsg) throws AxisFault { if (log.isDebugEnabled()) log.debug("Enter: CreateSeqMsgProcessor::processInMessage"); try { CreateSequence createSeqPart = (CreateSequence) createSeqRMMsg .getMessagePart(Sandesha2Constants.MessageParts.CREATE_SEQ); if (createSeqPart == null) { if (log.isDebugEnabled()) log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noCreateSeqParts)); FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noCreateSeqParts), new Exception()); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } MessageContext createSeqMsg = createSeqRMMsg.getMessageContext(); ConfigurationContext context = createSeqMsg.getConfigurationContext(); StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(context, context.getAxisConfiguration()); // If the inbound CreateSequence includes a SecurityTokenReference then // ask the security manager to resolve that to a token for us. We also // check that the Create was secured using the token. SecurityManager secManager = SandeshaUtil.getSecurityManager(context); OMElement theSTR = createSeqPart.getSecurityTokenReference(); SecurityToken token = null; if(theSTR != null) { MessageContext msgcontext = createSeqRMMsg.getMessageContext(); token = secManager.getSecurityToken(theSTR, msgcontext); // The create must be the body part of this message, so we check the // security of that element. OMElement body = msgcontext.getEnvelope().getBody(); secManager.checkProofOfPossession(token, body, msgcontext); } MessageContext outMessage = null; // Create the new sequence id, as well as establishing the beans that handle the // sequence state. RMDBean rmdBean = SequenceManager.setupNewSequence(createSeqRMMsg, storageManager, secManager, token); RMMsgContext createSeqResponse = RMMsgCreator.createCreateSeqResponseMsg(createSeqRMMsg, rmdBean); outMessage = createSeqResponse.getMessageContext(); // Set a message ID for this Create Sequence Response message outMessage.setMessageID(SandeshaUtil.getUUID()); createSeqResponse.setFlow(MessageContext.OUT_FLOW); // for making sure that this won't be processed again createSeqResponse.setProperty(Sandesha2Constants.APPLICATION_PROCESSING_DONE, "true"); CreateSequenceResponse createSeqResPart = (CreateSequenceResponse) createSeqResponse .getMessagePart(Sandesha2Constants.MessageParts.CREATE_SEQ_RESPONSE); // OFFER PROCESSING SequenceOffer offer = createSeqPart.getSequenceOffer(); if (offer != null) { Accept accept = createSeqResPart.getAccept(); if (accept == null) { if (log.isDebugEnabled()) log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noAcceptPart)); FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noAcceptPart), new Exception()); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } // offered seq id String offeredSequenceID = offer.getIdentifer().getIdentifier(); boolean offerEcepted = offerAccepted(offeredSequenceID, context, createSeqRMMsg, storageManager); if (offerEcepted) { // Setting the CreateSequence table entry for the outgoing // side. RMSBean rMSBean = new RMSBean(); rMSBean.setSequenceID(offeredSequenceID); String outgoingSideInternalSequenceId = SandeshaUtil .getOutgoingSideInternalSequenceID(rmdBean.getSequenceID()); rMSBean.setInternalSequenceID(outgoingSideInternalSequenceId); // this is a dummy value rMSBean.setCreateSeqMsgID(SandeshaUtil.getUUID()); rMSBean.setToEPR(rmdBean.getToEPR()); rMSBean.setAcksToEPR(rmdBean.getToEPR()); // The acks need to flow back into this endpoint rMSBean.setReplyToEPR(rmdBean.getReplyToEPR()); rMSBean.setLastActivatedTime(System.currentTimeMillis()); rMSBean.setRMVersion(rmdBean.getRMVersion()); rMSBean.setClientCompletedMessages(new RangeString()); // Setting sequence properties for the outgoing sequence. // Only will be used by the server side response path. Will // be wasted properties for the client side. Endpoint endpoint = offer.getEndpoint(); if (endpoint!=null) { // setting the OfferedEndpoint rMSBean.setOfferedEndPoint(endpoint.getEPR().getAddress()); } RMSBeanMgr rmsBeanMgr = storageManager.getRMSBeanMgr(); // Store the inbound token (if any) with the new sequence rMSBean.setSecurityTokenData(rmdBean.getSecurityTokenData()); // If this new sequence has anonymous acksTo, then we must poll for the acks // If the inbound sequence is targetted at the WSRM anonymous URI, we need to start // polling for this sequence. String acksTo = rMSBean.getAcksToEPR(); EndpointReference reference = new EndpointReference(acksTo); if ((acksTo == null || reference.hasAnonymousAddress()) && Sandesha2Constants.SPEC_VERSIONS.v1_1.equals(createSeqRMMsg.getRMSpecVersion())) { rMSBean.setPollingMode(true); } rmsBeanMgr.insert(rMSBean); SandeshaUtil.startWorkersForSequence(context, rMSBean); } else { // removing the accept part. createSeqResPart.setAccept(null); createSeqResponse.addSOAPEnvelope(); } } //TODO add createSequenceResponse message as the referenceMessage to the RMDBean. outMessage.setResponseWritten(true); rmdBean.setLastActivatedTime(System.currentTimeMillis()); // If the inbound sequence is targetted at the anonymous URI, we need to start // polling for this sequence. EndpointReference toEPR = createSeqMsg.getTo(); if (toEPR.hasAnonymousAddress()) { if (Sandesha2Constants.SPEC_VERSIONS.v1_1.equals(createSeqRMMsg.getRMSpecVersion())) { rmdBean.setPollingMode(true); } } storageManager.getRMDBeanMgr().update(rmdBean); SandeshaUtil.startWorkersForSequence(context, rmdBean); AxisEngine engine = new AxisEngine(context); try{ engine.send(outMessage); } catch(AxisFault e){ FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.couldNotSendCreateSeqResponse, SandeshaUtil.getStackTraceFromException(e)), e); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } EndpointReference replyTo = createSeqMsg.getReplyTo(); if(replyTo == null || replyTo.hasAnonymousAddress()) { createSeqMsg.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "true"); } else { createSeqMsg.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "false"); } // SequencePropertyBean findBean = new SequencePropertyBean (); // findBean.setName (Sandesha2Constants.SequenceProperties.TERMINATE_ON_CREATE_SEQUENCE); // findBean.setValue(createSeqMsg.getTo().getAddress()); //if toAddress is RMAnon we may need to terminate the request side sequence here. if (toEPR.hasAnonymousAddress()) { RMSBean findBean = new RMSBean (); findBean.setReplyToEPR(toEPR.getAddress()); findBean.setTerminationPauserForCS(true); //TODO recheck RMSBean rmsBean = storageManager.getRMSBeanMgr().findUnique(findBean); if (rmsBean!=null) { //AckManager hs not done the termination. Do the termination here. MessageContext requestSideRefMessage = storageManager.retrieveMessageContext(rmsBean.getReferenceMessageStoreKey(),context); if (requestSideRefMessage==null) { FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaMessageHelper.getMessage(SandeshaMessageKeys.referencedMessageNotFound, rmsBean.getInternalSequenceID()), new Exception()); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } RMMsgContext requestSideRefRMMessage = MsgInitializer.initializeMessage(requestSideRefMessage); TerminateManager.addTerminateSequenceMessage(requestSideRefRMMessage, rmsBean.getInternalSequenceID(), rmsBean.getSequenceID(), storageManager); } } createSeqRMMsg.pause(); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Caught an exception processing CreateSequence message", e); // Does the message context already contain a fault ? // If it doesn't then we can add the CreateSequenceRefusedFault. if (createSeqRMMsg.getMessageContext().getProperty(SOAP12Constants.SOAP_FAULT_CODE_LOCAL_NAME) == null && createSeqRMMsg.getMessageContext().getProperty(SOAP11Constants.SOAP_FAULT_CODE_LOCAL_NAME) == null) { // Add the fault details to the message FaultManager.makeCreateSequenceRefusedFault(createSeqRMMsg, SandeshaUtil.getStackTraceFromException(e), e); // Return false if an Exception hasn't been thrown. if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.FALSE); return false; } // If we are SOAP12 and we have already processed the fault - rethrow the exception if (createSeqRMMsg.getMessageContext().getProperty(SOAP12Constants.SOAP_FAULT_CODE_LOCAL_NAME) != null) { // throw the original exception if (e instanceof AxisFault) throw (AxisFault)e; throw new SandeshaException(e); } } if (log.isDebugEnabled()) log.debug("Exit: CreateSeqMsgProcessor::processInMessage " + Boolean.TRUE); return true; }
diff --git a/src/main/java/org/cyclopsgroup/jmxterm/cmd/OpenCommand.java b/src/main/java/org/cyclopsgroup/jmxterm/cmd/OpenCommand.java index 52cd0d7..aa50f88 100644 --- a/src/main/java/org/cyclopsgroup/jmxterm/cmd/OpenCommand.java +++ b/src/main/java/org/cyclopsgroup/jmxterm/cmd/OpenCommand.java @@ -1,62 +1,62 @@ package org.cyclopsgroup.jmxterm.cmd; import java.io.IOException; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import org.apache.commons.lang.Validate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.cyclopsgroup.jcli.annotation.Argument; import org.cyclopsgroup.jcli.annotation.Cli; import org.cyclopsgroup.jmxterm.Command; import org.cyclopsgroup.jmxterm.Connection; import org.cyclopsgroup.jmxterm.Session; import org.cyclopsgroup.jmxterm.SyntaxUtils; @Cli( name = "open", description = "Open JMX session", note = "eg. open localhost:9991, or open jmx:service:..." ) public class OpenCommand extends Command { private static final Log LOG = LogFactory.getLog( OpenCommand.class ); private String url; public void execute( Session session ) throws IOException { if ( url == null ) { Connection con = session.getConnection(); if ( con == null ) { session.output.println( "Not connected" ); } else { session.output.println( String.format( "Connected to: expr=%s, id=%s, url=%s", con.getOriginalUrl(), con.getConnector().getConnectionId(), con.getUrl() ) ); } return; } - Validate.isTrue( session.getConnection() == null ); + Validate.isTrue( session.getConnection() == null, "Session is already opened" ); JMXServiceURL u = SyntaxUtils.getUrl( url ); JMXConnector connector = JMXConnectorFactory.connect( u ); session.setConnection( new Connection( connector, u, url ) ); LOG.info( "Connection to " + url + " is opened" ); } public final String getUrl() { return url; } @Argument public final void setUrl( String url ) { this.url = url; } }
true
true
public void execute( Session session ) throws IOException { if ( url == null ) { Connection con = session.getConnection(); if ( con == null ) { session.output.println( "Not connected" ); } else { session.output.println( String.format( "Connected to: expr=%s, id=%s, url=%s", con.getOriginalUrl(), con.getConnector().getConnectionId(), con.getUrl() ) ); } return; } Validate.isTrue( session.getConnection() == null ); JMXServiceURL u = SyntaxUtils.getUrl( url ); JMXConnector connector = JMXConnectorFactory.connect( u ); session.setConnection( new Connection( connector, u, url ) ); LOG.info( "Connection to " + url + " is opened" ); }
public void execute( Session session ) throws IOException { if ( url == null ) { Connection con = session.getConnection(); if ( con == null ) { session.output.println( "Not connected" ); } else { session.output.println( String.format( "Connected to: expr=%s, id=%s, url=%s", con.getOriginalUrl(), con.getConnector().getConnectionId(), con.getUrl() ) ); } return; } Validate.isTrue( session.getConnection() == null, "Session is already opened" ); JMXServiceURL u = SyntaxUtils.getUrl( url ); JMXConnector connector = JMXConnectorFactory.connect( u ); session.setConnection( new Connection( connector, u, url ) ); LOG.info( "Connection to " + url + " is opened" ); }
diff --git a/eclipse/plugins/net.sf.orcc.simulators/src/net/sf/orcc/simulators/SimulatorCli.java b/eclipse/plugins/net.sf.orcc.simulators/src/net/sf/orcc/simulators/SimulatorCli.java index d8a6d99ff..5b03d47a6 100644 --- a/eclipse/plugins/net.sf.orcc.simulators/src/net/sf/orcc/simulators/SimulatorCli.java +++ b/eclipse/plugins/net.sf.orcc.simulators/src/net/sf/orcc/simulators/SimulatorCli.java @@ -1,216 +1,218 @@ /* * Copyright (c) 2012, IETR/INSA of Rennes * 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 IETR/INSA of Rennes 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 net.sf.orcc.simulators; import static net.sf.orcc.OrccLaunchConstants.GOLDEN_REFERENCE; import static net.sf.orcc.OrccLaunchConstants.GOLDEN_REFERENCE_FILE; import static net.sf.orcc.OrccLaunchConstants.INPUT_STIMULUS; import static net.sf.orcc.OrccLaunchConstants.LOOP_NUMBER; import static net.sf.orcc.OrccLaunchConstants.NO_DISPLAY; import static net.sf.orcc.OrccLaunchConstants.PROJECT; import static net.sf.orcc.OrccLaunchConstants.SIMULATOR; import static net.sf.orcc.OrccLaunchConstants.XDF_FILE; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import net.sf.orcc.OrccException; import net.sf.orcc.util.OrccLogger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.UnrecognizedOptionException; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceDescription; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; /** * Command-line version of CAL simulator. * * @author Antoine Lorence * */ public class SimulatorCli implements IApplication { boolean isAutoBuildActivated; IWorkspace workspace; /** * Initilize */ public SimulatorCli() { workspace = ResourcesPlugin.getWorkspace(); } private void disableAutoBuild() throws CoreException { IWorkspaceDescription desc = workspace.getDescription(); if (desc.isAutoBuilding()) { isAutoBuildActivated = true; desc.setAutoBuilding(false); workspace.setDescription(desc); } } private void restoreAutoBuild() throws CoreException { if (isAutoBuildActivated) { IWorkspaceDescription desc = workspace.getDescription(); desc.setAutoBuilding(true); workspace.setDescription(desc); } } @Override public Object start(IApplicationContext context) throws Exception { Options clOptions = new Options(); Option opt; // Required command line arguments opt = new Option("p", "project", true, "Set the project from "); opt.setRequired(true); clOptions.addOption(opt); opt = new Option("i", "input", true, "Set the input stimulus file"); opt.setRequired(true); clOptions.addOption(opt); // Optional command line arguments clOptions.addOption("l", "loopsnumber", true, "Defines the number of times input stimulus will be read before " + "application stop. A negative value means infinite. " + "Default : 1 time."); clOptions.addOption("r", "golden_reference", true, "Reference file which will be " + "used to compare with decoded stream."); clOptions.addOption("n", "nodisplay", false, "Disable display initialization"); clOptions.addOption("d", "debug", false, "Launch simulator in debug mode"); clOptions.addOption("h", "help", false, "Print this help message"); try { Map<String, Object> simulatorOptions = new HashMap<String, Object>(); CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse( clOptions, (String[]) context.getArguments().get( IApplicationContext.APPLICATION_ARGS)); if (commandLine.hasOption('h')) { printUsage(clOptions, null); return IApplication.EXIT_RELAUNCH; } simulatorOptions.put(PROJECT, commandLine.getOptionValue('p')); simulatorOptions.put(INPUT_STIMULUS, commandLine.getOptionValue('i')); simulatorOptions.put(XDF_FILE, commandLine.getArgList().get(0)); simulatorOptions.put( LOOP_NUMBER, commandLine.getOptionValue('l', String.valueOf(Simulator.DEFAULT_NB_LOOPS))); if (commandLine.hasOption('n')) { simulatorOptions.put(NO_DISPLAY, true); } if (commandLine.hasOption('d')) { OrccLogger.setLevel(OrccLogger.DEBUG); } if (commandLine.hasOption("r")) { simulatorOptions.put(GOLDEN_REFERENCE, true); simulatorOptions.put(GOLDEN_REFERENCE_FILE, commandLine.getOptionValue("r")); } simulatorOptions.put(SIMULATOR, "Visitor interpreter and debugger"); try { disableAutoBuild(); SimulatorFactory.getInstance().runSimulator( new NullProgressMonitor(), "run", simulatorOptions); } catch (CoreException ce) { OrccLogger.severeln("Unable to set the workspace properties."); restoreAutoBuild(); return IApplication.EXIT_RELAUNCH; } catch (OrccException oe) { OrccLogger.severeln("Simulator has shut down"); restoreAutoBuild(); return IApplication.EXIT_RELAUNCH; + } finally { + restoreAutoBuild(); } // Simulator correctly shut down return IApplication.EXIT_OK; } catch (UnrecognizedOptionException uoe) { printUsage(clOptions, uoe.getLocalizedMessage()); } catch (ParseException pe) { printUsage(clOptions, pe.getLocalizedMessage()); } return IApplication.EXIT_RELAUNCH; } @Override public void stop() { } public void printUsage(Options options, String parserMsg) { String footer = ""; if (parserMsg != null && !parserMsg.isEmpty()) { footer = "\nMessage of the command line parser :\n" + parserMsg; } HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setWidth(80); helpFormatter .printHelp( "net.sf.orcc.simulators.cli [options] <qualified path of your top network>", "Valid options are :", options, footer); } }
true
true
public Object start(IApplicationContext context) throws Exception { Options clOptions = new Options(); Option opt; // Required command line arguments opt = new Option("p", "project", true, "Set the project from "); opt.setRequired(true); clOptions.addOption(opt); opt = new Option("i", "input", true, "Set the input stimulus file"); opt.setRequired(true); clOptions.addOption(opt); // Optional command line arguments clOptions.addOption("l", "loopsnumber", true, "Defines the number of times input stimulus will be read before " + "application stop. A negative value means infinite. " + "Default : 1 time."); clOptions.addOption("r", "golden_reference", true, "Reference file which will be " + "used to compare with decoded stream."); clOptions.addOption("n", "nodisplay", false, "Disable display initialization"); clOptions.addOption("d", "debug", false, "Launch simulator in debug mode"); clOptions.addOption("h", "help", false, "Print this help message"); try { Map<String, Object> simulatorOptions = new HashMap<String, Object>(); CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse( clOptions, (String[]) context.getArguments().get( IApplicationContext.APPLICATION_ARGS)); if (commandLine.hasOption('h')) { printUsage(clOptions, null); return IApplication.EXIT_RELAUNCH; } simulatorOptions.put(PROJECT, commandLine.getOptionValue('p')); simulatorOptions.put(INPUT_STIMULUS, commandLine.getOptionValue('i')); simulatorOptions.put(XDF_FILE, commandLine.getArgList().get(0)); simulatorOptions.put( LOOP_NUMBER, commandLine.getOptionValue('l', String.valueOf(Simulator.DEFAULT_NB_LOOPS))); if (commandLine.hasOption('n')) { simulatorOptions.put(NO_DISPLAY, true); } if (commandLine.hasOption('d')) { OrccLogger.setLevel(OrccLogger.DEBUG); } if (commandLine.hasOption("r")) { simulatorOptions.put(GOLDEN_REFERENCE, true); simulatorOptions.put(GOLDEN_REFERENCE_FILE, commandLine.getOptionValue("r")); } simulatorOptions.put(SIMULATOR, "Visitor interpreter and debugger"); try { disableAutoBuild(); SimulatorFactory.getInstance().runSimulator( new NullProgressMonitor(), "run", simulatorOptions); } catch (CoreException ce) { OrccLogger.severeln("Unable to set the workspace properties."); restoreAutoBuild(); return IApplication.EXIT_RELAUNCH; } catch (OrccException oe) { OrccLogger.severeln("Simulator has shut down"); restoreAutoBuild(); return IApplication.EXIT_RELAUNCH; } // Simulator correctly shut down return IApplication.EXIT_OK; } catch (UnrecognizedOptionException uoe) { printUsage(clOptions, uoe.getLocalizedMessage()); } catch (ParseException pe) { printUsage(clOptions, pe.getLocalizedMessage()); } return IApplication.EXIT_RELAUNCH; }
public Object start(IApplicationContext context) throws Exception { Options clOptions = new Options(); Option opt; // Required command line arguments opt = new Option("p", "project", true, "Set the project from "); opt.setRequired(true); clOptions.addOption(opt); opt = new Option("i", "input", true, "Set the input stimulus file"); opt.setRequired(true); clOptions.addOption(opt); // Optional command line arguments clOptions.addOption("l", "loopsnumber", true, "Defines the number of times input stimulus will be read before " + "application stop. A negative value means infinite. " + "Default : 1 time."); clOptions.addOption("r", "golden_reference", true, "Reference file which will be " + "used to compare with decoded stream."); clOptions.addOption("n", "nodisplay", false, "Disable display initialization"); clOptions.addOption("d", "debug", false, "Launch simulator in debug mode"); clOptions.addOption("h", "help", false, "Print this help message"); try { Map<String, Object> simulatorOptions = new HashMap<String, Object>(); CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse( clOptions, (String[]) context.getArguments().get( IApplicationContext.APPLICATION_ARGS)); if (commandLine.hasOption('h')) { printUsage(clOptions, null); return IApplication.EXIT_RELAUNCH; } simulatorOptions.put(PROJECT, commandLine.getOptionValue('p')); simulatorOptions.put(INPUT_STIMULUS, commandLine.getOptionValue('i')); simulatorOptions.put(XDF_FILE, commandLine.getArgList().get(0)); simulatorOptions.put( LOOP_NUMBER, commandLine.getOptionValue('l', String.valueOf(Simulator.DEFAULT_NB_LOOPS))); if (commandLine.hasOption('n')) { simulatorOptions.put(NO_DISPLAY, true); } if (commandLine.hasOption('d')) { OrccLogger.setLevel(OrccLogger.DEBUG); } if (commandLine.hasOption("r")) { simulatorOptions.put(GOLDEN_REFERENCE, true); simulatorOptions.put(GOLDEN_REFERENCE_FILE, commandLine.getOptionValue("r")); } simulatorOptions.put(SIMULATOR, "Visitor interpreter and debugger"); try { disableAutoBuild(); SimulatorFactory.getInstance().runSimulator( new NullProgressMonitor(), "run", simulatorOptions); } catch (CoreException ce) { OrccLogger.severeln("Unable to set the workspace properties."); restoreAutoBuild(); return IApplication.EXIT_RELAUNCH; } catch (OrccException oe) { OrccLogger.severeln("Simulator has shut down"); restoreAutoBuild(); return IApplication.EXIT_RELAUNCH; } finally { restoreAutoBuild(); } // Simulator correctly shut down return IApplication.EXIT_OK; } catch (UnrecognizedOptionException uoe) { printUsage(clOptions, uoe.getLocalizedMessage()); } catch (ParseException pe) { printUsage(clOptions, pe.getLocalizedMessage()); } return IApplication.EXIT_RELAUNCH; }
diff --git a/src/enderdom/eddie/tasks/bio/Task_IprscanLocal.java b/src/enderdom/eddie/tasks/bio/Task_IprscanLocal.java index 3e1b8f6..5223694 100644 --- a/src/enderdom/eddie/tasks/bio/Task_IprscanLocal.java +++ b/src/enderdom/eddie/tasks/bio/Task_IprscanLocal.java @@ -1,209 +1,207 @@ package enderdom.eddie.tasks.bio; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Properties; import java.util.Stack; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import enderdom.eddie.bio.factories.SequenceListFactory; import enderdom.eddie.bio.sequence.SequenceList; import enderdom.eddie.bio.sequence.SequenceObject; import enderdom.eddie.tasks.Checklist; import enderdom.eddie.tasks.TaskState; import enderdom.eddie.tasks.TaskXTwIO; import enderdom.eddie.tools.Tools_File; import enderdom.eddie.tools.Tools_String; import enderdom.eddie.tools.Tools_System; import enderdom.eddie.tools.Tools_Task; import enderdom.eddie.tools.bio.Tools_Fasta; import enderdom.eddie.ui.UI; /** * * @author Dominic Wood * * I wasn't originally going to make this, * but for some reason nobody ever makes programs * which let you stop-start, As such this just * auto-splits file and keeps track of the progress * with checklist, thus allowing you to close and * restart at will. Though iprscan doesn't drop resources * immediately when you close the process, it least * with python so I assume the same is true for java. * */ public class Task_IprscanLocal extends TaskXTwIO{ private String iprscanbin; private String params; SequenceList sequences; private int split; private long timestart; public Task_IprscanLocal(){ /* */ setCore(true); split = 1; params = "-cli -iprlookup -goterms -nocrc -format xml -altjobs"; this.setHelpHeader("Task to help automate local iprscan-ing"); } public void parseArgsSub(CommandLine cmd){ super.parseArgsSub(cmd); if(cmd.hasOption("bin"))iprscanbin=cmd.getOptionValue("iprscanbin"); if(cmd.hasOption("params"))params = cmd.getOptionValue("params"); if(cmd.hasOption("pf")){ File fie = new File(cmd.getOptionValue("pf")); if(fie.isFile()){ params = Tools_File.quickRead(fie, false); } else{ logger.error("Iprscan parameter file does not exist"); params = ""; } } if(cmd.hasOption("split")){ Integer i = Tools_String.parseString2Int(cmd.getOptionValue("split")); if(i !=null)split=i; else logger.error("Integer set with -split is not an integer"); } } public void parseOpts(Properties props){ if(iprscanbin == null){ iprscanbin = props.getProperty("IPRSCAN_BIN"); } logger.trace("Parse Options From props"); } public void buildOptions(){ super.buildOptions(); options.addOption(new Option("b", "bin", true, "Set executable for local iprscan, else will use property file location")); options.addOption(new Option("pa", "params", true, "Parameters if not using default")); options.addOption(new Option("pf", "paramsfile", true, "File containing the parameters, !will overwrite anything in -params")); options.addOption(new Option("s", "split", true, "Successively split file into this many sequences")); options.getOption("i").setDescription("Input sequence file fasta"); options.getOption("o").setDescription("Output directory"); options.removeOption("p"); options.removeOption("w"); options.removeOption("filetype"); } public void run(){ setCompleteState(TaskState.STARTED); logger.debug("Started running task @ "+Tools_System.getDateNow()); this.checklist = openChecklist(ui); if(input != null && output != null){ File in = new File(input); File out = new File(output); int total = 0; timestart = System.currentTimeMillis(); if(in.isFile() && out.isDirectory() && this.iprscanbin !=null){ try{ this.sequences = SequenceListFactory.getSequenceList(input); - int size = this.sequences.getNoOfSequences(); if(checklist.inRecovery()){ trimRecovered(checklist.getData()); } logger.debug("About to start running iprscans"); while(this.sequences.getNoOfSequences() != 0){ SequenceObject[] id = sequences.getNoOfSequences() > split ? new SequenceObject[split] : new SequenceObject[sequences.getNoOfSequences()]; int c=0; Stack<String> removes = new Stack<String>(); for(String s : sequences.keySet()){ if(c == split)break; else{ id[c]=sequences.getSequence(s); + removes.add(s); } c++; } while(removes.size()!=0)sequences.removeSequenceObject(removes.pop()); runIPRScan(out, checklist, id); total+=c; long timecurrent = System.currentTimeMillis(); long rate = (timecurrent-timestart)/total; long s = rate*sequences.getNoOfSequences(); - int perc = (int) Math.round(((double)size-sequences.getNoOfSequences() / (double)size)*100); - if(perc==100)perc=99; - System.out.println(total + " sequences run, "+perc+"% complete. Estimated Time Left "+ Tools_System.long2DayHourMin(s)); + System.out.println(total + " sequences run, Estimated Time Left "+ Tools_System.long2DayHourMin(s)); } } catch(Exception io){ logger.error("Failed to run iprscan",io); } System.out.println(); System.out.println(" "+total + " sequences run, 100% complete"); } else{ logger.error("Check that in is file, out is directory and blast_bin/db/prg is set"); } } else{ logger.error("Null input/output"); } logger.debug("Finished running task @ "+Tools_System.getDateNow()); setCompleteState(TaskState.FINISHED); } public boolean isKeepArgs(){ return true; } private void trimRecovered(String[] data){ int j=0; for(int i =0;i < data.length; i++){ if(sequences.getSequence(data[i]) != null){ sequences.removeSequenceObject(data[i]); j++; } } logger.debug("Removed "+j+" of "+ data.length + " from list, as previously run"); } public void runIPRScan(File output, Checklist list, SequenceObject[] id){ FileWriter fstream = null; BufferedWriter out = null; File temp = null; try{ temp = File.createTempFile("Tempscan", ".fasta"); fstream = new FileWriter(temp, false); out = new BufferedWriter(fstream); for(int i =0; i < id.length; i++){ Tools_Fasta.saveFasta(id[i].getIdentifier(),id[i].getSequence(),out); } fstream.close(); logger.trace("Saved to " + temp.getPath() + " stream closed"); String exec = iprscanbin +" " + params+ " -i " + temp.getPath() + " -o " + output.getPath() + Tools_System.getFilepathSeparator()+ id[0].getIdentifier() +".xml"; logger.trace("About to execute output: " + exec); StringBuffer[] buffer = Tools_Task.runProcess(exec, true); logger.trace("Output:"+buffer[0].toString()); temp.delete(); } catch(IOException io){ logger.error(io); } } public boolean wantsUI(){ return true; } public void addUI(UI ui){ this.ui = ui; } }
false
true
public void run(){ setCompleteState(TaskState.STARTED); logger.debug("Started running task @ "+Tools_System.getDateNow()); this.checklist = openChecklist(ui); if(input != null && output != null){ File in = new File(input); File out = new File(output); int total = 0; timestart = System.currentTimeMillis(); if(in.isFile() && out.isDirectory() && this.iprscanbin !=null){ try{ this.sequences = SequenceListFactory.getSequenceList(input); int size = this.sequences.getNoOfSequences(); if(checklist.inRecovery()){ trimRecovered(checklist.getData()); } logger.debug("About to start running iprscans"); while(this.sequences.getNoOfSequences() != 0){ SequenceObject[] id = sequences.getNoOfSequences() > split ? new SequenceObject[split] : new SequenceObject[sequences.getNoOfSequences()]; int c=0; Stack<String> removes = new Stack<String>(); for(String s : sequences.keySet()){ if(c == split)break; else{ id[c]=sequences.getSequence(s); } c++; } while(removes.size()!=0)sequences.removeSequenceObject(removes.pop()); runIPRScan(out, checklist, id); total+=c; long timecurrent = System.currentTimeMillis(); long rate = (timecurrent-timestart)/total; long s = rate*sequences.getNoOfSequences(); int perc = (int) Math.round(((double)size-sequences.getNoOfSequences() / (double)size)*100); if(perc==100)perc=99; System.out.println(total + " sequences run, "+perc+"% complete. Estimated Time Left "+ Tools_System.long2DayHourMin(s)); } } catch(Exception io){ logger.error("Failed to run iprscan",io); } System.out.println(); System.out.println(" "+total + " sequences run, 100% complete"); } else{ logger.error("Check that in is file, out is directory and blast_bin/db/prg is set"); } } else{ logger.error("Null input/output"); } logger.debug("Finished running task @ "+Tools_System.getDateNow()); setCompleteState(TaskState.FINISHED); }
public void run(){ setCompleteState(TaskState.STARTED); logger.debug("Started running task @ "+Tools_System.getDateNow()); this.checklist = openChecklist(ui); if(input != null && output != null){ File in = new File(input); File out = new File(output); int total = 0; timestart = System.currentTimeMillis(); if(in.isFile() && out.isDirectory() && this.iprscanbin !=null){ try{ this.sequences = SequenceListFactory.getSequenceList(input); if(checklist.inRecovery()){ trimRecovered(checklist.getData()); } logger.debug("About to start running iprscans"); while(this.sequences.getNoOfSequences() != 0){ SequenceObject[] id = sequences.getNoOfSequences() > split ? new SequenceObject[split] : new SequenceObject[sequences.getNoOfSequences()]; int c=0; Stack<String> removes = new Stack<String>(); for(String s : sequences.keySet()){ if(c == split)break; else{ id[c]=sequences.getSequence(s); removes.add(s); } c++; } while(removes.size()!=0)sequences.removeSequenceObject(removes.pop()); runIPRScan(out, checklist, id); total+=c; long timecurrent = System.currentTimeMillis(); long rate = (timecurrent-timestart)/total; long s = rate*sequences.getNoOfSequences(); System.out.println(total + " sequences run, Estimated Time Left "+ Tools_System.long2DayHourMin(s)); } } catch(Exception io){ logger.error("Failed to run iprscan",io); } System.out.println(); System.out.println(" "+total + " sequences run, 100% complete"); } else{ logger.error("Check that in is file, out is directory and blast_bin/db/prg is set"); } } else{ logger.error("Null input/output"); } logger.debug("Finished running task @ "+Tools_System.getDateNow()); setCompleteState(TaskState.FINISHED); }
diff --git a/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/web/IndexBean.java b/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/web/IndexBean.java index cae459d88..94291ad5b 100644 --- a/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/web/IndexBean.java +++ b/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/web/IndexBean.java @@ -1,1185 +1,1185 @@ package net.i2p.i2ptunnel.web; /* * free (adj.): unencumbered; not under the control of others * Written by jrandom in 2005 and released into the public domain * with no warranty of any kind, either expressed or implied. * It probably won't make your computer catch on fire, or eat * your children, but it might. Use at your own risk. * */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.ConcurrentHashMap; import net.i2p.I2PAppContext; import net.i2p.data.Base32; import net.i2p.data.Certificate; import net.i2p.data.Destination; import net.i2p.data.PrivateKeyFile; import net.i2p.data.SessionKey; import net.i2p.i2ptunnel.I2PTunnelHTTPClient; import net.i2p.i2ptunnel.I2PTunnelHTTPClientBase; import net.i2p.i2ptunnel.I2PTunnelIRCClient; import net.i2p.i2ptunnel.TunnelController; import net.i2p.i2ptunnel.TunnelControllerGroup; import net.i2p.util.ConcurrentHashSet; import net.i2p.util.FileUtil; import net.i2p.util.Log; /** * Simple accessor for exposing tunnel info, but also an ugly form handler * * Warning - This class is not part of the i2ptunnel API, and at some point * it will be moved from the jar to the war. * Usage by classes outside of i2ptunnel.war is deprecated. */ public class IndexBean { protected final I2PAppContext _context; protected final Log _log; protected final TunnelControllerGroup _group; private String _action; private int _tunnel; //private long _prevNonce; //private long _prevNonce2; private String _curNonce; //private long _nextNonce; private String _type; private String _name; private String _description; private String _i2cpHost; private String _i2cpPort; private String _tunnelDepth; private String _tunnelQuantity; private String _tunnelVariance; private String _tunnelBackupQuantity; private boolean _connectDelay; private String _customOptions; private String _proxyList; private String _port; private String _reachableBy; private String _targetDestination; private String _targetHost; private String _targetPort; private String _spoofedHost; private String _privKeyFile; private String _profile; private boolean _startOnLoad; private boolean _sharedClient; private boolean _privKeyGenerate; private boolean _removeConfirmed; private final Set<String> _booleanOptions; private final Map<String, String> _otherOptions; private int _hashCashValue; private int _certType; private String _certSigner; public static final int RUNNING = 1; public static final int STARTING = 2; public static final int NOT_RUNNING = 3; public static final int STANDBY = 4; /** deprecated unimplemented, now using routerconsole realm */ //public static final String PROP_TUNNEL_PASSPHRASE = "i2ptunnel.passphrase"; public static final String PROP_TUNNEL_PASSPHRASE = "consolePassword"; //static final String PROP_NONCE = IndexBean.class.getName() + ".nonce"; //static final String PROP_NONCE_OLD = PROP_NONCE + '2'; /** 3 wasn't enough for some browsers. They are reloading the page for some reason - maybe HEAD? @since 0.8.1 */ private static final int MAX_NONCES = 8; /** store nonces in a static FIFO instead of in System Properties @since 0.8.1 */ private static final List<String> _nonces = new ArrayList(MAX_NONCES + 1); static final String CLIENT_NICKNAME = "shared clients"; public static final String PROP_THEME_NAME = "routerconsole.theme"; public static final String DEFAULT_THEME = "light"; public static final String PROP_CSS_DISABLED = "routerconsole.css.disabled"; public static final String PROP_JS_DISABLED = "routerconsole.javascript.disabled"; public IndexBean() { _context = I2PAppContext.getGlobalContext(); _log = _context.logManager().getLog(IndexBean.class); _group = TunnelControllerGroup.getInstance(); _tunnel = -1; _curNonce = "-1"; addNonce(); _booleanOptions = new ConcurrentHashSet(4); _otherOptions = new ConcurrentHashMap(4); } public static String getNextNonce() { synchronized (_nonces) { return _nonces.get(0); } } public void setNonce(String nonce) { if ( (nonce == null) || (nonce.trim().length() <= 0) ) return; _curNonce = nonce; } /** add a random nonce to the head of the queue @since 0.8.1 */ private void addNonce() { String nextNonce = Long.toString(_context.random().nextLong()); synchronized (_nonces) { _nonces.add(0, nextNonce); int sz = _nonces.size(); if (sz > MAX_NONCES) _nonces.remove(sz - 1); } } /** do we know this nonce? @since 0.8.1 */ private static boolean haveNonce(String nonce) { synchronized (_nonces) { return _nonces.contains(nonce); } } /** deprecated unimplemented, now using routerconsole realm */ public void setPassphrase(String phrase) { } public void setAction(String action) { if ( (action == null) || (action.trim().length() <= 0) ) return; _action = action; } public void setTunnel(String tunnel) { if ( (tunnel == null) || (tunnel.trim().length() <= 0) ) return; try { _tunnel = Integer.parseInt(tunnel); } catch (NumberFormatException nfe) { _tunnel = -1; } } /** just check if console password option is set, jetty will do auth */ private boolean validPassphrase() { String pass = _context.getProperty(PROP_TUNNEL_PASSPHRASE); return pass != null && pass.trim().length() > 0; } private String processAction() { if ( (_action == null) || (_action.trim().length() <= 0) || ("Cancel".equals(_action))) return ""; if ( (!haveNonce(_curNonce)) && (!validPassphrase()) ) return _("Invalid form submission, probably because you used the 'back' or 'reload' button on your browser. Please resubmit."); if ("Stop all".equals(_action)) return stopAll(); else if ("Start all".equals(_action)) return startAll(); else if ("Restart all".equals(_action)) return restartAll(); else if ("Reload configuration".equals(_action)) return reloadConfig(); else if ("stop".equals(_action)) return stop(); else if ("start".equals(_action)) return start(); else if ("Save changes".equals(_action) || // IE workaround: (_action.toLowerCase().indexOf("s</span>ave") >= 0)) return saveChanges(); else if ("Delete this proxy".equals(_action) || // IE workaround: (_action.toLowerCase().indexOf("d</span>elete") >= 0)) return deleteTunnel(); else if ("Estimate".equals(_action)) return PrivateKeyFile.estimateHashCashTime(_hashCashValue); else if ("Modify".equals(_action)) return modifyDestination(); else if ("Generate".equals(_action)) return generateNewEncryptionKey(); else return "Action " + _action + " unknown"; } private String stopAll() { if (_group == null) return ""; List<String> msgs = _group.stopAllControllers(); return getMessages(msgs); } private String startAll() { if (_group == null) return ""; List<String> msgs = _group.startAllControllers(); return getMessages(msgs); } private String restartAll() { if (_group == null) return ""; List<String> msgs = _group.restartAllControllers(); return getMessages(msgs); } private String reloadConfig() { if (_group == null) return ""; _group.reloadControllers(); return _("Configuration reloaded for all tunnels"); } private String start() { if (_tunnel < 0) return "Invalid tunnel"; List controllers = _group.getControllers(); if (_tunnel >= controllers.size()) return "Invalid tunnel"; TunnelController controller = (TunnelController)controllers.get(_tunnel); controller.startTunnelBackground(); // give the messages a chance to make it to the window try { Thread.sleep(1000); } catch (InterruptedException ie) {} // and give them something to look at in any case return _("Starting tunnel") + ' ' + getTunnelName(_tunnel) + "&hellip;"; } private String stop() { if (_tunnel < 0) return "Invalid tunnel"; List controllers = _group.getControllers(); if (_tunnel >= controllers.size()) return "Invalid tunnel"; TunnelController controller = (TunnelController)controllers.get(_tunnel); controller.stopTunnel(); // give the messages a chance to make it to the window try { Thread.sleep(1000); } catch (InterruptedException ie) {} // and give them something to look at in any case return _("Stopping tunnel") + ' ' + getTunnelName(_tunnel) + "&hellip;"; } private String saveChanges() { // Get current tunnel controller TunnelController cur = getController(_tunnel); Properties config = getConfig(); if (config == null) return "Invalid params"; if (cur == null) { // creating new cur = new TunnelController(config, "", true); _group.addController(cur); if (cur.getStartOnLoad()) cur.startTunnelBackground(); } else { cur.setConfig(config, ""); } // Only modify other shared tunnels // if the current tunnel is shared, and of supported type if ("true".equalsIgnoreCase(cur.getSharedClient()) && isClient(cur.getType())) { // all clients use the same I2CP session, and as such, use the same I2CP options List controllers = _group.getControllers(); for (int i = 0; i < controllers.size(); i++) { TunnelController c = (TunnelController)controllers.get(i); // Current tunnel modified by user, skip if (c == cur) continue; // Only modify this non-current tunnel // if it belongs to a shared destination, and is of supported type if ("true".equalsIgnoreCase(c.getSharedClient()) && isClient(c.getType())) { Properties cOpt = c.getConfig(""); if (_tunnelQuantity != null) { cOpt.setProperty("option.inbound.quantity", _tunnelQuantity); cOpt.setProperty("option.outbound.quantity", _tunnelQuantity); } if (_tunnelDepth != null) { cOpt.setProperty("option.inbound.length", _tunnelDepth); cOpt.setProperty("option.outbound.length", _tunnelDepth); } if (_tunnelVariance != null) { cOpt.setProperty("option.inbound.lengthVariance", _tunnelVariance); cOpt.setProperty("option.outbound.lengthVariance", _tunnelVariance); } if (_tunnelBackupQuantity != null) { cOpt.setProperty("option.inbound.backupQuantity", _tunnelBackupQuantity); cOpt.setProperty("option.outbound.backupQuantity", _tunnelBackupQuantity); } cOpt.setProperty("option.inbound.nickname", CLIENT_NICKNAME); cOpt.setProperty("option.outbound.nickname", CLIENT_NICKNAME); c.setConfig(cOpt, ""); } } } List<String> msgs = doSave(); return getMessages(msgs); } private List<String> doSave() { List<String> rv = _group.clearAllMessages(); try { _group.saveConfig(); rv.add(0, _("Configuration changes saved")); } catch (IOException ioe) { _log.error("Failed to save config file", ioe); rv.add(0, _("Failed to save configuration") + ": " + ioe.toString()); } return rv; } /** * Stop the tunnel, delete from config, * rename the private key file if in the default directory */ private String deleteTunnel() { if (!_removeConfirmed) return "Please confirm removal"; TunnelController cur = getController(_tunnel); if (cur == null) return "Invalid tunnel number"; List<String> msgs = _group.removeController(cur); msgs.addAll(doSave()); // Rename private key file if it was a default name in // the default directory, so it doesn't get reused when a new // tunnel is created. // Use configured file name if available, not the one from the form. String pk = cur.getPrivKeyFile(); if (pk == null) pk = _privKeyFile; if (pk != null && pk.startsWith("i2ptunnel") && pk.endsWith("-privKeys.dat")) { File pkf = new File(_context.getConfigDir(), pk); if (pkf.exists()) { String name = cur.getName(); if (name == null) { name = cur.getDescription(); if (name == null) { name = cur.getType(); if (name == null) name = Long.toString(_context.clock().now()); } } name = "i2ptunnel-deleted-" + name.replace(' ', '_') + "-privkeys.dat"; File to = new File(_context.getConfigDir(), name); if (to.exists()) to = new File(_context.getConfigDir(), name + '-' + _context.clock().now()); boolean success = FileUtil.rename(pkf, to); if (success) msgs.add("Private key file " + pkf.getAbsolutePath() + " renamed to " + to.getAbsolutePath()); } } return getMessages(msgs); } /** * Executes any action requested (start/stop/etc) and dump out the * messages. * */ public String getMessages() { if (_group == null) return ""; StringBuilder buf = new StringBuilder(512); if (_action != null) { try { buf.append(processAction()).append("\n"); } catch (Exception e) { _log.log(Log.CRIT, "Error processing " + _action, e); } } getMessages(_group.clearAllMessages(), buf); return buf.toString(); } //// // The remaining methods are simple bean props for the jsp to query //// public String getTheme() { String theme = _context.getProperty(PROP_THEME_NAME, DEFAULT_THEME); return "/themes/console/" + theme + "/"; } public boolean allowCSS() { String css = _context.getProperty(PROP_CSS_DISABLED); return (css == null); } public boolean allowJS() { String js = _context.getProperty(PROP_JS_DISABLED); return (js == null); } public int getTunnelCount() { if (_group == null) return 0; return _group.getControllers().size(); } public boolean isClient(int tunnelNum) { TunnelController cur = getController(tunnelNum); if (cur == null) return false; return isClient(cur.getType()); } public static boolean isClient(String type) { return ( ("client".equals(type)) || ("httpclient".equals(type)) || ("sockstunnel".equals(type)) || ("socksirctunnel".equals(type)) || ("connectclient".equals(type)) || ("streamrclient".equals(type)) || ("ircclient".equals(type))); } public String getTunnelName(int tunnel) { TunnelController tun = getController(tunnel); if (tun != null && tun.getName() != null) return tun.getName(); else return _("New Tunnel"); } public String getClientPort(int tunnel) { TunnelController tun = getController(tunnel); if (tun != null && tun.getListenPort() != null) return tun.getListenPort(); else return ""; } public String getTunnelType(int tunnel) { TunnelController tun = getController(tunnel); if (tun != null) return getTypeName(tun.getType()); else return ""; } public String getTypeName(String internalType) { if ("client".equals(internalType)) return _("Standard client"); else if ("httpclient".equals(internalType)) return _("HTTP client"); else if ("ircclient".equals(internalType)) return _("IRC client"); else if ("server".equals(internalType)) return _("Standard server"); else if ("httpserver".equals(internalType)) return _("HTTP server"); else if ("sockstunnel".equals(internalType)) return _("SOCKS 4/4a/5 proxy"); else if ("socksirctunnel".equals(internalType)) return _("SOCKS IRC proxy"); else if ("connectclient".equals(internalType)) return _("CONNECT/SSL/HTTPS proxy"); else if ("ircserver".equals(internalType)) return _("IRC server"); else if ("streamrclient".equals(internalType)) return _("Streamr client"); else if ("streamrserver".equals(internalType)) return _("Streamr server"); else if ("httpbidirserver".equals(internalType)) return _("HTTP bidir"); else return internalType; } public String getInternalType(int tunnel) { TunnelController tun = getController(tunnel); if (tun != null) return tun.getType(); else return ""; } public String getClientInterface(int tunnel) { TunnelController tun = getController(tunnel); if (tun != null) { if ("streamrclient".equals(tun.getType())) return tun.getTargetHost(); else return tun.getListenOnInterface(); } else return "127.0.0.1"; } public int getTunnelStatus(int tunnel) { TunnelController tun = getController(tunnel); if (tun == null) return NOT_RUNNING; if (tun.getIsRunning()) { if (isClient(tunnel) && tun.getIsStandby()) return STANDBY; else return RUNNING; } else if (tun.getIsStarting()) return STARTING; else return NOT_RUNNING; } public String getTunnelDescription(int tunnel) { TunnelController tun = getController(tunnel); if (tun != null && tun.getDescription() != null) return tun.getDescription(); else return ""; } public String getSharedClient(int tunnel) { TunnelController tun = getController(tunnel); if (tun != null) return tun.getSharedClient(); else return ""; } public String getClientDestination(int tunnel) { TunnelController tun = getController(tunnel); if (tun == null) return ""; String rv; if ("client".equals(tun.getType()) || "ircclient".equals(tun.getType()) || "streamrclient".equals(tun.getType())) rv = tun.getTargetDestination(); else rv = tun.getProxyList(); return rv != null ? rv : ""; } /** * Call this to see if it is ok to linkify getServerTarget() * @since 0.8.3 */ public boolean isServerTargetLinkValid(int tunnel) { TunnelController tun = getController(tunnel); return tun != null && "httpserver".equals(tun.getType()) && tun.getTargetHost() != null && tun.getTargetPort() != null; } /** * @return valid host:port only if isServerTargetLinkValid() is true */ public String getServerTarget(int tunnel) { TunnelController tun = getController(tunnel); if (tun != null) { String host; if ("streamrserver".equals(tun.getType())) host = tun.getListenOnInterface(); else host = tun.getTargetHost(); String port = tun.getTargetPort(); if (host == null) host = "<font color=\"red\">" + _("Host not set") + "</font>"; else if (host.indexOf(':') >= 0) host = '[' + host + ']'; if (port == null) port = "<font color=\"red\">" + _("Port not set") + "</font>"; return host + ':' + port; } else return ""; } public String getDestinationBase64(int tunnel) { TunnelController tun = getController(tunnel); if (tun != null) { String rv = tun.getMyDestination(); if (rv != null) return rv; // if not running, do this the hard way String keyFile = tun.getPrivKeyFile(); if (keyFile != null && keyFile.trim().length() > 0) { PrivateKeyFile pkf = new PrivateKeyFile(keyFile); try { Destination d = pkf.getDestination(); if (d != null) return d.toBase64(); } catch (Exception e) {} } } return ""; } public String getDestHashBase32(int tunnel) { TunnelController tun = getController(tunnel); if (tun != null) { String rv = tun.getMyDestHashBase32(); if (rv != null) return rv; } return ""; } /// /// bean props for form submission /// /** * What type of tunnel (httpclient, ircclient, client, or server). This is * required when adding a new tunnel. * */ public void setType(String type) { _type = (type != null ? type.trim() : null); } String getType() { return _type; } /** Short name of the tunnel */ public void setName(String name) { _name = (name != null ? name.trim() : null); } /** one line description */ public void setDescription(String description) { _description = (description != null ? description.trim() : null); } /** I2CP host the router is on, ignored when in router context */ public void setClientHost(String host) { _i2cpHost = (host != null ? host.trim() : null); } /** I2CP port the router is on, ignored when in router context */ public void setClientport(String port) { _i2cpPort = (port != null ? port.trim() : null); } /** how many hops to use for inbound tunnels */ public void setTunnelDepth(String tunnelDepth) { _tunnelDepth = (tunnelDepth != null ? tunnelDepth.trim() : null); } /** how many parallel inbound tunnels to use */ public void setTunnelQuantity(String tunnelQuantity) { _tunnelQuantity = (tunnelQuantity != null ? tunnelQuantity.trim() : null); } /** how much randomisation to apply to the depth of tunnels */ public void setTunnelVariance(String tunnelVariance) { _tunnelVariance = (tunnelVariance != null ? tunnelVariance.trim() : null); } /** how many tunnels to hold in reserve to guard against failures */ public void setTunnelBackupQuantity(String tunnelBackupQuantity) { _tunnelBackupQuantity = (tunnelBackupQuantity != null ? tunnelBackupQuantity.trim() : null); } /** what I2P session overrides should be used */ public void setCustomOptions(String customOptions) { _customOptions = (customOptions != null ? customOptions.trim() : null); } /** what HTTP outproxies should be used (httpclient specific) */ public void setProxyList(String proxyList) { _proxyList = (proxyList != null ? proxyList.trim() : null); } /** what port should this client/httpclient/ircclient listen on */ public void setPort(String port) { _port = (port != null ? port.trim() : null); } /** * what interface should this client/httpclient/ircclient listen on */ public void setReachableBy(String reachableBy) { _reachableBy = (reachableBy != null ? reachableBy.trim() : null); } /** What peer does this client tunnel point at */ public void setTargetDestination(String dest) { _targetDestination = (dest != null ? dest.trim() : null); } /** What host does this server tunnel point at */ public void setTargetHost(String host) { _targetHost = (host != null ? host.trim() : null); } /** What port does this server tunnel point at */ public void setTargetPort(String port) { _targetPort = (port != null ? port.trim() : null); } /** What host does this http server tunnel spoof */ public void setSpoofedHost(String host) { _spoofedHost = (host != null ? host.trim() : null); } /** What filename is this server tunnel's private keys stored in */ public void setPrivKeyFile(String file) { _privKeyFile = (file != null ? file.trim() : null); } /** * If called with any value (and the form submitted with action=Remove), * we really do want to stop and remove the tunnel. */ public void setRemoveConfirm(String moo) { _removeConfirmed = true; } /** * If called with any value, we want this tunnel to start whenever it is * loaded (aka right now and whenever the router is started up) */ public void setStartOnLoad(String moo) { _startOnLoad = true; } public void setShared(String moo) { _sharedClient=true; } public void setShared(boolean val) { _sharedClient=val; } public void setConnectDelay(String moo) { _connectDelay = true; } public void setProfile(String profile) { _profile = profile; } public void setReduce(String moo) { _booleanOptions.add("i2cp.reduceOnIdle"); } public void setClose(String moo) { _booleanOptions.add("i2cp.closeOnIdle"); } public void setEncrypt(String moo) { _booleanOptions.add("i2cp.encryptLeaseSet"); } /** @since 0.8.9 */ public void setDCC(String moo) { _booleanOptions.add(I2PTunnelIRCClient.PROP_DCC); } protected static final String PROP_ENABLE_ACCESS_LIST = "i2cp.enableAccessList"; protected static final String PROP_ENABLE_BLACKLIST = "i2cp.enableBlackList"; public void setAccessMode(String val) { if ("1".equals(val)) _booleanOptions.add(PROP_ENABLE_ACCESS_LIST); else if ("2".equals(val)) _booleanOptions.add(PROP_ENABLE_BLACKLIST); } public void setDelayOpen(String moo) { _booleanOptions.add("i2cp.delayOpen"); } public void setNewDest(String val) { if ("1".equals(val)) _booleanOptions.add("i2cp.newDestOnResume"); else if ("2".equals(val)) _booleanOptions.add("persistentClientKey"); } public void setReduceTime(String val) { if (val != null) { try { _otherOptions.put("i2cp.reduceIdleTime", "" + (Integer.parseInt(val.trim()) * 60*1000)); } catch (NumberFormatException nfe) {} } } public void setReduceCount(String val) { if (val != null) _otherOptions.put("i2cp.reduceQuantity", val.trim()); } public void setEncryptKey(String val) { if (val != null) _otherOptions.put("i2cp.leaseSetKey", val.trim()); } public void setAccessList(String val) { if (val != null) _otherOptions.put("i2cp.accessList", val.trim().replace("\r\n", ",").replace("\n", ",").replace(" ", ",")); } public void setJumpList(String val) { if (val != null) _otherOptions.put(I2PTunnelHTTPClient.PROP_JUMP_SERVERS, val.trim().replace("\r\n", ",").replace("\n", ",").replace(" ", ",")); } public void setCloseTime(String val) { if (val != null) { try { _otherOptions.put("i2cp.closeIdleTime", "" + (Integer.parseInt(val.trim()) * 60*1000)); } catch (NumberFormatException nfe) {} } } /** all proxy auth @since 0.8.2 */ public void setProxyAuth(String s) { _booleanOptions.add(I2PTunnelHTTPClientBase.PROP_AUTH); } public void setProxyUsername(String s) { if (s != null) _otherOptions.put(I2PTunnelHTTPClientBase.PROP_USER, s.trim()); } public void setProxyPassword(String s) { if (s != null) _otherOptions.put(I2PTunnelHTTPClientBase.PROP_PW, s.trim()); } public void setOutproxyAuth(String s) { _booleanOptions.add(I2PTunnelHTTPClientBase.PROP_OUTPROXY_AUTH); } public void setOutproxyUsername(String s) { if (s != null) _otherOptions.put(I2PTunnelHTTPClientBase.PROP_OUTPROXY_USER, s.trim()); } public void setOutproxyPassword(String s) { if (s != null) _otherOptions.put(I2PTunnelHTTPClientBase.PROP_OUTPROXY_PW, s.trim()); } /** all of these are @since 0.8.3 */ protected static final String PROP_MAX_CONNS_MIN = "i2p.streaming.maxConnsPerMinute"; protected static final String PROP_MAX_CONNS_HOUR = "i2p.streaming.maxConnsPerHour"; protected static final String PROP_MAX_CONNS_DAY = "i2p.streaming.maxConnsPerDay"; protected static final String PROP_MAX_TOTAL_CONNS_MIN = "i2p.streaming.maxTotalConnsPerMinute"; protected static final String PROP_MAX_TOTAL_CONNS_HOUR = "i2p.streaming.maxTotalConnsPerHour"; protected static final String PROP_MAX_TOTAL_CONNS_DAY = "i2p.streaming.maxTotalConnsPerDay"; protected static final String PROP_MAX_STREAMS = "i2p.streaming.maxConcurrentStreams"; public void setLimitMinute(String s) { if (s != null) _otherOptions.put(PROP_MAX_CONNS_MIN, s.trim()); } public void setLimitHour(String s) { if (s != null) _otherOptions.put(PROP_MAX_CONNS_HOUR, s.trim()); } public void setLimitDay(String s) { if (s != null) _otherOptions.put(PROP_MAX_CONNS_DAY, s.trim()); } public void setTotalMinute(String s) { if (s != null) _otherOptions.put(PROP_MAX_TOTAL_CONNS_MIN, s.trim()); } public void setTotalHour(String s) { if (s != null) _otherOptions.put(PROP_MAX_TOTAL_CONNS_HOUR, s.trim()); } public void setTotalDay(String s) { if (s != null) _otherOptions.put(PROP_MAX_TOTAL_CONNS_DAY, s.trim()); } public void setMaxStreams(String s) { if (s != null) _otherOptions.put(PROP_MAX_STREAMS, s.trim()); } /** params needed for hashcash and dest modification */ public void setEffort(String val) { if (val != null) { try { _hashCashValue = Integer.parseInt(val.trim()); } catch (NumberFormatException nfe) {} } } public void setCert(String val) { if (val != null) { try { _certType = Integer.parseInt(val.trim()); } catch (NumberFormatException nfe) {} } } public void setSigner(String val) { _certSigner = val; } /** Modify or create a destination */ private String modifyDestination() { if (_privKeyFile == null || _privKeyFile.trim().length() <= 0) return "Private Key File not specified"; TunnelController tun = getController(_tunnel); Properties config = getConfig(); if (config == null) return "Invalid params"; if (tun == null) { // creating new tun = new TunnelController(config, "", true); _group.addController(tun); saveChanges(); } else if (tun.getIsRunning() || tun.getIsStarting()) { return "Tunnel must be stopped before modifying destination"; } File keyFile = new File(_privKeyFile); if (!keyFile.isAbsolute()) keyFile = new File(_context.getConfigDir(), _privKeyFile); PrivateKeyFile pkf = new PrivateKeyFile(keyFile); try { pkf.createIfAbsent(); } catch (Exception e) { return "Create private key file failed: " + e; } switch (_certType) { case Certificate.CERTIFICATE_TYPE_NULL: case Certificate.CERTIFICATE_TYPE_HIDDEN: pkf.setCertType(_certType); break; case Certificate.CERTIFICATE_TYPE_HASHCASH: pkf.setHashCashCert(_hashCashValue); break; case Certificate.CERTIFICATE_TYPE_SIGNED: if (_certSigner == null || _certSigner.trim().length() <= 0) return "No signing destination specified"; // find the signer's key file... String signerPKF = null; for (int i = 0; i < getTunnelCount(); i++) { TunnelController c = getController(i); if (_certSigner.equals(c.getConfig("").getProperty("name")) || _certSigner.equals(c.getConfig("").getProperty("spoofedHost"))) { signerPKF = c.getConfig("").getProperty("privKeyFile"); break; } } if (signerPKF == null || signerPKF.length() <= 0) return "Signing destination " + _certSigner + " not found"; if (_privKeyFile.equals(signerPKF)) return "Self-signed destinations not allowed"; Certificate c = pkf.setSignedCert(new PrivateKeyFile(signerPKF)); if (c == null) return "Signing failed - does signer destination exist?"; break; default: return "Unknown certificate type"; } Destination newdest; try { pkf.write(); newdest = pkf.getDestination(); } catch (Exception e) { return "Modification failed: " + e; } return "Destination modified - " + "New Base32 is " + Base32.encode(newdest.calculateHash().getData()) + ".b32.i2p " + "New Destination is " + newdest.toBase64(); } /** New key */ private String generateNewEncryptionKey() { TunnelController tun = getController(_tunnel); Properties config = getConfig(); if (config == null) return "Invalid params"; if (tun == null) { // creating new tun = new TunnelController(config, "", true); _group.addController(tun); saveChanges(); } else if (tun.getIsRunning() || tun.getIsStarting()) { return "Tunnel must be stopped before modifying leaseset encryption key"; } byte[] data = new byte[SessionKey.KEYSIZE_BYTES]; _context.random().nextBytes(data); SessionKey sk = new SessionKey(data); setEncryptKey(sk.toBase64()); setEncrypt(""); saveChanges(); return "New Leaseset Encryption Key: " + sk.toBase64(); } /** * Based on all provided data, create a set of configuration parameters * suitable for use in a TunnelController. This will replace (not add to) * any existing parameters, so this should return a comprehensive mapping. * */ private Properties getConfig() { Properties config = new Properties(); updateConfigGeneric(config); if ((isClient(_type) && !"streamrclient".equals(_type)) || "streamrserver".equals(_type)) { // streamrserver uses interface if (_reachableBy != null) config.setProperty("interface", _reachableBy); else config.setProperty("interface", ""); } else { // streamrclient uses targetHost if (_targetHost != null) config.setProperty("targetHost", _targetHost); } if (isClient(_type)) { // generic client stuff if (_port != null) config.setProperty("listenPort", _port); config.setProperty("sharedClient", _sharedClient + ""); for (String p : _booleanClientOpts) config.setProperty("option." + p, "" + _booleanOptions.contains(p)); for (String p : _otherClientOpts) if (_otherOptions.containsKey(p)) config.setProperty("option." + p, _otherOptions.get(p)); } else { // generic server stuff if (_targetPort != null) config.setProperty("targetPort", _targetPort); for (String p : _booleanServerOpts) config.setProperty("option." + p, "" + _booleanOptions.contains(p)); for (String p : _otherServerOpts) if (_otherOptions.containsKey(p)) config.setProperty("option." + p, _otherOptions.get(p)); } // generic proxy stuff if ("httpclient".equals(_type) || "connectclient".equals(_type) || "sockstunnel".equals(_type) ||"socksirctunnel".equals(_type)) { for (String p : _booleanProxyOpts) config.setProperty("option." + p, "" + _booleanOptions.contains(p)); if (_proxyList != null) config.setProperty("proxyList", _proxyList); } if ("ircclient".equals(_type) || "client".equals(_type) || "streamrclient".equals(_type)) { if (_targetDestination != null) config.setProperty("targetDestination", _targetDestination); } else if ("httpserver".equals(_type) || "httpbidirserver".equals(_type)) { if (_spoofedHost != null) config.setProperty("spoofedHost", _spoofedHost); } if ("httpbidirserver".equals(_type)) { if (_port != null) config.setProperty("listenPort", _port); if (_reachableBy != null) config.setProperty("interface", _reachableBy); else if (_targetHost != null) config.setProperty("interface", _targetHost); else config.setProperty("interface", ""); } if ("ircclient".equals(_type)) { boolean dcc = _booleanOptions.contains(I2PTunnelIRCClient.PROP_DCC); config.setProperty("option." + I2PTunnelIRCClient.PROP_DCC, "" + dcc); // add some sane server options since they aren't in the GUI (yet) if (dcc) { - config.setProperty("options." + PROP_MAX_CONNS_MIN, "3"); - config.setProperty("options." + PROP_MAX_CONNS_HOUR, "10"); - config.setProperty("options." + PROP_MAX_TOTAL_CONNS_MIN, "5"); - config.setProperty("options." + PROP_MAX_TOTAL_CONNS_HOUR, "25"); + config.setProperty("option." + PROP_MAX_CONNS_MIN, "3"); + config.setProperty("option." + PROP_MAX_CONNS_HOUR, "10"); + config.setProperty("option." + PROP_MAX_TOTAL_CONNS_MIN, "5"); + config.setProperty("option." + PROP_MAX_TOTAL_CONNS_HOUR, "25"); } } return config; } private static final String _noShowOpts[] = { "inbound.length", "outbound.length", "inbound.lengthVariance", "outbound.lengthVariance", "inbound.backupQuantity", "outbound.backupQuantity", "inbound.quantity", "outbound.quantity", "inbound.nickname", "outbound.nickname", "i2p.streaming.connectDelay", "i2p.streaming.maxWindowSize", I2PTunnelIRCClient.PROP_DCC }; private static final String _booleanClientOpts[] = { "i2cp.reduceOnIdle", "i2cp.closeOnIdle", "i2cp.newDestOnResume", "persistentClientKey", "i2cp.delayOpen" }; private static final String _booleanProxyOpts[] = { I2PTunnelHTTPClientBase.PROP_AUTH, I2PTunnelHTTPClientBase.PROP_OUTPROXY_AUTH }; private static final String _booleanServerOpts[] = { "i2cp.reduceOnIdle", "i2cp.encryptLeaseSet", PROP_ENABLE_ACCESS_LIST, PROP_ENABLE_BLACKLIST }; private static final String _otherClientOpts[] = { "i2cp.reduceIdleTime", "i2cp.reduceQuantity", "i2cp.closeIdleTime", "proxyUsername", "proxyPassword", "outproxyUsername", "outproxyPassword", I2PTunnelHTTPClient.PROP_JUMP_SERVERS }; private static final String _otherServerOpts[] = { "i2cp.reduceIdleTime", "i2cp.reduceQuantity", "i2cp.leaseSetKey", "i2cp.accessList", PROP_MAX_CONNS_MIN, PROP_MAX_CONNS_HOUR, PROP_MAX_CONNS_DAY, PROP_MAX_TOTAL_CONNS_MIN, PROP_MAX_TOTAL_CONNS_HOUR, PROP_MAX_TOTAL_CONNS_DAY, PROP_MAX_STREAMS }; protected static final Set _noShowSet = new HashSet(64); static { _noShowSet.addAll(Arrays.asList(_noShowOpts)); _noShowSet.addAll(Arrays.asList(_booleanClientOpts)); _noShowSet.addAll(Arrays.asList(_booleanProxyOpts)); _noShowSet.addAll(Arrays.asList(_booleanServerOpts)); _noShowSet.addAll(Arrays.asList(_otherClientOpts)); _noShowSet.addAll(Arrays.asList(_otherServerOpts)); } private void updateConfigGeneric(Properties config) { config.setProperty("type", _type); if (_name != null) config.setProperty("name", _name); if (_description != null) config.setProperty("description", _description); if (!_context.isRouterContext()) { if (_i2cpHost != null) config.setProperty("i2cpHost", _i2cpHost); if ( (_i2cpPort != null) && (_i2cpPort.trim().length() > 0) ) { config.setProperty("i2cpPort", _i2cpPort); } else { config.setProperty("i2cpPort", "7654"); } } if (_privKeyFile != null) config.setProperty("privKeyFile", _privKeyFile); if (_customOptions != null) { StringTokenizer tok = new StringTokenizer(_customOptions); while (tok.hasMoreTokens()) { String pair = tok.nextToken(); int eq = pair.indexOf('='); if ( (eq <= 0) || (eq >= pair.length()) ) continue; String key = pair.substring(0, eq); if (_noShowSet.contains(key)) continue; String val = pair.substring(eq+1); config.setProperty("option." + key, val); } } config.setProperty("startOnLoad", _startOnLoad + ""); if (_tunnelQuantity != null) { config.setProperty("option.inbound.quantity", _tunnelQuantity); config.setProperty("option.outbound.quantity", _tunnelQuantity); } if (_tunnelDepth != null) { config.setProperty("option.inbound.length", _tunnelDepth); config.setProperty("option.outbound.length", _tunnelDepth); } if (_tunnelVariance != null) { config.setProperty("option.inbound.lengthVariance", _tunnelVariance); config.setProperty("option.outbound.lengthVariance", _tunnelVariance); } if (_tunnelBackupQuantity != null) { config.setProperty("option.inbound.backupQuantity", _tunnelBackupQuantity); config.setProperty("option.outbound.backupQuantity", _tunnelBackupQuantity); } if (_connectDelay) config.setProperty("option.i2p.streaming.connectDelay", "1000"); else config.setProperty("option.i2p.streaming.connectDelay", "0"); if (isClient(_type) && _sharedClient) { config.setProperty("option.inbound.nickname", CLIENT_NICKNAME); config.setProperty("option.outbound.nickname", CLIENT_NICKNAME); } else if (_name != null) { config.setProperty("option.inbound.nickname", _name); config.setProperty("option.outbound.nickname", _name); } if ("interactive".equals(_profile)) // This was 1 which doesn't make much sense // The real way to make it interactive is to make the streaming lib // MessageInputStream flush faster but there's no option for that yet, // Setting it to 16 instead of the default but not sure what good that is either. config.setProperty("option.i2p.streaming.maxWindowSize", "16"); else config.remove("option.i2p.streaming.maxWindowSize"); } /// /// /// protected TunnelController getController(int tunnel) { if (tunnel < 0) return null; if (_group == null) return null; List controllers = _group.getControllers(); if (controllers.size() > tunnel) return (TunnelController)controllers.get(tunnel); else return null; } private static String getMessages(List<String> msgs) { StringBuilder buf = new StringBuilder(128); getMessages(msgs, buf); return buf.toString(); } private static void getMessages(List<String> msgs, StringBuilder buf) { if (msgs == null) return; for (int i = 0; i < msgs.size(); i++) { buf.append(msgs.get(i)).append("\n"); } } protected String _(String key) { return Messages._(key, _context); } }
true
true
private Properties getConfig() { Properties config = new Properties(); updateConfigGeneric(config); if ((isClient(_type) && !"streamrclient".equals(_type)) || "streamrserver".equals(_type)) { // streamrserver uses interface if (_reachableBy != null) config.setProperty("interface", _reachableBy); else config.setProperty("interface", ""); } else { // streamrclient uses targetHost if (_targetHost != null) config.setProperty("targetHost", _targetHost); } if (isClient(_type)) { // generic client stuff if (_port != null) config.setProperty("listenPort", _port); config.setProperty("sharedClient", _sharedClient + ""); for (String p : _booleanClientOpts) config.setProperty("option." + p, "" + _booleanOptions.contains(p)); for (String p : _otherClientOpts) if (_otherOptions.containsKey(p)) config.setProperty("option." + p, _otherOptions.get(p)); } else { // generic server stuff if (_targetPort != null) config.setProperty("targetPort", _targetPort); for (String p : _booleanServerOpts) config.setProperty("option." + p, "" + _booleanOptions.contains(p)); for (String p : _otherServerOpts) if (_otherOptions.containsKey(p)) config.setProperty("option." + p, _otherOptions.get(p)); } // generic proxy stuff if ("httpclient".equals(_type) || "connectclient".equals(_type) || "sockstunnel".equals(_type) ||"socksirctunnel".equals(_type)) { for (String p : _booleanProxyOpts) config.setProperty("option." + p, "" + _booleanOptions.contains(p)); if (_proxyList != null) config.setProperty("proxyList", _proxyList); } if ("ircclient".equals(_type) || "client".equals(_type) || "streamrclient".equals(_type)) { if (_targetDestination != null) config.setProperty("targetDestination", _targetDestination); } else if ("httpserver".equals(_type) || "httpbidirserver".equals(_type)) { if (_spoofedHost != null) config.setProperty("spoofedHost", _spoofedHost); } if ("httpbidirserver".equals(_type)) { if (_port != null) config.setProperty("listenPort", _port); if (_reachableBy != null) config.setProperty("interface", _reachableBy); else if (_targetHost != null) config.setProperty("interface", _targetHost); else config.setProperty("interface", ""); } if ("ircclient".equals(_type)) { boolean dcc = _booleanOptions.contains(I2PTunnelIRCClient.PROP_DCC); config.setProperty("option." + I2PTunnelIRCClient.PROP_DCC, "" + dcc); // add some sane server options since they aren't in the GUI (yet) if (dcc) { config.setProperty("options." + PROP_MAX_CONNS_MIN, "3"); config.setProperty("options." + PROP_MAX_CONNS_HOUR, "10"); config.setProperty("options." + PROP_MAX_TOTAL_CONNS_MIN, "5"); config.setProperty("options." + PROP_MAX_TOTAL_CONNS_HOUR, "25"); } } return config; }
private Properties getConfig() { Properties config = new Properties(); updateConfigGeneric(config); if ((isClient(_type) && !"streamrclient".equals(_type)) || "streamrserver".equals(_type)) { // streamrserver uses interface if (_reachableBy != null) config.setProperty("interface", _reachableBy); else config.setProperty("interface", ""); } else { // streamrclient uses targetHost if (_targetHost != null) config.setProperty("targetHost", _targetHost); } if (isClient(_type)) { // generic client stuff if (_port != null) config.setProperty("listenPort", _port); config.setProperty("sharedClient", _sharedClient + ""); for (String p : _booleanClientOpts) config.setProperty("option." + p, "" + _booleanOptions.contains(p)); for (String p : _otherClientOpts) if (_otherOptions.containsKey(p)) config.setProperty("option." + p, _otherOptions.get(p)); } else { // generic server stuff if (_targetPort != null) config.setProperty("targetPort", _targetPort); for (String p : _booleanServerOpts) config.setProperty("option." + p, "" + _booleanOptions.contains(p)); for (String p : _otherServerOpts) if (_otherOptions.containsKey(p)) config.setProperty("option." + p, _otherOptions.get(p)); } // generic proxy stuff if ("httpclient".equals(_type) || "connectclient".equals(_type) || "sockstunnel".equals(_type) ||"socksirctunnel".equals(_type)) { for (String p : _booleanProxyOpts) config.setProperty("option." + p, "" + _booleanOptions.contains(p)); if (_proxyList != null) config.setProperty("proxyList", _proxyList); } if ("ircclient".equals(_type) || "client".equals(_type) || "streamrclient".equals(_type)) { if (_targetDestination != null) config.setProperty("targetDestination", _targetDestination); } else if ("httpserver".equals(_type) || "httpbidirserver".equals(_type)) { if (_spoofedHost != null) config.setProperty("spoofedHost", _spoofedHost); } if ("httpbidirserver".equals(_type)) { if (_port != null) config.setProperty("listenPort", _port); if (_reachableBy != null) config.setProperty("interface", _reachableBy); else if (_targetHost != null) config.setProperty("interface", _targetHost); else config.setProperty("interface", ""); } if ("ircclient".equals(_type)) { boolean dcc = _booleanOptions.contains(I2PTunnelIRCClient.PROP_DCC); config.setProperty("option." + I2PTunnelIRCClient.PROP_DCC, "" + dcc); // add some sane server options since they aren't in the GUI (yet) if (dcc) { config.setProperty("option." + PROP_MAX_CONNS_MIN, "3"); config.setProperty("option." + PROP_MAX_CONNS_HOUR, "10"); config.setProperty("option." + PROP_MAX_TOTAL_CONNS_MIN, "5"); config.setProperty("option." + PROP_MAX_TOTAL_CONNS_HOUR, "25"); } } return config; }
diff --git a/src/com/android/settings/TextToSpeechSettings.java b/src/com/android/settings/TextToSpeechSettings.java index 94b256f62..ec0fc8cde 100644 --- a/src/com/android/settings/TextToSpeechSettings.java +++ b/src/com/android/settings/TextToSpeechSettings.java @@ -1,387 +1,387 @@ /* * Copyright (C) 2009 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; import static android.provider.Settings.Secure.TTS_USE_DEFAULTS; import static android.provider.Settings.Secure.TTS_DEFAULT_RATE; import static android.provider.Settings.Secure.TTS_DEFAULT_LANG; import static android.provider.Settings.Secure.TTS_DEFAULT_COUNTRY; import static android.provider.Settings.Secure.TTS_DEFAULT_VARIANT; import static android.provider.Settings.Secure.TTS_DEFAULT_SYNTH; import android.content.ContentResolver; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.CheckBoxPreference; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.speech.tts.TextToSpeech; import android.util.Log; import java.util.List; import java.util.StringTokenizer; public class TextToSpeechSettings extends PreferenceActivity implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener, TextToSpeech.OnInitListener { private static final String TAG = "TextToSpeechSettings"; private static final String KEY_TTS_PLAY_EXAMPLE = "tts_play_example"; private static final String KEY_TTS_INSTALL_DATA = "tts_install_data"; private static final String KEY_TTS_USE_DEFAULT = "toggle_use_default_tts_settings"; private static final String KEY_TTS_DEFAULT_RATE = "tts_default_rate"; private static final String KEY_TTS_DEFAULT_LANG = "tts_default_lang"; private static final String KEY_TTS_DEFAULT_COUNTRY = "tts_default_country"; private static final String KEY_TTS_DEFAULT_VARIANT = "tts_default_variant"; private static final String LOCALE_DELIMITER = "-"; // TODO move this to android.speech.tts.TextToSpeech.Engine private static final String FALLBACK_TTS_DEFAULT_SYNTH = "com.svox.pico"; private Preference mPlayExample = null; private Preference mInstallData = null; private CheckBoxPreference mUseDefaultPref = null; private ListPreference mDefaultRatePref = null; private ListPreference mDefaultLocPref = null; private String mDefaultLanguage = null; private String mDefaultCountry = null; private String mDefaultLocVariant = null; private String mDefaultEng = ""; private boolean mEnableDemo = false; private TextToSpeech mTts = null; /** * Request code (arbitrary value) for voice data check through * startActivityForResult. */ private static final int VOICE_DATA_INTEGRITY_CHECK = 1977; /** * Request code (arbitrary value) for voice data installation through * startActivityForResult. */ private static final int VOICE_DATA_INSTALLATION = 1980; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.tts_settings); mEnableDemo = false; initClickers(); initDefaultSettings(); } @Override protected void onStart() { super.onStart(); // whenever we return to this screen, we don't know the state of the // system, so we have to recheck that we can play the demo, or it must be disabled. // TODO make the TTS service listen to "changes in the system", i.e. sd card un/mount initClickers(); updateWidgetState(); checkVoiceData(); } @Override protected void onDestroy() { super.onDestroy(); if (mTts != null) { mTts.shutdown(); } } private void initClickers() { mPlayExample = findPreference(KEY_TTS_PLAY_EXAMPLE); mPlayExample.setOnPreferenceClickListener(this); mInstallData = findPreference(KEY_TTS_INSTALL_DATA); mInstallData.setOnPreferenceClickListener(this); } private void initDefaultSettings() { ContentResolver resolver = getContentResolver(); int intVal = 0; // Find the default TTS values in the settings, initialize and store the // settings if they are not found. // "Use Defaults" mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT); try { intVal = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS); } catch (SettingNotFoundException e) { // "use default" setting not found, initialize it intVal = TextToSpeech.Engine.FALLBACK_TTS_USE_DEFAULTS; Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, intVal); } mUseDefaultPref.setChecked(intVal == 1); mUseDefaultPref.setOnPreferenceChangeListener(this); // Default engine String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH); if (engine == null) { // TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech engine = FALLBACK_TTS_DEFAULT_SYNTH; Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine); } mDefaultEng = engine; // Default rate mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE); try { intVal = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE); } catch (SettingNotFoundException e) { // default rate setting not found, initialize it intVal = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_RATE; Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, intVal); } mDefaultRatePref.setValue(String.valueOf(intVal)); mDefaultRatePref.setOnPreferenceChangeListener(this); // Default language / country / variant : these three values map to a single ListPref // representing the matching Locale String language = null; String country = null; String variant = null; mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG); language = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG); if (language != null) { mDefaultLanguage = language; } else { // default language setting not found, initialize it, as well as the country and variant language = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_LANG; country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY; variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT; Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, language); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant); } if (country == null) { // country wasn't initialized yet because a default language was found country = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_COUNTRY); - if (country.compareTo("null") != 0) { + if (country != null) { mDefaultCountry = country; } else { // default country setting not found, initialize it, as well as the variant; country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY; variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT; Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant); } } if (variant == null) { // variant wasn't initialized yet because a default country was found variant = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_VARIANT); - if (variant.compareTo("null") != 0) { + if (variant != null) { mDefaultLocVariant = variant; } else { // default variant setting not found, initialize it variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT; Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant); } } // we now have the default lang/country/variant trio, build a string value from it String localeString = new String(language); if (country.compareTo("") != 0) { localeString += LOCALE_DELIMITER + country; } else { localeString += LOCALE_DELIMITER + " "; } if (variant.compareTo("") != 0) { localeString += LOCALE_DELIMITER + variant; } Log.v(TAG, "In initDefaultSettings: localeString=" + localeString); // TODO handle the case where localeString isn't in the existing entries mDefaultLocPref.setValue(localeString); mDefaultLocPref.setOnPreferenceChangeListener(this); } /** * Ask the current default engine to launch the matching CHECK_TTS_DATA activity * to check the required TTS files are properly installed. */ private void checkVoiceData() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); intent.setAction("android.intent.action.CHECK_TTS_DATA"); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK); } } } /** * Ask the current default engine to launch the matching INSTALL_TTS_DATA activity * so the required TTS files are properly installed. */ private void installVoiceData() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); intent.setAction("android.intent.action.INSTALL_TTS_DATA"); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivityForResult(intent, VOICE_DATA_INSTALLATION); } } } /** * Called when the TTS engine is initialized. */ public void onInit(int status) { if (status == TextToSpeech.TTS_SUCCESS) { Log.v(TAG, "TTS engine for settings screen initialized."); mEnableDemo = true; } else { Log.v(TAG, "TTS engine for settings screen failed to initialize successfully."); mEnableDemo = false; } updateWidgetState(); } /** * Called when voice data integrity check returns */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_DATA_INTEGRITY_CHECK) { if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { Log.v(TAG, "Voice data check passed"); if (mTts == null) { mTts = new TextToSpeech(this, this); } } else { Log.v(TAG, "Voice data check failed"); mEnableDemo = false; updateWidgetState(); } } } public boolean onPreferenceChange(Preference preference, Object objValue) { if (KEY_TTS_USE_DEFAULT.equals(preference.getKey())) { // "Use Defaults" int value = (Boolean)objValue ? 1 : 0; Settings.Secure.putInt(getContentResolver(), TTS_USE_DEFAULTS, value); Log.i(TAG, "TTS use default settings is "+objValue.toString()); } else if (KEY_TTS_DEFAULT_RATE.equals(preference.getKey())) { // Default rate int value = Integer.parseInt((String) objValue); try { Settings.Secure.putInt(getContentResolver(), TTS_DEFAULT_RATE, value); if (mTts != null) { mTts.setSpeechRate(value); } Log.i(TAG, "TTS default rate is "+value); } catch (NumberFormatException e) { Log.e(TAG, "could not persist default TTS rate setting", e); } } else if (KEY_TTS_DEFAULT_LANG.equals(preference.getKey())) { // Default locale ContentResolver resolver = getContentResolver(); parseLocaleInfo((String) objValue); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); Log.v(TAG, "TTS default lang/country/variant set to " + mDefaultLanguage + "/" + mDefaultCountry + "/" + mDefaultLocVariant); } return true; } /** * Called when mPlayExample or mInstallData is clicked */ public boolean onPreferenceClick(Preference preference) { if (preference == mPlayExample) { // Play example if (mTts != null) { mTts.speak(getResources().getString(R.string.tts_demo), TextToSpeech.TTS_QUEUE_FLUSH, null); } return true; } if (preference == mInstallData) { installVoiceData(); // quit this activity so it needs to be restarted after installation of the voice data finish(); return true; } return false; } private void updateWidgetState() { mPlayExample.setEnabled(mEnableDemo); mUseDefaultPref.setEnabled(mEnableDemo); mDefaultRatePref.setEnabled(mEnableDemo); mDefaultLocPref.setEnabled(mEnableDemo); mInstallData.setEnabled(!mEnableDemo); } private void parseLocaleInfo(String locale) { StringTokenizer tokenizer = new StringTokenizer(locale, LOCALE_DELIMITER); mDefaultLanguage = ""; mDefaultCountry = ""; mDefaultLocVariant = ""; if (tokenizer.hasMoreTokens()) { mDefaultLanguage = tokenizer.nextToken().trim(); } if (tokenizer.hasMoreTokens()) { mDefaultCountry = tokenizer.nextToken().trim(); } if (tokenizer.hasMoreTokens()) { mDefaultLocVariant = tokenizer.nextToken().trim(); } } }
false
true
private void initDefaultSettings() { ContentResolver resolver = getContentResolver(); int intVal = 0; // Find the default TTS values in the settings, initialize and store the // settings if they are not found. // "Use Defaults" mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT); try { intVal = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS); } catch (SettingNotFoundException e) { // "use default" setting not found, initialize it intVal = TextToSpeech.Engine.FALLBACK_TTS_USE_DEFAULTS; Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, intVal); } mUseDefaultPref.setChecked(intVal == 1); mUseDefaultPref.setOnPreferenceChangeListener(this); // Default engine String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH); if (engine == null) { // TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech engine = FALLBACK_TTS_DEFAULT_SYNTH; Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine); } mDefaultEng = engine; // Default rate mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE); try { intVal = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE); } catch (SettingNotFoundException e) { // default rate setting not found, initialize it intVal = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_RATE; Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, intVal); } mDefaultRatePref.setValue(String.valueOf(intVal)); mDefaultRatePref.setOnPreferenceChangeListener(this); // Default language / country / variant : these three values map to a single ListPref // representing the matching Locale String language = null; String country = null; String variant = null; mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG); language = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG); if (language != null) { mDefaultLanguage = language; } else { // default language setting not found, initialize it, as well as the country and variant language = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_LANG; country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY; variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT; Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, language); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant); } if (country == null) { // country wasn't initialized yet because a default language was found country = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_COUNTRY); if (country.compareTo("null") != 0) { mDefaultCountry = country; } else { // default country setting not found, initialize it, as well as the variant; country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY; variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT; Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant); } } if (variant == null) { // variant wasn't initialized yet because a default country was found variant = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_VARIANT); if (variant.compareTo("null") != 0) { mDefaultLocVariant = variant; } else { // default variant setting not found, initialize it variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT; Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant); } } // we now have the default lang/country/variant trio, build a string value from it String localeString = new String(language); if (country.compareTo("") != 0) { localeString += LOCALE_DELIMITER + country; } else { localeString += LOCALE_DELIMITER + " "; } if (variant.compareTo("") != 0) { localeString += LOCALE_DELIMITER + variant; } Log.v(TAG, "In initDefaultSettings: localeString=" + localeString); // TODO handle the case where localeString isn't in the existing entries mDefaultLocPref.setValue(localeString); mDefaultLocPref.setOnPreferenceChangeListener(this); }
private void initDefaultSettings() { ContentResolver resolver = getContentResolver(); int intVal = 0; // Find the default TTS values in the settings, initialize and store the // settings if they are not found. // "Use Defaults" mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT); try { intVal = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS); } catch (SettingNotFoundException e) { // "use default" setting not found, initialize it intVal = TextToSpeech.Engine.FALLBACK_TTS_USE_DEFAULTS; Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, intVal); } mUseDefaultPref.setChecked(intVal == 1); mUseDefaultPref.setOnPreferenceChangeListener(this); // Default engine String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH); if (engine == null) { // TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech engine = FALLBACK_TTS_DEFAULT_SYNTH; Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine); } mDefaultEng = engine; // Default rate mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE); try { intVal = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE); } catch (SettingNotFoundException e) { // default rate setting not found, initialize it intVal = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_RATE; Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, intVal); } mDefaultRatePref.setValue(String.valueOf(intVal)); mDefaultRatePref.setOnPreferenceChangeListener(this); // Default language / country / variant : these three values map to a single ListPref // representing the matching Locale String language = null; String country = null; String variant = null; mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG); language = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG); if (language != null) { mDefaultLanguage = language; } else { // default language setting not found, initialize it, as well as the country and variant language = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_LANG; country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY; variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT; Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, language); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant); } if (country == null) { // country wasn't initialized yet because a default language was found country = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_COUNTRY); if (country != null) { mDefaultCountry = country; } else { // default country setting not found, initialize it, as well as the variant; country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY; variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT; Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant); } } if (variant == null) { // variant wasn't initialized yet because a default country was found variant = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_VARIANT); if (variant != null) { mDefaultLocVariant = variant; } else { // default variant setting not found, initialize it variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT; Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant); } } // we now have the default lang/country/variant trio, build a string value from it String localeString = new String(language); if (country.compareTo("") != 0) { localeString += LOCALE_DELIMITER + country; } else { localeString += LOCALE_DELIMITER + " "; } if (variant.compareTo("") != 0) { localeString += LOCALE_DELIMITER + variant; } Log.v(TAG, "In initDefaultSettings: localeString=" + localeString); // TODO handle the case where localeString isn't in the existing entries mDefaultLocPref.setValue(localeString); mDefaultLocPref.setOnPreferenceChangeListener(this); }
diff --git a/grails/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java b/grails/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java index 5df8d0fc2..bc8c13744 100644 --- a/grails/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java +++ b/grails/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java @@ -1,139 +1,138 @@ package org.codehaus.groovy.grails.web.pages; import junit.framework.TestCase; import org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException; import java.io.*; /** * Tests the GSP parser. This can detect issues caused by improper * GSP->Groovy conversion. Normally, to compare the code, you can * run the page with a showSource parameter specified. * * The methods parseCode() and trimAndRemoveCR() have been added * to simplify test case code. * * @author Daiji * */ public class ParseTests extends TestCase { public void testParse() throws Exception { String output = parseCode("myTest", "<div>hi</div>"); String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n"+ "\n"+ "class myTest extends GroovyPage {\n"+ "public Object run() {\n"+ "out.print('<div>hi</div>')\n"+ "}\n"+ "}"; assertEquals(expected, trimAndRemoveCR(output)); } public void testParseWithUnclosedSquareBracket() throws Exception { String output = parseCode("myTest", "<g:message code=\"[\"/>"); String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n"+ "\n"+ "class myTest extends GroovyPage {\n"+ "public Object run() {\n"+ "attrs1 = [\"code\":\"[\"]\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('message','g',attrs1,body1)\n"+ "}\n"+ "}"; assertEquals(expected, trimAndRemoveCR(output)); } public void testParseWithUnclosedGstringThrowsException() throws IOException { try{ parseCode("myTest", "<g:message value=\"${boom\">"); }catch(GrailsTagException e){ assertEquals("Unexpected end of file encountered parsing Tag [message] for myTest. Are you missing a closing brace '}'?", e.getMessage()); return; } fail("Expected parse exception not thrown"); } /** * Eliminate potential issues caused by operating system differences * and minor output differences that we don't care about. * * Note: this code is inefficient and could stand to be optimized. */ public String trimAndRemoveCR(String s) { int index; StringBuffer sb = new StringBuffer(s.trim()); while ((index = sb.toString().indexOf('\r')) != -1) { sb.deleteCharAt(index); } return sb.toString(); } public String parseCode(String uri, String gsp) throws IOException { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); InputStream gspIn = new ByteArrayInputStream(gsp.getBytes()); Parse parse = new Parse(uri, gspIn); InputStream in = parse.parse(); send(in, pw); return sw.toString(); } public void testParseGTagsWithNamespaces() throws Exception { String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n" + "\n" + "class myTest extends GroovyPage {\n" + "public Object run() {\n" + "out.print(STATIC_HTML_CONTENT_0)\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('form','tt',[:],body1)\n" + "out.print(STATIC_HTML_CONTENT_1)\n" + "}\n" + "static final STATIC_HTML_CONTENT_1 = '''</tbody>\n" + "'''\n" + "\n" + - "static final STATIC_HTML_CONTENT_0 = '''<tbody>\n" + - "'''\n" + + "static final STATIC_HTML_CONTENT_0 = '''<tbody>'''\n" + "\n" + "}"; String output = parseCode("myTest", "<tbody>\n" + " <tt:form />\n" + "</tbody>"); //System.out.println(output); assertEquals(trimAndRemoveCR(expected), trimAndRemoveCR(output)); } /** * Copy all of input to output. * @param in * @param out * @throws IOException */ public static void send(InputStream in, Writer out) throws IOException { try { Reader reader = new InputStreamReader(in); char[] buf = new char[8192]; for (;;) { int read = reader.read(buf); if (read <= 0) break; out.write(buf, 0, read); } } finally { out.close(); in.close(); } } // writeInputStreamToResponse() }
true
true
public void testParseGTagsWithNamespaces() throws Exception { String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n" + "\n" + "class myTest extends GroovyPage {\n" + "public Object run() {\n" + "out.print(STATIC_HTML_CONTENT_0)\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('form','tt',[:],body1)\n" + "out.print(STATIC_HTML_CONTENT_1)\n" + "}\n" + "static final STATIC_HTML_CONTENT_1 = '''</tbody>\n" + "'''\n" + "\n" + "static final STATIC_HTML_CONTENT_0 = '''<tbody>\n" + "'''\n" + "\n" + "}"; String output = parseCode("myTest", "<tbody>\n" + " <tt:form />\n" + "</tbody>"); //System.out.println(output); assertEquals(trimAndRemoveCR(expected), trimAndRemoveCR(output)); }
public void testParseGTagsWithNamespaces() throws Exception { String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n" + "\n" + "class myTest extends GroovyPage {\n" + "public Object run() {\n" + "out.print(STATIC_HTML_CONTENT_0)\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('form','tt',[:],body1)\n" + "out.print(STATIC_HTML_CONTENT_1)\n" + "}\n" + "static final STATIC_HTML_CONTENT_1 = '''</tbody>\n" + "'''\n" + "\n" + "static final STATIC_HTML_CONTENT_0 = '''<tbody>'''\n" + "\n" + "}"; String output = parseCode("myTest", "<tbody>\n" + " <tt:form />\n" + "</tbody>"); //System.out.println(output); assertEquals(trimAndRemoveCR(expected), trimAndRemoveCR(output)); }
diff --git a/iwsn/runtime.portal/src/main/java/de/uniluebeck/itm/tr/runtime/portalapp/SessionManagementServiceImpl.java b/iwsn/runtime.portal/src/main/java/de/uniluebeck/itm/tr/runtime/portalapp/SessionManagementServiceImpl.java index 63445f64..232693be 100644 --- a/iwsn/runtime.portal/src/main/java/de/uniluebeck/itm/tr/runtime/portalapp/SessionManagementServiceImpl.java +++ b/iwsn/runtime.portal/src/main/java/de/uniluebeck/itm/tr/runtime/portalapp/SessionManagementServiceImpl.java @@ -1,447 +1,446 @@ /********************************************************************************************************************** * Copyright (c) 2010, Institute of Telematics, University of Luebeck * * 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 University of Luebeck 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 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 de.uniluebeck.itm.tr.runtime.portalapp; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.internal.Nullable; import com.google.inject.name.Named; import de.uniluebeck.itm.gtr.TestbedRuntime; import de.uniluebeck.itm.tr.util.SecureIdGenerator; import de.uniluebeck.itm.tr.util.UrlUtils; import eu.wisebed.testbed.api.rs.RSServiceHelper; import eu.wisebed.testbed.api.rs.v1.ConfidentialReservationData; import eu.wisebed.testbed.api.rs.v1.RS; import eu.wisebed.testbed.api.rs.v1.RSExceptionException; import eu.wisebed.testbed.api.rs.v1.ReservervationNotFoundExceptionException; import eu.wisebed.testbed.api.wsn.Constants; import eu.wisebed.testbed.api.wsn.SessionManagementHelper; import eu.wisebed.testbed.api.wsn.SessionManagementPreconditions; import eu.wisebed.testbed.api.wsn.WSNServiceHelper; import eu.wisebed.testbed.api.wsn.v211.ExperimentNotRunningException_Exception; import eu.wisebed.testbed.api.wsn.v211.SecretReservationKey; import eu.wisebed.testbed.api.wsn.v211.UnknownReservationIdException_Exception; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jws.WebParam; import javax.jws.WebService; import javax.xml.ws.Endpoint; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkNotNull; @Singleton @WebService( serviceName = "SessionManagementService", targetNamespace = Constants.NAMESPACE_SESSION_MANAGEMENT_SERVICE, portName = "SessionManagementPort", endpointInterface = Constants.ENDPOINT_INTERFACE_SESSION_MANGEMENT_SERVICE ) public class SessionManagementServiceImpl implements SessionManagementService { private TestbedRuntime testbedRuntime; private class CleanUpWSNInstanceJob implements Runnable { private List<SecretReservationKey> secretReservationKeys; public CleanUpWSNInstanceJob(List<SecretReservationKey> secretReservationKeys) { this.secretReservationKeys = secretReservationKeys; } @Override public void run() { try { free(secretReservationKeys); } catch (ExperimentNotRunningException_Exception enre) { log.error(enre.getMessage(), enre); } catch (UnknownReservationIdException_Exception urie) { log.error(urie.getMessage(), urie); } //To change body of implemented methods use File | Settings | File Templates. } } /** * The logger for this service. */ private static final Logger log = LoggerFactory.getLogger(SessionManagementService.class); /** * The sessionManagementEndpoint of this Session Management service instance. */ private Endpoint sessionManagementEndpoint; /** * The sessionManagementEndpoint URL of this Session Management service instance. */ private URL sessionManagementEndpointUrl; /** * The sessionManagementEndpoint URL of the reservation system that is used for fetching node URNs from the reservation * data. If it is {@code null} then the reservation system is not used. */ private URL reservationEndpointUrl; /** * The URN prefix that is served by this instance. */ private String urnPrefix; /** * Used to generate secure random IDs to append them to newly created WSN API instances. */ private SecureIdGenerator secureIdGenerator = new SecureIdGenerator(); /** * Holds all currently instantiated WSN API instances that are not yet removed by {@link * de.uniluebeck.itm.tr.runtime.portalapp.SessionManagementService#free(java.util.List)}. */ private final Map<String, WSNServiceHandle> wsnInstances = new HashMap<String, WSNServiceHandle>(); /** * The base URL (i.e. prefix) that is prepended to a newly created WSN API instance. */ private URL wsnInstanceBaseUrl; /** * An instance of a preconditions checker initiated with the URN prefix of this instance. Used for checking * preconditions of the public Session Management API. */ private SessionManagementPreconditions preconditions; private String wiseML; @Inject public SessionManagementServiceImpl(@Named(PortalModule.NAME_URN_PREFIX) String urnPrefix, @Named(PortalModule.NAME_SESSION_MANAGEMENT_ENDPOINT_URL) String sessionManagementEndpointUrl, @Named(PortalModule.NAME_WSN_INSTANCE_BASE_URL) String wsnInstanceBaseUrl, @Nullable @Named(PortalModule.NAME_RESERVATION_ENDPOINT_URL) String reservationEndpointUrl, @Named(PortalModule.NAME_WISEML) String wiseML, TestbedRuntime testbedRuntime) throws MalformedURLException { checkNotNull(urnPrefix); checkNotNull(sessionManagementEndpointUrl); checkNotNull(wsnInstanceBaseUrl); checkNotNull(wiseML); checkNotNull(testbedRuntime); this.urnPrefix = urnPrefix; this.sessionManagementEndpointUrl = new URL(sessionManagementEndpointUrl); this.reservationEndpointUrl = reservationEndpointUrl == null ? null : new URL(reservationEndpointUrl); this.wsnInstanceBaseUrl = new URL(wsnInstanceBaseUrl.endsWith("/") ? wsnInstanceBaseUrl : wsnInstanceBaseUrl + "/"); this.wiseML = wiseML; this.testbedRuntime = testbedRuntime; this.preconditions = new SessionManagementPreconditions(); this.preconditions.addServedUrnPrefixes(urnPrefix); } @Override public void start() throws Exception { String bindAllInterfacesUrl = UrlUtils.convertHostToZeros(sessionManagementEndpointUrl.toString()); log.debug("Starting Session Management service ..."); log.debug("Endpoint URL: {}", sessionManagementEndpointUrl.toString()); log.debug("Binding URL: {}", bindAllInterfacesUrl); sessionManagementEndpoint = Endpoint.publish(bindAllInterfacesUrl, this); log.info("Started Session Management service on {}", bindAllInterfacesUrl); } @Override public void stop() { if (sessionManagementEndpoint != null) { sessionManagementEndpoint.stop(); log.info("Stopped Session Management service on {}", sessionManagementEndpointUrl); } } @Override public String getInstance( @WebParam(name = "secretReservationKey", targetNamespace = "") List<SecretReservationKey> secretReservationKeys, @WebParam(name = "controller", targetNamespace = "") String controller) throws ExperimentNotRunningException_Exception, UnknownReservationIdException_Exception { // TODO catch precondition exceptions and throw cleanly defined exception to client preconditions.checkGetInstanceArguments(secretReservationKeys, controller); // extract the one and only relevant secretReservationKey String secretReservationKey = secretReservationKeys.get(0).getSecretReservationKey(); // check if wsnInstance already exists and return it if that's the case WSNServiceHandle wsnServiceHandleInstance; synchronized (wsnInstances) { wsnServiceHandleInstance = wsnInstances.get(secretReservationKey); if (wsnServiceHandleInstance != null) { log.debug("Adding new controller to the list: {}", controller); wsnServiceHandleInstance.getWSNService().addController(controller); return wsnServiceHandleInstance.getWsnInstanceEndpointUrl().toString(); } } // no existing wsnInstance was found, so create new wsnInstance // query reservation system for reservation data if reservation system is to be used (i.e. // reservationEndpointUrl is not null) List<ConfidentialReservationData> confidentialReservationDataList; Set<String> reservedNodes = null; if (reservationEndpointUrl != null) { //integrate reservation system List<SecretReservationKey> keys = generateSecretReservationKeyList(secretReservationKey); confidentialReservationDataList = getReservationDataFromRS(keys); reservedNodes = new HashSet<String>(); // assure that wsnInstance creation doesn't happen before reservation time slot assertReservationIntervalMet(confidentialReservationDataList); //get reserved nodes for (ConfidentialReservationData data : confidentialReservationDataList) { reservedNodes.addAll(data.getNodeURNs()); } // assure that nodes are in TestbedRuntime assertNodesInTestbed(reservedNodes, testbedRuntime); // assure that all wsn-instances will be removed after expiration time for (ConfidentialReservationData data : confidentialReservationDataList) { //Creating delay for CleanUpJob long delay = data.getTo().toGregorianCalendar().getTimeInMillis() - System.currentTimeMillis(); //stop and remove invalid instances after their expiration time testbedRuntime.getSchedulerService() .schedule(new CleanUpWSNInstanceJob(keys), delay, TimeUnit.MILLISECONDS); } } else { log.info("Information: No Reservation-System found! All existing nodes will be used."); } try { URL wsnInstanceEndpointUrl = new URL(wsnInstanceBaseUrl + secureIdGenerator.getNextId()); URL controllerEndpointUrl = new URL(controller); - assert reservedNodes != null; wsnServiceHandleInstance = WSNServiceModule.Factory.create( testbedRuntime, urnPrefix, wsnInstanceEndpointUrl, controllerEndpointUrl, wiseML, - reservedNodes.toArray(new String[reservedNodes.size()]) + reservedNodes == null ? null : reservedNodes.toArray(new String[reservedNodes.size()]) ); } catch (MalformedURLException e) { throw new RuntimeException(e); } try { wsnServiceHandleInstance.start(); } catch (Exception e) { log.error("Exception while creating WSN API wsnInstance!", e); // TODO throw declared generic type throw new RuntimeException(e); } synchronized (wsnInstances) { wsnInstances.put(secretReservationKey, wsnServiceHandleInstance); } return wsnServiceHandleInstance.getWsnInstanceEndpointUrl().toString(); } //check if all reserved nodes are in testbedruntime private void assertNodesInTestbed(Set<String> reservedNodes, TestbedRuntime testbedRuntime) throws ExperimentNotRunningException_Exception { for (String node : reservedNodes) { if (!testbedRuntime.getLocalNodeNames().contains(node) && !testbedRuntime.getRoutingTableService() .getEntries().keySet().contains(node)) { throw new RuntimeException( "Node URN " + node + " in RS-ConfidentialReservationData not in testbed-runtime environment." ); } } } @Override public void free( @WebParam(name = "secretReservationKey", targetNamespace = "") List<SecretReservationKey> secretReservationKeyList) throws ExperimentNotRunningException_Exception, UnknownReservationIdException_Exception { // TODO catch precondition exceptions and throw cleanly defined exception to client preconditions.checkFreeArguments(secretReservationKeyList); // extract the one and only relevant secret reservation key String secretReservationKey = secretReservationKeyList.get(0).getSecretReservationKey(); synchronized (wsnInstances) { // search for the existing instance WSNServiceHandle wsnServiceHandleInstance = wsnInstances.get(secretReservationKey); // stop it if it is existing (it may have been freed before or its lifetime may have been reached) if (wsnServiceHandleInstance != null) { try { wsnServiceHandleInstance.stop(); } catch (Exception e) { log.error("Error while stopping WSN service instance: " + e, e); } wsnInstances.remove(secretReservationKey); log.debug( "Removing WSNServiceHandle for WSN service endpoint {}. {} WSN service endpoints running.", wsnServiceHandleInstance.getWsnInstanceEndpointUrl(), wsnInstances.size() ); } else { throw SessionManagementHelper.createExperimentNotRunningException(secretReservationKey); } } } @Override public String getNetwork() { // TODO implement run-time generation of WiseML file return wiseML; } private List<eu.wisebed.testbed.api.rs.v1.SecretReservationKey> convert( List<SecretReservationKey> secretReservationKey) { List<eu.wisebed.testbed.api.rs.v1.SecretReservationKey> retList = new ArrayList<eu.wisebed.testbed.api.rs.v1.SecretReservationKey>(secretReservationKey.size()); for (SecretReservationKey reservationKey : secretReservationKey) { retList.add(convert(reservationKey)); } return retList; } private eu.wisebed.testbed.api.rs.v1.SecretReservationKey convert(SecretReservationKey reservationKey) { eu.wisebed.testbed.api.rs.v1.SecretReservationKey retSRK = new eu.wisebed.testbed.api.rs.v1.SecretReservationKey(); retSRK.setSecretReservationKey(reservationKey.getSecretReservationKey()); retSRK.setUrnPrefix(reservationKey.getUrnPrefix()); return retSRK; } /** * Tries to fetch the reservation data from {@link de.uniluebeck.itm.tr.runtime.portalapp.SessionManagementServiceImpl#reservationEndpointUrl} * and returns the list of reservations. * * @param secretReservationKeys the list of secret reservation keys * * @return the list of reservations * * @throws UnknownReservationIdException_Exception * if the reservation could not be found */ private List<ConfidentialReservationData> getReservationDataFromRS( List<SecretReservationKey> secretReservationKeys) throws UnknownReservationIdException_Exception { try { RS rsService = RSServiceHelper.getRSService(reservationEndpointUrl.toString()); return rsService.getReservation(convert(secretReservationKeys)); } catch (RSExceptionException e) { String msg = "Generic exception occured in the federated reservation system"; log.warn(msg + ": " + e, e); // TODO replace with more generic exception type throw WSNServiceHelper.createUnknownReservationIdException(msg, null, e); } catch (ReservervationNotFoundExceptionException e) { log.debug("Reservation was not found. Message from RS: {}", e.getMessage()); throw WSNServiceHelper.createUnknownReservationIdException(e.getMessage(), null, e); } } /** * Checks the reservations' time intervals if they have already started or have already stopped and throws an exception * if that's the case. * * @param reservations the reservations to check * * @throws ExperimentNotRunningException_Exception * if now is not inside the reservations' time interval */ private void assertReservationIntervalMet(List<ConfidentialReservationData> reservations) throws ExperimentNotRunningException_Exception { for (ConfidentialReservationData reservation : reservations) { DateTime from = new DateTime(reservation.getFrom().toGregorianCalendar()); DateTime to = new DateTime(reservation.getTo().toGregorianCalendar()); if (from.isAfterNow()) { throw WSNServiceHelper.createExperimentNotRunningException("Reservation time interval for node URNs " + Arrays.toString(reservation.getNodeURNs().toArray()) + " lies in the future.", null ); } if (to.isBeforeNow()) { throw WSNServiceHelper.createExperimentNotRunningException("Reservation time interval for node URNs " + Arrays.toString(reservation.getNodeURNs().toArray()) + " lies in the past.", null ); } } } private List<SecretReservationKey> generateSecretReservationKeyList(String secretReservationKey) { List<SecretReservationKey> secretReservationKeyList = new LinkedList<SecretReservationKey>(); SecretReservationKey key = new SecretReservationKey(); key.setUrnPrefix(urnPrefix); key.setSecretReservationKey(secretReservationKey); secretReservationKeyList.add(key); return secretReservationKeyList; } }
false
true
public String getInstance( @WebParam(name = "secretReservationKey", targetNamespace = "") List<SecretReservationKey> secretReservationKeys, @WebParam(name = "controller", targetNamespace = "") String controller) throws ExperimentNotRunningException_Exception, UnknownReservationIdException_Exception { // TODO catch precondition exceptions and throw cleanly defined exception to client preconditions.checkGetInstanceArguments(secretReservationKeys, controller); // extract the one and only relevant secretReservationKey String secretReservationKey = secretReservationKeys.get(0).getSecretReservationKey(); // check if wsnInstance already exists and return it if that's the case WSNServiceHandle wsnServiceHandleInstance; synchronized (wsnInstances) { wsnServiceHandleInstance = wsnInstances.get(secretReservationKey); if (wsnServiceHandleInstance != null) { log.debug("Adding new controller to the list: {}", controller); wsnServiceHandleInstance.getWSNService().addController(controller); return wsnServiceHandleInstance.getWsnInstanceEndpointUrl().toString(); } } // no existing wsnInstance was found, so create new wsnInstance // query reservation system for reservation data if reservation system is to be used (i.e. // reservationEndpointUrl is not null) List<ConfidentialReservationData> confidentialReservationDataList; Set<String> reservedNodes = null; if (reservationEndpointUrl != null) { //integrate reservation system List<SecretReservationKey> keys = generateSecretReservationKeyList(secretReservationKey); confidentialReservationDataList = getReservationDataFromRS(keys); reservedNodes = new HashSet<String>(); // assure that wsnInstance creation doesn't happen before reservation time slot assertReservationIntervalMet(confidentialReservationDataList); //get reserved nodes for (ConfidentialReservationData data : confidentialReservationDataList) { reservedNodes.addAll(data.getNodeURNs()); } // assure that nodes are in TestbedRuntime assertNodesInTestbed(reservedNodes, testbedRuntime); // assure that all wsn-instances will be removed after expiration time for (ConfidentialReservationData data : confidentialReservationDataList) { //Creating delay for CleanUpJob long delay = data.getTo().toGregorianCalendar().getTimeInMillis() - System.currentTimeMillis(); //stop and remove invalid instances after their expiration time testbedRuntime.getSchedulerService() .schedule(new CleanUpWSNInstanceJob(keys), delay, TimeUnit.MILLISECONDS); } } else { log.info("Information: No Reservation-System found! All existing nodes will be used."); } try { URL wsnInstanceEndpointUrl = new URL(wsnInstanceBaseUrl + secureIdGenerator.getNextId()); URL controllerEndpointUrl = new URL(controller); assert reservedNodes != null; wsnServiceHandleInstance = WSNServiceModule.Factory.create( testbedRuntime, urnPrefix, wsnInstanceEndpointUrl, controllerEndpointUrl, wiseML, reservedNodes.toArray(new String[reservedNodes.size()]) ); } catch (MalformedURLException e) { throw new RuntimeException(e); } try { wsnServiceHandleInstance.start(); } catch (Exception e) { log.error("Exception while creating WSN API wsnInstance!", e); // TODO throw declared generic type throw new RuntimeException(e); } synchronized (wsnInstances) { wsnInstances.put(secretReservationKey, wsnServiceHandleInstance); } return wsnServiceHandleInstance.getWsnInstanceEndpointUrl().toString(); }
public String getInstance( @WebParam(name = "secretReservationKey", targetNamespace = "") List<SecretReservationKey> secretReservationKeys, @WebParam(name = "controller", targetNamespace = "") String controller) throws ExperimentNotRunningException_Exception, UnknownReservationIdException_Exception { // TODO catch precondition exceptions and throw cleanly defined exception to client preconditions.checkGetInstanceArguments(secretReservationKeys, controller); // extract the one and only relevant secretReservationKey String secretReservationKey = secretReservationKeys.get(0).getSecretReservationKey(); // check if wsnInstance already exists and return it if that's the case WSNServiceHandle wsnServiceHandleInstance; synchronized (wsnInstances) { wsnServiceHandleInstance = wsnInstances.get(secretReservationKey); if (wsnServiceHandleInstance != null) { log.debug("Adding new controller to the list: {}", controller); wsnServiceHandleInstance.getWSNService().addController(controller); return wsnServiceHandleInstance.getWsnInstanceEndpointUrl().toString(); } } // no existing wsnInstance was found, so create new wsnInstance // query reservation system for reservation data if reservation system is to be used (i.e. // reservationEndpointUrl is not null) List<ConfidentialReservationData> confidentialReservationDataList; Set<String> reservedNodes = null; if (reservationEndpointUrl != null) { //integrate reservation system List<SecretReservationKey> keys = generateSecretReservationKeyList(secretReservationKey); confidentialReservationDataList = getReservationDataFromRS(keys); reservedNodes = new HashSet<String>(); // assure that wsnInstance creation doesn't happen before reservation time slot assertReservationIntervalMet(confidentialReservationDataList); //get reserved nodes for (ConfidentialReservationData data : confidentialReservationDataList) { reservedNodes.addAll(data.getNodeURNs()); } // assure that nodes are in TestbedRuntime assertNodesInTestbed(reservedNodes, testbedRuntime); // assure that all wsn-instances will be removed after expiration time for (ConfidentialReservationData data : confidentialReservationDataList) { //Creating delay for CleanUpJob long delay = data.getTo().toGregorianCalendar().getTimeInMillis() - System.currentTimeMillis(); //stop and remove invalid instances after their expiration time testbedRuntime.getSchedulerService() .schedule(new CleanUpWSNInstanceJob(keys), delay, TimeUnit.MILLISECONDS); } } else { log.info("Information: No Reservation-System found! All existing nodes will be used."); } try { URL wsnInstanceEndpointUrl = new URL(wsnInstanceBaseUrl + secureIdGenerator.getNextId()); URL controllerEndpointUrl = new URL(controller); wsnServiceHandleInstance = WSNServiceModule.Factory.create( testbedRuntime, urnPrefix, wsnInstanceEndpointUrl, controllerEndpointUrl, wiseML, reservedNodes == null ? null : reservedNodes.toArray(new String[reservedNodes.size()]) ); } catch (MalformedURLException e) { throw new RuntimeException(e); } try { wsnServiceHandleInstance.start(); } catch (Exception e) { log.error("Exception while creating WSN API wsnInstance!", e); // TODO throw declared generic type throw new RuntimeException(e); } synchronized (wsnInstances) { wsnInstances.put(secretReservationKey, wsnServiceHandleInstance); } return wsnServiceHandleInstance.getWsnInstanceEndpointUrl().toString(); }
diff --git a/web/src/main/java/eionet/eunis/dao/SpeciesFactsheetDaoImpl.java b/web/src/main/java/eionet/eunis/dao/SpeciesFactsheetDaoImpl.java index d697d515..3e9c3885 100644 --- a/web/src/main/java/eionet/eunis/dao/SpeciesFactsheetDaoImpl.java +++ b/web/src/main/java/eionet/eunis/dao/SpeciesFactsheetDaoImpl.java @@ -1,140 +1,142 @@ package eionet.eunis.dao; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import ro.finsiel.eunis.factsheet.species.SpeciesFactsheet; import ro.finsiel.eunis.utilities.SQLUtilities; import eionet.eunis.dto.SpeciesAttributeDto; import eionet.eunis.dto.readers.SpeciesAttributeDTOReader; /** * @author Aleksandr Ivanov * <a href="mailto:[email protected]">contact</a> */ public class SpeciesFactsheetDaoImpl extends BaseDaoImpl implements ISpeciesFactsheetDao { private static final Logger logger = Logger.getLogger(SpeciesFactsheetDaoImpl.class); public SpeciesFactsheetDaoImpl(SQLUtilities sqlUtilities) { super(sqlUtilities); } /** * @see eionet.eunis.dao.ISpeciesFactsheetDao#getIdSpeciesForScientificName(java.lang.String) * {@inheritDoc} */ public int getIdSpeciesForScientificName(String idSpecies) { if (StringUtils.isBlank(idSpecies)) { return 0; } String sql = "SELECT ID_SPECIES FROM CHM62EDT_SPECIES WHERE SCIENTIFIC_NAME = '" + StringEscapeUtils.escapeSql( StringEscapeUtils.unescapeHtml(idSpecies)) + "'"; String result = getSqlUtils().ExecuteSQL(sql); return StringUtils.isNumeric(result) && !StringUtils.isBlank(result) ? new Integer(result) : 0; } /** * @see eionet.eunis.dao.ISpeciesFactsheetDao#getScientificName(int) * {@inheritDoc} */ public String getScientificName(int idSpecies) { SQLUtilities utils = getSqlUtils(); String sql = "SELECT SCIENTIFIC_NAME FROM CHM62EDT_SPECIES WHERE ID_SPECIES = " + idSpecies; return utils.ExecuteSQL(sql); } /** * @see eionet.eunis.dao.ISpeciesFactsheetDao#getCanonicalIdSpecies(int) * {@inheritDoc} */ public int getCanonicalIdSpecies(int idSpecies) { //sanity checks if (idSpecies <= 0) { return 0; } SQLUtilities utils = getSqlUtils(); String synonymSQL = "SELECT ID_SPECIES_LINK FROM CHM62EDT_SPECIES WHERE ID_SPECIES = " + idSpecies; String result = utils.ExecuteSQL(synonymSQL); return StringUtils.isNumeric(result) && StringUtils.isNotBlank(result) ? new Integer(result) : 0; } /* (non-Javadoc) * @see eionet.eunis.dao.ISpeciesFactsheetDao#getSynonyms(int) */ public List<Integer> getSynonyms(int idSpecies) { //sanity checks if (idSpecies <= 0) { return null; } SQLUtilities utils = getSqlUtils(); String sql = "SELECT ID_SPECIES FROM CHM62EDT_SPECIES WHERE ID_SPECIES_LINK = ? AND ID_SPECIES <> ?"; List<Object> params = new LinkedList<Object>(); params.add(idSpecies); params.add(idSpecies); try { return utils.executeQuery(sql, params); } catch (SQLException ignored) { logger.error(ignored); throw new RuntimeException(ignored); } } public List<SpeciesAttributeDto> getAttributesForNatureObject(int idNatureObject) { SQLUtilities utils = getSqlUtils(); String sql = "SELECT * FROM CHM62EDT_NATURE_OBJECT_ATTRIBUTES " + "WHERE ID_NATURE_OBJECT = ? AND NAME NOT LIKE '\\_%'"; List<Object> params = new LinkedList<Object>(); params.add(idNatureObject); try { SpeciesAttributeDTOReader attributeReader = new SpeciesAttributeDTOReader(); utils.executeQuery(sql, params, attributeReader ); return attributeReader.getResultList(); } catch (SQLException ignored) { logger.error(ignored); throw new RuntimeException(ignored); } } /* (non-Javadoc) * @see eionet.eunis.dao.ISpeciesFactsheetDao#getExpectedInSiteIds(int, int) */ public List<String> getExpectedInSiteIds(int idNatureObject, int idSpecies, int limit) { // String sql = "SELECT DISTINCT ID_SITE FROM CHM62EDT_NATURE_OBJECT_REPORT_TYPE R " + // "INNER JOIN CHM62EDT_SITES S ON R.ID_NATURE_OBJECT=S.ID_NATURE_OBJECT " + // "WHERE ID_NATURE_OBJECT_LINK= ? ORDER BY ID_SITE "; String synonymsIDs = SpeciesFactsheet.getSpeciesSynonymsCommaSeparated(idNatureObject, idSpecies); String sql = "SELECT C.ID_SITE " + " FROM CHM62EDT_SPECIES AS A " + " INNER JOIN CHM62EDT_NATURE_OBJECT_REPORT_TYPE AS B ON A.ID_NATURE_OBJECT = B.ID_NATURE_OBJECT_LINK " + " INNER JOIN CHM62EDT_SITES AS C ON B.ID_NATURE_OBJECT = C.ID_NATURE_OBJECT " + - " WHERE A.ID_NATURE_OBJECT IN ( " + synonymsIDs + " ) ORDER BY C.ID_SITE"; + " WHERE A.ID_NATURE_OBJECT IN ( " + synonymsIDs + " ) " + + " GROUP BY C.ID_NATURE_OBJECT " + + " ORDER BY C.ID_SITE"; List<Object> params = new LinkedList<Object>(); if (limit > 0) { sql += " LIMIT ?"; params.add(limit); } SQLUtilities utils = getSqlUtils(); try { return utils.executeQuery(sql, params); } catch(SQLException ignored) { logger.error(ignored); throw new RuntimeException(ignored); } } }
true
true
public List<String> getExpectedInSiteIds(int idNatureObject, int idSpecies, int limit) { // String sql = "SELECT DISTINCT ID_SITE FROM CHM62EDT_NATURE_OBJECT_REPORT_TYPE R " + // "INNER JOIN CHM62EDT_SITES S ON R.ID_NATURE_OBJECT=S.ID_NATURE_OBJECT " + // "WHERE ID_NATURE_OBJECT_LINK= ? ORDER BY ID_SITE "; String synonymsIDs = SpeciesFactsheet.getSpeciesSynonymsCommaSeparated(idNatureObject, idSpecies); String sql = "SELECT C.ID_SITE " + " FROM CHM62EDT_SPECIES AS A " + " INNER JOIN CHM62EDT_NATURE_OBJECT_REPORT_TYPE AS B ON A.ID_NATURE_OBJECT = B.ID_NATURE_OBJECT_LINK " + " INNER JOIN CHM62EDT_SITES AS C ON B.ID_NATURE_OBJECT = C.ID_NATURE_OBJECT " + " WHERE A.ID_NATURE_OBJECT IN ( " + synonymsIDs + " ) ORDER BY C.ID_SITE"; List<Object> params = new LinkedList<Object>(); if (limit > 0) { sql += " LIMIT ?"; params.add(limit); } SQLUtilities utils = getSqlUtils(); try { return utils.executeQuery(sql, params); } catch(SQLException ignored) { logger.error(ignored); throw new RuntimeException(ignored); } }
public List<String> getExpectedInSiteIds(int idNatureObject, int idSpecies, int limit) { // String sql = "SELECT DISTINCT ID_SITE FROM CHM62EDT_NATURE_OBJECT_REPORT_TYPE R " + // "INNER JOIN CHM62EDT_SITES S ON R.ID_NATURE_OBJECT=S.ID_NATURE_OBJECT " + // "WHERE ID_NATURE_OBJECT_LINK= ? ORDER BY ID_SITE "; String synonymsIDs = SpeciesFactsheet.getSpeciesSynonymsCommaSeparated(idNatureObject, idSpecies); String sql = "SELECT C.ID_SITE " + " FROM CHM62EDT_SPECIES AS A " + " INNER JOIN CHM62EDT_NATURE_OBJECT_REPORT_TYPE AS B ON A.ID_NATURE_OBJECT = B.ID_NATURE_OBJECT_LINK " + " INNER JOIN CHM62EDT_SITES AS C ON B.ID_NATURE_OBJECT = C.ID_NATURE_OBJECT " + " WHERE A.ID_NATURE_OBJECT IN ( " + synonymsIDs + " ) " + " GROUP BY C.ID_NATURE_OBJECT " + " ORDER BY C.ID_SITE"; List<Object> params = new LinkedList<Object>(); if (limit > 0) { sql += " LIMIT ?"; params.add(limit); } SQLUtilities utils = getSqlUtils(); try { return utils.executeQuery(sql, params); } catch(SQLException ignored) { logger.error(ignored); throw new RuntimeException(ignored); } }
diff --git a/amibe/src/org/jcae/mesh/amibe/algos3d/QEMDecimateHalfEdge.java b/amibe/src/org/jcae/mesh/amibe/algos3d/QEMDecimateHalfEdge.java index e4827329..0800415e 100644 --- a/amibe/src/org/jcae/mesh/amibe/algos3d/QEMDecimateHalfEdge.java +++ b/amibe/src/org/jcae/mesh/amibe/algos3d/QEMDecimateHalfEdge.java @@ -1,662 +1,671 @@ /* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD modeler, Finite element mesher, Plugin architecture. Copyright (C) 2003,2006 by EADS CRC Copyright (C) 2007,2008,2009,2010, by EADS France This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jcae.mesh.amibe.algos3d; import org.jcae.mesh.amibe.ds.Mesh; import org.jcae.mesh.amibe.ds.HalfEdge; import org.jcae.mesh.amibe.ds.Triangle; import org.jcae.mesh.amibe.ds.Vertex; import org.jcae.mesh.amibe.ds.AbstractHalfEdge; import org.jcae.mesh.amibe.metrics.Matrix3D; import org.jcae.mesh.amibe.projection.MeshLiaison; import org.jcae.mesh.xmldata.MeshReader; import org.jcae.mesh.xmldata.MeshWriter; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.io.File; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; /** * Decimates a mesh. This method is based on Michael Garland's work on * <a href="http://graphics.cs.uiuc.edu/~garland/research/quadrics.html">quadric error metrics</a>. * * <p> * A plane is fully determined by its normal <code>N</code> and the signed * distance <code>d</code> of the frame origin to this plane, or in other * words the equation of this plane is <code>tN V + d = 0</code>. * The squared distance of a point to this plane is * </p> * <pre> * D*D = (tN V + d) * (tN V + d) * = tV (N tN) V + 2d tN V + d*d * = tV A V + 2 tB V + c * </pre> * <p> * The quadric <code>Q=(A,B,c)=(N tN, dN, d*d)</code> is thus naturally * defined. Addition of these quadrics have a simple form: * <code>Q1(V)+Q2(V)=(Q1+Q2)(V)</code> with * <code>Q1+Q2=(A1+A2, B1+B2, c1+c2)</code> * To compute the squared distance of a point to a set of planes, we can * then compute this quadric for each plane and sum each element of * these quadrics. * </p> * * <p> * When an edge <code>(V1,V2)</code> is contracted into <code>V3</code>, * <code>Q1(V3)+Q2(V3)</code> represents the deviation to the set of * planes at <code>V1</code> and <code>V2</code>. The cost of this * contraction is thus defined as <code>Q1(V3)+Q2(V3)</code>. * We want to minimize this error. It can be shown that if <code>A</code> * is non singular, the optimal placement is for <code>V3=-inv(A) B</code>. * </p> * * <p> * The algorithm is straightforward: * </p> * <ol> * <li>Quadrics are computed for all vertices.</li> * <li>For each edge, compute the optimal placement and its cost.</li> * <li>Loop on edges: starting with the lowest cost, each edge is processed * until its cost is greater than the desired tolerance, and costs * of adjacent edges are updated.</li> * </ol> * * <p> * The real implementation is slightly modified: * </p> * <ol type='a'> * <li>Some checks must be performed to make sure that edge contraction does * not modify the topology of the mesh.</li> * <li>Optimal placement strategy can be chosen at run time among several * choices.</li> * <li>Boundary edges have to be preserved, otherwise they * will shrink. Virtual planes are added perpendicular to triangles at * boundaries so that vertices can be decimated along those edges, but * edges are stuck on their boundary. Garland's thesis dissertation * contains all informations about this process.</li> * <li>Weights are added to compute quadrics, as described in Garland's * dissertation.</li> * <li>Edges are swapped after being contracted to improve triangle quality, * as described by Frey in * <a href="http://www.lis.inpg.fr/pages_perso/attali/DEA-IVR/PAPERS/frey00.ps">About Surface Remeshing</a>.</li> * </ol> */ public class QEMDecimateHalfEdge extends AbstractAlgoHalfEdge { private static final Logger LOGGER=Logger.getLogger(QEMDecimateHalfEdge.class.getName()); private Quadric3DError.Placement placement = Quadric3DError.Placement.OPTIMAL; private HashMap<Vertex, Quadric3DError> quadricMap = null; private final MeshLiaison liaison; private boolean freeEdgesOnly = false; private Vertex v3; private Quadric3DError q3 = new Quadric3DError(); // vCostOpt and qCostOpt must be used only by cost() method. // Their aim is to avoid creating new objects for each cost() call. private final Vertex vCostOpt; private final Quadric3DError qCostOpt = new Quadric3DError(); private static final boolean testDump = false; /** * Creates a <code>QEMDecimateHalfEdge</code> instance. * * @param m the <code>Mesh</code> instance to refine. * @param options map containing key-value pairs to modify algorithm * behaviour. Valid keys are <code>size</code>, * <code>placement</code> and <code>maxtriangles</code>. */ public QEMDecimateHalfEdge(final Mesh m, final Map<String, String> options) { this(m, null, options); } public QEMDecimateHalfEdge(final MeshLiaison liaison, final Map<String, String> options) { this(liaison.getMesh(), liaison, options); } private QEMDecimateHalfEdge(final Mesh m, final MeshLiaison meshLiaison, final Map<String, String> options) { super(m); liaison = meshLiaison; v3 = m.createVertex(0.0, 0.0, 0.0); vCostOpt = m.createVertex(0.0, 0.0, 0.0); for (final Map.Entry<String, String> opt: options.entrySet()) { final String key = opt.getKey(); final String val = opt.getValue(); if (key.equals("size")) { final double sizeTarget = Double.parseDouble(val); tolerance = sizeTarget * sizeTarget; LOGGER.fine("Tolerance: "+tolerance); } else if (key.equals("placement")) { placement = Quadric3DError.Placement.getByName(val); LOGGER.fine("Placement: "+placement); } else if (key.equals("maxtriangles")) { nrFinal = Integer.valueOf(val).intValue(); LOGGER.fine("Nr max triangles: "+nrFinal); } else if (key.equals("maxlength")) { maxEdgeLength = Double.parseDouble(val); LOGGER.fine("Max edge length: "+maxEdgeLength); maxEdgeLength = maxEdgeLength*maxEdgeLength; } else if (key.equals("coplanarity")) { minCos = Double.parseDouble(val); LOGGER.fine("Minimum dot product of face normals allowed for swapping an edge: "+minCos); } else if ("freeEdgesOnly".equals(key)) { freeEdgesOnly = Boolean.parseBoolean(val); LOGGER.fine("freeEdgesOnly: "+freeEdgesOnly); } else throw new RuntimeException("Unknown option: "+key); } if (meshLiaison == null) mesh.buildRidges(minCos); if (freeEdgesOnly) setNoSwapAfterProcessing(true); } @Override public Logger thisLogger() { return LOGGER; } @Override public void preProcessAllHalfEdges() { final int roughNrNodes = mesh.getTriangles().size()/2; quadricMap = new HashMap<Vertex, Quadric3DError>(roughNrNodes); for (Triangle af: mesh.getTriangles()) { if (!af.isWritable()) continue; for (int i = 0; i < 3; i++) { final Vertex n = af.vertex[i]; if (!quadricMap.containsKey(n)) quadricMap.put(n, new Quadric3DError()); } } // Compute quadrics final double [] vect1 = new double[3]; final double [] vect2 = new double[3]; final double [] normal = new double[3]; for (Triangle f: mesh.getTriangles()) { if (!f.isWritable()) continue; double [] p0 = f.vertex[0].getUV(); double [] p1 = f.vertex[1].getUV(); double [] p2 = f.vertex[2].getUV(); vect1[0] = p1[0] - p0[0]; vect1[1] = p1[1] - p0[1]; vect1[2] = p1[2] - p0[2]; vect2[0] = p2[0] - p0[0]; vect2[1] = p2[1] - p0[1]; vect2[2] = p2[2] - p0[2]; Matrix3D.prodVect3D(vect1, vect2, normal); double norm = Matrix3D.norm(normal); // This is in fact 2*area, but that does not matter double area = norm; if (tolerance > 0.0) area /= tolerance; if (norm > 1.e-20) { norm = 1.0 / norm; for (int k = 0; k < 3; k++) normal[k] *= norm; } double d = - Matrix3D.prodSca(normal, f.vertex[0].getUV()); for (int i = 0; i < 3; i++) { final Quadric3DError q = quadricMap.get(f.vertex[i]); q.addError(normal, d, area); } // Penalty for boundary triangles HalfEdge e = (HalfEdge) f.getAbstractHalfEdge(); for (int i = 0; i < 3; i++) { e = e.next(); if (e.hasAttributes(AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD)) { for (Iterator<AbstractHalfEdge> it = e.fanIterator(); it.hasNext(); ) { HalfEdge b = (HalfEdge) it.next(); // Add a virtual plane // In his dissertation, Garland suggests to // add a weight proportional to squared edge // length. // Here norm(vect2) == norm(vect1) p0 = b.origin().getUV(); p1 = b.destination().getUV(); vect1[0] = p1[0] - p0[0]; vect1[1] = p1[1] - p0[1]; vect1[2] = p1[2] - p0[2]; Matrix3D.prodVect3D(vect1, normal, vect2); norm = Matrix3D.norm(vect2); if (norm > 1.e-20) { double invNorm = 1.0 / norm; for (int k = 0; k < 3; k++) vect2[k] *= invNorm; } d = - Matrix3D.prodSca(vect2, b.origin().getUV()); final Quadric3DError q1 = quadricMap.get(b.origin()); final Quadric3DError q2 = quadricMap.get(b.destination()); q1.addWeightedError(vect2, d, norm); q2.addWeightedError(vect2, d, norm); } } } } } @Override protected void postComputeTree() { if (testDump) restoreState(); } @Override protected void appendDumpState(final ObjectOutputStream out) throws IOException { out.writeObject(quadricMap); } @SuppressWarnings("unchecked") @Override protected void appendRestoreState(final ObjectInputStream q) throws IOException { try { quadricMap = (HashMap<Vertex, Quadric3DError>) q.readObject(); } catch (final ClassNotFoundException ex) { ex.printStackTrace(); System.exit(-1); } } @Override protected final double cost(final HalfEdge e) { final Vertex o = e.origin(); final Vertex d = e.destination(); if (!o.isMutable() && !d.isMutable()) return Double.MAX_VALUE; final Quadric3DError q1 = quadricMap.get(o); assert q1 != null : o; final Quadric3DError q2 = quadricMap.get(d); assert q2 != null : d; qCostOpt.computeQuadric3DError(q1, q2); qCostOpt.optimalPlacement(o, d, q1, q2, placement, vCostOpt); final double ret = q1.value(vCostOpt.getUV()) + q2.value(vCostOpt.getUV()); // TODO: check why this assertion sometimes fail // assert ret >= -1.e-2 : q1+"\n"+q2+"\n"+ret; return ret; } @Override public boolean canProcessEdge(HalfEdge current) { current = uniqueOrientation(current); if (current.hasAttributes(AbstractHalfEdge.IMMUTABLE)) return false; if (freeEdgesOnly && !current.hasAttributes(AbstractHalfEdge.BOUNDARY)) return false; final Vertex v1 = current.origin(); final Vertex v2 = current.destination(); assert v1 != v2 : current; // If an endpoint is not writable, its neighborhood is // not fully determined and contraction must not be // performed. if (!v1.isWritable() || !v2.isWritable()) return false; if (!v1.isMutable() && !v2.isMutable()) return false; /* FIXME: add an option so that boundary nodes may be frozen. */ final Quadric3DError q1 = quadricMap.get(v1); final Quadric3DError q2 = quadricMap.get(v2); assert q1 != null : v1; assert q2 != null : v2; q3.computeQuadric3DError(q1, q2); q3.optimalPlacement(v1, v2, q1, q2, placement, v3); if (!mesh.canCollapseEdge(current, v3)) return false; if (maxEdgeLength > 0.0) { for (Iterator<Vertex> itnv = v1.getNeighbourIteratorVertex(); itnv.hasNext(); ) { Vertex n = itnv.next(); if (n != mesh.outerVertex && v3.sqrDistance3D(n) > maxEdgeLength) return false; } for (Iterator<Vertex> itnv = v2.getNeighbourIteratorVertex(); itnv.hasNext(); ) { Vertex n = itnv.next(); if (n != mesh.outerVertex && v3.sqrDistance3D(n) > maxEdgeLength) return false; } } return true; } @Override public void preProcessEdge() { if (testDump) dumpState(); } @Override public HalfEdge processEdge(HalfEdge current, double costCurrent) { current = uniqueOrientation(current); + Vertex v1 = current.origin(); + Vertex v2 = current.destination(); + // If v1 or v2 are on a beam, they must not be replaced by v3, + // otherwise beams are no more connected to triangles. + if (!v1.isMutable()) + v3 = v1; + else if (!v2.isMutable()) + v3 = v2; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Contract edge: "+current+" into "+v3+" cost="+costCurrent); if (current.hasAttributes(AbstractHalfEdge.NONMANIFOLD)) { LOGGER.fine("Non-manifold edge:"); for (Iterator<AbstractHalfEdge> it = current.fanIterator(); it.hasNext(); ) LOGGER.fine(" --> "+it.next()); } } // HalfEdge instances on t1 and t2 will be deleted // when edge is contracted, and we do not know whether // they appear within tree or their symmetric ones, // so remove them now. for (Iterator<AbstractHalfEdge> it = current.fanIterator(); it.hasNext(); ) { HalfEdge f = (HalfEdge) it.next(); HalfEdge h = uniqueOrientation(f); if (!tree.remove(h)) notInTree++; assert !tree.contains(h); h.clearAttributes(AbstractHalfEdge.MARKED); if (f.getTri().isWritable()) { nrTriangles--; for (int i = 0; i < 2; i++) { f = f.next(); removeFromTree(f); } f = f.next(); } } HalfEdge sym = current.sym(); if (sym.getTri().isWritable()) { nrTriangles--; for (int i = 0; i < 2; i++) { sym = sym.next(); removeFromTree(sym); } sym = sym.next(); } // Contract (v1,v2) into v3 // By convention, collapse() returns edge (v3, apex) assert (!current.hasAttributes(AbstractHalfEdge.OUTER)); final Vertex apex = current.apex(); - Vertex v1 = current.origin(); - Vertex v2 = current.destination(); - // If v1 and v2 are manifold, they are removed from the - // mesh and can be reused. + // If v1 or v2 are manifold, they are removed from the + // mesh and can be reused. There is a problem vith vertex + // on beams, they may be considered as manifold whereas they + // are not. Add an isMutable() test, but ideally isManifold() + // should get fixed. Vertex vFree = null; Quadric3DError qFree = null; - if (v1.isManifold()) + if (v1.isManifold() && v1.isMutable()) { vFree = v1; qFree = quadricMap.remove(vFree); } - if (v2.isManifold()) + if (v2.isManifold() && v2.isMutable()) { vFree = v2; qFree = quadricMap.remove(vFree); } current = (HalfEdge) mesh.edgeCollapse(current, v3); if (liaison != null) { Triangle bg1T = liaison.removeVertex(v1); Triangle bg2T = liaison.removeVertex(v2); if (v3.sqrDistance3D(v1) < v3.sqrDistance3D(v2)) liaison.addVertex(v3, bg1T); else liaison.addVertex(v3, bg2T); } // Now current == (v3*a) // Update edge costs quadricMap.put(v3, q3); assert current != null : v3+" not connected to "+apex; assert current.origin() == v3 : ""+current+"\n"+v3+"\n"+apex; assert current.apex() == apex : ""+current+"\n"+v3+"\n"+apex; v3 = vFree; if (v3 == null) v3 = mesh.createVertex(0.0, 0.0, 0.0); q3 = qFree; if (q3 == null) q3 = new Quadric3DError(); updateIncidentEdges(current); if (!freeEdgesOnly && minCos >= -1.0) checkAndSwapAroundOrigin(current); return current.next(); } private void updateIncidentEdges(HalfEdge current) { Vertex o = current.origin(); if (!o.isReadable()) return; if (o.isManifold()) { Vertex apex = current.apex(); do { current = current.nextOriginLoop(); assert !current.hasAttributes(AbstractHalfEdge.NONMANIFOLD); if (current.destination().isReadable()) { double newCost = cost(current); HalfEdge h = uniqueOrientation(current); if (tree.contains(h)) tree.update(h, newCost); else { tree.insert(h, newCost); h.setAttributes(AbstractHalfEdge.MARKED); } } } while (current.apex() != apex); return; } Triangle [] list = (Triangle []) o.getLink(); for (Triangle t: list) { HalfEdge f = (HalfEdge) t.getAbstractHalfEdge(); if (f.destination() == o) f = f.next(); else if (f.apex() == o) f = f.prev(); assert f.origin() == o; Vertex d = f.destination(); do { f = f.nextOriginLoop(); if (f.destination().isReadable()) { double newCost = cost(f); HalfEdge h = uniqueOrientation(f); if (tree.contains(h)) tree.update(h, newCost); else { tree.insert(h, newCost); h.setAttributes(AbstractHalfEdge.MARKED); } } } while (f.destination() != d); } } private void checkAndSwapAroundOrigin(HalfEdge current) { Vertex d = current.destination(); boolean redo = true; while(redo) { redo = false; while(true) { if (current.checkSwap3D(mesh, minCos, maxEdgeLength) >= 0.0) { // Swap edge for (int i = 0; i < 3; i++) { current = current.next(); removeFromTree(current); } HalfEdge sym = current.sym(); for (int i = 0; i < 2; i++) { sym = sym.next(); removeFromTree(sym); } Vertex a = current.apex(); boolean updateDestination = current.destination() == d; current = (HalfEdge) mesh.edgeSwap(current); swapped++; redo = true; if (updateDestination) d = current.destination(); assert a == current.apex(); for (int i = 0; i < 3; i++) { current = current.next(); for (Iterator<AbstractHalfEdge> it = current.fanIterator(); it.hasNext(); ) { HalfEdge e = uniqueOrientation((HalfEdge) it.next()); addToTree(e); } } sym = current.next().sym(); for (int i = 0; i < 2; i++) { sym = sym.next(); for (Iterator<AbstractHalfEdge> it = sym.fanIterator(); it.hasNext(); ) { HalfEdge e = uniqueOrientation((HalfEdge) it.next()); addToTree(e); } } } else { current = current.nextOriginLoop(); if (current.destination() == d) break; } } } } @Override public void postProcessAllHalfEdges() { if (liaison != null) liaison.updateAll(); LOGGER.info("Number of contracted edges: "+processed); LOGGER.info("Total number of edges not contracted during processing: "+notProcessed); LOGGER.info("Total number of edges swapped to increase quality: "+swapped); //LOGGER.info("Number of edges which were not in the binary tree before being removed: "+notInTree); LOGGER.info("Number of edges still present in the binary tree: "+tree.size()); } private final static String usageString = "<xmlDir> <-t tolerance | -n nrTriangles> <brepFile> <outputDir>"; /** * * @param args xmlDir, -t tolerance | -n triangle, brepFile, output */ public static void main(final String[] args) { final HashMap<String, String> options = new HashMap<String, String>(); if(args.length != 5) { System.out.println(usageString); return; } if(args[1].equals("-n")) options.put("maxtriangles", args[2]); else if(args[1].equals("-t")) options.put("size", args[2]); else { System.out.println(usageString); return; } LOGGER.info("Load geometry file"); final Mesh mesh = new Mesh(); try { MeshReader.readObject3D(mesh, args[0]); } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } new QEMDecimateHalfEdge(mesh, options).compute(); final File brepFile=new File(args[3]); try { MeshWriter.writeObject3D(mesh, args[4], brepFile.getName()); } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } }
false
true
public HalfEdge processEdge(HalfEdge current, double costCurrent) { current = uniqueOrientation(current); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Contract edge: "+current+" into "+v3+" cost="+costCurrent); if (current.hasAttributes(AbstractHalfEdge.NONMANIFOLD)) { LOGGER.fine("Non-manifold edge:"); for (Iterator<AbstractHalfEdge> it = current.fanIterator(); it.hasNext(); ) LOGGER.fine(" --> "+it.next()); } } // HalfEdge instances on t1 and t2 will be deleted // when edge is contracted, and we do not know whether // they appear within tree or their symmetric ones, // so remove them now. for (Iterator<AbstractHalfEdge> it = current.fanIterator(); it.hasNext(); ) { HalfEdge f = (HalfEdge) it.next(); HalfEdge h = uniqueOrientation(f); if (!tree.remove(h)) notInTree++; assert !tree.contains(h); h.clearAttributes(AbstractHalfEdge.MARKED); if (f.getTri().isWritable()) { nrTriangles--; for (int i = 0; i < 2; i++) { f = f.next(); removeFromTree(f); } f = f.next(); } } HalfEdge sym = current.sym(); if (sym.getTri().isWritable()) { nrTriangles--; for (int i = 0; i < 2; i++) { sym = sym.next(); removeFromTree(sym); } sym = sym.next(); } // Contract (v1,v2) into v3 // By convention, collapse() returns edge (v3, apex) assert (!current.hasAttributes(AbstractHalfEdge.OUTER)); final Vertex apex = current.apex(); Vertex v1 = current.origin(); Vertex v2 = current.destination(); // If v1 and v2 are manifold, they are removed from the // mesh and can be reused. Vertex vFree = null; Quadric3DError qFree = null; if (v1.isManifold()) { vFree = v1; qFree = quadricMap.remove(vFree); } if (v2.isManifold()) { vFree = v2; qFree = quadricMap.remove(vFree); } current = (HalfEdge) mesh.edgeCollapse(current, v3); if (liaison != null) { Triangle bg1T = liaison.removeVertex(v1); Triangle bg2T = liaison.removeVertex(v2); if (v3.sqrDistance3D(v1) < v3.sqrDistance3D(v2)) liaison.addVertex(v3, bg1T); else liaison.addVertex(v3, bg2T); } // Now current == (v3*a) // Update edge costs quadricMap.put(v3, q3); assert current != null : v3+" not connected to "+apex; assert current.origin() == v3 : ""+current+"\n"+v3+"\n"+apex; assert current.apex() == apex : ""+current+"\n"+v3+"\n"+apex; v3 = vFree; if (v3 == null) v3 = mesh.createVertex(0.0, 0.0, 0.0); q3 = qFree; if (q3 == null) q3 = new Quadric3DError(); updateIncidentEdges(current); if (!freeEdgesOnly && minCos >= -1.0) checkAndSwapAroundOrigin(current); return current.next(); }
public HalfEdge processEdge(HalfEdge current, double costCurrent) { current = uniqueOrientation(current); Vertex v1 = current.origin(); Vertex v2 = current.destination(); // If v1 or v2 are on a beam, they must not be replaced by v3, // otherwise beams are no more connected to triangles. if (!v1.isMutable()) v3 = v1; else if (!v2.isMutable()) v3 = v2; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Contract edge: "+current+" into "+v3+" cost="+costCurrent); if (current.hasAttributes(AbstractHalfEdge.NONMANIFOLD)) { LOGGER.fine("Non-manifold edge:"); for (Iterator<AbstractHalfEdge> it = current.fanIterator(); it.hasNext(); ) LOGGER.fine(" --> "+it.next()); } } // HalfEdge instances on t1 and t2 will be deleted // when edge is contracted, and we do not know whether // they appear within tree or their symmetric ones, // so remove them now. for (Iterator<AbstractHalfEdge> it = current.fanIterator(); it.hasNext(); ) { HalfEdge f = (HalfEdge) it.next(); HalfEdge h = uniqueOrientation(f); if (!tree.remove(h)) notInTree++; assert !tree.contains(h); h.clearAttributes(AbstractHalfEdge.MARKED); if (f.getTri().isWritable()) { nrTriangles--; for (int i = 0; i < 2; i++) { f = f.next(); removeFromTree(f); } f = f.next(); } } HalfEdge sym = current.sym(); if (sym.getTri().isWritable()) { nrTriangles--; for (int i = 0; i < 2; i++) { sym = sym.next(); removeFromTree(sym); } sym = sym.next(); } // Contract (v1,v2) into v3 // By convention, collapse() returns edge (v3, apex) assert (!current.hasAttributes(AbstractHalfEdge.OUTER)); final Vertex apex = current.apex(); // If v1 or v2 are manifold, they are removed from the // mesh and can be reused. There is a problem vith vertex // on beams, they may be considered as manifold whereas they // are not. Add an isMutable() test, but ideally isManifold() // should get fixed. Vertex vFree = null; Quadric3DError qFree = null; if (v1.isManifold() && v1.isMutable()) { vFree = v1; qFree = quadricMap.remove(vFree); } if (v2.isManifold() && v2.isMutable()) { vFree = v2; qFree = quadricMap.remove(vFree); } current = (HalfEdge) mesh.edgeCollapse(current, v3); if (liaison != null) { Triangle bg1T = liaison.removeVertex(v1); Triangle bg2T = liaison.removeVertex(v2); if (v3.sqrDistance3D(v1) < v3.sqrDistance3D(v2)) liaison.addVertex(v3, bg1T); else liaison.addVertex(v3, bg2T); } // Now current == (v3*a) // Update edge costs quadricMap.put(v3, q3); assert current != null : v3+" not connected to "+apex; assert current.origin() == v3 : ""+current+"\n"+v3+"\n"+apex; assert current.apex() == apex : ""+current+"\n"+v3+"\n"+apex; v3 = vFree; if (v3 == null) v3 = mesh.createVertex(0.0, 0.0, 0.0); q3 = qFree; if (q3 == null) q3 = new Quadric3DError(); updateIncidentEdges(current); if (!freeEdgesOnly && minCos >= -1.0) checkAndSwapAroundOrigin(current); return current.next(); }
diff --git a/src/main/java/org/mozilla/gecko/fxa/activities/FxAccountSignInActivity.java b/src/main/java/org/mozilla/gecko/fxa/activities/FxAccountSignInActivity.java index eec4f8e11..e8350dbe5 100644 --- a/src/main/java/org/mozilla/gecko/fxa/activities/FxAccountSignInActivity.java +++ b/src/main/java/org/mozilla/gecko/fxa/activities/FxAccountSignInActivity.java @@ -1,140 +1,140 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.fxa.activities; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.mozilla.gecko.R; import org.mozilla.gecko.background.common.log.Logger; import org.mozilla.gecko.background.fxa.FxAccountClient; import org.mozilla.gecko.background.fxa.FxAccountClient10.RequestDelegate; import org.mozilla.gecko.background.fxa.FxAccountClient20; import org.mozilla.gecko.background.fxa.FxAccountClient20.LoginResponse; import org.mozilla.gecko.background.fxa.FxAccountClientException.FxAccountClientRemoteException; import org.mozilla.gecko.background.fxa.PasswordStretcher; import org.mozilla.gecko.background.fxa.QuickPasswordStretcher; import org.mozilla.gecko.fxa.FxAccountConstants; import org.mozilla.gecko.fxa.activities.FxAccountSetupTask.FxAccountSignInTask; import org.mozilla.gecko.sync.setup.activities.ActivityUtils; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; /** * Activity which displays sign in screen to the user. */ public class FxAccountSignInActivity extends FxAccountAbstractSetupActivity { protected static final String LOG_TAG = FxAccountSignInActivity.class.getSimpleName(); private static final int CHILD_REQUEST_CODE = 3; /** * {@inheritDoc} */ @Override public void onCreate(Bundle icicle) { Logger.debug(LOG_TAG, "onCreate(" + icicle + ")"); super.onCreate(icicle); setContentView(R.layout.fxaccount_sign_in); emailEdit = (EditText) ensureFindViewById(null, R.id.email, "email edit"); passwordEdit = (EditText) ensureFindViewById(null, R.id.password, "password edit"); showPasswordButton = (Button) ensureFindViewById(null, R.id.show_password, "show password button"); remoteErrorTextView = (TextView) ensureFindViewById(null, R.id.remote_error, "remote error text view"); button = (Button) ensureFindViewById(null, R.id.button, "sign in button"); progressBar = (ProgressBar) ensureFindViewById(null, R.id.progress, "progress bar"); minimumPasswordLength = 1; // Minimal restriction on passwords entered to sign in. createSignInButton(); addListeners(); updateButtonState(); createShowPasswordButton(); - View signInInsteadLink = ensureFindViewById(null, R.id.create_account_link, "create account instead link"); - signInInsteadLink.setOnClickListener(new OnClickListener() { + View createAccountInsteadLink = ensureFindViewById(null, R.id.create_account_link, "create account instead link"); + createAccountInsteadLink.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FxAccountSignInActivity.this, FxAccountCreateAccountActivity.class); intent.putExtra("email", emailEdit.getText().toString()); intent.putExtra("password", passwordEdit.getText().toString()); // Per http://stackoverflow.com/a/8992365, this triggers a known bug with // the soft keyboard not being shown for the started activity. Why, Android, why? intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivityForResult(intent, CHILD_REQUEST_CODE); } }); // Only set email/password in onCreate; we don't want to overwrite edited values onResume. if (getIntent() != null && getIntent().getExtras() != null) { Bundle bundle = getIntent().getExtras(); emailEdit.setText(bundle.getString("email")); passwordEdit.setText(bundle.getString("password")); } TextView view = (TextView) findViewById(R.id.forgot_password_link); ActivityUtils.linkTextView(view, R.string.fxaccount_sign_in_forgot_password, R.string.fxaccount_link_forgot_password); } /** * We might have switched to the CreateAccount activity; if that activity * succeeds, feed its result back to the authenticator. */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Logger.debug(LOG_TAG, "onActivityResult: " + requestCode); if (requestCode != CHILD_REQUEST_CODE || resultCode != RESULT_OK) { super.onActivityResult(requestCode, resultCode, data); return; } this.setResult(resultCode, data); this.finish(); } public void signIn(String email, String password) { String serverURI = FxAccountConstants.DEFAULT_AUTH_SERVER_ENDPOINT; PasswordStretcher passwordStretcher = new QuickPasswordStretcher(password); // This delegate creates a new Android account on success, opens the // appropriate "success!" activity, and finishes this activity. RequestDelegate<LoginResponse> delegate = new AddAccountDelegate(email, passwordStretcher, serverURI) { @Override public void handleError(Exception e) { showRemoteError(e, R.string.fxaccount_sign_in_unknown_error); } @Override public void handleFailure(FxAccountClientRemoteException e) { showRemoteError(e, R.string.fxaccount_sign_in_unknown_error); } }; Executor executor = Executors.newSingleThreadExecutor(); FxAccountClient client = new FxAccountClient20(serverURI, executor); try { hideRemoteError(); new FxAccountSignInTask(this, this, email, passwordStretcher, client, delegate).execute(); } catch (Exception e) { showRemoteError(e, R.string.fxaccount_sign_in_unknown_error); } } protected void createSignInButton() { button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final String email = emailEdit.getText().toString(); final String password = passwordEdit.getText().toString(); signIn(email, password); } }); } }
true
true
public void onCreate(Bundle icicle) { Logger.debug(LOG_TAG, "onCreate(" + icicle + ")"); super.onCreate(icicle); setContentView(R.layout.fxaccount_sign_in); emailEdit = (EditText) ensureFindViewById(null, R.id.email, "email edit"); passwordEdit = (EditText) ensureFindViewById(null, R.id.password, "password edit"); showPasswordButton = (Button) ensureFindViewById(null, R.id.show_password, "show password button"); remoteErrorTextView = (TextView) ensureFindViewById(null, R.id.remote_error, "remote error text view"); button = (Button) ensureFindViewById(null, R.id.button, "sign in button"); progressBar = (ProgressBar) ensureFindViewById(null, R.id.progress, "progress bar"); minimumPasswordLength = 1; // Minimal restriction on passwords entered to sign in. createSignInButton(); addListeners(); updateButtonState(); createShowPasswordButton(); View signInInsteadLink = ensureFindViewById(null, R.id.create_account_link, "create account instead link"); signInInsteadLink.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FxAccountSignInActivity.this, FxAccountCreateAccountActivity.class); intent.putExtra("email", emailEdit.getText().toString()); intent.putExtra("password", passwordEdit.getText().toString()); // Per http://stackoverflow.com/a/8992365, this triggers a known bug with // the soft keyboard not being shown for the started activity. Why, Android, why? intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivityForResult(intent, CHILD_REQUEST_CODE); } }); // Only set email/password in onCreate; we don't want to overwrite edited values onResume. if (getIntent() != null && getIntent().getExtras() != null) { Bundle bundle = getIntent().getExtras(); emailEdit.setText(bundle.getString("email")); passwordEdit.setText(bundle.getString("password")); } TextView view = (TextView) findViewById(R.id.forgot_password_link); ActivityUtils.linkTextView(view, R.string.fxaccount_sign_in_forgot_password, R.string.fxaccount_link_forgot_password); }
public void onCreate(Bundle icicle) { Logger.debug(LOG_TAG, "onCreate(" + icicle + ")"); super.onCreate(icicle); setContentView(R.layout.fxaccount_sign_in); emailEdit = (EditText) ensureFindViewById(null, R.id.email, "email edit"); passwordEdit = (EditText) ensureFindViewById(null, R.id.password, "password edit"); showPasswordButton = (Button) ensureFindViewById(null, R.id.show_password, "show password button"); remoteErrorTextView = (TextView) ensureFindViewById(null, R.id.remote_error, "remote error text view"); button = (Button) ensureFindViewById(null, R.id.button, "sign in button"); progressBar = (ProgressBar) ensureFindViewById(null, R.id.progress, "progress bar"); minimumPasswordLength = 1; // Minimal restriction on passwords entered to sign in. createSignInButton(); addListeners(); updateButtonState(); createShowPasswordButton(); View createAccountInsteadLink = ensureFindViewById(null, R.id.create_account_link, "create account instead link"); createAccountInsteadLink.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FxAccountSignInActivity.this, FxAccountCreateAccountActivity.class); intent.putExtra("email", emailEdit.getText().toString()); intent.putExtra("password", passwordEdit.getText().toString()); // Per http://stackoverflow.com/a/8992365, this triggers a known bug with // the soft keyboard not being shown for the started activity. Why, Android, why? intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivityForResult(intent, CHILD_REQUEST_CODE); } }); // Only set email/password in onCreate; we don't want to overwrite edited values onResume. if (getIntent() != null && getIntent().getExtras() != null) { Bundle bundle = getIntent().getExtras(); emailEdit.setText(bundle.getString("email")); passwordEdit.setText(bundle.getString("password")); } TextView view = (TextView) findViewById(R.id.forgot_password_link); ActivityUtils.linkTextView(view, R.string.fxaccount_sign_in_forgot_password, R.string.fxaccount_link_forgot_password); }
diff --git a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/javascript/typeinfo/model/impl/RecordTypeImpl.java b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/javascript/typeinfo/model/impl/RecordTypeImpl.java index 301931b7..77595b7a 100644 --- a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/javascript/typeinfo/model/impl/RecordTypeImpl.java +++ b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/javascript/typeinfo/model/impl/RecordTypeImpl.java @@ -1,245 +1,247 @@ /** * Copyright (c) 2011 NumberFour AG * * 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: * NumberFour AG - initial API and Implementation (Alex Panchenko) */ package org.eclipse.dltk.javascript.typeinfo.model.impl; import java.util.Collection; import org.eclipse.dltk.javascript.typeinfo.model.Member; import org.eclipse.dltk.javascript.typeinfo.model.RecordType; import org.eclipse.dltk.javascript.typeinfo.model.TypeInfoModelPackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Record Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.eclipse.dltk.javascript.typeinfo.model.impl.RecordTypeImpl#getMembers <em>Members</em>}</li> * <li>{@link org.eclipse.dltk.javascript.typeinfo.model.impl.RecordTypeImpl#getTypeName <em>Type Name</em>}</li> * </ul> * </p> * * @generated */ public class RecordTypeImpl extends EObjectImpl implements RecordType { /** * The cached value of the '{@link #getMembers() <em>Members</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMembers() * @generated * @ordered */ protected EList<Member> members; /** * The default value of the '{@link #getTypeName() <em>Type Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTypeName() * @generated * @ordered */ protected static final String TYPE_NAME_EDEFAULT = null; /** * The cached value of the '{@link #getTypeName() <em>Type Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTypeName() * @generated * @ordered */ protected String typeName = TYPE_NAME_EDEFAULT; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ protected RecordTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return TypeInfoModelPackage.Literals.RECORD_TYPE; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public EList<Member> getMembers() { if (members == null) { members = new EObjectContainmentEList<Member>(Member.class, this, TypeInfoModelPackage.RECORD_TYPE__MEMBERS); } return members; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getTypeName() { return typeName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTypeName(String newTypeName) { String oldTypeName = typeName; typeName = newTypeName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TypeInfoModelPackage.RECORD_TYPE__TYPE_NAME, oldTypeName, typeName)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ public String getName() { if (typeName != null) { return typeName; } final StringBuilder sb = new StringBuilder(); sb.append('{'); - for (Member member : members) { - if (sb.length() > 1) { - sb.append(','); - } - sb.append(member.getName()); - if (member.getType() != null) { - sb.append(':').append(member.getType().getName()); + if (members != null) { + for (Member member : members) { + if (sb.length() > 1) { + sb.append(','); + } + sb.append(member.getName()); + if (member.getType() != null) { + sb.append(':').append(member.getType().getName()); + } } } sb.append('}'); return sb.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case TypeInfoModelPackage.RECORD_TYPE__MEMBERS: return ((InternalEList<?>)getMembers()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case TypeInfoModelPackage.RECORD_TYPE__MEMBERS: return getMembers(); case TypeInfoModelPackage.RECORD_TYPE__TYPE_NAME: return getTypeName(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TypeInfoModelPackage.RECORD_TYPE__MEMBERS: getMembers().clear(); getMembers().addAll((Collection<? extends Member>)newValue); return; case TypeInfoModelPackage.RECORD_TYPE__TYPE_NAME: setTypeName((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case TypeInfoModelPackage.RECORD_TYPE__MEMBERS: getMembers().clear(); return; case TypeInfoModelPackage.RECORD_TYPE__TYPE_NAME: setTypeName(TYPE_NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case TypeInfoModelPackage.RECORD_TYPE__MEMBERS: return members != null && !members.isEmpty(); case TypeInfoModelPackage.RECORD_TYPE__TYPE_NAME: return TYPE_NAME_EDEFAULT == null ? typeName != null : !TYPE_NAME_EDEFAULT.equals(typeName); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (typeName: "); //$NON-NLS-1$ result.append(typeName); result.append(')'); return result.toString(); } } //RecordTypeImpl
true
true
public String getName() { if (typeName != null) { return typeName; } final StringBuilder sb = new StringBuilder(); sb.append('{'); for (Member member : members) { if (sb.length() > 1) { sb.append(','); } sb.append(member.getName()); if (member.getType() != null) { sb.append(':').append(member.getType().getName()); } } sb.append('}'); return sb.toString(); }
public String getName() { if (typeName != null) { return typeName; } final StringBuilder sb = new StringBuilder(); sb.append('{'); if (members != null) { for (Member member : members) { if (sb.length() > 1) { sb.append(','); } sb.append(member.getName()); if (member.getType() != null) { sb.append(':').append(member.getType().getName()); } } } sb.append('}'); return sb.toString(); }
diff --git a/src/com/memelab/jandig/JandigActivity.java b/src/com/memelab/jandig/JandigActivity.java index a383a59..6e522ce 100755 --- a/src/com/memelab/jandig/JandigActivity.java +++ b/src/com/memelab/jandig/JandigActivity.java @@ -1,412 +1,412 @@ package com.memelab.jandig; import android.os.Bundle; import android.util.Log; import edu.dhbw.andar.ARToolkit; import edu.dhbw.andar.AndARActivity; import edu.dhbw.andar.exceptions.AndARException; import edu.dhbw.andar.interfaces.OpenGLRenderer; //import edu.dhbw.andar.sample.CustomObject; import edu.dhbw.andar.sample.CustomRenderer; //import edu.dhbw.andar.util.IO; import java.io.BufferedReader; //import java.io.BufferedWriter; import java.io.File; //import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; //import java.io.FileReader; //import java.io.FileWriter; import java.io.IOException; //import java.io.InputStreamReader; import java.io.InputStream; //import java.net.URI; import java.text.SimpleDateFormat; import java.util.Calendar; //import java.util.Date; import java.util.Arrays; //import android.app.ProgressDialog; import android.content.ContentValues; //import android.content.ContentResolver; //import android.content.Context; //import android.content.Intent; //import android.content.res.Resources; import android.graphics.Bitmap; //import android.graphics.Bitmap.CompressFormat; import android.net.Uri; import android.os.AsyncTask; //import android.os.Debug; import android.provider.MediaStore; //import android.view.Menu; //import android.view.MenuItem; import android.view.MotionEvent; //import android.view.SurfaceHolder; import android.view.View; import android.view.View.OnTouchListener; import android.widget.Toast; //import edu.dhbw.andarmodelviewer.R; //import edu.dhbw.andobjviewer.graphics.LightingRenderer; import edu.dhbw.andobjviewer.graphics.Model3D; import edu.dhbw.andobjviewer.models.Model; import edu.dhbw.andobjviewer.parser.ObjParser; //import edu.dhbw.andobjviewer.parser.ParseException; //import edu.dhbw.andobjviewer.parser.Util; import edu.dhbw.andobjviewer.util.AssetsFileUtil; import edu.dhbw.andobjviewer.util.BaseFileUtil; //import edu.dhbw.andobjviewer.util.SDCardFileUtil; /** * Example of an application that makes use of the AndAR toolkit. * @author Tobi * */ public class JandigActivity extends AndARActivity { /* tgh: making it compatible with augmentedModelViewer */ public static final boolean DEBUG = false; private static final boolean TESTANDO = false; //CustomObject someObject; ARToolkit artoolkit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSurfaceView().setOnTouchListener(new TouchEventHandler()); if(TESTANDO){ createFromCustomObjects(savedInstanceState); } else{ //createFromAssets(savedInstanceState); createFromDirsInAssets(savedInstanceState); } Toast.makeText(JandigActivity.this, "Jandig 0.3. Toque na tela para tirar uma foto!", Toast.LENGTH_LONG).show(); } // function to register CustomObject objects onto the ARToolkit private void createFromCustomObjects(Bundle savedInstanceState){ OpenGLRenderer renderer = new JandigRenderer();// optional, may be set to null super.setNonARRenderer(renderer);// or might be omited artoolkit = super.getArtoolkit(); /* tgh: associate different color cubes to different .patt files */ try { //register a object for each marker type //CustomObject myObject; //myObject = new CustomObject("test0", "ap0_16x16.patt", 80.0, new double[]{0,0}, new float[]{255,0,0}); //artoolkit.registerARObject(myObject); //myObject = new CustomObject("test1", "ap1_16x16.patt", 80.0, new double[]{0,0}, new float[]{0,255,0}); //artoolkit.registerARObject(myObject); //myObject = new CustomObject("test2", "ap2_16x16.patt", 80.0, new double[]{0,0}, new float[]{0,0,255}); //artoolkit.registerARObject(myObject); ImageObject myImgObject; InputStream ins = getAssets().open("Images/ap0_16x16.png"); myImgObject = new ImageObject("test0", "ap0_16x16.patt", ins, 50.0, new double[]{0,0}); artoolkit.registerARObject(myImgObject); ins = getAssets().open("Images/ap1_16x16.png"); myImgObject = new ImageObject("test0", "ap1_16x16.patt", ins, 50.0, new double[]{0,0}); artoolkit.registerARObject(myImgObject); ins = getAssets().open("Images/ap2_16x16.png"); myImgObject = new ImageObject("test0", "ap2_16x16.patt", ins, 50.0, new double[]{0,0}); artoolkit.registerARObject(myImgObject); } catch (AndARException ex){ // handle the exception, that means: show the user what happened System.out.println(""); } catch(Exception e) { System.out.println(""); } } // function to register objects in the assets directory onto the ARToolkit private void createFromAssets(Bundle savedInstanceState) { OpenGLRenderer renderer = new CustomRenderer(); // optional, may be set to null super.setNonARRenderer(renderer); // or might be omited /* tgh: Model3D... wooohhooooooo!! */ Model model; Model3D model3d; ImageObject imageobject; artoolkit = super.getArtoolkit(); /* tgh: get every file in assets/objModels that ends in .obj * and every file in assets/Images, and associate them with the correct .patt */ try{ /* 3D MODEL FILES*/ // get every obj file in objModels directory, create a Model3D object, // bind it to a pattern and register it in the toolkit final String[] allObjFilesInAssets = getAssets().list("objModels"); for(int i=0; i<allObjFilesInAssets.length; i++) { if(allObjFilesInAssets[i].endsWith(".obj")){ String baseName = allObjFilesInAssets[i].substring(0,allObjFilesInAssets[i].lastIndexOf(".")); String modelFileName = allObjFilesInAssets[i]; BaseFileUtil fileUtil = new AssetsFileUtil(getAssets()); fileUtil.setBaseFolder("objModels/"); ObjParser parser = new ObjParser(fileUtil); if(fileUtil != null) { BufferedReader fileReader = fileUtil.getReaderFromName(modelFileName); if(fileReader != null) { model = parser.parse(modelFileName, fileReader); /* add a check here.... */ if(Arrays.asList(getAssets().list("")).contains(baseName+".patt")){ model3d = new Model3D(baseName, model,baseName+".patt", 80.0); artoolkit.registerARObject(model3d); } else{ // default model3d = new Model3D(model); artoolkit.registerARObject(model3d); } System.out.println("---created Model3D for: "+ allObjFilesInAssets[i]); } } } } /* IMAGE FILES*/ // grab every image file in assets/Images final String[] allImgFilesInAssets = getAssets().list("Images"); for(int i=0; i<allImgFilesInAssets.length; i++) { // maybe add a check for .gif/.GIF/.Gif, .bmp/.BMP/.Bmp, .jpg/.jpeg/.JPG/.JPEG/.Jpg/.Jpeg and .png/.PNG/.Png //if(allImgFilesInAssets[i].endsWith(".obj")) { String baseName = allImgFilesInAssets[i].substring(0,allImgFilesInAssets[i].lastIndexOf(".")); String ImageFileName = allImgFilesInAssets[i]; InputStream ins = getAssets().open("Images/"+ImageFileName); if(Arrays.asList(getAssets().list("")).contains(baseName+".patt")){ imageobject = new ImageObject(baseName, baseName+".patt", ins, 48.0); artoolkit.registerARObject(imageobject); } else{ // default pattern imageobject = new ImageObject(baseName, ins, 48.0); artoolkit.registerARObject(imageobject); } System.out.println("----cretaed ImageObject for: "+ allImgFilesInAssets[i]); } } catch(Exception e){ // handle the exception, that means: show the user what happened System.out.println("Some exception somewhere was thrown"); System.out.println("string: "+e.toString()); System.out.println("message: "+e.getMessage()); if(e.getCause() != null) { System.out.println("cause msg"+e.getCause().getMessage()); } } startPreview(); } // createFromAssets private void createFromDirsInAssets(Bundle savedInstanceState){ OpenGLRenderer renderer = new CustomRenderer(); // optional, may be set to null super.setNonARRenderer(renderer); // or might be omited /* tgh: Model3D... wooohhooooooo!! */ Model model; Model3D model3d; artoolkit = super.getArtoolkit(); // tgh: grab every directory in assets // inside each dir, look for a .obj, or a .png/.gif/.bmp/.jpg // if any of these exist, find a .patt of any name... try{ // for every thing in assets final String[] allFilesInAssets = getAssets().list(""); for(int i=0; i<allFilesInAssets.length; i++) { String patFileName = null; String objFileName = null; String imgFileName = null; // for all files inside directories in assets final String[] allFilesInDir = getAssets().list(allFilesInAssets[i]); for(int j=0; j<allFilesInDir.length; j++) { // detect if there is a .obj if(allFilesInDir[j].endsWith(".obj")){ objFileName = new String(allFilesInDir[j]); } // detect an image else if(allFilesInDir[j].endsWith(".bmp") || allFilesInDir[j].endsWith(".gif") || allFilesInDir[j].endsWith(".jpg") || allFilesInDir[j].endsWith(".png")){ imgFileName = new String(allFilesInDir[j]); } // detect pattern file else if(allFilesInDir[j].endsWith(".patt")){ patFileName = new String(allFilesInDir[j]); } - } + } // for all files in dir // if there is an obj file and a pat file --> it's a 3D .obj if((objFileName!=null) && (patFileName!=null)) { BaseFileUtil fileUtil = new AssetsFileUtil(getAssets()); fileUtil.setBaseFolder(allFilesInAssets[i]+File.separator); ObjParser parser = new ObjParser(fileUtil); BufferedReader fileReader = fileUtil.getReaderFromName(objFileName); model = parser.parse(objFileName, fileReader); model3d = new Model3D(allFilesInAssets[i], model, new String(allFilesInAssets[i]+File.separator+patFileName), 80.0); // hack to overcome the copying procedure in ARToolkit.registerARObject() InputStream in = getAssets().open(allFilesInAssets[i]+File.separator+patFileName); File bf = new File(getFilesDir().getAbsolutePath()+File.separator+allFilesInAssets[i]); if(!bf.exists()){ bf.mkdir(); } OutputStream out = new FileOutputStream(new File(bf,patFileName)); this.bCopy(in, out); artoolkit.registerARObject(model3d); System.out.println("----Created Model3D for: "+ allFilesInAssets[i]+" with "+objFileName+" and "+patFileName); } // if there is an image and a pat file, and no obj // kind of redundant, but sometimes obj models have a png... else if((imgFileName!=null) && (patFileName!=null) && (objFileName == null)) { InputStream ins = getAssets().open(allFilesInAssets[i]+File.separator+imgFileName); ImageObject imageobject = new ImageObject(allFilesInAssets[i], new String(allFilesInAssets[i]+File.separator+patFileName), ins, 48.0); // hack to overcome the copying procedure in ARToolkit.registerARObject() InputStream in = getAssets().open(allFilesInAssets[i]+File.separator+patFileName); File bf = new File(getFilesDir().getAbsolutePath()+File.separator+allFilesInAssets[i]); if(!bf.exists()){ bf.mkdir(); } OutputStream out = new FileOutputStream(new File(bf,patFileName)); this.bCopy(in, out); artoolkit.registerARObject(imageobject); System.out.println("----Created ImageObject for: "+ allFilesInAssets[i]+" with "+imgFileName+" and "+patFileName); } - } - } + } // for all dirs in assets + } // try catch(Exception e){ } } private void bCopy(InputStream in, OutputStream out ) throws IOException { byte[] buffer = new byte[ 0xFFFF ]; for ( int len; (len = in.read(buffer)) != -1; ) out.write( buffer, 0, len ); } /** * Inform the user about exceptions that occurred in background threads. * This exception is rather severe and can not be recovered from. * TODO Inform the user and shut down the application. */ @Override public void uncaughtException(Thread thread, Throwable ex) { Log.e("AndAR EXCEPTION", ex.getMessage()); finish(); } /////////////// class TouchEventHandler implements OnTouchListener { @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_UP) { // some pressure thresholding... if(event.getPressure() > 0.10){ new TakeAsyncScreenshot().execute(); } } return true; } } class TakeAsyncScreenshot extends AsyncTask<Void, Void, Void> { private String errorMsg = null; private File imgDir = new File("/sdcard/Jandig/"); private File imgFile = null; private Calendar calendar = Calendar.getInstance(); private SimpleDateFormat sdfD = new SimpleDateFormat("yyyyMMdd"); private SimpleDateFormat sdfT = new SimpleDateFormat("HHmmss"); @Override protected Void doInBackground(Void... params) { Bitmap bm = takeScreenshot(); try { String date = new String(sdfD.format(calendar.getTime())); String time = new String(sdfT.format(calendar.getTime())); String fname = new String("Jandig_"+date+"_"+time+".jpg"); imgDir.mkdirs(); imgFile = new File(imgDir,fname); // write into media folder ContentValues v = new ContentValues(); long dateTaken = calendar.getTimeInMillis()/1000; v.put(MediaStore.Images.Media.TITLE, fname); v.put(MediaStore.Images.Media.PICASA_ID, fname); v.put(MediaStore.Images.Media.DISPLAY_NAME, "Jandig"); v.put(MediaStore.Images.Media.DESCRIPTION, "Jandig"); v.put(MediaStore.Images.Media.DATE_ADDED, dateTaken); v.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken); v.put(MediaStore.Images.Media.DATE_MODIFIED, dateTaken); v.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); v.put(MediaStore.Images.Media.ORIENTATION, 0); v.put(MediaStore.Images.Media.DATA, imgFile.getAbsolutePath()); Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, v); OutputStream outStream = getContentResolver().openOutputStream(uri); bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream); outStream.flush(); outStream.close(); } catch (FileNotFoundException e) { errorMsg = e.getMessage(); e.printStackTrace(); } catch (IOException e) { errorMsg = e.getMessage(); e.printStackTrace(); } return null; } protected void onPostExecute(Void result) { if((errorMsg == null)&&(imgFile != null)){ //Toast.makeText(JandigActivity.this, "Imagem salva em: "+imgFile.getAbsolutePath(), Toast.LENGTH_SHORT ).show(); Toast.makeText(JandigActivity.this, "Imagem salva", Toast.LENGTH_SHORT ).show(); } else { Toast.makeText(JandigActivity.this, "Erro salvando imagem: "+errorMsg, Toast.LENGTH_SHORT ).show(); } } } // class TakeAsyncScreenshot }
false
true
private void createFromDirsInAssets(Bundle savedInstanceState){ OpenGLRenderer renderer = new CustomRenderer(); // optional, may be set to null super.setNonARRenderer(renderer); // or might be omited /* tgh: Model3D... wooohhooooooo!! */ Model model; Model3D model3d; artoolkit = super.getArtoolkit(); // tgh: grab every directory in assets // inside each dir, look for a .obj, or a .png/.gif/.bmp/.jpg // if any of these exist, find a .patt of any name... try{ // for every thing in assets final String[] allFilesInAssets = getAssets().list(""); for(int i=0; i<allFilesInAssets.length; i++) { String patFileName = null; String objFileName = null; String imgFileName = null; // for all files inside directories in assets final String[] allFilesInDir = getAssets().list(allFilesInAssets[i]); for(int j=0; j<allFilesInDir.length; j++) { // detect if there is a .obj if(allFilesInDir[j].endsWith(".obj")){ objFileName = new String(allFilesInDir[j]); } // detect an image else if(allFilesInDir[j].endsWith(".bmp") || allFilesInDir[j].endsWith(".gif") || allFilesInDir[j].endsWith(".jpg") || allFilesInDir[j].endsWith(".png")){ imgFileName = new String(allFilesInDir[j]); } // detect pattern file else if(allFilesInDir[j].endsWith(".patt")){ patFileName = new String(allFilesInDir[j]); } } // if there is an obj file and a pat file --> it's a 3D .obj if((objFileName!=null) && (patFileName!=null)) { BaseFileUtil fileUtil = new AssetsFileUtil(getAssets()); fileUtil.setBaseFolder(allFilesInAssets[i]+File.separator); ObjParser parser = new ObjParser(fileUtil); BufferedReader fileReader = fileUtil.getReaderFromName(objFileName); model = parser.parse(objFileName, fileReader); model3d = new Model3D(allFilesInAssets[i], model, new String(allFilesInAssets[i]+File.separator+patFileName), 80.0); // hack to overcome the copying procedure in ARToolkit.registerARObject() InputStream in = getAssets().open(allFilesInAssets[i]+File.separator+patFileName); File bf = new File(getFilesDir().getAbsolutePath()+File.separator+allFilesInAssets[i]); if(!bf.exists()){ bf.mkdir(); } OutputStream out = new FileOutputStream(new File(bf,patFileName)); this.bCopy(in, out); artoolkit.registerARObject(model3d); System.out.println("----Created Model3D for: "+ allFilesInAssets[i]+" with "+objFileName+" and "+patFileName); } // if there is an image and a pat file, and no obj // kind of redundant, but sometimes obj models have a png... else if((imgFileName!=null) && (patFileName!=null) && (objFileName == null)) { InputStream ins = getAssets().open(allFilesInAssets[i]+File.separator+imgFileName); ImageObject imageobject = new ImageObject(allFilesInAssets[i], new String(allFilesInAssets[i]+File.separator+patFileName), ins, 48.0); // hack to overcome the copying procedure in ARToolkit.registerARObject() InputStream in = getAssets().open(allFilesInAssets[i]+File.separator+patFileName); File bf = new File(getFilesDir().getAbsolutePath()+File.separator+allFilesInAssets[i]); if(!bf.exists()){ bf.mkdir(); } OutputStream out = new FileOutputStream(new File(bf,patFileName)); this.bCopy(in, out); artoolkit.registerARObject(imageobject); System.out.println("----Created ImageObject for: "+ allFilesInAssets[i]+" with "+imgFileName+" and "+patFileName); } } } catch(Exception e){ } }
private void createFromDirsInAssets(Bundle savedInstanceState){ OpenGLRenderer renderer = new CustomRenderer(); // optional, may be set to null super.setNonARRenderer(renderer); // or might be omited /* tgh: Model3D... wooohhooooooo!! */ Model model; Model3D model3d; artoolkit = super.getArtoolkit(); // tgh: grab every directory in assets // inside each dir, look for a .obj, or a .png/.gif/.bmp/.jpg // if any of these exist, find a .patt of any name... try{ // for every thing in assets final String[] allFilesInAssets = getAssets().list(""); for(int i=0; i<allFilesInAssets.length; i++) { String patFileName = null; String objFileName = null; String imgFileName = null; // for all files inside directories in assets final String[] allFilesInDir = getAssets().list(allFilesInAssets[i]); for(int j=0; j<allFilesInDir.length; j++) { // detect if there is a .obj if(allFilesInDir[j].endsWith(".obj")){ objFileName = new String(allFilesInDir[j]); } // detect an image else if(allFilesInDir[j].endsWith(".bmp") || allFilesInDir[j].endsWith(".gif") || allFilesInDir[j].endsWith(".jpg") || allFilesInDir[j].endsWith(".png")){ imgFileName = new String(allFilesInDir[j]); } // detect pattern file else if(allFilesInDir[j].endsWith(".patt")){ patFileName = new String(allFilesInDir[j]); } } // for all files in dir // if there is an obj file and a pat file --> it's a 3D .obj if((objFileName!=null) && (patFileName!=null)) { BaseFileUtil fileUtil = new AssetsFileUtil(getAssets()); fileUtil.setBaseFolder(allFilesInAssets[i]+File.separator); ObjParser parser = new ObjParser(fileUtil); BufferedReader fileReader = fileUtil.getReaderFromName(objFileName); model = parser.parse(objFileName, fileReader); model3d = new Model3D(allFilesInAssets[i], model, new String(allFilesInAssets[i]+File.separator+patFileName), 80.0); // hack to overcome the copying procedure in ARToolkit.registerARObject() InputStream in = getAssets().open(allFilesInAssets[i]+File.separator+patFileName); File bf = new File(getFilesDir().getAbsolutePath()+File.separator+allFilesInAssets[i]); if(!bf.exists()){ bf.mkdir(); } OutputStream out = new FileOutputStream(new File(bf,patFileName)); this.bCopy(in, out); artoolkit.registerARObject(model3d); System.out.println("----Created Model3D for: "+ allFilesInAssets[i]+" with "+objFileName+" and "+patFileName); } // if there is an image and a pat file, and no obj // kind of redundant, but sometimes obj models have a png... else if((imgFileName!=null) && (patFileName!=null) && (objFileName == null)) { InputStream ins = getAssets().open(allFilesInAssets[i]+File.separator+imgFileName); ImageObject imageobject = new ImageObject(allFilesInAssets[i], new String(allFilesInAssets[i]+File.separator+patFileName), ins, 48.0); // hack to overcome the copying procedure in ARToolkit.registerARObject() InputStream in = getAssets().open(allFilesInAssets[i]+File.separator+patFileName); File bf = new File(getFilesDir().getAbsolutePath()+File.separator+allFilesInAssets[i]); if(!bf.exists()){ bf.mkdir(); } OutputStream out = new FileOutputStream(new File(bf,patFileName)); this.bCopy(in, out); artoolkit.registerARObject(imageobject); System.out.println("----Created ImageObject for: "+ allFilesInAssets[i]+" with "+imgFileName+" and "+patFileName); } } // for all dirs in assets } // try catch(Exception e){ } }
diff --git a/main/src/com/google/refine/exporters/XlsExporter.java b/main/src/com/google/refine/exporters/XlsExporter.java index 8fb50af1..f8a40780 100644 --- a/main/src/com/google/refine/exporters/XlsExporter.java +++ b/main/src/com/google/refine/exporters/XlsExporter.java @@ -1,126 +1,131 @@ package com.google.refine.exporters; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.util.Calendar; import java.util.Date; import java.util.Properties; import org.apache.poi.hssf.usermodel.HSSFHyperlink; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import com.google.refine.ProjectManager; import com.google.refine.browsing.Engine; import com.google.refine.browsing.FilteredRows; import com.google.refine.browsing.RowVisitor; import com.google.refine.model.Cell; import com.google.refine.model.Column; import com.google.refine.model.Project; import com.google.refine.model.Row; public class XlsExporter implements Exporter { public String getContentType() { return "application/xls"; } public boolean takeWriter() { return false; } public void export(Project project, Properties options, Engine engine, Writer writer) throws IOException { throw new RuntimeException("Not implemented"); } public void export(Project project, Properties options, Engine engine, OutputStream outputStream) throws IOException { Workbook wb = new HSSFWorkbook(); Sheet s = wb.createSheet(); wb.setSheetName(0, ProjectManager.singleton.getProjectMetadata(project.id).getName()); int rowCount = 0; { org.apache.poi.ss.usermodel.Row r = s.createRow(rowCount++); int cellCount = 0; for (Column column : project.columnModel.columns) { org.apache.poi.ss.usermodel.Cell c = r.createCell(cellCount++); c.setCellValue(column.getName()); } } { RowVisitor visitor = new RowVisitor() { Sheet sheet; int rowCount; public RowVisitor init(Sheet sheet, int rowCount) { this.sheet = sheet; this.rowCount = rowCount; return this; } @Override public void start(Project project) { // nothing to do } @Override public void end(Project project) { // nothing to do } public boolean visit(Project project, int rowIndex, Row row) { org.apache.poi.ss.usermodel.Row r = sheet.createRow(rowCount++); int cellCount = 0; for (Column column : project.columnModel.columns) { org.apache.poi.ss.usermodel.Cell c = r.createCell(cellCount++); int cellIndex = column.getCellIndex(); if (cellIndex < row.cells.size()) { Cell cell = row.cells.get(cellIndex); if (cell != null) { if (cell.recon != null && cell.recon.match != null) { c.setCellValue(cell.recon.match.name); HSSFHyperlink hl = new HSSFHyperlink(HSSFHyperlink.LINK_URL); hl.setLabel(cell.recon.match.name); hl.setAddress("http://www.freebase.com/view" + cell.recon.match.id); c.setHyperlink(hl); } else if (cell.value != null) { Object v = cell.value; if (v instanceof Number) { c.setCellValue(((Number) v).doubleValue()); } else if (v instanceof Boolean) { c.setCellValue(((Boolean) v).booleanValue()); } else if (v instanceof Date) { c.setCellValue((Date) v); } else if (v instanceof Calendar) { c.setCellValue((Calendar) v); } else if (v instanceof String) { - c.setCellValue((String) v); + String s = (String) v; + if (s.length() > 32767) { + // The maximum length of cell contents (text) is 32,767 characters + s = s.substring(0, 32767); + } + c.setCellValue(s); } } } } } return false; } }.init(s, rowCount); FilteredRows filteredRows = engine.getAllFilteredRows(); filteredRows.accept(project, visitor); } wb.write(outputStream); outputStream.flush(); } }
true
true
public void export(Project project, Properties options, Engine engine, OutputStream outputStream) throws IOException { Workbook wb = new HSSFWorkbook(); Sheet s = wb.createSheet(); wb.setSheetName(0, ProjectManager.singleton.getProjectMetadata(project.id).getName()); int rowCount = 0; { org.apache.poi.ss.usermodel.Row r = s.createRow(rowCount++); int cellCount = 0; for (Column column : project.columnModel.columns) { org.apache.poi.ss.usermodel.Cell c = r.createCell(cellCount++); c.setCellValue(column.getName()); } } { RowVisitor visitor = new RowVisitor() { Sheet sheet; int rowCount; public RowVisitor init(Sheet sheet, int rowCount) { this.sheet = sheet; this.rowCount = rowCount; return this; } @Override public void start(Project project) { // nothing to do } @Override public void end(Project project) { // nothing to do } public boolean visit(Project project, int rowIndex, Row row) { org.apache.poi.ss.usermodel.Row r = sheet.createRow(rowCount++); int cellCount = 0; for (Column column : project.columnModel.columns) { org.apache.poi.ss.usermodel.Cell c = r.createCell(cellCount++); int cellIndex = column.getCellIndex(); if (cellIndex < row.cells.size()) { Cell cell = row.cells.get(cellIndex); if (cell != null) { if (cell.recon != null && cell.recon.match != null) { c.setCellValue(cell.recon.match.name); HSSFHyperlink hl = new HSSFHyperlink(HSSFHyperlink.LINK_URL); hl.setLabel(cell.recon.match.name); hl.setAddress("http://www.freebase.com/view" + cell.recon.match.id); c.setHyperlink(hl); } else if (cell.value != null) { Object v = cell.value; if (v instanceof Number) { c.setCellValue(((Number) v).doubleValue()); } else if (v instanceof Boolean) { c.setCellValue(((Boolean) v).booleanValue()); } else if (v instanceof Date) { c.setCellValue((Date) v); } else if (v instanceof Calendar) { c.setCellValue((Calendar) v); } else if (v instanceof String) { c.setCellValue((String) v); } } } } } return false; } }.init(s, rowCount); FilteredRows filteredRows = engine.getAllFilteredRows(); filteredRows.accept(project, visitor); } wb.write(outputStream); outputStream.flush(); }
public void export(Project project, Properties options, Engine engine, OutputStream outputStream) throws IOException { Workbook wb = new HSSFWorkbook(); Sheet s = wb.createSheet(); wb.setSheetName(0, ProjectManager.singleton.getProjectMetadata(project.id).getName()); int rowCount = 0; { org.apache.poi.ss.usermodel.Row r = s.createRow(rowCount++); int cellCount = 0; for (Column column : project.columnModel.columns) { org.apache.poi.ss.usermodel.Cell c = r.createCell(cellCount++); c.setCellValue(column.getName()); } } { RowVisitor visitor = new RowVisitor() { Sheet sheet; int rowCount; public RowVisitor init(Sheet sheet, int rowCount) { this.sheet = sheet; this.rowCount = rowCount; return this; } @Override public void start(Project project) { // nothing to do } @Override public void end(Project project) { // nothing to do } public boolean visit(Project project, int rowIndex, Row row) { org.apache.poi.ss.usermodel.Row r = sheet.createRow(rowCount++); int cellCount = 0; for (Column column : project.columnModel.columns) { org.apache.poi.ss.usermodel.Cell c = r.createCell(cellCount++); int cellIndex = column.getCellIndex(); if (cellIndex < row.cells.size()) { Cell cell = row.cells.get(cellIndex); if (cell != null) { if (cell.recon != null && cell.recon.match != null) { c.setCellValue(cell.recon.match.name); HSSFHyperlink hl = new HSSFHyperlink(HSSFHyperlink.LINK_URL); hl.setLabel(cell.recon.match.name); hl.setAddress("http://www.freebase.com/view" + cell.recon.match.id); c.setHyperlink(hl); } else if (cell.value != null) { Object v = cell.value; if (v instanceof Number) { c.setCellValue(((Number) v).doubleValue()); } else if (v instanceof Boolean) { c.setCellValue(((Boolean) v).booleanValue()); } else if (v instanceof Date) { c.setCellValue((Date) v); } else if (v instanceof Calendar) { c.setCellValue((Calendar) v); } else if (v instanceof String) { String s = (String) v; if (s.length() > 32767) { // The maximum length of cell contents (text) is 32,767 characters s = s.substring(0, 32767); } c.setCellValue(s); } } } } } return false; } }.init(s, rowCount); FilteredRows filteredRows = engine.getAllFilteredRows(); filteredRows.accept(project, visitor); } wb.write(outputStream); outputStream.flush(); }
diff --git a/src/commons/org/codehaus/groovy/grails/commons/GrailsDomainConfigurationUtil.java b/src/commons/org/codehaus/groovy/grails/commons/GrailsDomainConfigurationUtil.java index 900acdb0c..0a6a85444 100644 --- a/src/commons/org/codehaus/groovy/grails/commons/GrailsDomainConfigurationUtil.java +++ b/src/commons/org/codehaus/groovy/grails/commons/GrailsDomainConfigurationUtil.java @@ -1,222 +1,222 @@ /* Copyright 2004-2005 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.codehaus.groovy.grails.commons; import groovy.lang.GroovyObject; import org.apache.commons.lang.StringUtils; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URL; import java.sql.Blob; import java.sql.Clob; import java.sql.Time; import java.sql.Timestamp; import java.util.*; /** * Utility methods used in configuring the Grails Hibernate integration * * @author Graeme Rocher * @since 18-Feb-2006 */ public class GrailsDomainConfigurationUtil { /** * Configures the relationships between domain classes after they have been all loaded. * * @param domainClasses The domain classes to configure relationships for * @param domainMap The domain class map */ public static void configureDomainClassRelationships(GrailsClass[] domainClasses, Map domainMap) { // configure super/sub class relationships // and configure how domain class properties reference each other for (int i = 0; i < domainClasses.length; i++) { GrailsDomainClass domainClass = (GrailsDomainClass) domainClasses[i]; if(!domainClass.isRoot()) { Class superClass = domainClasses[i].getClazz().getSuperclass(); while(!superClass.equals(Object.class)&&!superClass.equals(GroovyObject.class)) { GrailsDomainClass gdc = (GrailsDomainClass)domainMap.get(superClass.getName()); if (gdc == null || gdc.getSubClasses()==null) break; gdc.getSubClasses().add(domainClasses[i]); superClass = superClass.getSuperclass(); } } GrailsDomainClassProperty[] props = domainClass.getPersistentProperties(); for (int j = 0; j < props.length; j++) { - if(props[j].isAssociation()) { + if(props[j] != null && props[j].isAssociation()) { GrailsDomainClassProperty prop = props[j]; GrailsDomainClass referencedGrailsDomainClass = (GrailsDomainClass)domainMap.get( props[j].getReferencedPropertyType().getName() ); prop.setReferencedDomainClass(referencedGrailsDomainClass); } } } // now configure so that the 'other side' of a property can be resolved by the property itself for (int i = 0; i < domainClasses.length; i++) { GrailsDomainClass domainClass = (GrailsDomainClass) domainClasses[i]; GrailsDomainClassProperty[] props = domainClass.getPersistentProperties(); for (int j = 0; j < props.length; j++) { - if(props[j].isAssociation()) { + if(props[j] != null && props[j].isAssociation()) { GrailsDomainClassProperty prop = props[j]; GrailsDomainClass referenced = prop.getReferencedDomainClass(); if(referenced != null) { boolean isOwnedBy = referenced.isOwningClass(domainClass.getClazz()); prop.setOwningSide(isOwnedBy); String refPropertyName = null; try { refPropertyName = prop.getReferencedPropertyName(); } catch (UnsupportedOperationException e) { // ignore (to support Hibernate entities) } if(!StringUtils.isBlank(refPropertyName)) { prop.setOtherSide(referenced.getPropertyByName(refPropertyName)); } else { GrailsDomainClassProperty[] referencedProperties = referenced.getPersistentProperties(); for (int k = 0; k < referencedProperties.length; k++) { // for bi-directional circular dependencies we don't want the other side // to be equal to self if(prop.equals(referencedProperties[k]) && prop.isBidirectional()) continue; if(domainClasses[i].getClazz().equals(referencedProperties[k].getReferencedPropertyType())) { prop.setOtherSide(referencedProperties[k]); break; } } } } } } } } /** * Returns the ORM frameworks mapping file name for the specified class name * * @param className The class name of the mapped file * @return The mapping file name */ public static String getMappingFileName(String className) { String fileName = className.replaceAll("\\.", "/"); return fileName+=".hbm.xml"; } /** * Returns the association map for the specified domain class * @param domainClass the domain class * @return The association map */ public static Map getAssociationMap(Class domainClass) { Map associationMap = (Map)GrailsClassUtils.getPropertyValueOfNewInstance( domainClass, GrailsDomainClassProperty.RELATES_TO_MANY, Map.class ); if(associationMap == null) { associationMap = (Map)GrailsClassUtils.getPropertyValueOfNewInstance(domainClass, GrailsDomainClassProperty.HAS_MANY, Map.class); if(associationMap == null) { associationMap = Collections.EMPTY_MAP; } } return associationMap; } /** * Retrieves the mappedBy map for the specified class * @param domainClass The domain class * @return The mappedBy map */ public static Map getMappedByMap(Class domainClass) { Map mappedByMap = (Map)GrailsClassUtils.getPropertyValueOfNewInstance(domainClass, GrailsDomainClassProperty.MAPPED_BY, Map.class); if(mappedByMap == null) { return Collections.EMPTY_MAP; } return mappedByMap; } /** * Establish whether its a basic type * * @param prop The domain class property * @return True if it is basic */ public static boolean isBasicType(GrailsDomainClassProperty prop) { if(prop == null)return false; Class propType = prop.getType(); return isBasicType(propType); } private static final Set BASIC_TYPES; static { Set basics = new HashSet(); basics.add( boolean.class.getName()); basics.add( long.class.getName()); basics.add( short.class.getName()); basics.add( int.class.getName()); basics.add( byte.class.getName()); basics.add( float.class.getName()); basics.add( double.class.getName()); basics.add( char.class.getName()); basics.add( Boolean.class.getName()); basics.add( Long.class.getName()); basics.add( Short.class.getName()); basics.add( Integer.class.getName()); basics.add( Byte.class.getName()); basics.add( Float.class.getName()); basics.add( Double.class.getName()); basics.add( Character.class.getName()); basics.add( String.class.getName()); basics.add( java.util.Date.class.getName()); basics.add( Time.class.getName()); basics.add( Timestamp.class.getName()); basics.add( java.sql.Date.class.getName()); basics.add( BigDecimal.class.getName()); basics.add( BigInteger.class.getName()); basics.add( Locale.class.getName()); basics.add( Calendar.class.getName()); basics.add( GregorianCalendar.class.getName()); basics.add( java.util.Currency.class.getName()); basics.add( TimeZone.class.getName()); basics.add( Object.class.getName()); basics.add( Class.class.getName()); basics.add( byte[].class.getName()); basics.add( Byte[].class.getName()); basics.add( char[].class.getName()); basics.add( Character[].class.getName()); basics.add( Blob.class.getName()); basics.add( Clob.class.getName()); basics.add( Serializable.class.getName() ); basics.add( URI.class.getName() ); basics.add( URL.class.getName() ); BASIC_TYPES = Collections.unmodifiableSet( basics ); } public static boolean isBasicType(Class propType) { if(propType.isArray()) { return isBasicType(propType.getComponentType()); } return BASIC_TYPES.contains(propType.getName()); } }
false
true
public static void configureDomainClassRelationships(GrailsClass[] domainClasses, Map domainMap) { // configure super/sub class relationships // and configure how domain class properties reference each other for (int i = 0; i < domainClasses.length; i++) { GrailsDomainClass domainClass = (GrailsDomainClass) domainClasses[i]; if(!domainClass.isRoot()) { Class superClass = domainClasses[i].getClazz().getSuperclass(); while(!superClass.equals(Object.class)&&!superClass.equals(GroovyObject.class)) { GrailsDomainClass gdc = (GrailsDomainClass)domainMap.get(superClass.getName()); if (gdc == null || gdc.getSubClasses()==null) break; gdc.getSubClasses().add(domainClasses[i]); superClass = superClass.getSuperclass(); } } GrailsDomainClassProperty[] props = domainClass.getPersistentProperties(); for (int j = 0; j < props.length; j++) { if(props[j].isAssociation()) { GrailsDomainClassProperty prop = props[j]; GrailsDomainClass referencedGrailsDomainClass = (GrailsDomainClass)domainMap.get( props[j].getReferencedPropertyType().getName() ); prop.setReferencedDomainClass(referencedGrailsDomainClass); } } } // now configure so that the 'other side' of a property can be resolved by the property itself for (int i = 0; i < domainClasses.length; i++) { GrailsDomainClass domainClass = (GrailsDomainClass) domainClasses[i]; GrailsDomainClassProperty[] props = domainClass.getPersistentProperties(); for (int j = 0; j < props.length; j++) { if(props[j].isAssociation()) { GrailsDomainClassProperty prop = props[j]; GrailsDomainClass referenced = prop.getReferencedDomainClass(); if(referenced != null) { boolean isOwnedBy = referenced.isOwningClass(domainClass.getClazz()); prop.setOwningSide(isOwnedBy); String refPropertyName = null; try { refPropertyName = prop.getReferencedPropertyName(); } catch (UnsupportedOperationException e) { // ignore (to support Hibernate entities) } if(!StringUtils.isBlank(refPropertyName)) { prop.setOtherSide(referenced.getPropertyByName(refPropertyName)); } else { GrailsDomainClassProperty[] referencedProperties = referenced.getPersistentProperties(); for (int k = 0; k < referencedProperties.length; k++) { // for bi-directional circular dependencies we don't want the other side // to be equal to self if(prop.equals(referencedProperties[k]) && prop.isBidirectional()) continue; if(domainClasses[i].getClazz().equals(referencedProperties[k].getReferencedPropertyType())) { prop.setOtherSide(referencedProperties[k]); break; } } } } } } } }
public static void configureDomainClassRelationships(GrailsClass[] domainClasses, Map domainMap) { // configure super/sub class relationships // and configure how domain class properties reference each other for (int i = 0; i < domainClasses.length; i++) { GrailsDomainClass domainClass = (GrailsDomainClass) domainClasses[i]; if(!domainClass.isRoot()) { Class superClass = domainClasses[i].getClazz().getSuperclass(); while(!superClass.equals(Object.class)&&!superClass.equals(GroovyObject.class)) { GrailsDomainClass gdc = (GrailsDomainClass)domainMap.get(superClass.getName()); if (gdc == null || gdc.getSubClasses()==null) break; gdc.getSubClasses().add(domainClasses[i]); superClass = superClass.getSuperclass(); } } GrailsDomainClassProperty[] props = domainClass.getPersistentProperties(); for (int j = 0; j < props.length; j++) { if(props[j] != null && props[j].isAssociation()) { GrailsDomainClassProperty prop = props[j]; GrailsDomainClass referencedGrailsDomainClass = (GrailsDomainClass)domainMap.get( props[j].getReferencedPropertyType().getName() ); prop.setReferencedDomainClass(referencedGrailsDomainClass); } } } // now configure so that the 'other side' of a property can be resolved by the property itself for (int i = 0; i < domainClasses.length; i++) { GrailsDomainClass domainClass = (GrailsDomainClass) domainClasses[i]; GrailsDomainClassProperty[] props = domainClass.getPersistentProperties(); for (int j = 0; j < props.length; j++) { if(props[j] != null && props[j].isAssociation()) { GrailsDomainClassProperty prop = props[j]; GrailsDomainClass referenced = prop.getReferencedDomainClass(); if(referenced != null) { boolean isOwnedBy = referenced.isOwningClass(domainClass.getClazz()); prop.setOwningSide(isOwnedBy); String refPropertyName = null; try { refPropertyName = prop.getReferencedPropertyName(); } catch (UnsupportedOperationException e) { // ignore (to support Hibernate entities) } if(!StringUtils.isBlank(refPropertyName)) { prop.setOtherSide(referenced.getPropertyByName(refPropertyName)); } else { GrailsDomainClassProperty[] referencedProperties = referenced.getPersistentProperties(); for (int k = 0; k < referencedProperties.length; k++) { // for bi-directional circular dependencies we don't want the other side // to be equal to self if(prop.equals(referencedProperties[k]) && prop.isBidirectional()) continue; if(domainClasses[i].getClazz().equals(referencedProperties[k].getReferencedPropertyType())) { prop.setOtherSide(referencedProperties[k]); break; } } } } } } } }
diff --git a/src/msf/RpcAsync.java b/src/msf/RpcAsync.java index c7663dd..fe0daf7 100644 --- a/src/msf/RpcAsync.java +++ b/src/msf/RpcAsync.java @@ -1,53 +1,53 @@ package msf; import java.io.*; import java.util.*; public class RpcAsync implements RpcConnection, Async { protected RpcQueue queue; protected RpcConnection connection; public RpcAsync(RpcConnection connection) { this.connection = connection; } public void execute_async(String methodName) { execute_async(methodName, new Object[]{}); } public void execute_async(String methodName, Object[] args) { if (queue == null) { queue = new RpcQueue(connection); } queue.execute(methodName, args); } public Object execute(String methodName) throws IOException { return connection.execute(methodName); } protected Map cache = new HashMap(); public Object execute(String methodName, Object[] params) throws IOException { if (methodName.equals("module.info") || methodName.equals("module.options") || methodName.equals("module.compatible_payloads")) { StringBuilder keysb = new StringBuilder(methodName); - for(int i = 1; i < params.length; i++) + for(int i = 0; i < params.length; i++) keysb.append(params[i].toString()); String key = keysb.toString(); Object result = cache.get(key); if(result != null) { return result; } result = connection.execute(methodName, params); cache.put(key, result); return result; } else { return connection.execute(methodName, params); } } }
true
true
public Object execute(String methodName, Object[] params) throws IOException { if (methodName.equals("module.info") || methodName.equals("module.options") || methodName.equals("module.compatible_payloads")) { StringBuilder keysb = new StringBuilder(methodName); for(int i = 1; i < params.length; i++) keysb.append(params[i].toString()); String key = keysb.toString(); Object result = cache.get(key); if(result != null) { return result; } result = connection.execute(methodName, params); cache.put(key, result); return result; } else { return connection.execute(methodName, params); } }
public Object execute(String methodName, Object[] params) throws IOException { if (methodName.equals("module.info") || methodName.equals("module.options") || methodName.equals("module.compatible_payloads")) { StringBuilder keysb = new StringBuilder(methodName); for(int i = 0; i < params.length; i++) keysb.append(params[i].toString()); String key = keysb.toString(); Object result = cache.get(key); if(result != null) { return result; } result = connection.execute(methodName, params); cache.put(key, result); return result; } else { return connection.execute(methodName, params); } }
diff --git a/src/me/ellbristow/greylistVote/greylistVote.java b/src/me/ellbristow/greylistVote/greylistVote.java index ef31320..28de408 100644 --- a/src/me/ellbristow/greylistVote/greylistVote.java +++ b/src/me/ellbristow/greylistVote/greylistVote.java @@ -1,630 +1,636 @@ package me.ellbristow.greylistVote; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionAttachment; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class greylistVote extends JavaPlugin { public static greylistVote plugin; public final Logger logger = Logger.getLogger("Minecraft"); public final greyBlockListener blockListener = new greyBlockListener(this); public final greyPlayerListener loginListener = new greyPlayerListener(this); protected FileConfiguration config; public FileConfiguration usersConfig = null; private File usersFile = null; @Override public void onDisable() { PluginDescriptionFile pdfFile = this.getDescription(); this.logger.info("[" + pdfFile.getName() + "] is now disabled."); } @Override public void onEnable() { PluginDescriptionFile pdfFile = this.getDescription(); this.logger.info("[" + pdfFile.getName() + "] version " + pdfFile.getVersion() + " is enabled."); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(blockListener, this); pm.registerEvents(loginListener, this); this.config = this.getConfig(); this.config.set("required_votes", this.config.getInt("required_votes", 2)); this.config.set("no_pvp", this.config.getBoolean("no_pvp", true)); this.saveConfig(); this.usersConfig = this.getUsersConfig(); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("glv")) { if (args.length == 0) { PluginDescriptionFile pdfFile = this.getDescription(); sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors()); sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]"); sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands"); sender.sendMessage(ChatColor.GOLD + " /greylist [player] || /gl [player] || /trust Player " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Increase player's reputation"); sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Reduce player's reputation"); sender.sendMessage(ChatColor.GOLD + " /votelist {player} || /glvlist {player} " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " View your (or player's) reputation"); if (sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "Admin Commands:"); sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. rep] " + ChatColor.GRAY + ": Set required reputation"); sender.sendMessage(ChatColor.GOLD + " /glv clearserver [player] " + ChatColor.GRAY + ": Remove player's Server votes"); sender.sendMessage(ChatColor.GOLD + " /glv clearall [player] " + ChatColor.GRAY + ": Remove all player's votes"); } return true; } else if (args.length == 2) { if (!sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "You do not have permission to do that!"); return false; } int reqVotes = config.getInt("required_votes", 2); if (args[0].equalsIgnoreCase("setrep")) { try { reqVotes = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" ); return false; } this.config.set("required_votes", reqVotes); this.saveConfig(); sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]); sender.sendMessage(ChatColor.GOLD + "Player approval will be updated on next login."); return true; } else if (args[0].equalsIgnoreCase("clearserver")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String newVoteList = null; String newGriefList = null; String[] voteArray = null; String[] griefArray = null; if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } if (voteList != null) { voteArray = voteList.split(","); for (String vote : voteArray) { if (!vote.equals("Server")) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList); } if (griefList != null) { griefArray = griefList.split(","); for (String vote : griefArray) { if (!vote.equals("Server")) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); } saveUsersConfig(); int rep = 0; voteArray = null; griefArray = null; if (newVoteList != null) { voteArray = voteList.split(","); for (@SuppressWarnings("unused") String vote : voteArray) { rep++; } } if (griefList != null) { griefArray = griefList.split(","); for (@SuppressWarnings("unused") String vote : griefArray) { rep--; } } sender.sendMessage(ChatColor.GOLD + "'Server' votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.GOLD + "Your Server Approval/Black-Ball votes were removed!"); if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else if (args[0].equalsIgnoreCase("clearall")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } usersConfig.set(target.getName().toLowerCase() + ".votes", null); usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(ChatColor.GOLD + "ALL votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.RED + "Your reputation was reset to 0!"); if (0 >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (0 < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else { sender.sendMessage(ChatColor.RED + "Command not recognised!"); return false; } } return false; } else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl") || commandLabel.equalsIgnoreCase("trust")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { + if (!sender.hasPermission("greylistvote.vote")) { + sender.sendMessage(ChatColor.RED + "You do not have permission to vote!"); + } Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + "!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + " by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to " + reqVotes + " by the Server!"); } } if (!target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setApproved(target); } this.saveUsersConfig(); return true; } if (sender.getName().equalsIgnoreCase(target.getName())) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (voteArray != null) { for (String vote : voteArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newGriefList = null; if (griefArray != null) { for (String vote : griefArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); griefArray = newGriefList.split(","); } else { griefArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); // Tell everyone about the reputation change for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GREEN + " increased your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (voteList.equals("")) { voteList = sender.getName(); } else { voteList = voteList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList); voteArray = voteList.split(","); int rep = 0; if (voteArray.length != 0) { rep += voteArray.length; } if (griefArray != null) { if (griefArray.length != 0) { rep -= griefArray.length; } } if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setApproved(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("griefer")) { + if (!sender.hasPermission("greylistvote.griefer")) { + sender.sendMessage(ChatColor.RED + "You do not have permission to vote!"); + } if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".votes", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1 by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to -1 by the Server!"); } } if (target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setGriefer(target); } this.saveUsersConfig(); return true; } if (sender.getName() == target.getName()) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (griefArray != null) { for (String vote : griefArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newVoteList = null; if (griefArray != null) { for (String vote : voteArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newVoteList); voteArray = newVoteList.split(","); } else { voteArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.RED + " reduced your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (griefList.equals("")) { griefList = sender.getName(); } else { griefList = griefList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".griefer", griefList); griefArray = griefList.split(","); int rep = 0; if (voteArray != null) { rep += voteArray.length; } if (griefArray != null) { rep -= griefArray.length; } if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setGriefer(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) { if (args.equals(null) || args.length == 0) { String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(ChatColor.GOLD + "You have not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(ChatColor.GOLD + "You have received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } else { OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]); String DN = null; String target = null; if (checktarget.isOnline()) { target = checktarget.getPlayer().getName(); DN = checktarget.getPlayer().getDisplayName(); } else { if (checktarget != null) { target = checktarget.getName(); DN = checktarget.getName(); } } if (target == null) { // Player not found sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } } return false; } public void setApproved(Player target) { PermissionAttachment attachment = target.addAttachment(this); attachment.setPermission("greylistvote.build", true); Player[] onlinePlayers = getServer().getOnlinePlayers(); int reqVotes = config.getInt("required_votes"); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has reached " + reqVotes + "!"); chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " can now build!"); } else { chatPlayer.sendMessage(ChatColor.GREEN + "Your reputation has reached " + reqVotes + "!"); chatPlayer.sendMessage(ChatColor.GREEN + "You can now build!"); } } } public void setGriefer(Player target) { PermissionAttachment attachment = target.addAttachment(this); attachment.setPermission("greylistvote.build", false); Player[] onlinePlayers = getServer().getOnlinePlayers(); int reqVotes = config.getInt("required_votes"); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has dropped below " + reqVotes + "!"); chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " can no longer build!"); } else { chatPlayer.sendMessage(ChatColor.RED + "Your reputation has dropped below " + reqVotes + "!"); chatPlayer.sendMessage(ChatColor.RED + "Your build rights have been revoked!"); } } } public void loadUsersConfig() { if (this.usersFile == null) { this.usersFile = new File(getDataFolder(),"users.yml"); } this.usersConfig = YamlConfiguration.loadConfiguration(this.usersFile); } public FileConfiguration getUsersConfig() { if (this.usersConfig == null) { this.loadUsersConfig(); } return this.usersConfig; } public void saveUsersConfig() { if (this.usersConfig == null || this.usersFile == null) { return; } try { this.usersConfig.save(this.usersFile); } catch (IOException ex) { this.logger.log(Level.SEVERE, "Could not save " + this.usersFile, ex ); } } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("glv")) { if (args.length == 0) { PluginDescriptionFile pdfFile = this.getDescription(); sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors()); sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]"); sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands"); sender.sendMessage(ChatColor.GOLD + " /greylist [player] || /gl [player] || /trust Player " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Increase player's reputation"); sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Reduce player's reputation"); sender.sendMessage(ChatColor.GOLD + " /votelist {player} || /glvlist {player} " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " View your (or player's) reputation"); if (sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "Admin Commands:"); sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. rep] " + ChatColor.GRAY + ": Set required reputation"); sender.sendMessage(ChatColor.GOLD + " /glv clearserver [player] " + ChatColor.GRAY + ": Remove player's Server votes"); sender.sendMessage(ChatColor.GOLD + " /glv clearall [player] " + ChatColor.GRAY + ": Remove all player's votes"); } return true; } else if (args.length == 2) { if (!sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "You do not have permission to do that!"); return false; } int reqVotes = config.getInt("required_votes", 2); if (args[0].equalsIgnoreCase("setrep")) { try { reqVotes = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" ); return false; } this.config.set("required_votes", reqVotes); this.saveConfig(); sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]); sender.sendMessage(ChatColor.GOLD + "Player approval will be updated on next login."); return true; } else if (args[0].equalsIgnoreCase("clearserver")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String newVoteList = null; String newGriefList = null; String[] voteArray = null; String[] griefArray = null; if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } if (voteList != null) { voteArray = voteList.split(","); for (String vote : voteArray) { if (!vote.equals("Server")) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList); } if (griefList != null) { griefArray = griefList.split(","); for (String vote : griefArray) { if (!vote.equals("Server")) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); } saveUsersConfig(); int rep = 0; voteArray = null; griefArray = null; if (newVoteList != null) { voteArray = voteList.split(","); for (@SuppressWarnings("unused") String vote : voteArray) { rep++; } } if (griefList != null) { griefArray = griefList.split(","); for (@SuppressWarnings("unused") String vote : griefArray) { rep--; } } sender.sendMessage(ChatColor.GOLD + "'Server' votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.GOLD + "Your Server Approval/Black-Ball votes were removed!"); if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else if (args[0].equalsIgnoreCase("clearall")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } usersConfig.set(target.getName().toLowerCase() + ".votes", null); usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(ChatColor.GOLD + "ALL votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.RED + "Your reputation was reset to 0!"); if (0 >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (0 < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else { sender.sendMessage(ChatColor.RED + "Command not recognised!"); return false; } } return false; } else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl") || commandLabel.equalsIgnoreCase("trust")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + "!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + " by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to " + reqVotes + " by the Server!"); } } if (!target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setApproved(target); } this.saveUsersConfig(); return true; } if (sender.getName().equalsIgnoreCase(target.getName())) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (voteArray != null) { for (String vote : voteArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newGriefList = null; if (griefArray != null) { for (String vote : griefArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); griefArray = newGriefList.split(","); } else { griefArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); // Tell everyone about the reputation change for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GREEN + " increased your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (voteList.equals("")) { voteList = sender.getName(); } else { voteList = voteList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList); voteArray = voteList.split(","); int rep = 0; if (voteArray.length != 0) { rep += voteArray.length; } if (griefArray != null) { if (griefArray.length != 0) { rep -= griefArray.length; } } if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setApproved(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("griefer")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".votes", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1 by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to -1 by the Server!"); } } if (target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setGriefer(target); } this.saveUsersConfig(); return true; } if (sender.getName() == target.getName()) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (griefArray != null) { for (String vote : griefArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newVoteList = null; if (griefArray != null) { for (String vote : voteArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newVoteList); voteArray = newVoteList.split(","); } else { voteArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.RED + " reduced your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (griefList.equals("")) { griefList = sender.getName(); } else { griefList = griefList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".griefer", griefList); griefArray = griefList.split(","); int rep = 0; if (voteArray != null) { rep += voteArray.length; } if (griefArray != null) { rep -= griefArray.length; } if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setGriefer(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) { if (args.equals(null) || args.length == 0) { String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(ChatColor.GOLD + "You have not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(ChatColor.GOLD + "You have received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } else { OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]); String DN = null; String target = null; if (checktarget.isOnline()) { target = checktarget.getPlayer().getName(); DN = checktarget.getPlayer().getDisplayName(); } else { if (checktarget != null) { target = checktarget.getName(); DN = checktarget.getName(); } } if (target == null) { // Player not found sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("glv")) { if (args.length == 0) { PluginDescriptionFile pdfFile = this.getDescription(); sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors()); sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]"); sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands"); sender.sendMessage(ChatColor.GOLD + " /greylist [player] || /gl [player] || /trust Player " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Increase player's reputation"); sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Reduce player's reputation"); sender.sendMessage(ChatColor.GOLD + " /votelist {player} || /glvlist {player} " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " View your (or player's) reputation"); if (sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "Admin Commands:"); sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. rep] " + ChatColor.GRAY + ": Set required reputation"); sender.sendMessage(ChatColor.GOLD + " /glv clearserver [player] " + ChatColor.GRAY + ": Remove player's Server votes"); sender.sendMessage(ChatColor.GOLD + " /glv clearall [player] " + ChatColor.GRAY + ": Remove all player's votes"); } return true; } else if (args.length == 2) { if (!sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "You do not have permission to do that!"); return false; } int reqVotes = config.getInt("required_votes", 2); if (args[0].equalsIgnoreCase("setrep")) { try { reqVotes = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" ); return false; } this.config.set("required_votes", reqVotes); this.saveConfig(); sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]); sender.sendMessage(ChatColor.GOLD + "Player approval will be updated on next login."); return true; } else if (args[0].equalsIgnoreCase("clearserver")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String newVoteList = null; String newGriefList = null; String[] voteArray = null; String[] griefArray = null; if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } if (voteList != null) { voteArray = voteList.split(","); for (String vote : voteArray) { if (!vote.equals("Server")) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList); } if (griefList != null) { griefArray = griefList.split(","); for (String vote : griefArray) { if (!vote.equals("Server")) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); } saveUsersConfig(); int rep = 0; voteArray = null; griefArray = null; if (newVoteList != null) { voteArray = voteList.split(","); for (@SuppressWarnings("unused") String vote : voteArray) { rep++; } } if (griefList != null) { griefArray = griefList.split(","); for (@SuppressWarnings("unused") String vote : griefArray) { rep--; } } sender.sendMessage(ChatColor.GOLD + "'Server' votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.GOLD + "Your Server Approval/Black-Ball votes were removed!"); if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else if (args[0].equalsIgnoreCase("clearall")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } usersConfig.set(target.getName().toLowerCase() + ".votes", null); usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(ChatColor.GOLD + "ALL votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.RED + "Your reputation was reset to 0!"); if (0 >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (0 < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else { sender.sendMessage(ChatColor.RED + "Command not recognised!"); return false; } } return false; } else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl") || commandLabel.equalsIgnoreCase("trust")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { if (!sender.hasPermission("greylistvote.vote")) { sender.sendMessage(ChatColor.RED + "You do not have permission to vote!"); } Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + "!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + " by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to " + reqVotes + " by the Server!"); } } if (!target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setApproved(target); } this.saveUsersConfig(); return true; } if (sender.getName().equalsIgnoreCase(target.getName())) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (voteArray != null) { for (String vote : voteArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newGriefList = null; if (griefArray != null) { for (String vote : griefArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); griefArray = newGriefList.split(","); } else { griefArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); // Tell everyone about the reputation change for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GREEN + " increased your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (voteList.equals("")) { voteList = sender.getName(); } else { voteList = voteList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList); voteArray = voteList.split(","); int rep = 0; if (voteArray.length != 0) { rep += voteArray.length; } if (griefArray != null) { if (griefArray.length != 0) { rep -= griefArray.length; } } if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setApproved(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("griefer")) { if (!sender.hasPermission("greylistvote.griefer")) { sender.sendMessage(ChatColor.RED + "You do not have permission to vote!"); } if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".votes", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1 by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to -1 by the Server!"); } } if (target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setGriefer(target); } this.saveUsersConfig(); return true; } if (sender.getName() == target.getName()) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (griefArray != null) { for (String vote : griefArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newVoteList = null; if (griefArray != null) { for (String vote : voteArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newVoteList); voteArray = newVoteList.split(","); } else { voteArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.RED + " reduced your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (griefList.equals("")) { griefList = sender.getName(); } else { griefList = griefList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".griefer", griefList); griefArray = griefList.split(","); int rep = 0; if (voteArray != null) { rep += voteArray.length; } if (griefArray != null) { rep -= griefArray.length; } if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setGriefer(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) { if (args.equals(null) || args.length == 0) { String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(ChatColor.GOLD + "You have not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(ChatColor.GOLD + "You have received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } else { OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]); String DN = null; String target = null; if (checktarget.isOnline()) { target = checktarget.getPlayer().getName(); DN = checktarget.getPlayer().getDisplayName(); } else { if (checktarget != null) { target = checktarget.getName(); DN = checktarget.getName(); } } if (target == null) { // Player not found sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } } return false; }
diff --git a/src/com/jidesoft/plaf/LookAndFeelFactory.java b/src/com/jidesoft/plaf/LookAndFeelFactory.java index ca75d814..370075d9 100644 --- a/src/com/jidesoft/plaf/LookAndFeelFactory.java +++ b/src/com/jidesoft/plaf/LookAndFeelFactory.java @@ -1,1410 +1,1409 @@ /* * @(#)LookAndFeelFactory.java 5/28/2005 * * Copyright 2002 - 2005 JIDE Software Inc. All rights reserved. */ package com.jidesoft.plaf; import com.jidesoft.icons.IconsFactory; import com.jidesoft.icons.JideIconsFactory; import com.jidesoft.plaf.basic.Painter; import com.jidesoft.plaf.eclipse.Eclipse3xMetalUtils; import com.jidesoft.plaf.eclipse.Eclipse3xWindowsUtils; import com.jidesoft.plaf.eclipse.EclipseMetalUtils; import com.jidesoft.plaf.eclipse.EclipseWindowsUtils; import com.jidesoft.plaf.office2003.Office2003Painter; import com.jidesoft.plaf.office2003.Office2003WindowsUtils; import com.jidesoft.plaf.vsnet.VsnetMetalUtils; import com.jidesoft.plaf.vsnet.VsnetWindowsUtils; import com.jidesoft.plaf.xerto.XertoMetalUtils; import com.jidesoft.plaf.xerto.XertoWindowsUtils; import com.jidesoft.swing.JideSwingUtilities; import com.jidesoft.swing.JideTabbedPane; import com.jidesoft.utils.ProductNames; import com.jidesoft.utils.SecurityUtils; import com.jidesoft.utils.SystemInfo; import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; import sun.swing.SwingLazyValue; import javax.swing.*; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.InsetsUIResource; import javax.swing.plaf.metal.MetalLookAndFeel; import java.awt.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Vector; /** * JIDE Software created many new components that need their own ComponentUI classes and additional UIDefaults in * UIDefaults table. LookAndFeelFactory can take the UIDefaults from any existing look and feel and add the extra * UIDefaults JIDE components need. * <p/> * Before using any JIDE components, please make you call one of the two LookAndFeelFactory.installJideExtension(...) * methods. Bascially, you set L&F using UIManager first just like before, then call installJideExtension. See code * below for an example. * <code><pre> * UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); // you need to catch the * exceptions * on this call. * LookAndFeelFactory.installJideExtension(); * </pre></code> * LookAndFeelFactory.installJideExtension() method will check what kind of L&F you set and what operating system you * are on and decide which style of JIDE extension it will install. Here is the rule. <ul> <li> OS: Windows XP with XP * theme on, L&F: Windows L&F => OFFICE2003_STYLE <li> OS: any Windows, L&F: Windows L&F => VSNET_STYLE <li> OS: Linux, * L&F: any L&F based on Metal L&F => VSNET_STYLE <li> OS: Mac OSX, L&F: Aqua L&F => AQUA_STYLE <li> OS: any OS, L&F: * Quaqua L&F => AQUA_STYLE <li> Otherwise => VSNET_STYLE </ul> There is also another installJideExtension which takes * an int style parameter. You can pass in {@link #VSNET_STYLE}, {@link #ECLIPSE_STYLE}, {@link #ECLIPSE3X_STYLE}, * {@link #OFFICE2003_STYLE}, or {@link #XERTO_STYLE}. In the other word, you will make the choice of style instead of * letting LookAndFeelFactory to decide one for you. Please note, there is no constant defined for AQUA_STYLE. The only * way to use it is when you are using Aqua L&F or Quaqua L&F and you call installJideExtension() method, the one * without parameter. * <p/> * LookAndFeelFactory supports a number of known L&Fs. You can see those L&Fs as constants whose names are something * like "_LNF" such as WINDOWS_LNF. * <p/> * If you are using a 3rd party L&F we are not officially supporting, we might need to customize it. Here are two * classes you can use. The first one is {@link UIDefaultsCustomizer}. You can add a number of customizers to * LookAndFeelFactory. After LookAndFeelFactory installJideExtension method is called, we will call customize() method * on each UIDefaultsCustomizer to add additional UIDefaults you specified. You can use UIDefaultsCustomizer to do * things like small tweaks to UIDefaults without the hassle of creating a new style. * <p/> * Most likely, we will not need to use {@link UIDefaultsInitializer} if you are use L&Fs such as WindowsLookAndFeel, * any L&Fs based on MetalLookAndFeel, or AquaLookAndFeel etc. The only exception is Synth L&F and any L&Fs based on it. * The reason is we calcualte all colors we will use in JIDE components from existing wel-known UIDefaults. For example, * we will use UIManagerLookup.getColor("activeCaption") to calculate a color that we can use in dockable frame's title * pane. We will use UIManagerLookup.getColor("control") to calculate a color that we can use as background of JIDE * component. Most L&Fs will fill those UIDefaults. However in Synth L&F, those UIDefaults may or may not have a valid * value. You will end up with NPE later in the code when you call installJideExtension. In this case, you can add those * extra UIDefaults in UIDefaultsInitializer. We will call it before installJideExtension is called so that those * UIDefaults are there ready for us to use. This is how added support to GTK L&F and Synthethica L&F. * <p/> * {@link #installJideExtension()} method will only add the additional UIDefaults to current ClassLoader. If you have * several class loaders in your system, you probably should tell the UIManager to use the class loader that called * <code>installJideExtension</code>. Otherwise, you might some unexpected errors. Here is how to specify the class * loaders. * <code><pre> * UIManager.put("ClassLoader", currentClass.getClassLoader()); // currentClass is the class where * the code is. * LookAndFeelFactory.installDefaultLookAndFeelAndExtension(); // or installJideExtension() * </pre></code> */ public class LookAndFeelFactory implements ProductNames { /** * Class name of Windows L&F provided in Sun JDK. */ public static final String WINDOWS_LNF = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; /** * Class name of Metal L&F provided in Sun JDK. */ public static final String METAL_LNF = "javax.swing.plaf.metal.MetalLookAndFeel"; /** * Class name of Aqua L&F provided in Apple Mac OSX JDK. */ public static final String AQUA_LNF = "apple.laf.AquaLookAndFeel"; /** * Class name of Quaqua L&F. */ public static final String QUAQUA_LNF = "ch.randelshofer.quaqua.QuaquaLookAndFeel"; /** * Class name of Quaqua Alloy L&F. */ public static final String ALLOY_LNF = "com.incors.plaf.alloy.AlloyLookAndFeel"; /** * Class name of Synthetica L&F. */ public static final String SYNTHETICA_LNF = "de.javasoft.plaf.synthetica.SyntheticaLookAndFeel"; private static final String SYNTHETICA_LNF_PREFIX = "de.javasoft.plaf.synthetica.Synthetica"; /** * Class name of Plastic3D L&F before JGoodies Look 1.3 release. */ public static final String PLASTIC3D_LNF = "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel"; /** * Class name of Plastic3D L&F after JGoodies Look 1.3 release. */ public static final String PLASTIC3D_LNF_1_3 = "com.jgoodies.looks.plastic.Plastic3DLookAndFeel"; /** * Class name of PlasticXP L&F. */ public static final String PLASTICXP_LNF = "com.jgoodies.looks.plastic.PlasticXPLookAndFeel"; /** * Class name of Tonic L&F. */ public static final String TONIC_LNF = "com.digitprop.tonic.TonicLookAndFeel"; /** * Class name of A03 L&F. */ public static final String A03_LNF = "a03.swing.plaf.A03LookAndFeel"; /** * Class name of Pgs L&F. */ public static final String PGS_LNF = "com.pagosoft.plaf.PgsLookAndFeel"; /** * Class name of GTK L&F provided by Sun JDK. */ public static final String GTK_LNF = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"; /** * The name of Nimbus L&F. We didn't create a constant for Nimbus is because the package name will be changed in * JDK7 release */ public static final String NIMBUS_LNF_NAME = "NimbusLookAndFeel"; /** * A style that you can use with {@link #installJideExtension(int)} method. This style is the same as VSNET_STYLE * except it doesn't have menu related UIDefaults. You can only use this style if you didn't use any component from * JIDE Action Framework. * <p/> * * @see #VSNET_STYLE */ public final static int VSNET_STYLE_WITHOUT_MENU = 0; /** * A style that you can use with {@link #installJideExtension(int)} method. This style mimics the visual style of * Microsoft Visuasl Studio .NET for the toolbars, menus and dockable windows. * <p/> * Vsnet style is a very simple style with no gradient. Although it works on almost all L&Fs in any operating * systems, it looks the best on Windows 2000 or 98, or on Windows XP when XP theme is not on. If XP theme is on, we * suggest you use Office2003 style or Xerto style. Since the style is so simple, it works with a lot of the 3rd * party L&F such as Tonic, Pgs, Alloy etc without causing too much noice. That's why this is also the default style * for any L&Fs we don't recognize when you call {@link #installJideExtension()}, the one with out style parameter. * If you would like another style to be used as the default style, you can call {@link #setDefaultStyle(int)} * method. * <p/> * Here is the code to set to Windows L&F with Vsnet style extension. * <code><pre> * UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); // you need to catch the * exceptions on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.VSNET_STYLE); * </pre></code> * There is a special system property "shading theme" you can use. If you turn it on using the code below, you will * see a graident on dockable frame's title pane and rounded corner and graident on the tabs of JideTabbedPane. So * if the L&F you are using uses graident, you can set this property to true to match with your L&F. For example, if * you use Plastic3D L&F, turning this property on will look better. * <code><pre> * System.setProperty("shadingtheme", "true"); * </pre></code> */ public final static int VSNET_STYLE = 1; /** * A style that you can use with {@link #installJideExtension(int)} method. This style mimics the visual style of * Eclipse 2.x for the toolbars, menus and dockable windows. * <p/> * Eclipse style works for almost all L&Fs and on any operating systems, although it looks the best on Windows. For * any other operating systems we suggest you to use XERTO_STYLE or VSNET_STYLE. * <p/> * Here is the code to set to any L&F with Eclipse style extension. * <code><pre> * UIManager.setLookAndFeel(AnyLookAndFeel.class.getName()); // you need to catch the * exceptions * on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.ECLIPSE_STYLE); * </pre></code> */ public final static int ECLIPSE_STYLE = 2; /** * A style that you can use with {@link #installJideExtension(int)} method. This style mimics the visual style of * Microsoft Office2003 for the toolbars, menus and dockable windows. * <p/> * Office2003 style looks great on Windows XP when Windows or Windows XP L&F from Sun JDK is used. It replicated the * exact same style as Microsoft Office 2003, to give your end user a familar visual style. * <p/> * Here is the code to set to Windows L&F with Office2003 style extension. * <code><pre> * UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); // you need to catch the * exceptions on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.OFFICE2003_STYLE); * </pre></code> * It works either on any other Windows such as Winodows 2000, Windows 98 etc. If you are on Windows XP, Office2003 * style will change theme based on the theme setting in Windows Display Property. But if you are not on XP, * Office2003 style will use the default gray theme only. You can force to change it using {@link * Office2003Painter#setColorName(String)} method, but it won't look good as other non-JIDE components won't have * the matching theme. * <p/> * Office2003 style doesn't work on any operating systems other than Windows mainly because the design of Office2003 * style is so centric to Windows that it doesn't look good on other operating systems. */ public final static int OFFICE2003_STYLE = 3; /** * A style that you can use with {@link #installJideExtension(int)} method. This style is created by Xerto * (http://www.xerto.com) which is used in their Imagery product. * <p/> * Xerto style looks great on Windows XP when Windows XP L&F from Sun JDK is used. * <p/> * Here is the code to set to Windows L&F with Xerto style extension. * <code><pre> * UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName()); // you need to catch the * exceptions on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.XERTO_STYLE); * </pre></code> * Although it looks the best on Windows, Xerto style also supports Linux or Solaris if you use any L&Fs based on * Metal L&F or Synth L&F. For example, we recommend you to use Xerto style as default if you use SyntheticaL&F, a * L&F based on Synth. To use it, you bascially replace WindowsLookAndFeel to the L&F you want to use in * setLookAndFeel line above. */ public final static int XERTO_STYLE = 4; /** * A style that you can use with {@link #installJideExtension(int)} method. This style is the same as XERTO_STYLE * except it doesn't have menu related UIDefaults. You can only use this style if you didn't use any component from * JIDE Action Framework. Please note, we only use menu extension for Xerto style when the underlying L&F is Windows * L&F. If you are using L&F such as Metal or other 3rd party L&F based on Metal, XERTO_STYLE_WITHOUT_MENU will be * used even you use XERTO_STYLE when calling to installJideExtension(). * <p/> * * @see #XERTO_STYLE */ public final static int XERTO_STYLE_WITHOUT_MENU = 6; /** * A style that you can use with {@link #installJideExtension(int)} method. This style mimics the visual style of * Eclipse 3.x for the toolbars, menus and dockable windows. * <p/> * Eclipse 3x style works for almost all L&Fs and on any operating systems, although it looks the best on Windows. * For any other OS's we suggest you to use XERTO_STYLE or VSNET_STYLE. * <code><pre> * UIManager.setLookAndFeel(AnyLookAndFeel.class.getName()); // you need to catch the * exceptions * on this call. * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.ECLIPSE3X_STYLE); * </pre></code> */ public final static int ECLIPSE3X_STYLE = 5; private static int _style = -1; private static int _defaultStyle = -1; private static LookAndFeel _lookAndFeel; /** * If installJideExtension is called, it will put an entry on UIDefaults table. * UIManagerLookup.getBoolean(JIDE_EXTENSION_INSTALLLED) will return true. You can also use {@link * #isJideExtensionInstalled()} to check the value instead of using UIManagerLookup.getBoolean(JIDE_EXTENSION_INSTALLLED). */ public final static String JIDE_EXTENSION_INSTALLLED = "jidesoft.extendsionInstalled"; /** * If installJideExtension is called, a JIDE style will be installed on UIDefaults table. If so, * UIManagerLookup.getInt(JIDE_STYLE_INSTALLED) will return you the style that is installed. For example, if the * value is 1, it means VSNET_STYLE is installed because 1 is the value of VSNET_STYLE. */ public final static String JIDE_STYLE_INSTALLED = "jidesoft.extendsionStyle"; /** * An interface to make the customization of UIDefaults easier. This customizer will be called after * installJideExtension() is called. So if you want to further customize UIDefault, you can use this customzier to * do it. */ public static interface UIDefaultsCustomizer { void customize(UIDefaults defaults); } /** * An interface to make the initialization of UIDefaults easier. This initializer will be called before * installJideExtension() is called. So if you want to initialize UIDefault before installJideExtension is called, * you can use this initializer to do it. */ public static interface UIDefaultsInitializer { void initialize(UIDefaults defaults); } private static List<UIDefaultsCustomizer> _uiDefaultsCustomizers = new Vector(); private static List<UIDefaultsInitializer> _uiDefaultsInitializers = new Vector(); protected LookAndFeelFactory() { } /** * Gets the default style. If you never set default style before, it will return OFFICE2003_STYLE if you are on * Windows XP, L&F is instance of Windows L&F and XP theme is on. Otherwise, it will return VSNET_STYLE. If you set * default style before, it will return whatever style you set. * * @return the default style. */ public static int getDefaultStyle() { if (_defaultStyle == -1) { int suggestedStyle; try { if (XPUtils.isXPStyleOn() && UIManager.getLookAndFeel() instanceof WindowsLookAndFeel) { suggestedStyle = OFFICE2003_STYLE; } else { suggestedStyle = VSNET_STYLE; } } catch (UnsupportedOperationException e) { suggestedStyle = VSNET_STYLE; } return suggestedStyle; } return _defaultStyle; } /** * Sets the default style. If you call this method to set a default style, {@link #installJideExtension()} will use * it as the default style. * * @param defaultStyle the default style. */ public static void setDefaultStyle(int defaultStyle) { _defaultStyle = defaultStyle; } /** * Adds additional UIDefaults JIDE needed to UIDefault table. You must call this method everytime switching look and * feel. And callupdateComponentTreeUI() in corresponding DockingManager or DockableBarManager after this call. * <pre><code> * try { * UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); * } * catch (ClassNotFoundException e) { * e.printStackTrace(); * } * catch (InstantiationException e) { * e.printStackTrace(); * } * catch (IllegalAccessException e) { * e.printStackTrace(); * } * catch (UnsupportedLookAndFeelException e) { * e.printStackTrace(); * } * <p/> * // to add attitional UIDefault for JIDE components * LookAndFeelFactory.installJideExtension(); // use default style VSNET_STYLE. You can change * to a different style * using setDefaultStyle(int style) and then call this method. Or simply call * installJideExtension(style). * <p/> * // call updateComponentTreeUI * frame.getDockableBarManager().updateComponentTreeUI(); * frame.getDockingManager().updateComponentTreeUI(); * </code></pre> */ public static void installJideExtension() { installJideExtension(getDefaultStyle()); } /** * Add additional UIDefaults JIDE needed to UIDefaults table. You must call this method everytime switching look and * feel. And call updateComponentTreeUI() in corresponding DockingManager or DockableBarManager after this call. * <pre><code> * try { * UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); * } * catch (ClassNotFoundException e) { * e.printStackTrace(); * } * catch (InstantiationException e) { * e.printStackTrace(); * } * catch (IllegalAccessException e) { * e.printStackTrace(); * } * catch (UnsupportedLookAndFeelException e) { * e.printStackTrace(); * } * <p/> * // to add attitional UIDefault for JIDE components * LookAndFeelFactory.installJideExtension(LookAndFeelFactory.OFFICE2003_STYLE); * <p/> * // call updateComponentTreeUI * frame.getDockableBarManager().updateComponentTreeUI(); * frame.getDockingManager().updateComponentTreeUI(); * </code></pre> * * @param style the style of the extension. */ public static void installJideExtension(int style) { installJideExtension(UIManager.getLookAndFeelDefaults(), UIManager.getLookAndFeel(), style); } /** * Checks if JIDE extension is installed. Please note, UIManager.setLookAndFeel() method will overwrite the whole * UIDefaults table. So even you called {@link #installJideExtension()} method before, UIManager.setLookAndFeel() * method make isJideExtensionInstalled returning false. * * @return true if installed. */ public static boolean isJideExtensionInstalled() { return UIDefaultsLookup.getBoolean(JIDE_EXTENSION_INSTALLLED); } /** * Installs the UIDefault needed by JIDE component to the uiDefaults table passed in. * * @param uiDefaults the UIDefault tables where JIDE UIDefaults will be installed. * @param lnf the LookAndFeel. This may have an effect on which set of JIDE UIDefaults we will install. * @param style the style of the JIDE UIDefaults. */ public static void installJideExtension(UIDefaults uiDefaults, LookAndFeel lnf, int style) { if (isJideExtensionInstalled() && _style == style && _lookAndFeel == lnf) { return; } _style = style; uiDefaults.put(JIDE_STYLE_INSTALLED, _style); _lookAndFeel = lnf; UIDefaultsInitializer[] initializers = getUIDefaultsInitializers(); for (UIDefaultsInitializer initializer : initializers) { if (initializer != null) { initializer.initialize(uiDefaults); } } // For Alloy /* if (lnf.getClass().getName().equals(ALLOY_LNF) && isAlloyLnfInstalled()) { Object progressBarUI = uiDefaults.get("ProgressBarUI"); VsnetMetalUtils.initClassDefaults(uiDefaults); VsnetMetalUtils.initComponentDefaults(uiDefaults); uiDefaults.put("ProgressBarUI", progressBarUI); uiDefaults.put("DockableFrameUI", "com.jidesoft.plaf.vsnet.VsnetDockableFrameUI"); uiDefaults.put("DockableFrameTitlePane.hideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 0, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.unfloatIcon", IconsFactory.getIcon(null, titleButtonImage, 0, titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.floatIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 2 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.autohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 3 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.stopAutohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 4 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.hideAutohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 5 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.maximizeIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 6 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.restoreIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 7 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.buttonGap", new Integer(4)); // gap between buttons } else */ if ((lnf.getClass().getName().equals(ALLOY_LNF) && isAlloyLnfInstalled()) || (lnf.getClass().getName().equals(PLASTIC3D_LNF) && isPlastic3DLnfInstalled()) || (lnf.getClass().getName().equals(PLASTIC3D_LNF_1_3) && isPlastic3D13LnfInstalled()) || (lnf.getClass().getName().equals(PLASTICXP_LNF) && isPlasticXPLnfInstalled()) || (lnf.getClass().getName().equals(PGS_LNF) && isPgsLnfInstalled()) || (lnf.getClass().getName().equals(TONIC_LNF) && isTonicLnfInstalled())) { switch (style) { case OFFICE2003_STYLE: VsnetWindowsUtils.initComponentDefaults(uiDefaults); Office2003WindowsUtils.initComponentDefaults(uiDefaults); Office2003WindowsUtils.initClassDefaults(uiDefaults, false); break; case VSNET_STYLE: case VSNET_STYLE_WITHOUT_MENU: VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); Painter gripperPainter = new Painter() { public void paint(JComponent c, Graphics g, Rectangle rect, int orientation, int state) { Office2003Painter.getInstance().paintGripper(c, g, rect, orientation, state); } }; // set all grippers to Office2003 style gripper uiDefaults.put("Gripper.painter", gripperPainter); uiDefaults.put("JideTabbedPane.gripperPainter", gripperPainter); uiDefaults.put("JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_OFFICE2003); uiDefaults.put("JideTabbedPane.selectedTabTextForeground", UIDefaultsLookup.getColor("controlText")); uiDefaults.put("JideTabbedPane.unselectedTabTextForeground", UIDefaultsLookup.getColor("controlText")); uiDefaults.put("JideTabbedPane.foreground", UIDefaultsLookup.getColor("controlText")); uiDefaults.put("JideTabbedPane.light", UIDefaultsLookup.getColor("control")); uiDefaults.put("JideSplitPaneDivider.gripperPainter", gripperPainter); int products = LookAndFeelFactory.getProductsUsed(); if ((products & PRODUCT_DOCK) != 0) { ImageIcon titleButtonImage = IconsFactory.getImageIcon(VsnetWindowsUtils.class, "icons/title_buttons_windows.gif"); // 10 x 10 x 8 final int titleButtonSize = 10; uiDefaults.put("DockableFrameUI", "com.jidesoft.plaf.vsnet.VsnetDockableFrameUI"); uiDefaults.put("DockableFrameTitlePane.hideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 0, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.unfloatIcon", IconsFactory.getIcon(null, titleButtonImage, 0, titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.floatIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 2 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.autohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 3 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.stopAutohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 4 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.hideAutohideIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 5 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.maximizeIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 6 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.restoreIcon", IconsFactory.getIcon(null, titleButtonImage, 0, 7 * titleButtonSize, titleButtonSize, titleButtonSize)); uiDefaults.put("DockableFrameTitlePane.buttonGap", 4); // gap between buttons uiDefaults.put("DockableFrame.titleBorder", new BorderUIResource(BorderFactory.createEmptyBorder(1, 0, 1, 0))); uiDefaults.put("DockableFrame.border", new BorderUIResource(BorderFactory.createEmptyBorder(2, 0, 0, 0))); uiDefaults.put("DockableFrameTitlePane.gripperPainter", gripperPainter); } break; case ECLIPSE_STYLE: EclipseMetalUtils.initComponentDefaults(uiDefaults); EclipseMetalUtils.initClassDefaults(uiDefaults); break; case ECLIPSE3X_STYLE: Eclipse3xMetalUtils.initComponentDefaults(uiDefaults); Eclipse3xMetalUtils.initClassDefaults(uiDefaults); break; case XERTO_STYLE: case XERTO_STYLE_WITHOUT_MENU: XertoMetalUtils.initComponentDefaults(uiDefaults); XertoMetalUtils.initClassDefaults(uiDefaults); break; } } else if (lnf.getClass().getName().equals(MetalLookAndFeel.class.getName())) { switch (style) { case OFFICE2003_STYLE: case VSNET_STYLE: VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaultsWithMenu(uiDefaults); break; case ECLIPSE_STYLE: EclipseMetalUtils.initComponentDefaults(uiDefaults); EclipseMetalUtils.initClassDefaults(uiDefaults); break; case ECLIPSE3X_STYLE: Eclipse3xMetalUtils.initComponentDefaults(uiDefaults); Eclipse3xMetalUtils.initClassDefaults(uiDefaults); break; case VSNET_STYLE_WITHOUT_MENU: VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); break; case XERTO_STYLE: case XERTO_STYLE_WITHOUT_MENU: XertoMetalUtils.initComponentDefaults(uiDefaults); XertoMetalUtils.initClassDefaults(uiDefaults); break; default: } } else if (lnf instanceof MetalLookAndFeel) { switch (style) { case OFFICE2003_STYLE: VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); break; case ECLIPSE_STYLE: EclipseMetalUtils.initClassDefaults(uiDefaults); EclipseMetalUtils.initComponentDefaults(uiDefaults); break; case ECLIPSE3X_STYLE: Eclipse3xMetalUtils.initClassDefaults(uiDefaults); Eclipse3xMetalUtils.initComponentDefaults(uiDefaults); break; case VSNET_STYLE: case VSNET_STYLE_WITHOUT_MENU: VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); break; case XERTO_STYLE: case XERTO_STYLE_WITHOUT_MENU: XertoMetalUtils.initComponentDefaults(uiDefaults); XertoMetalUtils.initClassDefaults(uiDefaults); break; default: } } else if (lnf instanceof WindowsLookAndFeel) { switch (style) { case OFFICE2003_STYLE: VsnetWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); VsnetWindowsUtils.initClassDefaultsWithMenu(uiDefaults); Office2003WindowsUtils.initClassDefaults(uiDefaults); Office2003WindowsUtils.initComponentDefaults(uiDefaults); break; case ECLIPSE_STYLE: EclipseWindowsUtils.initClassDefaultsWithMenu(uiDefaults); EclipseWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); break; case ECLIPSE3X_STYLE: Eclipse3xWindowsUtils.initClassDefaultsWithMenu(uiDefaults); Eclipse3xWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); break; case VSNET_STYLE: VsnetWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); VsnetWindowsUtils.initClassDefaultsWithMenu(uiDefaults); break; case VSNET_STYLE_WITHOUT_MENU: VsnetWindowsUtils.initComponentDefaults(uiDefaults); VsnetWindowsUtils.initClassDefaults(uiDefaults); break; case XERTO_STYLE: XertoWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); XertoWindowsUtils.initClassDefaultsWithMenu(uiDefaults); break; case XERTO_STYLE_WITHOUT_MENU: XertoWindowsUtils.initComponentDefaults(uiDefaults); XertoWindowsUtils.initClassDefaults(uiDefaults); break; default: } } // For Mac only else if ((isLnfInUse(AQUA_LNF) && isAquaLnfInstalled()) || (isLnfInUse(QUAQUA_LNF) && isQuaquaLnfInstalled())) { // use reflection since we don't deliver source code of AquaJideUtils as most users don't compile it on Mac OS X try { Class<?> aquaJideUtils = getUIManagerClassLoader().loadClass("com.jidesoft.plaf.aqua.AquaJideUtils"); aquaJideUtils.getMethod("initComponentDefaults", UIDefaults.class).invoke(null, uiDefaults); aquaJideUtils.getMethod("initClassDefaults", UIDefaults.class).invoke(null, uiDefaults); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { JideSwingUtilities.throwInvocationTargetException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } } else { // built in initializer if (isGTKLnfInstalled() && isLnfInUse(GTK_LNF)) { new GTKInitializer().initialize(uiDefaults); } else if (isSyntheticaLnfInstalled() && (lnf.getClass().getName().startsWith(SYNTHETICA_LNF_PREFIX) || isLnfInUse(SYNTHETICA_LNF))) { new SyntheticaInitializer().initialize(uiDefaults); } else if (isNimbusLnfInstalled() && lnf.getClass().getName().indexOf(NIMBUS_LNF_NAME) != -1) { new NimbusInitializer().initialize(uiDefaults); } switch (style) { case OFFICE2003_STYLE: if (SystemInfo.isWindows()) { VsnetWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); Office2003WindowsUtils.initComponentDefaults(uiDefaults); Office2003WindowsUtils.initClassDefaults(uiDefaults); } else { VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); } break; case ECLIPSE_STYLE: if (SystemInfo.isWindows()) { EclipseWindowsUtils.initClassDefaultsWithMenu(uiDefaults); EclipseWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); } else { EclipseMetalUtils.initClassDefaults(uiDefaults); EclipseMetalUtils.initComponentDefaults(uiDefaults); } break; case ECLIPSE3X_STYLE: if (SystemInfo.isWindows()) { Eclipse3xWindowsUtils.initClassDefaultsWithMenu(uiDefaults); Eclipse3xWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); } else { Eclipse3xMetalUtils.initClassDefaults(uiDefaults); Eclipse3xMetalUtils.initComponentDefaults(uiDefaults); } break; case VSNET_STYLE: if (SystemInfo.isWindows()) { VsnetWindowsUtils.initClassDefaultsWithMenu(uiDefaults); VsnetWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); } else { VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); } break; case VSNET_STYLE_WITHOUT_MENU: if (SystemInfo.isWindows()) { VsnetWindowsUtils.initClassDefaults(uiDefaults); VsnetWindowsUtils.initComponentDefaults(uiDefaults); } else { VsnetMetalUtils.initComponentDefaults(uiDefaults); VsnetMetalUtils.initClassDefaults(uiDefaults); } break; case XERTO_STYLE: if (SystemInfo.isWindows()) { XertoWindowsUtils.initClassDefaultsWithMenu(uiDefaults); XertoWindowsUtils.initComponentDefaultsWithMenu(uiDefaults); } else { XertoMetalUtils.initComponentDefaults(uiDefaults); XertoMetalUtils.initClassDefaults(uiDefaults); } break; case XERTO_STYLE_WITHOUT_MENU: if (SystemInfo.isWindows()) { XertoWindowsUtils.initClassDefaults(uiDefaults); XertoWindowsUtils.initComponentDefaults(uiDefaults); } else { XertoMetalUtils.initComponentDefaults(uiDefaults); XertoMetalUtils.initClassDefaults(uiDefaults); } break; default: } // built in customizer if (lnf.getClass().getName().startsWith(SYNTHETICA_LNF_PREFIX) || isLnfInUse(SYNTHETICA_LNF)) { new SyntheticaCustomizer().customize(uiDefaults); } } uiDefaults.put(JIDE_EXTENSION_INSTALLLED, Boolean.TRUE); UIDefaultsCustomizer[] customizers = getUIDefaultsCustomizers(); for (UIDefaultsCustomizer customizer : customizers) { if (customizer != null) { customizer.customize(uiDefaults); } } } /** * Returns whether or not the L&F is in classpath. * * @param lnfName the L&F name. * @return <tt>true</tt> if the L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isLnfInstalled(String lnfName) { try { getUIManagerClassLoader().loadClass(lnfName); return true; } catch (ClassNotFoundException e) { return false; } } public static ClassLoader getUIManagerClassLoader() { Object cl = UIManager.get("ClassLoader"); if (cl instanceof ClassLoader) { return (ClassLoader) cl; } ClassLoader classLoader = LookAndFeelFactory.class.getClassLoader(); if (classLoader == null) { classLoader = ClassLoader.getSystemClassLoader(); } return classLoader; } /** * Checks if the L&F is the L&F or a subclass of the L&F. * * @param lnfName the L&F name. * @return true or false. */ public static boolean isLnfInUse(String lnfName) { try { return lnfName.equals(UIManager.getLookAndFeel().getClass().getName()) || Class.forName(lnfName).isAssignableFrom(UIManager.getLookAndFeel().getClass()); } catch (ClassNotFoundException e) { return false; } } /** * Returns whether or not the Aqua L&F is in classpath. * * @return <tt>true</tt> if aqua L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isAquaLnfInstalled() { return isLnfInstalled(AQUA_LNF); } /** * Returns whether or not the Quaqua L&F is in classpath. * * @return <tt>true</tt> if Quaqua L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isQuaquaLnfInstalled() { return isLnfInstalled(QUAQUA_LNF); } /** * Returns whether alloy L&F is in classpath * * @return <tt>true</tt> alloy L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isAlloyLnfInstalled() { return isLnfInstalled(ALLOY_LNF); } /** * Returns whether GTK L&F is in classpath * * @return <tt>true</tt> GTK L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isGTKLnfInstalled() { return isLnfInstalled(GTK_LNF); } /** * Returns whether Plastic3D L&F is in classpath * * @return <tt>true</tt> Plastic3D L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isPlastic3DLnfInstalled() { return isLnfInstalled(PLASTIC3D_LNF); } /** * Returns whether Plastic3D L&F is in classpath * * @return <tt>true</tt> Plastic3D L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isPlastic3D13LnfInstalled() { return isLnfInstalled(PLASTIC3D_LNF_1_3); } /** * Returns whether PlasticXP L&F is in classpath * * @return <tt>true</tt> Plastic3D L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isPlasticXPLnfInstalled() { return isLnfInstalled(PLASTICXP_LNF); } /** * Returns whether Tonic L&F is in classpath * * @return <tt>true</tt> Tonic L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isTonicLnfInstalled() { return isLnfInstalled(TONIC_LNF); } /** * Returns whether A03 L&F is in classpath * * @return <tt>true</tt> A03 L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isA03LnfInstalled() { return isLnfInstalled(A03_LNF); } /** * Returns whether or not the Pgs L&F is in classpath. * * @return <tt>true</tt> if pgs L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isPgsLnfInstalled() { return isLnfInstalled(PGS_LNF); } /** * Returns whether or not the Synthetica L&F is in classpath. * * @return <tt>true</tt> if Synthetica L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isSyntheticaLnfInstalled() { return isLnfInstalled(SYNTHETICA_LNF); } /** * Returns whether or not the Nimbus L&F is in classpath. * * @return <tt>true</tt> if Nimbus L&F is in classpath, <tt>false</tt> otherwise */ public static boolean isNimbusLnfInstalled() { UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels(); for (UIManager.LookAndFeelInfo info : infos) { if (info.getClassName().indexOf(NIMBUS_LNF_NAME) != -1) { return true; } } return false; } /** * Install the default L&F. In this method, we will look at system property "swing.defaultlaf" first. If the value * is set and it's not an instance of Synth L&F, we will use it. Otherwise, we will use Metal L&F is OS is Linux or * UNIX and use UIManager.getSystemLookAndFeelClassName() for other OS. In addition, we will add JIDE extension to * it. */ public static void installDefaultLookAndFeelAndExtension() { installDefaultLookAndFeel(); // to add attitional UIDefault for JIDE components LookAndFeelFactory.installJideExtension(); } /** * Install the default L&F. In this method, we will look at system property "swing.defaultlaf" first. If the value * is set and it's not an instance of Synth L&F, we will use it. Otherwise, we will use Metal L&F is OS is Linux or * UNIX and use UIManager.getSystemLookAndFeelClassName() for other OS. */ public static void installDefaultLookAndFeel() { try { String lnfName = SecurityUtils.getProperty("swing.defaultlaf", null); Class<?> lnfClass = null; if (lnfName != null) { try { lnfClass = getUIManagerClassLoader().loadClass(lnfName); } catch (ClassNotFoundException e) { // ignore } } if (lnfClass == null) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else { UIManager.setLookAndFeel(lnfName); } } catch (Exception e) { // ignore } } /** * Gets current L&F. * * @return the current L&F. */ public static LookAndFeel getLookAndFeel() { return _lookAndFeel; } /** * Gets current style. * * @return the current style. */ public static int getStyle() { return _style; } /** * Gets all UIDefaults customizers. * * @return an array of UIDefaults customizers. */ public static UIDefaultsCustomizer[] getUIDefaultsCustomizers() { return _uiDefaultsCustomizers.toArray(new UIDefaultsCustomizer[_uiDefaultsCustomizers.size()]); } /** * Adds your own UIDefaults customizer. This customizer will be called after installJideExtension() is called. * <code><pre> * For example, we use "JideButton.font" as the UIDefault for the JideButton font. If you want * to use another font, you can do * LookAndFeelFactory.addUIDefaultsCustomizer(new LookAndFeelFactory.UIDefaultsCustomizer() { * public void customize(UIDefaults defaults) { * defaults.put("JideButton.font", whateverFont); * } * }); * </pre></code> * * @param uiDefaultsCustomizer the UIDefaultsCustomizer */ public static void addUIDefaultsCustomizer(UIDefaultsCustomizer uiDefaultsCustomizer) { if (!_uiDefaultsCustomizers.contains(uiDefaultsCustomizer)) { _uiDefaultsCustomizers.add(uiDefaultsCustomizer); } } /** * Removes an existing UIDefaults customizer you added before. * * @param uiDefaultsCustomizer the UIDefaultsCustomizer */ public static void removeUIDefaultsCustomizer(UIDefaultsCustomizer uiDefaultsCustomizer) { _uiDefaultsCustomizers.remove(uiDefaultsCustomizer); } /** * Gets all UIDefaults initializers. * * @return an array of UIDefaults initializers. */ public static UIDefaultsInitializer[] getUIDefaultsInitializers() { return _uiDefaultsInitializers.toArray(new UIDefaultsInitializer[_uiDefaultsInitializers.size()]); } /** * Adds your own UIDefaults initializer. This initializer will be called before installJideExtension() is called. * <p/> * Here is how you use it. For example, we use the color of UIDefault "activeCaption" to get the active title color * which we will use for active title bar color in JIDE components. If the L&F you are using doesn't set this * UIDefault, we might throw NPE later in the code. To avoid this, you call * <code><pre> * LookAndFeelFactory.addUIDefaultsInitializer(new LookAndFeelFactory.UIDefaultsInitializer() { * public void initialize(UIDefaults defaults) { * defaults.put("activeCaption", whateverColor); * } * }); * UIManager.setLookAndFeel(...); // set whatever L&F * LookAndFeelFactory.installJideExtension(); // install the UIDefaults needed by the JIDE * components * </pre></code> * * @param uiDefaultsInitializer the UIDefaultsInitializer. */ public static void addUIDefaultsInitializer(UIDefaultsInitializer uiDefaultsInitializer) { if (!_uiDefaultsInitializers.contains(uiDefaultsInitializer)) { _uiDefaultsInitializers.add(uiDefaultsInitializer); } } /** * Removes an existing UIDefaults initializer you added before. * * @param uiDefaultsInitializer the UIDefaultsInitializer */ public static void removeUIDefaultsInitializer(UIDefaultsInitializer uiDefaultsInitializer) { _uiDefaultsInitializers.remove(uiDefaultsInitializer); } public static class GTKInitializer implements UIDefaultsInitializer { public void initialize(UIDefaults defaults) { ImageIcon rightImageIcon = IconsFactory.createMaskImage(new JLabel(), JideIconsFactory.getImageIcon(JideIconsFactory.Arrow.RIGHT), Color.BLACK, Color.GRAY); ImageIcon downImageIcon = IconsFactory.createMaskImage(new JLabel(), JideIconsFactory.getImageIcon(JideIconsFactory.Arrow.DOWN), Color.BLACK, Color.GRAY); Object[] uiDefaults = { "activeCaption", defaults.getColor("textHighlight"), "activeCaptionText", defaults.getColor("textHighlightText"), "inactiveCaptionBorder", defaults.getColor("controlShadowtextHighlightText"), "CategorizedTable.categoryCollapsedIcon", rightImageIcon, "CategorizedTable.categoryExpandedIcon", downImageIcon, "CategorizedTable.collapsedIcon", rightImageIcon, "CategorizedTable.expandedIcon", downImageIcon, }; putDefaults(defaults, uiDefaults); } } public static class SyntheticaInitializer implements UIDefaultsInitializer { public void initialize(UIDefaults defaults) { Object[] uiDefaults = { "Label.font", UIDefaultsLookup.getFont("Button.font"), "ToolBar.font", UIDefaultsLookup.getFont("Button.font"), "MenuItem.acceleratorFont", UIDefaultsLookup.getFont("Button.font"), "ComboBox.disabledForeground", defaults.get("Synthetica.comboBox.disabled.textColor"), "ComboBox.disabledBackground", defaults.get("Synthetica.comboBox.disabled.backgroundColor"), "Slider.focusInsets", new InsetsUIResource(0, 0, 0, 0), }; putDefaults(defaults, uiDefaults); } } public static class SyntheticaCustomizer implements UIDefaultsCustomizer { public void customize(UIDefaults defaults) { try { Class syntheticaClass = Class.forName(SYNTHETICA_LNF); Class syntheticaFrameBorder = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaFrameBorder"); Color toolbarBackground = new JToolBar().getBackground(); Object[] uiDefaults = { "JideTabbedPaneUI", "com.jidesoft.plaf.synthetica.SyntheticaJideTabbedPaneUI", "Workspace.background", UIManager.getColor("control"), "JideTabbedPane.tabAreaBackground", UIManager.getColor("control"), "JideTabbedPane.background", UIManager.getColor("control"), "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "DockableFrame.inactiveTitleForeground", UIDefaultsLookup.getColor("Synthetica.docking.titlebar.color"), "DockableFrame.activeTitleForeground", UIDefaultsLookup.getColor("Synthetica.docking.titlebar.color.selected"), "DockableFrame.titleBorder", UIDefaultsLookup.getColor("Synthetica.docking.border.color"), "JideTabbedPane.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "FrameContainer.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "CollapsiblePane.background", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.emphasizedBackground", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.foreground", UIDefaultsLookup.getColor("TaskPane.titleForeground"), "CollapsiblePane.emphasizedForeground", UIDefaultsLookup.getColor("TaskPane.specialTitleForeground"), "StatusBarItem.border", new BorderUIResource(BorderFactory.createEmptyBorder(2, 2, 2, 2)), "JideButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "JideSplitButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "Icon.floating", Boolean.FALSE, "CommandBar.background", toolbarBackground, "ContentContainer.background", toolbarBackground, "CommandBar.border", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderVert", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderFloating", syntheticaFrameBorder.newInstance(), "CommandBar.titleBarBackground", UIDefaultsLookup.getColor("InternalFrame.activeTitleBackground"), "CommandBar.titleBarForeground", UIDefaultsLookup.getColor("InternalFrame.activeTitleForeground"), "CommandBarContainer.verticalGap", 0, "DockableFrameTitlePane.hideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.close")), "DockableFrameTitlePane.hideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.close.hover")), "DockableFrameTitlePane.hideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.close")), "DockableFrameTitlePane.hideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.close.hover")), "DockableFrameTitlePane.floatIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.undock")), "DockableFrameTitlePane.floatRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.undock.hover")), "DockableFrameTitlePane.floatActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.undock")), "DockableFrameTitlePane.floatRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.undock.hover")), "DockableFrameTitlePane.unfloatIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.dock")), "DockableFrameTitlePane.unfloatRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.dock.hover")), "DockableFrameTitlePane.unfloatActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.dock")), "DockableFrameTitlePane.unfloatRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.dock.hover")), "DockableFrameTitlePane.autohideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify")), "DockableFrameTitlePane.autohideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify.hover")), "DockableFrameTitlePane.autohideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify")), "DockableFrameTitlePane.autohideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify.hover")), "DockableFrameTitlePane.stopAutohideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore")), "DockableFrameTitlePane.stopAutohideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore.hover")), "DockableFrameTitlePane.stopAutohideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore")), "DockableFrameTitlePane.stopAutohideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore.hover")), "DockableFrameTitlePane.hideAutohideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify")), "DockableFrameTitlePane.hideAutohideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify.hover")), "DockableFrameTitlePane.hideAutohideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify")), "DockableFrameTitlePane.hideAutohideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify.hover")), "DockableFrameTitlePane.maximizeIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.maximize")), "DockableFrameTitlePane.maximizeRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.maximize.hover")), "DockableFrameTitlePane.maximizeActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.maximize")), "DockableFrameTitlePane.maximizeRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.maximize.hover")), "DockableFrameTitlePane.restoreIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore")), "DockableFrameTitlePane.restoreRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore.hover")), "DockableFrameTitlePane.restoreActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore")), "DockableFrameTitlePane.restoreRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore.hover")), "DockableFrameTitlePane.use3dButtons", Boolean.FALSE, "DockableFrameTitlePane.contentFilledButtons", Boolean.FALSE, "DockableFrameTitlePane.buttonGap", 0, "JideSplitPane.dividerSize", 6, }; - JideSwingUtilities.printUIDefaults(); overwriteDefaults(defaults, uiDefaults); Class<?> painterClass = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaJidePainter"); Method getInstanceMethod = painterClass.getMethod("getInstance"); Object painter = getInstanceMethod.invoke(null); UIDefaultsLookup.put(UIManager.getDefaults(), "Theme.painter", painter); } catch (Exception e) { e.printStackTrace(); } } } public static class NimbusInitializer implements UIDefaultsInitializer { public void initialize(UIDefaults defaults) { Object marginBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders$MarginBorder"); Object[] uiDefaults = { "textHighlight", new ColorUIResource(197, 218, 233), "controlText", new ColorUIResource(Color.BLACK), "activeCaptionText", new ColorUIResource(Color.BLACK), "MenuItem.acceleratorFont", new FontUIResource("Arial", Font.PLAIN, 12), "ComboBox.background", new ColorUIResource(Color.WHITE), "ComboBox.disabledForeground", new ColorUIResource(Color.DARK_GRAY), "ComboBox.disabledBackground", new ColorUIResource(Color.GRAY), "activeCaption", new ColorUIResource(197, 218, 233), "inactiveCaption", new ColorUIResource(Color.DARK_GRAY), "control", new ColorUIResource(220, 223, 228), "controlLtHighlight", new ColorUIResource(Color.WHITE), "controlHighlight", new ColorUIResource(Color.LIGHT_GRAY), "controlShadow", new ColorUIResource(133, 137, 144), "controlDkShadow", new ColorUIResource(Color.BLACK), "MenuItem.background", new ColorUIResource(237, 239, 242), "SplitPane.background", new ColorUIResource(220, 223, 228), "Tree.hash", new ColorUIResource(Color.GRAY), "TextField.foreground", new ColorUIResource(Color.BLACK), "TextField.inactiveForeground", new ColorUIResource(Color.BLACK), "TextField.selectionForeground", new ColorUIResource(Color.WHITE), "TextField.selectionBackground", new ColorUIResource(197, 218, 233), "Table.gridColor", new ColorUIResource(Color.BLACK), "TextField.background", new ColorUIResource(Color.WHITE), "Table.selectionBackground", defaults.getColor("Tree.selectionBackground"), "Table.selectionForeground", defaults.getColor("Tree.selectionForeground"), "Menu.border", marginBorder, "MenuItem.border", marginBorder, "CheckBoxMenuItem.border", marginBorder, "RadioButtonMenuItem.border", marginBorder, }; putDefaults(defaults, uiDefaults); } } @SuppressWarnings({"UseOfSystemOutOrSystemErr"}) public static void verifyDefaults(UIDefaults table, Object[] keyValueList) { for (int i = 0, max = keyValueList.length; i < max; i += 2) { Object value = keyValueList[i + 1]; if (value == null) { System.out.println("The value for " + keyValueList[i] + " is null"); } else { Object oldValue = table.get(keyValueList[i]); if (oldValue != null) { System.out.println("The value for " + keyValueList[i] + " exists which is " + oldValue); } } } } /** * Puts a list of UIDefault to the UIDefaults table. The keyValueList is an array with a key and value in pair. If * the value is null, this method will remove the key from the table. If the table already has a value for the key, * the new value will be ignored. This is the difference from {@link #putDefaults(javax.swing.UIDefaults,Object[])} * method. You should use this method in {@link UIDefaultsInitializer} so that it fills in the UIDefault value only * when it is missing. * * @param table the ui defaults table * @param keyValueArray the key value array. It is in the format of a key followed by a value. */ public static void putDefaults(UIDefaults table, Object[] keyValueArray) { for (int i = 0, max = keyValueArray.length; i < max; i += 2) { Object value = keyValueArray[i + 1]; if (value == null) { table.remove(keyValueArray[i]); } else { if (table.get(keyValueArray[i]) == null) { table.put(keyValueArray[i], value); } } } } /** * Puts a list of UIDefault to the UIDefaults table. The keyValueList is an array with a key and value in pair. If * the value is null, this method will remove the key from the table. Otherwise, it will put the new value in even * if the table already has a value for the key. This is the difference from {@link * #putDefaults(javax.swing.UIDefaults,Object[])} method. You should use this method in {@link UIDefaultsCustomizer} * because you always want to override the existing value using the new value. * * @param table the ui defaults table * @param keyValueArray the key value array. It is in the format of a key followed by a value. */ public static void overwriteDefaults(UIDefaults table, Object[] keyValueArray) { for (int i = 0, max = keyValueArray.length; i < max; i += 2) { Object value = keyValueArray[i + 1]; if (value == null) { table.remove(keyValueArray[i]); } else { table.put(keyValueArray[i], value); } } } private static int _productsUsed = -1; public static int getProductsUsed() { if (_productsUsed == -1) { _productsUsed = 0; try { Class.forName("com.jidesoft.docking.Product"); _productsUsed |= PRODUCT_DOCK; } catch (ClassNotFoundException e) { // } try { Class.forName("com.jidesoft.action.Product"); _productsUsed |= PRODUCT_ACTION; } catch (ClassNotFoundException e) { // } try { Class.forName("com.jidesoft.document.Product"); _productsUsed |= PRODUCT_COMPONENTS; } catch (ClassNotFoundException e) { // } try { Class.forName("com.jidesoft.grid.Product"); _productsUsed |= PRODUCT_GRIDS; } catch (ClassNotFoundException e) { // } try { Class.forName("com.jidesoft.wizard.Product"); _productsUsed |= PRODUCT_DIALOGS; } catch (ClassNotFoundException e) { // } try { Class.forName("com.jidesoft.pivot.Product"); _productsUsed |= PRODUCT_PIVOT; } catch (ClassNotFoundException e) { // } try { Class.forName("com.jidesoft.shortcut.Product"); _productsUsed |= PRODUCT_SHORTCUT; } catch (ClassNotFoundException e) { // } try { Class.forName("com.jidesoft.editor.Product"); _productsUsed |= PRODUCT_CODE_EDITOR; } catch (ClassNotFoundException e) { // } try { Class.forName("com.jidesoft.rss.Product"); _productsUsed |= PRODUCT_FEEDREADER; } catch (ClassNotFoundException e) { // } } return _productsUsed; } /** * Sets the products you will use. This is needed so that LookAndFeelFactory knows what UIDefault to initialize. For * example, if you use only JIDE Docking Framework and JIDE Grids, you should call * <code>setProductUsed(ProductNames.PRODUCT_DOCK | ProductNames.PRODUCT_GRIDS)</code> so that we don't initialize * UIDefaults needed by any other products. If you use this class as part of JIDE Common Layer open source project, * you should call <code>setProductUsed(ProductNames.PRODUCT_COMMON)</code>. If you want to use all JIDE products, * you should call <code>setProductUsed(ProductNames.PRODUCT_ALL)</code> * * @param productsUsed a bit-wise OR of product values defined in {@link com.jidesoft.utils.ProductNames}. */ public static void setProductsUsed(int productsUsed) { _productsUsed = productsUsed; } /** * Checks if the current L&F uses decorated frames. * * @return true if the current L&F uses decorated frames. Otherwise false. */ public static boolean isCurrentLnfDecorated() { return !isLnfInUse(SYNTHETICA_LNF); } }
true
true
public void customize(UIDefaults defaults) { try { Class syntheticaClass = Class.forName(SYNTHETICA_LNF); Class syntheticaFrameBorder = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaFrameBorder"); Color toolbarBackground = new JToolBar().getBackground(); Object[] uiDefaults = { "JideTabbedPaneUI", "com.jidesoft.plaf.synthetica.SyntheticaJideTabbedPaneUI", "Workspace.background", UIManager.getColor("control"), "JideTabbedPane.tabAreaBackground", UIManager.getColor("control"), "JideTabbedPane.background", UIManager.getColor("control"), "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "DockableFrame.inactiveTitleForeground", UIDefaultsLookup.getColor("Synthetica.docking.titlebar.color"), "DockableFrame.activeTitleForeground", UIDefaultsLookup.getColor("Synthetica.docking.titlebar.color.selected"), "DockableFrame.titleBorder", UIDefaultsLookup.getColor("Synthetica.docking.border.color"), "JideTabbedPane.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "FrameContainer.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "CollapsiblePane.background", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.emphasizedBackground", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.foreground", UIDefaultsLookup.getColor("TaskPane.titleForeground"), "CollapsiblePane.emphasizedForeground", UIDefaultsLookup.getColor("TaskPane.specialTitleForeground"), "StatusBarItem.border", new BorderUIResource(BorderFactory.createEmptyBorder(2, 2, 2, 2)), "JideButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "JideSplitButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "Icon.floating", Boolean.FALSE, "CommandBar.background", toolbarBackground, "ContentContainer.background", toolbarBackground, "CommandBar.border", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderVert", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderFloating", syntheticaFrameBorder.newInstance(), "CommandBar.titleBarBackground", UIDefaultsLookup.getColor("InternalFrame.activeTitleBackground"), "CommandBar.titleBarForeground", UIDefaultsLookup.getColor("InternalFrame.activeTitleForeground"), "CommandBarContainer.verticalGap", 0, "DockableFrameTitlePane.hideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.close")), "DockableFrameTitlePane.hideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.close.hover")), "DockableFrameTitlePane.hideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.close")), "DockableFrameTitlePane.hideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.close.hover")), "DockableFrameTitlePane.floatIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.undock")), "DockableFrameTitlePane.floatRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.undock.hover")), "DockableFrameTitlePane.floatActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.undock")), "DockableFrameTitlePane.floatRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.undock.hover")), "DockableFrameTitlePane.unfloatIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.dock")), "DockableFrameTitlePane.unfloatRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.dock.hover")), "DockableFrameTitlePane.unfloatActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.dock")), "DockableFrameTitlePane.unfloatRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.dock.hover")), "DockableFrameTitlePane.autohideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify")), "DockableFrameTitlePane.autohideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify.hover")), "DockableFrameTitlePane.autohideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify")), "DockableFrameTitlePane.autohideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify.hover")), "DockableFrameTitlePane.stopAutohideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore")), "DockableFrameTitlePane.stopAutohideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore.hover")), "DockableFrameTitlePane.stopAutohideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore")), "DockableFrameTitlePane.stopAutohideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore.hover")), "DockableFrameTitlePane.hideAutohideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify")), "DockableFrameTitlePane.hideAutohideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify.hover")), "DockableFrameTitlePane.hideAutohideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify")), "DockableFrameTitlePane.hideAutohideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify.hover")), "DockableFrameTitlePane.maximizeIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.maximize")), "DockableFrameTitlePane.maximizeRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.maximize.hover")), "DockableFrameTitlePane.maximizeActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.maximize")), "DockableFrameTitlePane.maximizeRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.maximize.hover")), "DockableFrameTitlePane.restoreIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore")), "DockableFrameTitlePane.restoreRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore.hover")), "DockableFrameTitlePane.restoreActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore")), "DockableFrameTitlePane.restoreRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore.hover")), "DockableFrameTitlePane.use3dButtons", Boolean.FALSE, "DockableFrameTitlePane.contentFilledButtons", Boolean.FALSE, "DockableFrameTitlePane.buttonGap", 0, "JideSplitPane.dividerSize", 6, }; JideSwingUtilities.printUIDefaults(); overwriteDefaults(defaults, uiDefaults); Class<?> painterClass = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaJidePainter"); Method getInstanceMethod = painterClass.getMethod("getInstance"); Object painter = getInstanceMethod.invoke(null); UIDefaultsLookup.put(UIManager.getDefaults(), "Theme.painter", painter); } catch (Exception e) { e.printStackTrace(); } }
public void customize(UIDefaults defaults) { try { Class syntheticaClass = Class.forName(SYNTHETICA_LNF); Class syntheticaFrameBorder = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaFrameBorder"); Color toolbarBackground = new JToolBar().getBackground(); Object[] uiDefaults = { "JideTabbedPaneUI", "com.jidesoft.plaf.synthetica.SyntheticaJideTabbedPaneUI", "Workspace.background", UIManager.getColor("control"), "JideTabbedPane.tabAreaBackground", UIManager.getColor("control"), "JideTabbedPane.background", UIManager.getColor("control"), "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "JideTabbedPane.defaultTabShape", JideTabbedPane.SHAPE_ROUNDED_VSNET, "DockableFrame.inactiveTitleForeground", UIDefaultsLookup.getColor("Synthetica.docking.titlebar.color"), "DockableFrame.activeTitleForeground", UIDefaultsLookup.getColor("Synthetica.docking.titlebar.color.selected"), "DockableFrame.titleBorder", UIDefaultsLookup.getColor("Synthetica.docking.border.color"), "JideTabbedPane.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "FrameContainer.contentBorderInsets", new InsetsUIResource(2, 2, 2, 2), "CollapsiblePane.background", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.emphasizedBackground", UIDefaultsLookup.getColor("TaskPane.borderColor"), "CollapsiblePane.foreground", UIDefaultsLookup.getColor("TaskPane.titleForeground"), "CollapsiblePane.emphasizedForeground", UIDefaultsLookup.getColor("TaskPane.specialTitleForeground"), "StatusBarItem.border", new BorderUIResource(BorderFactory.createEmptyBorder(2, 2, 2, 2)), "JideButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "JideSplitButton.foreground", UIDefaultsLookup.getColor("Button.foreground"), "Icon.floating", Boolean.FALSE, "CommandBar.background", toolbarBackground, "ContentContainer.background", toolbarBackground, "CommandBar.border", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderVert", new BorderUIResource(BorderFactory.createEmptyBorder()), "CommandBar.borderFloating", syntheticaFrameBorder.newInstance(), "CommandBar.titleBarBackground", UIDefaultsLookup.getColor("InternalFrame.activeTitleBackground"), "CommandBar.titleBarForeground", UIDefaultsLookup.getColor("InternalFrame.activeTitleForeground"), "CommandBarContainer.verticalGap", 0, "DockableFrameTitlePane.hideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.close")), "DockableFrameTitlePane.hideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.close.hover")), "DockableFrameTitlePane.hideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.close")), "DockableFrameTitlePane.hideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.close.hover")), "DockableFrameTitlePane.floatIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.undock")), "DockableFrameTitlePane.floatRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.undock.hover")), "DockableFrameTitlePane.floatActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.undock")), "DockableFrameTitlePane.floatRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.undock.hover")), "DockableFrameTitlePane.unfloatIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.dock")), "DockableFrameTitlePane.unfloatRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.dock.hover")), "DockableFrameTitlePane.unfloatActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.dock")), "DockableFrameTitlePane.unfloatRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.dock.hover")), "DockableFrameTitlePane.autohideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify")), "DockableFrameTitlePane.autohideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify.hover")), "DockableFrameTitlePane.autohideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify")), "DockableFrameTitlePane.autohideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify.hover")), "DockableFrameTitlePane.stopAutohideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore")), "DockableFrameTitlePane.stopAutohideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore.hover")), "DockableFrameTitlePane.stopAutohideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore")), "DockableFrameTitlePane.stopAutohideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore.hover")), "DockableFrameTitlePane.hideAutohideIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify")), "DockableFrameTitlePane.hideAutohideRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.iconify.hover")), "DockableFrameTitlePane.hideAutohideActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify")), "DockableFrameTitlePane.hideAutohideRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.iconify.hover")), "DockableFrameTitlePane.maximizeIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.maximize")), "DockableFrameTitlePane.maximizeRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.maximize.hover")), "DockableFrameTitlePane.maximizeActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.maximize")), "DockableFrameTitlePane.maximizeRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.maximize.hover")), "DockableFrameTitlePane.restoreIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore")), "DockableFrameTitlePane.restoreRolloverIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.restore.hover")), "DockableFrameTitlePane.restoreActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore")), "DockableFrameTitlePane.restoreRolloverActiveIcon", IconsFactory.getImageIcon(syntheticaClass, UIDefaultsLookup.getString("Synthetica.docking.titlebar.active.restore.hover")), "DockableFrameTitlePane.use3dButtons", Boolean.FALSE, "DockableFrameTitlePane.contentFilledButtons", Boolean.FALSE, "DockableFrameTitlePane.buttonGap", 0, "JideSplitPane.dividerSize", 6, }; overwriteDefaults(defaults, uiDefaults); Class<?> painterClass = Class.forName("com.jidesoft.plaf.synthetica.SyntheticaJidePainter"); Method getInstanceMethod = painterClass.getMethod("getInstance"); Object painter = getInstanceMethod.invoke(null); UIDefaultsLookup.put(UIManager.getDefaults(), "Theme.painter", painter); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigInputFormat.java b/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigInputFormat.java index dab97e7f..b1a5873e 100644 --- a/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigInputFormat.java +++ b/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigInputFormat.java @@ -1,342 +1,343 @@ /* * 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.pig.backend.hadoop.executionengine.mapReduceLayer; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.HashSet; import java.util.HashMap; import java.util.Comparator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.pig.ExecType; import org.apache.pig.FuncSpec; import org.apache.pig.IndexableLoadFunc; import org.apache.pig.LoadFunc; import org.apache.pig.PigException; import org.apache.pig.CollectableLoadFunc; import org.apache.pig.OrderedLoadFunc; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil; import org.apache.pig.backend.hadoop.executionengine.util.MapRedUtil; import org.apache.pig.data.Tuple; import org.apache.pig.impl.PigContext; import org.apache.pig.impl.io.FileSpec; import org.apache.pig.impl.plan.OperatorKey; import org.apache.pig.impl.util.ObjectSerializer; import org.apache.pig.impl.util.Pair; import org.apache.pig.impl.util.UDFContext; public class PigInputFormat extends InputFormat<Text, Tuple> { public static final Log log = LogFactory .getLog(PigInputFormat.class); private static final PathFilter hiddenFileFilter = new PathFilter() { public boolean accept(Path p) { String name = p.getName(); return !name.startsWith("_") && !name.startsWith("."); } }; public static final String PIG_INPUTS = "pig.inputs"; /** * @deprecated Use {@link UDFContext} instead in the following way to get * the job's {@link Configuration}: * <pre>UdfContext.getUdfContext().getJobConf()</pre> */ @Deprecated public static Configuration sJob; /* (non-Javadoc) * @see org.apache.hadoop.mapreduce.InputFormat#createRecordReader(org.apache.hadoop.mapreduce.InputSplit, org.apache.hadoop.mapreduce.TaskAttemptContext) */ @Override public org.apache.hadoop.mapreduce.RecordReader<Text, Tuple> createRecordReader( org.apache.hadoop.mapreduce.InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { // We need to create a TaskAttemptContext based on the Configuration which // was used in the getSplits() to produce the split supplied here. For // this, let's find out the input of the script which produced the split // supplied here and then get the corresponding Configuration and setup // TaskAttemptContext based on it and then call the real InputFormat's // createRecordReader() method PigSplit pigSplit = (PigSplit)split; activeSplit = pigSplit; // XXX hadoop 20 new API integration: get around a hadoop 20 bug by // passing total # of splits to each split so it can be retrieved // here and set it to the configuration object. This number is needed // by PoissonSampleLoader to compute the number of samples int n = pigSplit.getTotalSplits(); context.getConfiguration().setInt("pig.mapsplits.count", n); Configuration conf = context.getConfiguration(); LoadFunc loadFunc = getLoadFunc(pigSplit.getInputIndex(), conf); // Pass loader signature to LoadFunc and to InputFormat through // the conf passLoadSignature(loadFunc, pigSplit.getInputIndex(), conf); // merge entries from split specific conf into the conf we got PigInputFormat.mergeSplitSpecificConf(loadFunc, pigSplit, conf); // for backward compatibility PigInputFormat.sJob = conf; InputFormat inputFormat = loadFunc.getInputFormat(); return new PigRecordReader(inputFormat, pigSplit, loadFunc, context); } /** * get the corresponding configuration for the input on which the split * is based and merge it with the Conf supplied * * package level access so that this is not publicly used elsewhere * @throws IOException */ static void mergeSplitSpecificConf(LoadFunc loadFunc, PigSplit pigSplit, Configuration originalConf) throws IOException { // set up conf with entries from input specific conf Job job = new Job(originalConf); loadFunc.setLocation(getLoadLocation(pigSplit.getInputIndex(), originalConf), job); // The above setLocation call could write to the conf within // the job - merge that updated conf with original conf ConfigurationUtil.mergeConf(originalConf, job.getConfiguration()); } /** * @param inputIndex * @param conf * @return * @throws IOException */ @SuppressWarnings("unchecked") private static LoadFunc getLoadFunc(int inputIndex, Configuration conf) throws IOException { ArrayList<FileSpec> inputs = (ArrayList<FileSpec>) ObjectSerializer.deserialize( conf.get(PIG_INPUTS)); FuncSpec loadFuncSpec = inputs.get(inputIndex).getFuncSpec(); return (LoadFunc) PigContext.instantiateFuncFromSpec(loadFuncSpec); } @SuppressWarnings("unchecked") private static String getLoadLocation(int inputIndex, Configuration conf) throws IOException { ArrayList<FileSpec> inputs = (ArrayList<FileSpec>) ObjectSerializer.deserialize( conf.get(PIG_INPUTS)); return inputs.get(inputIndex).getFileName(); } /** * Pass loader signature to LoadFunc and to InputFormat through * the conf * @param loadFunc the Loadfunc to set the signature on * @param inputIndex the index of the input corresponding to the loadfunc * @param conf the Configuration object into which the signature should be * set * @throws IOException on failure */ @SuppressWarnings("unchecked") static void passLoadSignature(LoadFunc loadFunc, int inputIndex, Configuration conf) throws IOException { List<String> inpSignatureLists = (ArrayList<String>)ObjectSerializer.deserialize( conf.get("pig.inpSignatures")); // signature can be null for intermediate jobs where it will not // be required to be passed down if(inpSignatureLists.get(inputIndex) != null) { loadFunc.setUDFContextSignature(inpSignatureLists.get(inputIndex)); conf.set("pig.loader.signature", inpSignatureLists.get(inputIndex)); } MapRedUtil.setupUDFContext(conf); } /* (non-Javadoc) * @see org.apache.hadoop.mapreduce.InputFormat#getSplits(org.apache.hadoop.mapreduce.JobContext) */ @SuppressWarnings("unchecked") @Override public List<InputSplit> getSplits(JobContext jobcontext) throws IOException, InterruptedException { Configuration conf = jobcontext.getConfiguration(); ArrayList<FileSpec> inputs; ArrayList<ArrayList<OperatorKey>> inpTargets; PigContext pigContext; try { inputs = (ArrayList<FileSpec>) ObjectSerializer .deserialize(conf.get("pig.inputs")); inpTargets = (ArrayList<ArrayList<OperatorKey>>) ObjectSerializer .deserialize(conf.get("pig.inpTargets")); pigContext = (PigContext) ObjectSerializer.deserialize(conf .get("pig.pigContext")); PigContext.setPackageImportList((ArrayList<String>)ObjectSerializer.deserialize(conf.get("udf.import.list"))); + MapRedUtil.setupUDFContext(conf); } catch (Exception e) { int errCode = 2094; String msg = "Unable to deserialize object."; throw new ExecException(msg, errCode, PigException.BUG, e); } ArrayList<InputSplit> splits = new ArrayList<InputSplit>(); for (int i = 0; i < inputs.size(); i++) { try { Path path = new Path(inputs.get(i).getFileName()); FileSystem fs; try { fs = path.getFileSystem(conf); } catch (Exception e) { // If an application specific // scheme was used // (e.g.: "hbase://table") we will fail // getting the file system. That's // ok, we just use the dfs in that case. fs = new Path("/").getFileSystem(conf); } // if the execution is against Mapred DFS, set // working dir to /user/<userid> if(pigContext.getExecType() == ExecType.MAPREDUCE) { fs.setWorkingDirectory(jobcontext.getWorkingDirectory()); } // first pass input location to the loader - for this send a // clone of the configuration we have - this is so that if the // loader (or the inputformat of the loader) decide to store the // input location into the configuration (for example, // FileInputFormat stores this in mapred.input.dir in the conf), // then for different inputs, the loader's don't end up // over-writing the same conf. FuncSpec loadFuncSpec = inputs.get(i).getFuncSpec(); LoadFunc loadFunc = (LoadFunc) PigContext.instantiateFuncFromSpec( loadFuncSpec); boolean combinable = !(loadFunc instanceof MergeJoinIndexer) && !(IndexableLoadFunc.class.isAssignableFrom(loadFunc.getClass())) && !(CollectableLoadFunc.class.isAssignableFrom(loadFunc.getClass()) && OrderedLoadFunc.class.isAssignableFrom(loadFunc.getClass())); if (combinable) combinable = !conf.getBoolean("pig.noSplitCombination", false); Configuration confClone = new Configuration(conf); Job inputSpecificJob = new Job(confClone); // Pass loader signature to LoadFunc and to InputFormat through // the conf passLoadSignature(loadFunc, i, inputSpecificJob.getConfiguration()); loadFunc.setLocation(inputs.get(i).getFileName(), inputSpecificJob); // The above setLocation call could write to the conf within // the inputSpecificJob - use this updated conf // get the InputFormat from it and ask for splits InputFormat inpFormat = loadFunc.getInputFormat(); List<InputSplit> oneInputSplits = inpFormat.getSplits( new JobContext(inputSpecificJob.getConfiguration(), jobcontext.getJobID())); List<InputSplit> oneInputPigSplits = getPigSplits( oneInputSplits, i, inpTargets.get(i), fs.getDefaultBlockSize(), combinable, confClone); splits.addAll(oneInputPigSplits); } catch (ExecException ee) { throw ee; } catch (Exception e) { int errCode = 2118; String msg = "Unable to create input splits for: " + inputs.get(i).getFileName(); if(e.getMessage() !=null && (!e.getMessage().isEmpty()) ){ throw new ExecException(e.getMessage(), errCode, PigException.BUG, e); }else{ throw new ExecException(msg, errCode, PigException.BUG, e); } } } // XXX hadoop 20 new API integration: get around a hadoop 20 bug by // passing total # of splits to each split so that it can be retrieved // in the RecordReader method when called by mapreduce framework later. int n = splits.size(); // also passing the multi-input flag to the back-end so that // the multi-input record counters can be created int m = inputs.size(); for (InputSplit split : splits) { ((PigSplit) split).setTotalSplits(n); if (m > 1) ((PigSplit) split).setMultiInputs(true); } return splits; } protected List<InputSplit> getPigSplits(List<InputSplit> oneInputSplits, int inputIndex, ArrayList<OperatorKey> targetOps, long blockSize, boolean combinable, Configuration conf) throws IOException, InterruptedException { ArrayList<InputSplit> pigSplits = new ArrayList<InputSplit>(); if (!combinable) { int splitIndex = 0; for (InputSplit inputSplit : oneInputSplits) { PigSplit pigSplit = new PigSplit(new InputSplit[] {inputSplit}, inputIndex, targetOps, splitIndex++); pigSplit.setConf(conf); pigSplits.add(pigSplit); } return pigSplits; } else { long maxCombinedSplitSize = conf.getLong("pig.maxCombinedSplitSize", 0); if (maxCombinedSplitSize== 0) // default is the block size maxCombinedSplitSize = blockSize; List<List<InputSplit>> combinedSplits = MapRedUtil.getCombinePigSplits(oneInputSplits, maxCombinedSplitSize, conf); for (int i = 0; i < combinedSplits.size(); i++) pigSplits.add(createPigSplit(combinedSplits.get(i), inputIndex, targetOps, i, conf)); return pigSplits; } } private InputSplit createPigSplit(List<InputSplit> combinedSplits, int inputIndex, ArrayList<OperatorKey> targetOps, int splitIndex, Configuration conf) { PigSplit pigSplit = new PigSplit(combinedSplits.toArray(new InputSplit[0]), inputIndex, targetOps, splitIndex); pigSplit.setConf(conf); return pigSplit; } public static PigSplit getActiveSplit() { return activeSplit; } private static PigSplit activeSplit; }
true
true
public List<InputSplit> getSplits(JobContext jobcontext) throws IOException, InterruptedException { Configuration conf = jobcontext.getConfiguration(); ArrayList<FileSpec> inputs; ArrayList<ArrayList<OperatorKey>> inpTargets; PigContext pigContext; try { inputs = (ArrayList<FileSpec>) ObjectSerializer .deserialize(conf.get("pig.inputs")); inpTargets = (ArrayList<ArrayList<OperatorKey>>) ObjectSerializer .deserialize(conf.get("pig.inpTargets")); pigContext = (PigContext) ObjectSerializer.deserialize(conf .get("pig.pigContext")); PigContext.setPackageImportList((ArrayList<String>)ObjectSerializer.deserialize(conf.get("udf.import.list"))); } catch (Exception e) { int errCode = 2094; String msg = "Unable to deserialize object."; throw new ExecException(msg, errCode, PigException.BUG, e); } ArrayList<InputSplit> splits = new ArrayList<InputSplit>(); for (int i = 0; i < inputs.size(); i++) { try { Path path = new Path(inputs.get(i).getFileName()); FileSystem fs; try { fs = path.getFileSystem(conf); } catch (Exception e) { // If an application specific // scheme was used // (e.g.: "hbase://table") we will fail // getting the file system. That's // ok, we just use the dfs in that case. fs = new Path("/").getFileSystem(conf); } // if the execution is against Mapred DFS, set // working dir to /user/<userid> if(pigContext.getExecType() == ExecType.MAPREDUCE) { fs.setWorkingDirectory(jobcontext.getWorkingDirectory()); } // first pass input location to the loader - for this send a // clone of the configuration we have - this is so that if the // loader (or the inputformat of the loader) decide to store the // input location into the configuration (for example, // FileInputFormat stores this in mapred.input.dir in the conf), // then for different inputs, the loader's don't end up // over-writing the same conf. FuncSpec loadFuncSpec = inputs.get(i).getFuncSpec(); LoadFunc loadFunc = (LoadFunc) PigContext.instantiateFuncFromSpec( loadFuncSpec); boolean combinable = !(loadFunc instanceof MergeJoinIndexer) && !(IndexableLoadFunc.class.isAssignableFrom(loadFunc.getClass())) && !(CollectableLoadFunc.class.isAssignableFrom(loadFunc.getClass()) && OrderedLoadFunc.class.isAssignableFrom(loadFunc.getClass())); if (combinable) combinable = !conf.getBoolean("pig.noSplitCombination", false); Configuration confClone = new Configuration(conf); Job inputSpecificJob = new Job(confClone); // Pass loader signature to LoadFunc and to InputFormat through // the conf passLoadSignature(loadFunc, i, inputSpecificJob.getConfiguration()); loadFunc.setLocation(inputs.get(i).getFileName(), inputSpecificJob); // The above setLocation call could write to the conf within // the inputSpecificJob - use this updated conf // get the InputFormat from it and ask for splits InputFormat inpFormat = loadFunc.getInputFormat(); List<InputSplit> oneInputSplits = inpFormat.getSplits( new JobContext(inputSpecificJob.getConfiguration(), jobcontext.getJobID())); List<InputSplit> oneInputPigSplits = getPigSplits( oneInputSplits, i, inpTargets.get(i), fs.getDefaultBlockSize(), combinable, confClone); splits.addAll(oneInputPigSplits); } catch (ExecException ee) { throw ee; } catch (Exception e) { int errCode = 2118; String msg = "Unable to create input splits for: " + inputs.get(i).getFileName(); if(e.getMessage() !=null && (!e.getMessage().isEmpty()) ){ throw new ExecException(e.getMessage(), errCode, PigException.BUG, e); }else{ throw new ExecException(msg, errCode, PigException.BUG, e); } } } // XXX hadoop 20 new API integration: get around a hadoop 20 bug by // passing total # of splits to each split so that it can be retrieved // in the RecordReader method when called by mapreduce framework later. int n = splits.size(); // also passing the multi-input flag to the back-end so that // the multi-input record counters can be created int m = inputs.size(); for (InputSplit split : splits) { ((PigSplit) split).setTotalSplits(n); if (m > 1) ((PigSplit) split).setMultiInputs(true); } return splits; }
public List<InputSplit> getSplits(JobContext jobcontext) throws IOException, InterruptedException { Configuration conf = jobcontext.getConfiguration(); ArrayList<FileSpec> inputs; ArrayList<ArrayList<OperatorKey>> inpTargets; PigContext pigContext; try { inputs = (ArrayList<FileSpec>) ObjectSerializer .deserialize(conf.get("pig.inputs")); inpTargets = (ArrayList<ArrayList<OperatorKey>>) ObjectSerializer .deserialize(conf.get("pig.inpTargets")); pigContext = (PigContext) ObjectSerializer.deserialize(conf .get("pig.pigContext")); PigContext.setPackageImportList((ArrayList<String>)ObjectSerializer.deserialize(conf.get("udf.import.list"))); MapRedUtil.setupUDFContext(conf); } catch (Exception e) { int errCode = 2094; String msg = "Unable to deserialize object."; throw new ExecException(msg, errCode, PigException.BUG, e); } ArrayList<InputSplit> splits = new ArrayList<InputSplit>(); for (int i = 0; i < inputs.size(); i++) { try { Path path = new Path(inputs.get(i).getFileName()); FileSystem fs; try { fs = path.getFileSystem(conf); } catch (Exception e) { // If an application specific // scheme was used // (e.g.: "hbase://table") we will fail // getting the file system. That's // ok, we just use the dfs in that case. fs = new Path("/").getFileSystem(conf); } // if the execution is against Mapred DFS, set // working dir to /user/<userid> if(pigContext.getExecType() == ExecType.MAPREDUCE) { fs.setWorkingDirectory(jobcontext.getWorkingDirectory()); } // first pass input location to the loader - for this send a // clone of the configuration we have - this is so that if the // loader (or the inputformat of the loader) decide to store the // input location into the configuration (for example, // FileInputFormat stores this in mapred.input.dir in the conf), // then for different inputs, the loader's don't end up // over-writing the same conf. FuncSpec loadFuncSpec = inputs.get(i).getFuncSpec(); LoadFunc loadFunc = (LoadFunc) PigContext.instantiateFuncFromSpec( loadFuncSpec); boolean combinable = !(loadFunc instanceof MergeJoinIndexer) && !(IndexableLoadFunc.class.isAssignableFrom(loadFunc.getClass())) && !(CollectableLoadFunc.class.isAssignableFrom(loadFunc.getClass()) && OrderedLoadFunc.class.isAssignableFrom(loadFunc.getClass())); if (combinable) combinable = !conf.getBoolean("pig.noSplitCombination", false); Configuration confClone = new Configuration(conf); Job inputSpecificJob = new Job(confClone); // Pass loader signature to LoadFunc and to InputFormat through // the conf passLoadSignature(loadFunc, i, inputSpecificJob.getConfiguration()); loadFunc.setLocation(inputs.get(i).getFileName(), inputSpecificJob); // The above setLocation call could write to the conf within // the inputSpecificJob - use this updated conf // get the InputFormat from it and ask for splits InputFormat inpFormat = loadFunc.getInputFormat(); List<InputSplit> oneInputSplits = inpFormat.getSplits( new JobContext(inputSpecificJob.getConfiguration(), jobcontext.getJobID())); List<InputSplit> oneInputPigSplits = getPigSplits( oneInputSplits, i, inpTargets.get(i), fs.getDefaultBlockSize(), combinable, confClone); splits.addAll(oneInputPigSplits); } catch (ExecException ee) { throw ee; } catch (Exception e) { int errCode = 2118; String msg = "Unable to create input splits for: " + inputs.get(i).getFileName(); if(e.getMessage() !=null && (!e.getMessage().isEmpty()) ){ throw new ExecException(e.getMessage(), errCode, PigException.BUG, e); }else{ throw new ExecException(msg, errCode, PigException.BUG, e); } } } // XXX hadoop 20 new API integration: get around a hadoop 20 bug by // passing total # of splits to each split so that it can be retrieved // in the RecordReader method when called by mapreduce framework later. int n = splits.size(); // also passing the multi-input flag to the back-end so that // the multi-input record counters can be created int m = inputs.size(); for (InputSplit split : splits) { ((PigSplit) split).setTotalSplits(n); if (m > 1) ((PigSplit) split).setMultiInputs(true); } return splits; }
diff --git a/src/main/java/hudson/scm/SubversionRepositoryStatus.java b/src/main/java/hudson/scm/SubversionRepositoryStatus.java index f01dc84..d18f7d9 100644 --- a/src/main/java/hudson/scm/SubversionRepositoryStatus.java +++ b/src/main/java/hudson/scm/SubversionRepositoryStatus.java @@ -1,105 +1,106 @@ package hudson.scm; import hudson.model.AbstractModelObject; import hudson.model.AbstractProject; import hudson.model.Hudson; import hudson.scm.SubversionSCM.ModuleLocation; import hudson.triggers.SCMTrigger; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.tmatesoft.svn.core.SVNException; import javax.servlet.ServletException; import static javax.servlet.http.HttpServletResponse.SC_OK; import java.io.BufferedReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.UUID; import static java.util.logging.Level.FINE; import static java.util.logging.Level.WARNING; import java.util.logging.Logger; /** * Per repository status. * * @author Kohsuke Kawaguchi * @see SubversionStatus */ public class SubversionRepositoryStatus extends AbstractModelObject { public final UUID uuid; public SubversionRepositoryStatus(UUID uuid) { this.uuid = uuid; } public String getDisplayName() { return uuid.toString(); } public String getSearchUrl() { return uuid.toString(); } /** * Notify the commit to this repository. * * <p> * Because this URL is not guarded, we can't really trust the data that's sent to us. But we intentionally * don't protect this URL to simplify <tt>post-commit</tt> script set up. */ public void doNotifyCommit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { requirePOST(); // compute the affected paths Set<String> affectedPath = new HashSet<String>(); String line; - while((line=new BufferedReader(req.getReader()).readLine())!=null) { + BufferedReader r = new BufferedReader(req.getReader()); + while((line=r.readLine())!=null) { LOGGER.finer("Reading line: "+line); affectedPath.add(line.substring(4)); } if(LOGGER.isLoggable(FINE)) LOGGER.fine("Change reported to Subversion repository "+uuid+" on "+affectedPath); OUTER: for (AbstractProject<?,?> p : Hudson.getInstance().getItems(AbstractProject.class)) { try { SCM scm = p.getScm(); if (!(scm instanceof SubversionSCM)) continue; SCMTrigger trigger = p.getTrigger(SCMTrigger.class); if(trigger==null) continue; SubversionSCM sscm = (SubversionSCM) scm; for (ModuleLocation loc : sscm.getLocations()) { if(!loc.getUUID().equals(uuid)) continue; // different repository String m = loc.getSVNURL().getPath(); String n = loc.getRepositoryRoot().getPath(); if(!m.startsWith(n)) continue; // repository root should be a subpath of the module path, but be defensive String remaining = m.substring(n.length()); if(remaining.startsWith("/")) remaining=remaining.substring(1); String remainingSlash = remaining + '/'; for (String path : affectedPath) { if(path.equals(remaining) /*for files*/ || path.startsWith(remainingSlash) /*for dirs*/) { // this project is possibly changed. poll now. // if any of the data we used was bogus, the trigger will not detect a chaange LOGGER.fine("Scheduling the immediate polling of "+p); trigger.run(); continue OUTER; } } } } catch (SVNException e) { LOGGER.log(WARNING,"Failed to handle Subversion commit notification",e); } } rsp.setStatus(SC_OK); } private static final Logger LOGGER = Logger.getLogger(SubversionRepositoryStatus.class.getName()); }
true
true
public void doNotifyCommit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { requirePOST(); // compute the affected paths Set<String> affectedPath = new HashSet<String>(); String line; while((line=new BufferedReader(req.getReader()).readLine())!=null) { LOGGER.finer("Reading line: "+line); affectedPath.add(line.substring(4)); } if(LOGGER.isLoggable(FINE)) LOGGER.fine("Change reported to Subversion repository "+uuid+" on "+affectedPath); OUTER: for (AbstractProject<?,?> p : Hudson.getInstance().getItems(AbstractProject.class)) { try { SCM scm = p.getScm(); if (!(scm instanceof SubversionSCM)) continue; SCMTrigger trigger = p.getTrigger(SCMTrigger.class); if(trigger==null) continue; SubversionSCM sscm = (SubversionSCM) scm; for (ModuleLocation loc : sscm.getLocations()) { if(!loc.getUUID().equals(uuid)) continue; // different repository String m = loc.getSVNURL().getPath(); String n = loc.getRepositoryRoot().getPath(); if(!m.startsWith(n)) continue; // repository root should be a subpath of the module path, but be defensive String remaining = m.substring(n.length()); if(remaining.startsWith("/")) remaining=remaining.substring(1); String remainingSlash = remaining + '/'; for (String path : affectedPath) { if(path.equals(remaining) /*for files*/ || path.startsWith(remainingSlash) /*for dirs*/) { // this project is possibly changed. poll now. // if any of the data we used was bogus, the trigger will not detect a chaange LOGGER.fine("Scheduling the immediate polling of "+p); trigger.run(); continue OUTER; } } } } catch (SVNException e) { LOGGER.log(WARNING,"Failed to handle Subversion commit notification",e); } } rsp.setStatus(SC_OK); }
public void doNotifyCommit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { requirePOST(); // compute the affected paths Set<String> affectedPath = new HashSet<String>(); String line; BufferedReader r = new BufferedReader(req.getReader()); while((line=r.readLine())!=null) { LOGGER.finer("Reading line: "+line); affectedPath.add(line.substring(4)); } if(LOGGER.isLoggable(FINE)) LOGGER.fine("Change reported to Subversion repository "+uuid+" on "+affectedPath); OUTER: for (AbstractProject<?,?> p : Hudson.getInstance().getItems(AbstractProject.class)) { try { SCM scm = p.getScm(); if (!(scm instanceof SubversionSCM)) continue; SCMTrigger trigger = p.getTrigger(SCMTrigger.class); if(trigger==null) continue; SubversionSCM sscm = (SubversionSCM) scm; for (ModuleLocation loc : sscm.getLocations()) { if(!loc.getUUID().equals(uuid)) continue; // different repository String m = loc.getSVNURL().getPath(); String n = loc.getRepositoryRoot().getPath(); if(!m.startsWith(n)) continue; // repository root should be a subpath of the module path, but be defensive String remaining = m.substring(n.length()); if(remaining.startsWith("/")) remaining=remaining.substring(1); String remainingSlash = remaining + '/'; for (String path : affectedPath) { if(path.equals(remaining) /*for files*/ || path.startsWith(remainingSlash) /*for dirs*/) { // this project is possibly changed. poll now. // if any of the data we used was bogus, the trigger will not detect a chaange LOGGER.fine("Scheduling the immediate polling of "+p); trigger.run(); continue OUTER; } } } } catch (SVNException e) { LOGGER.log(WARNING,"Failed to handle Subversion commit notification",e); } } rsp.setStatus(SC_OK); }
diff --git a/R/tests/testdir_javapredict/PredictCSV.java b/R/tests/testdir_javapredict/PredictCSV.java index 7398a6167..2719e373a 100644 --- a/R/tests/testdir_javapredict/PredictCSV.java +++ b/R/tests/testdir_javapredict/PredictCSV.java @@ -1,214 +1,211 @@ import java.io.*; import java.util.HashMap; class PredictCSV { private static String modelClassName; private static String inputCSVFileName; private static String outputCSVFileName; private static int skipFirstLine = -1; private static void usage() { System.out.println(""); System.out.println("usage: java [...java args...] PredictCSV (--header | --noheader) --model modelClassName --input inputCSVFileName --output outputCSVFileName"); System.out.println(""); System.out.println(" model class name is something like GBMModel_blahblahblahblah."); System.out.println(""); System.out.println(" inputCSV is the test data set."); System.out.println(" Specify --header or --noheader as appropriate."); System.out.println(""); System.out.println(" outputCSV is the prediction data set (one row per test data set)."); System.out.println(""); System.exit(1); } private static void usageHeader() { System.out.println("ERROR: One of --header or --noheader must be specified exactly once"); usage(); } private static void parseArgs(String[] args) { for (int i = 0; i < args.length; i++) { String s = args[i]; if (s.equals("--model")) { i++; if (i >= args.length) usage(); modelClassName = args[i]; } else if (s.equals("--input")) { i++; if (i >= args.length) usage(); inputCSVFileName = args[i]; } else if (s.equals("--output")) { i++; if (i >= args.length) usage(); outputCSVFileName = args[i]; } else if (s.equals("--header")) { if (skipFirstLine >= 0) usageHeader(); skipFirstLine = 1; } else if (s.equals("--noheader")) { if (skipFirstLine >= 0) usageHeader(); skipFirstLine = 0; } else { System.out.println("ERROR: Bad parameter: " + s); usage(); } } if (skipFirstLine < 0) { usageHeader(); } if (modelClassName == null) { System.out.println("ERROR: model not specified"); usage(); } if (inputCSVFileName == null) { System.out.println("ERROR: input not specified"); usage(); } if (outputCSVFileName == null) { System.out.println("ERROR: output not specified"); usage(); } } public static void main(String[] args) throws Exception{ parseArgs(args); water.genmodel.GeneratedModel model; model = (water.genmodel.GeneratedModel) Class.forName(modelClassName).newInstance(); BufferedReader input = new BufferedReader(new FileReader(inputCSVFileName)); BufferedWriter output = new BufferedWriter(new FileWriter(outputCSVFileName)); System.out.println("COLS " + model.getNumCols()); // Create map of input variable domain information. // This contains the categorical string to numeric mapping. HashMap<Integer,HashMap<String,Integer>> domainMap = new HashMap<Integer,HashMap<String,Integer>>(); for (int i = 0; i < model.getNumCols(); i++) { String[] domainValues = model.getDomainValues(i); if (domainValues != null) { HashMap<String,Integer> m = new HashMap<String,Integer>(); for (int j = 0; j < domainValues.length; j++) { System.out.println("Putting ("+ i +","+ j +","+ domainValues[j] +")"); m.put(domainValues[j], new Integer(j)); } domainMap.put(i, m); } } // Print outputCSV column names. output.write("predict"); for (int i = 0; i < model.getNumResponseClasses(); i++) { output.write(","); output.write(model.getDomainValues(model.getResponseIdx())[i]); } output.write("\n"); // Loop over inputCSV one row at a time. int lineno = 0; String line = null; + // An array to store predicted values + float[] preds = new float[model.getPredsSize()]; while ((line = input.readLine()) != null) { lineno++; if (skipFirstLine > 0) { skipFirstLine = 0; String[] names = line.trim().split(","); String[] modelNames = model.getNames(); for (int i=0; i < Math.min(names.length, modelNames.length); i++ ) if ( !names[i].equals(modelNames[i]) ) { System.out.println("ERROR: Column names does not match: input column " + i + ". "+names[i]+" != model column "+modelNames[i] ); System.exit(1); } // go to the next line continue; } // Parse the CSV line. Don't handle quoted commas. This isn't a parser test. String trimmedLine = line.trim(); String[] inputColumnsArray = trimmedLine.split(","); - int numInputColumns = model.getNames().length; + int numInputColumns = model.getNames().length-1; // we do not need response ! if (inputColumnsArray.length != numInputColumns) { System.out.println("WARNING: Line " + lineno + " has " + inputColumnsArray.length + " columns (expected " + numInputColumns + ")"); } // Assemble the input values for the row. double[] row = new double[inputColumnsArray.length]; for (int i = 0; i < inputColumnsArray.length; i++) { String cellString = inputColumnsArray[i]; // System.out.println("Line " + lineno +" column ("+ model.getNames()[i] + " == " + i + ") cellString("+cellString+")"); String[] domainValues = model.getDomainValues(i); if (cellString.equals("") || // empty field is default NA (domainValues == null) && ( // if the column is enum then NA is part of domain by default ! cellString.equals("NA") || cellString.equals("N/A") || cellString.equals("-") ) ) { row[i] = Double.NaN; } else { if (domainValues != null) { HashMap m = (HashMap<String,Integer>) domainMap.get(i); assert (m != null); Integer cellOrdinalValue = (Integer) m.get(cellString); if (cellOrdinalValue == null) { System.out.println("WARNING: Line " + lineno + " column ("+ model.getNames()[i] + " == " + i +") has unknown categorical value (" + cellString + ")"); row[i] = Double.NaN; } else { row[i] = (double) cellOrdinalValue.intValue(); } } else { double value = Double.parseDouble(cellString); row[i] = value; } } } // Do the prediction. - float[] preds = new float[model.getNumResponseClasses()+1]; model.predict(row, preds); // Emit the result to the output file. for (int i = 0; i < preds.length; i++) { - if (i == 0) { + if (i == 0 && model.isClassifier()) { // See if there is a domain to map this output value to. String[] domainValues = model.getDomainValues(model.getResponseIdx()); if (domainValues != null) { // Classification. double value = preds[i]; int valueAsInt = (int)value; if (value != (int)valueAsInt) { System.out.println("ERROR: Line " + lineno + " has non-integer output for classification (" + value + ")"); System.exit(1); } String predictedOutputClassLevel = domainValues[valueAsInt]; output.write(predictedOutputClassLevel); } - else { - // Regression. - output.write(Double.toString(preds[i])); - } - } - else { - output.write(","); + } else { + if (i > 0) output.write(","); output.write(Double.toString(preds[i])); + if (!model.isClassifier()) break; } } output.write("\n"); } // Clean up. output.close(); input.close(); // Predictions were successfully generated. Calling program can now compare them with something. System.exit(0); } }
false
true
public static void main(String[] args) throws Exception{ parseArgs(args); water.genmodel.GeneratedModel model; model = (water.genmodel.GeneratedModel) Class.forName(modelClassName).newInstance(); BufferedReader input = new BufferedReader(new FileReader(inputCSVFileName)); BufferedWriter output = new BufferedWriter(new FileWriter(outputCSVFileName)); System.out.println("COLS " + model.getNumCols()); // Create map of input variable domain information. // This contains the categorical string to numeric mapping. HashMap<Integer,HashMap<String,Integer>> domainMap = new HashMap<Integer,HashMap<String,Integer>>(); for (int i = 0; i < model.getNumCols(); i++) { String[] domainValues = model.getDomainValues(i); if (domainValues != null) { HashMap<String,Integer> m = new HashMap<String,Integer>(); for (int j = 0; j < domainValues.length; j++) { System.out.println("Putting ("+ i +","+ j +","+ domainValues[j] +")"); m.put(domainValues[j], new Integer(j)); } domainMap.put(i, m); } } // Print outputCSV column names. output.write("predict"); for (int i = 0; i < model.getNumResponseClasses(); i++) { output.write(","); output.write(model.getDomainValues(model.getResponseIdx())[i]); } output.write("\n"); // Loop over inputCSV one row at a time. int lineno = 0; String line = null; while ((line = input.readLine()) != null) { lineno++; if (skipFirstLine > 0) { skipFirstLine = 0; String[] names = line.trim().split(","); String[] modelNames = model.getNames(); for (int i=0; i < Math.min(names.length, modelNames.length); i++ ) if ( !names[i].equals(modelNames[i]) ) { System.out.println("ERROR: Column names does not match: input column " + i + ". "+names[i]+" != model column "+modelNames[i] ); System.exit(1); } // go to the next line continue; } // Parse the CSV line. Don't handle quoted commas. This isn't a parser test. String trimmedLine = line.trim(); String[] inputColumnsArray = trimmedLine.split(","); int numInputColumns = model.getNames().length; if (inputColumnsArray.length != numInputColumns) { System.out.println("WARNING: Line " + lineno + " has " + inputColumnsArray.length + " columns (expected " + numInputColumns + ")"); } // Assemble the input values for the row. double[] row = new double[inputColumnsArray.length]; for (int i = 0; i < inputColumnsArray.length; i++) { String cellString = inputColumnsArray[i]; // System.out.println("Line " + lineno +" column ("+ model.getNames()[i] + " == " + i + ") cellString("+cellString+")"); String[] domainValues = model.getDomainValues(i); if (cellString.equals("") || // empty field is default NA (domainValues == null) && ( // if the column is enum then NA is part of domain by default ! cellString.equals("NA") || cellString.equals("N/A") || cellString.equals("-") ) ) { row[i] = Double.NaN; } else { if (domainValues != null) { HashMap m = (HashMap<String,Integer>) domainMap.get(i); assert (m != null); Integer cellOrdinalValue = (Integer) m.get(cellString); if (cellOrdinalValue == null) { System.out.println("WARNING: Line " + lineno + " column ("+ model.getNames()[i] + " == " + i +") has unknown categorical value (" + cellString + ")"); row[i] = Double.NaN; } else { row[i] = (double) cellOrdinalValue.intValue(); } } else { double value = Double.parseDouble(cellString); row[i] = value; } } } // Do the prediction. float[] preds = new float[model.getNumResponseClasses()+1]; model.predict(row, preds); // Emit the result to the output file. for (int i = 0; i < preds.length; i++) { if (i == 0) { // See if there is a domain to map this output value to. String[] domainValues = model.getDomainValues(model.getResponseIdx()); if (domainValues != null) { // Classification. double value = preds[i]; int valueAsInt = (int)value; if (value != (int)valueAsInt) { System.out.println("ERROR: Line " + lineno + " has non-integer output for classification (" + value + ")"); System.exit(1); } String predictedOutputClassLevel = domainValues[valueAsInt]; output.write(predictedOutputClassLevel); } else { // Regression. output.write(Double.toString(preds[i])); } } else { output.write(","); output.write(Double.toString(preds[i])); } } output.write("\n"); } // Clean up. output.close(); input.close(); // Predictions were successfully generated. Calling program can now compare them with something. System.exit(0); }
public static void main(String[] args) throws Exception{ parseArgs(args); water.genmodel.GeneratedModel model; model = (water.genmodel.GeneratedModel) Class.forName(modelClassName).newInstance(); BufferedReader input = new BufferedReader(new FileReader(inputCSVFileName)); BufferedWriter output = new BufferedWriter(new FileWriter(outputCSVFileName)); System.out.println("COLS " + model.getNumCols()); // Create map of input variable domain information. // This contains the categorical string to numeric mapping. HashMap<Integer,HashMap<String,Integer>> domainMap = new HashMap<Integer,HashMap<String,Integer>>(); for (int i = 0; i < model.getNumCols(); i++) { String[] domainValues = model.getDomainValues(i); if (domainValues != null) { HashMap<String,Integer> m = new HashMap<String,Integer>(); for (int j = 0; j < domainValues.length; j++) { System.out.println("Putting ("+ i +","+ j +","+ domainValues[j] +")"); m.put(domainValues[j], new Integer(j)); } domainMap.put(i, m); } } // Print outputCSV column names. output.write("predict"); for (int i = 0; i < model.getNumResponseClasses(); i++) { output.write(","); output.write(model.getDomainValues(model.getResponseIdx())[i]); } output.write("\n"); // Loop over inputCSV one row at a time. int lineno = 0; String line = null; // An array to store predicted values float[] preds = new float[model.getPredsSize()]; while ((line = input.readLine()) != null) { lineno++; if (skipFirstLine > 0) { skipFirstLine = 0; String[] names = line.trim().split(","); String[] modelNames = model.getNames(); for (int i=0; i < Math.min(names.length, modelNames.length); i++ ) if ( !names[i].equals(modelNames[i]) ) { System.out.println("ERROR: Column names does not match: input column " + i + ". "+names[i]+" != model column "+modelNames[i] ); System.exit(1); } // go to the next line continue; } // Parse the CSV line. Don't handle quoted commas. This isn't a parser test. String trimmedLine = line.trim(); String[] inputColumnsArray = trimmedLine.split(","); int numInputColumns = model.getNames().length-1; // we do not need response ! if (inputColumnsArray.length != numInputColumns) { System.out.println("WARNING: Line " + lineno + " has " + inputColumnsArray.length + " columns (expected " + numInputColumns + ")"); } // Assemble the input values for the row. double[] row = new double[inputColumnsArray.length]; for (int i = 0; i < inputColumnsArray.length; i++) { String cellString = inputColumnsArray[i]; // System.out.println("Line " + lineno +" column ("+ model.getNames()[i] + " == " + i + ") cellString("+cellString+")"); String[] domainValues = model.getDomainValues(i); if (cellString.equals("") || // empty field is default NA (domainValues == null) && ( // if the column is enum then NA is part of domain by default ! cellString.equals("NA") || cellString.equals("N/A") || cellString.equals("-") ) ) { row[i] = Double.NaN; } else { if (domainValues != null) { HashMap m = (HashMap<String,Integer>) domainMap.get(i); assert (m != null); Integer cellOrdinalValue = (Integer) m.get(cellString); if (cellOrdinalValue == null) { System.out.println("WARNING: Line " + lineno + " column ("+ model.getNames()[i] + " == " + i +") has unknown categorical value (" + cellString + ")"); row[i] = Double.NaN; } else { row[i] = (double) cellOrdinalValue.intValue(); } } else { double value = Double.parseDouble(cellString); row[i] = value; } } } // Do the prediction. model.predict(row, preds); // Emit the result to the output file. for (int i = 0; i < preds.length; i++) { if (i == 0 && model.isClassifier()) { // See if there is a domain to map this output value to. String[] domainValues = model.getDomainValues(model.getResponseIdx()); if (domainValues != null) { // Classification. double value = preds[i]; int valueAsInt = (int)value; if (value != (int)valueAsInt) { System.out.println("ERROR: Line " + lineno + " has non-integer output for classification (" + value + ")"); System.exit(1); } String predictedOutputClassLevel = domainValues[valueAsInt]; output.write(predictedOutputClassLevel); } } else { if (i > 0) output.write(","); output.write(Double.toString(preds[i])); if (!model.isClassifier()) break; } } output.write("\n"); } // Clean up. output.close(); input.close(); // Predictions were successfully generated. Calling program can now compare them with something. System.exit(0); }
diff --git a/pace-base/src/main/java/com/pace/base/utility/PafXStream.java b/pace-base/src/main/java/com/pace/base/utility/PafXStream.java index 78f1769f..08334153 100644 --- a/pace-base/src/main/java/com/pace/base/utility/PafXStream.java +++ b/pace-base/src/main/java/com/pace/base/utility/PafXStream.java @@ -1,484 +1,485 @@ /* * File: @(#)PafXStream.java Package: com.pace.base.utility Project: Paf Base Libraries * Created: Feb 13, 2005 By: JWatkins * Version: x.xx * * Copyright (c) 2005-2007 Palladium Group, Inc. All rights reserved. * * This software is the confidential and proprietary information of Palladium Group, Inc. * ("Confidential Information"). You shall not disclose such Confidential Information and * should use it only in accordance with the terms of the license agreement you entered into * with Palladium Group, Inc. * * * Date Author Version Changes xx/xx/xx xxxxxxxx x.xx .............. * */ package com.pace.base.utility; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.pace.base.PafBaseConstants; import com.pace.base.PafConfigFileNotFoundException; import com.pace.base.PafErrSeverity; import com.pace.base.app.*; import com.pace.base.comm.CustomMenuDef; import com.pace.base.comm.PafPlannerConfig; import com.pace.base.comm.PafViewTreeItem; import com.pace.base.db.membertags.MemberTagCommentEntry; import com.pace.base.db.membertags.MemberTagDef; import com.pace.base.funcs.CustomFunctionDef; import com.pace.base.rules.*; import com.pace.base.ui.PafProject; import com.pace.base.ui.PafServer; import com.pace.base.view.*; import com.thoughtworks.xstream.XStream; /** * * PafXStream is a wrapper class for XStream. * * @author JWatkins * @version x.xx * */ public class PafXStream { private static final String UTF_8 = "UTF-8"; //instance of Logger private static Logger logger = Logger.getLogger(PafXStream.class); //instance of XStream private static XStream xs = getXStream(); //a map that is keyed off of root node name and has a value of matching namespace private static Map<String, String> namespaceHeaderMap; private static final String ARRAY = "-array"; public static final String PAF_APPLICATION_DEF = "Application"; public static final String PAF_APPLICATION_DEF_ARRAY = PAF_APPLICATION_DEF + ARRAY; public static final String CUSTOM_MENU_DEF = "CustomMenuDef"; public static final String CUSTOM_MENU_DEF_ARRAY = CUSTOM_MENU_DEF + ARRAY; public static final String CUSTOM_FUNCTION_DEF = "CustomFunctionDef"; public static final String CUSTOM_FUNCTION_DEF_ARRAY = CUSTOM_FUNCTION_DEF + ARRAY; public static final String VERSION_DEF = "VersionDef"; public static final String VERSION_DEF_ARRAY = VERSION_DEF + ARRAY; public static final String RULE_SET = "RuleSet"; public static final String ROUNDING_RULE = "RoundingRule"; public static final String ROUNDING_RULE_ARRAY = ROUNDING_RULE + ARRAY; public static final String MEASURE_DEF = "MeasureDef"; public static final String MEASURE_DEF_ARRAY = MEASURE_DEF + ARRAY; public static final String VIEW_SECTION_DEF = "ViewSection"; // protected constructor to control access protected PafXStream() { } /** * Returns singleton XStream object. If XStream is null, initilizes it and creates it. * * @return XStream object for custom serialization scenarios */ public static XStream getXStream() { if (xs == null) { initXStream(); } return xs; } /** * Initializes the xstream class to standard paf aliases probably will expand to use either annotations or * load from property / constants file */ private static void initXStream() { //xs = new XStream(new DomDriver("UTF-16")); xs = new XStream(); //writes out all xml xs.setMode(XStream.NO_REFERENCES); xs.alias("PafView", PafView.class); xs.alias("UserSelection", PafUserSelection.class); xs.alias(VIEW_SECTION_DEF, PafViewSection.class); xs.alias("ViewTuple", ViewTuple.class); xs.alias("PageTuple", PageTuple.class); xs.alias("ViewHeader", PafViewHeader.class); xs.alias("NumberFormat", PafNumberFormat.class); xs.alias("NumericMemberFormat", NumericMemberFormat.class); xs.alias("PafBorder", PafBorder.class); xs.alias(RULE_SET, RuleSet.class); xs.alias("RuleGroup", RuleGroup.class); xs.alias("Rule", Rule.class); xs.alias("SeasonList", SeasonList.class); xs.alias("Season", Season.class); xs.alias("PlannerRole", PafPlannerRole.class); xs.alias("PafUser", PafUserSecurity.class); xs.alias(PAF_APPLICATION_DEF, PafApplicationDef.class); xs.alias("WorkSpec", PafWorkSpec.class); xs.alias("DimSpec", PafDimSpec.class); xs.alias("PlanCycle", PlanCycle.class); //xs.alias("ViewSectionUI", PafViewSectionUI.class); xs.alias(MEASURE_DEF, MeasureDef.class); xs.alias(VERSION_DEF, VersionDef.class); xs.alias("VersionFormula", VersionFormula.class); xs.alias("PafViewTreeItem", PafViewTreeItem.class); xs.alias("PafPlannerConfig", PafPlannerConfig.class); // notice this is hierarchy format now xs.alias("GenerationFormat", HierarchyFormat.class); xs.alias("HierarchyFormat", HierarchyFormat.class); xs.alias("Dimension", Dimension.class); xs.alias("LevelFormat", LevelFormat.class); xs.alias("GenFormat", GenFormat.class); + xs.alias("PafStyle", PafStyle.class); xs.alias(CUSTOM_FUNCTION_DEF, CustomFunctionDef.class); xs.alias("CustomActionDef", CustomActionDef.class); xs.alias(CUSTOM_MENU_DEF, CustomMenuDef.class); xs.alias("PafServer", PafServer.class); xs.alias("PafProject", PafProject.class); xs.alias(ROUNDING_RULE, RoundingRule.class); xs.alias("MemberSet", MemberSet.class); xs.alias("PafViewGroup", PafViewGroup.class); xs.alias("PafViewGroupItem", PafViewGroupItem.class); xs.alias("AliasMapping", AliasMapping.class); xs.alias("DynamicMemberDef", DynamicMemberDef.class); xs.alias("MemberTagDef", MemberTagDef.class); xs.alias("MemberTagCommentEntry", MemberTagCommentEntry.class); namespaceHeaderMap = new HashMap<String, String>(); namespaceHeaderMap.put(PAF_APPLICATION_DEF_ARRAY, PAF_APPLICATION_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_APPS); namespaceHeaderMap.put(CUSTOM_MENU_DEF_ARRAY, CUSTOM_MENU_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_CUSTOM_MENUS); namespaceHeaderMap.put(CUSTOM_FUNCTION_DEF_ARRAY, CUSTOM_FUNCTION_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_FUNCTIONS); namespaceHeaderMap.put(MEASURE_DEF_ARRAY, MEASURE_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_MEASURES); namespaceHeaderMap.put(ROUNDING_RULE_ARRAY, ROUNDING_RULE_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_ROUNDING_RULES); namespaceHeaderMap.put(RULE_SET, RULE_SET + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_RULE_SET); namespaceHeaderMap.put(VERSION_DEF_ARRAY, VERSION_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_VERSIONS); } public static Object importObjectFromXml(String fullFilePath, boolean validateFileContents) throws PafConfigFileNotFoundException { logger.debug("Importing object from xml, " + fullFilePath); File f = new File(fullFilePath); Object o = null; //if file doesn't exist, throw not found exception if (!f.exists()) { throw new PafConfigFileNotFoundException("File " + f.getName() + " does not exist.", PafErrSeverity.Info); } InputStream fis = null; InputStreamReader inputStreamReader = null; try { // Create input stream from file fis = new FileInputStream(f); Charset charSet = Charset.forName(UTF_8); // Create reader using UTF-8 inputStreamReader = new InputStreamReader(fis, charSet); // Get the object from XML o = getXStream().fromXML(inputStreamReader); logger.debug("Succesfully import: " + o.getClass().getSimpleName()); } catch (RuntimeException re) { logger.error(re.getMessage()); if ( validateFileContents ) { throw re; } } catch (FileNotFoundException e) { //should have already thrown a PafConfigFileNotFoundException } finally { if ( inputStreamReader != null ) { try { inputStreamReader.close(); } catch (IOException e) { //do nothing } } if ( fis != null ) { try { fis.close(); } catch (IOException e) { //do nothing } } } //return imported object return o; } /** * * Imports an object given the full file path. * * @param fullFilePath path + filename * @return imported object * @throws PafConfigFileNotFoundException */ public static Object importObjectFromXml(String fullFilePath) throws PafConfigFileNotFoundException { return importObjectFromXml(fullFilePath, false); } /** * Imports an object given the file path and file name. * * @param filePath file path * @param fileName file name * @return imported object * @throws PafConfigFileNotFoundException */ public static Object importObjectFromXml(String filePath, String fileName) throws PafConfigFileNotFoundException { return importObjectFromXml(filePath + fileName); } /** * Exports an object to the provided full file path + name. * * @param object object to export * @param fullFileName path + file name */ public static void exportObjectToXml(Object object, String fullFileName) { PafXStream.setMode(XStream.NO_REFERENCES); logger.debug("Exporting object to xml. " + object.getClass().getSimpleName() + " to " + fullFileName); //serialize object to a string xml format String s = xs.toXML(object); s = addXSDHeader(s); //ref to file File f = new File(fullFileName); FileOutputStream fif = null; OutputStreamWriter osw = null; try { //create new file f.createNewFile(); //create file output stream fif = new FileOutputStream(f); Charset charSet = Charset.forName(UTF_8); // Create a writer using UTF-8 osw = new OutputStreamWriter(fif, charSet); //write out bytes from string osw.write(s); logger.debug("Succesfully exported " + object.getClass().getSimpleName()); } catch (Exception ex) { //log warning logger.warn(ex.getMessage()); } finally { if ( osw != null ) { try { osw.close(); } catch (IOException e) { //do nothing } } if ( fif != null ) { try { fif.close(); } catch (IOException e) { //do nothing } } } } /** * Addes a namespace to the string if the string starts with * one of the keys in the namespace map. * * @param s string to attempt to add namespace to * @return s w/ added namespace if beginning of s matches key in map; returns * null if s is null. */ public static String addXSDHeader(String s) { if ( s != null ) { for ( String key : namespaceHeaderMap.keySet() ) { String headerIdnt = PafBaseConstants.XML_OPEN_TAG + key; if ( s.startsWith( headerIdnt )) { String xsdNamespace = namespaceHeaderMap.get(key); if ( ! s.contains(xsdNamespace)) { s = s.replaceFirst(key, xsdNamespace); } break; } } } return s; } /** * Exports an object to the provided full file path + name. * * @param object object to export * @param filePath file path * @param fileName file name */ public static void exportObjectToXml(Object object, String filePath, String fileName) { exportObjectToXml(object, filePath + fileName); } /** * Set's the internal XStream mod * * @param mode */ public static void setMode(int mode) { getXStream().setMode(mode); } /** * Imports an object given the input stream * * @param is input stream * @return imported object */ public static Object importObjectFromXml(InputStream is) throws Exception { logger.debug("Importing object from input stream"); StringBuffer sb = new StringBuffer(); Object o = null; BufferedReader br = null; try { Charset charSet = Charset.forName(UTF_8); br = new BufferedReader(new InputStreamReader(is, charSet)); String thisLine; while ((thisLine = br.readLine()) != null) { sb.append(thisLine); } XStream xs = getXStream(); o = xs.fromXML(sb.toString()); } catch (Exception ex) { logger.error(ex.getMessage()); } finally { if (br != null) { try { br.close(); } catch (IOException e) { // do nothing } } } return o; } }
true
true
private static void initXStream() { //xs = new XStream(new DomDriver("UTF-16")); xs = new XStream(); //writes out all xml xs.setMode(XStream.NO_REFERENCES); xs.alias("PafView", PafView.class); xs.alias("UserSelection", PafUserSelection.class); xs.alias(VIEW_SECTION_DEF, PafViewSection.class); xs.alias("ViewTuple", ViewTuple.class); xs.alias("PageTuple", PageTuple.class); xs.alias("ViewHeader", PafViewHeader.class); xs.alias("NumberFormat", PafNumberFormat.class); xs.alias("NumericMemberFormat", NumericMemberFormat.class); xs.alias("PafBorder", PafBorder.class); xs.alias(RULE_SET, RuleSet.class); xs.alias("RuleGroup", RuleGroup.class); xs.alias("Rule", Rule.class); xs.alias("SeasonList", SeasonList.class); xs.alias("Season", Season.class); xs.alias("PlannerRole", PafPlannerRole.class); xs.alias("PafUser", PafUserSecurity.class); xs.alias(PAF_APPLICATION_DEF, PafApplicationDef.class); xs.alias("WorkSpec", PafWorkSpec.class); xs.alias("DimSpec", PafDimSpec.class); xs.alias("PlanCycle", PlanCycle.class); //xs.alias("ViewSectionUI", PafViewSectionUI.class); xs.alias(MEASURE_DEF, MeasureDef.class); xs.alias(VERSION_DEF, VersionDef.class); xs.alias("VersionFormula", VersionFormula.class); xs.alias("PafViewTreeItem", PafViewTreeItem.class); xs.alias("PafPlannerConfig", PafPlannerConfig.class); // notice this is hierarchy format now xs.alias("GenerationFormat", HierarchyFormat.class); xs.alias("HierarchyFormat", HierarchyFormat.class); xs.alias("Dimension", Dimension.class); xs.alias("LevelFormat", LevelFormat.class); xs.alias("GenFormat", GenFormat.class); xs.alias(CUSTOM_FUNCTION_DEF, CustomFunctionDef.class); xs.alias("CustomActionDef", CustomActionDef.class); xs.alias(CUSTOM_MENU_DEF, CustomMenuDef.class); xs.alias("PafServer", PafServer.class); xs.alias("PafProject", PafProject.class); xs.alias(ROUNDING_RULE, RoundingRule.class); xs.alias("MemberSet", MemberSet.class); xs.alias("PafViewGroup", PafViewGroup.class); xs.alias("PafViewGroupItem", PafViewGroupItem.class); xs.alias("AliasMapping", AliasMapping.class); xs.alias("DynamicMemberDef", DynamicMemberDef.class); xs.alias("MemberTagDef", MemberTagDef.class); xs.alias("MemberTagCommentEntry", MemberTagCommentEntry.class); namespaceHeaderMap = new HashMap<String, String>(); namespaceHeaderMap.put(PAF_APPLICATION_DEF_ARRAY, PAF_APPLICATION_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_APPS); namespaceHeaderMap.put(CUSTOM_MENU_DEF_ARRAY, CUSTOM_MENU_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_CUSTOM_MENUS); namespaceHeaderMap.put(CUSTOM_FUNCTION_DEF_ARRAY, CUSTOM_FUNCTION_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_FUNCTIONS); namespaceHeaderMap.put(MEASURE_DEF_ARRAY, MEASURE_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_MEASURES); namespaceHeaderMap.put(ROUNDING_RULE_ARRAY, ROUNDING_RULE_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_ROUNDING_RULES); namespaceHeaderMap.put(RULE_SET, RULE_SET + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_RULE_SET); namespaceHeaderMap.put(VERSION_DEF_ARRAY, VERSION_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_VERSIONS); }
private static void initXStream() { //xs = new XStream(new DomDriver("UTF-16")); xs = new XStream(); //writes out all xml xs.setMode(XStream.NO_REFERENCES); xs.alias("PafView", PafView.class); xs.alias("UserSelection", PafUserSelection.class); xs.alias(VIEW_SECTION_DEF, PafViewSection.class); xs.alias("ViewTuple", ViewTuple.class); xs.alias("PageTuple", PageTuple.class); xs.alias("ViewHeader", PafViewHeader.class); xs.alias("NumberFormat", PafNumberFormat.class); xs.alias("NumericMemberFormat", NumericMemberFormat.class); xs.alias("PafBorder", PafBorder.class); xs.alias(RULE_SET, RuleSet.class); xs.alias("RuleGroup", RuleGroup.class); xs.alias("Rule", Rule.class); xs.alias("SeasonList", SeasonList.class); xs.alias("Season", Season.class); xs.alias("PlannerRole", PafPlannerRole.class); xs.alias("PafUser", PafUserSecurity.class); xs.alias(PAF_APPLICATION_DEF, PafApplicationDef.class); xs.alias("WorkSpec", PafWorkSpec.class); xs.alias("DimSpec", PafDimSpec.class); xs.alias("PlanCycle", PlanCycle.class); //xs.alias("ViewSectionUI", PafViewSectionUI.class); xs.alias(MEASURE_DEF, MeasureDef.class); xs.alias(VERSION_DEF, VersionDef.class); xs.alias("VersionFormula", VersionFormula.class); xs.alias("PafViewTreeItem", PafViewTreeItem.class); xs.alias("PafPlannerConfig", PafPlannerConfig.class); // notice this is hierarchy format now xs.alias("GenerationFormat", HierarchyFormat.class); xs.alias("HierarchyFormat", HierarchyFormat.class); xs.alias("Dimension", Dimension.class); xs.alias("LevelFormat", LevelFormat.class); xs.alias("GenFormat", GenFormat.class); xs.alias("PafStyle", PafStyle.class); xs.alias(CUSTOM_FUNCTION_DEF, CustomFunctionDef.class); xs.alias("CustomActionDef", CustomActionDef.class); xs.alias(CUSTOM_MENU_DEF, CustomMenuDef.class); xs.alias("PafServer", PafServer.class); xs.alias("PafProject", PafProject.class); xs.alias(ROUNDING_RULE, RoundingRule.class); xs.alias("MemberSet", MemberSet.class); xs.alias("PafViewGroup", PafViewGroup.class); xs.alias("PafViewGroupItem", PafViewGroupItem.class); xs.alias("AliasMapping", AliasMapping.class); xs.alias("DynamicMemberDef", DynamicMemberDef.class); xs.alias("MemberTagDef", MemberTagDef.class); xs.alias("MemberTagCommentEntry", MemberTagCommentEntry.class); namespaceHeaderMap = new HashMap<String, String>(); namespaceHeaderMap.put(PAF_APPLICATION_DEF_ARRAY, PAF_APPLICATION_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_APPS); namespaceHeaderMap.put(CUSTOM_MENU_DEF_ARRAY, CUSTOM_MENU_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_CUSTOM_MENUS); namespaceHeaderMap.put(CUSTOM_FUNCTION_DEF_ARRAY, CUSTOM_FUNCTION_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_FUNCTIONS); namespaceHeaderMap.put(MEASURE_DEF_ARRAY, MEASURE_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_MEASURES); namespaceHeaderMap.put(ROUNDING_RULE_ARRAY, ROUNDING_RULE_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_ROUNDING_RULES); namespaceHeaderMap.put(RULE_SET, RULE_SET + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_RULE_SET); namespaceHeaderMap.put(VERSION_DEF_ARRAY, VERSION_DEF_ARRAY + " " + PafBaseConstants.HTTP_WWW_THEPALLADIUMGROUP_COM_PAF_VERSIONS); }
diff --git a/core/src/main/java/tripleplay/ui/bgs/BorderedBackground.java b/core/src/main/java/tripleplay/ui/bgs/BorderedBackground.java index 3e7bfc34..4d1314df 100644 --- a/core/src/main/java/tripleplay/ui/bgs/BorderedBackground.java +++ b/core/src/main/java/tripleplay/ui/bgs/BorderedBackground.java @@ -1,47 +1,46 @@ // // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.ui.bgs; import pythagoras.f.IDimension; import playn.core.ImmediateLayer; import playn.core.Surface; import static playn.core.PlayN.graphics; import tripleplay.ui.Background; /** * A background that shows a line around a solid color. */ public class BorderedBackground extends Background { public BorderedBackground (int bgColor, int borderColor, float thickness) { _bgColor = bgColor; _borderColor = borderColor; _thickness = thickness; } @Override protected Instance instantiate (final IDimension size) { return new LayerInstance(graphics().createImmediateLayer(new ImmediateLayer.Renderer() { public void render (Surface surf) { float width = size.width(), height = size.height(); - float bot = height-1, right = width-1; surf.setAlpha(alpha); surf.setFillColor(_bgColor).fillRect(0, 0, width, height); surf.setFillColor(_borderColor). - drawLine(0, 0, right, 0, _thickness). - drawLine(right, 0, right, bot, _thickness). - drawLine(right, bot, 0, bot, _thickness). - drawLine(0, bot, 0, 0, _thickness); + fillRect(0, 0, width, _thickness). + fillRect(0, 0, _thickness, height). + fillRect(width-_thickness, 0, _thickness, height). + fillRect(0, height-_thickness, width, _thickness); surf.setAlpha(1); } })); } protected final int _bgColor, _borderColor; protected final float _thickness; }
false
true
protected Instance instantiate (final IDimension size) { return new LayerInstance(graphics().createImmediateLayer(new ImmediateLayer.Renderer() { public void render (Surface surf) { float width = size.width(), height = size.height(); float bot = height-1, right = width-1; surf.setAlpha(alpha); surf.setFillColor(_bgColor).fillRect(0, 0, width, height); surf.setFillColor(_borderColor). drawLine(0, 0, right, 0, _thickness). drawLine(right, 0, right, bot, _thickness). drawLine(right, bot, 0, bot, _thickness). drawLine(0, bot, 0, 0, _thickness); surf.setAlpha(1); } })); }
protected Instance instantiate (final IDimension size) { return new LayerInstance(graphics().createImmediateLayer(new ImmediateLayer.Renderer() { public void render (Surface surf) { float width = size.width(), height = size.height(); surf.setAlpha(alpha); surf.setFillColor(_bgColor).fillRect(0, 0, width, height); surf.setFillColor(_borderColor). fillRect(0, 0, width, _thickness). fillRect(0, 0, _thickness, height). fillRect(width-_thickness, 0, _thickness, height). fillRect(0, height-_thickness, width, _thickness); surf.setAlpha(1); } })); }
diff --git a/src/main/java/lamprey/seprphase3/GUI/Images/Mechanic.java b/src/main/java/lamprey/seprphase3/GUI/Images/Mechanic.java index 9c47cf6..9c07a21 100644 --- a/src/main/java/lamprey/seprphase3/GUI/Images/Mechanic.java +++ b/src/main/java/lamprey/seprphase3/GUI/Images/Mechanic.java @@ -1,118 +1,118 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package lamprey.seprphase3.GUI.Images; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import lamprey.seprphase3.GUI.Screens.Direction; /** * * @author Simeon */ public class Mechanic extends Image { private final static float MOVEMENT_SPEED = 8f; private float mechanicX; private float mechanicWidth; private float moveMechanicTo; private float stateTime; private Animation mechanicAnimation; private TextureRegion frame; private TextureRegionDrawable notMoving; private Direction mechanicDirection; // public Mechanic(Drawable drawable, Direction mechanicDirection) { // super(drawable); // this.mechanicDirection = mechanicDirection; // } // // public Mechanic(Texture texture, Direction mechanicDirection) { // super(texture); // this.mechanicDirection = mechanicDirection; // } public Mechanic(TextureRegion[] sheet, Texture notMoving, Direction mechanicDirection) { super(notMoving); mechanicAnimation = new Animation(0.05f, sheet); this.notMoving = new TextureRegionDrawable(new TextureRegion(notMoving)); this.mechanicDirection = mechanicDirection; stateTime = 0; } @Override public void draw (SpriteBatch batch, float parentAlpha) { if (mechanicDirection == Direction.Right) { super.draw(batch, parentAlpha); } else if (mechanicDirection == Direction.Left) { mechanicX = this.getX(); mechanicWidth = this.getWidth(); this.setX(mechanicX + mechanicWidth); this.setScaleX(-1f); super.draw(batch, parentAlpha); this.setX(mechanicX); this.setScaleX(1f); } } /** * Returns the direction the mechanic is looking at (left or right) * @return */ public Direction getDirection() { return this.mechanicDirection; } /** * Sets the direction the mechanic is looking at (left or right) * @param mechanicDirection the direction */ public void setDirection(Direction mechanicDirection) { this.mechanicDirection = mechanicDirection; } public void moveMechanic() { mechanicX = this.getX(); if (Math.abs(mechanicX - moveMechanicTo) > 0.1) { stateTime += Gdx.graphics.getDeltaTime(); frame = mechanicAnimation.getKeyFrame(stateTime, true); this.setDrawable(new TextureRegionDrawable(frame)); - this.setScaleY(0.8f); + this.setSize(100f, 130f); if (Math.abs(mechanicX - moveMechanicTo) < MOVEMENT_SPEED) { this.setX(moveMechanicTo); } else if (mechanicX < moveMechanicTo) { this.setDirection(Direction.Right); mechanicX += MOVEMENT_SPEED; this.setX(mechanicX); } else if (mechanicX > moveMechanicTo) { this.setDirection(Direction.Left); mechanicX -= MOVEMENT_SPEED; this.setX(mechanicX); } } else { this.setDrawable(notMoving); - this.setScaleY(1f); + this.setSize(105f, 153f); } } public void moveMechanicTo(float moveMechanicTo) { this.moveMechanicTo = moveMechanicTo; } }
false
true
public void moveMechanic() { mechanicX = this.getX(); if (Math.abs(mechanicX - moveMechanicTo) > 0.1) { stateTime += Gdx.graphics.getDeltaTime(); frame = mechanicAnimation.getKeyFrame(stateTime, true); this.setDrawable(new TextureRegionDrawable(frame)); this.setScaleY(0.8f); if (Math.abs(mechanicX - moveMechanicTo) < MOVEMENT_SPEED) { this.setX(moveMechanicTo); } else if (mechanicX < moveMechanicTo) { this.setDirection(Direction.Right); mechanicX += MOVEMENT_SPEED; this.setX(mechanicX); } else if (mechanicX > moveMechanicTo) { this.setDirection(Direction.Left); mechanicX -= MOVEMENT_SPEED; this.setX(mechanicX); } } else { this.setDrawable(notMoving); this.setScaleY(1f); } }
public void moveMechanic() { mechanicX = this.getX(); if (Math.abs(mechanicX - moveMechanicTo) > 0.1) { stateTime += Gdx.graphics.getDeltaTime(); frame = mechanicAnimation.getKeyFrame(stateTime, true); this.setDrawable(new TextureRegionDrawable(frame)); this.setSize(100f, 130f); if (Math.abs(mechanicX - moveMechanicTo) < MOVEMENT_SPEED) { this.setX(moveMechanicTo); } else if (mechanicX < moveMechanicTo) { this.setDirection(Direction.Right); mechanicX += MOVEMENT_SPEED; this.setX(mechanicX); } else if (mechanicX > moveMechanicTo) { this.setDirection(Direction.Left); mechanicX -= MOVEMENT_SPEED; this.setX(mechanicX); } } else { this.setDrawable(notMoving); this.setSize(105f, 153f); } }
diff --git a/src/main/java/com/philihp/weblabora/model/building/CoalHarbor.java b/src/main/java/com/philihp/weblabora/model/building/CoalHarbor.java index ee4cd84..320f7aa 100644 --- a/src/main/java/com/philihp/weblabora/model/building/CoalHarbor.java +++ b/src/main/java/com/philihp/weblabora/model/building/CoalHarbor.java @@ -1,38 +1,38 @@ package com.philihp.weblabora.model.building; import static com.philihp.weblabora.model.TerrainTypeEnum.COAST; import static com.philihp.weblabora.model.TerrainTypeEnum.HILLSIDE; import static com.philihp.weblabora.model.TerrainTypeEnum.PLAINS; import java.util.EnumSet; import java.util.Set; import com.philihp.weblabora.model.Board; import com.philihp.weblabora.model.BuildCost; import com.philihp.weblabora.model.Player; import com.philihp.weblabora.model.SettlementRound; import com.philihp.weblabora.model.TerrainTypeEnum; import com.philihp.weblabora.model.UsageParam; import com.philihp.weblabora.model.UsageParamSingle; import com.philihp.weblabora.model.WeblaboraException; public class CoalHarbor extends BuildingSingleUsage { public CoalHarbor() { super("I31", SettlementRound.C, 4, "Coal Harbor", BuildCost.is().clay(1).stone(2), 0, 12, EnumSet.of(COAST), false); } @Override public void use(Board board, UsageParamSingle param) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); - int iterations = param.getPeat(); + int iterations = param.getCoal(); - if(iterations == 0) throw new WeblaboraException(getName()+" was not supplied any peat."); - if(iterations > 3) throw new WeblaboraException(getName()+" was supplied "+iterations+" peat, but can only consume a maximum of 3."); - player.subtractPeat(iterations); + if(iterations == 0) throw new WeblaboraException(getName()+" was not supplied any coal."); + if(iterations > 3) throw new WeblaboraException(getName()+" was supplied "+iterations+" coal, but can only consume a maximum of 3."); + player.subtractCoal(iterations); player.addCoins(3*iterations); player.addWhiskey(iterations); } }
false
true
public void use(Board board, UsageParamSingle param) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); int iterations = param.getPeat(); if(iterations == 0) throw new WeblaboraException(getName()+" was not supplied any peat."); if(iterations > 3) throw new WeblaboraException(getName()+" was supplied "+iterations+" peat, but can only consume a maximum of 3."); player.subtractPeat(iterations); player.addCoins(3*iterations); player.addWhiskey(iterations); }
public void use(Board board, UsageParamSingle param) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); int iterations = param.getCoal(); if(iterations == 0) throw new WeblaboraException(getName()+" was not supplied any coal."); if(iterations > 3) throw new WeblaboraException(getName()+" was supplied "+iterations+" coal, but can only consume a maximum of 3."); player.subtractCoal(iterations); player.addCoins(3*iterations); player.addWhiskey(iterations); }
diff --git a/src/com/phonegap/menu/AppMenu.java b/src/com/phonegap/menu/AppMenu.java index a8ac82d..f7fa707 100644 --- a/src/com/phonegap/menu/AppMenu.java +++ b/src/com/phonegap/menu/AppMenu.java @@ -1,254 +1,254 @@ package com.phonegap.menu; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.ListIterator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.content.res.Configuration; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.phonegap.DroidGap; import com.phonegap.api.Plugin; import com.phonegap.api.PluginResult; class MenuInfo { public String label = ""; public Drawable icon; public String callback; public boolean disabled; } public class AppMenu extends Plugin { private Menu appMenu; private ArrayList <MenuInfo> items; private boolean menuChanged = false; private String _densityFolder = "mdpi"; public void getScreenDensity(){ try{ final DroidGap droidGap = (DroidGap)this.ctx; DisplayMetrics metrics = new DisplayMetrics(); droidGap.getWindowManager().getDefaultDisplay().getMetrics(metrics); int _densityDPI = metrics.densityDpi; switch(_densityDPI) { case 160 : { //MEDIUM/DEFAULT _densityFolder = "mdpi"; break; } case 240 : { //HIGH _densityFolder = "hdpi"; break; } case 120 : { //LOW _densityFolder = "ldpi"; break; } case 320 : { //Extra HIGH - _densityFolder = "hdpi"; + _densityFolder = "xhdpi"; break; } } }catch(Exception e){ Log.e("Error in GetScreenDensity", e.getMessage()); } } @Override public PluginResult execute(String action, JSONArray args, String callbackId) { // TODO Auto-generated method stub if(action.equals("create")) { return this.createMenu(args); } if(action.equals("update")) { return this.updateMenu(args); } else if(action.equals("refresh")) { return this.refresh(args); } else { return new PluginResult(PluginResult.Status.INVALID_ACTION); } } private PluginResult refresh(JSONArray args) { // TODO Auto-generated method stub this.menuChanged = true; return new PluginResult(PluginResult.Status.OK); } private PluginResult createMenu(JSONArray args) { PluginResult goodResult = updateMenu(args); /* This should only be done if we are going to be using an action bar if(android.os.Build.VERSION.RELEASE.startsWith("3.")) { appMenu = ctx.dMenu; buildHoneycombMenu(appMenu); } */ //We should do something here if Honeycomb fails! return goodResult; } private PluginResult updateMenu(JSONArray args) { this.getScreenDensity(); //Toss out all the items, and create a new list items = new ArrayList<MenuInfo>(); try { String menu = args.getString(0); JSONArray menuArr = new JSONArray(menu); for(int i = 0; i < menuArr.length(); ++i) { JSONObject mObject = menuArr.getJSONObject(i); MenuInfo info = parseInfo(mObject); items.add(info); } return new PluginResult(PluginResult.Status.OK); } catch (JSONException e) { //e.printStackTrace(); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } } private MenuInfo parseInfo(JSONObject mObject) throws JSONException { MenuInfo info = new MenuInfo(); info.label = mObject.getString("label"); info.callback = mObject.getString("action"); if(mObject.has("icon")) { String tmp_uri = mObject.getString("icon"); //I don't expect this to work at all try { info.icon = getIcon(tmp_uri); } catch (IOException e) { //DO NOTHING, we just don't have a file here! } } try { info.disabled = mObject.getBoolean("disabled"); } //Catch the case when "enabled" is not defined catch(JSONException e) { Log.d("AppMenuPlugin", "DISABLED"); info.disabled = false; } return info; } private Drawable getIcon(String tmp_uri) throws IOException { AssetManager mgr = this.ctx.getAssets(); String fileName = "www/img/" + _densityFolder + "/" + tmp_uri; InputStream image = mgr.open(fileName); // density breakages: http://stackoverflow.com/questions/7361976/how-to-create-a-drawable-from-a-stream-without-resizing-it //Drawable icon = Drawable.createFromStream(image, tmp_uri); Bitmap b = BitmapFactory.decodeStream(image); b.setDensity(Bitmap.DENSITY_NONE); Drawable icon = new BitmapDrawable(b); return icon; } public boolean isMenuChanged() { return menuChanged; } /** * Call to build the menu * * @param menu * @return */ public boolean buildMenu(Menu menu) { appMenu = menu; if(appMenu.size() > 0) appMenu.clear(); ListIterator<MenuInfo> iter = items.listIterator(); while(iter.hasNext()) { int itemId = iter.nextIndex(); MenuInfo item = iter.next(); appMenu.add(Menu.NONE, itemId, Menu.NONE, item.label); if(item.icon != null) { MenuItem currentItem = menu.getItem(itemId); currentItem.setIcon(item.icon); } if(item.disabled == true) { MenuItem currentItem = menu.getItem(itemId); currentItem.setEnabled(false); } } menuChanged = false; return true; } public boolean buildHoneycombMenu(final Menu menu) { final AppMenu that = this; ctx.runOnUiThread(new Runnable() { public void run() { menu.clear(); that.buildMenu(menu); } }); return true; } /** * Call your receive when menuItem is selected. * * @param item * @return */ public boolean onMenuItemSelected(MenuItem item) { //This is where everything tends to fall down, we should instead something else webView.loadUrl("javascript:window.plugins.SimpleMenu.fireCallback(" + item.getItemId() + ")"); return true; } }
true
true
public void getScreenDensity(){ try{ final DroidGap droidGap = (DroidGap)this.ctx; DisplayMetrics metrics = new DisplayMetrics(); droidGap.getWindowManager().getDefaultDisplay().getMetrics(metrics); int _densityDPI = metrics.densityDpi; switch(_densityDPI) { case 160 : { //MEDIUM/DEFAULT _densityFolder = "mdpi"; break; } case 240 : { //HIGH _densityFolder = "hdpi"; break; } case 120 : { //LOW _densityFolder = "ldpi"; break; } case 320 : { //Extra HIGH _densityFolder = "hdpi"; break; } } }catch(Exception e){ Log.e("Error in GetScreenDensity", e.getMessage()); } }
public void getScreenDensity(){ try{ final DroidGap droidGap = (DroidGap)this.ctx; DisplayMetrics metrics = new DisplayMetrics(); droidGap.getWindowManager().getDefaultDisplay().getMetrics(metrics); int _densityDPI = metrics.densityDpi; switch(_densityDPI) { case 160 : { //MEDIUM/DEFAULT _densityFolder = "mdpi"; break; } case 240 : { //HIGH _densityFolder = "hdpi"; break; } case 120 : { //LOW _densityFolder = "ldpi"; break; } case 320 : { //Extra HIGH _densityFolder = "xhdpi"; break; } } }catch(Exception e){ Log.e("Error in GetScreenDensity", e.getMessage()); } }
diff --git a/server/src/main/java/org/uiautomation/ios/inspector/views/IDEMainView.java b/server/src/main/java/org/uiautomation/ios/inspector/views/IDEMainView.java index 9f722b9d..0cc7e191 100644 --- a/server/src/main/java/org/uiautomation/ios/inspector/views/IDEMainView.java +++ b/server/src/main/java/org/uiautomation/ios/inspector/views/IDEMainView.java @@ -1,148 +1,148 @@ /* * Copyright 2012-2013 eBay Software Foundation and ios-driver committers * * 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.uiautomation.ios.inspector.views; import freemarker.template.Configuration; import freemarker.template.Template; import org.json.JSONArray; import org.json.JSONObject; import org.uiautomation.ios.UIAModels.Orientation; import org.uiautomation.ios.communication.device.DeviceType; import org.uiautomation.ios.communication.device.DeviceVariation; import org.uiautomation.ios.inspector.model.IDESessionModel; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; public class IDEMainView implements View { private final IDESessionModel model; private final String servletPath; public IDEMainView(IDESessionModel model, String servletPath) { this.model = model; this.servletPath = servletPath; } @Override public void render(HttpServletResponse response) throws Exception { Configuration conf = new Configuration(); conf.setClassForTemplateLoading(this.getClass(), "/"); Template template = conf.getTemplate("/inspector/inspector.html"); StringWriter writer = new StringWriter(); Map<String, Object> map = new HashMap<String, Object>(); List<String> cssList = new ArrayList<String>(); cssList.add(getResource("inspector/css/inspector.css")); cssList.add(getResource("inspector/css/ide.css")); - cssList.add(getResource("inspector/thrid_party/jquery.layout.css")); - cssList.add(getResource("inspector/thrid_party/jquery-ui-1.10.3.custom/css/smoothness/jquery-ui-1.10.3.custom.min.css")); + cssList.add(getResource("inspector/third_party/jquery.layout.css")); + cssList.add(getResource("inspector/third_party/jquery-ui-1.10.3.custom/css/smoothness/jquery-ui-1.10.3.custom.min.css")); map.put("cssList", cssList); List<String> jsList = new ArrayList<String>(); - jsList.add(getResource("inspector/thrid_party/jquery-ui-1.10.3.custom/js/jquery-1.9.1.js")); - jsList.add(getResource("inspector/thrid_party/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js")); + jsList.add(getResource("inspector/third_party/jquery-ui-1.10.3.custom/js/jquery-1.9.1.js")); + jsList.add(getResource("inspector/third_party/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js")); jsList.add(getResource("inspector/layout.js")); - jsList.add(getResource("inspector/thrid_party/jquery.jstree.js")); - jsList.add(getResource("inspector/thrid_party/jquery.xpath.js")); + jsList.add(getResource("inspector/third_party/jquery.jstree.js")); + jsList.add(getResource("inspector/third_party/jquery.xpath.js")); jsList.add(getResource("inspector/prettify.js")); jsList.add(getResource("inspector/Logger.js")); jsList.add(getResource("inspector/Recorder.js")); jsList.add(getResource("inspector/inspector.js")); jsList.add(getResource("inspector/ide.js")); jsList.add(getResource("uiactions.js")); - jsList.add(getResource("inspector/thrid_party/jquery.layout1.3.js")); + jsList.add(getResource("inspector/third_party/jquery.layout1.3.js")); map.put("jsList", jsList); DeviceType device = model.getCapabilities().getDevice(); DeviceVariation variation = model.getCapabilities().getDeviceVariation(); Orientation orientation = model.getDeviceOrientation(); map.put("frame", getFrame(device, variation, orientation)); map.put("screenshot", getScreen()); String type = "iphone"; if (model.getCapabilities().getDevice() == DeviceType.ipad) { type = "ipad"; } map.put("type", type); map.put("variation", variation); map.put("orientation", orientation); template.process(map, writer); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); response.getWriter().print(writer.toString()); } private String getScreen() { return getResource("session/" + model.getSession().getSessionId() + "/screenshot.png"); } private String getFrame(DeviceType device, DeviceVariation variation, Orientation o) { if (device == DeviceType.iphone) { if (variation == DeviceVariation.Retina4) { return getResource("inspector/images/frames/frame_iphone5_" + o.instrumentsValue() + ".png"); } else { return getResource("inspector/images/frames/frame_iphone_" + o.instrumentsValue() + ".png"); } } else { return getResource("inspector/images/frames/frame_ipad_" + o.instrumentsValue() + ".jpg"); } } private String getResource(String name) { String res = servletPath + "/resources/" + name; return res; } private JSONObject getStatus() throws Exception { return model.getStatus(); } private JSONObject getAppFromStatus() throws Exception { JSONObject status = getStatus(); JSONArray array = status.getJSONObject("value").getJSONArray("supportedApps"); for (int i = 0; i < array.length(); i++) { JSONObject jsonApp = array.getJSONObject(i); String other = (String) jsonApp.get("CFBundleIdentifier"); String me = (String) model.getCapabilities().getRawCapabilities().get("CFBundleIdentifier"); if (other.equals(me)) { return jsonApp; } } return null; } }
false
true
public void render(HttpServletResponse response) throws Exception { Configuration conf = new Configuration(); conf.setClassForTemplateLoading(this.getClass(), "/"); Template template = conf.getTemplate("/inspector/inspector.html"); StringWriter writer = new StringWriter(); Map<String, Object> map = new HashMap<String, Object>(); List<String> cssList = new ArrayList<String>(); cssList.add(getResource("inspector/css/inspector.css")); cssList.add(getResource("inspector/css/ide.css")); cssList.add(getResource("inspector/thrid_party/jquery.layout.css")); cssList.add(getResource("inspector/thrid_party/jquery-ui-1.10.3.custom/css/smoothness/jquery-ui-1.10.3.custom.min.css")); map.put("cssList", cssList); List<String> jsList = new ArrayList<String>(); jsList.add(getResource("inspector/thrid_party/jquery-ui-1.10.3.custom/js/jquery-1.9.1.js")); jsList.add(getResource("inspector/thrid_party/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js")); jsList.add(getResource("inspector/layout.js")); jsList.add(getResource("inspector/thrid_party/jquery.jstree.js")); jsList.add(getResource("inspector/thrid_party/jquery.xpath.js")); jsList.add(getResource("inspector/prettify.js")); jsList.add(getResource("inspector/Logger.js")); jsList.add(getResource("inspector/Recorder.js")); jsList.add(getResource("inspector/inspector.js")); jsList.add(getResource("inspector/ide.js")); jsList.add(getResource("uiactions.js")); jsList.add(getResource("inspector/thrid_party/jquery.layout1.3.js")); map.put("jsList", jsList); DeviceType device = model.getCapabilities().getDevice(); DeviceVariation variation = model.getCapabilities().getDeviceVariation(); Orientation orientation = model.getDeviceOrientation(); map.put("frame", getFrame(device, variation, orientation)); map.put("screenshot", getScreen()); String type = "iphone"; if (model.getCapabilities().getDevice() == DeviceType.ipad) { type = "ipad"; } map.put("type", type); map.put("variation", variation); map.put("orientation", orientation); template.process(map, writer); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); response.getWriter().print(writer.toString()); }
public void render(HttpServletResponse response) throws Exception { Configuration conf = new Configuration(); conf.setClassForTemplateLoading(this.getClass(), "/"); Template template = conf.getTemplate("/inspector/inspector.html"); StringWriter writer = new StringWriter(); Map<String, Object> map = new HashMap<String, Object>(); List<String> cssList = new ArrayList<String>(); cssList.add(getResource("inspector/css/inspector.css")); cssList.add(getResource("inspector/css/ide.css")); cssList.add(getResource("inspector/third_party/jquery.layout.css")); cssList.add(getResource("inspector/third_party/jquery-ui-1.10.3.custom/css/smoothness/jquery-ui-1.10.3.custom.min.css")); map.put("cssList", cssList); List<String> jsList = new ArrayList<String>(); jsList.add(getResource("inspector/third_party/jquery-ui-1.10.3.custom/js/jquery-1.9.1.js")); jsList.add(getResource("inspector/third_party/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js")); jsList.add(getResource("inspector/layout.js")); jsList.add(getResource("inspector/third_party/jquery.jstree.js")); jsList.add(getResource("inspector/third_party/jquery.xpath.js")); jsList.add(getResource("inspector/prettify.js")); jsList.add(getResource("inspector/Logger.js")); jsList.add(getResource("inspector/Recorder.js")); jsList.add(getResource("inspector/inspector.js")); jsList.add(getResource("inspector/ide.js")); jsList.add(getResource("uiactions.js")); jsList.add(getResource("inspector/third_party/jquery.layout1.3.js")); map.put("jsList", jsList); DeviceType device = model.getCapabilities().getDevice(); DeviceVariation variation = model.getCapabilities().getDeviceVariation(); Orientation orientation = model.getDeviceOrientation(); map.put("frame", getFrame(device, variation, orientation)); map.put("screenshot", getScreen()); String type = "iphone"; if (model.getCapabilities().getDevice() == DeviceType.ipad) { type = "ipad"; } map.put("type", type); map.put("variation", variation); map.put("orientation", orientation); template.process(map, writer); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); response.getWriter().print(writer.toString()); }
diff --git a/solr/src/common/org/apache/solr/common/util/SystemIdResolver.java b/solr/src/common/org/apache/solr/common/util/SystemIdResolver.java index ab76b2202..b396735df 100644 --- a/solr/src/common/org/apache/solr/common/util/SystemIdResolver.java +++ b/solr/src/common/org/apache/solr/common/util/SystemIdResolver.java @@ -1,171 +1,176 @@ /** * 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.solr.common.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.solr.common.ResourceLoader; import org.xml.sax.InputSource; import org.xml.sax.EntityResolver; import org.xml.sax.ext.EntityResolver2; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.sax.SAXSource; import javax.xml.stream.XMLResolver; import javax.xml.stream.XMLStreamException; /** * This is a helper class to support resolving of XIncludes or other hrefs * inside XML files on top of a {@link ResourceLoader}. Just plug this class * on top of a {@link ResourceLoader} and pass it as {@link EntityResolver} to SAX parsers * or via wrapper methods as {@link URIResolver} to XSL transformers or {@link XMLResolver} to STAX parsers. * The resolver handles special SystemIds with an URI scheme of {@code solrres:} that point * to resources. To produce such systemIds when you initially call the parser, use * {@link #createSystemIdFromResourceName} which produces a SystemId that can * be included along the InputStream coming from {@link ResourceLoader#openResource}. * <p>In general create the {@link InputSource} to be passed to the parser like:</p> * <pre class="prettyprint"> * InputSource is = new InputSource(loader.openSchema(name)); * is.setSystemId(SystemIdResolver.createSystemIdFromResourceName(name)); * final DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); * db.setEntityResolver(new SystemIdResolver(loader)); * Document doc = db.parse(is); * </pre> */ public final class SystemIdResolver implements EntityResolver, EntityResolver2 { private static final Logger log = LoggerFactory.getLogger(SystemIdResolver.class); public static final String RESOURCE_LOADER_URI_SCHEME = "solrres"; public static final String RESOURCE_LOADER_AUTHORITY_ABSOLUTE = "@"; private final ResourceLoader loader; public SystemIdResolver(ResourceLoader loader) { this.loader = loader; } public EntityResolver asEntityResolver() { return this; } public URIResolver asURIResolver() { return new URIResolver() { public Source resolve(String href, String base) throws TransformerException { try { final InputSource src = SystemIdResolver.this.resolveEntity(null, null, base, href); return (src == null) ? null : new SAXSource(src); } catch (IOException ioe) { throw new TransformerException("Cannot resolve entity", ioe); } } }; } public XMLResolver asXMLResolver() { return new XMLResolver() { public Object resolveEntity(String publicId, String systemId, String baseURI, String namespace) throws XMLStreamException { try { final InputSource src = SystemIdResolver.this.resolveEntity(null, publicId, baseURI, systemId); return (src == null) ? null : src.getByteStream(); } catch (IOException ioe) { throw new XMLStreamException("Cannot resolve entity", ioe); } } }; } URI resolveRelativeURI(String baseURI, String systemId) throws IOException,URISyntaxException { URI uri; // special case for backwards compatibility: if relative systemId starts with "/" (we convert that to an absolute solrres:-URI) if (systemId.startsWith("/")) { uri = new URI(RESOURCE_LOADER_URI_SCHEME, RESOURCE_LOADER_AUTHORITY_ABSOLUTE, "/", null, null).resolve(systemId); } else { // simply parse as URI uri = new URI(systemId); } // do relative resolving if (baseURI != null ) { uri = new URI(baseURI).resolve(uri); } return uri; } // *** EntityResolver(2) methods: public InputSource getExternalSubset(String name, String baseURI) { return null; } public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws IOException { if (systemId == null) return null; try { final URI uri = resolveRelativeURI(baseURI, systemId); // check schema and resolve with ResourceLoader if (RESOURCE_LOADER_URI_SCHEME.equals(uri.getScheme())) { String path = uri.getPath(), authority = uri.getAuthority(); if (!RESOURCE_LOADER_AUTHORITY_ABSOLUTE.equals(authority)) { path = path.substring(1); } - final InputSource is = new InputSource(loader.openResource(path)); - is.setSystemId(uri.toASCIIString()); - is.setPublicId(publicId); - return is; + try { + final InputSource is = new InputSource(loader.openResource(path)); + is.setSystemId(uri.toASCIIString()); + is.setPublicId(publicId); + return is; + } catch (RuntimeException re) { + // unfortunately XInclude fallback only works with IOException, but openResource() never throws that one + throw (IOException) (new IOException(re.getMessage()).initCause(re)); + } } else { // resolve all other URIs using the standard resolver return null; } } catch (URISyntaxException use) { log.warn("An URI systax problem occurred during resolving SystemId, falling back to default resolver", use); return null; } } public InputSource resolveEntity(String publicId, String systemId) throws IOException { return resolveEntity(null, publicId, null, systemId); } public static String createSystemIdFromResourceName(String name) { name = name.replace(File.separatorChar, '/'); final String authority; if (name.startsWith("/")) { // a hack to preserve absolute filenames and keep them absolute after resolving, we set the URI's authority to "@" on absolute filenames: authority = RESOURCE_LOADER_AUTHORITY_ABSOLUTE; } else { authority = null; name = "/" + name; } try { return new URI(RESOURCE_LOADER_URI_SCHEME, authority, name, null, null).toASCIIString(); } catch (URISyntaxException use) { throw new IllegalArgumentException("Invalid syntax of Solr Resource URI", use); } } }
true
true
public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws IOException { if (systemId == null) return null; try { final URI uri = resolveRelativeURI(baseURI, systemId); // check schema and resolve with ResourceLoader if (RESOURCE_LOADER_URI_SCHEME.equals(uri.getScheme())) { String path = uri.getPath(), authority = uri.getAuthority(); if (!RESOURCE_LOADER_AUTHORITY_ABSOLUTE.equals(authority)) { path = path.substring(1); } final InputSource is = new InputSource(loader.openResource(path)); is.setSystemId(uri.toASCIIString()); is.setPublicId(publicId); return is; } else { // resolve all other URIs using the standard resolver return null; } } catch (URISyntaxException use) { log.warn("An URI systax problem occurred during resolving SystemId, falling back to default resolver", use); return null; } }
public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws IOException { if (systemId == null) return null; try { final URI uri = resolveRelativeURI(baseURI, systemId); // check schema and resolve with ResourceLoader if (RESOURCE_LOADER_URI_SCHEME.equals(uri.getScheme())) { String path = uri.getPath(), authority = uri.getAuthority(); if (!RESOURCE_LOADER_AUTHORITY_ABSOLUTE.equals(authority)) { path = path.substring(1); } try { final InputSource is = new InputSource(loader.openResource(path)); is.setSystemId(uri.toASCIIString()); is.setPublicId(publicId); return is; } catch (RuntimeException re) { // unfortunately XInclude fallback only works with IOException, but openResource() never throws that one throw (IOException) (new IOException(re.getMessage()).initCause(re)); } } else { // resolve all other URIs using the standard resolver return null; } } catch (URISyntaxException use) { log.warn("An URI systax problem occurred during resolving SystemId, falling back to default resolver", use); return null; } }
diff --git a/src/main/java/org/candlepin/util/X509Util.java b/src/main/java/org/candlepin/util/X509Util.java index 11359eb30..1d27b0501 100644 --- a/src/main/java/org/candlepin/util/X509Util.java +++ b/src/main/java/org/candlepin/util/X509Util.java @@ -1,223 +1,222 @@ /** * Copyright (c) 2009 - 2012 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package org.candlepin.util; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.candlepin.model.Consumer; import org.candlepin.model.Entitlement; import org.candlepin.model.EntitlementCurator; import org.candlepin.model.EnvironmentContent; import org.candlepin.model.Product; import org.candlepin.model.ProductContent; import com.google.common.base.Predicate; /** * X509Util */ public abstract class X509Util { private static Logger log = Logger.getLogger(X509Util.class); public static final Predicate<Product> PROD_FILTER_PREDICATE = new Predicate<Product>() { @Override public boolean apply(Product product) { return product != null && StringUtils.isNumeric(product.getId()); } }; public static final String ARCH_FACT = "uname.machine"; public static final String PRODUCT_ARCH_ATTR = "arch"; /** * Scan the product content looking for any we should filter out. * * Will filter out any content which modifies another product if the consumer does * not have an entitlement granting them access to that product. * * Will also filter out any content not promoted to the consumer's environment * if environment filtering is enabled. * * @param prod the product who's content we should filter * @param ent the original entitlement * @param entCurator * @param promotedContent * @param filterEnvironment show content also be filtered by environment. * @return ProductContent to include in the certificate. */ public Set<ProductContent> filterProductContent(Product prod, Entitlement ent, EntitlementCurator entCurator, Map<String, EnvironmentContent> promotedContent, boolean filterEnvironment) { Set<ProductContent> filtered = new HashSet<ProductContent>(); for (ProductContent pc : prod.getProductContent()) { // Filter any content not promoted to environment. if (filterEnvironment) { if (ent.getConsumer().getEnvironment() != null && !promotedContent.containsKey(pc.getContent().getId())) { log.debug("Skipping content not promoted to environment: " + pc.getContent().getId()); continue; } } boolean include = true; if (pc.getContent().getModifiedProductIds().size() > 0) { include = false; Set<String> prodIds = pc.getContent().getModifiedProductIds(); // If consumer has an entitlement to just one of the modified products, // we will include this content set: for (String prodId : prodIds) { Set<Entitlement> entsProviding = entCurator.listProviding( ent.getConsumer(), prodId, ent.getStartDate(), ent.getEndDate()); if (entsProviding.size() > 0) { include = true; break; } } } if (include) { filtered.add(pc); } } return filtered; } /** * Creates a Content url from the prefix and the path * @param contentPrefix to prepend to the path * @param pc the product content * @return the complete content path */ public String createFullContentPath(String contentPrefix, ProductContent pc) { String prefix = "/"; String contentPath = pc.getContent().getContentUrl(); // Allow for the case wherethe content url is a true url. // If that is true, then return it as is. if (contentPath.startsWith("http://") || contentPath.startsWith("file://") || contentPath.startsWith("https://") || contentPath.startsWith("ftp://")) { return contentPath; } if (!StringUtils.isEmpty(contentPrefix)) { // Ensure there is no double // in the URL. See BZ952735 // remove them all except one. prefix = StringUtils.stripEnd(contentPrefix, "/") + prefix; } contentPath = StringUtils.stripStart(contentPath, "/"); return prefix + contentPath; } /* * remove content sets that do not match the consumers arch */ public Set<ProductContent> filterContentByContentArch( Set<ProductContent> pcSet, Consumer consumer, Product product) { Set<ProductContent> filtered = new HashSet<ProductContent>(); /* FIXME: make this a feature flag in the config */ boolean enabledContentArchFiltering = true; if (!enabledContentArchFiltering) { return pcSet; } String consumerArch = consumer.getFact(ARCH_FACT); log.debug("consumerArch: " + consumerArch); if (consumerArch == null) { log.debug("consumer: " + consumer.getId() + " has no " + ARCH_FACT + " attribute."); log.debug("not filtering by arch"); return pcSet; } for (ProductContent pc : pcSet) { boolean canUse = false; Set<String> contentArches = Arch.parseArches(pc.getContent().getArches()); Set<String> productArches = Arch.parseArches(product.getAttributeValue(PRODUCT_ARCH_ATTR)); log.debug("product_content arch list for " + pc.getContent().getLabel()); log.debug("contentArches: " + contentArches); log.debug("productArches: " + productArches); // empty or null Content.arches should result in // inheriting the arches from the product if (contentArches.isEmpty()) { log.debug("content set " + pc.getContent().getLabel() + " does not specific content arches"); // so use the arches from the product contentArches.addAll(productArches); log.debug("using the arches from the product " + product.toString()); log.debug("productArches: " + productArches.toString()); } for (String contentArch : contentArches) { log.debug("_ca_ Checking consumerArch " + consumerArch + " can use content for " + contentArch); log.debug("_ca_ arch.contentForConsume" + Arch.contentForConsumer(contentArch, consumerArch)); // if archCompare(contentArch, productArch if (Arch.contentForConsumer(contentArch, consumerArch)) { log.debug("_ca_ CAN use content " + pc.getContent().getLabel() + " for arch " + contentArch); canUse = true; } else { log.debug("_ca_ CAN NOT use content " + pc.getContent().getLabel() + " for arch " + contentArch); } - canUse = true; } // if we found a workable arch for this content, include it if (canUse) { filtered.add(pc); log.debug("_ca_ Including content " + pc.getContent().getLabel()); } else { log.debug("_ca_ Skipping content " + pc.getContent().getLabel()); } } log.debug("_ca_ arch approriate content for " + consumerArch + " includes: "); for (ProductContent apc : filtered) { log.debug("_ca_ \t " + apc.toString()); } return filtered; } }
true
true
public Set<ProductContent> filterContentByContentArch( Set<ProductContent> pcSet, Consumer consumer, Product product) { Set<ProductContent> filtered = new HashSet<ProductContent>(); /* FIXME: make this a feature flag in the config */ boolean enabledContentArchFiltering = true; if (!enabledContentArchFiltering) { return pcSet; } String consumerArch = consumer.getFact(ARCH_FACT); log.debug("consumerArch: " + consumerArch); if (consumerArch == null) { log.debug("consumer: " + consumer.getId() + " has no " + ARCH_FACT + " attribute."); log.debug("not filtering by arch"); return pcSet; } for (ProductContent pc : pcSet) { boolean canUse = false; Set<String> contentArches = Arch.parseArches(pc.getContent().getArches()); Set<String> productArches = Arch.parseArches(product.getAttributeValue(PRODUCT_ARCH_ATTR)); log.debug("product_content arch list for " + pc.getContent().getLabel()); log.debug("contentArches: " + contentArches); log.debug("productArches: " + productArches); // empty or null Content.arches should result in // inheriting the arches from the product if (contentArches.isEmpty()) { log.debug("content set " + pc.getContent().getLabel() + " does not specific content arches"); // so use the arches from the product contentArches.addAll(productArches); log.debug("using the arches from the product " + product.toString()); log.debug("productArches: " + productArches.toString()); } for (String contentArch : contentArches) { log.debug("_ca_ Checking consumerArch " + consumerArch + " can use content for " + contentArch); log.debug("_ca_ arch.contentForConsume" + Arch.contentForConsumer(contentArch, consumerArch)); // if archCompare(contentArch, productArch if (Arch.contentForConsumer(contentArch, consumerArch)) { log.debug("_ca_ CAN use content " + pc.getContent().getLabel() + " for arch " + contentArch); canUse = true; } else { log.debug("_ca_ CAN NOT use content " + pc.getContent().getLabel() + " for arch " + contentArch); } canUse = true; } // if we found a workable arch for this content, include it if (canUse) { filtered.add(pc); log.debug("_ca_ Including content " + pc.getContent().getLabel()); } else { log.debug("_ca_ Skipping content " + pc.getContent().getLabel()); } } log.debug("_ca_ arch approriate content for " + consumerArch + " includes: "); for (ProductContent apc : filtered) { log.debug("_ca_ \t " + apc.toString()); } return filtered; }
public Set<ProductContent> filterContentByContentArch( Set<ProductContent> pcSet, Consumer consumer, Product product) { Set<ProductContent> filtered = new HashSet<ProductContent>(); /* FIXME: make this a feature flag in the config */ boolean enabledContentArchFiltering = true; if (!enabledContentArchFiltering) { return pcSet; } String consumerArch = consumer.getFact(ARCH_FACT); log.debug("consumerArch: " + consumerArch); if (consumerArch == null) { log.debug("consumer: " + consumer.getId() + " has no " + ARCH_FACT + " attribute."); log.debug("not filtering by arch"); return pcSet; } for (ProductContent pc : pcSet) { boolean canUse = false; Set<String> contentArches = Arch.parseArches(pc.getContent().getArches()); Set<String> productArches = Arch.parseArches(product.getAttributeValue(PRODUCT_ARCH_ATTR)); log.debug("product_content arch list for " + pc.getContent().getLabel()); log.debug("contentArches: " + contentArches); log.debug("productArches: " + productArches); // empty or null Content.arches should result in // inheriting the arches from the product if (contentArches.isEmpty()) { log.debug("content set " + pc.getContent().getLabel() + " does not specific content arches"); // so use the arches from the product contentArches.addAll(productArches); log.debug("using the arches from the product " + product.toString()); log.debug("productArches: " + productArches.toString()); } for (String contentArch : contentArches) { log.debug("_ca_ Checking consumerArch " + consumerArch + " can use content for " + contentArch); log.debug("_ca_ arch.contentForConsume" + Arch.contentForConsumer(contentArch, consumerArch)); // if archCompare(contentArch, productArch if (Arch.contentForConsumer(contentArch, consumerArch)) { log.debug("_ca_ CAN use content " + pc.getContent().getLabel() + " for arch " + contentArch); canUse = true; } else { log.debug("_ca_ CAN NOT use content " + pc.getContent().getLabel() + " for arch " + contentArch); } } // if we found a workable arch for this content, include it if (canUse) { filtered.add(pc); log.debug("_ca_ Including content " + pc.getContent().getLabel()); } else { log.debug("_ca_ Skipping content " + pc.getContent().getLabel()); } } log.debug("_ca_ arch approriate content for " + consumerArch + " includes: "); for (ProductContent apc : filtered) { log.debug("_ca_ \t " + apc.toString()); } return filtered; }
diff --git a/tests/tests/org.jboss.tools.tests/src/org/jboss/tools/test/util/ResourcesUtils.java b/tests/tests/org.jboss.tools.tests/src/org/jboss/tools/test/util/ResourcesUtils.java index 00e6a76b4..d1ee34358 100644 --- a/tests/tests/org.jboss.tools.tests/src/org/jboss/tools/test/util/ResourcesUtils.java +++ b/tests/tests/org.jboss.tools.tests/src/org/jboss/tools/test/util/ResourcesUtils.java @@ -1,248 +1,250 @@ /******************************************************************************* * Copyright (c) 2007 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is 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: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.test.util; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceDescription; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.IOverwriteQuery; import org.eclipse.ui.wizards.datatransfer.ImportOperation; import org.jboss.tools.tests.ImportProvider; import org.osgi.framework.Bundle; /** * @author eskimo * */ public class ResourcesUtils { public static IProject importProject( Bundle bundle, String templLocation, IProgressMonitor monitor) throws IOException, CoreException, InvocationTargetException, InterruptedException { String tplPrjLcStr; tplPrjLcStr = FileLocator.resolve(bundle.getEntry(templLocation)) .getFile(); IProject importedPrj = importProjectIntoWorkspace(tplPrjLcStr, new Path(tplPrjLcStr).lastSegment()); return importedPrj; } public static IProject importProject( Bundle bundle, String templLocation) throws IOException, CoreException, InvocationTargetException, InterruptedException { return importProject(bundle, templLocation, new NullProgressMonitor()); } public static IProject createEclipseProject(String projectName, IProgressMonitor monitor) throws CoreException { IProject newProjectHandle = ResourcesPlugin.getWorkspace().getRoot() .getProject(projectName); IWorkspace workspace = ResourcesPlugin.getWorkspace(); final IProjectDescription description = workspace .newProjectDescription(projectName); newProjectHandle.create(description, new NullProgressMonitor()); newProjectHandle.open(monitor); return newProjectHandle; } public static IProject createEclipseProject(Bundle bundle, String templateLocation, IProgressMonitor monitor) throws CoreException, IOException { IPath tplPrjDescr = new Path(templateLocation) .append(IProjectDescription.DESCRIPTION_FILE_NAME); IProjectDescription descr = ResourcesPlugin.getWorkspace() .loadProjectDescription(tplPrjDescr); descr.setLocation(null); IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( descr.getName()); project.create(descr, monitor); project.open(IResource.BACKGROUND_REFRESH, monitor); return project; } public static IProject createEclipseProject(Bundle bundle, String templateLocation) throws CoreException, IOException { return createEclipseProject(bundle,templateLocation, new NullProgressMonitor()); } public static IProject createEclipseProject(String bundle, String templateLocation, IProgressMonitor monitor) throws CoreException, IOException { return createEclipseProject( Platform.getBundle(bundle), templateLocation, monitor); } public static boolean findLineInFile(IFile file, String pattern) throws CoreException, IOException { InputStream content = null; InputStreamReader isr = null; boolean patternIsFound = false; try { content = file.getContents(true); isr = new InputStreamReader(content); LineNumberReader contentReader = new LineNumberReader(isr); String line; do { line = contentReader.readLine(); if(line!=null && !patternIsFound) { patternIsFound = line.trim().matches(pattern); } } while (line != null && !patternIsFound); } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { // ignore } } if (content != null) { try { content.close(); } catch (IOException e) { // ignore } } } return patternIsFound; } /** * @param string * @param string2 * @param nullProgressMonitor * @return * @throws InterruptedException * @throws InvocationTargetException * @throws CoreException * @throws IOException */ public static IProject importProject(String bundleName, String templatePath, IProgressMonitor monitor) throws IOException, CoreException, InvocationTargetException, InterruptedException { // TODO Auto-generated method stub return importProject(Platform.getBundle(bundleName), templatePath, monitor==null?new NullProgressMonitor():monitor); } public static IProject importProject(String bundleName, String templatePath) throws IOException, CoreException, InvocationTargetException, InterruptedException { // TODO Auto-generated method stub return importProject(Platform.getBundle(bundleName), templatePath, null); } public static void deleteProject(String projectName) throws CoreException { IResource member = ResourcesPlugin.getWorkspace().getRoot().findMember(projectName); if (member != null) { member.getProject().delete(true, true, null); } } public static boolean setBuildAutomatically(boolean state) throws CoreException { boolean oldAutoBuilding; IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceDescription description = workspace.getDescription(); oldAutoBuilding = description.isAutoBuilding(); if (state != oldAutoBuilding) { description.setAutoBuilding(state); workspace.setDescription(description); } return oldAutoBuilding; } //static public void importProjectIntoWorkspace(ImportBean bean) { // importProjectIntoWorkspace(bean); //} private static final long IMPORT_DELAY = 50; /** * Import project into workspace. * * @param path the path * @param projectName the project name */ static public IProject importProjectIntoWorkspace(String path, String projectName) { IProject project = null; try { boolean state = ResourcesUtils.setBuildAutomatically(false); project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); project.create(null); project.open(null); JobUtils.waitForIdle(IMPORT_DELAY); IOverwriteQuery overwrite = new IOverwriteQuery() { public String queryOverwrite(String pathString) { return ALL; } }; ImportProvider importProvider = new ImportProvider(); // need to remove from imported project "svn" files List<String> unimportedFiles = new ArrayList<String>(); unimportedFiles.add(".svn"); //$NON-NLS-1$ importProvider.setUnimportedFiles(unimportedFiles); // create import operation ImportOperation importOp = new ImportOperation(project .getFullPath(), new File(path), importProvider, overwrite); // import files just to project folder ( without old structure ) importOp.setCreateContainerStructure(false); importOp.setContext(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); // run import importOp.run(null); JobUtils.waitForIdle(IMPORT_DELAY); ResourcesUtils.setBuildAutomatically(state); } catch (InvocationTargetException ite) { // TePlugin.getDefault().logError(ite.getCause()); + ite.printStackTrace(); } catch (InterruptedException ie) { // VPETestPlugin.getDefault().logError(ie); + ie.printStackTrace(); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } return project; } }
false
true
static public IProject importProjectIntoWorkspace(String path, String projectName) { IProject project = null; try { boolean state = ResourcesUtils.setBuildAutomatically(false); project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); project.create(null); project.open(null); JobUtils.waitForIdle(IMPORT_DELAY); IOverwriteQuery overwrite = new IOverwriteQuery() { public String queryOverwrite(String pathString) { return ALL; } }; ImportProvider importProvider = new ImportProvider(); // need to remove from imported project "svn" files List<String> unimportedFiles = new ArrayList<String>(); unimportedFiles.add(".svn"); //$NON-NLS-1$ importProvider.setUnimportedFiles(unimportedFiles); // create import operation ImportOperation importOp = new ImportOperation(project .getFullPath(), new File(path), importProvider, overwrite); // import files just to project folder ( without old structure ) importOp.setCreateContainerStructure(false); importOp.setContext(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); // run import importOp.run(null); JobUtils.waitForIdle(IMPORT_DELAY); ResourcesUtils.setBuildAutomatically(state); } catch (InvocationTargetException ite) { // TePlugin.getDefault().logError(ite.getCause()); } catch (InterruptedException ie) { // VPETestPlugin.getDefault().logError(ie); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } return project; }
static public IProject importProjectIntoWorkspace(String path, String projectName) { IProject project = null; try { boolean state = ResourcesUtils.setBuildAutomatically(false); project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); project.create(null); project.open(null); JobUtils.waitForIdle(IMPORT_DELAY); IOverwriteQuery overwrite = new IOverwriteQuery() { public String queryOverwrite(String pathString) { return ALL; } }; ImportProvider importProvider = new ImportProvider(); // need to remove from imported project "svn" files List<String> unimportedFiles = new ArrayList<String>(); unimportedFiles.add(".svn"); //$NON-NLS-1$ importProvider.setUnimportedFiles(unimportedFiles); // create import operation ImportOperation importOp = new ImportOperation(project .getFullPath(), new File(path), importProvider, overwrite); // import files just to project folder ( without old structure ) importOp.setCreateContainerStructure(false); importOp.setContext(PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); // run import importOp.run(null); JobUtils.waitForIdle(IMPORT_DELAY); ResourcesUtils.setBuildAutomatically(state); } catch (InvocationTargetException ite) { // TePlugin.getDefault().logError(ite.getCause()); ite.printStackTrace(); } catch (InterruptedException ie) { // VPETestPlugin.getDefault().logError(ie); ie.printStackTrace(); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } return project; }
diff --git a/commons/src/main/java/org/wikimedia/commons/MediaWikiImageView.java b/commons/src/main/java/org/wikimedia/commons/MediaWikiImageView.java index 83320035..fac11f46 100644 --- a/commons/src/main/java/org/wikimedia/commons/MediaWikiImageView.java +++ b/commons/src/main/java/org/wikimedia/commons/MediaWikiImageView.java @@ -1,214 +1,214 @@ /** * Copyright (C) 2013 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 org.wikimedia.commons; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.ImageLoader.ImageContainer; import com.android.volley.toolbox.ImageLoader.ImageListener; import org.wikimedia.commons.contributions.Contribution; import org.wikimedia.commons.contributions.ContributionsContentProvider; public class MediaWikiImageView extends ImageView { private Media mMedia; private ImageLoader mImageLoader; private ImageContainer mImageContainer; private View loadingView; public MediaWikiImageView(Context context) { this(context, null); } public MediaWikiImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MediaWikiImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setMedia(Media media, ImageLoader imageLoader) { this.mMedia = media; mImageLoader = imageLoader; loadImageIfNecessary(false); } public void setLoadingView(View loadingView) { this.loadingView = loadingView; } public View getLoadingView() { return loadingView; } private void loadImageIfNecessary(final boolean isInLayoutPass) { loadImageIfNecessary(isInLayoutPass, false); } private void loadImageIfNecessary(final boolean isInLayoutPass, final boolean tryOriginal) { int width = getWidth(); int height = getHeight(); // if the view's bounds aren't known yet, hold off on loading the image. if (width == 0 && height == 0) { return; } if(mMedia == null) { return; } final String mUrl; if(tryOriginal) { mUrl = mMedia.getImageUrl(); } else { - // Round it down to the nearest 320 + // Round it to the nearest 320 // Possible a similar size image has already been generated. // Reduces Server cache fragmentation, also increases chance of cache hit - // If width is less than 320, we just use that directly, to avoid a case of the Maths - int bucketedWidth = width <= 320 ? width: (width / 320) * 320; + // If width is less than 320, we round up to 320 + int bucketedWidth = width <= 320 ? 320 : Math.round((float)width / 320.0f) * 320; if(mMedia.getWidth() != 0 && mMedia.getWidth() < bucketedWidth) { // If we know that the width of the image is lesser than the required width // We don't even try to load the thumbnai, go directly to the source loadImageIfNecessary(isInLayoutPass, true); return; } else { - mUrl = mMedia.getThumbnailUrl(width <= 320 ? width : (width / 320) * 320); + mUrl = mMedia.getThumbnailUrl(bucketedWidth); } } // if the URL to be loaded in this view is empty, cancel any old requests and clear the // currently loaded image. if (TextUtils.isEmpty(mUrl)) { if (mImageContainer != null) { mImageContainer.cancelRequest(); mImageContainer = null; } setImageBitmap(null); return; } // Don't repeat work. Prevents onLayout cascades // We ignore it if the image request was for either the current URL of for the full URL // Since the full URL is always the second, and if (mImageContainer != null && mImageContainer.getRequestUrl() != null) { if (mImageContainer.getRequestUrl().equals(mMedia.getImageUrl()) || mImageContainer.getRequestUrl().equals(mUrl)) { return; } else { // if there is a pre-existing request, cancel it if it's fetching a different URL. mImageContainer.cancelRequest(); BitmapDrawable actualDrawable = (BitmapDrawable)getDrawable(); if(actualDrawable != null && actualDrawable.getBitmap() != null) { setImageBitmap(null); if(loadingView != null) { loadingView.setVisibility(View.VISIBLE); } } } } // The pre-existing content of this view didn't match the current URL. Load the new image // from the network. ImageContainer newContainer = mImageLoader.get(mUrl, new ImageListener() { @Override public void onErrorResponse(final VolleyError error) { if(!tryOriginal) { post(new Runnable() { public void run() { loadImageIfNecessary(false, true); } }); } } @Override public void onResponse(final ImageContainer response, boolean isImmediate) { // If this was an immediate response that was delivered inside of a layout // pass do not set the image immediately as it will trigger a requestLayout // inside of a layout. Instead, defer setting the image by posting back to // the main thread. if (isImmediate && isInLayoutPass) { post(new Runnable() { @Override public void run() { onResponse(response, false); } }); return; } if (response.getBitmap() != null) { setImageBitmap(response.getBitmap()); if(tryOriginal && mMedia instanceof Contribution && response.getBitmap().getWidth() > mMedia.getWidth() || response.getBitmap().getHeight() > mMedia.getHeight()) { // If there is no width information for this image, save it. This speeds up image loading massively for smaller images mMedia.setHeight(response.getBitmap().getHeight()); mMedia.setWidth(response.getBitmap().getWidth()); ((Contribution)mMedia).setContentProviderClient(MediaWikiImageView.this.getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY)); ((Contribution)mMedia).save(); } if(loadingView != null) { loadingView.setVisibility(View.GONE); } } else { // I'm not really sure where this would hit but not onError } } }); // update the ImageContainer to be the new bitmap container. mImageContainer = newContainer; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); loadImageIfNecessary(true); } @Override protected void onDetachedFromWindow() { if (mImageContainer != null) { // If the view was bound to an image request, cancel it and clear // out the image from the view. mImageContainer.cancelRequest(); setImageBitmap(null); // also clear out the container so we can reload the image if necessary. mImageContainer = null; } super.onDetachedFromWindow(); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); invalidate(); } }
false
true
private void loadImageIfNecessary(final boolean isInLayoutPass, final boolean tryOriginal) { int width = getWidth(); int height = getHeight(); // if the view's bounds aren't known yet, hold off on loading the image. if (width == 0 && height == 0) { return; } if(mMedia == null) { return; } final String mUrl; if(tryOriginal) { mUrl = mMedia.getImageUrl(); } else { // Round it down to the nearest 320 // Possible a similar size image has already been generated. // Reduces Server cache fragmentation, also increases chance of cache hit // If width is less than 320, we just use that directly, to avoid a case of the Maths int bucketedWidth = width <= 320 ? width: (width / 320) * 320; if(mMedia.getWidth() != 0 && mMedia.getWidth() < bucketedWidth) { // If we know that the width of the image is lesser than the required width // We don't even try to load the thumbnai, go directly to the source loadImageIfNecessary(isInLayoutPass, true); return; } else { mUrl = mMedia.getThumbnailUrl(width <= 320 ? width : (width / 320) * 320); } } // if the URL to be loaded in this view is empty, cancel any old requests and clear the // currently loaded image. if (TextUtils.isEmpty(mUrl)) { if (mImageContainer != null) { mImageContainer.cancelRequest(); mImageContainer = null; } setImageBitmap(null); return; } // Don't repeat work. Prevents onLayout cascades // We ignore it if the image request was for either the current URL of for the full URL // Since the full URL is always the second, and if (mImageContainer != null && mImageContainer.getRequestUrl() != null) { if (mImageContainer.getRequestUrl().equals(mMedia.getImageUrl()) || mImageContainer.getRequestUrl().equals(mUrl)) { return; } else { // if there is a pre-existing request, cancel it if it's fetching a different URL. mImageContainer.cancelRequest(); BitmapDrawable actualDrawable = (BitmapDrawable)getDrawable(); if(actualDrawable != null && actualDrawable.getBitmap() != null) { setImageBitmap(null); if(loadingView != null) { loadingView.setVisibility(View.VISIBLE); } } } } // The pre-existing content of this view didn't match the current URL. Load the new image // from the network. ImageContainer newContainer = mImageLoader.get(mUrl, new ImageListener() { @Override public void onErrorResponse(final VolleyError error) { if(!tryOriginal) { post(new Runnable() { public void run() { loadImageIfNecessary(false, true); } }); } } @Override public void onResponse(final ImageContainer response, boolean isImmediate) { // If this was an immediate response that was delivered inside of a layout // pass do not set the image immediately as it will trigger a requestLayout // inside of a layout. Instead, defer setting the image by posting back to // the main thread. if (isImmediate && isInLayoutPass) { post(new Runnable() { @Override public void run() { onResponse(response, false); } }); return; } if (response.getBitmap() != null) { setImageBitmap(response.getBitmap()); if(tryOriginal && mMedia instanceof Contribution && response.getBitmap().getWidth() > mMedia.getWidth() || response.getBitmap().getHeight() > mMedia.getHeight()) { // If there is no width information for this image, save it. This speeds up image loading massively for smaller images mMedia.setHeight(response.getBitmap().getHeight()); mMedia.setWidth(response.getBitmap().getWidth()); ((Contribution)mMedia).setContentProviderClient(MediaWikiImageView.this.getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY)); ((Contribution)mMedia).save(); } if(loadingView != null) { loadingView.setVisibility(View.GONE); } } else { // I'm not really sure where this would hit but not onError } } }); // update the ImageContainer to be the new bitmap container. mImageContainer = newContainer; }
private void loadImageIfNecessary(final boolean isInLayoutPass, final boolean tryOriginal) { int width = getWidth(); int height = getHeight(); // if the view's bounds aren't known yet, hold off on loading the image. if (width == 0 && height == 0) { return; } if(mMedia == null) { return; } final String mUrl; if(tryOriginal) { mUrl = mMedia.getImageUrl(); } else { // Round it to the nearest 320 // Possible a similar size image has already been generated. // Reduces Server cache fragmentation, also increases chance of cache hit // If width is less than 320, we round up to 320 int bucketedWidth = width <= 320 ? 320 : Math.round((float)width / 320.0f) * 320; if(mMedia.getWidth() != 0 && mMedia.getWidth() < bucketedWidth) { // If we know that the width of the image is lesser than the required width // We don't even try to load the thumbnai, go directly to the source loadImageIfNecessary(isInLayoutPass, true); return; } else { mUrl = mMedia.getThumbnailUrl(bucketedWidth); } } // if the URL to be loaded in this view is empty, cancel any old requests and clear the // currently loaded image. if (TextUtils.isEmpty(mUrl)) { if (mImageContainer != null) { mImageContainer.cancelRequest(); mImageContainer = null; } setImageBitmap(null); return; } // Don't repeat work. Prevents onLayout cascades // We ignore it if the image request was for either the current URL of for the full URL // Since the full URL is always the second, and if (mImageContainer != null && mImageContainer.getRequestUrl() != null) { if (mImageContainer.getRequestUrl().equals(mMedia.getImageUrl()) || mImageContainer.getRequestUrl().equals(mUrl)) { return; } else { // if there is a pre-existing request, cancel it if it's fetching a different URL. mImageContainer.cancelRequest(); BitmapDrawable actualDrawable = (BitmapDrawable)getDrawable(); if(actualDrawable != null && actualDrawable.getBitmap() != null) { setImageBitmap(null); if(loadingView != null) { loadingView.setVisibility(View.VISIBLE); } } } } // The pre-existing content of this view didn't match the current URL. Load the new image // from the network. ImageContainer newContainer = mImageLoader.get(mUrl, new ImageListener() { @Override public void onErrorResponse(final VolleyError error) { if(!tryOriginal) { post(new Runnable() { public void run() { loadImageIfNecessary(false, true); } }); } } @Override public void onResponse(final ImageContainer response, boolean isImmediate) { // If this was an immediate response that was delivered inside of a layout // pass do not set the image immediately as it will trigger a requestLayout // inside of a layout. Instead, defer setting the image by posting back to // the main thread. if (isImmediate && isInLayoutPass) { post(new Runnable() { @Override public void run() { onResponse(response, false); } }); return; } if (response.getBitmap() != null) { setImageBitmap(response.getBitmap()); if(tryOriginal && mMedia instanceof Contribution && response.getBitmap().getWidth() > mMedia.getWidth() || response.getBitmap().getHeight() > mMedia.getHeight()) { // If there is no width information for this image, save it. This speeds up image loading massively for smaller images mMedia.setHeight(response.getBitmap().getHeight()); mMedia.setWidth(response.getBitmap().getWidth()); ((Contribution)mMedia).setContentProviderClient(MediaWikiImageView.this.getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY)); ((Contribution)mMedia).save(); } if(loadingView != null) { loadingView.setVisibility(View.GONE); } } else { // I'm not really sure where this would hit but not onError } } }); // update the ImageContainer to be the new bitmap container. mImageContainer = newContainer; }
diff --git a/app/googleMapsDirections/Directions.java b/app/googleMapsDirections/Directions.java index 3589efa..461afcf 100644 --- a/app/googleMapsDirections/Directions.java +++ b/app/googleMapsDirections/Directions.java @@ -1,61 +1,59 @@ package googleMapsDirections; import java.util.ArrayList; import java.util.Iterator; import org.codehaus.jackson.JsonNode; public class Directions { ArrayList<Location> route; final String apiServer = "http://maps.googleapis.com/maps/api/directions/json?"; public Directions() { route = new ArrayList<Location>(); } public void addRoutePoint(Location loc) { route.add(loc); } public long getTotalDistance() { - String requestURL = String - .format("%sorigin=%s&destination=%s&sensor=false&units=metric&waypoints=%s", - apiServer, getOriginLocation(), - getDestinationLocation(), getWaypointsLocations()); + String requestURL = String.format("%sorigin=%s&destination=%s&sensor=false&units=metric&waypoints=%s", apiServer, getOriginLocation(), + getDestinationLocation(), getWaypointsLocations()); HttpRequest req = new HttpRequest(requestURL); JsonNode result = req.getResult(); long distance = 0; - Iterator<JsonNode> it = result.getElements(); - while (it.hasNext()) { - JsonNode node = it.next(); - System.out.println(node); - if (node.findValue("legs") != null) { - JsonNode distanceValue = node.findValue("legs").findValue("distance").findValue("value"); - System.out.println(distanceValue.asLong()); - distance += distanceValue.asLong(); + if (result.findValue("routes") != null && result.findValue("routes").findValue("legs") != null) { + Iterator<JsonNode> it = result.findValue("routes").findValue("legs").getElements(); + while (it.hasNext()) { + JsonNode node = it.next(); + if (node.findValue("distance") != null && node.findValue("distance").findValue("value") != null) { + JsonNode distanceValue = node.findValue("distance").findValue("value"); + distance += distanceValue.asLong(); + } } } return distance; } private String getWaypointsLocations() { StringBuilder res = new StringBuilder(); for (Location loc : route.subList(1, route.size() - 1)) { res.append(loc.getLongLatString()); } return res.toString(); } private String getDestinationLocation() { return route.get(route.size() - 1).getLongLatString(); } private String getOriginLocation() { return route.get(0).getLongLatString(); } }
false
true
public long getTotalDistance() { String requestURL = String .format("%sorigin=%s&destination=%s&sensor=false&units=metric&waypoints=%s", apiServer, getOriginLocation(), getDestinationLocation(), getWaypointsLocations()); HttpRequest req = new HttpRequest(requestURL); JsonNode result = req.getResult(); long distance = 0; Iterator<JsonNode> it = result.getElements(); while (it.hasNext()) { JsonNode node = it.next(); System.out.println(node); if (node.findValue("legs") != null) { JsonNode distanceValue = node.findValue("legs").findValue("distance").findValue("value"); System.out.println(distanceValue.asLong()); distance += distanceValue.asLong(); } } return distance; }
public long getTotalDistance() { String requestURL = String.format("%sorigin=%s&destination=%s&sensor=false&units=metric&waypoints=%s", apiServer, getOriginLocation(), getDestinationLocation(), getWaypointsLocations()); HttpRequest req = new HttpRequest(requestURL); JsonNode result = req.getResult(); long distance = 0; if (result.findValue("routes") != null && result.findValue("routes").findValue("legs") != null) { Iterator<JsonNode> it = result.findValue("routes").findValue("legs").getElements(); while (it.hasNext()) { JsonNode node = it.next(); if (node.findValue("distance") != null && node.findValue("distance").findValue("value") != null) { JsonNode distanceValue = node.findValue("distance").findValue("value"); distance += distanceValue.asLong(); } } } return distance; }
diff --git a/src/java/org/lwjgl/opengl/glu/MipMap.java b/src/java/org/lwjgl/opengl/glu/MipMap.java index abc44a84..4940964e 100644 --- a/src/java/org/lwjgl/opengl/glu/MipMap.java +++ b/src/java/org/lwjgl/opengl/glu/MipMap.java @@ -1,287 +1,296 @@ package org.lwjgl.opengl.glu; import java.nio.ByteBuffer; import org.lwjgl.opengl.GL11; /** * MipMap.java * * * Created 11-jan-2004 * @author Erik Duijs */ public class MipMap extends Util { /** * Method gluBuild2DMipmaps * * @param target * @param components * @param width * @param height * @param format * @param type * @param data * @return int */ public static int gluBuild2DMipmaps( int target, int components, int width, int height, int format, int type, ByteBuffer data) { int retVal = 0; int error; int w, h, maxSize; ByteBuffer image, newimage; int neww, newh, level, bpp; boolean done; if (width < 1 || height < 1) return GLU.GLU_INVALID_VALUE; maxSize = glGetIntegerv(GL11.GL_MAX_TEXTURE_SIZE); w = nearestPower(width); if (w > maxSize) { w = maxSize; } h = nearestPower(height); if (h > maxSize) { h = maxSize; } bpp = bytesPerPixel(format, type); if (bpp == 0) { return GLU.GLU_INVALID_ENUM; } // Get current glPixelStore state PixelStoreState pss = new PixelStoreState(); // set pixel packing GL11.glPixelStorei(GL11.GL_PACK_ROW_LENGTH, 0); GL11.glPixelStorei(GL11.GL_PACK_ALIGNMENT, 1); GL11.glPixelStorei(GL11.GL_PACK_SKIP_ROWS, 0); GL11.glPixelStorei(GL11.GL_PACK_SKIP_PIXELS, 0); done = false; if (w != width || h != height) { // must rescale image to get "top" mipmap texture image image = ByteBuffer.allocateDirect((w + 4) * h * bpp); error = gluScaleImage(format, width, height, type, data, w, h, type, image); if (error != 0) { retVal = error; done = true; } } else { image = data; } level = 0; while (!done) { if (image != data) { /* set pixel unpacking */ GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0); GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); GL11.glPixelStorei(GL11.GL_UNPACK_SKIP_ROWS, 0); GL11.glPixelStorei(GL11.GL_UNPACK_SKIP_PIXELS, 0); } GL11.glTexImage2D(target, level, components, w, h, 0, format, type, image); if (w == 1 && h == 1) break; neww = (w < 2) ? 1 : w / 2; newh = (h < 2) ? 1 : h / 2; newimage = ByteBuffer.allocateDirect((neww + 4) * newh * bpp); error = gluScaleImage(format, w, h, type, image, neww, newh, type, newimage); if (error != 0) { retVal = error; done = true; } image = newimage; w = neww; h = newh; level++; } // Restore original glPixelStore state pss.save(); return retVal; } /** * Method gluScaleImage. * @param format * @param widthIn * @param heightIn * @param typein * @param dataIn * @param widthOut * @param heightOut * @param typeOut * @param dataOut * @return int */ public static int gluScaleImage( int format, int widthIn, int heightIn, int typein, ByteBuffer dataIn, int widthOut, int heightOut, int typeOut, ByteBuffer dataOut) { int components, i, j, k; float[] tempin, tempout; float sx, sy; int sizein, sizeout; int rowstride, rowlen; components = compPerPix(format); if (components == -1) { return GLU.GLU_INVALID_ENUM; } // temp image data tempin = new float[widthIn * heightIn * components]; tempout = new float[widthOut * heightOut * components]; // Determine bytes per input type switch (typein) { case GL11.GL_UNSIGNED_BYTE : sizein = 1; break; default : return GL11.GL_INVALID_ENUM; } // Determine bytes per output type switch (typeOut) { case GL11.GL_UNSIGNED_BYTE : sizeout = 1; break; default : return GL11.GL_INVALID_ENUM; } // Get glPixelStore state PixelStoreState pss = new PixelStoreState(); //Unpack the pixel data and convert to floating point if (pss.unpackRowLength > 0) { rowlen = pss.unpackRowLength; } else { rowlen = widthIn; } if (sizein >= pss.unpackAlignment) { rowstride = components * rowlen; } else { rowstride = pss.unpackAlignment / sizein * ceil(components * rowlen * sizein, pss.unpackAlignment); } switch (typein) { case GL11.GL_UNSIGNED_BYTE : k = 0; dataIn.rewind(); for (i = 0; i < heightIn; i++) { int ubptr = i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components; for (j = 0; j < widthIn * components; j++) { tempin[k++] = (float) ((int) dataIn.get(ubptr++) & 0xff); } } break; default : return GLU.GLU_INVALID_ENUM; } // Do scaling sx = (float) widthIn / (float) widthOut; sy = (float) heightIn / (float) heightOut; float[] c = new float[components]; int src, dst; for (int iy = 0; iy < heightOut; iy++) { for (int ix = 0; ix < widthOut; ix++) { int x0 = (int) (ix * sx); int x1 = (int) ((ix + 1) * sx); int y0 = (int) (iy * sy); int y1 = (int) ((iy + 1) * sy); int readPix = 0; // reset weighted pixel for (int ic = 0; ic < components; ic++) { c[ic] = 0; } // create weighted pixel for (int ix0 = x0; ix0 < x1; ix0++) { for (int iy0 = y0; iy0 < y1; iy0++) { src = (iy0 * widthIn + ix0) * components; for (int ic = 0; ic < components; ic++) { c[ic] += tempin[src + ic]; } readPix++; } } // store weighted pixel dst = (iy * widthOut + ix) * components; - for (k = 0; k < components; k++) { - tempout[dst++] = c[k] / readPix; - } + if (readPix == 0) { + // Image is sized up, caused by non power of two texture as input + src = (y0 * widthIn + x0) * components; + for (int ic = 0; ic < components; ic++) { + tempout[dst++] = tempin[src + ic]; + } + } else { + // sized down + for (k = 0; k < components; k++) { + tempout[dst++] = c[k] / readPix; + } + } } } // Convert temp output if (pss.packRowLength > 0) { rowlen = pss.packRowLength; } else { rowlen = widthOut; } if (sizeout >= pss.packAlignment) { rowstride = components * rowlen; } else { rowstride = pss.packAlignment / sizeout * ceil(components * rowlen * sizeout, pss.packAlignment); } switch (typeOut) { case GL11.GL_UNSIGNED_BYTE : k = 0; for (i = 0; i < heightOut; i++) { int ubptr = i * rowstride + pss.packSkipRows * rowstride + pss.packSkipPixels * components; for (j = 0; j < widthOut * components; j++) { dataOut.put(ubptr++, (byte) tempout[k++]); } } break; default : return GLU.GLU_INVALID_ENUM; } return 0; } }
true
true
public static int gluScaleImage( int format, int widthIn, int heightIn, int typein, ByteBuffer dataIn, int widthOut, int heightOut, int typeOut, ByteBuffer dataOut) { int components, i, j, k; float[] tempin, tempout; float sx, sy; int sizein, sizeout; int rowstride, rowlen; components = compPerPix(format); if (components == -1) { return GLU.GLU_INVALID_ENUM; } // temp image data tempin = new float[widthIn * heightIn * components]; tempout = new float[widthOut * heightOut * components]; // Determine bytes per input type switch (typein) { case GL11.GL_UNSIGNED_BYTE : sizein = 1; break; default : return GL11.GL_INVALID_ENUM; } // Determine bytes per output type switch (typeOut) { case GL11.GL_UNSIGNED_BYTE : sizeout = 1; break; default : return GL11.GL_INVALID_ENUM; } // Get glPixelStore state PixelStoreState pss = new PixelStoreState(); //Unpack the pixel data and convert to floating point if (pss.unpackRowLength > 0) { rowlen = pss.unpackRowLength; } else { rowlen = widthIn; } if (sizein >= pss.unpackAlignment) { rowstride = components * rowlen; } else { rowstride = pss.unpackAlignment / sizein * ceil(components * rowlen * sizein, pss.unpackAlignment); } switch (typein) { case GL11.GL_UNSIGNED_BYTE : k = 0; dataIn.rewind(); for (i = 0; i < heightIn; i++) { int ubptr = i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components; for (j = 0; j < widthIn * components; j++) { tempin[k++] = (float) ((int) dataIn.get(ubptr++) & 0xff); } } break; default : return GLU.GLU_INVALID_ENUM; } // Do scaling sx = (float) widthIn / (float) widthOut; sy = (float) heightIn / (float) heightOut; float[] c = new float[components]; int src, dst; for (int iy = 0; iy < heightOut; iy++) { for (int ix = 0; ix < widthOut; ix++) { int x0 = (int) (ix * sx); int x1 = (int) ((ix + 1) * sx); int y0 = (int) (iy * sy); int y1 = (int) ((iy + 1) * sy); int readPix = 0; // reset weighted pixel for (int ic = 0; ic < components; ic++) { c[ic] = 0; } // create weighted pixel for (int ix0 = x0; ix0 < x1; ix0++) { for (int iy0 = y0; iy0 < y1; iy0++) { src = (iy0 * widthIn + ix0) * components; for (int ic = 0; ic < components; ic++) { c[ic] += tempin[src + ic]; } readPix++; } } // store weighted pixel dst = (iy * widthOut + ix) * components; for (k = 0; k < components; k++) { tempout[dst++] = c[k] / readPix; } } } // Convert temp output if (pss.packRowLength > 0) { rowlen = pss.packRowLength; } else { rowlen = widthOut; } if (sizeout >= pss.packAlignment) { rowstride = components * rowlen; } else { rowstride = pss.packAlignment / sizeout * ceil(components * rowlen * sizeout, pss.packAlignment); } switch (typeOut) { case GL11.GL_UNSIGNED_BYTE : k = 0; for (i = 0; i < heightOut; i++) { int ubptr = i * rowstride + pss.packSkipRows * rowstride + pss.packSkipPixels * components; for (j = 0; j < widthOut * components; j++) { dataOut.put(ubptr++, (byte) tempout[k++]); } } break; default : return GLU.GLU_INVALID_ENUM; } return 0; }
public static int gluScaleImage( int format, int widthIn, int heightIn, int typein, ByteBuffer dataIn, int widthOut, int heightOut, int typeOut, ByteBuffer dataOut) { int components, i, j, k; float[] tempin, tempout; float sx, sy; int sizein, sizeout; int rowstride, rowlen; components = compPerPix(format); if (components == -1) { return GLU.GLU_INVALID_ENUM; } // temp image data tempin = new float[widthIn * heightIn * components]; tempout = new float[widthOut * heightOut * components]; // Determine bytes per input type switch (typein) { case GL11.GL_UNSIGNED_BYTE : sizein = 1; break; default : return GL11.GL_INVALID_ENUM; } // Determine bytes per output type switch (typeOut) { case GL11.GL_UNSIGNED_BYTE : sizeout = 1; break; default : return GL11.GL_INVALID_ENUM; } // Get glPixelStore state PixelStoreState pss = new PixelStoreState(); //Unpack the pixel data and convert to floating point if (pss.unpackRowLength > 0) { rowlen = pss.unpackRowLength; } else { rowlen = widthIn; } if (sizein >= pss.unpackAlignment) { rowstride = components * rowlen; } else { rowstride = pss.unpackAlignment / sizein * ceil(components * rowlen * sizein, pss.unpackAlignment); } switch (typein) { case GL11.GL_UNSIGNED_BYTE : k = 0; dataIn.rewind(); for (i = 0; i < heightIn; i++) { int ubptr = i * rowstride + pss.unpackSkipRows * rowstride + pss.unpackSkipPixels * components; for (j = 0; j < widthIn * components; j++) { tempin[k++] = (float) ((int) dataIn.get(ubptr++) & 0xff); } } break; default : return GLU.GLU_INVALID_ENUM; } // Do scaling sx = (float) widthIn / (float) widthOut; sy = (float) heightIn / (float) heightOut; float[] c = new float[components]; int src, dst; for (int iy = 0; iy < heightOut; iy++) { for (int ix = 0; ix < widthOut; ix++) { int x0 = (int) (ix * sx); int x1 = (int) ((ix + 1) * sx); int y0 = (int) (iy * sy); int y1 = (int) ((iy + 1) * sy); int readPix = 0; // reset weighted pixel for (int ic = 0; ic < components; ic++) { c[ic] = 0; } // create weighted pixel for (int ix0 = x0; ix0 < x1; ix0++) { for (int iy0 = y0; iy0 < y1; iy0++) { src = (iy0 * widthIn + ix0) * components; for (int ic = 0; ic < components; ic++) { c[ic] += tempin[src + ic]; } readPix++; } } // store weighted pixel dst = (iy * widthOut + ix) * components; if (readPix == 0) { // Image is sized up, caused by non power of two texture as input src = (y0 * widthIn + x0) * components; for (int ic = 0; ic < components; ic++) { tempout[dst++] = tempin[src + ic]; } } else { // sized down for (k = 0; k < components; k++) { tempout[dst++] = c[k] / readPix; } } } } // Convert temp output if (pss.packRowLength > 0) { rowlen = pss.packRowLength; } else { rowlen = widthOut; } if (sizeout >= pss.packAlignment) { rowstride = components * rowlen; } else { rowstride = pss.packAlignment / sizeout * ceil(components * rowlen * sizeout, pss.packAlignment); } switch (typeOut) { case GL11.GL_UNSIGNED_BYTE : k = 0; for (i = 0; i < heightOut; i++) { int ubptr = i * rowstride + pss.packSkipRows * rowstride + pss.packSkipPixels * components; for (j = 0; j < widthOut * components; j++) { dataOut.put(ubptr++, (byte) tempout[k++]); } } break; default : return GLU.GLU_INVALID_ENUM; } return 0; }
diff --git a/src/gov/nih/nci/caintegrator/application/mail/test/MailTest.java b/src/gov/nih/nci/caintegrator/application/mail/test/MailTest.java index 20ff3a8..ff1f2d7 100644 --- a/src/gov/nih/nci/caintegrator/application/mail/test/MailTest.java +++ b/src/gov/nih/nci/caintegrator/application/mail/test/MailTest.java @@ -1,36 +1,37 @@ package gov.nih.nci.caintegrator.application.mail.test; import gov.nih.nci.caintegrator.application.mail.MailManager; import junit.framework.TestCase; import java.util.ArrayList; public class MailTest extends TestCase { public MailTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testMail() { //MailManager mailMgr = new MailManager(); //System.out.println(mailMgr); try { ArrayList<String> al = new ArrayList<String>(); al.add("test.zip"); - MailManager.sendFTPMail("[email protected]", false, al); + MailManager.sendFTPMail("[email protected]", al); + MailManager.sendFTPErrorMail("[email protected]"); } catch (Exception e1) { e1.printStackTrace(); } } }
true
true
public void testMail() { //MailManager mailMgr = new MailManager(); //System.out.println(mailMgr); try { ArrayList<String> al = new ArrayList<String>(); al.add("test.zip"); MailManager.sendFTPMail("[email protected]", false, al); } catch (Exception e1) { e1.printStackTrace(); } }
public void testMail() { //MailManager mailMgr = new MailManager(); //System.out.println(mailMgr); try { ArrayList<String> al = new ArrayList<String>(); al.add("test.zip"); MailManager.sendFTPMail("[email protected]", al); MailManager.sendFTPErrorMail("[email protected]"); } catch (Exception e1) { e1.printStackTrace(); } }
diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/defaultadaptor/BundleResourceHandler.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/defaultadaptor/BundleResourceHandler.java index 20d93bf8..e88c3289 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/defaultadaptor/BundleResourceHandler.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/defaultadaptor/BundleResourceHandler.java @@ -1,259 +1,259 @@ /******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.osgi.framework.internal.defaultadaptor; import java.io.IOException; import java.net.*; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor; import org.eclipse.osgi.framework.internal.core.Bundle; import org.eclipse.osgi.framework.internal.protocol.ProtocolActivator; import org.osgi.framework.AdminPermission; import org.osgi.framework.BundleContext; /** * URLStreamHandler the bundleentry and bundleresource protocols. */ public abstract class BundleResourceHandler extends URLStreamHandler implements ProtocolActivator { public static final String SECURITY_AUTHORIZED = "SECURITY_AUTHORIZED"; protected BundleContext context; protected BundleEntry bundleEntry; /** Single object for permission checks */ protected AdminPermission adminPermission; /** * Constructor for a bundle protocol resource URLStreamHandler. */ public BundleResourceHandler() { } public BundleResourceHandler(BundleEntry bundleEntry, BundleContext context) { this.context = context; this.bundleEntry = bundleEntry; } /** * Parse reference URL. */ protected void parseURL(URL url, String str, int start, int end) { if (end <= start) { return; } // Check the permission of the caller to see if they // are allowed access to the resource. checkAdminPermission(); String bundleId,path; if (str.startsWith(url.getProtocol())) { if (str.charAt(start) != '/' || str.charAt(start+1) != '/') - throw new IllegalArgumentException("URL must be opaque."); + throw new IllegalArgumentException(AdaptorMsg.formatter.getString("URL_IS_OPAQUE",url.getProtocol())); start += 2; int slash = str.indexOf("/",start); if (slash < 0) { throw new IllegalArgumentException(AdaptorMsg.formatter.getString("URL_NO_PATH")); } bundleId = str.substring(start,slash); path = str.substring(slash,end); } else { // A call to a URL constructor has been made that // uses an authorized URL as its context. bundleId = url.getHost(); if (str.length() > 0 && str.charAt(0) == '/') { // does not specify a relative path. path = str; } else { // relative path specified. StringBuffer pathBuffer = new StringBuffer(url.getPath()); if (pathBuffer.charAt(pathBuffer.length() - 1) != '/') pathBuffer.append('/'); pathBuffer.append(str); path = pathBuffer.toString(); } // null out bundleEntry because it will not be valid for the new path bundleEntry = null; } // Setting the authority portion of the URL to SECURITY_ATHORIZED // ensures that this URL was created by using this parseURL // method. The openConnection method will only open URLs // that have the authority set to this. setURL(url, url.getProtocol(), bundleId, 0, SECURITY_AUTHORIZED, null, path, null, null); } /** * Establishes a connection to the resource specified by <code>URL</code>. * Since different protocols may have unique ways of connecting, it must be * overridden by the subclass. * * @return java.net.URLConnection * @param url java.net.URL * * @exception IOException thrown if an IO error occurs during connection establishment */ protected URLConnection openConnection(URL url) throws IOException { String authority = url.getAuthority(); // check to make sure that this URL was created using the // parseURL method. This ensures the security check was done // at URL construction. if (!url.getAuthority().equals(SECURITY_AUTHORIZED)) { // No admin security check was made better check now. checkAdminPermission(); } if (bundleEntry != null){ return (new BundleURLConnection(url,bundleEntry)); } else { String bidString = url.getHost(); if (bidString == null) { throw new IOException(AdaptorMsg.formatter.getString("URL_NO_BUNDLE_ID", url.toExternalForm())); } Bundle bundle = null; try { Long bundleID = new Long(bidString); bundle = (Bundle) context.getBundle(bundleID.longValue()); } catch (NumberFormatException nfe) { throw new MalformedURLException(AdaptorMsg.formatter.getString("URL_INVALID_BUNDLE_ID", bidString)); } if (bundle == null) { throw new IOException(AdaptorMsg.formatter.getString("URL_NO_BUNDLE_FOUND", url.toExternalForm())); } return(new BundleURLConnection(url, findBundleEntry(url,bundle))); } } /** * Finds the bundle entry for this protocal. This is handled * differently for Bundle.gerResource() and Bundle.getEntry() * because getResource uses the bundle classloader and getEntry * only used the base bundle file. * @param url The URL to find the BundleEntry for. * @return */ abstract protected BundleEntry findBundleEntry(URL url,Bundle bundle) throws IOException; /** * Converts a bundle URL to a String. * * @param url the URL. * @return a string representation of the URL. */ protected String toExternalForm(URL url) { StringBuffer result = new StringBuffer(url.getProtocol()); result.append("://"); String bundleId = url.getHost(); if ((bundleId != null) && (bundleId.length() > 0)) { result.append(bundleId); } String path = url.getPath(); if (path != null) { if ((path.length() > 0) && (path.charAt(0) != '/')) /* if name doesn't have a leading slash */ { result.append("/"); } result.append(path); } return (result.toString()); } public void start(BundleContext context, FrameworkAdaptor adaptor) { this.context = context; } protected int hashCode(URL url) { int hash=0; String protocol = url.getProtocol(); if (protocol != null) hash += protocol.hashCode(); String host = url.getHost(); if (host != null) hash += host.hashCode(); String path = url.getPath(); if (path != null) hash += path.hashCode(); return hash; } protected boolean equals(URL url1, URL url2) { return sameFile(url1, url2); } protected synchronized InetAddress getHostAddress(URL url) { return null; } protected boolean hostsEqual(URL url1, URL url2) { String host1 = url1.getHost(); String host2 = url2.getHost(); if (host1 != null && host2 != null) return host1.equalsIgnoreCase(host2); else return (host1 == null && host2 == null); } protected boolean sameFile(URL url1, URL url2) { String p1 = url1.getProtocol(); String p2 = url2.getProtocol(); if (!((p1 == p2) || (p1 != null && p1.equalsIgnoreCase(p2)))) return false; if (!hostsEqual(url1,url2)) return false; String a1 = url1.getAuthority(); String a2 = url2.getAuthority(); if (!((a1 == a2) || (a1 != null && a1.equals(a2)))) return false; String path1 = url1.getPath(); String path2 = url2.getPath(); if (!((path1 == path2) || (path1 != null && path1.equals(path2)))) return false; return true; } protected void checkAdminPermission() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (adminPermission == null) { adminPermission = new AdminPermission(); } sm.checkPermission(adminPermission); } } }
true
true
protected void parseURL(URL url, String str, int start, int end) { if (end <= start) { return; } // Check the permission of the caller to see if they // are allowed access to the resource. checkAdminPermission(); String bundleId,path; if (str.startsWith(url.getProtocol())) { if (str.charAt(start) != '/' || str.charAt(start+1) != '/') throw new IllegalArgumentException("URL must be opaque."); start += 2; int slash = str.indexOf("/",start); if (slash < 0) { throw new IllegalArgumentException(AdaptorMsg.formatter.getString("URL_NO_PATH")); } bundleId = str.substring(start,slash); path = str.substring(slash,end); } else { // A call to a URL constructor has been made that // uses an authorized URL as its context. bundleId = url.getHost(); if (str.length() > 0 && str.charAt(0) == '/') { // does not specify a relative path. path = str; } else { // relative path specified. StringBuffer pathBuffer = new StringBuffer(url.getPath()); if (pathBuffer.charAt(pathBuffer.length() - 1) != '/') pathBuffer.append('/'); pathBuffer.append(str); path = pathBuffer.toString(); } // null out bundleEntry because it will not be valid for the new path bundleEntry = null; } // Setting the authority portion of the URL to SECURITY_ATHORIZED // ensures that this URL was created by using this parseURL // method. The openConnection method will only open URLs // that have the authority set to this. setURL(url, url.getProtocol(), bundleId, 0, SECURITY_AUTHORIZED, null, path, null, null); }
protected void parseURL(URL url, String str, int start, int end) { if (end <= start) { return; } // Check the permission of the caller to see if they // are allowed access to the resource. checkAdminPermission(); String bundleId,path; if (str.startsWith(url.getProtocol())) { if (str.charAt(start) != '/' || str.charAt(start+1) != '/') throw new IllegalArgumentException(AdaptorMsg.formatter.getString("URL_IS_OPAQUE",url.getProtocol())); start += 2; int slash = str.indexOf("/",start); if (slash < 0) { throw new IllegalArgumentException(AdaptorMsg.formatter.getString("URL_NO_PATH")); } bundleId = str.substring(start,slash); path = str.substring(slash,end); } else { // A call to a URL constructor has been made that // uses an authorized URL as its context. bundleId = url.getHost(); if (str.length() > 0 && str.charAt(0) == '/') { // does not specify a relative path. path = str; } else { // relative path specified. StringBuffer pathBuffer = new StringBuffer(url.getPath()); if (pathBuffer.charAt(pathBuffer.length() - 1) != '/') pathBuffer.append('/'); pathBuffer.append(str); path = pathBuffer.toString(); } // null out bundleEntry because it will not be valid for the new path bundleEntry = null; } // Setting the authority portion of the URL to SECURITY_ATHORIZED // ensures that this URL was created by using this parseURL // method. The openConnection method will only open URLs // that have the authority set to this. setURL(url, url.getProtocol(), bundleId, 0, SECURITY_AUTHORIZED, null, path, null, null); }
diff --git a/src/biz/bokhorst/xprivacy/XWifiManager.java b/src/biz/bokhorst/xprivacy/XWifiManager.java index f96efdfa..249fc2de 100644 --- a/src/biz/bokhorst/xprivacy/XWifiManager.java +++ b/src/biz/bokhorst/xprivacy/XWifiManager.java @@ -1,108 +1,108 @@ package biz.bokhorst.xprivacy; import java.lang.reflect.Field; import java.util.ArrayList; import android.net.DhcpInfo; import android.net.wifi.ScanResult; import android.net.wifi.SupplicantState; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import de.robv.android.xposed.XC_MethodHook.MethodHookParam; import static de.robv.android.xposed.XposedHelpers.findField; public class XWifiManager extends XHook { public XWifiManager(String methodName, String restrictionName, String[] permissions) { super(methodName, restrictionName, permissions, null); } // public List<WifiConfiguration> getConfiguredNetworks() // public WifiInfo getConnectionInfo() // public DhcpInfo getDhcpInfo() // public List<ScanResult> getScanResults() // public WifiConfiguration getWifiApConfiguration() // frameworks/base/wifi/java/android/net/wifi/WifiManager.java @Override protected void before(MethodHookParam param) throws Throwable { if (param.method.getName().equals("getConfiguredNetworks")) { if (isRestricted(param)) param.setResult(new ArrayList<WifiConfiguration>()); } else if (param.method.getName().equals("getScanResults")) { if (isRestricted(param)) param.setResult(new ArrayList<ScanResult>()); } else if (param.method.getName().equals("getWifiApConfiguration")) { if (isRestricted(param)) param.setResult(null); } } @Override protected void after(MethodHookParam param) throws Throwable { if (param.method.getName().equals("getConnectionInfo")) { // frameworks/base/wifi/java/android/net/wifi/WifiInfo.java WifiInfo wInfo = (WifiInfo) param.getResult(); if (wInfo != null) if (isRestricted(param)) if (getRestrictionName().equals(PrivacyManager.cInternet)) { // Supplicant state try { Field fieldState = findField(WifiInfo.class, "mSupplicantState"); fieldState.set(wInfo, SupplicantState.DISCONNECTED); } catch (Throwable ex) { Util.bug(this, ex); } } else { // BSSID try { Field fieldBSSID = findField(WifiInfo.class, "mBSSID"); fieldBSSID.set(wInfo, PrivacyManager.getDefacedProp("MAC")); } catch (Throwable ex) { Util.bug(this, ex); } // IP address try { Field fieldIp = findField(WifiInfo.class, "mIpAddress"); fieldIp.set(wInfo, PrivacyManager.getDefacedProp("InetAddress")); } catch (Throwable ex) { Util.bug(this, ex); } // MAC address try { Field fieldMAC = findField(WifiInfo.class, "mMacAddress"); fieldMAC.set(wInfo, PrivacyManager.getDefacedProp("MAC")); } catch (Throwable ex) { Util.bug(this, ex); } // SSID try { Field fieldSSID = findField(WifiInfo.class, "mSSID"); fieldSSID.set(wInfo, PrivacyManager.getDefacedProp("SSID")); } catch (Throwable ex) { try { Field fieldWifiSsid = findField(WifiInfo.class, "mWifiSsid"); - fieldWifiSsid.set(wInfo, PrivacyManager.getDefacedProp("SSID")); + fieldWifiSsid.set(wInfo, PrivacyManager.getDefacedProp("WifiSsid.octets")); } catch (Throwable exex) { Util.bug(this, exex); } } } } else if (param.method.getName().equals("getDhcpInfo")) { // frameworks/base/core/java/android/net/DhcpInfo.java DhcpInfo dInfo = (DhcpInfo) param.getResult(); if (dInfo != null) if (isRestricted(param)) { dInfo.ipAddress = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.gateway = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.dns1 = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.dns2 = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.serverAddress = (Integer) PrivacyManager.getDefacedProp("IPInt"); } } } }
true
true
protected void after(MethodHookParam param) throws Throwable { if (param.method.getName().equals("getConnectionInfo")) { // frameworks/base/wifi/java/android/net/wifi/WifiInfo.java WifiInfo wInfo = (WifiInfo) param.getResult(); if (wInfo != null) if (isRestricted(param)) if (getRestrictionName().equals(PrivacyManager.cInternet)) { // Supplicant state try { Field fieldState = findField(WifiInfo.class, "mSupplicantState"); fieldState.set(wInfo, SupplicantState.DISCONNECTED); } catch (Throwable ex) { Util.bug(this, ex); } } else { // BSSID try { Field fieldBSSID = findField(WifiInfo.class, "mBSSID"); fieldBSSID.set(wInfo, PrivacyManager.getDefacedProp("MAC")); } catch (Throwable ex) { Util.bug(this, ex); } // IP address try { Field fieldIp = findField(WifiInfo.class, "mIpAddress"); fieldIp.set(wInfo, PrivacyManager.getDefacedProp("InetAddress")); } catch (Throwable ex) { Util.bug(this, ex); } // MAC address try { Field fieldMAC = findField(WifiInfo.class, "mMacAddress"); fieldMAC.set(wInfo, PrivacyManager.getDefacedProp("MAC")); } catch (Throwable ex) { Util.bug(this, ex); } // SSID try { Field fieldSSID = findField(WifiInfo.class, "mSSID"); fieldSSID.set(wInfo, PrivacyManager.getDefacedProp("SSID")); } catch (Throwable ex) { try { Field fieldWifiSsid = findField(WifiInfo.class, "mWifiSsid"); fieldWifiSsid.set(wInfo, PrivacyManager.getDefacedProp("SSID")); } catch (Throwable exex) { Util.bug(this, exex); } } } } else if (param.method.getName().equals("getDhcpInfo")) { // frameworks/base/core/java/android/net/DhcpInfo.java DhcpInfo dInfo = (DhcpInfo) param.getResult(); if (dInfo != null) if (isRestricted(param)) { dInfo.ipAddress = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.gateway = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.dns1 = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.dns2 = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.serverAddress = (Integer) PrivacyManager.getDefacedProp("IPInt"); } } }
protected void after(MethodHookParam param) throws Throwable { if (param.method.getName().equals("getConnectionInfo")) { // frameworks/base/wifi/java/android/net/wifi/WifiInfo.java WifiInfo wInfo = (WifiInfo) param.getResult(); if (wInfo != null) if (isRestricted(param)) if (getRestrictionName().equals(PrivacyManager.cInternet)) { // Supplicant state try { Field fieldState = findField(WifiInfo.class, "mSupplicantState"); fieldState.set(wInfo, SupplicantState.DISCONNECTED); } catch (Throwable ex) { Util.bug(this, ex); } } else { // BSSID try { Field fieldBSSID = findField(WifiInfo.class, "mBSSID"); fieldBSSID.set(wInfo, PrivacyManager.getDefacedProp("MAC")); } catch (Throwable ex) { Util.bug(this, ex); } // IP address try { Field fieldIp = findField(WifiInfo.class, "mIpAddress"); fieldIp.set(wInfo, PrivacyManager.getDefacedProp("InetAddress")); } catch (Throwable ex) { Util.bug(this, ex); } // MAC address try { Field fieldMAC = findField(WifiInfo.class, "mMacAddress"); fieldMAC.set(wInfo, PrivacyManager.getDefacedProp("MAC")); } catch (Throwable ex) { Util.bug(this, ex); } // SSID try { Field fieldSSID = findField(WifiInfo.class, "mSSID"); fieldSSID.set(wInfo, PrivacyManager.getDefacedProp("SSID")); } catch (Throwable ex) { try { Field fieldWifiSsid = findField(WifiInfo.class, "mWifiSsid"); fieldWifiSsid.set(wInfo, PrivacyManager.getDefacedProp("WifiSsid.octets")); } catch (Throwable exex) { Util.bug(this, exex); } } } } else if (param.method.getName().equals("getDhcpInfo")) { // frameworks/base/core/java/android/net/DhcpInfo.java DhcpInfo dInfo = (DhcpInfo) param.getResult(); if (dInfo != null) if (isRestricted(param)) { dInfo.ipAddress = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.gateway = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.dns1 = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.dns2 = (Integer) PrivacyManager.getDefacedProp("IPInt"); dInfo.serverAddress = (Integer) PrivacyManager.getDefacedProp("IPInt"); } } }
diff --git a/orbisgis-view/src/main/java/org/orbisgis/view/map/mapsManager/MapsManager.java b/orbisgis-view/src/main/java/org/orbisgis/view/map/mapsManager/MapsManager.java index 964f3d84a..ebeddf532 100644 --- a/orbisgis-view/src/main/java/org/orbisgis/view/map/mapsManager/MapsManager.java +++ b/orbisgis-view/src/main/java/org/orbisgis/view/map/mapsManager/MapsManager.java @@ -1,228 +1,229 @@ /* * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able to * manipulate and create vector and raster spatial information. * * OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG" * team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488. * * Copyright (C) 2007-2012 IRSTV (FR CNRS 2488) * * This file is part of OrbisGIS. * * OrbisGIS 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. * * OrbisGIS 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 * OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: <http://www.orbisgis.org/> * or contact directly: * info_at_ orbisgis.org */ package org.orbisgis.view.map.mapsManager; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.apache.log4j.Logger; import org.orbisgis.core.Services; import org.orbisgis.view.background.BackgroundManager; import org.orbisgis.view.components.fstree.FileTree; import org.orbisgis.view.components.fstree.FileTreeModel; import org.orbisgis.view.components.fstree.TreeNodeFileFactoryManager; import org.orbisgis.view.components.fstree.TreeNodeFolder; import org.orbisgis.view.components.fstree.TreeNodePath; import org.orbisgis.view.map.mapsManager.jobs.ReadStoredMap; import org.orbisgis.view.workspace.ViewWorkspace; import org.xnap.commons.i18n.I18n; import org.xnap.commons.i18n.I18nFactory; /** * A title and a tree that show local and remote map contexts * @author Nicolas Fortin */ public class MapsManager extends JPanel { // Minimal tree size is incremented by this emptySpace private static final long serialVersionUID = 1L; private static final I18n I18N = I18nFactory.getI18n(MapsManager.class); private static final Logger LOGGER = Logger.getLogger(MapsManager.class); private FileTree tree; private DefaultTreeModel treeModel; private MutableTreeNode rootNode = new DefaultMutableTreeNode(); private TreeNodeFolder rootFolder; private TreeNodeRemoteRoot rootRemote; private JScrollPane scrollPane; private File loadedMap; // Store all the compatible map context private AtomicBoolean initialized = new AtomicBoolean(false); /** * Default constructor */ public MapsManager() { super(new BorderLayout()); treeModel = new FileTreeModel(rootNode, true); treeModel.setAsksAllowsChildren(true); // Add the tree in the panel tree = new FileTree(treeModel); tree.setEditable(true); + tree.setShowsRootHandles(true); // Retrieve the default ows maps folder ViewWorkspace workspace = Services.getService(ViewWorkspace.class); // Add the root folder File rootFolderPath = new File(workspace.getMapContextPath()); if(!rootFolderPath.exists()) { rootFolderPath.mkdirs(); } rootFolder = new TreeNodeFolder(rootFolderPath,tree); rootFolder.setLabel(I18N.tr("Local")); rootRemote = new TreeNodeRemoteRoot(); initInternalFactories(); // Init file readers treeModel.insertNodeInto(rootFolder, rootNode, rootNode.getChildCount()); treeModel.insertNodeInto(rootRemote, rootNode, rootNode.getChildCount()); tree.setRootVisible(false); scrollPane = new JScrollPane(tree); JLabel title = new JLabel(I18N.tr("Maps manager")); // Disable mouse event propagation on this label title.addMouseListener(new MouseAdapter(){}); add(title,BorderLayout.NORTH); add(scrollPane,BorderLayout.CENTER); setBorder(BorderFactory.createEtchedBorder()); } /** * Used by the UI to convert a File into a MapElement * @return The Map file factory manager */ public TreeNodeFileFactoryManager getFactoryManager() { return tree; } /** * Update the shown elements in the disk tree */ public void updateDiskTree() { rootFolder.updateTree(); applyLoadedMapHint(); } private List<TreeLeafMapElement> getAllMapElements(TreeNode parentNode) { List<TreeLeafMapElement> mapElements = new ArrayList<TreeLeafMapElement>(); if(!parentNode.isLeaf()) { for(int childIndex=0; childIndex < parentNode.getChildCount(); childIndex++) { TreeNode nodeElement = parentNode.getChildAt(childIndex); if(nodeElement instanceof TreeLeafMapElement) { mapElements.add((TreeLeafMapElement)nodeElement); } else { mapElements.addAll(getAllMapElements(nodeElement)); } } } return mapElements; } @Override public void setVisible(boolean visible) { super.setVisible(visible); if(visible && !initialized.getAndSet(true)) { // Set a listener to the root folder rootFolder.updateTree(); //Read the file system tree // Expand Local and remote folder tree.expandPath(new TreePath(new Object[] {rootNode,rootFolder})); tree.expandPath(new TreePath(new Object[] {rootNode,rootRemote})); updateMapsTitle(); // Apply loaded map property on map nodes applyLoadedMapHint(); } } private void updateMapsTitle() { // Fetch all maps to find their titles BackgroundManager bm = Services.getService(BackgroundManager.class); bm.nonBlockingBackgroundOperation(new ReadStoredMap(getAllMapElements(rootFolder))); } /** * Load built-ins map factory */ private void initInternalFactories() { tree.addFactory("ows",new TreeNodeOwsMapContextFactory()); } /** * * @return The internal tree */ public JTree getTree() { return tree; } /** * The map manager will read and update the map server list * @param mapCatalogServers */ public void setServerList(List<String> mapCatalogServers) { rootRemote.setServerList(mapCatalogServers); } /** * Update the state of the tree to show to the user a visual hint that a * map is currently shown in the MapEditor or not. * * @param loadedMap */ public void setLoadedMap(File loadedMap) { this.loadedMap = loadedMap; applyLoadedMapHint(); } private void applyLoadedMapHint() { if(loadedMap!=null) { List<TreeLeafMapElement> mapElements = getAllMapElements(rootFolder); for(TreeLeafMapElement mapEl : mapElements) { if(mapEl instanceof TreeNodePath) { if(((TreeNodePath)mapEl).getFilePath().equals(loadedMap)) { mapEl.setLoaded(true); } else { mapEl.setLoaded(false); } } } } } /** * Compute the best height to show all the items of the JTree * plus the decoration height. * @return Height in pixels */ public Dimension getMinimalComponentDimension() { Dimension panel = getPreferredSize(); Dimension treeDim = tree.getPreferredSize(); // Get the vertical scrollbar width JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); if(scrollBar!=null && scrollBar.isVisible()) { return new Dimension(panel.width+scrollBar.getWidth(),treeDim.height+getMinimumSize().height); } else { return new Dimension(panel.width,treeDim.height+getMinimumSize().height); } } }
true
true
public MapsManager() { super(new BorderLayout()); treeModel = new FileTreeModel(rootNode, true); treeModel.setAsksAllowsChildren(true); // Add the tree in the panel tree = new FileTree(treeModel); tree.setEditable(true); // Retrieve the default ows maps folder ViewWorkspace workspace = Services.getService(ViewWorkspace.class); // Add the root folder File rootFolderPath = new File(workspace.getMapContextPath()); if(!rootFolderPath.exists()) { rootFolderPath.mkdirs(); } rootFolder = new TreeNodeFolder(rootFolderPath,tree); rootFolder.setLabel(I18N.tr("Local")); rootRemote = new TreeNodeRemoteRoot(); initInternalFactories(); // Init file readers treeModel.insertNodeInto(rootFolder, rootNode, rootNode.getChildCount()); treeModel.insertNodeInto(rootRemote, rootNode, rootNode.getChildCount()); tree.setRootVisible(false); scrollPane = new JScrollPane(tree); JLabel title = new JLabel(I18N.tr("Maps manager")); // Disable mouse event propagation on this label title.addMouseListener(new MouseAdapter(){}); add(title,BorderLayout.NORTH); add(scrollPane,BorderLayout.CENTER); setBorder(BorderFactory.createEtchedBorder()); }
public MapsManager() { super(new BorderLayout()); treeModel = new FileTreeModel(rootNode, true); treeModel.setAsksAllowsChildren(true); // Add the tree in the panel tree = new FileTree(treeModel); tree.setEditable(true); tree.setShowsRootHandles(true); // Retrieve the default ows maps folder ViewWorkspace workspace = Services.getService(ViewWorkspace.class); // Add the root folder File rootFolderPath = new File(workspace.getMapContextPath()); if(!rootFolderPath.exists()) { rootFolderPath.mkdirs(); } rootFolder = new TreeNodeFolder(rootFolderPath,tree); rootFolder.setLabel(I18N.tr("Local")); rootRemote = new TreeNodeRemoteRoot(); initInternalFactories(); // Init file readers treeModel.insertNodeInto(rootFolder, rootNode, rootNode.getChildCount()); treeModel.insertNodeInto(rootRemote, rootNode, rootNode.getChildCount()); tree.setRootVisible(false); scrollPane = new JScrollPane(tree); JLabel title = new JLabel(I18N.tr("Maps manager")); // Disable mouse event propagation on this label title.addMouseListener(new MouseAdapter(){}); add(title,BorderLayout.NORTH); add(scrollPane,BorderLayout.CENTER); setBorder(BorderFactory.createEtchedBorder()); }
diff --git a/src/com/gitblit/wicket/GitBlitWebApp.java b/src/com/gitblit/wicket/GitBlitWebApp.java index 245b1e05..4e32daac 100644 --- a/src/com/gitblit/wicket/GitBlitWebApp.java +++ b/src/com/gitblit/wicket/GitBlitWebApp.java @@ -1,158 +1,158 @@ /* * Copyright 2011 gitblit.com. * * 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.gitblit.wicket; import org.apache.wicket.Application; import org.apache.wicket.Page; import org.apache.wicket.Request; import org.apache.wicket.Response; import org.apache.wicket.Session; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.protocol.http.WebApplication; import com.gitblit.GitBlit; import com.gitblit.Keys; import com.gitblit.wicket.pages.ActivityPage; import com.gitblit.wicket.pages.BlamePage; import com.gitblit.wicket.pages.BlobDiffPage; import com.gitblit.wicket.pages.BlobPage; import com.gitblit.wicket.pages.BranchesPage; import com.gitblit.wicket.pages.CommitDiffPage; import com.gitblit.wicket.pages.CommitPage; import com.gitblit.wicket.pages.DocsPage; import com.gitblit.wicket.pages.FederationRegistrationPage; import com.gitblit.wicket.pages.ForkPage; import com.gitblit.wicket.pages.ForksPage; import com.gitblit.wicket.pages.GitSearchPage; import com.gitblit.wicket.pages.GravatarProfilePage; import com.gitblit.wicket.pages.HistoryPage; import com.gitblit.wicket.pages.LogPage; import com.gitblit.wicket.pages.LuceneSearchPage; import com.gitblit.wicket.pages.MarkdownPage; import com.gitblit.wicket.pages.MetricsPage; import com.gitblit.wicket.pages.PatchPage; import com.gitblit.wicket.pages.ProjectPage; import com.gitblit.wicket.pages.ProjectsPage; import com.gitblit.wicket.pages.RawPage; import com.gitblit.wicket.pages.RepositoriesPage; import com.gitblit.wicket.pages.ReviewProposalPage; import com.gitblit.wicket.pages.SummaryPage; import com.gitblit.wicket.pages.TagPage; import com.gitblit.wicket.pages.TagsPage; import com.gitblit.wicket.pages.TicketPage; import com.gitblit.wicket.pages.TicketsPage; import com.gitblit.wicket.pages.TreePage; import com.gitblit.wicket.pages.UserPage; import com.gitblit.wicket.pages.UsersPage; public class GitBlitWebApp extends WebApplication { @Override public void init() { super.init(); // Setup page authorization mechanism boolean useAuthentication = GitBlit.getBoolean(Keys.web.authenticateViewPages, false) || GitBlit.getBoolean(Keys.web.authenticateAdminPages, false); if (useAuthentication) { AuthorizationStrategy authStrategy = new AuthorizationStrategy(); getSecuritySettings().setAuthorizationStrategy(authStrategy); getSecuritySettings().setUnauthorizedComponentInstantiationListener(authStrategy); } // Grab Browser info (like timezone, etc) if (GitBlit.getBoolean(Keys.web.useClientTimezone, false)) { getRequestCycleSettings().setGatherExtendedBrowserInfo(true); } // configure the resource cache duration to 90 days for deployment if (!GitBlit.isDebugMode()) { getResourceSettings().setDefaultCacheDuration(90 * 86400); } // setup the standard gitweb-ish urls mount("/summary", SummaryPage.class, "r"); mount("/log", LogPage.class, "r", "h"); mount("/tags", TagsPage.class, "r"); mount("/branches", BranchesPage.class, "r"); mount("/commit", CommitPage.class, "r", "h"); mount("/tag", TagPage.class, "r", "h"); mount("/tree", TreePage.class, "r", "h", "f"); mount("/blob", BlobPage.class, "r", "h", "f"); mount("/raw", RawPage.class, "r", "h", "f"); mount("/blobdiff", BlobDiffPage.class, "r", "h", "f"); mount("/commitdiff", CommitDiffPage.class, "r", "h"); mount("/patch", PatchPage.class, "r", "h", "f"); mount("/history", HistoryPage.class, "r", "h", "f"); mount("/search", GitSearchPage.class); mount("/metrics", MetricsPage.class, "r"); mount("/blame", BlamePage.class, "r", "h", "f"); mount("/users", UsersPage.class); // setup ticket urls mount("/tickets", TicketsPage.class, "r"); - mount("/ticket", TicketPage.class, "r", "h", "f"); + mount("/ticket", TicketPage.class, "r", "f"); // setup the markdown urls mount("/docs", DocsPage.class, "r"); mount("/markdown", MarkdownPage.class, "r", "h", "f"); // federation urls mount("/proposal", ReviewProposalPage.class, "t"); mount("/registration", FederationRegistrationPage.class, "u", "n"); mount("/activity", ActivityPage.class, "r", "h"); mount("/gravatar", GravatarProfilePage.class, "h"); mount("/lucene", LuceneSearchPage.class); mount("/project", ProjectPage.class, "p"); mount("/projects", ProjectsPage.class); mount("/user", UserPage.class, "user"); mount("/forks", ForksPage.class, "r"); mount("/fork", ForkPage.class, "r"); } private void mount(String location, Class<? extends WebPage> clazz, String... parameters) { if (parameters == null) { parameters = new String[] {}; } if (!GitBlit.getBoolean(Keys.web.mountParameters, true)) { parameters = new String[] {}; } mount(new GitblitParamUrlCodingStrategy(location, clazz, parameters)); } @Override public Class<? extends Page> getHomePage() { return RepositoriesPage.class; } @Override public final Session newSession(Request request, Response response) { return new GitBlitWebSession(request); } @Override public final String getConfigurationType() { if (GitBlit.isDebugMode()) { return Application.DEVELOPMENT; } return Application.DEPLOYMENT; } public static GitBlitWebApp get() { return (GitBlitWebApp) WebApplication.get(); } }
true
true
public void init() { super.init(); // Setup page authorization mechanism boolean useAuthentication = GitBlit.getBoolean(Keys.web.authenticateViewPages, false) || GitBlit.getBoolean(Keys.web.authenticateAdminPages, false); if (useAuthentication) { AuthorizationStrategy authStrategy = new AuthorizationStrategy(); getSecuritySettings().setAuthorizationStrategy(authStrategy); getSecuritySettings().setUnauthorizedComponentInstantiationListener(authStrategy); } // Grab Browser info (like timezone, etc) if (GitBlit.getBoolean(Keys.web.useClientTimezone, false)) { getRequestCycleSettings().setGatherExtendedBrowserInfo(true); } // configure the resource cache duration to 90 days for deployment if (!GitBlit.isDebugMode()) { getResourceSettings().setDefaultCacheDuration(90 * 86400); } // setup the standard gitweb-ish urls mount("/summary", SummaryPage.class, "r"); mount("/log", LogPage.class, "r", "h"); mount("/tags", TagsPage.class, "r"); mount("/branches", BranchesPage.class, "r"); mount("/commit", CommitPage.class, "r", "h"); mount("/tag", TagPage.class, "r", "h"); mount("/tree", TreePage.class, "r", "h", "f"); mount("/blob", BlobPage.class, "r", "h", "f"); mount("/raw", RawPage.class, "r", "h", "f"); mount("/blobdiff", BlobDiffPage.class, "r", "h", "f"); mount("/commitdiff", CommitDiffPage.class, "r", "h"); mount("/patch", PatchPage.class, "r", "h", "f"); mount("/history", HistoryPage.class, "r", "h", "f"); mount("/search", GitSearchPage.class); mount("/metrics", MetricsPage.class, "r"); mount("/blame", BlamePage.class, "r", "h", "f"); mount("/users", UsersPage.class); // setup ticket urls mount("/tickets", TicketsPage.class, "r"); mount("/ticket", TicketPage.class, "r", "h", "f"); // setup the markdown urls mount("/docs", DocsPage.class, "r"); mount("/markdown", MarkdownPage.class, "r", "h", "f"); // federation urls mount("/proposal", ReviewProposalPage.class, "t"); mount("/registration", FederationRegistrationPage.class, "u", "n"); mount("/activity", ActivityPage.class, "r", "h"); mount("/gravatar", GravatarProfilePage.class, "h"); mount("/lucene", LuceneSearchPage.class); mount("/project", ProjectPage.class, "p"); mount("/projects", ProjectsPage.class); mount("/user", UserPage.class, "user"); mount("/forks", ForksPage.class, "r"); mount("/fork", ForkPage.class, "r"); }
public void init() { super.init(); // Setup page authorization mechanism boolean useAuthentication = GitBlit.getBoolean(Keys.web.authenticateViewPages, false) || GitBlit.getBoolean(Keys.web.authenticateAdminPages, false); if (useAuthentication) { AuthorizationStrategy authStrategy = new AuthorizationStrategy(); getSecuritySettings().setAuthorizationStrategy(authStrategy); getSecuritySettings().setUnauthorizedComponentInstantiationListener(authStrategy); } // Grab Browser info (like timezone, etc) if (GitBlit.getBoolean(Keys.web.useClientTimezone, false)) { getRequestCycleSettings().setGatherExtendedBrowserInfo(true); } // configure the resource cache duration to 90 days for deployment if (!GitBlit.isDebugMode()) { getResourceSettings().setDefaultCacheDuration(90 * 86400); } // setup the standard gitweb-ish urls mount("/summary", SummaryPage.class, "r"); mount("/log", LogPage.class, "r", "h"); mount("/tags", TagsPage.class, "r"); mount("/branches", BranchesPage.class, "r"); mount("/commit", CommitPage.class, "r", "h"); mount("/tag", TagPage.class, "r", "h"); mount("/tree", TreePage.class, "r", "h", "f"); mount("/blob", BlobPage.class, "r", "h", "f"); mount("/raw", RawPage.class, "r", "h", "f"); mount("/blobdiff", BlobDiffPage.class, "r", "h", "f"); mount("/commitdiff", CommitDiffPage.class, "r", "h"); mount("/patch", PatchPage.class, "r", "h", "f"); mount("/history", HistoryPage.class, "r", "h", "f"); mount("/search", GitSearchPage.class); mount("/metrics", MetricsPage.class, "r"); mount("/blame", BlamePage.class, "r", "h", "f"); mount("/users", UsersPage.class); // setup ticket urls mount("/tickets", TicketsPage.class, "r"); mount("/ticket", TicketPage.class, "r", "f"); // setup the markdown urls mount("/docs", DocsPage.class, "r"); mount("/markdown", MarkdownPage.class, "r", "h", "f"); // federation urls mount("/proposal", ReviewProposalPage.class, "t"); mount("/registration", FederationRegistrationPage.class, "u", "n"); mount("/activity", ActivityPage.class, "r", "h"); mount("/gravatar", GravatarProfilePage.class, "h"); mount("/lucene", LuceneSearchPage.class); mount("/project", ProjectPage.class, "p"); mount("/projects", ProjectsPage.class); mount("/user", UserPage.class, "user"); mount("/forks", ForksPage.class, "r"); mount("/fork", ForkPage.class, "r"); }
diff --git a/gui/src/test/java/com/doublesignal/sepm/jake/gui/JakeGuiTest.java b/gui/src/test/java/com/doublesignal/sepm/jake/gui/JakeGuiTest.java index b65a5567..8130f023 100644 --- a/gui/src/test/java/com/doublesignal/sepm/jake/gui/JakeGuiTest.java +++ b/gui/src/test/java/com/doublesignal/sepm/jake/gui/JakeGuiTest.java @@ -1,38 +1,38 @@ package com.doublesignal.sepm.jake.gui; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class JakeGuiTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ - public AppTest( String testName ) + public JakeGuiTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( JakeGuiTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
true
true
public AppTest( String testName ) { super( testName ); }
public JakeGuiTest( String testName ) { super( testName ); }
diff --git a/src/com/github/ideajavadocs/generator/impl/MethodJavaDocGenerator.java b/src/com/github/ideajavadocs/generator/impl/MethodJavaDocGenerator.java index 156a017..07bc392 100755 --- a/src/com/github/ideajavadocs/generator/impl/MethodJavaDocGenerator.java +++ b/src/com/github/ideajavadocs/generator/impl/MethodJavaDocGenerator.java @@ -1,70 +1,69 @@ package com.github.ideajavadocs.generator.impl; import com.github.ideajavadocs.generator.JavaDocGenerator; import com.intellij.psi.*; import com.intellij.psi.javadoc.PsiDocComment; public class MethodJavaDocGenerator implements JavaDocGenerator<PsiMethod> { @Override public PsiDocComment generate(PsiMethod element, boolean replace) { PsiDocComment oldDocComment = null; if (element.getFirstChild() instanceof PsiDocComment) { oldDocComment = (PsiDocComment) element.getFirstChild(); } if (oldDocComment != null) { // TODO merge or replace javadoc } String name = element.getName(); PsiParameterList parameterList = element.getParameterList(); PsiType returnType = element.getReturnType(); PsiClassType[] throwsList = element.getThrowsList().getReferencedTypes(); boolean isConstructor = element.isConstructor(); StringBuilder result = new StringBuilder(); result .append("/**\n") .append("* The ") .append(name); if (isConstructor) { - result.append(" constructor\n"); + result.append(" constructor."); } else { - result.append(" method\n"); + result.append(" method."); } - result.append(".\n"); result.append("*\n"); if (parameterList.getParametersCount() > 0) { for (PsiParameter parameter : parameterList.getParameters()) { String paramType = parameter.getType().getCanonicalText(); result.append("* @param ") .append(parameter.getName()) .append(" the ") .append(paramType) .append("\n"); } } if (returnType != null && !returnType.isAssignableFrom(PsiType.VOID)) { result.append("* @return ") .append(returnType.getCanonicalText()) .append("\n"); } if (throwsList.length > 0) { for (PsiClassType throwsType : throwsList) { result.append("* @throws") .append(throwsType.getCanonicalText()) .append("\n"); } } result.append("*/\n"); PsiElementFactory psiElementFactory = PsiElementFactory.SERVICE.getInstance(element.getProject()); PsiDocComment docElement = psiElementFactory.createDocCommentFromText(result.toString()); return docElement; } }
false
true
public PsiDocComment generate(PsiMethod element, boolean replace) { PsiDocComment oldDocComment = null; if (element.getFirstChild() instanceof PsiDocComment) { oldDocComment = (PsiDocComment) element.getFirstChild(); } if (oldDocComment != null) { // TODO merge or replace javadoc } String name = element.getName(); PsiParameterList parameterList = element.getParameterList(); PsiType returnType = element.getReturnType(); PsiClassType[] throwsList = element.getThrowsList().getReferencedTypes(); boolean isConstructor = element.isConstructor(); StringBuilder result = new StringBuilder(); result .append("/**\n") .append("* The ") .append(name); if (isConstructor) { result.append(" constructor\n"); } else { result.append(" method\n"); } result.append(".\n"); result.append("*\n"); if (parameterList.getParametersCount() > 0) { for (PsiParameter parameter : parameterList.getParameters()) { String paramType = parameter.getType().getCanonicalText(); result.append("* @param ") .append(parameter.getName()) .append(" the ") .append(paramType) .append("\n"); } } if (returnType != null && !returnType.isAssignableFrom(PsiType.VOID)) { result.append("* @return ") .append(returnType.getCanonicalText()) .append("\n"); } if (throwsList.length > 0) { for (PsiClassType throwsType : throwsList) { result.append("* @throws") .append(throwsType.getCanonicalText()) .append("\n"); } } result.append("*/\n"); PsiElementFactory psiElementFactory = PsiElementFactory.SERVICE.getInstance(element.getProject()); PsiDocComment docElement = psiElementFactory.createDocCommentFromText(result.toString()); return docElement; }
public PsiDocComment generate(PsiMethod element, boolean replace) { PsiDocComment oldDocComment = null; if (element.getFirstChild() instanceof PsiDocComment) { oldDocComment = (PsiDocComment) element.getFirstChild(); } if (oldDocComment != null) { // TODO merge or replace javadoc } String name = element.getName(); PsiParameterList parameterList = element.getParameterList(); PsiType returnType = element.getReturnType(); PsiClassType[] throwsList = element.getThrowsList().getReferencedTypes(); boolean isConstructor = element.isConstructor(); StringBuilder result = new StringBuilder(); result .append("/**\n") .append("* The ") .append(name); if (isConstructor) { result.append(" constructor."); } else { result.append(" method."); } result.append("*\n"); if (parameterList.getParametersCount() > 0) { for (PsiParameter parameter : parameterList.getParameters()) { String paramType = parameter.getType().getCanonicalText(); result.append("* @param ") .append(parameter.getName()) .append(" the ") .append(paramType) .append("\n"); } } if (returnType != null && !returnType.isAssignableFrom(PsiType.VOID)) { result.append("* @return ") .append(returnType.getCanonicalText()) .append("\n"); } if (throwsList.length > 0) { for (PsiClassType throwsType : throwsList) { result.append("* @throws") .append(throwsType.getCanonicalText()) .append("\n"); } } result.append("*/\n"); PsiElementFactory psiElementFactory = PsiElementFactory.SERVICE.getInstance(element.getProject()); PsiDocComment docElement = psiElementFactory.createDocCommentFromText(result.toString()); return docElement; }
diff --git a/technical-debt/src/test/java/org/sonar/plugins/technicaldebt/it/StrutsIT.java b/technical-debt/src/test/java/org/sonar/plugins/technicaldebt/it/StrutsIT.java index dd17ae23e..6f98f3d46 100644 --- a/technical-debt/src/test/java/org/sonar/plugins/technicaldebt/it/StrutsIT.java +++ b/technical-debt/src/test/java/org/sonar/plugins/technicaldebt/it/StrutsIT.java @@ -1,115 +1,115 @@ /* * Sonar, open source software quality management tool. * Copyright (C) 2009 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar 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. * * Sonar 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 Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.technicaldebt.it; import org.junit.BeforeClass; import org.junit.Test; import org.sonar.wsclient.Sonar; import org.sonar.wsclient.services.Measure; import org.sonar.wsclient.services.ResourceQuery; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.core.Is.is; import static org.hamcrest.number.IsCloseTo.closeTo; import static org.junit.Assert.assertThat; public class StrutsIT { private static Sonar sonar; private static final String PROJECT_STRUTS = "org.apache.struts:struts-parent"; private static final String MODULE_CORE = "org.apache.struts:struts-core"; private static final String FILE_ACTION = "org.apache.struts:struts-core:org.apache.struts.action.Action"; private static final String PACKAGE_ACTION = "org.apache.struts:struts-core:org.apache.struts.action"; @BeforeClass public static void buildServer() { sonar = Sonar.create("http://localhost:9000"); } @Test public void strutsIsAnalyzed() { assertThat(sonar.find(new ResourceQuery(PROJECT_STRUTS)).getName(), is("Struts")); assertThat(sonar.find(new ResourceQuery(PROJECT_STRUTS)).getVersion(), is("1.3.9")); assertThat(sonar.find(new ResourceQuery(MODULE_CORE)).getName(), is("Struts Core")); assertThat(sonar.find(new ResourceQuery(PACKAGE_ACTION)).getName(), is("org.apache.struts.action")); } @Test public void projectsMetrics() { assertThat(getProjectMeasure("technical_debt_repart").getData(), anyOf( is("Comments=4.2;Complexity=11.35;Coverage=29.26;Design=3.13;Duplication=37.09;Violations=14.94"), is("Comments=4.2;Complexity=11.36;Coverage=29.28;Design=3.14;Duplication=37.04;Violations=14.95"), // sonar 2.6, td 1.2 is("Comments=4.2;Complexity=11.34;Coverage=29.29;Design=3.14;Duplication=37.04;Violations=14.96") )); // 2 values to cope with the fact that CPD has a different behavior when running in java 5 or 6 - assertThat(getProjectMeasure("technical_debt").getValue(), anyOf(is(276205.3), is(275455.3), is(310717.8), is(310467.8))); + assertThat(getProjectMeasure("technical_debt").getValue(), anyOf(is(276205.3), is(275455.3), is(310717.8), is(310467.8), is(310405.3))); assertThat(getProjectMeasure("technical_debt_ratio").getValue(), anyOf(is(27.9), is(21.7), is(22.5))); assertThat(getProjectMeasure("technical_debt_days").getValue(), anyOf(is(552.4), is(550.9), is(447.5), is(446.2), closeTo(621.0, 1.0))); } @Test public void modulesMetrics() { assertThat(getCoreModuleMeasure("technical_debt_repart").getData(), anyOf( is("Comments=10.15;Complexity=20.72;Coverage=34.71;Design=14.45;Duplication=1.2;Violations=18.73"), is("Comments=10.3;Complexity=21.02;Coverage=35.21;Design=14.66;Duplication=1.22;Violations=17.56"), is("Comments=10.15;Complexity=20.72;Coverage=34.71;Design=14.45;Duplication=1.2;Violations=18.74"))); assertThat(getCoreModuleMeasure("technical_debt").getValue(), anyOf(is(62258.9), is(61377.6), is(62265.1))); assertThat(getCoreModuleMeasure("technical_debt_ratio").getValue(), anyOf(is(17.3), is(17.1), /* sonar 2.6, td 1.2 */is(17.4))); assertThat(getCoreModuleMeasure("technical_debt_days").getValue(), anyOf(is(124.5), closeTo(123.0, 0.5))); } @Test public void packagesMetrics() { assertThat(getPackageMeasure("technical_debt_repart").getData(), anyOf( is("Comments=0.14;Complexity=26.28;Coverage=50.46;Duplication=2.88;Violations=20.23"), is("Comments=0.15;Complexity=28.03;Coverage=53.83;Duplication=3.07;Violations=14.9"))); assertThat(getPackageMeasure("technical_debt").getValue(), anyOf(is(8680.3), is(8136.6))); assertThat(getPackageMeasure("technical_debt_ratio").getValue(), anyOf(is(10.1), is(9.5))); assertThat(getPackageMeasure("technical_debt_days").getValue(), anyOf(is(17.4), is(16.3))); } @Test public void filesMetrics() { assertThat(getFileMeasure("technical_debt").getValue(), is(662.5)); assertThat(getFileMeasure("technical_debt_ratio").getValue(), is(26.5)); assertThat(getFileMeasure("technical_debt_days").getValue(), is(1.3)); assertThat(getFileMeasure("technical_debt_repart").getData(), is("Coverage=75.47;Violations=24.52")); } private Measure getFileMeasure(String metricKey) { return sonar.find(ResourceQuery.createForMetrics(FILE_ACTION, metricKey)).getMeasure(metricKey); } private Measure getPackageMeasure(String metricKey) { return sonar.find(ResourceQuery.createForMetrics(PACKAGE_ACTION, metricKey)).getMeasure(metricKey); } private Measure getCoreModuleMeasure(String metricKey) { return sonar.find(ResourceQuery.createForMetrics(MODULE_CORE, metricKey)).getMeasure(metricKey); } private Measure getProjectMeasure(String metricKey) { return sonar.find(ResourceQuery.createForMetrics(PROJECT_STRUTS, metricKey)).getMeasure(metricKey); } }
true
true
public void projectsMetrics() { assertThat(getProjectMeasure("technical_debt_repart").getData(), anyOf( is("Comments=4.2;Complexity=11.35;Coverage=29.26;Design=3.13;Duplication=37.09;Violations=14.94"), is("Comments=4.2;Complexity=11.36;Coverage=29.28;Design=3.14;Duplication=37.04;Violations=14.95"), // sonar 2.6, td 1.2 is("Comments=4.2;Complexity=11.34;Coverage=29.29;Design=3.14;Duplication=37.04;Violations=14.96") )); // 2 values to cope with the fact that CPD has a different behavior when running in java 5 or 6 assertThat(getProjectMeasure("technical_debt").getValue(), anyOf(is(276205.3), is(275455.3), is(310717.8), is(310467.8))); assertThat(getProjectMeasure("technical_debt_ratio").getValue(), anyOf(is(27.9), is(21.7), is(22.5))); assertThat(getProjectMeasure("technical_debt_days").getValue(), anyOf(is(552.4), is(550.9), is(447.5), is(446.2), closeTo(621.0, 1.0))); }
public void projectsMetrics() { assertThat(getProjectMeasure("technical_debt_repart").getData(), anyOf( is("Comments=4.2;Complexity=11.35;Coverage=29.26;Design=3.13;Duplication=37.09;Violations=14.94"), is("Comments=4.2;Complexity=11.36;Coverage=29.28;Design=3.14;Duplication=37.04;Violations=14.95"), // sonar 2.6, td 1.2 is("Comments=4.2;Complexity=11.34;Coverage=29.29;Design=3.14;Duplication=37.04;Violations=14.96") )); // 2 values to cope with the fact that CPD has a different behavior when running in java 5 or 6 assertThat(getProjectMeasure("technical_debt").getValue(), anyOf(is(276205.3), is(275455.3), is(310717.8), is(310467.8), is(310405.3))); assertThat(getProjectMeasure("technical_debt_ratio").getValue(), anyOf(is(27.9), is(21.7), is(22.5))); assertThat(getProjectMeasure("technical_debt_days").getValue(), anyOf(is(552.4), is(550.9), is(447.5), is(446.2), closeTo(621.0, 1.0))); }
diff --git a/modules/tools/artimport/src/classes/org/jdesktop/wonderland/modules/artimport/client/jme/ModelImporterFrame.java b/modules/tools/artimport/src/classes/org/jdesktop/wonderland/modules/artimport/client/jme/ModelImporterFrame.java index f9566dfb0..efc0cdddd 100644 --- a/modules/tools/artimport/src/classes/org/jdesktop/wonderland/modules/artimport/client/jme/ModelImporterFrame.java +++ b/modules/tools/artimport/src/classes/org/jdesktop/wonderland/modules/artimport/client/jme/ModelImporterFrame.java @@ -1,1199 +1,1199 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.modules.artimport.client.jme; import org.jdesktop.mtgame.ProcessorArmingCollection; import org.jdesktop.wonderland.client.cell.Cell; import org.jdesktop.wonderland.client.jme.artimport.ImportSettings; import org.jdesktop.wonderland.client.jme.artimport.LoaderManager; import com.jme.bounding.BoundingBox; import com.jme.bounding.BoundingSphere; import com.jme.bounding.BoundingVolume; import com.jme.image.Texture; import com.jme.math.Matrix3f; import com.jme.math.Quaternion; import com.jme.math.Vector3f; import com.jme.scene.Geometry; import com.jme.scene.Node; import com.jme.scene.Spatial; import com.jme.scene.state.TextureState; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashSet; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import javax.swing.table.DefaultTableModel; import org.jdesktop.mtgame.Entity; import org.jdesktop.mtgame.NewFrameCondition; import org.jdesktop.mtgame.ProcessorComponent; import org.jdesktop.wonderland.client.cell.TransformChangeListener; import org.jdesktop.wonderland.client.cell.view.ViewCell; import org.jdesktop.wonderland.client.jme.ViewManager; import org.jdesktop.wonderland.client.jme.artimport.ImportedModel; import org.jdesktop.wonderland.client.jme.utils.traverser.ProcessNodeInterface; import org.jdesktop.wonderland.client.jme.utils.traverser.TreeScan; import org.jdesktop.wonderland.common.cell.CellTransform; /** * * @author paulby * @author Ronny Standtke <[email protected]> */ public class ModelImporterFrame extends javax.swing.JFrame { private static final Logger LOGGER = Logger.getLogger(ModelImporterFrame.class.getName()); private static final ResourceBundle BUNDLE = ResourceBundle.getBundle( "org/jdesktop/wonderland/modules/artimport/client/jme/resources/Bundle"); private File lastModelDir; // private GeometryStatsDialog geometryStatsDialog = null; private TransformChangeListener userMotionListener = null; private ChangeListener translationChangeListener = null; private ChangeListener rotationChangeListener = null; private ChangeListener scaleChangeListener = null; private Vector3f currentTranslation = new Vector3f(); private Vector3f currentRotationValues = new Vector3f(); private Vector3f currentScale = new Vector3f(); private Matrix3f currentRotation = new Matrix3f(); private ImportSessionFrame sessionFrame; private ImportSettings importSettings = null; private ImportedModel importedModel = null; private TransformProcessorComponent transformProcessor; /** Creates new form ModelImporterFrame */ public ModelImporterFrame(ImportSessionFrame session, File lastModelDir) { this.lastModelDir = lastModelDir; sessionFrame = session; initComponents(); textureTable.setModel(new DefaultTableModel() { String[] names = new String[]{ BUNDLE.getString("Original_Filename"), BUNDLE.getString("Wonderland_Path"), BUNDLE.getString("Wonderland_Filename") }; Class[] types = new Class[]{ String.class, String.class, String.class }; boolean[] canEdit = new boolean[]{ false, false, false }; @Override public String getColumnName(int column) { return names[column]; } @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); Float value = new Float(0); Float min = new Float(Float.NEGATIVE_INFINITY); Float max = new Float(Float.POSITIVE_INFINITY); Float step = new Float(0.1); SpinnerNumberModel translationX = new SpinnerNumberModel(value, min, max, step); SpinnerNumberModel translationY = new SpinnerNumberModel(value, min, max, step); SpinnerNumberModel translationZ = new SpinnerNumberModel(value, min, max, step); translationXTF.setModel(translationX); translationYTF.setModel(translationY); translationZTF.setModel(translationZ); value = new Float(1); SpinnerNumberModel scaleX = new SpinnerNumberModel(value, min, max, step); scaleTF.setModel(scaleX); value = new Float(0); min = new Float(-360); max = new Float(360); step = new Float(1); SpinnerNumberModel rotationX = new SpinnerNumberModel(value, min, max, step); SpinnerNumberModel rotationY = new SpinnerNumberModel(value, min, max, step); SpinnerNumberModel rotationZ = new SpinnerNumberModel(value, min, max, step); rotationXTF.setModel(rotationX); rotationYTF.setModel(rotationY); rotationZTF.setModel(rotationZ); currentRotation.loadIdentity(); // TODO add Float editors to the spinners userMotionListener = new TransformChangeListener() { private Vector3f look = new Vector3f(); private Vector3f pos = new Vector3f(); public void transformChanged(Cell cell, ChangeSource source) { CellTransform t = cell.getWorldTransform(); t.getLookAt(pos, look); look.mult(3); pos.addLocal(look); currentTranslation.set(pos); ((SpinnerNumberModel) translationXTF.getModel()).setValue( new Float(pos.x)); ((SpinnerNumberModel) translationYTF.getModel()).setValue( new Float(pos.y)); ((SpinnerNumberModel) translationZTF.getModel()).setValue( new Float(pos.z)); if (transformProcessor != null) { transformProcessor.setTransform( currentRotation, currentTranslation); } } }; translationChangeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { float x = (Float) ((SpinnerNumberModel) translationXTF.getModel()).getValue(); float y = (Float) ((SpinnerNumberModel) translationYTF.getModel()).getValue(); float z = (Float) ((SpinnerNumberModel) translationZTF.getModel()).getValue(); if (x != currentTranslation.x || y != currentTranslation.y || z != currentTranslation.z) { currentTranslation.set(x, y, z); importedModel.setTranslation(currentTranslation); if (transformProcessor != null) { transformProcessor.setTransform( currentRotation, currentTranslation); } } } }; rotationChangeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { float x = (Float) ((SpinnerNumberModel) rotationXTF.getModel()).getValue(); float y = (Float) ((SpinnerNumberModel) rotationYTF.getModel()).getValue(); float z = (Float) ((SpinnerNumberModel) rotationZTF.getModel()).getValue(); if (x != currentRotationValues.x || y != currentRotationValues.y || z != currentRotationValues.z) { currentRotationValues.set(x, y, z); importedModel.setOrientation(currentRotationValues); calcCurrentRotationMatrix(); if (transformProcessor != null) { transformProcessor.setTransform( currentRotation, currentTranslation); } } } }; ((SpinnerNumberModel) rotationXTF.getModel()).addChangeListener( rotationChangeListener); ((SpinnerNumberModel) rotationYTF.getModel()).addChangeListener( rotationChangeListener); ((SpinnerNumberModel) rotationZTF.getModel()).addChangeListener( rotationChangeListener); scaleChangeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { float x = (Float) ((SpinnerNumberModel) scaleTF.getModel()).getValue(); // float y = (Float)((SpinnerNumberModel)translationYTF.getModel()).getValue(); // float z = (Float)((SpinnerNumberModel)translationZTF.getModel()).getValue(); if (x != currentScale.x) { currentScale.set(x, x, x); importedModel.setScale(currentScale); if (transformProcessor != null) { transformProcessor.setTransform( currentRotation, currentTranslation, currentScale); } } } }; ((SpinnerNumberModel) scaleTF.getModel()).addChangeListener( scaleChangeListener); // Disable move with avatar avatarMoveCB.setSelected(false); enableSpinners(true); } /** * Set the spinners to the rotation, translation and scale local coords of * this node * @param node */ private void setSpinners(Node modelBG, Node rootBG) { Vector3f translation = rootBG.getLocalTranslation(); Quaternion quat = modelBG.getLocalRotation(); float[] angles = quat.toAngles(new float[3]); Vector3f scale = modelBG.getLocalScale(); translationXTF.setValue(translation.x); translationYTF.setValue(translation.y); translationZTF.setValue(translation.z); rotationXTF.setValue((float) Math.toDegrees(angles[0])); rotationYTF.setValue((float) Math.toDegrees(angles[1])); rotationZTF.setValue((float) Math.toDegrees(angles[2])); scaleTF.setValue(scale.x); importedModel.setTranslation(translation); importedModel.setOrientation(new Vector3f( (float) Math.toDegrees(angles[0]), (float) Math.toDegrees(angles[1]), (float) Math.toDegrees(angles[2]))); importedModel.setScale(new Vector3f(scale.x, scale.x, scale.x)); } private void calcCurrentRotationMatrix() { currentRotation = ImportSessionFrame.calcRotationMatrix( (float) Math.toRadians(currentRotationValues.x), (float) Math.toRadians(currentRotationValues.y), (float) Math.toRadians(currentRotationValues.z)); } void chooseFile() { texturePrefixTF.setText(""); modelNameTF.setText(""); modelX3dTF.setText(""); importedModel = null; SwingUtilities.invokeLater(new Runnable() { public void run() { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( LoaderManager.getLoaderManager().getLoaderExtensions()); chooser.setFileFilter(filter); if (lastModelDir != null) { chooser.setCurrentDirectory(lastModelDir); } int returnVal = chooser.showOpenDialog(ModelImporterFrame.this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { importModel(chooser.getSelectedFile(), false); } catch (FileNotFoundException ex) { LOGGER.log(Level.SEVERE, null, ex); } catch (IOException ioe) { LOGGER.log(Level.SEVERE, null, ioe); } setVisible(true); lastModelDir = chooser.getSelectedFile().getParentFile(); } } }); } /** * Edit a model that has already been imported * @param model */ void editModel(ImportedModel model) { // texturePrefixTF.setText(model.getTexturePrefix()); modelX3dTF.setText(model.getOriginalURL().toExternalForm()); modelNameTF.setText(model.getWonderlandName()); currentTranslation.set(model.getTranslation()); currentRotationValues.set(model.getOrientation()); calcCurrentRotationMatrix(); ((SpinnerNumberModel) rotationXTF.getModel()).setValue( model.getOrientation().x); ((SpinnerNumberModel) rotationYTF.getModel()).setValue( model.getOrientation().y); ((SpinnerNumberModel) rotationZTF.getModel()).setValue( model.getOrientation().z); ((SpinnerNumberModel) translationXTF.getModel()).setValue( model.getTranslation().x); ((SpinnerNumberModel) translationYTF.getModel()).setValue( model.getTranslation().y); ((SpinnerNumberModel) translationZTF.getModel()).setValue( model.getTranslation().x); ((SpinnerNumberModel) scaleTF.getModel()).setValue(model.getScale().x); avatarMoveCB.setSelected(false); populateTextureList(model.getRootBG()); processBounds(model.getModelBG()); } /** * Import a model from a file * * @param origFile */ void importModel(final File origFile, boolean attachToAvatar) throws IOException { avatarMoveCB.setSelected(attachToAvatar); modelX3dTF.setText(origFile.getAbsolutePath()); importSettings = new ImportSettings(origFile.toURI().toURL()); sessionFrame.asyncLoadModel( importSettings, new ImportSessionFrame.LoadCompleteListener() { public void loadComplete(ImportedModel importedModel) { ModelImporterFrame.this.importedModel = importedModel; Entity entity = importedModel.getEntity(); transformProcessor = (TransformProcessorComponent) entity.getComponent( TransformProcessorComponent.class); setSpinners( importedModel.getModelBG(), importedModel.getRootBG()); entity.addComponent(LoadCompleteProcessor.class, new LoadCompleteProcessor(importedModel)); String dir = origFile.getAbsolutePath(); dir = dir.substring(0, dir.lastIndexOf(File.separatorChar)); dir = dir.substring(dir.lastIndexOf(File.separatorChar) + 1); texturePrefixTF.setText(dir); String filename = origFile.getAbsolutePath(); filename = filename.substring( filename.lastIndexOf(File.separatorChar) + 1); filename = filename.substring(0, filename.lastIndexOf('.')); modelNameTF.setText(filename); if (avatarMoveCB.isSelected()) { ViewManager viewManager = ViewManager.getViewManager(); ViewCell viewCell = viewManager.getPrimaryViewCell(); viewCell.addTransformChangeListener(userMotionListener); } } }); } private void populateTextureList(Node bg) { final DefaultTableModel model = (DefaultTableModel) textureTable.getModel(); while (model.getRowCount() != 0) { model.removeRow(0); } final String texturePath = texturePrefixTF.getText(); final HashSet<String> textureSet = new HashSet(); TreeScan.findNode(bg, Geometry.class, new ProcessNodeInterface() { public boolean processNode(Spatial node) { TextureState ts = (TextureState) node.getRenderState( TextureState.RS_TEXTURE); if (ts == null) { return true; } Texture t = ts.getTexture(); if (t != null) { String tFile = t.getImageLocation(); if (textureSet.add(tFile)) { model.addRow(new Object[]{new String(tFile), "not implemented", "not implemented"}); } } return true; } }, false, true); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); basicPanel = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); translationXTF = new javax.swing.JSpinner(); translationYTF = new javax.swing.JSpinner(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); translationZTF = new javax.swing.JSpinner(); avatarMoveCB = new javax.swing.JCheckBox(); jPanel5 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); rotationXTF = new javax.swing.JSpinner(); rotationYTF = new javax.swing.JSpinner(); jLabel13 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); rotationZTF = new javax.swing.JSpinner(); modelNameTF = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); modelX3dTF = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); scaleTF = new javax.swing.JSpinner(); advancedPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); textureTable = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); texturePrefixTF = new javax.swing.JTextField(); jLabel25 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); boundsCenterYTF = new javax.swing.JTextField(); boundsCenterXTF = new javax.swing.JTextField(); jLabel28 = new javax.swing.JLabel(); jLabel29 = new javax.swing.JLabel(); boundsCenterZTF = new javax.swing.JTextField(); boundsSizeXTF = new javax.swing.JTextField(); jLabel26 = new javax.swing.JLabel(); geometryStatsB = new javax.swing.JButton(); jLabel30 = new javax.swing.JLabel(); boundsSizeYTF = new javax.swing.JTextField(); boundsSizeZTF = new javax.swing.JTextField(); jLabel31 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); cancelB = new javax.swing.JButton(); okB = new javax.swing.JButton(); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/modules/artimport/client/jme/resources/Bundle"); // NOI18N setTitle(bundle.getString("ModelImporterFrame.title")); // NOI18N jTabbedPane1.setFont(jTabbedPane1.getFont()); jTabbedPane1.setPreferredSize(new java.awt.Dimension(102, 167)); basicPanel.addInputMethodListener(new java.awt.event.InputMethodListener() { public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) { basicPanelInputMethodTextChanged(evt); } public void caretPositionChanged(java.awt.event.InputMethodEvent evt) { } }); jLabel7.setText(bundle.getString("ModelImporterFrame.jLabel7.text")); // NOI18N jLabel6.setText(bundle.getString("ModelImporterFrame.jLabel6.text")); // NOI18N translationXTF.setEnabled(false); translationYTF.setEnabled(false); jLabel8.setText(bundle.getString("ModelImporterFrame.jLabel8.text")); // NOI18N jLabel9.setText(bundle.getString("ModelImporterFrame.jLabel9.text")); // NOI18N translationZTF.setEnabled(false); avatarMoveCB.setFont(avatarMoveCB.getFont()); avatarMoveCB.setSelected(true); avatarMoveCB.setText(bundle.getString("ModelImporterFrame.avatarMoveCB.text")); // NOI18N avatarMoveCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { avatarMoveCBActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel7) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel6) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel8) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel9)) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(translationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.LEADING, translationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(translationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) - .addContainerGap(6, Short.MAX_VALUE)) + .addContainerGap(10, Short.MAX_VALUE)) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(30, Short.MAX_VALUE) .add(avatarMoveCB)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .add(jLabel7) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel6) .add(translationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(translationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel8)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(translationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel9)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(avatarMoveCB)) ); jLabel10.setText(bundle.getString("ModelImporterFrame.jLabel10.text")); // NOI18N jLabel11.setText(bundle.getString("ModelImporterFrame.jLabel11.text")); // NOI18N jLabel13.setText(bundle.getString("ModelImporterFrame.jLabel13.text")); // NOI18N jLabel12.setText(bundle.getString("ModelImporterFrame.jLabel12.text")); // NOI18N org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel5Layout.createSequentialGroup() .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel10) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel11) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel13) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel12)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(rotationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(rotationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(rotationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5Layout.linkSize(new java.awt.Component[] {jLabel11, jLabel12, jLabel13}, org.jdesktop.layout.GroupLayout.HORIZONTAL); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel5Layout.createSequentialGroup() .add(jLabel10) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel11) .add(rotationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(rotationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel13)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(rotationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel12)) .addContainerGap(29, Short.MAX_VALUE)) ); modelNameTF.setText(bundle.getString("ModelImporterFrame.modelNameTF.text")); // NOI18N modelNameTF.setToolTipText(bundle.getString("ModelImporterFrame.modelNameTF.toolTipText")); // NOI18N jLabel5.setText(bundle.getString("ModelImporterFrame.jLabel5.text")); // NOI18N modelX3dTF.setEditable(false); modelX3dTF.setText(bundle.getString("ModelImporterFrame.modelX3dTF.text")); // NOI18N modelX3dTF.setToolTipText(bundle.getString("ModelImporterFrame.modelX3dTF.toolTipText")); // NOI18N jLabel1.setText(bundle.getString("ModelImporterFrame.jLabel1.text")); // NOI18N jLabel3.setText(bundle.getString("ModelImporterFrame.jLabel3.text")); // NOI18N org.jdesktop.layout.GroupLayout basicPanelLayout = new org.jdesktop.layout.GroupLayout(basicPanel); basicPanel.setLayout(basicPanelLayout); basicPanelLayout.setHorizontalGroup( basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(basicPanelLayout.createSequentialGroup() .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(basicPanelLayout.createSequentialGroup() .addContainerGap() .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel3) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel5) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel1)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(scaleTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) - .add(modelX3dTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE) - .add(modelNameTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE))) + .add(modelX3dTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE) + .add(modelNameTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE))) .add(basicPanelLayout.createSequentialGroup() .add(31, 31, 31) .add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); basicPanelLayout.setVerticalGroup( basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(basicPanelLayout.createSequentialGroup() .addContainerGap() .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel1) .add(modelX3dTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(5, 5, 5) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(modelNameTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel5)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel3) .add(scaleTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(64, 64, 64)) ); jTabbedPane1.addTab(bundle.getString("ModelImporterFrame.basicPanel.TabConstraints.tabTitle"), basicPanel); // NOI18N jScrollPane1.setViewportView(textureTable); jLabel2.setText(bundle.getString("ModelImporterFrame.jLabel2.text")); // NOI18N texturePrefixTF.setEditable(false); texturePrefixTF.setText(bundle.getString("ModelImporterFrame.texturePrefixTF.text")); // NOI18N texturePrefixTF.setToolTipText(bundle.getString("ModelImporterFrame.texturePrefixTF.toolTipText")); // NOI18N jLabel25.setText(bundle.getString("ModelImporterFrame.jLabel25.text")); // NOI18N jLabel27.setText(bundle.getString("ModelImporterFrame.jLabel27.text")); // NOI18N boundsCenterYTF.setColumns(12); boundsCenterYTF.setEditable(false); boundsCenterYTF.setFont(boundsCenterYTF.getFont()); boundsCenterYTF.setText(bundle.getString("ModelImporterFrame.boundsCenterYTF.text")); // NOI18N boundsCenterXTF.setColumns(12); boundsCenterXTF.setEditable(false); boundsCenterXTF.setFont(boundsCenterXTF.getFont()); boundsCenterXTF.setText(bundle.getString("ModelImporterFrame.boundsCenterXTF.text")); // NOI18N jLabel28.setText(bundle.getString("ModelImporterFrame.jLabel28.text")); // NOI18N jLabel29.setText(bundle.getString("ModelImporterFrame.jLabel29.text")); // NOI18N boundsCenterZTF.setColumns(12); boundsCenterZTF.setEditable(false); boundsCenterZTF.setFont(boundsCenterZTF.getFont()); boundsCenterZTF.setText(bundle.getString("ModelImporterFrame.boundsCenterZTF.text")); // NOI18N boundsSizeXTF.setColumns(12); boundsSizeXTF.setEditable(false); boundsSizeXTF.setFont(boundsSizeXTF.getFont()); boundsSizeXTF.setText(bundle.getString("ModelImporterFrame.boundsSizeXTF.text")); // NOI18N jLabel26.setText(bundle.getString("ModelImporterFrame.jLabel26.text")); // NOI18N geometryStatsB.setText(bundle.getString("ModelImporterFrame.geometryStatsB.text")); // NOI18N geometryStatsB.setToolTipText(bundle.getString("ModelImporterFrame.geometryStatsB.toolTipText")); // NOI18N geometryStatsB.setEnabled(false); geometryStatsB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { geometryStatsBActionPerformed(evt); } }); jLabel30.setText(bundle.getString("ModelImporterFrame.jLabel30.text")); // NOI18N boundsSizeYTF.setColumns(12); boundsSizeYTF.setEditable(false); boundsSizeYTF.setFont(boundsSizeYTF.getFont()); boundsSizeYTF.setText(bundle.getString("ModelImporterFrame.boundsSizeYTF.text")); // NOI18N boundsSizeZTF.setColumns(12); boundsSizeZTF.setEditable(false); boundsSizeZTF.setFont(boundsSizeZTF.getFont()); boundsSizeZTF.setText(bundle.getString("ModelImporterFrame.boundsSizeZTF.text")); // NOI18N jLabel31.setText(bundle.getString("ModelImporterFrame.jLabel31.text")); // NOI18N jLabel32.setText(bundle.getString("ModelImporterFrame.jLabel32.text")); // NOI18N jLabel33.setText(bundle.getString("ModelImporterFrame.jLabel33.text")); // NOI18N org.jdesktop.layout.GroupLayout advancedPanelLayout = new org.jdesktop.layout.GroupLayout(advancedPanel); advancedPanel.setLayout(advancedPanelLayout); advancedPanelLayout.setHorizontalGroup( advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .addContainerGap() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE) .addContainerGap()) .add(advancedPanelLayout.createSequentialGroup() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .add(jLabel2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(texturePrefixTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)) + .add(texturePrefixTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)) .add(jLabel30)) .add(6, 6, 6)) .add(advancedPanelLayout.createSequentialGroup() .add(6, 6, 6) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(org.jdesktop.layout.GroupLayout.LEADING, geometryStatsB) .add(org.jdesktop.layout.GroupLayout.LEADING, advancedPanelLayout.createSequentialGroup() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel25) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel27) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel28) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel29)) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(boundsCenterYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsCenterXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsCenterZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(85, 85, 85) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(jLabel31) .add(jLabel33) .add(jLabel32)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(boundsSizeXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsSizeYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsSizeZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(advancedPanelLayout.createSequentialGroup() .add(120, 120, 120) .add(jLabel26))))) .add(3, 3, 3)))) ); advancedPanelLayout.linkSize(new java.awt.Component[] {boundsSizeXTF, boundsSizeYTF, boundsSizeZTF}, org.jdesktop.layout.GroupLayout.HORIZONTAL); advancedPanelLayout.linkSize(new java.awt.Component[] {boundsCenterXTF, boundsCenterYTF, boundsCenterZTF}, org.jdesktop.layout.GroupLayout.HORIZONTAL); advancedPanelLayout.setVerticalGroup( advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .addContainerGap() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel2) .add(texturePrefixTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jLabel30) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 97, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel25, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel26)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel27) .add(boundsCenterYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel31) .add(boundsSizeXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel28) .add(boundsCenterXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel32) .add(boundsSizeYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel29) .add(boundsCenterZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel33) .add(boundsSizeZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(geometryStatsB) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jTabbedPane1.addTab(bundle.getString("ModelImporterFrame.advancedPanel.TabConstraints.tabTitle"), advancedPanel); // NOI18N cancelB.setText(bundle.getString("ModelImporterFrame.cancelB.text")); // NOI18N cancelB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelBActionPerformed(evt); } }); okB.setText(bundle.getString("ModelImporterFrame.okB.text")); // NOI18N okB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okBActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap(261, Short.MAX_VALUE) .add(cancelB) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(okB) .addContainerGap()) .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 370, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(cancelB) .add(okB)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void okBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okBActionPerformed if (avatarMoveCB.isSelected()) { ViewManager viewManager = ViewManager.getViewManager(); ViewCell viewCell = viewManager.getPrimaryViewCell(); viewCell.removeTransformChangeListener(userMotionListener); } setVisible(false); Vector3f translation = new Vector3f((Float) translationXTF.getValue(), (Float) translationYTF.getValue(), (Float) translationZTF.getValue()); Vector3f orientation = new Vector3f((Float) rotationXTF.getValue(), (Float) rotationYTF.getValue(), (Float) rotationZTF.getValue()); importedModel.setWonderlandName(modelNameTF.getText()); // importedModel.setTexturePrefix(texturePrefixTF.getText()); sessionFrame.loadCompleted(importedModel); }//GEN-LAST:event_okBActionPerformed private void cancelBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelBActionPerformed this.setVisible(false); if (userMotionListener != null) { ViewManager viewManager = ViewManager.getViewManager(); ViewCell viewCell = viewManager.getPrimaryViewCell(); viewCell.removeTransformChangeListener(userMotionListener); } sessionFrame.loadCancelled(importedModel); }//GEN-LAST:event_cancelBActionPerformed private void geometryStatsBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_geometryStatsBActionPerformed // if (geometryStatsDialog==null) // geometryStatsDialog = new GeometryStatsDialog(this); // geometryStatsDialog.calcGeometryStats(modelBG); // geometryStatsDialog.setVisible(true); System.err.println("geometryStats not implemented"); }//GEN-LAST:event_geometryStatsBActionPerformed private void avatarMoveCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_avatarMoveCBActionPerformed if (userMotionListener == null) { return; } ViewManager viewManager = ViewManager.getViewManager(); ViewCell viewCell = viewManager.getPrimaryViewCell(); if (avatarMoveCB.isSelected()) { enableSpinners(false); viewCell.addTransformChangeListener(userMotionListener); } else { enableSpinners(true); viewCell.removeTransformChangeListener(userMotionListener); } }//GEN-LAST:event_avatarMoveCBActionPerformed private void basicPanelInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_basicPanelInputMethodTextChanged // TODO add your handling code here: System.err.println(evt); }//GEN-LAST:event_basicPanelInputMethodTextChanged private void enableSpinners(boolean enabled) { translationXTF.setEnabled(enabled); translationYTF.setEnabled(enabled); translationZTF.setEnabled(enabled); rotationXTF.setEnabled(enabled); rotationYTF.setEnabled(enabled); rotationZTF.setEnabled(enabled); if (enabled) { ((SpinnerNumberModel) translationXTF.getModel()).addChangeListener( translationChangeListener); ((SpinnerNumberModel) translationYTF.getModel()).addChangeListener( translationChangeListener); ((SpinnerNumberModel) translationZTF.getModel()).addChangeListener( translationChangeListener); ((SpinnerNumberModel) rotationXTF.getModel()).addChangeListener( rotationChangeListener); ((SpinnerNumberModel) rotationYTF.getModel()).addChangeListener( rotationChangeListener); ((SpinnerNumberModel) rotationZTF.getModel()).addChangeListener( rotationChangeListener); } else { ((SpinnerNumberModel) translationXTF.getModel()).removeChangeListener( translationChangeListener); ((SpinnerNumberModel) translationYTF.getModel()).removeChangeListener( translationChangeListener); ((SpinnerNumberModel) translationZTF.getModel()).removeChangeListener( translationChangeListener); ((SpinnerNumberModel) rotationXTF.getModel()).removeChangeListener( rotationChangeListener); ((SpinnerNumberModel) rotationYTF.getModel()).removeChangeListener( rotationChangeListener); ((SpinnerNumberModel) rotationZTF.getModel()).removeChangeListener( rotationChangeListener); } } /** * Process the bounds of the graph, updating the UI. */ private void processBounds(Node bg) { // System.err.println("Model Node "+bg); if (bg == null) { return; } BoundingVolume bounds = bg.getWorldBound(); if (bounds == null) { bounds = calcBounds(bg); } // Remove the rotation from the bounds because it will be reapplied by // the cell // Quaternion rot = bg.getWorldRotation(); // rot.inverseLocal(); // bounds = bounds.transform(rot, new Vector3f(), new Vector3f(1,1,1), bounds); // // System.err.println("ROTATED "+bounds); // System.err.println(rot.toAngleAxis(null)); if (bounds instanceof BoundingSphere) { BoundingSphere sphere = (BoundingSphere) bounds; Vector3f center = new Vector3f(); sphere.getCenter(center); boundsCenterXTF.setText(Double.toString(center.x)); boundsCenterYTF.setText(Double.toString(center.y)); boundsCenterZTF.setText(Double.toString(center.z)); boundsSizeXTF.setText(Double.toString(sphere.getRadius())); boundsSizeYTF.setText("N/A Sphere"); boundsSizeZTF.setText("N/A Sphere"); } else if (bounds instanceof BoundingBox) { BoundingBox box = (BoundingBox) bounds; Vector3f center = new Vector3f(); box.getCenter(); boundsCenterXTF.setText(Double.toString(center.x)); boundsCenterYTF.setText(Double.toString(center.y)); boundsCenterZTF.setText(Double.toString(center.z)); boundsSizeXTF.setText(Float.toString(box.xExtent)); boundsSizeYTF.setText(Float.toString(box.yExtent)); boundsSizeZTF.setText(Float.toString(box.zExtent)); } } /** * Traverse the graph, combining all the world bounds into bv * @param n * @param bv */ BoundingVolume calcBounds(Spatial n) { BoundingVolume bounds = null; if (n instanceof Geometry) { bounds = new BoundingBox(); bounds.computeFromPoints(((Geometry) n).getVertexBuffer()); bounds.transform( n.getLocalRotation(), n.getLocalTranslation(), n.getLocalScale()); } if (n instanceof Node && ((Node) n).getQuantity() > 0) { for (Spatial child : ((Node) n).getChildren()) { BoundingVolume childB = calcBounds(child); if (bounds == null) { bounds = childB; } else { bounds.mergeLocal(childB); } } } if (bounds != null) { bounds.transform( n.getLocalRotation(), n.getLocalTranslation(), n.getLocalScale(), bounds); } // Vector3f axis = new Vector3f(); // float angle = n.getLocalRotation().toAngleAxis(axis); // System.err.println("Applying transform "+n.getLocalTranslation()+" "+angle+" "+axis); // System.err.println("BOunds "+bounds); return bounds; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel advancedPanel; private javax.swing.JCheckBox avatarMoveCB; private javax.swing.JPanel basicPanel; private javax.swing.JTextField boundsCenterXTF; private javax.swing.JTextField boundsCenterYTF; private javax.swing.JTextField boundsCenterZTF; private javax.swing.JTextField boundsSizeXTF; private javax.swing.JTextField boundsSizeYTF; private javax.swing.JTextField boundsSizeZTF; private javax.swing.JButton cancelB; private javax.swing.JButton geometryStatsB; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel30; private javax.swing.JLabel jLabel31; private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel33; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTextField modelNameTF; private javax.swing.JTextField modelX3dTF; private javax.swing.JButton okB; private javax.swing.JSpinner rotationXTF; private javax.swing.JSpinner rotationYTF; private javax.swing.JSpinner rotationZTF; private javax.swing.JSpinner scaleTF; private javax.swing.JTextField texturePrefixTF; private javax.swing.JTable textureTable; private javax.swing.JSpinner translationXTF; private javax.swing.JSpinner translationYTF; private javax.swing.JSpinner translationZTF; // End of variables declaration//GEN-END:variables /** * Case independent filename extension filter */ class FileNameExtensionFilter extends FileFilter { private HashSet<String> extensions; private String description; public FileNameExtensionFilter(String ext) { extensions = new HashSet(); extensions.add(ext); description = new String(ext); } public FileNameExtensionFilter(String[] ext) { extensions = new HashSet(); StringBuffer desc = new StringBuffer(); for (String e : ext) { extensions.add(e); desc.append(e + ", "); } description = desc.toString(); } public boolean accept(File pathname) { if (pathname.isDirectory()) { return true; } String e = pathname.getName(); e = e.substring(e.lastIndexOf('.') + 1); if (extensions.contains(e.toLowerCase())) { return true; } return false; } @Override public String getDescription() { return description; } } class LoadCompleteProcessor extends ProcessorComponent { private ImportedModel importedModel; public LoadCompleteProcessor(ImportedModel importedModel) { this.importedModel = importedModel; } @Override public void compute(ProcessorArmingCollection arg0) { processBounds(importedModel.getModelBG()); populateTextureList(importedModel.getModelBG()); importedModel.getEntity().removeComponent( LoadCompleteProcessor.class); setArmingCondition(null); } @Override public void commit(ProcessorArmingCollection arg0) { } @Override public void initialize() { setArmingCondition(new NewFrameCondition(this)); } } }
false
true
private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); basicPanel = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); translationXTF = new javax.swing.JSpinner(); translationYTF = new javax.swing.JSpinner(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); translationZTF = new javax.swing.JSpinner(); avatarMoveCB = new javax.swing.JCheckBox(); jPanel5 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); rotationXTF = new javax.swing.JSpinner(); rotationYTF = new javax.swing.JSpinner(); jLabel13 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); rotationZTF = new javax.swing.JSpinner(); modelNameTF = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); modelX3dTF = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); scaleTF = new javax.swing.JSpinner(); advancedPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); textureTable = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); texturePrefixTF = new javax.swing.JTextField(); jLabel25 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); boundsCenterYTF = new javax.swing.JTextField(); boundsCenterXTF = new javax.swing.JTextField(); jLabel28 = new javax.swing.JLabel(); jLabel29 = new javax.swing.JLabel(); boundsCenterZTF = new javax.swing.JTextField(); boundsSizeXTF = new javax.swing.JTextField(); jLabel26 = new javax.swing.JLabel(); geometryStatsB = new javax.swing.JButton(); jLabel30 = new javax.swing.JLabel(); boundsSizeYTF = new javax.swing.JTextField(); boundsSizeZTF = new javax.swing.JTextField(); jLabel31 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); cancelB = new javax.swing.JButton(); okB = new javax.swing.JButton(); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/modules/artimport/client/jme/resources/Bundle"); // NOI18N setTitle(bundle.getString("ModelImporterFrame.title")); // NOI18N jTabbedPane1.setFont(jTabbedPane1.getFont()); jTabbedPane1.setPreferredSize(new java.awt.Dimension(102, 167)); basicPanel.addInputMethodListener(new java.awt.event.InputMethodListener() { public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) { basicPanelInputMethodTextChanged(evt); } public void caretPositionChanged(java.awt.event.InputMethodEvent evt) { } }); jLabel7.setText(bundle.getString("ModelImporterFrame.jLabel7.text")); // NOI18N jLabel6.setText(bundle.getString("ModelImporterFrame.jLabel6.text")); // NOI18N translationXTF.setEnabled(false); translationYTF.setEnabled(false); jLabel8.setText(bundle.getString("ModelImporterFrame.jLabel8.text")); // NOI18N jLabel9.setText(bundle.getString("ModelImporterFrame.jLabel9.text")); // NOI18N translationZTF.setEnabled(false); avatarMoveCB.setFont(avatarMoveCB.getFont()); avatarMoveCB.setSelected(true); avatarMoveCB.setText(bundle.getString("ModelImporterFrame.avatarMoveCB.text")); // NOI18N avatarMoveCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { avatarMoveCBActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel7) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel6) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel8) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel9)) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(translationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.LEADING, translationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(translationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap(6, Short.MAX_VALUE)) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(30, Short.MAX_VALUE) .add(avatarMoveCB)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .add(jLabel7) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel6) .add(translationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(translationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel8)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(translationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel9)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(avatarMoveCB)) ); jLabel10.setText(bundle.getString("ModelImporterFrame.jLabel10.text")); // NOI18N jLabel11.setText(bundle.getString("ModelImporterFrame.jLabel11.text")); // NOI18N jLabel13.setText(bundle.getString("ModelImporterFrame.jLabel13.text")); // NOI18N jLabel12.setText(bundle.getString("ModelImporterFrame.jLabel12.text")); // NOI18N org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel5Layout.createSequentialGroup() .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel10) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel11) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel13) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel12)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(rotationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(rotationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(rotationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5Layout.linkSize(new java.awt.Component[] {jLabel11, jLabel12, jLabel13}, org.jdesktop.layout.GroupLayout.HORIZONTAL); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel5Layout.createSequentialGroup() .add(jLabel10) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel11) .add(rotationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(rotationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel13)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(rotationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel12)) .addContainerGap(29, Short.MAX_VALUE)) ); modelNameTF.setText(bundle.getString("ModelImporterFrame.modelNameTF.text")); // NOI18N modelNameTF.setToolTipText(bundle.getString("ModelImporterFrame.modelNameTF.toolTipText")); // NOI18N jLabel5.setText(bundle.getString("ModelImporterFrame.jLabel5.text")); // NOI18N modelX3dTF.setEditable(false); modelX3dTF.setText(bundle.getString("ModelImporterFrame.modelX3dTF.text")); // NOI18N modelX3dTF.setToolTipText(bundle.getString("ModelImporterFrame.modelX3dTF.toolTipText")); // NOI18N jLabel1.setText(bundle.getString("ModelImporterFrame.jLabel1.text")); // NOI18N jLabel3.setText(bundle.getString("ModelImporterFrame.jLabel3.text")); // NOI18N org.jdesktop.layout.GroupLayout basicPanelLayout = new org.jdesktop.layout.GroupLayout(basicPanel); basicPanel.setLayout(basicPanelLayout); basicPanelLayout.setHorizontalGroup( basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(basicPanelLayout.createSequentialGroup() .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(basicPanelLayout.createSequentialGroup() .addContainerGap() .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel3) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel5) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel1)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(scaleTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(modelX3dTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE) .add(modelNameTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE))) .add(basicPanelLayout.createSequentialGroup() .add(31, 31, 31) .add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); basicPanelLayout.setVerticalGroup( basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(basicPanelLayout.createSequentialGroup() .addContainerGap() .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel1) .add(modelX3dTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(5, 5, 5) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(modelNameTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel5)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel3) .add(scaleTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(64, 64, 64)) ); jTabbedPane1.addTab(bundle.getString("ModelImporterFrame.basicPanel.TabConstraints.tabTitle"), basicPanel); // NOI18N jScrollPane1.setViewportView(textureTable); jLabel2.setText(bundle.getString("ModelImporterFrame.jLabel2.text")); // NOI18N texturePrefixTF.setEditable(false); texturePrefixTF.setText(bundle.getString("ModelImporterFrame.texturePrefixTF.text")); // NOI18N texturePrefixTF.setToolTipText(bundle.getString("ModelImporterFrame.texturePrefixTF.toolTipText")); // NOI18N jLabel25.setText(bundle.getString("ModelImporterFrame.jLabel25.text")); // NOI18N jLabel27.setText(bundle.getString("ModelImporterFrame.jLabel27.text")); // NOI18N boundsCenterYTF.setColumns(12); boundsCenterYTF.setEditable(false); boundsCenterYTF.setFont(boundsCenterYTF.getFont()); boundsCenterYTF.setText(bundle.getString("ModelImporterFrame.boundsCenterYTF.text")); // NOI18N boundsCenterXTF.setColumns(12); boundsCenterXTF.setEditable(false); boundsCenterXTF.setFont(boundsCenterXTF.getFont()); boundsCenterXTF.setText(bundle.getString("ModelImporterFrame.boundsCenterXTF.text")); // NOI18N jLabel28.setText(bundle.getString("ModelImporterFrame.jLabel28.text")); // NOI18N jLabel29.setText(bundle.getString("ModelImporterFrame.jLabel29.text")); // NOI18N boundsCenterZTF.setColumns(12); boundsCenterZTF.setEditable(false); boundsCenterZTF.setFont(boundsCenterZTF.getFont()); boundsCenterZTF.setText(bundle.getString("ModelImporterFrame.boundsCenterZTF.text")); // NOI18N boundsSizeXTF.setColumns(12); boundsSizeXTF.setEditable(false); boundsSizeXTF.setFont(boundsSizeXTF.getFont()); boundsSizeXTF.setText(bundle.getString("ModelImporterFrame.boundsSizeXTF.text")); // NOI18N jLabel26.setText(bundle.getString("ModelImporterFrame.jLabel26.text")); // NOI18N geometryStatsB.setText(bundle.getString("ModelImporterFrame.geometryStatsB.text")); // NOI18N geometryStatsB.setToolTipText(bundle.getString("ModelImporterFrame.geometryStatsB.toolTipText")); // NOI18N geometryStatsB.setEnabled(false); geometryStatsB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { geometryStatsBActionPerformed(evt); } }); jLabel30.setText(bundle.getString("ModelImporterFrame.jLabel30.text")); // NOI18N boundsSizeYTF.setColumns(12); boundsSizeYTF.setEditable(false); boundsSizeYTF.setFont(boundsSizeYTF.getFont()); boundsSizeYTF.setText(bundle.getString("ModelImporterFrame.boundsSizeYTF.text")); // NOI18N boundsSizeZTF.setColumns(12); boundsSizeZTF.setEditable(false); boundsSizeZTF.setFont(boundsSizeZTF.getFont()); boundsSizeZTF.setText(bundle.getString("ModelImporterFrame.boundsSizeZTF.text")); // NOI18N jLabel31.setText(bundle.getString("ModelImporterFrame.jLabel31.text")); // NOI18N jLabel32.setText(bundle.getString("ModelImporterFrame.jLabel32.text")); // NOI18N jLabel33.setText(bundle.getString("ModelImporterFrame.jLabel33.text")); // NOI18N org.jdesktop.layout.GroupLayout advancedPanelLayout = new org.jdesktop.layout.GroupLayout(advancedPanel); advancedPanel.setLayout(advancedPanelLayout); advancedPanelLayout.setHorizontalGroup( advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .addContainerGap() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE) .addContainerGap()) .add(advancedPanelLayout.createSequentialGroup() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .add(jLabel2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(texturePrefixTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)) .add(jLabel30)) .add(6, 6, 6)) .add(advancedPanelLayout.createSequentialGroup() .add(6, 6, 6) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(org.jdesktop.layout.GroupLayout.LEADING, geometryStatsB) .add(org.jdesktop.layout.GroupLayout.LEADING, advancedPanelLayout.createSequentialGroup() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel25) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel27) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel28) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel29)) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(boundsCenterYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsCenterXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsCenterZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(85, 85, 85) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(jLabel31) .add(jLabel33) .add(jLabel32)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(boundsSizeXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsSizeYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsSizeZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(advancedPanelLayout.createSequentialGroup() .add(120, 120, 120) .add(jLabel26))))) .add(3, 3, 3)))) ); advancedPanelLayout.linkSize(new java.awt.Component[] {boundsSizeXTF, boundsSizeYTF, boundsSizeZTF}, org.jdesktop.layout.GroupLayout.HORIZONTAL); advancedPanelLayout.linkSize(new java.awt.Component[] {boundsCenterXTF, boundsCenterYTF, boundsCenterZTF}, org.jdesktop.layout.GroupLayout.HORIZONTAL); advancedPanelLayout.setVerticalGroup( advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .addContainerGap() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel2) .add(texturePrefixTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jLabel30) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 97, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel25, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel26)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel27) .add(boundsCenterYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel31) .add(boundsSizeXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel28) .add(boundsCenterXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel32) .add(boundsSizeYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel29) .add(boundsCenterZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel33) .add(boundsSizeZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(geometryStatsB) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jTabbedPane1.addTab(bundle.getString("ModelImporterFrame.advancedPanel.TabConstraints.tabTitle"), advancedPanel); // NOI18N cancelB.setText(bundle.getString("ModelImporterFrame.cancelB.text")); // NOI18N cancelB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelBActionPerformed(evt); } }); okB.setText(bundle.getString("ModelImporterFrame.okB.text")); // NOI18N okB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okBActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap(261, Short.MAX_VALUE) .add(cancelB) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(okB) .addContainerGap()) .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 370, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(cancelB) .add(okB)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); basicPanel = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); translationXTF = new javax.swing.JSpinner(); translationYTF = new javax.swing.JSpinner(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); translationZTF = new javax.swing.JSpinner(); avatarMoveCB = new javax.swing.JCheckBox(); jPanel5 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); rotationXTF = new javax.swing.JSpinner(); rotationYTF = new javax.swing.JSpinner(); jLabel13 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); rotationZTF = new javax.swing.JSpinner(); modelNameTF = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); modelX3dTF = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); scaleTF = new javax.swing.JSpinner(); advancedPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); textureTable = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); texturePrefixTF = new javax.swing.JTextField(); jLabel25 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); boundsCenterYTF = new javax.swing.JTextField(); boundsCenterXTF = new javax.swing.JTextField(); jLabel28 = new javax.swing.JLabel(); jLabel29 = new javax.swing.JLabel(); boundsCenterZTF = new javax.swing.JTextField(); boundsSizeXTF = new javax.swing.JTextField(); jLabel26 = new javax.swing.JLabel(); geometryStatsB = new javax.swing.JButton(); jLabel30 = new javax.swing.JLabel(); boundsSizeYTF = new javax.swing.JTextField(); boundsSizeZTF = new javax.swing.JTextField(); jLabel31 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); cancelB = new javax.swing.JButton(); okB = new javax.swing.JButton(); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/modules/artimport/client/jme/resources/Bundle"); // NOI18N setTitle(bundle.getString("ModelImporterFrame.title")); // NOI18N jTabbedPane1.setFont(jTabbedPane1.getFont()); jTabbedPane1.setPreferredSize(new java.awt.Dimension(102, 167)); basicPanel.addInputMethodListener(new java.awt.event.InputMethodListener() { public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) { basicPanelInputMethodTextChanged(evt); } public void caretPositionChanged(java.awt.event.InputMethodEvent evt) { } }); jLabel7.setText(bundle.getString("ModelImporterFrame.jLabel7.text")); // NOI18N jLabel6.setText(bundle.getString("ModelImporterFrame.jLabel6.text")); // NOI18N translationXTF.setEnabled(false); translationYTF.setEnabled(false); jLabel8.setText(bundle.getString("ModelImporterFrame.jLabel8.text")); // NOI18N jLabel9.setText(bundle.getString("ModelImporterFrame.jLabel9.text")); // NOI18N translationZTF.setEnabled(false); avatarMoveCB.setFont(avatarMoveCB.getFont()); avatarMoveCB.setSelected(true); avatarMoveCB.setText(bundle.getString("ModelImporterFrame.avatarMoveCB.text")); // NOI18N avatarMoveCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { avatarMoveCBActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel7) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel6) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel8) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel9)) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(translationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.LEADING, translationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(translationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap(10, Short.MAX_VALUE)) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(30, Short.MAX_VALUE) .add(avatarMoveCB)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel4Layout.createSequentialGroup() .add(jLabel7) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel6) .add(translationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(translationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel8)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(translationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel9)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(avatarMoveCB)) ); jLabel10.setText(bundle.getString("ModelImporterFrame.jLabel10.text")); // NOI18N jLabel11.setText(bundle.getString("ModelImporterFrame.jLabel11.text")); // NOI18N jLabel13.setText(bundle.getString("ModelImporterFrame.jLabel13.text")); // NOI18N jLabel12.setText(bundle.getString("ModelImporterFrame.jLabel12.text")); // NOI18N org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel5Layout.createSequentialGroup() .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel10) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel11) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel13) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel12)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(rotationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(rotationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(rotationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5Layout.linkSize(new java.awt.Component[] {jLabel11, jLabel12, jLabel13}, org.jdesktop.layout.GroupLayout.HORIZONTAL); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel5Layout.createSequentialGroup() .add(jLabel10) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel11) .add(rotationXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(rotationYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel13)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(rotationZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel12)) .addContainerGap(29, Short.MAX_VALUE)) ); modelNameTF.setText(bundle.getString("ModelImporterFrame.modelNameTF.text")); // NOI18N modelNameTF.setToolTipText(bundle.getString("ModelImporterFrame.modelNameTF.toolTipText")); // NOI18N jLabel5.setText(bundle.getString("ModelImporterFrame.jLabel5.text")); // NOI18N modelX3dTF.setEditable(false); modelX3dTF.setText(bundle.getString("ModelImporterFrame.modelX3dTF.text")); // NOI18N modelX3dTF.setToolTipText(bundle.getString("ModelImporterFrame.modelX3dTF.toolTipText")); // NOI18N jLabel1.setText(bundle.getString("ModelImporterFrame.jLabel1.text")); // NOI18N jLabel3.setText(bundle.getString("ModelImporterFrame.jLabel3.text")); // NOI18N org.jdesktop.layout.GroupLayout basicPanelLayout = new org.jdesktop.layout.GroupLayout(basicPanel); basicPanel.setLayout(basicPanelLayout); basicPanelLayout.setHorizontalGroup( basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(basicPanelLayout.createSequentialGroup() .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(basicPanelLayout.createSequentialGroup() .addContainerGap() .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel3) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel5) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel1)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(scaleTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(modelX3dTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE) .add(modelNameTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE))) .add(basicPanelLayout.createSequentialGroup() .add(31, 31, 31) .add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); basicPanelLayout.setVerticalGroup( basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(basicPanelLayout.createSequentialGroup() .addContainerGap() .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel1) .add(modelX3dTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(5, 5, 5) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(modelNameTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel5)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(basicPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel3) .add(scaleTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(64, 64, 64)) ); jTabbedPane1.addTab(bundle.getString("ModelImporterFrame.basicPanel.TabConstraints.tabTitle"), basicPanel); // NOI18N jScrollPane1.setViewportView(textureTable); jLabel2.setText(bundle.getString("ModelImporterFrame.jLabel2.text")); // NOI18N texturePrefixTF.setEditable(false); texturePrefixTF.setText(bundle.getString("ModelImporterFrame.texturePrefixTF.text")); // NOI18N texturePrefixTF.setToolTipText(bundle.getString("ModelImporterFrame.texturePrefixTF.toolTipText")); // NOI18N jLabel25.setText(bundle.getString("ModelImporterFrame.jLabel25.text")); // NOI18N jLabel27.setText(bundle.getString("ModelImporterFrame.jLabel27.text")); // NOI18N boundsCenterYTF.setColumns(12); boundsCenterYTF.setEditable(false); boundsCenterYTF.setFont(boundsCenterYTF.getFont()); boundsCenterYTF.setText(bundle.getString("ModelImporterFrame.boundsCenterYTF.text")); // NOI18N boundsCenterXTF.setColumns(12); boundsCenterXTF.setEditable(false); boundsCenterXTF.setFont(boundsCenterXTF.getFont()); boundsCenterXTF.setText(bundle.getString("ModelImporterFrame.boundsCenterXTF.text")); // NOI18N jLabel28.setText(bundle.getString("ModelImporterFrame.jLabel28.text")); // NOI18N jLabel29.setText(bundle.getString("ModelImporterFrame.jLabel29.text")); // NOI18N boundsCenterZTF.setColumns(12); boundsCenterZTF.setEditable(false); boundsCenterZTF.setFont(boundsCenterZTF.getFont()); boundsCenterZTF.setText(bundle.getString("ModelImporterFrame.boundsCenterZTF.text")); // NOI18N boundsSizeXTF.setColumns(12); boundsSizeXTF.setEditable(false); boundsSizeXTF.setFont(boundsSizeXTF.getFont()); boundsSizeXTF.setText(bundle.getString("ModelImporterFrame.boundsSizeXTF.text")); // NOI18N jLabel26.setText(bundle.getString("ModelImporterFrame.jLabel26.text")); // NOI18N geometryStatsB.setText(bundle.getString("ModelImporterFrame.geometryStatsB.text")); // NOI18N geometryStatsB.setToolTipText(bundle.getString("ModelImporterFrame.geometryStatsB.toolTipText")); // NOI18N geometryStatsB.setEnabled(false); geometryStatsB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { geometryStatsBActionPerformed(evt); } }); jLabel30.setText(bundle.getString("ModelImporterFrame.jLabel30.text")); // NOI18N boundsSizeYTF.setColumns(12); boundsSizeYTF.setEditable(false); boundsSizeYTF.setFont(boundsSizeYTF.getFont()); boundsSizeYTF.setText(bundle.getString("ModelImporterFrame.boundsSizeYTF.text")); // NOI18N boundsSizeZTF.setColumns(12); boundsSizeZTF.setEditable(false); boundsSizeZTF.setFont(boundsSizeZTF.getFont()); boundsSizeZTF.setText(bundle.getString("ModelImporterFrame.boundsSizeZTF.text")); // NOI18N jLabel31.setText(bundle.getString("ModelImporterFrame.jLabel31.text")); // NOI18N jLabel32.setText(bundle.getString("ModelImporterFrame.jLabel32.text")); // NOI18N jLabel33.setText(bundle.getString("ModelImporterFrame.jLabel33.text")); // NOI18N org.jdesktop.layout.GroupLayout advancedPanelLayout = new org.jdesktop.layout.GroupLayout(advancedPanel); advancedPanel.setLayout(advancedPanelLayout); advancedPanelLayout.setHorizontalGroup( advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .addContainerGap() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE) .addContainerGap()) .add(advancedPanelLayout.createSequentialGroup() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .add(jLabel2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(texturePrefixTF, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)) .add(jLabel30)) .add(6, 6, 6)) .add(advancedPanelLayout.createSequentialGroup() .add(6, 6, 6) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(org.jdesktop.layout.GroupLayout.LEADING, geometryStatsB) .add(org.jdesktop.layout.GroupLayout.LEADING, advancedPanelLayout.createSequentialGroup() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel25) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel27) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel28) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel29)) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(boundsCenterYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsCenterXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsCenterZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(85, 85, 85) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(jLabel31) .add(jLabel33) .add(jLabel32)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(boundsSizeXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsSizeYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(boundsSizeZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(advancedPanelLayout.createSequentialGroup() .add(120, 120, 120) .add(jLabel26))))) .add(3, 3, 3)))) ); advancedPanelLayout.linkSize(new java.awt.Component[] {boundsSizeXTF, boundsSizeYTF, boundsSizeZTF}, org.jdesktop.layout.GroupLayout.HORIZONTAL); advancedPanelLayout.linkSize(new java.awt.Component[] {boundsCenterXTF, boundsCenterYTF, boundsCenterZTF}, org.jdesktop.layout.GroupLayout.HORIZONTAL); advancedPanelLayout.setVerticalGroup( advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(advancedPanelLayout.createSequentialGroup() .addContainerGap() .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel2) .add(texturePrefixTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jLabel30) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 97, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel25, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel26)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel27) .add(boundsCenterYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel31) .add(boundsSizeXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel28) .add(boundsCenterXTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel32) .add(boundsSizeYTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(advancedPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(jLabel29) .add(boundsCenterZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel33) .add(boundsSizeZTF, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(geometryStatsB) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jTabbedPane1.addTab(bundle.getString("ModelImporterFrame.advancedPanel.TabConstraints.tabTitle"), advancedPanel); // NOI18N cancelB.setText(bundle.getString("ModelImporterFrame.cancelB.text")); // NOI18N cancelB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelBActionPerformed(evt); } }); okB.setText(bundle.getString("ModelImporterFrame.okB.text")); // NOI18N okB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okBActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap(261, Short.MAX_VALUE) .add(cancelB) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(okB) .addContainerGap()) .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 370, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(cancelB) .add(okB)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/framework/src/play/data/binding/Binder.java b/framework/src/play/data/binding/Binder.java index bbea6566..4ab57edf 100644 --- a/framework/src/play/data/binding/Binder.java +++ b/framework/src/play/data/binding/Binder.java @@ -1,435 +1,436 @@ package play.data.binding; import play.Logger; import play.Play; import play.PlayPlugin; import play.data.Upload; import play.data.binding.annotations.As; import play.data.binding.annotations.NoBinding; import play.data.validation.Validation; import play.exceptions.UnexpectedException; import play.utils.Utils; import java.io.File; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The binder try to convert String values to Java objects. */ public class Binder { static Map<Class, SupportedType> supportedTypes = new HashMap<Class, SupportedType>(); static { supportedTypes.put(Date.class, new DateBinder()); supportedTypes.put(File.class, new FileBinder()); supportedTypes.put(File[].class, new FileArrayBinder()); supportedTypes.put(Upload.class, new UploadBinder()); supportedTypes.put(Upload[].class, new UploadArrayBinder()); supportedTypes.put(Calendar.class, new CalendarBinder()); supportedTypes.put(Locale.class, new LocaleBinder()); supportedTypes.put(byte[].class, new ByteArrayBinder()); supportedTypes.put(byte[][].class, new ByteArrayArrayBinder()); } static Map<Class, BeanWrapper> beanwrappers = new HashMap<Class, BeanWrapper>(); static BeanWrapper getBeanWrapper(Class clazz) { if (!beanwrappers.containsKey(clazz)) { BeanWrapper beanwrapper = new BeanWrapper(clazz); beanwrappers.put(clazz, beanwrapper); } return beanwrappers.get(clazz); } public final static Object MISSING = new Object(); public final static Object NO_BINDING = new Object(); // TODO move me to Utils private static String toString(String[] values) { String toReturn = ""; if (values != null) { for (String value : values) { toReturn = "," + value; } } if (toReturn.equals("")) { return toReturn; } return toReturn.substring(1); } @SuppressWarnings("unchecked") static Object bindInternal(String name, Class clazz, Type type, Annotation[] annotations, Map<String, String[]> params, String prefix, String[] profiles) { try { Logger.trace("bindInternal: class [" + clazz + "] name [" + name + "] annotation [" + Utils.toString(annotations) + "] isComposite [" + isComposite(name + prefix, params.keySet()) + "]"); if (isComposite(name + prefix, params.keySet())) { BeanWrapper beanWrapper = getBeanWrapper(clazz); return beanWrapper.bind(name, type, params, prefix, annotations); } Logger.trace("bindInternal: name [" + name + "] prefix [" + prefix + "]"); String[] value = params.get(name + prefix); Logger.trace("bindInternal: value [" + value + "]"); Logger.trace("bindInternal: profile [" + toString(profiles) + "]"); // Let see if we have a BindAs annotation and a separator. If so, we need to split the values // Look up for the BindAs annotation. Extract the profile if there is any. // TODO: Move me somewhere else? if (annotations != null) { for (Annotation annotation : annotations) { if ((clazz.isArray() || Collection.class.isAssignableFrom(clazz)) && value != null && value.length > 0 && annotation.annotationType().equals(As.class)) { As as = ((As) annotation); final String separator = as.value()[0]; value = value[0].split(separator); } if (annotation.annotationType().equals(NoBinding.class)) { NoBinding bind = ((NoBinding) annotation); String[] localUnbindProfiles = bind.value(); Logger.trace("bindInternal: localUnbindProfiles [" + toString(localUnbindProfiles) + "]"); if (localUnbindProfiles != null && contains(profiles, localUnbindProfiles)) { return NO_BINDING; } } } } // Arrays types // The array condition is not so nice... We should find another way of doing this.... if (clazz.isArray() && (clazz != byte[].class && clazz != byte[][].class && clazz != File[].class && clazz != Upload[].class)) { if (value == null) { value = params.get(name + prefix + "[]"); } if (value == null) { return MISSING; } Object r = Array.newInstance(clazz.getComponentType(), value.length); for (int i = 0; i <= value.length; i++) { try { Array.set(r, i, directBind(annotations, value[i], clazz.getComponentType())); } catch (Exception e) { // ?? One item was bad } } return r; } // Enums if (Enum.class.isAssignableFrom(clazz)) { if (value == null || value.length == 0) { return MISSING; } return Enum.valueOf(clazz, value[0]); } // Map if (Map.class.isAssignableFrom(clazz)) { Class keyClass = String.class; Class valueClass = String.class; if (type instanceof ParameterizedType) { keyClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; valueClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1]; } // Search for all params Map<Object, Object> r = new HashMap<Object, Object>(); for (String param : params.keySet()) { Pattern p = Pattern.compile("^" + name + prefix + "\\[([^\\]]+)\\](.*)$"); Matcher m = p.matcher(param); if (m.matches()) { String key = m.group(1); + value = params.get(param); Map<String, String[]> tP = new HashMap<String, String[]>(); tP.put("key", new String[]{key}); Object oKey = bindInternal("key", keyClass, keyClass, annotations, tP, "", value); if (oKey != MISSING) { if (isComposite(name + prefix + "[" + key + "]", params.keySet())) { BeanWrapper beanWrapper = getBeanWrapper(valueClass); Object oValue = beanWrapper.bind("", type, params, name + prefix + "[" + key + "]", annotations); r.put(oKey, oValue); } else { tP = new HashMap<String, String[]>(); tP.put("value", params.get(name + prefix + "[" + key + "]")); Object oValue = bindInternal("value", valueClass, valueClass, annotations, tP, "", value); if (oValue != MISSING) { r.put(oKey, oValue); } else { r.put(oKey, null); } } } } } return r; } // Collections types if (Collection.class.isAssignableFrom(clazz)) { if (clazz.isInterface()) { if (clazz.equals(List.class)) { clazz = ArrayList.class; } if (clazz.equals(Set.class)) { clazz = HashSet.class; } if (clazz.equals(SortedSet.class)) { clazz = TreeSet.class; } } Collection r = (Collection) clazz.newInstance(); Class componentClass = String.class; if (type instanceof ParameterizedType) { componentClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; } if (value == null) { value = params.get(name + prefix + "[]"); if (value == null && r instanceof List) { for (String param : params.keySet()) { Pattern p = Pattern.compile("^" + name + prefix + "\\[([0-9]+)\\](.*)$"); Matcher m = p.matcher(param); if (m.matches()) { int key = Integer.parseInt(m.group(1)); while (((List<?>) r).size() <= key) { ((List<?>) r).add(null); } if (isComposite(name + prefix + "[" + key + "]", params.keySet())) { BeanWrapper beanWrapper = getBeanWrapper(componentClass); Object oValue = beanWrapper.bind("", type, params, name + prefix + "[" + key + "]", annotations); ((List) r).set(key, oValue); } else { Map<String, String[]> tP = new HashMap<String, String[]>(); tP.put("value", params.get(name + prefix + "[" + key + "]")); Object oValue = bindInternal("value", componentClass, componentClass, annotations, tP, "", value); if (oValue != MISSING) { ((List) r).set(key, oValue); } } } } return r.size() == 0 ? MISSING : r; } } if (value == null) { return MISSING; } for (String v : value) { try { r.add(directBind(annotations, v, componentClass)); } catch (Exception e) { // ?? One item was bad Logger.debug(e, "error:"); } } return r; } // Simple types if (value == null || value.length == 0) { return MISSING; } return directBind(annotations, value[0], clazz); } catch (Exception e) { Validation.addError(name + prefix, "validation.invalid"); return MISSING; } } public static boolean contains(String[] profiles, String[] localProfiles) { if (localProfiles != null) { for (String l : localProfiles) { if ("*".equals(l)) { return true; } if (profiles != null) { for (String p : profiles) { if (l.equals(p) || "*".equals(p)) { return true; } } } } } return false; } public static Object bind(String name, Class clazz, Type type, Annotation[] annotations, Map<String, String[]> params) { return bind(name, clazz, type, annotations, params, null, null, 0); } public static Object bind(String name, Class clazz, Type type, Annotation[] annotations, Map<String, String[]> params, Object o, Method method, int parameterIndex) { Logger.trace("bind: name [" + name + "] annotation [" + Utils.toString(annotations) + "] "); Object result = null; // Let a chance to plugins to bind this object for (PlayPlugin plugin : Play.plugins) { result = plugin.bind(name, clazz, type, annotations, params); if (result != null) { return result; } } String[] profiles = null; if (annotations != null) { for (Annotation annotation : annotations) { if (annotation.annotationType().equals(As.class)) { As as = ((As) annotation); profiles = as.value(); } if (annotation.annotationType().equals(NoBinding.class)) { NoBinding bind = ((NoBinding) annotation); profiles = bind.value(); } } } result = bindInternal(name, clazz, type, annotations, params, "", profiles); if (result == MISSING) { // Try the scala default if (o != null && parameterIndex > 0) { try { Method defaultMethod = method.getDeclaringClass().getDeclaredMethod(method.getName() + "$default$" + parameterIndex); return defaultMethod.invoke(o); } catch (NoSuchMethodException e) { // } catch (Exception e) { throw new UnexpectedException(e); } } if (clazz.equals(boolean.class)) { return false; } if (clazz.equals(int.class)) { return 0; } if (clazz.equals(long.class)) { return 0; } if (clazz.equals(double.class)) { return 0; } if (clazz.equals(short.class)) { return 0; } if (clazz.equals(byte.class)) { return 0; } if (clazz.equals(char.class)) { return ' '; } return null; } return result; } static boolean isComposite(String name, Set<String> pNames) { for (String pName : pNames) { if (pName.startsWith(name + ".")) { return true; } } return false; } public static Object directBind(String value, Class clazz) throws Exception { return directBind(null, value, clazz); } public static Object directBind(Annotation[] annotations, String value, Class clazz) throws Exception { Logger.trace("directBind: value [" + value + "] annotation [" + Utils.toString(annotations) + "] Class [" + clazz + "]"); if (clazz.equals(String.class)) { return value; } if (annotations != null) { for (Annotation annotation : annotations) { if (annotation.getClass().equals(As.class)) { Class<? extends SupportedType> toInstanciate = ((As) annotation).binder(); if (!(toInstanciate.equals(As.DEFAULT.class))) { // Instanciate the binder SupportedType myInstance = toInstanciate.newInstance(); return myInstance.bind(annotations, value); } } } } boolean nullOrEmpty = value == null || value.trim().length() == 0; if (supportedTypes.containsKey(clazz)) { return nullOrEmpty ? null : supportedTypes.get(clazz).bind(annotations, value); } // int or Integer binding if (clazz.getName().equals("int") || clazz.equals(Integer.class)) { if (nullOrEmpty) return clazz.isPrimitive() ? 0 : null; return Integer.parseInt(value.contains(".") ? value.substring(0, value.indexOf(".")) : value); } // long or Long binding if (clazz.getName().equals("long") || clazz.equals(Long.class)) { if (nullOrEmpty) return clazz.isPrimitive() ? 0l : null; return Long.parseLong(value.contains(".") ? value.substring(0, value.indexOf(".")) : value); } // byte or Byte binding if (clazz.getName().equals("byte") || clazz.equals(Byte.class)) { if (nullOrEmpty) return clazz.isPrimitive() ? (byte) 0 : null; return Byte.parseByte(value.contains(".") ? value.substring(0, value.indexOf(".")) : value); } // short or Short binding if (clazz.getName().equals("short") || clazz.equals(Short.class)) { if (nullOrEmpty) return clazz.isPrimitive() ? (short) 0 : null; return Short.parseShort(value.contains(".") ? value.substring(0, value.indexOf(".")) : value); } // float or Float binding if (clazz.getName().equals("float") || clazz.equals(Float.class)) { if (nullOrEmpty) return clazz.isPrimitive() ? 0f : null; return Float.parseFloat(value); } // double or Double binding if (clazz.getName().equals("double") || clazz.equals(Double.class)) { if (nullOrEmpty) return clazz.isPrimitive() ? 0d : null; return Double.parseDouble(value); } // BigDecimal binding if (clazz.equals(BigDecimal.class)) { if (nullOrEmpty) return null; return new BigDecimal(value); } // boolean or Boolean binding if (clazz.getName().equals("boolean") || clazz.equals(Boolean.class)) { if (nullOrEmpty) return clazz.isPrimitive() ? false : null; if (value.equals("1") || value.toLowerCase().equals("on") || value.toLowerCase().equals("yes")) return true; return Boolean.parseBoolean(value); } return null; } }
true
true
static Object bindInternal(String name, Class clazz, Type type, Annotation[] annotations, Map<String, String[]> params, String prefix, String[] profiles) { try { Logger.trace("bindInternal: class [" + clazz + "] name [" + name + "] annotation [" + Utils.toString(annotations) + "] isComposite [" + isComposite(name + prefix, params.keySet()) + "]"); if (isComposite(name + prefix, params.keySet())) { BeanWrapper beanWrapper = getBeanWrapper(clazz); return beanWrapper.bind(name, type, params, prefix, annotations); } Logger.trace("bindInternal: name [" + name + "] prefix [" + prefix + "]"); String[] value = params.get(name + prefix); Logger.trace("bindInternal: value [" + value + "]"); Logger.trace("bindInternal: profile [" + toString(profiles) + "]"); // Let see if we have a BindAs annotation and a separator. If so, we need to split the values // Look up for the BindAs annotation. Extract the profile if there is any. // TODO: Move me somewhere else? if (annotations != null) { for (Annotation annotation : annotations) { if ((clazz.isArray() || Collection.class.isAssignableFrom(clazz)) && value != null && value.length > 0 && annotation.annotationType().equals(As.class)) { As as = ((As) annotation); final String separator = as.value()[0]; value = value[0].split(separator); } if (annotation.annotationType().equals(NoBinding.class)) { NoBinding bind = ((NoBinding) annotation); String[] localUnbindProfiles = bind.value(); Logger.trace("bindInternal: localUnbindProfiles [" + toString(localUnbindProfiles) + "]"); if (localUnbindProfiles != null && contains(profiles, localUnbindProfiles)) { return NO_BINDING; } } } } // Arrays types // The array condition is not so nice... We should find another way of doing this.... if (clazz.isArray() && (clazz != byte[].class && clazz != byte[][].class && clazz != File[].class && clazz != Upload[].class)) { if (value == null) { value = params.get(name + prefix + "[]"); } if (value == null) { return MISSING; } Object r = Array.newInstance(clazz.getComponentType(), value.length); for (int i = 0; i <= value.length; i++) { try { Array.set(r, i, directBind(annotations, value[i], clazz.getComponentType())); } catch (Exception e) { // ?? One item was bad } } return r; } // Enums if (Enum.class.isAssignableFrom(clazz)) { if (value == null || value.length == 0) { return MISSING; } return Enum.valueOf(clazz, value[0]); } // Map if (Map.class.isAssignableFrom(clazz)) { Class keyClass = String.class; Class valueClass = String.class; if (type instanceof ParameterizedType) { keyClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; valueClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1]; } // Search for all params Map<Object, Object> r = new HashMap<Object, Object>(); for (String param : params.keySet()) { Pattern p = Pattern.compile("^" + name + prefix + "\\[([^\\]]+)\\](.*)$"); Matcher m = p.matcher(param); if (m.matches()) { String key = m.group(1); Map<String, String[]> tP = new HashMap<String, String[]>(); tP.put("key", new String[]{key}); Object oKey = bindInternal("key", keyClass, keyClass, annotations, tP, "", value); if (oKey != MISSING) { if (isComposite(name + prefix + "[" + key + "]", params.keySet())) { BeanWrapper beanWrapper = getBeanWrapper(valueClass); Object oValue = beanWrapper.bind("", type, params, name + prefix + "[" + key + "]", annotations); r.put(oKey, oValue); } else { tP = new HashMap<String, String[]>(); tP.put("value", params.get(name + prefix + "[" + key + "]")); Object oValue = bindInternal("value", valueClass, valueClass, annotations, tP, "", value); if (oValue != MISSING) { r.put(oKey, oValue); } else { r.put(oKey, null); } } } } } return r; } // Collections types if (Collection.class.isAssignableFrom(clazz)) { if (clazz.isInterface()) { if (clazz.equals(List.class)) { clazz = ArrayList.class; } if (clazz.equals(Set.class)) { clazz = HashSet.class; } if (clazz.equals(SortedSet.class)) { clazz = TreeSet.class; } } Collection r = (Collection) clazz.newInstance(); Class componentClass = String.class; if (type instanceof ParameterizedType) { componentClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; } if (value == null) { value = params.get(name + prefix + "[]"); if (value == null && r instanceof List) { for (String param : params.keySet()) { Pattern p = Pattern.compile("^" + name + prefix + "\\[([0-9]+)\\](.*)$"); Matcher m = p.matcher(param); if (m.matches()) { int key = Integer.parseInt(m.group(1)); while (((List<?>) r).size() <= key) { ((List<?>) r).add(null); } if (isComposite(name + prefix + "[" + key + "]", params.keySet())) { BeanWrapper beanWrapper = getBeanWrapper(componentClass); Object oValue = beanWrapper.bind("", type, params, name + prefix + "[" + key + "]", annotations); ((List) r).set(key, oValue); } else { Map<String, String[]> tP = new HashMap<String, String[]>(); tP.put("value", params.get(name + prefix + "[" + key + "]")); Object oValue = bindInternal("value", componentClass, componentClass, annotations, tP, "", value); if (oValue != MISSING) { ((List) r).set(key, oValue); } } } } return r.size() == 0 ? MISSING : r; } } if (value == null) { return MISSING; } for (String v : value) { try { r.add(directBind(annotations, v, componentClass)); } catch (Exception e) { // ?? One item was bad Logger.debug(e, "error:"); } } return r; } // Simple types if (value == null || value.length == 0) { return MISSING; } return directBind(annotations, value[0], clazz); } catch (Exception e) { Validation.addError(name + prefix, "validation.invalid"); return MISSING; } }
static Object bindInternal(String name, Class clazz, Type type, Annotation[] annotations, Map<String, String[]> params, String prefix, String[] profiles) { try { Logger.trace("bindInternal: class [" + clazz + "] name [" + name + "] annotation [" + Utils.toString(annotations) + "] isComposite [" + isComposite(name + prefix, params.keySet()) + "]"); if (isComposite(name + prefix, params.keySet())) { BeanWrapper beanWrapper = getBeanWrapper(clazz); return beanWrapper.bind(name, type, params, prefix, annotations); } Logger.trace("bindInternal: name [" + name + "] prefix [" + prefix + "]"); String[] value = params.get(name + prefix); Logger.trace("bindInternal: value [" + value + "]"); Logger.trace("bindInternal: profile [" + toString(profiles) + "]"); // Let see if we have a BindAs annotation and a separator. If so, we need to split the values // Look up for the BindAs annotation. Extract the profile if there is any. // TODO: Move me somewhere else? if (annotations != null) { for (Annotation annotation : annotations) { if ((clazz.isArray() || Collection.class.isAssignableFrom(clazz)) && value != null && value.length > 0 && annotation.annotationType().equals(As.class)) { As as = ((As) annotation); final String separator = as.value()[0]; value = value[0].split(separator); } if (annotation.annotationType().equals(NoBinding.class)) { NoBinding bind = ((NoBinding) annotation); String[] localUnbindProfiles = bind.value(); Logger.trace("bindInternal: localUnbindProfiles [" + toString(localUnbindProfiles) + "]"); if (localUnbindProfiles != null && contains(profiles, localUnbindProfiles)) { return NO_BINDING; } } } } // Arrays types // The array condition is not so nice... We should find another way of doing this.... if (clazz.isArray() && (clazz != byte[].class && clazz != byte[][].class && clazz != File[].class && clazz != Upload[].class)) { if (value == null) { value = params.get(name + prefix + "[]"); } if (value == null) { return MISSING; } Object r = Array.newInstance(clazz.getComponentType(), value.length); for (int i = 0; i <= value.length; i++) { try { Array.set(r, i, directBind(annotations, value[i], clazz.getComponentType())); } catch (Exception e) { // ?? One item was bad } } return r; } // Enums if (Enum.class.isAssignableFrom(clazz)) { if (value == null || value.length == 0) { return MISSING; } return Enum.valueOf(clazz, value[0]); } // Map if (Map.class.isAssignableFrom(clazz)) { Class keyClass = String.class; Class valueClass = String.class; if (type instanceof ParameterizedType) { keyClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; valueClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1]; } // Search for all params Map<Object, Object> r = new HashMap<Object, Object>(); for (String param : params.keySet()) { Pattern p = Pattern.compile("^" + name + prefix + "\\[([^\\]]+)\\](.*)$"); Matcher m = p.matcher(param); if (m.matches()) { String key = m.group(1); value = params.get(param); Map<String, String[]> tP = new HashMap<String, String[]>(); tP.put("key", new String[]{key}); Object oKey = bindInternal("key", keyClass, keyClass, annotations, tP, "", value); if (oKey != MISSING) { if (isComposite(name + prefix + "[" + key + "]", params.keySet())) { BeanWrapper beanWrapper = getBeanWrapper(valueClass); Object oValue = beanWrapper.bind("", type, params, name + prefix + "[" + key + "]", annotations); r.put(oKey, oValue); } else { tP = new HashMap<String, String[]>(); tP.put("value", params.get(name + prefix + "[" + key + "]")); Object oValue = bindInternal("value", valueClass, valueClass, annotations, tP, "", value); if (oValue != MISSING) { r.put(oKey, oValue); } else { r.put(oKey, null); } } } } } return r; } // Collections types if (Collection.class.isAssignableFrom(clazz)) { if (clazz.isInterface()) { if (clazz.equals(List.class)) { clazz = ArrayList.class; } if (clazz.equals(Set.class)) { clazz = HashSet.class; } if (clazz.equals(SortedSet.class)) { clazz = TreeSet.class; } } Collection r = (Collection) clazz.newInstance(); Class componentClass = String.class; if (type instanceof ParameterizedType) { componentClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; } if (value == null) { value = params.get(name + prefix + "[]"); if (value == null && r instanceof List) { for (String param : params.keySet()) { Pattern p = Pattern.compile("^" + name + prefix + "\\[([0-9]+)\\](.*)$"); Matcher m = p.matcher(param); if (m.matches()) { int key = Integer.parseInt(m.group(1)); while (((List<?>) r).size() <= key) { ((List<?>) r).add(null); } if (isComposite(name + prefix + "[" + key + "]", params.keySet())) { BeanWrapper beanWrapper = getBeanWrapper(componentClass); Object oValue = beanWrapper.bind("", type, params, name + prefix + "[" + key + "]", annotations); ((List) r).set(key, oValue); } else { Map<String, String[]> tP = new HashMap<String, String[]>(); tP.put("value", params.get(name + prefix + "[" + key + "]")); Object oValue = bindInternal("value", componentClass, componentClass, annotations, tP, "", value); if (oValue != MISSING) { ((List) r).set(key, oValue); } } } } return r.size() == 0 ? MISSING : r; } } if (value == null) { return MISSING; } for (String v : value) { try { r.add(directBind(annotations, v, componentClass)); } catch (Exception e) { // ?? One item was bad Logger.debug(e, "error:"); } } return r; } // Simple types if (value == null || value.length == 0) { return MISSING; } return directBind(annotations, value[0], clazz); } catch (Exception e) { Validation.addError(name + prefix, "validation.invalid"); return MISSING; } }
diff --git a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/StudyFileEditBean.java b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/StudyFileEditBean.java index 38efcd6ba..5febc97f8 100644 --- a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/StudyFileEditBean.java +++ b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/StudyFileEditBean.java @@ -1,312 +1,312 @@ /* Copyright (C) 2005-2012, by the President and Fellows of Harvard College. 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. Dataverse Network - A web application to share, preserve and analyze research data. Developed at the Institute for Quantitative Social Science, Harvard University. Version 3.0. */ /* * StudyFileEditBean.java * * Created on October 10, 2006, 5:52 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package edu.harvard.iq.dvn.core.study; import edu.harvard.iq.dvn.core.util.FileUtil; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.logging.*; import javax.ejb.EJBException; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; /** * * @author gdurand */ public class StudyFileEditBean implements Serializable { private static Logger dbgLog = Logger.getLogger(StudyFileEditBean.class.getCanonicalName()); /** Creates a new instance of StudyFileEditBean */ public StudyFileEditBean(StudyFile sf) { this.studyFile = sf; } /** Creates a new instance of StudyFileEditBean */ public StudyFileEditBean(FileMetadata fileMetadata) { this.fileMetadata = fileMetadata; this.studyFile = fileMetadata.getStudyFile(); } public StudyFileEditBean(File file, String fileSystemName, Study study) throws IOException { this(file,fileSystemName,study,false); } public StudyFileEditBean(File file, String fileSystemName, Study study, boolean asOtherMaterial) throws IOException { dbgLog.fine("***** within StudyFileEditBean: constructor: start *****"); dbgLog.fine("reached before studyFile constructor"); String fileType = FileUtil.determineFileType(file); dbgLog.fine("return from FileUtil.determineFileType(file), fileType="+fileType); // boolean asOtherMaterial flag is to force uploading a potentially // subsettable file as a non-subsettable ("Other Material") data file. if (!asOtherMaterial && ( fileType.equals("application/x-stata") || fileType.equals("application/x-spss-por") || fileType.equals("application/x-spss-sav") ) ) { dbgLog.fine("tablularFile"); this.studyFile = new TabularDataFile(); // do not yet attach to study, as it has to be ingested } else if (!asOtherMaterial && fileType.equals("text/xml-graphml")) { dbgLog.fine("isGraphMLFile = true"); this.studyFile = new NetworkDataFile(); - } else if (!asOtherMaterial && fileType.equals("")) { + } else if (!asOtherMaterial && fileType.equals("application/fits")) { this.studyFile = new SpecialOtherFile(); dbgLog.fine("FITS file"); } else { this.studyFile = new OtherFile(study); } fileMetadata = new FileMetadata(); fileMetadata.setStudyFile(studyFile); this.getStudyFile().setFileType( fileType ); dbgLog.fine("reached before original filename"); this.setOriginalFileName(file.getName()); this.getStudyFile().setFileType(fileType); dbgLog.fine("after setFileType"); // not yet supported as subsettable //this.getStudyFile().getFileType().equals("application/x-rlang-transport") ); dbgLog.fine("before setFileName"); // replace extension with ".tab" if this we are going to convert this to a tabular data file fileMetadata.setLabel(this.getStudyFile() instanceof TabularDataFile ? FileUtil.replaceExtension(this.getOriginalFileName()) : this.getOriginalFileName()); dbgLog.fine("before tempsystemfilelocation"); this.setTempSystemFileLocation(file.getAbsolutePath()); this.getStudyFile().setFileSystemName(fileSystemName); dbgLog.fine("StudyFileEditBean: contents:\n" + this.toString()); dbgLog.fine("***** within StudyFileEditBean: constructor: end *****"); } public StudyFileEditBean(File file, String fileSystemName, Study study, String controlCardTempLocation, String controlCardType) throws IOException { dbgLog.fine("***** within StudyFileEditBean: control card constructor: start *****"); dbgLog.fine("reached before studyFile constructor"); String fileType = FileUtil.determineFileType(file); dbgLog.fine("return from FileUtil.determineFileType(file), fileType="+fileType); this.studyFile = new TabularDataFile(); // do not yet attach to study, as it has to be ingested fileMetadata = new FileMetadata(); fileMetadata.setStudyFile(studyFile); this.getStudyFile().setFileType( fileType ); dbgLog.fine("reached before original filename"); this.setOriginalFileName(file.getName()); this.getStudyFile().setFileType(fileType); dbgLog.fine("after setFileType"); dbgLog.fine("before setFileName"); // replace extension with ".tab" if we are going to convert this to a tabular data file fileMetadata.setLabel(FileUtil.replaceExtension(this.getOriginalFileName())); dbgLog.fine("before tempsystemfilelocation"); this.setTempSystemFileLocation(file.getAbsolutePath()); this.setControlCardSystemFileLocation(controlCardTempLocation); if (controlCardType != null && !controlCardType.equals("")) { this.setControlCardType(controlCardType); } this.getStudyFile().setFileSystemName(fileSystemName); dbgLog.fine("StudyFileEditBean: contents:\n" + this.toString()); dbgLog.fine("***** within StudyFileEditBean: constructor: end *****"); } private FileMetadata fileMetadata; private StudyFile studyFile; private String originalFileName; private String tempSystemFileLocation; private String controlCardSystemFileLocation; private String controlCardType; private String rawDataTempSystemFileLocation; private String ingestedSystemFileLocation; private boolean deleteFlag; private Long sizeFormatted = null; private java.util.Map<String, String> extendedVariableLabelMap = null; public void setExtendedVariableLabelMap (Map<String,String> varLabelMap ) { extendedVariableLabelMap = varLabelMap; } public Map<String,String> getExtendedVariableLabelMap () { return extendedVariableLabelMap; } public FileMetadata getFileMetadata() { return fileMetadata; } public void setFileMetadata(FileMetadata fileMetadata) { this.fileMetadata = fileMetadata; } //end of EV additions public StudyFile getStudyFile() { return studyFile; } public void setStudyFile(StudyFile studyFile) { this.studyFile = studyFile; } public String getOriginalFileName() { return originalFileName; } public void setOriginalFileName(String originalFileName) { this.originalFileName = originalFileName; } public String getTempSystemFileLocation() { return tempSystemFileLocation; } public void setTempSystemFileLocation(String tempSystemFileLocation) { this.tempSystemFileLocation = tempSystemFileLocation; } public String getControlCardSystemFileLocation() { return controlCardSystemFileLocation; } public String getControlCardFileName() { if (controlCardSystemFileLocation != null && !controlCardSystemFileLocation.equals("")) { return (new File(controlCardSystemFileLocation)).getName(); } return null; } public void setControlCardSystemFileLocation(String controlCardSystemFileLocation) { this.controlCardSystemFileLocation = controlCardSystemFileLocation; } public String getControlCardType() { return controlCardType; } public void setControlCardType(String cct) { this.controlCardType = cct; } public String getRawDataTempSystemFileLocation() { return rawDataTempSystemFileLocation; } public void setRawDataTempSystemFileLocation(String rawDataTempSystemFileLocation) { this.rawDataTempSystemFileLocation = rawDataTempSystemFileLocation; } public String getIngestedSystemFileLocation() { return ingestedSystemFileLocation; } public void setIngestedSystemFileLocation(String ingestedSystemFileLocation) { this.ingestedSystemFileLocation = ingestedSystemFileLocation; } public boolean isDeleteFlag() { return deleteFlag; } public void setDeleteFlag(boolean deleteFlag) { this.deleteFlag = deleteFlag; } public void addFiletoStudy(Study s) { StudyFile file = this.getStudyFile(); file.setStudy(s); s.getStudyFiles().add(file); //addFileToCategory(s); // also create study file activity object StudyFileActivity sfActivity = new StudyFileActivity(); file.setStudyFileActivity(sfActivity); sfActivity.setStudyFile(file); sfActivity.setStudy(s); } public String getUserFriendlyFileType() { return FileUtil.getUserFriendlyFileType(studyFile); } //EV added for compatibility with icefaces /** * Method to return the file size as a formatted string * For example, 4000 bytes would be returned as 4kb * *@return formatted file size */ public Long getSizeFormatted() { return sizeFormatted; } public void setSizeFormatted(Long s) { sizeFormatted = s; } // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.MULTI_LINE_STYLE); // } }
true
true
public StudyFileEditBean(File file, String fileSystemName, Study study, boolean asOtherMaterial) throws IOException { dbgLog.fine("***** within StudyFileEditBean: constructor: start *****"); dbgLog.fine("reached before studyFile constructor"); String fileType = FileUtil.determineFileType(file); dbgLog.fine("return from FileUtil.determineFileType(file), fileType="+fileType); // boolean asOtherMaterial flag is to force uploading a potentially // subsettable file as a non-subsettable ("Other Material") data file. if (!asOtherMaterial && ( fileType.equals("application/x-stata") || fileType.equals("application/x-spss-por") || fileType.equals("application/x-spss-sav") ) ) { dbgLog.fine("tablularFile"); this.studyFile = new TabularDataFile(); // do not yet attach to study, as it has to be ingested } else if (!asOtherMaterial && fileType.equals("text/xml-graphml")) { dbgLog.fine("isGraphMLFile = true"); this.studyFile = new NetworkDataFile(); } else if (!asOtherMaterial && fileType.equals("")) { this.studyFile = new SpecialOtherFile(); dbgLog.fine("FITS file"); } else { this.studyFile = new OtherFile(study); } fileMetadata = new FileMetadata(); fileMetadata.setStudyFile(studyFile); this.getStudyFile().setFileType( fileType ); dbgLog.fine("reached before original filename"); this.setOriginalFileName(file.getName()); this.getStudyFile().setFileType(fileType); dbgLog.fine("after setFileType"); // not yet supported as subsettable //this.getStudyFile().getFileType().equals("application/x-rlang-transport") ); dbgLog.fine("before setFileName"); // replace extension with ".tab" if this we are going to convert this to a tabular data file fileMetadata.setLabel(this.getStudyFile() instanceof TabularDataFile ? FileUtil.replaceExtension(this.getOriginalFileName()) : this.getOriginalFileName()); dbgLog.fine("before tempsystemfilelocation"); this.setTempSystemFileLocation(file.getAbsolutePath()); this.getStudyFile().setFileSystemName(fileSystemName); dbgLog.fine("StudyFileEditBean: contents:\n" + this.toString()); dbgLog.fine("***** within StudyFileEditBean: constructor: end *****"); }
public StudyFileEditBean(File file, String fileSystemName, Study study, boolean asOtherMaterial) throws IOException { dbgLog.fine("***** within StudyFileEditBean: constructor: start *****"); dbgLog.fine("reached before studyFile constructor"); String fileType = FileUtil.determineFileType(file); dbgLog.fine("return from FileUtil.determineFileType(file), fileType="+fileType); // boolean asOtherMaterial flag is to force uploading a potentially // subsettable file as a non-subsettable ("Other Material") data file. if (!asOtherMaterial && ( fileType.equals("application/x-stata") || fileType.equals("application/x-spss-por") || fileType.equals("application/x-spss-sav") ) ) { dbgLog.fine("tablularFile"); this.studyFile = new TabularDataFile(); // do not yet attach to study, as it has to be ingested } else if (!asOtherMaterial && fileType.equals("text/xml-graphml")) { dbgLog.fine("isGraphMLFile = true"); this.studyFile = new NetworkDataFile(); } else if (!asOtherMaterial && fileType.equals("application/fits")) { this.studyFile = new SpecialOtherFile(); dbgLog.fine("FITS file"); } else { this.studyFile = new OtherFile(study); } fileMetadata = new FileMetadata(); fileMetadata.setStudyFile(studyFile); this.getStudyFile().setFileType( fileType ); dbgLog.fine("reached before original filename"); this.setOriginalFileName(file.getName()); this.getStudyFile().setFileType(fileType); dbgLog.fine("after setFileType"); // not yet supported as subsettable //this.getStudyFile().getFileType().equals("application/x-rlang-transport") ); dbgLog.fine("before setFileName"); // replace extension with ".tab" if this we are going to convert this to a tabular data file fileMetadata.setLabel(this.getStudyFile() instanceof TabularDataFile ? FileUtil.replaceExtension(this.getOriginalFileName()) : this.getOriginalFileName()); dbgLog.fine("before tempsystemfilelocation"); this.setTempSystemFileLocation(file.getAbsolutePath()); this.getStudyFile().setFileSystemName(fileSystemName); dbgLog.fine("StudyFileEditBean: contents:\n" + this.toString()); dbgLog.fine("***** within StudyFileEditBean: constructor: end *****"); }
diff --git a/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/VmListModel.java b/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/VmListModel.java index 22e6261e4..307ef38ad 100644 --- a/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/VmListModel.java +++ b/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/VmListModel.java @@ -1,2993 +1,2990 @@ package org.ovirt.engine.ui.uicommonweb.models.vms; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import org.ovirt.engine.core.common.VdcActionUtils; import org.ovirt.engine.core.common.action.AddVmFromScratchParameters; import org.ovirt.engine.core.common.action.AddVmFromTemplateParameters; import org.ovirt.engine.core.common.action.AddVmTemplateParameters; import org.ovirt.engine.core.common.action.AttachEntityToTagParameters; import org.ovirt.engine.core.common.action.ChangeDiskCommandParameters; import org.ovirt.engine.core.common.action.ChangeVMClusterParameters; import org.ovirt.engine.core.common.action.HibernateVmParameters; import org.ovirt.engine.core.common.action.MigrateVmParameters; import org.ovirt.engine.core.common.action.MigrateVmToServerParameters; import org.ovirt.engine.core.common.action.MoveVmParameters; import org.ovirt.engine.core.common.action.RemoveVmParameters; import org.ovirt.engine.core.common.action.RunVmOnceParams; import org.ovirt.engine.core.common.action.RunVmParams; import org.ovirt.engine.core.common.action.ShutdownVmParameters; import org.ovirt.engine.core.common.action.StopVmParameters; import org.ovirt.engine.core.common.action.StopVmTypeEnum; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.action.VmManagementParametersBase; import org.ovirt.engine.core.common.action.VmOperationParameterBase; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.DiskImageBase; import org.ovirt.engine.core.common.businessentities.DisplayType; import org.ovirt.engine.core.common.businessentities.MigrationSupport; import org.ovirt.engine.core.common.businessentities.Quota; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.UsbPolicy; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VmNetworkInterface; import org.ovirt.engine.core.common.businessentities.VmOsType; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.VmType; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.storage_domains; import org.ovirt.engine.core.common.businessentities.storage_pool; import org.ovirt.engine.core.common.interfaces.SearchType; import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParamenters; import org.ovirt.engine.core.common.queries.GetVmByVmIdParameters; import org.ovirt.engine.core.common.queries.SearchParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.Event; import org.ovirt.engine.core.compat.EventArgs; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NGuid; import org.ovirt.engine.core.compat.ObservableCollection; import org.ovirt.engine.core.compat.PropertyChangedEventArgs; import org.ovirt.engine.core.compat.StringFormat; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.ui.frontend.AsyncQuery; import org.ovirt.engine.ui.frontend.Frontend; import org.ovirt.engine.ui.frontend.INewAsyncCallback; import org.ovirt.engine.ui.uicommonweb.Cloner; import org.ovirt.engine.ui.uicommonweb.DataProvider; import org.ovirt.engine.ui.uicommonweb.Linq; import org.ovirt.engine.ui.uicommonweb.TagsEqualityComparer; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider; import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.ISupportSystemTreeContext; import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel; import org.ovirt.engine.ui.uicommonweb.models.Model; import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemModel; import org.ovirt.engine.ui.uicommonweb.models.configure.ChangeCDModel; import org.ovirt.engine.ui.uicommonweb.models.configure.PermissionListModel; import org.ovirt.engine.ui.uicommonweb.models.tags.TagListModel; import org.ovirt.engine.ui.uicommonweb.models.tags.TagModel; import org.ovirt.engine.ui.uicommonweb.models.userportal.AttachCdModel; import org.ovirt.engine.ui.uicompat.Assembly; import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult; import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult; import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback; import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback; import org.ovirt.engine.ui.uicompat.ResourceManager; @SuppressWarnings("unused") public class VmListModel extends ListWithDetailsModel implements ISupportSystemTreeContext { private UICommand privateNewServerCommand; public UICommand getNewServerCommand() { return privateNewServerCommand; } private void setNewServerCommand(UICommand value) { privateNewServerCommand = value; } private UICommand privateNewDesktopCommand; public UICommand getNewDesktopCommand() { return privateNewDesktopCommand; } private void setNewDesktopCommand(UICommand value) { privateNewDesktopCommand = value; } private UICommand privateEditCommand; public UICommand getEditCommand() { return privateEditCommand; } private void setEditCommand(UICommand value) { privateEditCommand = value; } private UICommand privateRemoveCommand; public UICommand getRemoveCommand() { return privateRemoveCommand; } private void setRemoveCommand(UICommand value) { privateRemoveCommand = value; } private UICommand privateRunCommand; public UICommand getRunCommand() { return privateRunCommand; } private void setRunCommand(UICommand value) { privateRunCommand = value; } private UICommand privatePauseCommand; public UICommand getPauseCommand() { return privatePauseCommand; } private void setPauseCommand(UICommand value) { privatePauseCommand = value; } private UICommand privateStopCommand; public UICommand getStopCommand() { return privateStopCommand; } private void setStopCommand(UICommand value) { privateStopCommand = value; } private UICommand privateShutdownCommand; public UICommand getShutdownCommand() { return privateShutdownCommand; } private void setShutdownCommand(UICommand value) { privateShutdownCommand = value; } private UICommand privateCancelMigrateCommand; public UICommand getCancelMigrateCommand() { return privateCancelMigrateCommand; } private void setCancelMigrateCommand(UICommand value) { privateCancelMigrateCommand = value; } private UICommand privateMigrateCommand; public UICommand getMigrateCommand() { return privateMigrateCommand; } private void setMigrateCommand(UICommand value) { privateMigrateCommand = value; } private UICommand privateNewTemplateCommand; public UICommand getNewTemplateCommand() { return privateNewTemplateCommand; } private void setNewTemplateCommand(UICommand value) { privateNewTemplateCommand = value; } private UICommand privateRunOnceCommand; public UICommand getRunOnceCommand() { return privateRunOnceCommand; } private void setRunOnceCommand(UICommand value) { privateRunOnceCommand = value; } private UICommand privateExportCommand; public UICommand getExportCommand() { return privateExportCommand; } private void setExportCommand(UICommand value) { privateExportCommand = value; } private UICommand privateMoveCommand; public UICommand getMoveCommand() { return privateMoveCommand; } private void setMoveCommand(UICommand value) { privateMoveCommand = value; } private UICommand privateRetrieveIsoImagesCommand; public UICommand getRetrieveIsoImagesCommand() { return privateRetrieveIsoImagesCommand; } private void setRetrieveIsoImagesCommand(UICommand value) { privateRetrieveIsoImagesCommand = value; } private UICommand privateGuideCommand; public UICommand getGuideCommand() { return privateGuideCommand; } private void setGuideCommand(UICommand value) { privateGuideCommand = value; } private UICommand privateChangeCdCommand; public UICommand getChangeCdCommand() { return privateChangeCdCommand; } private void setChangeCdCommand(UICommand value) { privateChangeCdCommand = value; } private UICommand privateAssignTagsCommand; public UICommand getAssignTagsCommand() { return privateAssignTagsCommand; } private void setAssignTagsCommand(UICommand value) { privateAssignTagsCommand = value; } private Model errorWindow; public Model getErrorWindow() { return errorWindow; } public void setErrorWindow(Model value) { if (errorWindow != value) { errorWindow = value; OnPropertyChanged(new PropertyChangedEventArgs("ErrorWindow")); } } private ConsoleModel defaultConsoleModel; public ConsoleModel getDefaultConsoleModel() { return defaultConsoleModel; } public void setDefaultConsoleModel(ConsoleModel value) { if (defaultConsoleModel != value) { defaultConsoleModel = value; OnPropertyChanged(new PropertyChangedEventArgs("DefaultConsoleModel")); } } private ConsoleModel additionalConsoleModel; public ConsoleModel getAdditionalConsoleModel() { return additionalConsoleModel; } public void setAdditionalConsoleModel(ConsoleModel value) { if (additionalConsoleModel != value) { additionalConsoleModel = value; OnPropertyChanged(new PropertyChangedEventArgs("AdditionalConsoleModel")); } } private boolean hasAdditionalConsoleModel; public boolean getHasAdditionalConsoleModel() { return hasAdditionalConsoleModel; } public void setHasAdditionalConsoleModel(boolean value) { if (hasAdditionalConsoleModel != value) { hasAdditionalConsoleModel = value; OnPropertyChanged(new PropertyChangedEventArgs("HasAdditionalConsoleModel")); } } public ObservableCollection<ChangeCDModel> isoImages; public ObservableCollection<ChangeCDModel> getIsoImages() { return isoImages; } private void setIsoImages(ObservableCollection<ChangeCDModel> value) { if ((isoImages == null && value != null) || (isoImages != null && !isoImages.equals(value))) { isoImages = value; OnPropertyChanged(new PropertyChangedEventArgs("IsoImages")); } } // get { return SelectedItems == null ? new object[0] : SelectedItems.Cast<VM>().Select(a => // a.vm_guid).Cast<object>().ToArray(); } protected Object[] getSelectedKeys() { if (getSelectedItems() == null) { return new Object[0]; } Object[] keys = new Object[getSelectedItems().size()]; for (int i = 0; i < getSelectedItems().size(); i++) { keys[i] = ((VM) getSelectedItems().get(i)).getId(); } return keys; } private Object privateGuideContext; public Object getGuideContext() { return privateGuideContext; } public void setGuideContext(Object value) { privateGuideContext = value; } private VM privatecurrentVm; public VM getcurrentVm() { return privatecurrentVm; } public void setcurrentVm(VM value) { privatecurrentVm = value; } private final java.util.HashMap<Guid, java.util.ArrayList<ConsoleModel>> cachedConsoleModels; private java.util.ArrayList<String> privateCustomPropertiesKeysList; private java.util.ArrayList<String> getCustomPropertiesKeysList() { return privateCustomPropertiesKeysList; } private void setCustomPropertiesKeysList(java.util.ArrayList<String> value) { privateCustomPropertiesKeysList = value; } public VmListModel() { setTitle("Virtual Machines"); setDefaultSearchString("Vms:"); setSearchString(getDefaultSearchString()); cachedConsoleModels = new java.util.HashMap<Guid, java.util.ArrayList<ConsoleModel>>(); setNewServerCommand(new UICommand("NewServer", this)); setNewDesktopCommand(new UICommand("NewDesktop", this)); setEditCommand(new UICommand("Edit", this)); setRemoveCommand(new UICommand("Remove", this)); setRunCommand(new UICommand("Run", this, true)); setPauseCommand(new UICommand("Pause", this)); setStopCommand(new UICommand("Stop", this)); setShutdownCommand(new UICommand("Shutdown", this)); setMigrateCommand(new UICommand("Migrate", this)); setCancelMigrateCommand(new UICommand("CancelMigration", this)); setNewTemplateCommand(new UICommand("NewTemplate", this)); setRunOnceCommand(new UICommand("RunOnce", this)); setExportCommand(new UICommand("Export", this)); setMoveCommand(new UICommand("Move", this)); setGuideCommand(new UICommand("Guide", this)); setRetrieveIsoImagesCommand(new UICommand("RetrieveIsoImages", this)); setChangeCdCommand(new UICommand("ChangeCD", this)); setAssignTagsCommand(new UICommand("AssignTags", this)); setIsoImages(new ObservableCollection<ChangeCDModel>()); ChangeCDModel tempVar = new ChangeCDModel(); tempVar.setTitle("Retrieving CDs..."); getIsoImages().add(tempVar); UpdateActionAvailability(); getSearchNextPageCommand().setIsAvailable(true); getSearchPreviousPageCommand().setIsAvailable(true); AsyncDataProvider.GetCustomPropertiesList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmListModel model = (VmListModel) target; if (returnValue != null) { String[] array = ((String) returnValue).split("[;]", -1); model.setCustomPropertiesKeysList(new java.util.ArrayList<String>()); for (String s : array) { model.getCustomPropertiesKeysList().add(s); } } } })); } private void AssignTags() { if (getWindow() != null) { return; } TagListModel model = new TagListModel(); setWindow(model); model.setTitle("Assign Tags"); model.setHashName("assign_tags_vms"); GetAttachedTagsToSelectedVMs(model); UICommand tempVar = new UICommand("OnAssignTags", this); tempVar.setTitle("OK"); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle("Cancel"); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } public java.util.Map<Guid, Boolean> attachedTagsToEntities; public java.util.ArrayList<org.ovirt.engine.core.common.businessentities.tags> allAttachedTags; public int selectedItemsCounter; private void GetAttachedTagsToSelectedVMs(TagListModel model) { java.util.ArrayList<Guid> vmIds = new java.util.ArrayList<Guid>(); for (Object item : getSelectedItems()) { VM vm = (VM) item; vmIds.add(vm.getId()); } attachedTagsToEntities = new java.util.HashMap<Guid, Boolean>(); allAttachedTags = new java.util.ArrayList<org.ovirt.engine.core.common.businessentities.tags>(); selectedItemsCounter = 0; for (Guid id : vmIds) { AsyncDataProvider.GetAttachedTagsToVm(new AsyncQuery(new Object[] { this, model }, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { Object[] array = (Object[]) target; VmListModel vmListModel = (VmListModel) array[0]; TagListModel tagListModel = (TagListModel) array[1]; vmListModel.allAttachedTags.addAll((java.util.ArrayList<org.ovirt.engine.core.common.businessentities.tags>) returnValue); vmListModel.selectedItemsCounter++; if (vmListModel.selectedItemsCounter == vmListModel.getSelectedItems().size()) { PostGetAttachedTags(vmListModel, tagListModel); } } }), id); } } private void PostGetAttachedTags(VmListModel vmListModel, TagListModel tagListModel) { if (vmListModel.getLastExecutedCommand() == getAssignTagsCommand()) { // C# TO JAVA CONVERTER TODO TASK: There is no Java equivalent to LINQ queries: java.util.ArrayList<org.ovirt.engine.core.common.businessentities.tags> attachedTags = Linq.Distinct(vmListModel.allAttachedTags, new TagsEqualityComparer()); for (org.ovirt.engine.core.common.businessentities.tags tag : attachedTags) { int count = 0; for (org.ovirt.engine.core.common.businessentities.tags tag2 : vmListModel.allAttachedTags) { if (tag2.gettag_id().equals(tag.gettag_id())) { count++; } } vmListModel.attachedTagsToEntities.put(tag.gettag_id(), count == vmListModel.getSelectedItems().size()); } tagListModel.setAttachedTagsToEntities(vmListModel.attachedTagsToEntities); } else if (StringHelper.stringsEqual(vmListModel.getLastExecutedCommand().getName(), "OnAssignTags")) { vmListModel.PostOnAssignTags(tagListModel.getAttachedTagsToEntities()); } } private void OnAssignTags() { TagListModel model = (TagListModel) getWindow(); GetAttachedTagsToSelectedVMs(model); } public void PostOnAssignTags(java.util.Map<Guid, Boolean> attachedTags) { TagListModel model = (TagListModel) getWindow(); java.util.ArrayList<Guid> vmIds = new java.util.ArrayList<Guid>(); for (Object item : getSelectedItems()) { VM vm = (VM) item; vmIds.add(vm.getId()); } // prepare attach/detach lists java.util.ArrayList<Guid> tagsToAttach = new java.util.ArrayList<Guid>(); java.util.ArrayList<Guid> tagsToDetach = new java.util.ArrayList<Guid>(); if (model.getItems() != null && ((java.util.ArrayList<TagModel>) model.getItems()).size() > 0) { java.util.ArrayList<TagModel> tags = (java.util.ArrayList<TagModel>) model.getItems(); TagModel rootTag = tags.get(0); TagModel.RecursiveEditAttachDetachLists(rootTag, attachedTags, tagsToAttach, tagsToDetach); } java.util.ArrayList<VdcActionParametersBase> parameters = new java.util.ArrayList<VdcActionParametersBase>(); for (Guid a : tagsToAttach) { parameters.add(new AttachEntityToTagParameters(a, vmIds)); } Frontend.RunMultipleAction(VdcActionType.AttachVmsToTag, parameters); parameters = new java.util.ArrayList<VdcActionParametersBase>(); for (Guid a : tagsToDetach) { parameters.add(new AttachEntityToTagParameters(a, vmIds)); } Frontend.RunMultipleAction(VdcActionType.DetachVmFromTag, parameters); Cancel(); } private void Guide() { VmGuideModel model = new VmGuideModel(); setWindow(model); model.setTitle("New Virtual Machine - Guide Me"); model.setHashName("new_virtual_machine_-_guide_me"); if (getGuideContext() == null) { VM vm = (VM) getSelectedItem(); setGuideContext(vm.getId()); } AsyncDataProvider.GetVmById(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmListModel vmListModel = (VmListModel) target; VmGuideModel model = (VmGuideModel) vmListModel.getWindow(); model.setEntity((VM) returnValue); UICommand tempVar = new UICommand("Cancel", vmListModel); tempVar.setTitle("Configure Later"); tempVar.setIsDefault(true); tempVar.setIsCancel(true); model.getCommands().add(tempVar); } }), (Guid) getGuideContext()); } @Override protected void InitDetailModels() { super.InitDetailModels(); ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>(); list.add(new VmGeneralModel()); list.add(new VmInterfaceListModel()); list.add(new VmDiskListModel()); list.add(new VmSnapshotListModel()); list.add(new VmEventListModel()); list.add(new VmAppListModel()); list.add(new PermissionListModel()); setDetailModels(list); } @Override public boolean IsSearchStringMatch(String searchString) { return searchString.trim().toLowerCase().startsWith("vm"); } @Override protected void SyncSearch() { SearchParameters tempVar = new SearchParameters(getSearchString(), SearchType.VM); tempVar.setMaxCount(getSearchPageSize()); super.SyncSearch(VdcQueryType.Search, tempVar); } @Override protected void AsyncSearch() { super.AsyncSearch(); setAsyncResult(Frontend.RegisterSearch(getSearchString(), SearchType.VM, getSearchPageSize())); setItems(getAsyncResult().getData()); } private void UpdateConsoleModels() { java.util.List tempVar = getSelectedItems(); java.util.List selectedItems = (tempVar != null) ? tempVar : new java.util.ArrayList(); Object tempVar2 = getSelectedItem(); VM vm = (VM) ((tempVar2 instanceof VM) ? tempVar2 : null); if (vm == null || selectedItems.size() > 1) { setDefaultConsoleModel(null); setAdditionalConsoleModel(null); setHasAdditionalConsoleModel(false); } else { if (!cachedConsoleModels.containsKey(vm.getId())) { SpiceConsoleModel spiceConsoleModel = new SpiceConsoleModel(); spiceConsoleModel.getErrorEvent().addListener(this); VncConsoleModel vncConsoleModel = new VncConsoleModel(); RdpConsoleModel rdpConsoleModel = new RdpConsoleModel(); cachedConsoleModels.put(vm.getId(), new java.util.ArrayList<ConsoleModel>(java.util.Arrays.asList(new ConsoleModel[] { spiceConsoleModel, vncConsoleModel, rdpConsoleModel }))); } java.util.ArrayList<ConsoleModel> cachedModels = cachedConsoleModels.get(vm.getId()); for (ConsoleModel a : cachedModels) { a.setEntity(null); a.setEntity(vm); } setDefaultConsoleModel(vm.getdisplay_type() == DisplayType.vnc ? cachedModels.get(1) : cachedModels.get(0)); if (DataProvider.IsWindowsOsType(vm.getvm_os())) { for (ConsoleModel a : cachedModels) { if (a instanceof RdpConsoleModel) { setAdditionalConsoleModel(a); break; } } setHasAdditionalConsoleModel(true); } else { setAdditionalConsoleModel(null); setHasAdditionalConsoleModel(false); } } } public java.util.ArrayList<ConsoleModel> GetConsoleModelsByVmGuid(Guid vmGuid) { if (cachedConsoleModels != null && cachedConsoleModels.containsKey(vmGuid)) { return cachedConsoleModels.get(vmGuid); } return null; } private void NewDesktop() { NewInternal(VmType.Desktop); } private void NewServer() { NewInternal(VmType.Server); } private void NewInternal(VmType vmType) { if (getWindow() != null) { return; } UnitVmModel model = new UnitVmModel(new NewVmModelBehavior()); model.setTitle(StringFormat.format("New %1$s Virtual Machine", vmType == VmType.Server ? "Server" : "Desktop")); model.setHashName("new_" + (vmType == VmType.Server ? "server" : "desktop")); model.setIsNew(true); model.setVmType(vmType); model.setCustomPropertiesKeysList(getCustomPropertiesKeysList()); setWindow(model); model.Initialize(getSystemTreeSelectedItem()); // Ensures that the default provisioning is "Clone" for a new server and "Thin" for a new desktop. boolean selectValue = model.getVmType() == VmType.Server; model.getProvisioning().setEntity(selectValue); UICommand tempVar = new UICommand("OnSave", this); tempVar.setTitle("OK"); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle("Cancel"); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } private void Edit() { VM vm = (VM) getSelectedItem(); if (vm == null) { return; } if (getWindow() != null) { return; } UnitVmModel model = new UnitVmModel(new ExistingVmModelBehavior(vm)); model.setVmType(vm.getvm_type()); setWindow(model); model.setTitle(StringFormat.format("Edit %1$s Virtual Machine", vm.getvm_type() == VmType.Server ? "Server" : "Desktop")); model.setHashName("edit_" + (vm.getvm_type() == VmType.Server ? "server" : "desktop")); model.setCustomPropertiesKeysList(getCustomPropertiesKeysList()); model.Initialize(this.getSystemTreeSelectedItem()); // TODO: // VDSGroup cluster = null; // if (model.Cluster.Items == null) // { // model.Commands.Add( // new UICommand("Cancel", this) // { // Title = "Cancel", // IsCancel = true // }); // return; // } UICommand tempVar = new UICommand("OnSave", this); tempVar.setTitle("OK"); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle("Cancel"); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } private void remove() { if (getWindow() != null) { return; } ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle("Remove Virtual Machine(s)"); model.setHashName("remove_virtual_machine"); model.setMessage("Virtual Machine(s)"); // model.Items = SelectedItems.Cast<VM>().Select(a => a.vm_name); java.util.ArrayList<String> list = new java.util.ArrayList<String>(); for (Object selectedItem : getSelectedItems()) { VM a = (VM) selectedItem; list.add(a.getvm_name()); } model.setItems(list); UICommand tempVar = new UICommand("OnRemove", this); tempVar.setTitle("OK"); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle("Cancel"); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } private void Move() { VM vm = (VM) getSelectedItem(); if (vm == null) { return; } if (getWindow() != null) { return; } MoveDiskModel model = new MoveDiskModel(vm); setWindow(model); model.setTitle("Move Virtual Machine"); model.setHashName("move_virtual_machine"); model.setIsSourceStorageDomainNameAvailable(true); model.setEntity(this); model.StartProgress(null); AsyncDataProvider.GetVmDiskList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmListModel vmListModel = (VmListModel) target; MoveDiskModel moveDiskModel = (MoveDiskModel) vmListModel.getWindow(); LinkedList<DiskImage> disks = (LinkedList<DiskImage>) returnValue; ArrayList<DiskImage> diskImages = new ArrayList<DiskImage>(); diskImages.addAll(disks); moveDiskModel.init(diskImages); } }), vm.getId(), true); } private void Export() { VM vm = (VM) getSelectedItem(); if (vm == null) { return; } if (getWindow() != null) { return; } ExportVmModel model = new ExportVmModel(); setWindow(model); model.setTitle("Export Virtual Machine"); model.setHashName("export_virtual_machine"); AsyncDataProvider.GetStorageDomainList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmListModel vmListModel = (VmListModel) target; java.util.ArrayList<storage_domains> storageDomains = (java.util.ArrayList<storage_domains>) returnValue; java.util.ArrayList<storage_domains> filteredStorageDomains = new java.util.ArrayList<storage_domains>(); for (storage_domains a : storageDomains) { if (a.getstorage_domain_type() == StorageDomainType.ImportExport) { filteredStorageDomains.add(a); } } vmListModel.PostExportGetStorageDomainList(filteredStorageDomains); } }), vm.getstorage_pool_id()); } private void PostExportGetStorageDomainList(java.util.ArrayList<storage_domains> storageDomains) { ExportVmModel model = (ExportVmModel) getWindow(); model.getStorage().setItems(storageDomains); model.getStorage().setSelectedItem(Linq.FirstOrDefault(storageDomains)); boolean noActiveStorage = true; for (storage_domains a : storageDomains) { if (a.getstatus() == StorageDomainStatus.Active) { noActiveStorage = false; break; } } if (SelectedVmsOnDifferentDataCenters()) { model.getCollapseSnapshots().setIsChangable(false); model.getForceOverride().setIsChangable(false); model.setMessage("Virtual Machines reside on several Data Centers. Make sure the exported Virtual Machines reside on the same Data Center."); UICommand tempVar = new UICommand("Cancel", this); tempVar.setTitle("Close"); tempVar.setIsDefault(true); tempVar.setIsCancel(true); model.getCommands().add(tempVar); } else if (storageDomains.isEmpty()) { model.getCollapseSnapshots().setIsChangable(false); model.getForceOverride().setIsChangable(false); model.setMessage("There is no Export Domain to Backup the Virtual Machine into. Attach an Export Domain to the Virtual Machine(s) Data Center."); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle("Close"); tempVar2.setIsDefault(true); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } else if (noActiveStorage) { model.getCollapseSnapshots().setIsChangable(false); model.getForceOverride().setIsChangable(false); model.setMessage("The relevant Export Domain in not active. Please activate it."); UICommand tempVar3 = new UICommand("Cancel", this); tempVar3.setTitle("Close"); tempVar3.setIsDefault(true); tempVar3.setIsCancel(true); model.getCommands().add(tempVar3); } else { showWarningOnExistingVms(model); UICommand tempVar4 = new UICommand("OnExport", this); tempVar4.setTitle("OK"); tempVar4.setIsDefault(true); model.getCommands().add(tempVar4); UICommand tempVar5 = new UICommand("Cancel", this); tempVar5.setTitle("Cancel"); tempVar5.setIsCancel(true); model.getCommands().add(tempVar5); } } private void showWarningOnExistingVms(ExportVmModel model) { Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId(); AsyncDataProvider.GetDataCentersByStorageDomain(new AsyncQuery(new Object[] { this, model }, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { Object[] array = (Object[]) target; VmListModel vmListModel = (VmListModel) array[0]; ExportVmModel exportVmModel = (ExportVmModel) array[1]; java.util.ArrayList<storage_pool> storagePools = (java.util.ArrayList<storage_pool>) returnValue; vmListModel.PostShowWarningOnExistingVms(exportVmModel, storagePools); } }), storageDomainId); } private void PostShowWarningOnExistingVms(ExportVmModel exportModel, java.util.List<storage_pool> storagePools) { storage_pool storagePool = storagePools.size() > 0 ? storagePools.get(0) : null; String existingVMs = ""; if (storagePool != null) { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object ReturnValue) { VmListModel vmListModel = (VmListModel) model; ExportVmModel exportModel1 = (ExportVmModel) vmListModel.getWindow(); String existingVMs = ""; if (ReturnValue != null) { for (Object selectedItem : vmListModel.getSelectedItems()) { VM vm = (VM) selectedItem; VM foundVm = null; VdcQueryReturnValue returnValue = (VdcQueryReturnValue) ReturnValue; for (VM a : (java.util.ArrayList<VM>) returnValue.getReturnValue()) { if (a.getId().equals(vm.getId())) { foundVm = a; break; } } if (foundVm != null) { existingVMs += "\u2022 " + vm.getvm_name() + "\n"; } } } if (!StringHelper.isNullOrEmpty(existingVMs)) { exportModel1.setMessage(StringFormat.format("VM(s):\n%1$s already exist on the target Export Domain. If you want to override them, please check the 'Force Override' check-box.", existingVMs)); } } }; Guid storageDomainId = ((storage_domains) exportModel.getStorage().getSelectedItem()).getId(); GetAllFromExportDomainQueryParamenters tempVar = new GetAllFromExportDomainQueryParamenters(storagePool.getId(), storageDomainId); tempVar.setGetAll(true); Frontend.RunQuery(VdcQueryType.GetVmsFromExportDomain, tempVar, _asyncQuery); } } private boolean SelectedVmsOnDifferentDataCenters() { java.util.ArrayList<VM> vms = new java.util.ArrayList<VM>(); for (Object selectedItem : getSelectedItems()) { VM a = (VM) selectedItem; vms.add(a); } java.util.Map<NGuid, java.util.ArrayList<VM>> t = new java.util.HashMap<NGuid, java.util.ArrayList<VM>>(); for (VM a : vms) { if (!t.containsKey(a.getstorage_pool_id())) { t.put(a.getstorage_pool_id(), new java.util.ArrayList<VM>()); } java.util.ArrayList<VM> list = t.get(a.getstorage_pool_id()); list.add(a); } return t.size() > 1; } private void GetTemplatesNotPresentOnExportDomain() { ExportVmModel model = (ExportVmModel) getWindow(); Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId(); AsyncDataProvider.GetDataCentersByStorageDomain(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmListModel vmListModel = (VmListModel) target; java.util.ArrayList<storage_pool> storagePools = (java.util.ArrayList<storage_pool>) returnValue; storage_pool storagePool = storagePools.size() > 0 ? storagePools.get(0) : null; vmListModel.PostGetTemplatesNotPresentOnExportDomain(storagePool); } }), storageDomainId); } private void PostGetTemplatesNotPresentOnExportDomain(storage_pool storagePool) { ExportVmModel model = (ExportVmModel) getWindow(); Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId(); if (storagePool != null) { AsyncDataProvider.GetAllTemplatesFromExportDomain(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmListModel vmListModel = (VmListModel) target; java.util.HashMap<VmTemplate, java.util.ArrayList<DiskImage>> templatesDiskSet = (java.util.HashMap<VmTemplate, java.util.ArrayList<DiskImage>>) returnValue; java.util.HashMap<String, java.util.ArrayList<String>> templateDic = new java.util.HashMap<String, java.util.ArrayList<String>>(); // check if relevant templates are already there for (Object selectedItem : vmListModel.getSelectedItems()) { VM vm = (VM) selectedItem; boolean hasMatch = false; for (VmTemplate a : templatesDiskSet.keySet()) { if (vm.getvmt_guid().equals(a.getId())) { hasMatch = true; break; } } if (!vm.getvmt_guid().equals(NGuid.Empty) && !hasMatch) { if (!templateDic.containsKey(vm.getvmt_name())) { templateDic.put(vm.getvmt_name(), new java.util.ArrayList<String>()); } templateDic.get(vm.getvmt_name()).add(vm.getvm_name()); } } String tempStr; java.util.ArrayList<String> tempList; java.util.ArrayList<String> missingTemplates = new java.util.ArrayList<String>(); for (java.util.Map.Entry<String, java.util.ArrayList<String>> keyValuePair : templateDic.entrySet()) { tempList = keyValuePair.getValue(); tempStr = "Template " + keyValuePair.getKey() + " (for "; int i; for (i = 0; i < tempList.size() - 1; i++) { tempStr += tempList.get(i) + ", "; } tempStr += tempList.get(i) + ")"; missingTemplates.add(tempStr); } vmListModel.PostExportGetMissingTemplates(missingTemplates); } }), storagePool.getId(), storageDomainId); } } private void PostExportGetMissingTemplates(java.util.ArrayList<String> missingTemplatesFromVms) { ExportVmModel model = (ExportVmModel) getWindow(); Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId(); java.util.ArrayList<VdcActionParametersBase> parameters = new java.util.ArrayList<VdcActionParametersBase>(); model.StopProgress(); for (Object a : getSelectedItems()) { VM vm = (VM) a; MoveVmParameters parameter = new MoveVmParameters(vm.getId(), storageDomainId); parameter.setForceOverride((Boolean) model.getForceOverride().getEntity()); parameter.setCopyCollapse((Boolean) model.getCollapseSnapshots().getEntity()); parameter.setTemplateMustExists(true); parameters.add(parameter); } if (!(Boolean) model.getCollapseSnapshots().getEntity()) { if ((missingTemplatesFromVms == null || missingTemplatesFromVms.size() > 0)) { ConfirmationModel confirmModel = new ConfirmationModel(); setConfirmWindow(confirmModel); confirmModel.setTitle("Template(s) not Found on Export Domain"); confirmModel.setHashName("template_not_found_on_export_domain"); confirmModel.setMessage(missingTemplatesFromVms == null ? "Could not read templates from Export Domain" : "The following templates are missing on the target Export Domain:"); confirmModel.setItems(missingTemplatesFromVms); UICommand tempVar = new UICommand("OnExportNoTemplates", this); tempVar.setTitle("OK"); tempVar.setIsDefault(true); confirmModel.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("CancelConfirmation", this); tempVar2.setTitle("Cancel"); tempVar2.setIsCancel(true); confirmModel.getCommands().add(tempVar2); } else { if (model.getProgress() != null) { return; } model.StartProgress(null); Frontend.RunMultipleAction(VdcActionType.ExportVm, parameters, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { ExportVmModel localModel = (ExportVmModel) result.getState(); localModel.StopProgress(); Cancel(); } }, model); } } else { if (model.getProgress() != null) { return; } for (VdcActionParametersBase item : parameters) { MoveVmParameters parameter = (MoveVmParameters) item; parameter.setTemplateMustExists(false); } model.StartProgress(null); Frontend.RunMultipleAction(VdcActionType.ExportVm, parameters, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { ExportVmModel localModel = (ExportVmModel) result.getState(); localModel.StopProgress(); Cancel(); } }, model); } } public void OnExport() { ExportVmModel model = (ExportVmModel) getWindow(); Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId(); if (!model.Validate()) { return; } model.StartProgress(null); GetTemplatesNotPresentOnExportDomain(); } private void OnExportNoTemplates() { ExportVmModel model = (ExportVmModel) getWindow(); Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId(); if (model.getProgress() != null) { return; } java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { VM a = (VM) item; MoveVmParameters parameters = new MoveVmParameters(a.getId(), storageDomainId); parameters.setForceOverride((Boolean) model.getForceOverride().getEntity()); parameters.setCopyCollapse((Boolean) model.getCollapseSnapshots().getEntity()); parameters.setTemplateMustExists(false); list.add(parameters); } model.StartProgress(null); Frontend.RunMultipleAction(VdcActionType.ExportVm, list, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { ExportVmModel localModel = (ExportVmModel) result.getState(); localModel.StopProgress(); Cancel(); } }, model); } private void RunOnce() { VM vm = (VM) getSelectedItem(); RunOnceModel model = new RunOnceModel(); setWindow(model); model.setTitle("Run Virtual Machine(s)"); model.setHashName("run_virtual_machine"); model.getAttachIso().setEntity(false); model.getAttachFloppy().setEntity(false); model.getRunAsStateless().setEntity(vm.getis_stateless()); model.getRunAndPause().setEntity(false); model.setHwAcceleration(true); // passing Kernel parameters model.getKernel_parameters().setEntity(vm.getkernel_params()); model.getKernel_path().setEntity(vm.getkernel_url()); model.getInitrd_path().setEntity(vm.getinitrd_url()); // Custom Properties model.getCustomProperties().setEntity(vm.getCustomProperties()); model.setCustomPropertiesKeysList(getCustomPropertiesKeysList()); model.setIsLinux_Unassign_UnknownOS(DataProvider.IsLinuxOsType(vm.getvm_os()) || vm.getvm_os() == VmOsType.Unassigned || vm.getvm_os() == VmOsType.Other); model.getIsLinuxOptionsAvailable().setEntity(model.getIsLinux_Unassign_UnknownOS()); model.setIsWindowsOS(DataProvider.IsWindowsOsType(vm.getvm_os())); model.getIsVmFirstRun().setEntity(!vm.getis_initialized()); model.getSysPrepDomainName().setSelectedItem(vm.getvm_domain()); RunOnceUpdateDisplayProtocols(vm); RunOnceUpdateFloppy(vm, new java.util.ArrayList<String>()); RunOnceUpdateImages(vm); RunOnceUpdateDomains(); RunOnceUpdateBootSequence(vm); UICommand tempVar = new UICommand("OnRunOnce", this); tempVar.setTitle("OK"); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle("Cancel"); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } private void RunOnceUpdateDisplayProtocols(VM vm) { RunOnceModel model = (RunOnceModel) getWindow(); EntityModel tempVar = new EntityModel(); tempVar.setTitle("VNC"); tempVar.setEntity(DisplayType.vnc); EntityModel vncProtocol = tempVar; EntityModel tempVar2 = new EntityModel(); tempVar2.setTitle("Spice"); tempVar2.setEntity(DisplayType.qxl); EntityModel qxlProtocol = tempVar2; boolean isVncSelected = vm.getdefault_display_type() == DisplayType.vnc; model.getDisplayConsole_Vnc_IsSelected().setEntity(isVncSelected); model.getDisplayConsole_Spice_IsSelected().setEntity(!isVncSelected); java.util.ArrayList<EntityModel> items = new java.util.ArrayList<EntityModel>(); items.add(vncProtocol); items.add(qxlProtocol); model.getDisplayProtocol().setItems(items); model.getDisplayProtocol().setSelectedItem(isVncSelected ? vncProtocol : qxlProtocol); } private void RunOnceUpdateBootSequence(VM vm) { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object ReturnValue) { VmListModel vmListModel = (VmListModel) model; RunOnceModel runOnceModel = (RunOnceModel) vmListModel.getWindow(); boolean hasNics = ((java.util.ArrayList<VmNetworkInterface>) ((VdcQueryReturnValue) ReturnValue).getReturnValue()).size() > 0; if (!hasNics) { BootSequenceModel bootSequenceModel = runOnceModel.getBootSequence(); bootSequenceModel.getNetworkOption().setIsChangable(false); bootSequenceModel.getNetworkOption() .getChangeProhibitionReasons() .add("Virtual Machine must have at least one network interface defined to boot from network."); } } }; Frontend.RunQuery(VdcQueryType.GetVmInterfacesByVmId, new GetVmByVmIdParameters(vm.getId()), _asyncQuery); } private void RunOnceUpdateDomains() { RunOnceModel model = (RunOnceModel) getWindow(); // Update Domain list AsyncDataProvider.GetDomainList(new AsyncQuery(model, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { RunOnceModel runOnceModel = (RunOnceModel) target; java.util.List<String> domains = (java.util.List<String>) returnValue; String oldDomain = (String) runOnceModel.getSysPrepDomainName().getSelectedItem(); if (oldDomain != null && !oldDomain.equals("") && !domains.contains(oldDomain)) { domains.add(0, oldDomain); } runOnceModel.getSysPrepDomainName().setItems(domains); String selectedDomain = (oldDomain != null) ? oldDomain : Linq.FirstOrDefault(domains); if (!StringHelper.stringsEqual(selectedDomain, "")) { runOnceModel.getSysPrepDomainName().setSelectedItem(selectedDomain); } } }), true); } public void RunOnceUpdateFloppy(VM vm, java.util.ArrayList<String> images) { RunOnceModel model = (RunOnceModel) getWindow(); if (DataProvider.IsWindowsOsType(vm.getvm_os())) { // Add a pseudo floppy disk image used for Windows' sysprep. if (!vm.getis_initialized()) { images.add(0, "[sysprep]"); model.getAttachFloppy().setEntity(true); } else { images.add("[sysprep]"); } } model.getFloppyImage().setItems(images); if (model.getFloppyImage().getIsChangable() && model.getFloppyImage().getSelectedItem() == null) { model.getFloppyImage().setSelectedItem(Linq.FirstOrDefault(images)); } } private void RunOnceUpdateImages(VM vm) { AsyncQuery _asyncQuery0 = new AsyncQuery(); _asyncQuery0.setModel(this); _asyncQuery0.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model0, Object result0) { if (result0 != null) { storage_domains isoDomain = (storage_domains) result0; VmListModel vmListModel = (VmListModel) model0; AsyncQuery _asyncQuery1 = new AsyncQuery(); _asyncQuery1.setModel(vmListModel); _asyncQuery1.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model1, Object result) { VmListModel vmListModel1 = (VmListModel) model1; RunOnceModel runOnceModel = (RunOnceModel) vmListModel1.getWindow(); java.util.ArrayList<String> images = (java.util.ArrayList<String>) result; runOnceModel.getIsoImage().setItems(images); if (runOnceModel.getIsoImage().getIsChangable() && runOnceModel.getIsoImage().getSelectedItem() == null) { runOnceModel.getIsoImage().setSelectedItem(Linq.FirstOrDefault(images)); } } }; AsyncDataProvider.GetIrsImageList(_asyncQuery1, isoDomain.getId(), false); AsyncQuery _asyncQuery2 = new AsyncQuery(); _asyncQuery2.setModel(vmListModel); _asyncQuery2.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model2, Object result) { VmListModel vmListModel2 = (VmListModel) model2; VM selectedVM = (VM) vmListModel2.getSelectedItem(); java.util.ArrayList<String> images = (java.util.ArrayList<String>) result; vmListModel2.RunOnceUpdateFloppy(selectedVM, images); } }; AsyncDataProvider.GetFloppyImageList(_asyncQuery2, isoDomain.getId(), false); } } }; AsyncDataProvider.GetIsoDomainByDataCenterId(_asyncQuery0, vm.getstorage_pool_id()); } private void OnRunOnce() { VM vm = (VM) getSelectedItem(); if (vm == null) { Cancel(); return; } RunOnceModel model = (RunOnceModel) getWindow(); if (!model.Validate()) { return; } BootSequenceModel bootSequenceModel = model.getBootSequence(); RunVmOnceParams tempVar = new RunVmOnceParams(); tempVar.setVmId(vm.getId()); tempVar.setBootSequence(bootSequenceModel.getSequence()); tempVar.setDiskPath((Boolean) model.getAttachIso().getEntity() ? (String) model.getIsoImage().getSelectedItem() : ""); tempVar.setFloppyPath(model.getFloppyImagePath()); tempVar.setKvmEnable(model.getHwAcceleration()); tempVar.setRunAndPause((Boolean) model.getRunAndPause().getEntity()); tempVar.setAcpiEnable(true); tempVar.setRunAsStateless((Boolean) model.getRunAsStateless().getEntity()); tempVar.setReinitialize(model.getReinitialize()); tempVar.setCustomProperties((String) model.getCustomProperties().getEntity()); RunVmOnceParams param = tempVar; // kernel params if (model.getKernel_path().getEntity() != null) { param.setkernel_url((String) model.getKernel_path().getEntity()); } if (model.getKernel_parameters().getEntity() != null) { param.setkernel_params((String) model.getKernel_parameters().getEntity()); } if (model.getInitrd_path().getEntity() != null) { param.setinitrd_url((String) model.getInitrd_path().getEntity()); } // Sysprep params if (model.getSysPrepDomainName().getSelectedItem() != null) { param.setSysPrepDomainName(model.getSysPrepSelectedDomainName().getEntity().equals("") ? (String) model.getSysPrepSelectedDomainName() .getEntity() : (String) model.getSysPrepDomainName().getSelectedItem()); } if (model.getSysPrepUserName().getEntity() != null) { param.setSysPrepUserName((String) model.getSysPrepUserName().getEntity()); } if (model.getSysPrepPassword().getEntity() != null) { param.setSysPrepPassword((String) model.getSysPrepPassword().getEntity()); } EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem(); param.setUseVnc((DisplayType) displayProtocolSelectedItem.getEntity() == DisplayType.vnc); if ((Boolean) model.getDisplayConsole_Vnc_IsSelected().getEntity() || (Boolean) model.getDisplayConsole_Spice_IsSelected().getEntity()) { param.setUseVnc((Boolean) model.getDisplayConsole_Vnc_IsSelected().getEntity()); } Frontend.RunAction(VdcActionType.RunVmOnce, param, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { } }, this); Cancel(); } private void NewTemplate() { VM vm = (VM) getSelectedItem(); if (vm == null) { return; } if (getWindow() != null) { return; } UnitVmModel model = new UnitVmModel(new NewTemplateVmModelBehavior(vm)); setWindow(model); model.setTitle("New Template"); model.setHashName("new_template"); model.setIsNew(true); model.setVmType(vm.getvm_type()); model.Initialize(getSystemTreeSelectedItem()); UICommand tempVar = new UICommand("OnNewTemplate", this); tempVar.setTitle("OK"); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle("Cancel"); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } private void DisableNewTemplateModel(VmModel model, String errMessage) { model.setMessage(errMessage); model.getName().setIsChangable(false); model.getDescription().setIsChangable(false); model.getCluster().setIsChangable(false); model.getStorageDomain().setIsChangable(false); model.getIsTemplatePublic().setIsChangable(false); UICommand tempVar = new UICommand("Cancel", this); tempVar.setTitle("Close"); tempVar.setIsCancel(true); model.getCommands().add(tempVar); } private void OnNewTemplate() { UnitVmModel model = (UnitVmModel) getWindow(); VM vm = (VM) getSelectedItem(); if (vm == null) { Cancel(); return; } if (model.getProgress() != null) { return; } if (!model.Validate()) { model.setIsValid(false); } else { String name = (String) model.getName().getEntity(); // Check name unicitate. AsyncDataProvider.IsTemplateNameUnique(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmListModel vmListModel = (VmListModel) target; boolean isNameUnique = (Boolean) returnValue; if (!isNameUnique) { UnitVmModel VmModel = (UnitVmModel) vmListModel.getWindow(); VmModel.getInvalidityReasons().clear(); VmModel.getName().getInvalidityReasons().add("Name must be unique."); VmModel.getName().setIsValid(false); VmModel.setIsValid(false); } else { vmListModel.PostNameUniqueCheck(); } } }), name); } } public void PostNameUniqueCheck() { UnitVmModel model = (UnitVmModel) getWindow(); VM vm = (VM) getSelectedItem(); VM tempVar = new VM(); tempVar.setId(vm.getId()); tempVar.setvm_type(model.getVmType()); if (model.getQuota().getSelectedItem() != null) { tempVar.setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId()); } tempVar.setvm_os((VmOsType) model.getOSType().getSelectedItem()); tempVar.setnum_of_monitors((Integer) model.getNumOfMonitors().getSelectedItem()); tempVar.setvm_domain(model.getDomain().getIsAvailable() ? (String) model.getDomain().getSelectedItem() : ""); tempVar.setvm_mem_size_mb((Integer) model.getMemSize().getEntity()); tempVar.setMinAllocatedMem((Integer) model.getMinAllocatedMemory().getEntity()); tempVar.setvds_group_id(((VDSGroup) model.getCluster().getSelectedItem()).getId()); tempVar.settime_zone(model.getTimeZone().getIsAvailable() && model.getTimeZone().getSelectedItem() != null ? ((java.util.Map.Entry<String, String>) model.getTimeZone() .getSelectedItem()).getKey() : ""); tempVar.setnum_of_sockets((Integer) model.getNumOfSockets().getEntity()); tempVar.setcpu_per_socket((Integer) model.getTotalCPUCores().getEntity() / (Integer) model.getNumOfSockets().getEntity()); tempVar.setusb_policy((UsbPolicy) model.getUsbPolicy().getSelectedItem()); tempVar.setis_auto_suspend(false); tempVar.setis_stateless((Boolean) model.getIsStateless().getEntity()); tempVar.setdefault_boot_sequence(model.getBootSequence()); tempVar.setauto_startup((Boolean) model.getIsHighlyAvailable().getEntity()); tempVar.setiso_path(model.getCdImage().getIsChangable() ? (String) model.getCdImage().getSelectedItem() : ""); tempVar.setinitrd_url(vm.getinitrd_url()); tempVar.setkernel_url(vm.getkernel_url()); tempVar.setkernel_params(vm.getkernel_params()); VM newvm = tempVar; EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem(); newvm.setdefault_display_type((DisplayType) displayProtocolSelectedItem.getEntity()); EntityModel prioritySelectedItem = (EntityModel) model.getPriority().getSelectedItem(); newvm.setpriority((Integer) prioritySelectedItem.getEntity()); AddVmTemplateParameters addVmTemplateParameters = new AddVmTemplateParameters(newvm, (String) model.getName().getEntity(), (String) model.getDescription().getEntity()); addVmTemplateParameters.setPublicUse((Boolean) model.getIsTemplatePublic().getEntity()); addVmTemplateParameters.setDiskInfoDestinationMap( model.getDisksAllocationModel() .getImageToDestinationDomainMap((Boolean) model.getDisksAllocationModel() .getIsSingleStorageDomain() .getEntity())); model.StartProgress(null); Frontend.RunAction(VdcActionType.AddVmTemplate, addVmTemplateParameters, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); vmListModel.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel.Cancel(); } } }, this); } private void Migrate() { VM vm = (VM) getSelectedItem(); if (vm == null) { return; } if (getWindow() != null) { return; } MigrateModel model = new MigrateModel(); setWindow(model); model.setTitle("Migrate Virtual Machine(s)"); model.setHashName("migrate_virtual_machine"); model.setVmsOnSameCluster(true); model.setIsAutoSelect(true); model.setVmList(Linq.<VM> Cast(getSelectedItems())); AsyncDataProvider.GetUpHostListByCluster(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { VmListModel vmListModel = (VmListModel) target; vmListModel.PostMigrateGetUpHosts((java.util.ArrayList<VDS>) returnValue); } }), vm.getvds_group_name()); } private void CancelMigration() { java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { VM a = (VM) item; list.add(new VmOperationParameterBase(a.getId())); } Frontend.RunMultipleAction(VdcActionType.CancelMigrateVm, list, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed( FrontendMultipleActionAsyncResult result) { } }, null); } private void PostMigrateGetUpHosts(java.util.ArrayList<VDS> hosts) { MigrateModel model = (MigrateModel) getWindow(); NGuid run_on_vds = null; boolean allRunOnSameVds = true; for (Object item : getSelectedItems()) { VM a = (VM) item; if (!a.getvds_group_id().equals(((VM) getSelectedItems().get(0)).getvds_group_id())) { model.setVmsOnSameCluster(false); } if (run_on_vds == null) { run_on_vds = a.getrun_on_vds().getValue(); } else if (allRunOnSameVds && !run_on_vds.equals(a.getrun_on_vds().getValue())) { allRunOnSameVds = false; } } model.setIsHostSelAvailable(model.getVmsOnSameCluster() && hosts.size() > 0); if (model.getVmsOnSameCluster() && allRunOnSameVds) { VDS runOnSameVDS = null; for (VDS host : hosts) { if (host.getId().equals(run_on_vds)) { runOnSameVDS = host; } } hosts.remove(runOnSameVDS); } if (hosts.isEmpty()) { model.setIsHostSelAvailable(false); if (allRunOnSameVds) { model.setNoSelAvailable(true); UICommand tempVar = new UICommand("Cancel", this); tempVar.setTitle("Close"); tempVar.setIsDefault(true); tempVar.setIsCancel(true); model.getCommands().add(tempVar); } } else { model.getHosts().setItems(hosts); model.getHosts().setSelectedItem(Linq.FirstOrDefault(hosts)); UICommand tempVar2 = new UICommand("OnMigrate", this); tempVar2.setTitle("OK"); tempVar2.setIsDefault(true); model.getCommands().add(tempVar2); UICommand tempVar3 = new UICommand("Cancel", this); tempVar3.setTitle("Cancel"); tempVar3.setIsCancel(true); model.getCommands().add(tempVar3); } } private void OnMigrate() { MigrateModel model = (MigrateModel) getWindow(); if (model.getProgress() != null) { return; } model.StartProgress(null); if (model.getIsAutoSelect()) { java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { VM a = (VM) item; list.add(new MigrateVmParameters(true, a.getId())); } Frontend.RunMultipleAction(VdcActionType.MigrateVm, list, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { MigrateModel localModel = (MigrateModel) result.getState(); localModel.StopProgress(); Cancel(); } }, model); } else { java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { VM a = (VM) item; if (a.getrun_on_vds().getValue().equals(((VDS) model.getHosts().getSelectedItem()).getId())) { continue; } list.add(new MigrateVmToServerParameters(true, a.getId(), ((VDS) model.getHosts() .getSelectedItem()).getId())); } Frontend.RunMultipleAction(VdcActionType.MigrateVmToServer, list, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { MigrateModel localModel = (MigrateModel) result.getState(); localModel.StopProgress(); Cancel(); } }, model); } } private void Shutdown() { ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle("Shut down Virtual Machine(s)"); model.setHashName("shut_down_virtual_machine"); model.setMessage("Are you sure you want to Shut down the following Virtual Machines?"); // model.Items = SelectedItems.Cast<VM>().Select(a => a.vm_name); java.util.ArrayList<String> items = new java.util.ArrayList<String>(); for (Object item : getSelectedItems()) { VM a = (VM) item; items.add(a.getvm_name()); } model.setItems(items); UICommand tempVar = new UICommand("OnShutdown", this); tempVar.setTitle("OK"); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle("Cancel"); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } private void OnShutdown() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { VM a = (VM) item; list.add(new ShutdownVmParameters(a.getId(), true)); } model.StartProgress(null); Frontend.RunMultipleAction(VdcActionType.ShutdownVm, list, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.StopProgress(); Cancel(); } }, model); } private void stop() { ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle("Stop Virtual Machine(s)"); model.setHashName("stop_virtual_machine"); model.setMessage("Are you sure you want to Stop the following Virtual Machines?"); // model.Items = SelectedItems.Cast<VM>().Select(a => a.vm_name); java.util.ArrayList<String> items = new java.util.ArrayList<String>(); for (Object item : getSelectedItems()) { VM a = (VM) item; items.add(a.getvm_name()); } model.setItems(items); UICommand tempVar = new UICommand("OnStop", this); tempVar.setTitle("OK"); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle("Cancel"); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } private void OnStop() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { VM a = (VM) item; list.add(new StopVmParameters(a.getId(), StopVmTypeEnum.NORMAL)); } model.StartProgress(null); Frontend.RunMultipleAction(VdcActionType.StopVm, list, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.StopProgress(); Cancel(); } }, model); } private void Pause() { java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { VM a = (VM) item; list.add(new HibernateVmParameters(a.getId())); } Frontend.RunMultipleAction(VdcActionType.HibernateVm, list, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { } }, null); } private void Run() { java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { VM a = (VM) item; // use sysprep iff the vm is not initialized and vm has Win OS boolean reinitialize = !a.getis_initialized() && DataProvider.IsWindowsOsType(a.getvm_os()); RunVmParams tempVar = new RunVmParams(a.getId()); tempVar.setReinitialize(reinitialize); list.add(tempVar); } Frontend.RunMultipleAction(VdcActionType.RunVm, list, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { } }, null); } private void OnRemove() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } java.util.ArrayList<VdcActionParametersBase> list = new java.util.ArrayList<VdcActionParametersBase>(); for (Object item : getSelectedItems()) { VM a = (VM) item; list.add(new RemoveVmParameters(a.getId(), false)); } model.StartProgress(null); Frontend.RunMultipleAction(VdcActionType.RemoveVm, list, new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.StopProgress(); Cancel(); } }, model); } private void ChangeCD() { VM vm = (VM) getSelectedItem(); if (vm == null) { return; } AttachCdModel model = new AttachCdModel(); setWindow(model); model.setTitle("Change CD"); model.setHashName("change_cd"); AsyncQuery _asyncQuery1 = new AsyncQuery(); _asyncQuery1.setModel(this); _asyncQuery1.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model1, Object result1) { VmListModel vmListModel1 = (VmListModel) model1; AttachCdModel attachCdModel = (AttachCdModel) vmListModel1.getWindow(); java.util.ArrayList<String> images1 = new java.util.ArrayList<String>(java.util.Arrays.asList(new String[] { "No CDs" })); attachCdModel.getIsoImage().setItems(images1); attachCdModel.getIsoImage().setSelectedItem(Linq.FirstOrDefault(images1)); if (result1 != null) { storage_domains isoDomain = (storage_domains) result1; AsyncQuery _asyncQuery2 = new AsyncQuery(); _asyncQuery2.setModel(vmListModel1); _asyncQuery2.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model2, Object result2) { VmListModel vmListModel2 = (VmListModel) model2; AttachCdModel _attachCdModel = (AttachCdModel) vmListModel2.getWindow(); java.util.ArrayList<String> images2 = (java.util.ArrayList<String>) result2; if (images2.size() > 0) { images2.add(0, ConsoleModel.EjectLabel); _attachCdModel.getIsoImage().setItems(images2); } if (_attachCdModel.getIsoImage().getIsChangable()) { _attachCdModel.getIsoImage().setSelectedItem(Linq.FirstOrDefault(images2)); } } }; AsyncDataProvider.GetIrsImageList(_asyncQuery2, isoDomain.getId(), false); } } }; AsyncDataProvider.GetIsoDomainByDataCenterId(_asyncQuery1, vm.getstorage_pool_id()); UICommand tempVar = new UICommand("OnChangeCD", this); tempVar.setTitle("OK"); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); tempVar2.setTitle("Cancel"); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } private void OnChangeCD() { VM vm = (VM) getSelectedItem(); if (vm == null) { Cancel(); return; } AttachCdModel model = (AttachCdModel) getWindow(); if (model.getProgress() != null) { return; } String isoName = (StringHelper.stringsEqual(model.getIsoImage().getSelectedItem().toString(), ConsoleModel.EjectLabel)) ? "" : model.getIsoImage().getSelectedItem().toString(); model.StartProgress(null); Frontend.RunAction(VdcActionType.ChangeDisk, new ChangeDiskCommandParameters(vm.getId(), isoName), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { AttachCdModel attachCdModel = (AttachCdModel) result.getState(); attachCdModel.StopProgress(); Cancel(); } }, model); } private void OnSave() { UnitVmModel model = (UnitVmModel) getWindow(); VM selectedItem = (VM) getSelectedItem(); if (model.getIsNew() == false && selectedItem == null) { Cancel(); return; } setcurrentVm(model.getIsNew() ? new VM() : (VM) Cloner.clone(selectedItem)); if (!model.Validate()) { return; } String name = (String) model.getName().getEntity(); // Check name unicitate. if (!DataProvider.IsVmNameUnique(name) && name.compareToIgnoreCase(getcurrentVm().getvm_name()) != 0) { model.getName().setIsValid(false); model.getName().getInvalidityReasons().add("Name must be unique."); model.setIsGeneralTabValid(false); return; } // Save changes. VmTemplate template = (VmTemplate) model.getTemplate().getSelectedItem(); getcurrentVm().setvm_type(model.getVmType()); getcurrentVm().setvmt_guid(template.getId()); getcurrentVm().setvm_name(name); if (model.getQuota().getSelectedItem() != null) { getcurrentVm().setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId()); } getcurrentVm().setvm_os((VmOsType) model.getOSType().getSelectedItem()); getcurrentVm().setnum_of_monitors((Integer) model.getNumOfMonitors().getSelectedItem()); getcurrentVm().setvm_description((String) model.getDescription().getEntity()); getcurrentVm().setvm_domain(model.getDomain().getIsAvailable() ? (String) model.getDomain().getSelectedItem() : ""); getcurrentVm().setvm_mem_size_mb((Integer) model.getMemSize().getEntity()); getcurrentVm().setMinAllocatedMem((Integer) model.getMinAllocatedMemory().getEntity()); Guid newClusterID = ((VDSGroup) model.getCluster().getSelectedItem()).getId(); getcurrentVm().setvds_group_id(newClusterID); getcurrentVm().settime_zone((model.getTimeZone().getIsAvailable() && model.getTimeZone().getSelectedItem() != null) ? ((java.util.Map.Entry<String, String>) model.getTimeZone() .getSelectedItem()).getKey() : ""); getcurrentVm().setnum_of_sockets((Integer) model.getNumOfSockets().getEntity()); getcurrentVm().setcpu_per_socket((Integer) model.getTotalCPUCores().getEntity() / (Integer) model.getNumOfSockets().getEntity()); getcurrentVm().setusb_policy((UsbPolicy) model.getUsbPolicy().getSelectedItem()); getcurrentVm().setis_auto_suspend(false); getcurrentVm().setis_stateless((Boolean) model.getIsStateless().getEntity()); getcurrentVm().setdefault_boot_sequence(model.getBootSequence()); getcurrentVm().setiso_path(model.getCdImage().getIsChangable() ? (String) model.getCdImage().getSelectedItem() : ""); getcurrentVm().setauto_startup((Boolean) model.getIsHighlyAvailable().getEntity()); getcurrentVm().setinitrd_url((String) model.getInitrd_path().getEntity()); getcurrentVm().setkernel_url((String) model.getKernel_path().getEntity()); getcurrentVm().setkernel_params((String) model.getKernel_parameters().getEntity()); getcurrentVm().setCustomProperties((String) model.getCustomProperties().getEntity()); EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem(); getcurrentVm().setdefault_display_type((DisplayType) displayProtocolSelectedItem.getEntity()); EntityModel prioritySelectedItem = (EntityModel) model.getPriority().getSelectedItem(); getcurrentVm().setpriority((Integer) prioritySelectedItem.getEntity()); VDS defaultHost = (VDS) model.getDefaultHost().getSelectedItem(); if ((Boolean) model.getIsAutoAssign().getEntity()) { getcurrentVm().setdedicated_vm_for_vds(null); } else { getcurrentVm().setdedicated_vm_for_vds(defaultHost.getId()); } getcurrentVm().setMigrationSupport(MigrationSupport.MIGRATABLE); if ((Boolean) model.getRunVMOnSpecificHost().getEntity()) { getcurrentVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); } else if ((Boolean) model.getDontMigrateVM().getEntity()) { getcurrentVm().setMigrationSupport(MigrationSupport.IMPLICITLY_NON_MIGRATABLE); } if (model.getIsNew()) { if (getcurrentVm().getvmt_guid().equals(NGuid.Empty)) { if (model.getProgress() != null) { return; } model.StartProgress(null); Frontend.RunAction(VdcActionType.AddVmFromScratch, new AddVmFromScratchParameters(getcurrentVm(), new java.util.ArrayList<DiskImageBase>(), NGuid.Empty), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); vmListModel.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel.Cancel(); vmListModel.setGuideContext(returnValueBase.getActionReturnValue()); vmListModel.UpdateActionAvailability(); vmListModel.getGuideCommand().Execute(); } } }, this); } else { if (model.getProgress() != null) { return; } if ((Boolean) model.getProvisioning().getEntity()) { model.StartProgress(null); AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model1, Object result1) { VmListModel vmListModel = (VmListModel) model1; java.util.ArrayList<DiskImage> templateDisks = (java.util.ArrayList<DiskImage>) result1; UnitVmModel unitVmModel = (UnitVmModel) vmListModel.getWindow(); HashMap<Guid, DiskImage> imageToDestinationDomainMap = unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap(); ArrayList<storage_domains> activeStorageDomains = unitVmModel.getDisksAllocationModel().getActiveStorageDomains(); for (DiskImage templateDisk : templateDisks) { DiskModel disk = null; for (DiskModel a : unitVmModel.getDisksAllocationModel().getDisks()) { if (StringHelper.stringsEqual(a.getName(), templateDisk.getinternal_drive_mapping())) { disk = a; break; } } storage_domains storageDomain = Linq.getStorageById( imageToDestinationDomainMap.get(templateDisk.getId()) .getstorage_ids() .get(0), activeStorageDomains); if (disk != null) { templateDisk.setvolume_type((VolumeType) disk.getVolumeType().getSelectedItem()); templateDisk.setvolume_format(DataProvider.GetDiskVolumeFormat( (VolumeType) disk.getVolumeType().getSelectedItem(), storageDomain.getstorage_type())); } } HashMap<String, DiskImageBase> dict = new HashMap<String, DiskImageBase>(); for (DiskImage a : templateDisks) { dict.put(a.getinternal_drive_mapping(), a); } storage_domains storageDomain = (storage_domains) unitVmModel.getDisksAllocationModel() .getStorageDomain().getSelectedItem(); AddVmFromTemplateParameters parameters = new AddVmFromTemplateParameters(vmListModel.getcurrentVm(), dict, storageDomain.getId()); - if (!(Boolean) unitVmModel.getDisksAllocationModel().getIsSingleStorageDomain().getEntity()) - { - parameters.setDiskInfoDestinationMap( - unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap()); - } + parameters.setDiskInfoDestinationMap( + unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap()); Frontend.RunAction(VdcActionType.AddVmFromTemplate, parameters, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel1 = (VmListModel) result.getState(); vmListModel1.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel1.Cancel(); } } }, vmListModel); } }; AsyncDataProvider.GetTemplateDiskList(_asyncQuery, template.getId()); } else { if (model.getProgress() != null) { return; } model.StartProgress(null); HashMap<Guid, DiskImage> imageToDestinationDomainMap = model.getDisksAllocationModel().getImageToDestinationDomainMap(); storage_domains storageDomain = ((storage_domains) model.getDisksAllocationModel().getStorageDomain().getSelectedItem()); if ((Boolean) model.getDisksAllocationModel().getIsSingleStorageDomain().getEntity()) { for (Guid key : imageToDestinationDomainMap.keySet()) { ArrayList<Guid> storageIdList = new ArrayList<Guid>(); storageIdList.add(storageDomain.getId()); DiskImage diskImage = new DiskImage(); diskImage.setstorage_ids(storageIdList); imageToDestinationDomainMap.put(key, diskImage); } } VmManagementParametersBase params = new VmManagementParametersBase(getcurrentVm()); params.setDiskInfoDestinationMap(imageToDestinationDomainMap); Frontend.RunAction(VdcActionType.AddVm, params, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); vmListModel.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel.Cancel(); } } }, this); } } } else // Update existing VM -> consists of editing VM cluster, and if succeeds - editing VM: { if (model.getProgress() != null) { return; } // runEditVM: should be true if Cluster hasn't changed or if // Cluster has changed and Editing it in the Backend has succeeded: Guid oldClusterID = selectedItem.getvds_group_id(); if (oldClusterID.equals(newClusterID) == false) { ChangeVMClusterParameters parameters = new ChangeVMClusterParameters(newClusterID, getcurrentVm().getId()); model.StartProgress(null); Frontend.RunAction(VdcActionType.ChangeVMCluster, parameters, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { Frontend.RunAction(VdcActionType.UpdateVm, new VmManagementParametersBase(vmListModel.getcurrentVm()), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result1) { VmListModel vmListModel1 = (VmListModel) result1.getState(); vmListModel1.getWindow().StopProgress(); VdcReturnValueBase retVal = result1.getReturnValue(); boolean isSucceeded = retVal.getSucceeded(); if (retVal != null && isSucceeded) { vmListModel1.Cancel(); } } }, vmListModel); } else { vmListModel.getWindow().StopProgress(); } } }, this); } else { if (model.getProgress() != null) { return; } model.StartProgress(null); Frontend.RunAction(VdcActionType.UpdateVm, new VmManagementParametersBase(getcurrentVm()), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); vmListModel.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel.Cancel(); } } }, this); } } } private void RetrieveIsoImages() { Object tempVar = getSelectedItem(); VM vm = (VM) ((tempVar instanceof VM) ? tempVar : null); if (vm == null) { return; } Guid storagePoolId = vm.getstorage_pool_id(); getIsoImages().clear(); ChangeCDModel tempVar2 = new ChangeCDModel(); tempVar2.setTitle(ConsoleModel.EjectLabel); ChangeCDModel ejectModel = tempVar2; ejectModel.getExecutedEvent().addListener(this); getIsoImages().add(ejectModel); java.util.ArrayList<String> list = DataProvider.GetIrsImageList(storagePoolId, false); if (list.size() > 0) { for (String iso : list) { ChangeCDModel tempVar3 = new ChangeCDModel(); tempVar3.setTitle(iso); ChangeCDModel model = tempVar3; // model.Executed += changeCD; model.getExecutedEvent().addListener(this); getIsoImages().add(model); } } else { ChangeCDModel tempVar4 = new ChangeCDModel(); tempVar4.setTitle("No CDs"); getIsoImages().add(tempVar4); } } private void changeCD(Object sender, EventArgs e) { ChangeCDModel model = (ChangeCDModel) sender; // TODO: Patch! String isoName = model.getTitle(); if (StringHelper.stringsEqual(isoName, "No CDs")) { return; } Object tempVar = getSelectedItem(); VM vm = (VM) ((tempVar instanceof VM) ? tempVar : null); if (vm == null) { return; } Frontend.RunMultipleAction(VdcActionType.ChangeDisk, new java.util.ArrayList<VdcActionParametersBase>(java.util.Arrays.asList(new VdcActionParametersBase[] { new ChangeDiskCommandParameters(vm.getId(), StringHelper.stringsEqual(isoName, ConsoleModel.EjectLabel) ? "" : isoName) })), new IFrontendMultipleActionAsyncCallback() { @Override public void Executed(FrontendMultipleActionAsyncResult result) { } }, null); } public void Cancel() { Frontend.Unsubscribe(); CancelConfirmation(); setGuideContext(null); setWindow(null); UpdateActionAvailability(); } private void CancelConfirmation() { setConfirmWindow(null); } public void CancelError() { setErrorWindow(null); } @Override protected void OnSelectedItemChanged() { super.OnSelectedItemChanged(); UpdateActionAvailability(); UpdateConsoleModels(); } @Override protected void SelectedItemsChanged() { super.SelectedItemsChanged(); UpdateActionAvailability(); UpdateConsoleModels(); } @Override protected void SelectedItemPropertyChanged(Object sender, PropertyChangedEventArgs e) { super.SelectedItemPropertyChanged(sender, e); // C# TO JAVA CONVERTER NOTE: The following 'switch' operated on a string member and was converted to Java // 'if-else' logic: // switch (e.PropertyName) // ORIGINAL LINE: case "status": if (e.PropertyName.equals("status")) { UpdateActionAvailability(); } // ORIGINAL LINE: case "display_type": else if (e.PropertyName.equals("display_type")) { UpdateConsoleModels(); } } private void UpdateActionAvailability() { java.util.List items = getSelectedItems() != null && getSelectedItem() != null ? getSelectedItems() : new java.util.ArrayList(); getEditCommand().setIsExecutionAllowed(items.size() == 1); getRemoveCommand().setIsExecutionAllowed(items.size() > 0 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.RemoveVm)); getRunCommand().setIsExecutionAllowed(items.size() > 0 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.RunVm)); getPauseCommand().setIsExecutionAllowed(items.size() > 0 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.HibernateVm)); getShutdownCommand().setIsExecutionAllowed(items.size() > 0 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ShutdownVm)); getStopCommand().setIsExecutionAllowed(items.size() > 0 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.StopVm)); getMigrateCommand().setIsExecutionAllowed(items.size() > 0 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.MigrateVm)); getCancelMigrateCommand().setIsExecutionAllowed(items.size() > 0 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.CancelMigrateVm)); getNewTemplateCommand().setIsExecutionAllowed(items.size() == 1 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.AddVmTemplate)); getRunOnceCommand().setIsExecutionAllowed(items.size() == 1 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.RunVmOnce)); getExportCommand().setIsExecutionAllowed(items.size() > 0 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ExportVm)); getMoveCommand().setIsExecutionAllowed(items.size() == 1 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.MoveVm)); getRetrieveIsoImagesCommand().setIsExecutionAllowed(items.size() == 1 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ChangeDisk)); getChangeCdCommand().setIsExecutionAllowed(items.size() == 1 && VdcActionUtils.CanExecute(items, VM.class, VdcActionType.ChangeDisk)); getAssignTagsCommand().setIsExecutionAllowed(items.size() > 0); getGuideCommand().setIsExecutionAllowed(getGuideContext() != null || (getSelectedItem() != null && getSelectedItems() != null && getSelectedItems().size() == 1)); } @Override public void eventRaised(Event ev, Object sender, EventArgs args) { super.eventRaised(ev, sender, args); if (ev.equals(ChangeCDModel.ExecutedEventDefinition)) { changeCD(sender, args); } else if (ev.equals(ConsoleModel.ErrorEventDefinition) && sender instanceof SpiceConsoleModel) { SpiceConsoleModel_Error(sender, (ErrorCodeEventArgs) args); } } private void SpiceConsoleModel_Error(Object sender, ErrorCodeEventArgs e) { ResourceManager rm = new ResourceManager("UICommon.Resources.RdpErrors.RdpErrors", Assembly.GetExecutingAssembly()); ConfirmationModel model = new ConfirmationModel(); if (getErrorWindow() == null) { setErrorWindow(model); } model.setTitle("Console Disconnected"); model.setHashName("console_disconnected"); model.setMessage(StringFormat.format("Error connecting to Virtual Machine using Spice:\n%1$s", rm.GetString("E" + e.getErrorCode()))); rm.ReleaseAllResources(); UICommand tempVar = new UICommand("CancelError", this); tempVar.setTitle("Close"); tempVar.setIsDefault(true); tempVar.setIsCancel(true); model.getCommands().add(tempVar); } @Override public void ExecuteCommand(UICommand command) { super.ExecuteCommand(command); if (command == getNewServerCommand()) { NewServer(); } else if (command == getNewDesktopCommand()) { NewDesktop(); } else if (command == getEditCommand()) { Edit(); } else if (command == getRemoveCommand()) { remove(); } else if (command == getRunCommand()) { Run(); } else if (command == getPauseCommand()) { Pause(); } else if (command == getStopCommand()) { stop(); } else if (command == getShutdownCommand()) { Shutdown(); } else if (command == getMigrateCommand()) { Migrate(); } else if (command == getNewTemplateCommand()) { NewTemplate(); } else if (command == getRunOnceCommand()) { RunOnce(); } else if (command == getExportCommand()) { Export(); } else if (command == getMoveCommand()) { Move(); } else if (command == getGuideCommand()) { Guide(); } else if (command == getRetrieveIsoImagesCommand()) { RetrieveIsoImages(); } else if (command == getChangeCdCommand()) { ChangeCD(); } else if (command == getAssignTagsCommand()) { AssignTags(); } else if (StringHelper.stringsEqual(command.getName(), "OnAssignTags")) { OnAssignTags(); } else if (StringHelper.stringsEqual(command.getName(), "Cancel")) { Cancel(); } else if (StringHelper.stringsEqual(command.getName(), "OnSave")) { OnSave(); } else if (StringHelper.stringsEqual(command.getName(), "OnRemove")) { OnRemove(); } else if (StringHelper.stringsEqual(command.getName(), "OnExport")) { OnExport(); } else if (StringHelper.stringsEqual(command.getName(), "OnExportNoTemplates")) { OnExportNoTemplates(); } else if (StringHelper.stringsEqual(command.getName(), "CancelConfirmation")) { CancelConfirmation(); } else if (StringHelper.stringsEqual(command.getName(), "CancelError")) { CancelError(); } else if (StringHelper.stringsEqual(command.getName(), "OnRunOnce")) { OnRunOnce(); } else if (StringHelper.stringsEqual(command.getName(), "OnNewTemplate")) { OnNewTemplate(); } else if (StringHelper.stringsEqual(command.getName(), "OnMigrate")) { OnMigrate(); } else if (command == getCancelMigrateCommand()) { CancelMigration(); } else if (StringHelper.stringsEqual(command.getName(), "OnShutdown")) { OnShutdown(); } else if (StringHelper.stringsEqual(command.getName(), "OnStop")) { OnStop(); } else if (StringHelper.stringsEqual(command.getName(), "OnChangeCD")) { OnChangeCD(); } } private SystemTreeItemModel systemTreeSelectedItem; @Override public SystemTreeItemModel getSystemTreeSelectedItem() { return systemTreeSelectedItem; } @Override public void setSystemTreeSelectedItem(SystemTreeItemModel value) { systemTreeSelectedItem = value; OnPropertyChanged(new PropertyChangedEventArgs("SystemTreeSelectedItem")); } @Override protected String getListName() { return "VmListModel"; } }
true
true
private void OnSave() { UnitVmModel model = (UnitVmModel) getWindow(); VM selectedItem = (VM) getSelectedItem(); if (model.getIsNew() == false && selectedItem == null) { Cancel(); return; } setcurrentVm(model.getIsNew() ? new VM() : (VM) Cloner.clone(selectedItem)); if (!model.Validate()) { return; } String name = (String) model.getName().getEntity(); // Check name unicitate. if (!DataProvider.IsVmNameUnique(name) && name.compareToIgnoreCase(getcurrentVm().getvm_name()) != 0) { model.getName().setIsValid(false); model.getName().getInvalidityReasons().add("Name must be unique."); model.setIsGeneralTabValid(false); return; } // Save changes. VmTemplate template = (VmTemplate) model.getTemplate().getSelectedItem(); getcurrentVm().setvm_type(model.getVmType()); getcurrentVm().setvmt_guid(template.getId()); getcurrentVm().setvm_name(name); if (model.getQuota().getSelectedItem() != null) { getcurrentVm().setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId()); } getcurrentVm().setvm_os((VmOsType) model.getOSType().getSelectedItem()); getcurrentVm().setnum_of_monitors((Integer) model.getNumOfMonitors().getSelectedItem()); getcurrentVm().setvm_description((String) model.getDescription().getEntity()); getcurrentVm().setvm_domain(model.getDomain().getIsAvailable() ? (String) model.getDomain().getSelectedItem() : ""); getcurrentVm().setvm_mem_size_mb((Integer) model.getMemSize().getEntity()); getcurrentVm().setMinAllocatedMem((Integer) model.getMinAllocatedMemory().getEntity()); Guid newClusterID = ((VDSGroup) model.getCluster().getSelectedItem()).getId(); getcurrentVm().setvds_group_id(newClusterID); getcurrentVm().settime_zone((model.getTimeZone().getIsAvailable() && model.getTimeZone().getSelectedItem() != null) ? ((java.util.Map.Entry<String, String>) model.getTimeZone() .getSelectedItem()).getKey() : ""); getcurrentVm().setnum_of_sockets((Integer) model.getNumOfSockets().getEntity()); getcurrentVm().setcpu_per_socket((Integer) model.getTotalCPUCores().getEntity() / (Integer) model.getNumOfSockets().getEntity()); getcurrentVm().setusb_policy((UsbPolicy) model.getUsbPolicy().getSelectedItem()); getcurrentVm().setis_auto_suspend(false); getcurrentVm().setis_stateless((Boolean) model.getIsStateless().getEntity()); getcurrentVm().setdefault_boot_sequence(model.getBootSequence()); getcurrentVm().setiso_path(model.getCdImage().getIsChangable() ? (String) model.getCdImage().getSelectedItem() : ""); getcurrentVm().setauto_startup((Boolean) model.getIsHighlyAvailable().getEntity()); getcurrentVm().setinitrd_url((String) model.getInitrd_path().getEntity()); getcurrentVm().setkernel_url((String) model.getKernel_path().getEntity()); getcurrentVm().setkernel_params((String) model.getKernel_parameters().getEntity()); getcurrentVm().setCustomProperties((String) model.getCustomProperties().getEntity()); EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem(); getcurrentVm().setdefault_display_type((DisplayType) displayProtocolSelectedItem.getEntity()); EntityModel prioritySelectedItem = (EntityModel) model.getPriority().getSelectedItem(); getcurrentVm().setpriority((Integer) prioritySelectedItem.getEntity()); VDS defaultHost = (VDS) model.getDefaultHost().getSelectedItem(); if ((Boolean) model.getIsAutoAssign().getEntity()) { getcurrentVm().setdedicated_vm_for_vds(null); } else { getcurrentVm().setdedicated_vm_for_vds(defaultHost.getId()); } getcurrentVm().setMigrationSupport(MigrationSupport.MIGRATABLE); if ((Boolean) model.getRunVMOnSpecificHost().getEntity()) { getcurrentVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); } else if ((Boolean) model.getDontMigrateVM().getEntity()) { getcurrentVm().setMigrationSupport(MigrationSupport.IMPLICITLY_NON_MIGRATABLE); } if (model.getIsNew()) { if (getcurrentVm().getvmt_guid().equals(NGuid.Empty)) { if (model.getProgress() != null) { return; } model.StartProgress(null); Frontend.RunAction(VdcActionType.AddVmFromScratch, new AddVmFromScratchParameters(getcurrentVm(), new java.util.ArrayList<DiskImageBase>(), NGuid.Empty), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); vmListModel.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel.Cancel(); vmListModel.setGuideContext(returnValueBase.getActionReturnValue()); vmListModel.UpdateActionAvailability(); vmListModel.getGuideCommand().Execute(); } } }, this); } else { if (model.getProgress() != null) { return; } if ((Boolean) model.getProvisioning().getEntity()) { model.StartProgress(null); AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model1, Object result1) { VmListModel vmListModel = (VmListModel) model1; java.util.ArrayList<DiskImage> templateDisks = (java.util.ArrayList<DiskImage>) result1; UnitVmModel unitVmModel = (UnitVmModel) vmListModel.getWindow(); HashMap<Guid, DiskImage> imageToDestinationDomainMap = unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap(); ArrayList<storage_domains> activeStorageDomains = unitVmModel.getDisksAllocationModel().getActiveStorageDomains(); for (DiskImage templateDisk : templateDisks) { DiskModel disk = null; for (DiskModel a : unitVmModel.getDisksAllocationModel().getDisks()) { if (StringHelper.stringsEqual(a.getName(), templateDisk.getinternal_drive_mapping())) { disk = a; break; } } storage_domains storageDomain = Linq.getStorageById( imageToDestinationDomainMap.get(templateDisk.getId()) .getstorage_ids() .get(0), activeStorageDomains); if (disk != null) { templateDisk.setvolume_type((VolumeType) disk.getVolumeType().getSelectedItem()); templateDisk.setvolume_format(DataProvider.GetDiskVolumeFormat( (VolumeType) disk.getVolumeType().getSelectedItem(), storageDomain.getstorage_type())); } } HashMap<String, DiskImageBase> dict = new HashMap<String, DiskImageBase>(); for (DiskImage a : templateDisks) { dict.put(a.getinternal_drive_mapping(), a); } storage_domains storageDomain = (storage_domains) unitVmModel.getDisksAllocationModel() .getStorageDomain().getSelectedItem(); AddVmFromTemplateParameters parameters = new AddVmFromTemplateParameters(vmListModel.getcurrentVm(), dict, storageDomain.getId()); if (!(Boolean) unitVmModel.getDisksAllocationModel().getIsSingleStorageDomain().getEntity()) { parameters.setDiskInfoDestinationMap( unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap()); } Frontend.RunAction(VdcActionType.AddVmFromTemplate, parameters, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel1 = (VmListModel) result.getState(); vmListModel1.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel1.Cancel(); } } }, vmListModel); } }; AsyncDataProvider.GetTemplateDiskList(_asyncQuery, template.getId()); } else { if (model.getProgress() != null) { return; } model.StartProgress(null); HashMap<Guid, DiskImage> imageToDestinationDomainMap = model.getDisksAllocationModel().getImageToDestinationDomainMap(); storage_domains storageDomain = ((storage_domains) model.getDisksAllocationModel().getStorageDomain().getSelectedItem()); if ((Boolean) model.getDisksAllocationModel().getIsSingleStorageDomain().getEntity()) { for (Guid key : imageToDestinationDomainMap.keySet()) { ArrayList<Guid> storageIdList = new ArrayList<Guid>(); storageIdList.add(storageDomain.getId()); DiskImage diskImage = new DiskImage(); diskImage.setstorage_ids(storageIdList); imageToDestinationDomainMap.put(key, diskImage); } } VmManagementParametersBase params = new VmManagementParametersBase(getcurrentVm()); params.setDiskInfoDestinationMap(imageToDestinationDomainMap); Frontend.RunAction(VdcActionType.AddVm, params, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); vmListModel.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel.Cancel(); } } }, this); } } } else // Update existing VM -> consists of editing VM cluster, and if succeeds - editing VM: { if (model.getProgress() != null) { return; } // runEditVM: should be true if Cluster hasn't changed or if // Cluster has changed and Editing it in the Backend has succeeded: Guid oldClusterID = selectedItem.getvds_group_id(); if (oldClusterID.equals(newClusterID) == false) { ChangeVMClusterParameters parameters = new ChangeVMClusterParameters(newClusterID, getcurrentVm().getId()); model.StartProgress(null); Frontend.RunAction(VdcActionType.ChangeVMCluster, parameters, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { Frontend.RunAction(VdcActionType.UpdateVm, new VmManagementParametersBase(vmListModel.getcurrentVm()), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result1) { VmListModel vmListModel1 = (VmListModel) result1.getState(); vmListModel1.getWindow().StopProgress(); VdcReturnValueBase retVal = result1.getReturnValue(); boolean isSucceeded = retVal.getSucceeded(); if (retVal != null && isSucceeded) { vmListModel1.Cancel(); } } }, vmListModel); } else { vmListModel.getWindow().StopProgress(); } } }, this); } else { if (model.getProgress() != null) { return; } model.StartProgress(null); Frontend.RunAction(VdcActionType.UpdateVm, new VmManagementParametersBase(getcurrentVm()), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); vmListModel.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel.Cancel(); } } }, this); } } }
private void OnSave() { UnitVmModel model = (UnitVmModel) getWindow(); VM selectedItem = (VM) getSelectedItem(); if (model.getIsNew() == false && selectedItem == null) { Cancel(); return; } setcurrentVm(model.getIsNew() ? new VM() : (VM) Cloner.clone(selectedItem)); if (!model.Validate()) { return; } String name = (String) model.getName().getEntity(); // Check name unicitate. if (!DataProvider.IsVmNameUnique(name) && name.compareToIgnoreCase(getcurrentVm().getvm_name()) != 0) { model.getName().setIsValid(false); model.getName().getInvalidityReasons().add("Name must be unique."); model.setIsGeneralTabValid(false); return; } // Save changes. VmTemplate template = (VmTemplate) model.getTemplate().getSelectedItem(); getcurrentVm().setvm_type(model.getVmType()); getcurrentVm().setvmt_guid(template.getId()); getcurrentVm().setvm_name(name); if (model.getQuota().getSelectedItem() != null) { getcurrentVm().setQuotaId(((Quota) model.getQuota().getSelectedItem()).getId()); } getcurrentVm().setvm_os((VmOsType) model.getOSType().getSelectedItem()); getcurrentVm().setnum_of_monitors((Integer) model.getNumOfMonitors().getSelectedItem()); getcurrentVm().setvm_description((String) model.getDescription().getEntity()); getcurrentVm().setvm_domain(model.getDomain().getIsAvailable() ? (String) model.getDomain().getSelectedItem() : ""); getcurrentVm().setvm_mem_size_mb((Integer) model.getMemSize().getEntity()); getcurrentVm().setMinAllocatedMem((Integer) model.getMinAllocatedMemory().getEntity()); Guid newClusterID = ((VDSGroup) model.getCluster().getSelectedItem()).getId(); getcurrentVm().setvds_group_id(newClusterID); getcurrentVm().settime_zone((model.getTimeZone().getIsAvailable() && model.getTimeZone().getSelectedItem() != null) ? ((java.util.Map.Entry<String, String>) model.getTimeZone() .getSelectedItem()).getKey() : ""); getcurrentVm().setnum_of_sockets((Integer) model.getNumOfSockets().getEntity()); getcurrentVm().setcpu_per_socket((Integer) model.getTotalCPUCores().getEntity() / (Integer) model.getNumOfSockets().getEntity()); getcurrentVm().setusb_policy((UsbPolicy) model.getUsbPolicy().getSelectedItem()); getcurrentVm().setis_auto_suspend(false); getcurrentVm().setis_stateless((Boolean) model.getIsStateless().getEntity()); getcurrentVm().setdefault_boot_sequence(model.getBootSequence()); getcurrentVm().setiso_path(model.getCdImage().getIsChangable() ? (String) model.getCdImage().getSelectedItem() : ""); getcurrentVm().setauto_startup((Boolean) model.getIsHighlyAvailable().getEntity()); getcurrentVm().setinitrd_url((String) model.getInitrd_path().getEntity()); getcurrentVm().setkernel_url((String) model.getKernel_path().getEntity()); getcurrentVm().setkernel_params((String) model.getKernel_parameters().getEntity()); getcurrentVm().setCustomProperties((String) model.getCustomProperties().getEntity()); EntityModel displayProtocolSelectedItem = (EntityModel) model.getDisplayProtocol().getSelectedItem(); getcurrentVm().setdefault_display_type((DisplayType) displayProtocolSelectedItem.getEntity()); EntityModel prioritySelectedItem = (EntityModel) model.getPriority().getSelectedItem(); getcurrentVm().setpriority((Integer) prioritySelectedItem.getEntity()); VDS defaultHost = (VDS) model.getDefaultHost().getSelectedItem(); if ((Boolean) model.getIsAutoAssign().getEntity()) { getcurrentVm().setdedicated_vm_for_vds(null); } else { getcurrentVm().setdedicated_vm_for_vds(defaultHost.getId()); } getcurrentVm().setMigrationSupport(MigrationSupport.MIGRATABLE); if ((Boolean) model.getRunVMOnSpecificHost().getEntity()) { getcurrentVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); } else if ((Boolean) model.getDontMigrateVM().getEntity()) { getcurrentVm().setMigrationSupport(MigrationSupport.IMPLICITLY_NON_MIGRATABLE); } if (model.getIsNew()) { if (getcurrentVm().getvmt_guid().equals(NGuid.Empty)) { if (model.getProgress() != null) { return; } model.StartProgress(null); Frontend.RunAction(VdcActionType.AddVmFromScratch, new AddVmFromScratchParameters(getcurrentVm(), new java.util.ArrayList<DiskImageBase>(), NGuid.Empty), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); vmListModel.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel.Cancel(); vmListModel.setGuideContext(returnValueBase.getActionReturnValue()); vmListModel.UpdateActionAvailability(); vmListModel.getGuideCommand().Execute(); } } }, this); } else { if (model.getProgress() != null) { return; } if ((Boolean) model.getProvisioning().getEntity()) { model.StartProgress(null); AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model1, Object result1) { VmListModel vmListModel = (VmListModel) model1; java.util.ArrayList<DiskImage> templateDisks = (java.util.ArrayList<DiskImage>) result1; UnitVmModel unitVmModel = (UnitVmModel) vmListModel.getWindow(); HashMap<Guid, DiskImage> imageToDestinationDomainMap = unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap(); ArrayList<storage_domains> activeStorageDomains = unitVmModel.getDisksAllocationModel().getActiveStorageDomains(); for (DiskImage templateDisk : templateDisks) { DiskModel disk = null; for (DiskModel a : unitVmModel.getDisksAllocationModel().getDisks()) { if (StringHelper.stringsEqual(a.getName(), templateDisk.getinternal_drive_mapping())) { disk = a; break; } } storage_domains storageDomain = Linq.getStorageById( imageToDestinationDomainMap.get(templateDisk.getId()) .getstorage_ids() .get(0), activeStorageDomains); if (disk != null) { templateDisk.setvolume_type((VolumeType) disk.getVolumeType().getSelectedItem()); templateDisk.setvolume_format(DataProvider.GetDiskVolumeFormat( (VolumeType) disk.getVolumeType().getSelectedItem(), storageDomain.getstorage_type())); } } HashMap<String, DiskImageBase> dict = new HashMap<String, DiskImageBase>(); for (DiskImage a : templateDisks) { dict.put(a.getinternal_drive_mapping(), a); } storage_domains storageDomain = (storage_domains) unitVmModel.getDisksAllocationModel() .getStorageDomain().getSelectedItem(); AddVmFromTemplateParameters parameters = new AddVmFromTemplateParameters(vmListModel.getcurrentVm(), dict, storageDomain.getId()); parameters.setDiskInfoDestinationMap( unitVmModel.getDisksAllocationModel().getImageToDestinationDomainMap()); Frontend.RunAction(VdcActionType.AddVmFromTemplate, parameters, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel1 = (VmListModel) result.getState(); vmListModel1.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel1.Cancel(); } } }, vmListModel); } }; AsyncDataProvider.GetTemplateDiskList(_asyncQuery, template.getId()); } else { if (model.getProgress() != null) { return; } model.StartProgress(null); HashMap<Guid, DiskImage> imageToDestinationDomainMap = model.getDisksAllocationModel().getImageToDestinationDomainMap(); storage_domains storageDomain = ((storage_domains) model.getDisksAllocationModel().getStorageDomain().getSelectedItem()); if ((Boolean) model.getDisksAllocationModel().getIsSingleStorageDomain().getEntity()) { for (Guid key : imageToDestinationDomainMap.keySet()) { ArrayList<Guid> storageIdList = new ArrayList<Guid>(); storageIdList.add(storageDomain.getId()); DiskImage diskImage = new DiskImage(); diskImage.setstorage_ids(storageIdList); imageToDestinationDomainMap.put(key, diskImage); } } VmManagementParametersBase params = new VmManagementParametersBase(getcurrentVm()); params.setDiskInfoDestinationMap(imageToDestinationDomainMap); Frontend.RunAction(VdcActionType.AddVm, params, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); vmListModel.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel.Cancel(); } } }, this); } } } else // Update existing VM -> consists of editing VM cluster, and if succeeds - editing VM: { if (model.getProgress() != null) { return; } // runEditVM: should be true if Cluster hasn't changed or if // Cluster has changed and Editing it in the Backend has succeeded: Guid oldClusterID = selectedItem.getvds_group_id(); if (oldClusterID.equals(newClusterID) == false) { ChangeVMClusterParameters parameters = new ChangeVMClusterParameters(newClusterID, getcurrentVm().getId()); model.StartProgress(null); Frontend.RunAction(VdcActionType.ChangeVMCluster, parameters, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { Frontend.RunAction(VdcActionType.UpdateVm, new VmManagementParametersBase(vmListModel.getcurrentVm()), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result1) { VmListModel vmListModel1 = (VmListModel) result1.getState(); vmListModel1.getWindow().StopProgress(); VdcReturnValueBase retVal = result1.getReturnValue(); boolean isSucceeded = retVal.getSucceeded(); if (retVal != null && isSucceeded) { vmListModel1.Cancel(); } } }, vmListModel); } else { vmListModel.getWindow().StopProgress(); } } }, this); } else { if (model.getProgress() != null) { return; } model.StartProgress(null); Frontend.RunAction(VdcActionType.UpdateVm, new VmManagementParametersBase(getcurrentVm()), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VmListModel vmListModel = (VmListModel) result.getState(); vmListModel.getWindow().StopProgress(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { vmListModel.Cancel(); } } }, this); } } }
diff --git a/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/instructions/SendStaticMessage.java b/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/instructions/SendStaticMessage.java index 2f494afab..491043c5b 100644 --- a/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/instructions/SendStaticMessage.java +++ b/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/instructions/SendStaticMessage.java @@ -1,63 +1,63 @@ package org.eclipse.jdt.internal.debug.eval.ast.instructions; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.text.MessageFormat; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.debug.core.IJavaClassType; import org.eclipse.jdt.debug.core.IJavaType; import org.eclipse.jdt.debug.core.IJavaValue; /** * Sends a message. The arguments are on the * stack in reverse order, followed by the receiver. * Pushes the result, if any, onto the stack */ public class SendStaticMessage extends CompoundInstruction { private int fArgCount; private String fSelector; private String fSignature; private String fTypeSignature; public SendStaticMessage(String typeSignature, String selector, String signature, int argCount, int start) { super(start); fArgCount= argCount; fSelector= selector; fSignature= signature; fTypeSignature= typeSignature; } public void execute() throws CoreException { IJavaValue[] args = new IJavaValue[fArgCount]; // args are in reverse order for (int i= fArgCount - 1; i >= 0; i--) { args[i] = (IJavaValue)popValue(); } - IJavaType receiver= getType(Signature.toString(fTypeSignature)); + IJavaType receiver= getType(Signature.toString(fTypeSignature).replace('/', '.')); IJavaValue result; if (receiver instanceof IJavaClassType) { result= ((IJavaClassType)receiver).sendMessage(fSelector, fSignature, args, getContext().getThread()); } else { throw new CoreException(new Status(Status.ERROR, DebugPlugin.PLUGIN_ID, Status.OK, InstructionsEvaluationMessages.getString("SendStaticMessage.Cannot_send_a_static_message_to_a_non_class_type_object_1"), null)); //$NON-NLS-1$ } if (!fSignature.endsWith(")V")) { //$NON-NLS-1$ // only push the result if not a void method push(result); } } public String toString() { return MessageFormat.format(InstructionsEvaluationMessages.getString("SendStaticMessage.send_static_message_{0}_{1}_2"), new String[]{fSelector, fSignature}); //$NON-NLS-1$ } }
true
true
public void execute() throws CoreException { IJavaValue[] args = new IJavaValue[fArgCount]; // args are in reverse order for (int i= fArgCount - 1; i >= 0; i--) { args[i] = (IJavaValue)popValue(); } IJavaType receiver= getType(Signature.toString(fTypeSignature)); IJavaValue result; if (receiver instanceof IJavaClassType) { result= ((IJavaClassType)receiver).sendMessage(fSelector, fSignature, args, getContext().getThread()); } else { throw new CoreException(new Status(Status.ERROR, DebugPlugin.PLUGIN_ID, Status.OK, InstructionsEvaluationMessages.getString("SendStaticMessage.Cannot_send_a_static_message_to_a_non_class_type_object_1"), null)); //$NON-NLS-1$ } if (!fSignature.endsWith(")V")) { //$NON-NLS-1$ // only push the result if not a void method push(result); } }
public void execute() throws CoreException { IJavaValue[] args = new IJavaValue[fArgCount]; // args are in reverse order for (int i= fArgCount - 1; i >= 0; i--) { args[i] = (IJavaValue)popValue(); } IJavaType receiver= getType(Signature.toString(fTypeSignature).replace('/', '.')); IJavaValue result; if (receiver instanceof IJavaClassType) { result= ((IJavaClassType)receiver).sendMessage(fSelector, fSignature, args, getContext().getThread()); } else { throw new CoreException(new Status(Status.ERROR, DebugPlugin.PLUGIN_ID, Status.OK, InstructionsEvaluationMessages.getString("SendStaticMessage.Cannot_send_a_static_message_to_a_non_class_type_object_1"), null)); //$NON-NLS-1$ } if (!fSignature.endsWith(")V")) { //$NON-NLS-1$ // only push the result if not a void method push(result); } }
diff --git a/test-modules/functional-tests/src/test/java/org/openlmis/functional/ManageDistribution.java b/test-modules/functional-tests/src/test/java/org/openlmis/functional/ManageDistribution.java index 3e858c81db..30f62839c0 100644 --- a/test-modules/functional-tests/src/test/java/org/openlmis/functional/ManageDistribution.java +++ b/test-modules/functional-tests/src/test/java/org/openlmis/functional/ManageDistribution.java @@ -1,252 +1,251 @@ /* * Copyright © 2013 VillageReach. All Rights Reserved. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.openlmis.functional; import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener; import org.openlmis.UiUtils.TestCaseHelper; import org.openlmis.pageobjects.*; import org.openqa.selenium.WebElement; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import org.testng.annotations.Test; import org.testng.annotations.Listeners; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import java.util.ArrayList; import java.util.List; import static com.thoughtworks.selenium.SeleneseTestBase.assertEquals; import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue; import static com.thoughtworks.selenium.SeleneseTestBase.fail; @TransactionConfiguration(defaultRollback = true) @Transactional @Listeners(CaptureScreenshotOnFailureListener.class) public class ManageDistribution extends TestCaseHelper { public static final String NONE_ASSIGNED = "--None Assigned--"; public static final String SELECT_DELIVERY_ZONE = "--Select Delivery Zone--"; public static final String periodDisplayedByDefault = "Period14"; public static final String periodNotToBeDisplayedInDropDown = "Period1"; @BeforeMethod(groups = {"functional2", "smoke"}) public void setUp() throws Exception { super.setup(); } @Test(groups = {"smoke"}, dataProvider = "Data-Provider-Function") public void testShouldFetchProgramPeriod(String userSIC, String password, String deliveryZoneCodeFirst, String deliveryZoneCodeSecond, String deliveryZoneNameFirst, String deliveryZoneNameSecond, String facilityCodeFirst, String facilityCodeSecond, String programFirst, String programSecond, String schedule, String period, Integer totalNumberOfPeriods) throws Exception { List<String> rightsList = new ArrayList<String>(); rightsList.add("MANAGE_DISTRIBUTION"); setupTestDataToInitiateRnRForDistribution(true, programFirst, userSIC, "200", "openLmis", rightsList, programSecond); setupDataForDeliveryZone(deliveryZoneCodeFirst, deliveryZoneCodeSecond, deliveryZoneNameFirst, deliveryZoneNameSecond, facilityCodeFirst, facilityCodeSecond, programFirst, programSecond, schedule); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSIC, password); DistributionPage distributionPage = homePage.navigatePlanDistribution(); verifyElementsPresent(distributionPage); String defaultDistributionZoneValuesToBeVerified = NONE_ASSIGNED; WebElement actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromDeliveryZone(); verifySelectedOptionFromSelectField(defaultDistributionZoneValuesToBeVerified, actualSelectFieldElement); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeFirst); homePage.navigateHomePage(); homePage.navigatePlanDistribution(); distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst); List<String> firstProgramValuesToBeVerified = new ArrayList<String>(); firstProgramValuesToBeVerified.add(programFirst); List<WebElement> valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromProgram(); verifyAllSelectFieldValues(firstProgramValuesToBeVerified, valuesPresentInDropDown); distributionPage.selectValueFromProgram(programFirst); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(periodDisplayedByDefault, actualSelectFieldElement); distributionPage.clickViewLoadAmount(); //verifySubOptionsOfProceedButton(distributionPage); } @Test(groups = {"functional2"}, dataProvider = "Data-Provider-Function") public void testManageDistribution(String userSIC, String password, String deliveryZoneCodeFirst, String deliveryZoneCodeSecond, String deliveryZoneNameFirst, String deliveryZoneNameSecond, String facilityCodeFirst, String facilityCodeSecond, String programFirst, String programSecond, String schedule, String period, Integer totalNumberOfPeriods) throws Exception { List<String> rightsList = new ArrayList<String>(); rightsList.add("MANAGE_DISTRIBUTION"); setupTestDataToInitiateRnRForDistribution(true, programFirst, userSIC, "200", "openLmis", rightsList, programSecond); setupDataForDeliveryZone(deliveryZoneCodeFirst, deliveryZoneCodeSecond, deliveryZoneNameFirst, deliveryZoneNameSecond, facilityCodeFirst, facilityCodeSecond, programFirst, programSecond, schedule); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSIC, password); DistributionPage distributionPage = homePage.navigatePlanDistribution(); verifyElementsPresent(distributionPage); String defaultDistributionZoneValuesToBeVerified = NONE_ASSIGNED; WebElement actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromDeliveryZone(); verifySelectedOptionFromSelectField(defaultDistributionZoneValuesToBeVerified, actualSelectFieldElement); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeFirst); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeSecond); homePage.navigateHomePage(); homePage.navigatePlanDistribution(); List<String> distributionZoneValuesToBeVerified = new ArrayList<String>(); distributionZoneValuesToBeVerified.add(deliveryZoneNameFirst); distributionZoneValuesToBeVerified.add(deliveryZoneNameSecond); List<WebElement> valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromDeliveryZone(); verifyAllSelectFieldValues(distributionZoneValuesToBeVerified, valuesPresentInDropDown); String defaultProgramValuesToBeVerified = NONE_ASSIGNED; actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromProgram(); verifySelectedOptionFromSelectField(defaultProgramValuesToBeVerified, actualSelectFieldElement); String defaultPeriodValuesToBeVerified = NONE_ASSIGNED; actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst); List<String> firstProgramValuesToBeVerified = new ArrayList<String>(); firstProgramValuesToBeVerified.add(programFirst); valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromProgram(); verifyAllSelectFieldValues(firstProgramValuesToBeVerified, valuesPresentInDropDown); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); distributionPage.selectValueFromDeliveryZone(deliveryZoneNameSecond); List<String> secondProgramValuesToBeVerified = new ArrayList<String>(); secondProgramValuesToBeVerified.add(programSecond); valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromProgram(); verifyAllSelectFieldValues(secondProgramValuesToBeVerified, valuesPresentInDropDown); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); distributionPage.selectValueFromProgram(programSecond); List<String> periodValuesToBeVerified = new ArrayList<String>(); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(periodDisplayedByDefault, actualSelectFieldElement); for (int counter = 2; counter <= totalNumberOfPeriods; counter++) { String periodWithCounter = period + counter; periodValuesToBeVerified.add(periodWithCounter); } valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromPeriod(); verifyAllSelectFieldValues(periodValuesToBeVerified, valuesPresentInDropDown); verifySelectFieldValueNotPresent(periodNotToBeDisplayedInDropDown, valuesPresentInDropDown); distributionPage.selectValueFromPeriod(periodDisplayedByDefault); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromDeliveryZone(); verifySelectedOptionFromSelectField(deliveryZoneNameSecond, actualSelectFieldElement); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromProgram(); verifySelectedOptionFromSelectField(programSecond, actualSelectFieldElement); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(periodDisplayedByDefault, actualSelectFieldElement); - distributionPage.clickViewLoadAmount(); distributionPage.selectValueFromDeliveryZone(SELECT_DELIVERY_ZONE); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromProgram(); verifySelectedOptionFromSelectField(defaultProgramValuesToBeVerified, actualSelectFieldElement); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); } private void verifyElementsPresent(DistributionPage distributionPage) { assertTrue("selectDeliveryZoneSelectBox should be present", distributionPage.getSelectDeliveryZoneSelectBox().isDisplayed()); assertTrue("selectProgramSelectBox should be present", distributionPage.getSelectProgramSelectBox().isDisplayed()); assertTrue("selectPeriodSelectBox should be present", distributionPage.getSelectPeriodSelectBox().isDisplayed()); assertTrue("proceedButton should be present", distributionPage.getViewLoadAmountButton().isDisplayed()); } private void verifyAllSelectFieldValues(List<String> valuesToBeVerified, List<WebElement> valuesPresentInDropDown) { String collectionOfValuesPresentINDropDown = ""; int valuesToBeVerifiedCounter = valuesToBeVerified.size(); int valuesInSelectFieldCounter = valuesPresentInDropDown.size(); if (valuesToBeVerifiedCounter == valuesInSelectFieldCounter - 1) { for (WebElement webElement : valuesPresentInDropDown) { collectionOfValuesPresentINDropDown = collectionOfValuesPresentINDropDown + webElement.getText().trim(); } for (String values : valuesToBeVerified) { assertTrue(collectionOfValuesPresentINDropDown.contains(values)); } } else { fail("Values in select field are not same in number as values to be verified"); } } private void verifySelectFieldValueNotPresent(String valueToBeVerified, List<WebElement> valuesPresentInDropDown) { boolean flag = false; for (WebElement webElement : valuesPresentInDropDown) { if (valueToBeVerified.equalsIgnoreCase(webElement.getText().trim())) { flag = true; break; } } assertTrue(valueToBeVerified + " should not exist in period drop down", flag == false); } private void verifySelectedOptionFromSelectField(String valuesToBeVerified, WebElement actualSelectFieldElement) { testWebDriver.sleep(500); testWebDriver.waitForElementToAppear(actualSelectFieldElement); assertEquals(valuesToBeVerified, actualSelectFieldElement.getText()); } @AfterMethod(groups = {"functional2", "smoke"}) public void tearDown() throws Exception { HomePage homePage = new HomePage(testWebDriver); homePage.logout(baseUrlGlobal); dbWrapper.deleteData(); dbWrapper.closeConnection(); } @DataProvider(name = "Data-Provider-Function") public Object[][] parameterIntTestProviderPositive() { return new Object[][]{ {"storeincharge", "Admin123", "DZ1", "DZ2", "Delivery Zone First", "Delivery Zone Second", "F10", "F11", "VACCINES", "TB", "M", "Period", 14} }; } }
true
true
public void testManageDistribution(String userSIC, String password, String deliveryZoneCodeFirst, String deliveryZoneCodeSecond, String deliveryZoneNameFirst, String deliveryZoneNameSecond, String facilityCodeFirst, String facilityCodeSecond, String programFirst, String programSecond, String schedule, String period, Integer totalNumberOfPeriods) throws Exception { List<String> rightsList = new ArrayList<String>(); rightsList.add("MANAGE_DISTRIBUTION"); setupTestDataToInitiateRnRForDistribution(true, programFirst, userSIC, "200", "openLmis", rightsList, programSecond); setupDataForDeliveryZone(deliveryZoneCodeFirst, deliveryZoneCodeSecond, deliveryZoneNameFirst, deliveryZoneNameSecond, facilityCodeFirst, facilityCodeSecond, programFirst, programSecond, schedule); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSIC, password); DistributionPage distributionPage = homePage.navigatePlanDistribution(); verifyElementsPresent(distributionPage); String defaultDistributionZoneValuesToBeVerified = NONE_ASSIGNED; WebElement actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromDeliveryZone(); verifySelectedOptionFromSelectField(defaultDistributionZoneValuesToBeVerified, actualSelectFieldElement); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeFirst); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeSecond); homePage.navigateHomePage(); homePage.navigatePlanDistribution(); List<String> distributionZoneValuesToBeVerified = new ArrayList<String>(); distributionZoneValuesToBeVerified.add(deliveryZoneNameFirst); distributionZoneValuesToBeVerified.add(deliveryZoneNameSecond); List<WebElement> valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromDeliveryZone(); verifyAllSelectFieldValues(distributionZoneValuesToBeVerified, valuesPresentInDropDown); String defaultProgramValuesToBeVerified = NONE_ASSIGNED; actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromProgram(); verifySelectedOptionFromSelectField(defaultProgramValuesToBeVerified, actualSelectFieldElement); String defaultPeriodValuesToBeVerified = NONE_ASSIGNED; actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst); List<String> firstProgramValuesToBeVerified = new ArrayList<String>(); firstProgramValuesToBeVerified.add(programFirst); valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromProgram(); verifyAllSelectFieldValues(firstProgramValuesToBeVerified, valuesPresentInDropDown); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); distributionPage.selectValueFromDeliveryZone(deliveryZoneNameSecond); List<String> secondProgramValuesToBeVerified = new ArrayList<String>(); secondProgramValuesToBeVerified.add(programSecond); valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromProgram(); verifyAllSelectFieldValues(secondProgramValuesToBeVerified, valuesPresentInDropDown); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); distributionPage.selectValueFromProgram(programSecond); List<String> periodValuesToBeVerified = new ArrayList<String>(); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(periodDisplayedByDefault, actualSelectFieldElement); for (int counter = 2; counter <= totalNumberOfPeriods; counter++) { String periodWithCounter = period + counter; periodValuesToBeVerified.add(periodWithCounter); } valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromPeriod(); verifyAllSelectFieldValues(periodValuesToBeVerified, valuesPresentInDropDown); verifySelectFieldValueNotPresent(periodNotToBeDisplayedInDropDown, valuesPresentInDropDown); distributionPage.selectValueFromPeriod(periodDisplayedByDefault); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromDeliveryZone(); verifySelectedOptionFromSelectField(deliveryZoneNameSecond, actualSelectFieldElement); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromProgram(); verifySelectedOptionFromSelectField(programSecond, actualSelectFieldElement); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(periodDisplayedByDefault, actualSelectFieldElement); distributionPage.clickViewLoadAmount(); distributionPage.selectValueFromDeliveryZone(SELECT_DELIVERY_ZONE); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromProgram(); verifySelectedOptionFromSelectField(defaultProgramValuesToBeVerified, actualSelectFieldElement); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); }
public void testManageDistribution(String userSIC, String password, String deliveryZoneCodeFirst, String deliveryZoneCodeSecond, String deliveryZoneNameFirst, String deliveryZoneNameSecond, String facilityCodeFirst, String facilityCodeSecond, String programFirst, String programSecond, String schedule, String period, Integer totalNumberOfPeriods) throws Exception { List<String> rightsList = new ArrayList<String>(); rightsList.add("MANAGE_DISTRIBUTION"); setupTestDataToInitiateRnRForDistribution(true, programFirst, userSIC, "200", "openLmis", rightsList, programSecond); setupDataForDeliveryZone(deliveryZoneCodeFirst, deliveryZoneCodeSecond, deliveryZoneNameFirst, deliveryZoneNameSecond, facilityCodeFirst, facilityCodeSecond, programFirst, programSecond, schedule); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSIC, password); DistributionPage distributionPage = homePage.navigatePlanDistribution(); verifyElementsPresent(distributionPage); String defaultDistributionZoneValuesToBeVerified = NONE_ASSIGNED; WebElement actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromDeliveryZone(); verifySelectedOptionFromSelectField(defaultDistributionZoneValuesToBeVerified, actualSelectFieldElement); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeFirst); dbWrapper.insertRoleAssignmentForDistribution(userSIC, "store in-charge", deliveryZoneCodeSecond); homePage.navigateHomePage(); homePage.navigatePlanDistribution(); List<String> distributionZoneValuesToBeVerified = new ArrayList<String>(); distributionZoneValuesToBeVerified.add(deliveryZoneNameFirst); distributionZoneValuesToBeVerified.add(deliveryZoneNameSecond); List<WebElement> valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromDeliveryZone(); verifyAllSelectFieldValues(distributionZoneValuesToBeVerified, valuesPresentInDropDown); String defaultProgramValuesToBeVerified = NONE_ASSIGNED; actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromProgram(); verifySelectedOptionFromSelectField(defaultProgramValuesToBeVerified, actualSelectFieldElement); String defaultPeriodValuesToBeVerified = NONE_ASSIGNED; actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); distributionPage.selectValueFromDeliveryZone(deliveryZoneNameFirst); List<String> firstProgramValuesToBeVerified = new ArrayList<String>(); firstProgramValuesToBeVerified.add(programFirst); valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromProgram(); verifyAllSelectFieldValues(firstProgramValuesToBeVerified, valuesPresentInDropDown); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); distributionPage.selectValueFromDeliveryZone(deliveryZoneNameSecond); List<String> secondProgramValuesToBeVerified = new ArrayList<String>(); secondProgramValuesToBeVerified.add(programSecond); valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromProgram(); verifyAllSelectFieldValues(secondProgramValuesToBeVerified, valuesPresentInDropDown); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); distributionPage.selectValueFromProgram(programSecond); List<String> periodValuesToBeVerified = new ArrayList<String>(); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(periodDisplayedByDefault, actualSelectFieldElement); for (int counter = 2; counter <= totalNumberOfPeriods; counter++) { String periodWithCounter = period + counter; periodValuesToBeVerified.add(periodWithCounter); } valuesPresentInDropDown = distributionPage.getAllSelectOptionsFromPeriod(); verifyAllSelectFieldValues(periodValuesToBeVerified, valuesPresentInDropDown); verifySelectFieldValueNotPresent(periodNotToBeDisplayedInDropDown, valuesPresentInDropDown); distributionPage.selectValueFromPeriod(periodDisplayedByDefault); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromDeliveryZone(); verifySelectedOptionFromSelectField(deliveryZoneNameSecond, actualSelectFieldElement); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromProgram(); verifySelectedOptionFromSelectField(programSecond, actualSelectFieldElement); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(periodDisplayedByDefault, actualSelectFieldElement); distributionPage.selectValueFromDeliveryZone(SELECT_DELIVERY_ZONE); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromProgram(); verifySelectedOptionFromSelectField(defaultProgramValuesToBeVerified, actualSelectFieldElement); actualSelectFieldElement = distributionPage.getFirstSelectedOptionFromPeriod(); verifySelectedOptionFromSelectField(defaultPeriodValuesToBeVerified, actualSelectFieldElement); }
diff --git a/cmput391proj/src/cmput391/Record.java b/cmput391proj/src/cmput391/Record.java index 6827a09..c53ed3a 100644 --- a/cmput391proj/src/cmput391/Record.java +++ b/cmput391proj/src/cmput391/Record.java @@ -1,28 +1,28 @@ package cmput391; public class Record { private int recordID; private int imgID; public Record(int record) { this.recordID = record; - imgID = 0; + imgID = record; } public void setRecordID(int record) { this.recordID = record; } public void setImgID(int img) { this.imgID = img; } public int getRecordID() { return recordID; } public int getImgID() { return imgID; } }
true
true
public Record(int record) { this.recordID = record; imgID = 0; }
public Record(int record) { this.recordID = record; imgID = record; }
diff --git a/plugins/org.bigraph.bigwb.playground/src/it/uniud/bigredit/command/CompositionCommand.java b/plugins/org.bigraph.bigwb.playground/src/it/uniud/bigredit/command/CompositionCommand.java index 05c07717..4e069d13 100644 --- a/plugins/org.bigraph.bigwb.playground/src/it/uniud/bigredit/command/CompositionCommand.java +++ b/plugins/org.bigraph.bigwb.playground/src/it/uniud/bigredit/command/CompositionCommand.java @@ -1,461 +1,461 @@ package it.uniud.bigredit.command; import it.uniud.bigredit.CompositionWizard; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.commands.Command; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.graphics.Color; import org.eclipse.ui.IWorkbenchPart; import dk.itu.big_red.model.Bigraph; import dk.itu.big_red.model.Container; import dk.itu.big_red.model.Edge; import dk.itu.big_red.model.InnerName; import dk.itu.big_red.model.Layoutable; import dk.itu.big_red.model.Link; import dk.itu.big_red.model.OuterName; import dk.itu.big_red.model.Point; import dk.itu.big_red.model.Port; import dk.itu.big_red.model.Root; import dk.itu.big_red.model.Site; import dk.itu.big_red.model.changes.ChangeGroup; public class CompositionCommand extends Command { private Bigraph inner; private Bigraph outer; private IWorkbenchPart part; private HashMap< Site, Root > placeMap = null; private HashMap< InnerName, OuterName > linkMap = null; private HashMap< Layoutable, Rectangle > oldLayouts; private ArrayList< Link > links = null; private HashMap< Layoutable, Rectangle > oldLayouts2 = null; private HashMap< Layoutable, Layoutable > oldParents = null; private InnerName oldInnerNames = null; private boolean executed = false; private boolean disabled = false; private HashMap< Edge, Color > oldColors = null; private HashMap< Edge, String > oldNames = null; private boolean reactumSpecialCase = false; public CompositionCommand( Bigraph inner, Bigraph outer, IWorkbenchPart part ) { this.inner = inner; this.outer = outer; this.part = part; } public void disable() { disabled = true; } public boolean wasExecuted() { return executed; } @Override public boolean canExecute() { return inner != null && outer != null && part != null; //&& !disabled; } @Override public void execute() { System.out.println("start Compose"); setLabel( "Compose" ); CompositionWizard wizard = new CompositionWizard( inner, outer ); WizardDialog dialog = new WizardDialog( part.getSite().getShell(), wizard ); dialog.create(); dialog.setTitle( "Bigraph composition" ); dialog.setMessage( "Composing " + outer.getName() + " with " + inner.getName() ); if ( dialog.open() != WizardDialog.CANCEL ) { System.out.println("REDO"); placeMap = wizard.getPlaceMap(); linkMap = wizard.getLinkMap(); executed = true; redo(); } } class Pair { public Pair( Layoutable a, Layoutable b ) { this.a = a; this.b = b; } Layoutable a; Layoutable b; } private class ColorMix { int r = 0; int g = 0; int b = 0; int parts = 0; } @Override public void redo(){ if ( !executed ) return; ChangeGroup cg = new ChangeGroup(); /**start placing roots in sites */ for(Site site : placeMap.keySet()){ Container parent=site.getParent(); Root root= placeMap.get(site); for (Layoutable children: root.getChildren()){ // //OLDTODO parent.addChild(children); ////children.getParent().removeChild(children); //OLDTODO children.setParent(parent); } //OLDTODO parent.removeChild(site); } for (InnerName iNames:inner.getInnerNames()){ //OLDTODO outer.addChild(iNames); //OLDTODo iNames.setParent(outer); } /** connect link and ports */ HashMap<Link, List<Point>> connection= new HashMap<Link, List<Point>> (); for(InnerName innerName : linkMap.keySet()){ Link link=innerName.getLink(); - link.removePoint(innerName); + //TODO link.removePoint(innerName); OuterName outerName=linkMap.get(innerName); System.out.println("compute innerName"+ innerName.getName()); List<Point> points=new ArrayList<Point>(); points= outerName.getPoints(); connection.put(link, points); //OLDTODO outer.removeChild(innerName); } /** from hashMap connection create update links*/ for(Link link : connection.keySet()){ List<Point> points=connection.get(link); System.out.println(points.size()); for(int i=0;i<points.size();i++){ System.out.println(points.size()); Point p=points.get(i); - points.get(i).getLink().removePoint(points.get(i)); + //TODO points.get(i).getLink().removePoint(points.get(i)); System.out.println(points.size()); if(link instanceof OuterName){ - ((OuterName)link).addPoint(p); + //TODO ((OuterName)link).addPoint(p); }else if (link instanceof Edge){ - ((Edge)link).addPoint(p); + //TODO ((Edge)link).addPoint(p); } } } //inner.dispose(); //inner.getParent().removeChild(inner); outer.relayout(); } private void changeConnection(){ } /*@Override public void redo() { if ( !executed ) return; //if ( inner.getParent() instanceof Reaction && ( ( Reaction )inner.getParent() ).getReactum() == inner ) // reactumSpecialCase = true; ArrayList< Layoutable > startingChildren = new ArrayList< Layoutable >( outer.getChildren() ); links = new ArrayList< Link >(); for ( InnerName innerName : linkMap.keySet() ) { OuterName outerName = linkMap.get( innerName ); ArrayList< Layoutable > sources = new ArrayList< Layoutable >(); ArrayList< Layoutable > targets = new ArrayList< Layoutable >(); while ( innerName.getLink() != null ) { Link link = innerName.getLink(); Layoutable t = link; startingChildren.remove( t ); if ( !targets.contains( t ) ) targets.add( t ); //link.disconnect(); links.add( link ); } while ( !outerName.getPoints().isEmpty() ) { Link link = outerName.getAllConnections().get( 0 ); Layoutable t = link.getOther( outerName ); startingChildren.remove( t ); if ( !sources.contains( t ) ) sources.add( t ); link.disconnect(); links.add( link ); } for ( int a = 0; a < sources.size(); a++ ) { for ( int b = 0; b < targets.size(); b++ ) { boolean already = false; for ( Link link : links ) { if ( link.getSource() == sources.get( a ) && link.getTarget() == targets.get( b ) ) { already = true; break; } } if ( !already ) links.add( new Link( sources.get( a ), targets.get( b ) ) ); } } } oldInnerNames = outer.getInnerNames(); outer.removeChild( oldInnerNames ); NameBar innerInnerNames = inner.getInnerNames(); inner.removeChild( innerInnerNames ); outer.addChild( innerInnerNames ); oldLayouts2 = new HashMap< Layoutable, Rectangle >(); oldParents = new HashMap< Layoutable, Layoutable >(); for ( Site site : placeMap.keySet() ) { Root root = placeMap.get( site ); oldParents.put( site, site.getParent() ); Layoutable parent = site.getParent(); parent.removeChild( site ); int xMin = root.getLayout().width; int yMin = root.getLayout().height; int xMax = 0; int yMax = 0; for ( Layoutable t : root.getChildren() ) { xMin = Math.min( xMin, t.getLayout().x ); yMin = Math.min( yMin, t.getLayout().y ); xMax = Math.max( xMax, t.getLayout().x + t.getLayout().width ); yMax = Math.max( yMax, t.getLayout().y + t.getLayout().height ); } int xCentre = site.getLayout().x + site.getLayout().width / 2 - xMin - ( xMax - xMin ) / 2; int yCentre = site.getLayout().y + site.getLayout().height / 2 - yMin - ( yMax - yMin ) / 2; while ( !root.getChildren().isEmpty() ) { Layoutable t = root.getChildren().get( 0 ); oldParents.put( t, root ); t.getParent().removeChild( t ); parent.addChild( t ); Rectangle r = new Rectangle( t.getLayout() ); r.x += xCentre; r.y += yCentre; oldLayouts2.put( t, new Rectangle( t.getLayout() ) ); t.setLayout( r ); } } HashMap< Edge, ColorMix > mixMap = new HashMap< Edge, ColorMix >(); oldColors = new HashMap< Edge, Color >(); for ( Layoutable t : new ArrayList< Layoutable >( inner.getChildren() ) ) { if ( t instanceof Edge ) { ArrayList< Layoutable > otherEdges = new ArrayList< Layoutable >(); for ( Link link : t.getAllConnections() ) { if ( link.getOther( t ) instanceof Edge ) { link.disconnect(); links.add( link ); otherEdges.add( link.getOther( t ) ); startingChildren.remove( link.getOther( t ) ); } } if ( otherEdges.size() == 0 ) continue; boolean first = true; Point avg = new Point( 0, 0 ); for ( Layoutable edge : otherEdges ) { avg.translate( edge.getLayout().getTopLeft() ); if ( first ) first = false; else { oldParents.put( edge, edge.getParent() ); edge.getParent().removeChild( edge ); for ( Link link : edge.getAllConnections() ) { Layoutable other = link.getOther( edge ); link.disconnect(); links.add( link ); links.add( new Link( other, otherEdges.get( 0 ) ) ); startingChildren.remove( other ); } } } avg.x /= otherEdges.size(); avg.y /= otherEdges.size(); oldLayouts2.put( otherEdges.get( 0 ), otherEdges.get( 0 ).getLayout() ); otherEdges.get( 0 ).setLayout( new Rectangle( avg.x, avg.y, EdgeFigure.DEF_WIDTH, EdgeFigure.DEF_HEIGHT ) ); ColorMix mix = new ColorMix(); ArrayList< Layoutable > mixers = new ArrayList< Layoutable >( otherEdges ); mixers.add( t ); for ( Layoutable mixer : mixers ) { Edge e = ( Edge )mixer; if ( mixMap.containsKey( e ) ) { mix.r += mixMap.get( e ).r; mix.g += mixMap.get( e ).g; mix.b += mixMap.get( e ).b; mix.parts += mixMap.get( e ).parts; } else { mix.r += e.getColor().getRed(); mix.g += e.getColor().getGreen(); mix.b += e.getColor().getBlue(); mix.parts++; } } mixMap.put( ( Edge )otherEdges.get( 0 ), mix ); for ( Link link : t.getAllConnections() ) { link.disconnect(); links.add( link ); Layoutable other = link.getOther( t ); links.add( new Link( otherEdges.get( 0 ), other ) ); } } } for ( Layoutable t : new ArrayList< Layoutable >( inner.getChildren() ) ) { if ( t instanceof Edge ) { boolean b = false; for ( Link link : t.getAllConnections() ) { if ( link.getOther( t ).getGraph() == outer ) { b = true; break; } } if ( !b ) continue; oldParents.put( t, t.getParent() ); t.getParent().removeChild( t ); outer.addChild( t ); } } for ( Layoutable t : new ArrayList< Layoutable >( outer.getChildren() ) ) { if ( t instanceof Edge && t.getAllConnections().size() == 0 ) { for ( Link link : t.getAllConnections() ) { link.disconnect(); links.add( link ); } oldParents.put( t, t.getParent() ); t.getParent().removeChild( t ); } else if ( t instanceof Edge && !startingChildren.contains( t ) ) { int count = 0; Point avg = new Point( 0, 0 ); for ( Link link : t.getAllConnections() ) { count++; Rectangle r = link.getOther( t ).getLayout(); Point p = new Point( r.x + r.width / 2, r.y + r.height / 2 ); link.getOther( t ).getParent().translateToAbsolute( p ); avg.translate( p ); } avg.x /= count; avg.y /= count; outer.translateToRelative( avg ); if ( count == 1 ) { Layoutable source = t.getAllConnections().get( 0 ).getOther( t ); Point p1 = source.getLayout().getCenter(); source.getParent().translateToAbsolute( p1 ); Point p2 = source.getParent().getLayout().getCenter(); source.getParent().getParent().translateToAbsolute( p2 ); if ( source instanceof Port ) avg = p1.scale( 2 ).translate( p2.negate() ); else avg = new Point( p1.x, p2.y + ( ( ( NameBar )source.getParent() ).isInner() ? -source.getParent().getLayout().height : source.getParent().getLayout().height ) ); outer.translateToRelative( avg ); } if ( !oldLayouts2.containsKey( t ) ) oldLayouts2.put( t, t.getLayout() ); t.setLayout( new Rectangle( avg.x - EdgeFigure.DEF_WIDTH / 2, avg.y - EdgeFigure.DEF_HEIGHT / 2, EdgeFigure.DEF_WIDTH, EdgeFigure.DEF_HEIGHT ) ); } } oldNames = new HashMap< Edge, String >(); for ( Edge t : mixMap.keySet() ) { if ( t.getGraph() != outer ) continue; oldColors.put( t, t.getColor() ); ColorMix mix = mixMap.get( t ); t.setColor( new Color( null, mix.r / mix.parts, mix.g / mix.parts, mix.b / mix.parts ) ); oldNames.put( t, t.getName() ); t.setName( "Composed edge" ); } oldParents.put( inner, inner.getParent() ); inner.getParent().removeChild( inner ); oldLayouts = outer.organiseGraph(); }*/ // // @Override // public void undo() // { // if ( !executed ) // return; // for ( Edge edge : oldColors.keySet() ) { // edge.setColor( oldColors.get( edge ) ); // edge.setName( oldNames.get( edge ) ); // } // outer.undoOrganiseGraph( oldLayouts ); // // for ( Layoutable t : oldParents.keySet() ) { // if ( t.getParent() != null ) // t.getParent().removeChild( t ); // if ( oldLayouts2.keySet().contains( t ) ) // t.setLayout( oldLayouts2.get( t ) ); // if ( t == inner && reactumSpecialCase ) // ( ( Reaction )oldParents.get( t ) ).addChild( t, true ); // else // oldParents.get( t ).addChild( t ); // } // for ( Layoutable t : oldLayouts2.keySet() ) { // if ( oldParents.keySet().contains( t ) ) // continue; // t.setLayout( oldLayouts2.get( t ) ); // } // // NameBar innerNames = outer.getInnerNames(); // outer.removeChild( innerNames ); // inner.addChild( innerNames ); // outer.addChild( oldInnerNames ); // // for ( Link link : links ) { // if ( link.isConnected() ) // link.disconnect(); // else // link.reconnect(); // } // inner.checkLabels( inner ); // outer.checkLabels( outer ); // } }
false
true
public void redo(){ if ( !executed ) return; ChangeGroup cg = new ChangeGroup(); /**start placing roots in sites */ for(Site site : placeMap.keySet()){ Container parent=site.getParent(); Root root= placeMap.get(site); for (Layoutable children: root.getChildren()){ // //OLDTODO parent.addChild(children); ////children.getParent().removeChild(children); //OLDTODO children.setParent(parent); } //OLDTODO parent.removeChild(site); } for (InnerName iNames:inner.getInnerNames()){ //OLDTODO outer.addChild(iNames); //OLDTODo iNames.setParent(outer); } /** connect link and ports */ HashMap<Link, List<Point>> connection= new HashMap<Link, List<Point>> (); for(InnerName innerName : linkMap.keySet()){ Link link=innerName.getLink(); link.removePoint(innerName); OuterName outerName=linkMap.get(innerName); System.out.println("compute innerName"+ innerName.getName()); List<Point> points=new ArrayList<Point>(); points= outerName.getPoints(); connection.put(link, points); //OLDTODO outer.removeChild(innerName); } /** from hashMap connection create update links*/ for(Link link : connection.keySet()){ List<Point> points=connection.get(link); System.out.println(points.size()); for(int i=0;i<points.size();i++){ System.out.println(points.size()); Point p=points.get(i); points.get(i).getLink().removePoint(points.get(i)); System.out.println(points.size()); if(link instanceof OuterName){ ((OuterName)link).addPoint(p); }else if (link instanceof Edge){ ((Edge)link).addPoint(p); } } } //inner.dispose(); //inner.getParent().removeChild(inner); outer.relayout(); }
public void redo(){ if ( !executed ) return; ChangeGroup cg = new ChangeGroup(); /**start placing roots in sites */ for(Site site : placeMap.keySet()){ Container parent=site.getParent(); Root root= placeMap.get(site); for (Layoutable children: root.getChildren()){ // //OLDTODO parent.addChild(children); ////children.getParent().removeChild(children); //OLDTODO children.setParent(parent); } //OLDTODO parent.removeChild(site); } for (InnerName iNames:inner.getInnerNames()){ //OLDTODO outer.addChild(iNames); //OLDTODo iNames.setParent(outer); } /** connect link and ports */ HashMap<Link, List<Point>> connection= new HashMap<Link, List<Point>> (); for(InnerName innerName : linkMap.keySet()){ Link link=innerName.getLink(); //TODO link.removePoint(innerName); OuterName outerName=linkMap.get(innerName); System.out.println("compute innerName"+ innerName.getName()); List<Point> points=new ArrayList<Point>(); points= outerName.getPoints(); connection.put(link, points); //OLDTODO outer.removeChild(innerName); } /** from hashMap connection create update links*/ for(Link link : connection.keySet()){ List<Point> points=connection.get(link); System.out.println(points.size()); for(int i=0;i<points.size();i++){ System.out.println(points.size()); Point p=points.get(i); //TODO points.get(i).getLink().removePoint(points.get(i)); System.out.println(points.size()); if(link instanceof OuterName){ //TODO ((OuterName)link).addPoint(p); }else if (link instanceof Edge){ //TODO ((Edge)link).addPoint(p); } } } //inner.dispose(); //inner.getParent().removeChild(inner); outer.relayout(); }
diff --git a/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/PortalSiteHelperImpl.java b/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/PortalSiteHelperImpl.java index 82294b2d..6ef94677 100644 --- a/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/PortalSiteHelperImpl.java +++ b/portal-impl/impl/src/java/org/sakaiproject/portal/charon/site/PortalSiteHelperImpl.java @@ -1,1130 +1,1133 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 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.portal.charon.site; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.alias.api.Alias; import org.sakaiproject.alias.cover.AliasService; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.user.cover.PreferencesService; import org.sakaiproject.user.api.Preferences; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.EntityProducer; import org.sakaiproject.entity.api.EntitySummary; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.Summary; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.portal.api.PageFilter; import org.sakaiproject.portal.api.Portal; import org.sakaiproject.portal.api.PortalSiteHelper; import org.sakaiproject.portal.api.SiteView; import org.sakaiproject.portal.api.SiteView.View; import org.sakaiproject.portal.charon.ToolHelperImpl; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.thread_local.cover.ThreadLocalManager; import org.sakaiproject.time.api.Time; import org.sakaiproject.tool.api.Placement; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.user.cover.PreferencesService; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.ArrayUtil; import org.sakaiproject.util.MapUtil; import org.sakaiproject.util.Web; /** * @author ieb * @since Sakai 2.4 * @version $Rev$ */ public class PortalSiteHelperImpl implements PortalSiteHelper { // Alias prefix for page aliases. Use Entity.SEPARATOR as IDs shouldn't contain it. private static final String PAGE_ALIAS = Entity.SEPARATOR+ "pagealias"+ Entity.SEPARATOR; private static final Log log = LogFactory.getLog(PortalSiteHelper.class); private final String PROP_PARENT_ID = SiteService.PROP_PARENT_ID; private final String PROP_HTML_INCLUDE = "sakai:htmlInclude"; protected final static String CURRENT_PLACEMENT = "sakai:ToolComponent:current.placement"; private Portal portal; private boolean lookForPageAliases; // 2.3 back port // private final String PROP_PARENT_ID = "sakai:parent-id"; private ToolHelperImpl toolHelper = new ToolHelperImpl(); /** * @param portal */ public PortalSiteHelperImpl(Portal portal, boolean lookForPageAliases) { this.portal = portal; this.lookForPageAliases = lookForPageAliases; } /* (non-Javadoc) * @see org.sakaiproject.portal.api.PortalSiteHelper#doGatewaySiteList() */ public boolean doGatewaySiteList() { String gatewaySiteListPref = ServerConfigurationService .getString("gatewaySiteList"); if (gatewaySiteListPref == null) return false; return (gatewaySiteListPref.trim().length() > 0); } // Determine if we are to do multiple tabs for the anonymous view (Gateway) /** * @see org.sakaiproject.portal.api.PortalSiteHelper#doGatewaySiteList() */ public String getGatewaySiteId() { String gatewaySiteListPref = ServerConfigurationService .getString("gatewaySiteList"); if (gatewaySiteListPref == null) return null; String[] gatewaySiteIds = getGatewaySiteList(); if (gatewaySiteIds == null) { return null; } // Loop throught the sites making sure they exist and are visitable for (int i = 0; i < gatewaySiteIds.length; i++) { String siteId = gatewaySiteIds[i]; Site site = null; try { site = getSiteVisit(siteId); } catch (IdUnusedException e) { continue; } catch (PermissionException e) { continue; } if (site != null) { return siteId; } } log.warn("No suitable gateway sites found, gatewaySiteList preference had " + gatewaySiteIds.length + " sites."); return null; } // Return the list of tabs for the anonymous view (Gateway) // If we have a list of sites, return that - if not simply pull in the // single // Gateway site /** * @return */ private String[] getGatewaySiteList() { String gatewaySiteListPref = ServerConfigurationService .getString("gatewaySiteList"); if (gatewaySiteListPref == null || gatewaySiteListPref.trim().length() < 1) { gatewaySiteListPref = ServerConfigurationService.getGatewaySiteId(); } if (gatewaySiteListPref == null || gatewaySiteListPref.trim().length() < 1) return null; String[] gatewaySites = gatewaySiteListPref.split(","); if (gatewaySites.length < 1) return null; return gatewaySites; } /* * Get All Sites which indicate the current site as their parent */ // TODO: Move into SiteStructureProvider /** * @see org.sakaiproject.portal.api.PortalSiteHelper#getSubSites(org.sakaiproject.site.api.Site) */ public List<Site> getSubSites(Site site) { if (site == null) return null; Map<String, String> propMap = new HashMap<String, String>(); propMap.put(PROP_PARENT_ID, site.getId()); List<Site> mySites = SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, null, propMap, org.sakaiproject.site.api.SiteService.SortType.TITLE_ASC, null); return mySites; } public List<Map> getSitesInContext(String context, String userId) { return null; } /** * This method takes a list of sites and organizes it into a list of maps of * properties. There is an additional complication that the depth contains * informaiton arround. * * @see org.sakaiproject.portal.api.PortalSiteHelper#convertSitesToMaps(javax.servlet.http.HttpServletRequest, * java.util.List, java.lang.String, java.lang.String, * java.lang.String, boolean, boolean, boolean, boolean, * java.lang.String, boolean) */ public List<Map> convertSitesToMaps(HttpServletRequest req, List mySites, String prefix, String currentSiteId, String myWorkspaceSiteId, boolean includeSummary, boolean expandSite, boolean resetTools, boolean doPages, String toolContextPath, boolean loggedIn) { List<Map> l = new ArrayList<Map>(); Map<String, Integer> depthChart = new HashMap<String, Integer>(); boolean motdDone = false; // We only compute the depths if there is no user chosen order boolean computeDepth = true; Session session = SessionManager.getCurrentSession(); if ( session != null ) { Preferences prefs = PreferencesService.getPreferences(session.getUserId()); ResourceProperties props = prefs.getProperties("sakai:portal:sitenav"); List propList = props.getPropertyList("order"); if (propList != null) { computeDepth = false; } } // Determine the depths of the child sites if needed for (Iterator i = mySites.iterator(); i.hasNext();) { Site s = (Site) i.next(); // The first site is the current site if (currentSiteId == null) currentSiteId = s.getId(); Integer cDepth = new Integer(0); if ( computeDepth ) { ResourceProperties rp = s.getProperties(); String ourParent = rp.getProperty(PROP_PARENT_ID); // System.out.println("Depth Site:"+s.getTitle()+ // "parent="+ourParent); if (ourParent != null) { Integer pDepth = depthChart.get(ourParent); if (pDepth != null) { cDepth = pDepth + 1; } } depthChart.put(s.getId(), cDepth); // System.out.println("Depth = "+cDepth); } Map m = convertSiteToMap(req, s, prefix, currentSiteId, myWorkspaceSiteId, includeSummary, expandSite, resetTools, doPages, toolContextPath, loggedIn); // Add the Depth of the site m.put("depth", cDepth); if (includeSummary && m.get("rssDescription") == null) { if (!motdDone) { summarizeTool(m, s, "sakai.motd"); motdDone = true; } else { summarizeTool(m, s, "sakai.announcements"); } } l.add(m); } return l; } /** * Explode a site into a map suitable for use in the map * * @see org.sakaiproject.portal.api.PortalSiteHelper#convertSiteToMap(javax.servlet.http.HttpServletRequest, * org.sakaiproject.site.api.Site, java.lang.String, java.lang.String, * java.lang.String, boolean, boolean, boolean, boolean, * java.lang.String, boolean) */ public Map convertSiteToMap(HttpServletRequest req, Site s, String prefix, String currentSiteId, String myWorkspaceSiteId, boolean includeSummary, boolean expandSite, boolean resetTools, boolean doPages, String toolContextPath, boolean loggedIn) { if (s == null) return null; Map<String, Object> m = new HashMap<String, Object>(); // In case the effective is different than the actual site String effectiveSite = getSiteEffectiveId(s); boolean isCurrentSite = currentSiteId != null && (s.getId().equals(currentSiteId) || effectiveSite .equals(currentSiteId)); m.put("isCurrentSite", Boolean.valueOf(isCurrentSite)); m.put("isMyWorkspace", Boolean.valueOf(myWorkspaceSiteId != null && (s.getId().equals(myWorkspaceSiteId) || effectiveSite .equals(myWorkspaceSiteId)))); m.put("siteTitle", Web.escapeHtml(s.getTitle())); m.put("siteDescription", Web.escapeHtml(s.getDescription())); String siteUrl = Web.serverUrl(req) + ServerConfigurationService.getString("portalPath") + "/"; if (prefix != null) siteUrl = siteUrl + prefix + "/"; // siteUrl = siteUrl + Web.escapeUrl(siteHelper.getSiteEffectiveId(s)); m.put("siteUrl", siteUrl + Web.escapeUrl(getSiteEffectiveId(s))); // TODO: This should come from the site neighbourhood. ResourceProperties rp = s.getProperties(); String ourParent = rp.getProperty(PROP_PARENT_ID); boolean isChild = ourParent != null; m.put("isChild", Boolean.valueOf(isChild)); m.put("parentSite", ourParent); // Get the current site hierarchy if (isChild && isCurrentSite) { List<Site> pwd = getPwd(s, ourParent); if (pwd != null) { List<Map> l = new ArrayList<Map>(); for (int i = 0; i < pwd.size(); i++) { Site site = pwd.get(i); // System.out.println("PWD["+i+"]="+site.getId()+" // "+site.getTitle()); Map<String, Object> pm = new HashMap<String, Object>(); pm.put("siteTitle", Web.escapeHtml(site.getTitle())); pm.put("siteUrl", siteUrl + Web.escapeUrl(getSiteEffectiveId(site))); l.add(pm); } m.put("pwd", l); } } if (includeSummary) { summarizeTool(m, s, "sakai.announce"); } if (expandSite) { Map pageMap = pageListToMap(req, loggedIn, s, /* SitePage */null, toolContextPath, prefix, doPages, resetTools, includeSummary); m.put("sitePages", pageMap); } return m; } /** * Gets the path of sites back to the root of the tree. * @param s * @param ourParent * @return */ private List<Site> getPwd(Site s, String ourParent) { if (ourParent == null) return null; // System.out.println("Getting Current Working Directory for // "+s.getId()+" "+s.getTitle()); int depth = 0; Vector<Site> pwd = new Vector<Site>(); Set<String> added = new HashSet<String>(); // Add us to the list at the top (will become the end) pwd.add(s); added.add(s.getId()); // Make sure we don't go on forever while (ourParent != null && depth < 8) { depth++; Site site = null; try { site = SiteService.getSiteVisit(ourParent); } catch (Exception e) { break; } // We have no patience with loops if (added.contains(site.getId())) break; // System.out.println("Adding Parent "+site.getId()+" // "+site.getTitle()); pwd.insertElementAt(site, 0); // Push down stack added.add(site.getId()); ResourceProperties rp = site.getProperties(); ourParent = rp.getProperty(PROP_PARENT_ID); } // PWD is only defined for > 1 site if (pwd.size() < 2) return null; return pwd; } /** * Produce a page and/or a tool list doPage = true is best for the * tabs-based portal and for RSS - these think in terms of pages doPage = * false is best for the portlet-style - it unrolls all of the tools unless * a page is marked as a popup. If the page is a popup - it is left a page * and marked as such. restTools = true - generate resetting tool URLs. * * @see org.sakaiproject.portal.api.PortalSiteHelper#pageListToMap(javax.servlet.http.HttpServletRequest, * boolean, org.sakaiproject.site.api.Site, * org.sakaiproject.site.api.SitePage, java.lang.String, * java.lang.String, boolean, boolean, boolean) */ public Map pageListToMap(HttpServletRequest req, boolean loggedIn, Site site, SitePage page, String toolContextPath, String portalPrefix, boolean doPages, boolean resetTools, boolean includeSummary) { Map<String, Object> theMap = new HashMap<String, Object>(); String pageUrl = Web.returnUrl(req, "/" + portalPrefix + "/" + Web.escapeUrl(getSiteEffectiveId(site)) + "/page/"); String toolUrl = Web.returnUrl(req, "/" + portalPrefix + "/" + Web.escapeUrl(getSiteEffectiveId(site))); if (resetTools) { toolUrl = toolUrl + "/tool-reset/"; } else { toolUrl = toolUrl + "/tool/"; } String pagePopupUrl = Web.returnUrl(req, "/page/"); boolean showHelp = ServerConfigurationService.getBoolean("display.help.menu", true); String iconUrl = ""; try { if (site.getIconUrlFull() != null) iconUrl = new URI(site.getIconUrlFull()).toString(); } catch (URISyntaxException uex) { log.debug("Icon URL is invalid: " + site.getIconUrlFull()); } boolean published = site.isPublished(); String type = site.getType(); theMap.put("pageNavPublished", Boolean.valueOf(published)); theMap.put("pageNavType", type); theMap.put("pageNavIconUrl", iconUrl); String htmlInclude = site.getProperties().getProperty(PROP_HTML_INCLUDE); if (htmlInclude != null) theMap.put("siteHTMLInclude", htmlInclude); // theMap.put("pageNavSitToolsHead", // Web.escapeHtml(rb.getString("sit_toolshead"))); // order the pages based on their tools and the tool order for the // site type // List pages = site.getOrderedPages(); List pages = getPermittedPagesInOrder(site); List<Map> l = new ArrayList<Map>(); for (Iterator i = pages.iterator(); i.hasNext();) { SitePage p = (SitePage) i.next(); // check if current user has permission to see page // we will draw page button if it have permission to see at least // one tool on the page List pTools = p.getTools(); ToolConfiguration firstTool = null; if (pTools != null && pTools.size() > 0) { firstTool = (ToolConfiguration) pTools.get(0); } String toolsOnPage = null; boolean current = (page != null && p.getId().equals(page.getId()) && !p .isPopUp()); String alias = lookupPageToAlias(site.getId(), p); String pagerefUrl = pageUrl + Web.escapeUrl((alias != null)?alias:p.getId()); if (doPages || p.isPopUp()) { Map<String, Object> m = new HashMap<String, Object>(); m.put("isPage", Boolean.valueOf(true)); m.put("current", Boolean.valueOf(current)); m.put("ispopup", Boolean.valueOf(p.isPopUp())); m.put("pagePopupUrl", pagePopupUrl); m.put("pageTitle", Web.escapeHtml(p.getTitle())); m.put("jsPageTitle", Web.escapeJavascript(p.getTitle())); m.put("pageId", Web.escapeUrl(p.getId())); m.put("jsPageId", Web.escapeJavascript(p.getId())); m.put("pageRefUrl", pagerefUrl); - Iterator tools = pTools.iterator(); - //get the tool descriptions for this page, typically only one per page, execpt for the Home page - StringBuffer desc = new StringBuffer(); - int tCount = 0; - while(tools.hasNext()){ - ToolConfiguration t = (ToolConfiguration)tools.next(); - if (tCount > 0){ - desc.append(" | "); - } - if ( t.getTool() == null ) continue; - desc.append(t.getTool().getDescription()); - tCount++; + StringBuffer desc = new StringBuffer(); + if (pTools != null) { + Iterator tools = pTools.iterator(); + //get the tool descriptions for this page, typically only one per page, execpt for the Home page + int tCount = 0; + while(tools.hasNext()){ + ToolConfiguration t = (ToolConfiguration)tools.next(); + if (tCount > 0){ + desc.append(" | "); + } + if ( t.getTool() == null ) continue; + desc.append(t.getTool().getDescription()); + tCount++; + } } // Just make sure no double quotes... String description = desc.toString().replace('"','-'); m.put("description", desc.toString()); - if (toolsOnPage != null) m.put("toolsOnPage", toolsOnPage); + // toolsOnPage is always null + //if (toolsOnPage != null) m.put("toolsOnPage", toolsOnPage); if (includeSummary) summarizePage(m, site, p); if (firstTool != null) { String menuClass = firstTool.getToolId(); menuClass = "icon-" + menuClass.replace('.', '-'); m.put("menuClass", menuClass); } else { m.put("menuClass", "icon-default-tool"); } m.put("pageProps", createPageProps(p)); // this is here to allow the tool reorder to work m.put("_sitePage", p); l.add(m); continue; } // Loop through the tools again and Unroll the tools Iterator iPt = pTools.iterator(); while (iPt.hasNext()) { ToolConfiguration placement = (ToolConfiguration) iPt.next(); String toolrefUrl = toolUrl + Web.escapeUrl(placement.getId()); Map<String, Object> m = new HashMap<String, Object>(); m.put("isPage", Boolean.valueOf(false)); m.put("toolId", Web.escapeUrl(placement.getId())); m.put("jsToolId", Web.escapeJavascript(placement.getId())); m.put("toolRegistryId", placement.getToolId()); m.put("toolTitle", Web.escapeHtml(placement.getTitle())); m.put("jsToolTitle", Web.escapeJavascript(placement.getTitle())); m.put("toolrefUrl", toolrefUrl); String menuClass = placement.getToolId(); menuClass = "icon-" + menuClass.replace('.', '-'); m.put("menuClass", menuClass); // this is here to allow the tool reorder to work if requried. m.put("_placement", placement); l.add(m); } } PageFilter pageFilter = portal.getPageFilter(); if (pageFilter != null) { l = pageFilter.filterPlacements(l, site); } theMap.put("pageNavTools", l); theMap.put("pageMaxIfSingle", ServerConfigurationService.getBoolean( "portal.experimental.maximizesinglepage", false)); theMap.put("pageNavToolsCount", Integer.valueOf(l.size())); String helpUrl = ServerConfigurationService.getHelpUrl(null); theMap.put("pageNavShowHelp", Boolean.valueOf(showHelp)); theMap.put("pageNavHelpUrl", helpUrl); theMap.put("helpMenuClass", "icon-sakai-help"); theMap.put("subsiteClass", "icon-sakai-subsite"); // theMap.put("pageNavSitContentshead", // Web.escapeHtml(rb.getString("sit_contentshead"))); // Display presence? Global property display.users.present may be always / never / true / false // If true or false, the value may be overriden by the site property display-users-present // which may be true or false. boolean showPresence; String globalShowPresence = ServerConfigurationService.getString("display.users.present"); if ("never".equals(globalShowPresence)) { showPresence = false; } else if ("always".equals(globalShowPresence)) { showPresence = true; } else { String showPresenceSite = site.getProperties().getProperty("display-users-present"); if (showPresenceSite == null) { showPresence = Boolean.valueOf(globalShowPresence).booleanValue(); } else { showPresence = Boolean.valueOf(showPresenceSite).booleanValue(); } } // Check to see if this is a my workspace site, and if so, whether presence is disabled if (showPresence && SiteService.isUserSite(site.getId()) && !ServerConfigurationService.getBoolean("display.users.present.myworkspace", true)) showPresence = false; String presenceUrl = Web.returnUrl(req, "/presence/" + Web.escapeUrl(site.getId())); // theMap.put("pageNavSitPresenceTitle", // Web.escapeHtml(rb.getString("sit_presencetitle"))); // theMap.put("pageNavSitPresenceFrameTitle", // Web.escapeHtml(rb.getString("sit_presenceiframetit"))); theMap.put("pageNavShowPresenceLoggedIn", Boolean.valueOf(showPresence && loggedIn)); theMap.put("pageNavPresenceUrl", presenceUrl); return theMap; } /** * @param p * @return */ private Map createPageProps(SitePage p) { Map properties = new HashMap(); for (Iterator<String> i = p.getProperties().getPropertyNames(); i.hasNext();) { String propName = i.next(); properties.put(propName, p.getProperties().get(propName)); } return properties; } /** * @see org.sakaiproject.portal.api.PortalSiteHelper#getMyWorkspace(org.sakaiproject.tool.api.Session) */ public Site getMyWorkspace(Session session) { String siteId = SiteService.getUserSiteId(session.getUserId()); // Make sure we can visit Site site = null; try { site = getSiteVisit(siteId); } catch (IdUnusedException e) { site = null; } catch (PermissionException e) { site = null; } return site; } /* * Temporarily set a placement with the site id as the context - we do not * set a tool ID this will not be a rich enough placement to do *everything* * but for those services which call * ToolManager.getCurrentPlacement().getContext() to contextualize their * information - it wil be sufficient. */ public boolean setTemporaryPlacement(Site site) { if (site == null) return false; Placement ppp = ToolManager.getCurrentPlacement(); if (ppp != null && site.getId().equals(ppp.getContext())) { return true; } // Create a site-only placement Placement placement = new org.sakaiproject.util.Placement("portal-temporary", /* toolId */ null, /* tool */null, /* config */null, /* context */site.getId(), /* title */null); ThreadLocalManager.set(CURRENT_PLACEMENT, placement); // Debugging ppp = ToolManager.getCurrentPlacement(); if (ppp == null) { System.out.println("WARNING portal-temporary placement not set - null"); } else { String cont = ppp.getContext(); if (site.getId().equals(cont)) { return true; } else { System.out.println("WARNING portal-temporary placement mismatch site=" + site.getId() + " context=" + cont); } } return false; } public boolean summarizePage(Map m, Site site, SitePage page) { List pTools = page.getTools(); Iterator iPt = pTools.iterator(); while (iPt.hasNext()) { ToolConfiguration placement = (ToolConfiguration) iPt.next(); if (summarizeTool(m, site, placement.getToolId())) { return true; } } return false; } /** * There must be a better way of doing this as this hard codes the services * in surely there should be some whay of looking up the serivce and making * the getSummary part of an interface. TODO: Add an interface beside * EntityProducer to generate summaries Make this discoverable * * @param m * @param site * @param toolIdentifier * @return */ private boolean summarizeTool(Map m, Site site, String toolIdentifier) { if (site == null) return false; setTemporaryPlacement(site); Map newMap = null; /* * This is a new, cooler way to do this (I hope) chmaurer... (ieb) Yes:) * All summaries now through this interface */ // offer to all EntityProducers for (Iterator i = EntityManager.getEntityProducers().iterator(); i.hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntitySummary) { try { EntitySummary es = (EntitySummary) ep; // if this producer claims this tool id if (ArrayUtil.contains(es.summarizableToolIds(), toolIdentifier)) { String summarizableReference = es.getSummarizableReference(site .getId(), toolIdentifier); newMap = es.getSummary(summarizableReference, 5, 30); } } catch (Throwable t) { log.warn( "Error encountered while asking EntitySummary to getSummary() for: " + toolIdentifier, t); } } } if (newMap != null) { return (MapUtil.copyHtml(m, "rssDescription", newMap, Summary.PROP_DESCRIPTION) && MapUtil.copy(m, "rssPubdate", newMap, Summary.PROP_PUBDATE)); } else { Time modDate = site.getModifiedTime(); // Yes, some sites have never been modified if (modDate != null) { m.put("rssPubDate", (modDate.toStringRFC822Local())); } return false; } } /** * If this is a user site, return an id based on the user EID, otherwise * just return the site id. * * @param site * The site. * @return The effective site id. */ public String getSiteEffectiveId(Site site) { if (SiteService.isUserSite(site.getId())) { try { String userId = SiteService.getSiteUserId(site.getId()); String eid = UserDirectoryService.getUserEid(userId); return SiteService.getUserSiteId(eid); } catch (UserNotDefinedException e) { log.warn("getSiteEffectiveId: user eid not found for user site: " + site.getId()); } } else { String displayId = portal.getSiteNeighbourhoodService().lookupSiteAlias(site.getReference(), null); if (displayId != null) { return displayId; } } return site.getId(); } /** * Do the getSiteVisit, but if not found and the id is a user site, try * translating from user EID to ID. * * @param siteId * The Site Id. * @return The Site. * @throws PermissionException * If not allowed. * @throws IdUnusedException * If not found. */ public Site getSiteVisit(String siteId) throws PermissionException, IdUnusedException { try { return SiteService.getSiteVisit(siteId); } catch (IdUnusedException e) { if (SiteService.isUserSite(siteId)) { try { String userEid = SiteService.getSiteUserId(siteId); String userId = UserDirectoryService.getUserId(userEid); String alternateSiteId = SiteService.getUserSiteId(userId); return SiteService.getSiteVisit(alternateSiteId); } catch (UserNotDefinedException ee) { } } else { String reference = portal.getSiteNeighbourhoodService().parseSiteAlias(siteId); Reference ref = EntityManager.getInstance().newReference(reference); try { return SiteService.getSiteVisit(ref.getId()); } catch (IdUnusedException iue) { } } // re-throw if that didn't work throw e; } } /** * Retrieve the list of pages in this site, checking to see if the user has * permission to see the page - by checking the permissions of tools on the * page. * * @param site * @return */ private List getPermittedPagesInOrder(Site site) { // Get all of the pages List pages = site.getOrderedPages(); List newPages = new ArrayList(); for (Iterator i = pages.iterator(); i.hasNext();) { // check if current user has permission to see page SitePage p = (SitePage) i.next(); List pTools = p.getTools(); Iterator iPt = pTools.iterator(); boolean allowPage = false; while (iPt.hasNext()) { ToolConfiguration placement = (ToolConfiguration) iPt.next(); boolean thisTool = allowTool(site, placement); if (thisTool) allowPage = true; } if (allowPage) newPages.add(p); } PageFilter pageFilter = portal.getPageFilter(); if (pageFilter != null) { newPages = pageFilter.filter(newPages, site); } return newPages; } /** * Make sure that we have a proper page selected in the site pageid is * generally the last page used in the site. pageId must be in the site and * the user must have permission for the page as well. * * @see org.sakaiproject.portal.api.PortalSiteHelper#lookupSitePage(java.lang.String, * org.sakaiproject.site.api.Site) */ public SitePage lookupSitePage(String pageId, Site site) { // Make sure we have some permitted pages List pages = getPermittedPagesInOrder(site); if (pages.isEmpty()) return null; SitePage page = site.getPage(pageId); if (page == null) { page = lookupAliasToPage(pageId, site); if (page == null) { page = (SitePage) pages.get(0); return page; } } // Make sure that they user has permission for the page. // If the page is not in the permitted list go to the first // page. boolean found = false; for (Iterator i = pages.iterator(); i.hasNext();) { SitePage p = (SitePage) i.next(); if (p.getId().equals(page.getId())) return page; } return (SitePage) pages.get(0); } public SitePage lookupAliasToPage(String alias, Site site) { //Shortcut if we aren't using page aliases. if (!lookForPageAliases) { return null; } SitePage page = null; if (alias != null && alias.length() > 0) { try { // Use page#{siteId}:{pageAlias} So we can scan for fist colon and alias can contain any character String refString = AliasService.getTarget(buildAlias(alias, site)); String aliasPageId = EntityManager.newReference(refString).getId(); page = (SitePage) site.getPage(aliasPageId); } catch (IdUnusedException e) { if (log.isDebugEnabled()) { log.debug("Alias does not resolve " + e.getMessage()); } } } return page; } public String lookupPageToAlias(String siteId, SitePage page) { // Shortcut if we aren't using page aliases. if (!lookForPageAliases) { return null; } String alias = null; List<Alias> aliases = AliasService.getAliases(page.getReference()); if (aliases.size() > 0) { if (aliases.size() > 1 && log.isWarnEnabled()) { log.warn("More than one alias for: "+siteId+ ":"+ page.getId()); // Sort on ID so it is consistent in the alias it uses. Collections.sort(aliases, getAliasComparator()); } alias = aliases.get(0).getId(); alias = parseAlias(alias, siteId); } return alias; } /** * Find the short alias. * @param alias * @return */ private String parseAlias(String aliasId, String siteId) { String prefix = PAGE_ALIAS+ siteId+ Entity.SEPARATOR; String alias = null; if (aliasId.startsWith(prefix)) { alias = aliasId.substring(prefix.length()); } return alias; } private String buildAlias(String alias, Site site) { return PAGE_ALIAS+site.getId()+Entity.SEPARATOR+alias; } private Comparator<Alias> getAliasComparator() { return new Comparator<Alias>() { public int compare(Alias o1, Alias o2) { // Sort by date, then by ID to assure consistent order. return o1.getCreatedTime().compareTo(o2.getCreatedTime()) * 10 + o1.getId().compareTo(o2.getId()); } }; } /** * @see org.sakaiproject.portal.api.PortalSiteHelper#allowTool(org.sakaiproject.site.api.Site, * org.sakaiproject.tool.api.Placement) */ public boolean allowTool(Site site, Placement placement) { return toolHelper.allowTool(site, placement); } /* * (non-Javadoc) * * @see org.sakaiproject.portal.api.PortalSiteHelper#getSitesView(org.sakaiproject.portal.api.SiteView.View, * javax.servlet.http.HttpServletRequest, * org.sakaiproject.tool.api.Session, java.lang.String) */ public SiteView getSitesView(View view, HttpServletRequest request, Session session, String siteId) { switch (view) { case CURRENT_SITE_VIEW: return new CurrentSiteViewImpl(this, portal.getSiteNeighbourhoodService(), request, session, siteId, SiteService .getInstance(), ServerConfigurationService.getInstance(), PreferencesService.getInstance()); case ALL_SITES_VIEW: return new AllSitesViewImpl(this, portal.getSiteNeighbourhoodService(), request, session, siteId, SiteService .getInstance(), ServerConfigurationService.getInstance(), PreferencesService.getInstance()); case DEFAULT_SITE_VIEW: return new DefaultSiteViewImpl(this, portal.getSiteNeighbourhoodService(), request, session, siteId, SiteService .getInstance(), ServerConfigurationService.getInstance(), PreferencesService.getInstance()); case DHTML_MORE_VIEW: return new MoreSiteViewImpl(this,portal.getSiteNeighbourhoodService(), request, session, siteId, SiteService .getInstance(), ServerConfigurationService.getInstance(), PreferencesService.getInstance()); case SUB_SITES_VIEW: return new SubSiteViewImpl(this, portal.getSiteNeighbourhoodService(), request, session, siteId, SiteService .getInstance(), ServerConfigurationService.getInstance(), PreferencesService.getInstance()); } return null; } }
false
true
public Map pageListToMap(HttpServletRequest req, boolean loggedIn, Site site, SitePage page, String toolContextPath, String portalPrefix, boolean doPages, boolean resetTools, boolean includeSummary) { Map<String, Object> theMap = new HashMap<String, Object>(); String pageUrl = Web.returnUrl(req, "/" + portalPrefix + "/" + Web.escapeUrl(getSiteEffectiveId(site)) + "/page/"); String toolUrl = Web.returnUrl(req, "/" + portalPrefix + "/" + Web.escapeUrl(getSiteEffectiveId(site))); if (resetTools) { toolUrl = toolUrl + "/tool-reset/"; } else { toolUrl = toolUrl + "/tool/"; } String pagePopupUrl = Web.returnUrl(req, "/page/"); boolean showHelp = ServerConfigurationService.getBoolean("display.help.menu", true); String iconUrl = ""; try { if (site.getIconUrlFull() != null) iconUrl = new URI(site.getIconUrlFull()).toString(); } catch (URISyntaxException uex) { log.debug("Icon URL is invalid: " + site.getIconUrlFull()); } boolean published = site.isPublished(); String type = site.getType(); theMap.put("pageNavPublished", Boolean.valueOf(published)); theMap.put("pageNavType", type); theMap.put("pageNavIconUrl", iconUrl); String htmlInclude = site.getProperties().getProperty(PROP_HTML_INCLUDE); if (htmlInclude != null) theMap.put("siteHTMLInclude", htmlInclude); // theMap.put("pageNavSitToolsHead", // Web.escapeHtml(rb.getString("sit_toolshead"))); // order the pages based on their tools and the tool order for the // site type // List pages = site.getOrderedPages(); List pages = getPermittedPagesInOrder(site); List<Map> l = new ArrayList<Map>(); for (Iterator i = pages.iterator(); i.hasNext();) { SitePage p = (SitePage) i.next(); // check if current user has permission to see page // we will draw page button if it have permission to see at least // one tool on the page List pTools = p.getTools(); ToolConfiguration firstTool = null; if (pTools != null && pTools.size() > 0) { firstTool = (ToolConfiguration) pTools.get(0); } String toolsOnPage = null; boolean current = (page != null && p.getId().equals(page.getId()) && !p .isPopUp()); String alias = lookupPageToAlias(site.getId(), p); String pagerefUrl = pageUrl + Web.escapeUrl((alias != null)?alias:p.getId()); if (doPages || p.isPopUp()) { Map<String, Object> m = new HashMap<String, Object>(); m.put("isPage", Boolean.valueOf(true)); m.put("current", Boolean.valueOf(current)); m.put("ispopup", Boolean.valueOf(p.isPopUp())); m.put("pagePopupUrl", pagePopupUrl); m.put("pageTitle", Web.escapeHtml(p.getTitle())); m.put("jsPageTitle", Web.escapeJavascript(p.getTitle())); m.put("pageId", Web.escapeUrl(p.getId())); m.put("jsPageId", Web.escapeJavascript(p.getId())); m.put("pageRefUrl", pagerefUrl); Iterator tools = pTools.iterator(); //get the tool descriptions for this page, typically only one per page, execpt for the Home page StringBuffer desc = new StringBuffer(); int tCount = 0; while(tools.hasNext()){ ToolConfiguration t = (ToolConfiguration)tools.next(); if (tCount > 0){ desc.append(" | "); } if ( t.getTool() == null ) continue; desc.append(t.getTool().getDescription()); tCount++; } // Just make sure no double quotes... String description = desc.toString().replace('"','-'); m.put("description", desc.toString()); if (toolsOnPage != null) m.put("toolsOnPage", toolsOnPage); if (includeSummary) summarizePage(m, site, p); if (firstTool != null) { String menuClass = firstTool.getToolId(); menuClass = "icon-" + menuClass.replace('.', '-'); m.put("menuClass", menuClass); } else { m.put("menuClass", "icon-default-tool"); } m.put("pageProps", createPageProps(p)); // this is here to allow the tool reorder to work m.put("_sitePage", p); l.add(m); continue; } // Loop through the tools again and Unroll the tools Iterator iPt = pTools.iterator(); while (iPt.hasNext()) { ToolConfiguration placement = (ToolConfiguration) iPt.next(); String toolrefUrl = toolUrl + Web.escapeUrl(placement.getId()); Map<String, Object> m = new HashMap<String, Object>(); m.put("isPage", Boolean.valueOf(false)); m.put("toolId", Web.escapeUrl(placement.getId())); m.put("jsToolId", Web.escapeJavascript(placement.getId())); m.put("toolRegistryId", placement.getToolId()); m.put("toolTitle", Web.escapeHtml(placement.getTitle())); m.put("jsToolTitle", Web.escapeJavascript(placement.getTitle())); m.put("toolrefUrl", toolrefUrl); String menuClass = placement.getToolId(); menuClass = "icon-" + menuClass.replace('.', '-'); m.put("menuClass", menuClass); // this is here to allow the tool reorder to work if requried. m.put("_placement", placement); l.add(m); } } PageFilter pageFilter = portal.getPageFilter(); if (pageFilter != null) { l = pageFilter.filterPlacements(l, site); } theMap.put("pageNavTools", l); theMap.put("pageMaxIfSingle", ServerConfigurationService.getBoolean( "portal.experimental.maximizesinglepage", false)); theMap.put("pageNavToolsCount", Integer.valueOf(l.size())); String helpUrl = ServerConfigurationService.getHelpUrl(null); theMap.put("pageNavShowHelp", Boolean.valueOf(showHelp)); theMap.put("pageNavHelpUrl", helpUrl); theMap.put("helpMenuClass", "icon-sakai-help"); theMap.put("subsiteClass", "icon-sakai-subsite"); // theMap.put("pageNavSitContentshead", // Web.escapeHtml(rb.getString("sit_contentshead"))); // Display presence? Global property display.users.present may be always / never / true / false // If true or false, the value may be overriden by the site property display-users-present // which may be true or false. boolean showPresence; String globalShowPresence = ServerConfigurationService.getString("display.users.present"); if ("never".equals(globalShowPresence)) { showPresence = false; } else if ("always".equals(globalShowPresence)) { showPresence = true; } else { String showPresenceSite = site.getProperties().getProperty("display-users-present"); if (showPresenceSite == null) { showPresence = Boolean.valueOf(globalShowPresence).booleanValue(); } else { showPresence = Boolean.valueOf(showPresenceSite).booleanValue(); } } // Check to see if this is a my workspace site, and if so, whether presence is disabled if (showPresence && SiteService.isUserSite(site.getId()) && !ServerConfigurationService.getBoolean("display.users.present.myworkspace", true)) showPresence = false; String presenceUrl = Web.returnUrl(req, "/presence/" + Web.escapeUrl(site.getId())); // theMap.put("pageNavSitPresenceTitle", // Web.escapeHtml(rb.getString("sit_presencetitle"))); // theMap.put("pageNavSitPresenceFrameTitle", // Web.escapeHtml(rb.getString("sit_presenceiframetit"))); theMap.put("pageNavShowPresenceLoggedIn", Boolean.valueOf(showPresence && loggedIn)); theMap.put("pageNavPresenceUrl", presenceUrl); return theMap; }
public Map pageListToMap(HttpServletRequest req, boolean loggedIn, Site site, SitePage page, String toolContextPath, String portalPrefix, boolean doPages, boolean resetTools, boolean includeSummary) { Map<String, Object> theMap = new HashMap<String, Object>(); String pageUrl = Web.returnUrl(req, "/" + portalPrefix + "/" + Web.escapeUrl(getSiteEffectiveId(site)) + "/page/"); String toolUrl = Web.returnUrl(req, "/" + portalPrefix + "/" + Web.escapeUrl(getSiteEffectiveId(site))); if (resetTools) { toolUrl = toolUrl + "/tool-reset/"; } else { toolUrl = toolUrl + "/tool/"; } String pagePopupUrl = Web.returnUrl(req, "/page/"); boolean showHelp = ServerConfigurationService.getBoolean("display.help.menu", true); String iconUrl = ""; try { if (site.getIconUrlFull() != null) iconUrl = new URI(site.getIconUrlFull()).toString(); } catch (URISyntaxException uex) { log.debug("Icon URL is invalid: " + site.getIconUrlFull()); } boolean published = site.isPublished(); String type = site.getType(); theMap.put("pageNavPublished", Boolean.valueOf(published)); theMap.put("pageNavType", type); theMap.put("pageNavIconUrl", iconUrl); String htmlInclude = site.getProperties().getProperty(PROP_HTML_INCLUDE); if (htmlInclude != null) theMap.put("siteHTMLInclude", htmlInclude); // theMap.put("pageNavSitToolsHead", // Web.escapeHtml(rb.getString("sit_toolshead"))); // order the pages based on their tools and the tool order for the // site type // List pages = site.getOrderedPages(); List pages = getPermittedPagesInOrder(site); List<Map> l = new ArrayList<Map>(); for (Iterator i = pages.iterator(); i.hasNext();) { SitePage p = (SitePage) i.next(); // check if current user has permission to see page // we will draw page button if it have permission to see at least // one tool on the page List pTools = p.getTools(); ToolConfiguration firstTool = null; if (pTools != null && pTools.size() > 0) { firstTool = (ToolConfiguration) pTools.get(0); } String toolsOnPage = null; boolean current = (page != null && p.getId().equals(page.getId()) && !p .isPopUp()); String alias = lookupPageToAlias(site.getId(), p); String pagerefUrl = pageUrl + Web.escapeUrl((alias != null)?alias:p.getId()); if (doPages || p.isPopUp()) { Map<String, Object> m = new HashMap<String, Object>(); m.put("isPage", Boolean.valueOf(true)); m.put("current", Boolean.valueOf(current)); m.put("ispopup", Boolean.valueOf(p.isPopUp())); m.put("pagePopupUrl", pagePopupUrl); m.put("pageTitle", Web.escapeHtml(p.getTitle())); m.put("jsPageTitle", Web.escapeJavascript(p.getTitle())); m.put("pageId", Web.escapeUrl(p.getId())); m.put("jsPageId", Web.escapeJavascript(p.getId())); m.put("pageRefUrl", pagerefUrl); StringBuffer desc = new StringBuffer(); if (pTools != null) { Iterator tools = pTools.iterator(); //get the tool descriptions for this page, typically only one per page, execpt for the Home page int tCount = 0; while(tools.hasNext()){ ToolConfiguration t = (ToolConfiguration)tools.next(); if (tCount > 0){ desc.append(" | "); } if ( t.getTool() == null ) continue; desc.append(t.getTool().getDescription()); tCount++; } } // Just make sure no double quotes... String description = desc.toString().replace('"','-'); m.put("description", desc.toString()); // toolsOnPage is always null //if (toolsOnPage != null) m.put("toolsOnPage", toolsOnPage); if (includeSummary) summarizePage(m, site, p); if (firstTool != null) { String menuClass = firstTool.getToolId(); menuClass = "icon-" + menuClass.replace('.', '-'); m.put("menuClass", menuClass); } else { m.put("menuClass", "icon-default-tool"); } m.put("pageProps", createPageProps(p)); // this is here to allow the tool reorder to work m.put("_sitePage", p); l.add(m); continue; } // Loop through the tools again and Unroll the tools Iterator iPt = pTools.iterator(); while (iPt.hasNext()) { ToolConfiguration placement = (ToolConfiguration) iPt.next(); String toolrefUrl = toolUrl + Web.escapeUrl(placement.getId()); Map<String, Object> m = new HashMap<String, Object>(); m.put("isPage", Boolean.valueOf(false)); m.put("toolId", Web.escapeUrl(placement.getId())); m.put("jsToolId", Web.escapeJavascript(placement.getId())); m.put("toolRegistryId", placement.getToolId()); m.put("toolTitle", Web.escapeHtml(placement.getTitle())); m.put("jsToolTitle", Web.escapeJavascript(placement.getTitle())); m.put("toolrefUrl", toolrefUrl); String menuClass = placement.getToolId(); menuClass = "icon-" + menuClass.replace('.', '-'); m.put("menuClass", menuClass); // this is here to allow the tool reorder to work if requried. m.put("_placement", placement); l.add(m); } } PageFilter pageFilter = portal.getPageFilter(); if (pageFilter != null) { l = pageFilter.filterPlacements(l, site); } theMap.put("pageNavTools", l); theMap.put("pageMaxIfSingle", ServerConfigurationService.getBoolean( "portal.experimental.maximizesinglepage", false)); theMap.put("pageNavToolsCount", Integer.valueOf(l.size())); String helpUrl = ServerConfigurationService.getHelpUrl(null); theMap.put("pageNavShowHelp", Boolean.valueOf(showHelp)); theMap.put("pageNavHelpUrl", helpUrl); theMap.put("helpMenuClass", "icon-sakai-help"); theMap.put("subsiteClass", "icon-sakai-subsite"); // theMap.put("pageNavSitContentshead", // Web.escapeHtml(rb.getString("sit_contentshead"))); // Display presence? Global property display.users.present may be always / never / true / false // If true or false, the value may be overriden by the site property display-users-present // which may be true or false. boolean showPresence; String globalShowPresence = ServerConfigurationService.getString("display.users.present"); if ("never".equals(globalShowPresence)) { showPresence = false; } else if ("always".equals(globalShowPresence)) { showPresence = true; } else { String showPresenceSite = site.getProperties().getProperty("display-users-present"); if (showPresenceSite == null) { showPresence = Boolean.valueOf(globalShowPresence).booleanValue(); } else { showPresence = Boolean.valueOf(showPresenceSite).booleanValue(); } } // Check to see if this is a my workspace site, and if so, whether presence is disabled if (showPresence && SiteService.isUserSite(site.getId()) && !ServerConfigurationService.getBoolean("display.users.present.myworkspace", true)) showPresence = false; String presenceUrl = Web.returnUrl(req, "/presence/" + Web.escapeUrl(site.getId())); // theMap.put("pageNavSitPresenceTitle", // Web.escapeHtml(rb.getString("sit_presencetitle"))); // theMap.put("pageNavSitPresenceFrameTitle", // Web.escapeHtml(rb.getString("sit_presenceiframetit"))); theMap.put("pageNavShowPresenceLoggedIn", Boolean.valueOf(showPresence && loggedIn)); theMap.put("pageNavPresenceUrl", presenceUrl); return theMap; }
diff --git a/src/ibis/io/IbisHash.java b/src/ibis/io/IbisHash.java index 1fab9727..9e78cde8 100644 --- a/src/ibis/io/IbisHash.java +++ b/src/ibis/io/IbisHash.java @@ -1,545 +1,545 @@ package ibis.io; import ibis.util.Timer; import ibis.util.TypedProperties; /** * A hash table that aims for speed for pairs (Object, int). * * Goodies that differ from java.util.Hashtable: * + The calls into this hash are not synchronized. The caller is * responsible for locking the hash. * + Optionally, deletions are supported. If they are not, inserts and * lookups can be faster. * + Hash table size is always a power of two for fast modulo calculations. */ final class IbisHash { private static final boolean ASSERTS = TypedProperties.booleanProperty(IOProps.s_hash_asserts); // private final boolean ASSERTS; private static final boolean STATS = TypedProperties.booleanProperty(IOProps.s_hash_stats); private static final boolean TIMINGS = TypedProperties.booleanProperty(IOProps.s_hash_timings); private static final int MIN_BUCKETS = 32; private static final int USE_NEW_BOUND = Integer.MAX_VALUE; /* Choose this value between 2 and 4 */ private static final int RESIZE_FACTOR = 2; /* Choose this value between 1 and 3 */ private static final int PRE_ALLOC_FACTOR = 1; // private static final int SHIFT1 = 5; // private static final int SHIFT1 = 4; private static final int SHIFT2 = 16; private Object[] dataBucket; private int[] handleBucket; private final boolean supportDelete; private boolean[] deleted; private int n_deleted; // if (STATS) private long contains; private long finds; private long rebuilds; private long collisions; private long rebuild_collisions; private long new_buckets; // if (TIMINGS) private ibis.util.Timer t_insert; private ibis.util.Timer t_find; private ibis.util.Timer t_rebuild; private ibis.util.Timer t_clear; private ibis.util.Timer t_delete; private int offset = 0; private int size; private int initsize; private int alloc_size; private int present = 0; IbisHash() { this(MIN_BUCKETS); } IbisHash(boolean supportDelete) { this(MIN_BUCKETS, supportDelete); } IbisHash(int sz) { this(sz, false); } IbisHash(int sz, boolean supportDelete) { this.supportDelete = supportDelete; int x = 1; while (x < sz) { x <<= 1; } if (x != sz) { System.err.println("Warning: Hash table size (" + sz + ") must be a power of two. Increment to " + x); sz = x; } size = sz; initsize = sz; newBucketSet(initsize); if (TIMINGS) { t_insert = Timer.createTimer(); t_find = Timer.createTimer(); t_rebuild = Timer.createTimer(); t_clear = Timer.createTimer(); t_delete = Timer.createTimer(); } if (STATS || TIMINGS) { Runtime.getRuntime().addShutdownHook(new Thread("IbisHash ShutdownHook") { public void run() { statistics(); } }); } } private void newBucketSet(int sz) { dataBucket = new Object[sz]; handleBucket = new int[sz]; if (supportDelete) { deleted = new boolean[sz]; } alloc_size = sz; } private static final int hash_first(int b, int size) { // return ((b >>> SHIFT1) ^ (b & ((1 << SHIFT2) - 1))) & (size-1); return ((b >>> SHIFT2) ^ (b & ((1 << SHIFT2) - 1))) & (size-1); // // This is used in java.util.IdentityHashMap: // // return ((b << 1) - (b << 8)) & (size - 1); // return (b - (b << 7)) & (size - 1); } private static final int hash_second(int b) { return (b & ~0x1) + 12345; /* some odd number */ // Jason suggests +1 to improve cache locality // return 1; // return (b & 0xffe) + 1; /* some SMALL odd number */ // This is used in java.util.IdentityHashMap: // return 1; } /** * We know size is a power of two. Make mod cheap. */ private static final int mod(int x, int size) { return (x & (size - 1)); } // Don't call hashCode on the object. Some objects behave very strange :-) // If you don't understand this, think "ProActive". final int getHashCode(Object ref) { return System.identityHashCode(ref); } // synchronized final int find(Object ref, int hashCode) { int result; if (TIMINGS) { t_find.start(); } if (STATS) { finds++; } int h0 = hash_first(hashCode, size); int ix = h0 + offset; Object b = dataBucket[ix]; if (b == null) { result = 0; } else if (b == ref) { result = handleBucket[ix]; } else { int h1 = hash_second(hashCode); do { h0 = mod(h0 + h1, size); ix = h0 + offset; b = dataBucket[ix]; } while (b != null && b != ref); result = (b == null) ? 0 : handleBucket[ix]; } if (supportDelete && deleted[ix]) { result = 0; } if (TIMINGS) { t_find.stop(); } if (ASSERTS) { if (result == 0) { for (int i = offset; i < offset + size; i++) { if (dataBucket[i] == ref && (! supportDelete || ! deleted[i])) { System.err.println("CORRUPTED HASH: find returns 'no' but it's there in bucket[" + i + "]"); } } } } return result; } final int find(Object ref) { return find(ref, getHashCode(ref)); } /** * Rebuild if fill factor is too high or deletions are too high. */ private final void rebuild() { if (2 * present <= size && (! supportDelete || 4 * (present - n_deleted) <= size)) { return; } if (TIMINGS) { t_rebuild.start(); } int n = size * RESIZE_FACTOR; int new_offset = 0; Object[] old_data = dataBucket; int[] old_handle = handleBucket; boolean[] old_deleted = deleted; /* Only buy a new array when we really overflow. * If the array we allocated previously still has enough * free space, use first/last slice when we currently use * last/first slice. */ if (n + size > alloc_size) { - newBucketSet(PRE_ALLOC_FACTOR * (size + n)); + newBucketSet(PRE_ALLOC_FACTOR * n); } else if (offset == 0) { new_offset = alloc_size - n; } for (int i = 0; i < size; i++) { int ix = i + offset; Object b = old_data[ix]; if (b != null && (! supportDelete || ! old_deleted[ix])) { int h = System.identityHashCode(b); int h0 = hash_first(h, n); while (dataBucket[h0 + new_offset] != null) { int h1 = hash_second(h); do { h0 = mod(h0 + h1, n); if (STATS) { rebuild_collisions++; } } while (dataBucket[h0 + new_offset] != null); } dataBucket[h0 + new_offset] = b; handleBucket[h0 + new_offset] = old_handle[ix]; if (! ASSERTS) { old_data[ix] = null; if (supportDelete && old_deleted[ix]) { old_deleted[ix] = false; } } } } int old_offset = offset; int old_size = size; size = n; offset = new_offset; if (ASSERTS) { for (int i = old_offset; i < old_offset + old_size; i++) { if (old_data[i] != null && (! supportDelete || ! old_deleted[i]) && find(old_data[i]) == 0) { System.err.println("CORRUPTED HASH after rebuild: " + "cannot find item[" + i + "] = " + Integer.toHexString(getHashCode(old_data[i]))); } old_data[i] = null; if (supportDelete && old_deleted[i]) { old_deleted[i] = false; } } int cont = 0; for (int i = offset; i < offset + size; i++) { if (dataBucket[i] != null) { cont++; } } if (cont != present) { System.err.println("CORRUPTED HASH after rebuild: present " + present + " but contains " + cont); } } if (TIMINGS) { t_rebuild.stop(); } if (STATS) { rebuilds++; } } /** * Lazy insert (ref, handle) into the hash table. * * @param ref the object that is inserted * @param handle the (int valued) key * @param hashCode the hashCode of ref that may be kept over calls to the * hash table * @param lazy if lazy is <code>true</code>, insert (ref, handle) only * if ref is not yet present. * @return if lazy is <code>true</code> and ref is already in the hash * table, return the value of its stored handle and ignore * parameter handle. Else, ref is inserted and the value of * parameter handle is returned. */ private int put(Object ref, int handle, int hashCode, boolean lazy) { if (TIMINGS) { t_insert.start(); } int h0 = hash_first(hashCode, size); int deleted_ix = -1; Object b = dataBucket[h0 + offset]; if (b != null && b != ref) { int h1 = hash_second(hashCode); do { h0 = mod(h0 + h1, size); if (STATS) { collisions++; } b = dataBucket[h0 + offset]; if (supportDelete && deleted[h0 + offset] && deleted_ix == -1) { deleted_ix = h0; if (! lazy) { break; } } } while (b != null && b != ref); } if (lazy && b != null) { if (TIMINGS) { t_insert.stop(); } return handleBucket[h0 + offset]; } if (ASSERTS) { if (lazy) { for (int i = offset; i < offset + size; i++) { if (dataBucket[i] == ref && (! supportDelete || ! deleted[i])) { System.err.println("CORRUPTED HASH: lazyPut finds 'no' but it's there in bucket[" + i + "]"); } } } } if (supportDelete && deleted_ix != -1) { n_deleted--; h0 = deleted_ix; deleted[h0 + offset] = false; } dataBucket[h0 + offset] = ref; handleBucket[h0 + offset] = handle; present++; rebuild(); if (TIMINGS) { t_insert.stop(); } if (STATS) { contains++; } return handle; } // synchronized final void put(Object ref, int handle, int hashCode) { put(ref, handle, hashCode, false); } // synchronized final void put(Object ref, int handle) { put(ref, handle, getHashCode(ref)); } // synchronized final int lazyPut(Object ref, int handle, int hashCode) { return put(ref, handle, hashCode, true); } // synchronized final int lazyPut(Object ref, int handle) { return lazyPut(ref, handle, getHashCode(ref)); } // synchronized final boolean delete(Object ref, int hashCode) { if (! supportDelete) { throw new RuntimeException("Delete in IbisHash with deletes turned off"); } if (TIMINGS) { t_delete.start(); } int h0 = hash_first(hashCode, size); Object b = dataBucket[h0 + offset]; if (b != null && b != ref) { int h1 = hash_second(hashCode); do { h0 = mod(h0 + h1, size); if (STATS) { collisions++; } b = dataBucket[h0 + offset]; } while (b != null && b != ref); } if (b == null || deleted[h0 + offset]) { return false; } deleted[h0 + offset] = true; n_deleted++; present--; if (TIMINGS) { t_delete.stop(); } rebuild(); return true; } final void delete(Object ref) { delete(ref, getHashCode(ref)); } // synchronized final void clear() { /** * The hash is between 1/4 and 1/2 full. * Cleaning is most efficient by doing a swipe over * the whole bucket array. */ if (TIMINGS) { t_clear.start(); } if (size < USE_NEW_BOUND) { for (int i = 0; i < size; i++) { dataBucket[i + offset] = null; } } else { // System.err.println("New bucket set..."); newBucketSet(initsize); } size = initsize; offset = 0; present = 0; if (TIMINGS) { t_clear.stop(); } if (STATS) { // contains = 0; // finds = 0; } } final void statistics() { if (STATS) { System.err.println(this + ":" + " alloc_size " + alloc_size + " contains " + contains + " finds " + finds + " rebuilds " + rebuilds + " new buckets " + new_buckets + " collisions " + collisions + " (rebuild " + rebuild_collisions + ")"); } if (TIMINGS) { System.err.println(this + " insert(" + t_insert.nrTimes() + ") " + Timer.format(t_insert.totalTimeVal()) + " find(" + t_find.nrTimes() + ") " + Timer.format(t_find.totalTimeVal()) + " rebuild(" + t_rebuild.nrTimes() + ") " + Timer.format(t_rebuild.totalTimeVal()) + " clear(" + t_clear.nrTimes() + ") " + Timer.format(t_clear.totalTimeVal()) + " delete(" + t_delete.nrTimes() + ") " + Timer.format(t_delete.totalTimeVal())); } } }
true
true
private final void rebuild() { if (2 * present <= size && (! supportDelete || 4 * (present - n_deleted) <= size)) { return; } if (TIMINGS) { t_rebuild.start(); } int n = size * RESIZE_FACTOR; int new_offset = 0; Object[] old_data = dataBucket; int[] old_handle = handleBucket; boolean[] old_deleted = deleted; /* Only buy a new array when we really overflow. * If the array we allocated previously still has enough * free space, use first/last slice when we currently use * last/first slice. */ if (n + size > alloc_size) { newBucketSet(PRE_ALLOC_FACTOR * (size + n)); } else if (offset == 0) { new_offset = alloc_size - n; } for (int i = 0; i < size; i++) { int ix = i + offset; Object b = old_data[ix]; if (b != null && (! supportDelete || ! old_deleted[ix])) { int h = System.identityHashCode(b); int h0 = hash_first(h, n); while (dataBucket[h0 + new_offset] != null) { int h1 = hash_second(h); do { h0 = mod(h0 + h1, n); if (STATS) { rebuild_collisions++; } } while (dataBucket[h0 + new_offset] != null); } dataBucket[h0 + new_offset] = b; handleBucket[h0 + new_offset] = old_handle[ix]; if (! ASSERTS) { old_data[ix] = null; if (supportDelete && old_deleted[ix]) { old_deleted[ix] = false; } } } } int old_offset = offset; int old_size = size; size = n; offset = new_offset; if (ASSERTS) { for (int i = old_offset; i < old_offset + old_size; i++) { if (old_data[i] != null && (! supportDelete || ! old_deleted[i]) && find(old_data[i]) == 0) { System.err.println("CORRUPTED HASH after rebuild: " + "cannot find item[" + i + "] = " + Integer.toHexString(getHashCode(old_data[i]))); } old_data[i] = null; if (supportDelete && old_deleted[i]) { old_deleted[i] = false; } } int cont = 0; for (int i = offset; i < offset + size; i++) { if (dataBucket[i] != null) { cont++; } } if (cont != present) { System.err.println("CORRUPTED HASH after rebuild: present " + present + " but contains " + cont); } } if (TIMINGS) { t_rebuild.stop(); } if (STATS) { rebuilds++; } }
private final void rebuild() { if (2 * present <= size && (! supportDelete || 4 * (present - n_deleted) <= size)) { return; } if (TIMINGS) { t_rebuild.start(); } int n = size * RESIZE_FACTOR; int new_offset = 0; Object[] old_data = dataBucket; int[] old_handle = handleBucket; boolean[] old_deleted = deleted; /* Only buy a new array when we really overflow. * If the array we allocated previously still has enough * free space, use first/last slice when we currently use * last/first slice. */ if (n + size > alloc_size) { newBucketSet(PRE_ALLOC_FACTOR * n); } else if (offset == 0) { new_offset = alloc_size - n; } for (int i = 0; i < size; i++) { int ix = i + offset; Object b = old_data[ix]; if (b != null && (! supportDelete || ! old_deleted[ix])) { int h = System.identityHashCode(b); int h0 = hash_first(h, n); while (dataBucket[h0 + new_offset] != null) { int h1 = hash_second(h); do { h0 = mod(h0 + h1, n); if (STATS) { rebuild_collisions++; } } while (dataBucket[h0 + new_offset] != null); } dataBucket[h0 + new_offset] = b; handleBucket[h0 + new_offset] = old_handle[ix]; if (! ASSERTS) { old_data[ix] = null; if (supportDelete && old_deleted[ix]) { old_deleted[ix] = false; } } } } int old_offset = offset; int old_size = size; size = n; offset = new_offset; if (ASSERTS) { for (int i = old_offset; i < old_offset + old_size; i++) { if (old_data[i] != null && (! supportDelete || ! old_deleted[i]) && find(old_data[i]) == 0) { System.err.println("CORRUPTED HASH after rebuild: " + "cannot find item[" + i + "] = " + Integer.toHexString(getHashCode(old_data[i]))); } old_data[i] = null; if (supportDelete && old_deleted[i]) { old_deleted[i] = false; } } int cont = 0; for (int i = offset; i < offset + size; i++) { if (dataBucket[i] != null) { cont++; } } if (cont != present) { System.err.println("CORRUPTED HASH after rebuild: present " + present + " but contains " + cont); } } if (TIMINGS) { t_rebuild.stop(); } if (STATS) { rebuilds++; } }
diff --git a/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/ConferenceSubStrategy.java b/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/ConferenceSubStrategy.java index 8cccbe2a3..a8f1e611b 100644 --- a/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/ConferenceSubStrategy.java +++ b/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/ConferenceSubStrategy.java @@ -1,267 +1,269 @@ package org.mobicents.servlet.sip.restcomm.interpreter.tagstrategy; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.joda.time.DateTime; import org.mobicents.servlet.sip.restcomm.ServiceLocator; import org.mobicents.servlet.sip.restcomm.Sid; import org.mobicents.servlet.sip.restcomm.entities.Notification; import org.mobicents.servlet.sip.restcomm.interpreter.RcmlInterpreter; import org.mobicents.servlet.sip.restcomm.interpreter.RcmlInterpreterContext; import org.mobicents.servlet.sip.restcomm.interpreter.TagStrategyException; import org.mobicents.servlet.sip.restcomm.media.api.Call; import org.mobicents.servlet.sip.restcomm.media.api.CallObserver; import org.mobicents.servlet.sip.restcomm.media.api.Conference; import org.mobicents.servlet.sip.restcomm.media.api.ConferenceCenter; import org.mobicents.servlet.sip.restcomm.media.api.ConferenceObserver; import org.mobicents.servlet.sip.restcomm.util.StringUtils; import org.mobicents.servlet.sip.restcomm.util.TimeUtils; import org.mobicents.servlet.sip.restcomm.xml.Attribute; import org.mobicents.servlet.sip.restcomm.xml.Tag; import org.mobicents.servlet.sip.restcomm.xml.rcml.RcmlTag; import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.Beep; import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.EndConferenceOnExit; import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.MaxParticipants; import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.Muted; import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.StartConferenceOnEnter; import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.WaitMethod; import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.WaitUrl; public final class ConferenceSubStrategy extends RcmlTagStrategy implements CallObserver, ConferenceObserver { private final ConferenceCenter conferenceCenter; private final URI action; private final String method; private final int timeLimit; private final boolean record; private Sid recordingSid; private String name; private boolean muted; private boolean beep; private boolean startConferenceOnEnter; private boolean endConferenceOnExit; private URI waitUrl; private String waitMethod; private int maxParticipants; public ConferenceSubStrategy(final URI action, final String method, final int timeLimit, final boolean record) { super(); final ServiceLocator services = ServiceLocator.getInstance(); this.conferenceCenter = services.get(ConferenceCenter.class); this.action = action; this.method = method; this.timeLimit = timeLimit; this.record = record; if(record) { recordingSid = Sid.generate(Sid.Type.RECORDING); } waitUrl = URI.create("file://" + configuration.getString("conference-music-file")); } @Override public synchronized void execute(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Call call = context.getCall(); final StringBuilder buffer = new StringBuilder(); buffer.append(context.getAccountSid().toString()).append(":").append(name); final String room = buffer.toString(); final DateTime start = DateTime.now(); final Conference conference = conferenceCenter.getConference(room); if(!startConferenceOnEnter) { - if(!call.isMuted()) { + if(Call.Status.IN_PROGRESS == call.getStatus() && !call.isMuted()) { call.mute(); } if(conference.getNumberOfParticipants() == 0) { if(waitUrl != null) { final List<URI> music = new ArrayList<URI>(); music.add(waitUrl); conference.setBackgroundMusic(music); conference.playBackgroundMusic(); } } } else { conference.stopBackgroundMusic(); if(beep) { conference.alert(); } - if(muted) { call.mute(); } + if(Call.Status.IN_PROGRESS == call.getStatus() && muted) { call.mute(); } } - call.addObserver(this); - conference.addObserver(this); - conference.addParticipant(call); - try { wait(TimeUtils.SECOND_IN_MILLIS * timeLimit); } - catch(final InterruptedException ignored) { } - conference.removeObserver(this); - call.removeObserver(this); - if(endConferenceOnExit || conference.getNumberOfParticipants() == 0) { + if(Call.Status.IN_PROGRESS == call.getStatus()) { + call.addObserver(this); + conference.addObserver(this); + conference.addParticipant(call); + try { wait(TimeUtils.SECOND_IN_MILLIS * timeLimit); } + catch(final InterruptedException ignored) { } + conference.removeObserver(this); + call.removeObserver(this); + } + if(endConferenceOnExit) { conferenceCenter.removeConference(room); } else { if(Call.Status.IN_PROGRESS == call.getStatus() && Conference.Status.IN_PROGRESS == conference.getStatus()) { conference.removeParticipant(call); } } final DateTime finish = DateTime.now(); if(Call.Status.IN_PROGRESS == call.getStatus() && action != null) { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("DialCallStatus", "completed")); parameters.add(new BasicNameValuePair("DialCallDuration", Long.toString(finish.minus(start.getMillis()).getMillis() / TimeUtils.SECOND_IN_MILLIS))); if(record) { parameters.add(new BasicNameValuePair("RecordingUrl", toRecordingPath(recordingSid).toString())); } interpreter.load(action, method, parameters); interpreter.redirect(); } } private boolean getBeep(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Attribute attribute = tag.getAttribute(Beep.NAME); if(attribute == null) { return true; } final String value = attribute.getValue(); if("true".equalsIgnoreCase(value)) { return true; } else if("false".equalsIgnoreCase(value)) { return false; } else { return true; } } private Tag getConferenceTag(final List<Tag> tags) { final String name = org.mobicents.servlet.sip.restcomm.xml.rcml.Conference.NAME; for(final Tag tag : tags) { if(name.equals(tag.getName())) { return tag; } } return null; } private boolean getEndConferenceOnExit(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Attribute attribute = tag.getAttribute(EndConferenceOnExit.NAME); if(attribute == null) { return false; } final String value = attribute.getValue(); if("true".equalsIgnoreCase(value)) { return true; } else if("false".equalsIgnoreCase(value)) { return false; } else { interpreter.notify(context, Notification.WARNING, 13231); return false; } } private int getMaxParticipants(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Attribute attribute = tag.getAttribute(MaxParticipants.NAME); if(attribute == null) { return 40; } final String value = attribute.getValue(); if(StringUtils.isPositiveInteger(value)) { final int result = Integer.parseInt(value); if(result > 0) { return result; } } return 40; } private boolean getMuted(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Attribute attribute = tag.getAttribute(Muted.NAME); if(attribute == null) { return false; } final String value = attribute.getValue(); if("true".equalsIgnoreCase(value)) { return true; } else if("false".equalsIgnoreCase(value)) { return false; } else { interpreter.notify(context, Notification.WARNING, 13230); return false; } } private boolean getStartConferenceOnEnter(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Attribute attribute = tag.getAttribute(StartConferenceOnEnter.NAME); if(attribute == null) { return true; } final String value = attribute.getValue(); if("true".equalsIgnoreCase(value)) { return true; } else if("false".equalsIgnoreCase(value)) { return false; } else { interpreter.notify(context, Notification.WARNING, 13232); return true; } } private URI getWaitUrl(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Attribute attribute = tag.getAttribute(WaitUrl.NAME); if(attribute != null) { try { final URI base = interpreter.getCurrentResourceUri(); return resolveIfNotAbsolute(base, attribute.getValue()); } catch(final IllegalArgumentException exception) { interpreter.notify(context, Notification.ERROR, 13233); throw new TagStrategyException(exception); } } return null; } private String getWaitMethod(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Attribute attribute = tag.getAttribute(WaitMethod.NAME); if(attribute == null) { return "POST"; } final String value = attribute.getValue(); if("GET".equalsIgnoreCase(value)) { return "GET"; } else if("POST".equalsIgnoreCase(value)) { return "POST"; } else { interpreter.notify(context, Notification.WARNING, 13234); return "POST"; } } @Override public synchronized void initialize(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final RcmlTag conference = (RcmlTag)getConferenceTag(tag.getChildren()); name = conference.getText(); muted = getMuted(interpreter, context, conference); beep = getBeep(interpreter, context, conference); startConferenceOnEnter = getStartConferenceOnEnter(interpreter, context, conference); endConferenceOnExit = getEndConferenceOnExit(interpreter, context, conference); waitUrl = getWaitUrl(interpreter, context, conference); waitMethod = getWaitMethod(interpreter, context, conference); maxParticipants = getMaxParticipants(interpreter, context, conference); } @Override public synchronized void onStatusChanged(final Call call) { final Call.Status status = call.getStatus(); if(Call.Status.CANCELLED == status || Call.Status.COMPLETED == status || Call.Status.FAILED == status) { notify(); } } @Override public synchronized void onStatusChanged(final Conference conference) { final Conference.Status status = conference.getStatus(); if(Conference.Status.COMPLETED == status || Conference.Status.FAILED == status) { notify(); } } }
false
true
@Override public synchronized void execute(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Call call = context.getCall(); final StringBuilder buffer = new StringBuilder(); buffer.append(context.getAccountSid().toString()).append(":").append(name); final String room = buffer.toString(); final DateTime start = DateTime.now(); final Conference conference = conferenceCenter.getConference(room); if(!startConferenceOnEnter) { if(!call.isMuted()) { call.mute(); } if(conference.getNumberOfParticipants() == 0) { if(waitUrl != null) { final List<URI> music = new ArrayList<URI>(); music.add(waitUrl); conference.setBackgroundMusic(music); conference.playBackgroundMusic(); } } } else { conference.stopBackgroundMusic(); if(beep) { conference.alert(); } if(muted) { call.mute(); } } call.addObserver(this); conference.addObserver(this); conference.addParticipant(call); try { wait(TimeUtils.SECOND_IN_MILLIS * timeLimit); } catch(final InterruptedException ignored) { } conference.removeObserver(this); call.removeObserver(this); if(endConferenceOnExit || conference.getNumberOfParticipants() == 0) { conferenceCenter.removeConference(room); } else { if(Call.Status.IN_PROGRESS == call.getStatus() && Conference.Status.IN_PROGRESS == conference.getStatus()) { conference.removeParticipant(call); } } final DateTime finish = DateTime.now(); if(Call.Status.IN_PROGRESS == call.getStatus() && action != null) { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("DialCallStatus", "completed")); parameters.add(new BasicNameValuePair("DialCallDuration", Long.toString(finish.minus(start.getMillis()).getMillis() / TimeUtils.SECOND_IN_MILLIS))); if(record) { parameters.add(new BasicNameValuePair("RecordingUrl", toRecordingPath(recordingSid).toString())); } interpreter.load(action, method, parameters); interpreter.redirect(); } }
@Override public synchronized void execute(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Call call = context.getCall(); final StringBuilder buffer = new StringBuilder(); buffer.append(context.getAccountSid().toString()).append(":").append(name); final String room = buffer.toString(); final DateTime start = DateTime.now(); final Conference conference = conferenceCenter.getConference(room); if(!startConferenceOnEnter) { if(Call.Status.IN_PROGRESS == call.getStatus() && !call.isMuted()) { call.mute(); } if(conference.getNumberOfParticipants() == 0) { if(waitUrl != null) { final List<URI> music = new ArrayList<URI>(); music.add(waitUrl); conference.setBackgroundMusic(music); conference.playBackgroundMusic(); } } } else { conference.stopBackgroundMusic(); if(beep) { conference.alert(); } if(Call.Status.IN_PROGRESS == call.getStatus() && muted) { call.mute(); } } if(Call.Status.IN_PROGRESS == call.getStatus()) { call.addObserver(this); conference.addObserver(this); conference.addParticipant(call); try { wait(TimeUtils.SECOND_IN_MILLIS * timeLimit); } catch(final InterruptedException ignored) { } conference.removeObserver(this); call.removeObserver(this); } if(endConferenceOnExit) { conferenceCenter.removeConference(room); } else { if(Call.Status.IN_PROGRESS == call.getStatus() && Conference.Status.IN_PROGRESS == conference.getStatus()) { conference.removeParticipant(call); } } final DateTime finish = DateTime.now(); if(Call.Status.IN_PROGRESS == call.getStatus() && action != null) { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("DialCallStatus", "completed")); parameters.add(new BasicNameValuePair("DialCallDuration", Long.toString(finish.minus(start.getMillis()).getMillis() / TimeUtils.SECOND_IN_MILLIS))); if(record) { parameters.add(new BasicNameValuePair("RecordingUrl", toRecordingPath(recordingSid).toString())); } interpreter.load(action, method, parameters); interpreter.redirect(); } }
diff --git a/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java b/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java index 1aae276..89719c4 100644 --- a/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java +++ b/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java @@ -1,207 +1,209 @@ /************************************************************************************ * * Copyright (C) 2009-2012 Broadcom Corporation * * 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.bluetooth.pbap; import android.content.Context; import android.os.SystemProperties; import android.util.Log; import com.android.bluetooth.Utils; import com.android.bluetooth.pbap.BluetoothPbapService; import com.android.vcard.VCardComposer; import com.android.vcard.VCardConfig; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Profile; import android.provider.ContactsContract.RawContactsEntity; import com.android.vcard.VCardComposer; import com.android.vcard.VCardConfig; public class BluetoothPbapUtils { private static final String TAG = "FilterUtils"; private static final boolean V = BluetoothPbapService.VERBOSE; public static int FILTER_PHOTO = 3; public static int FILTER_TEL = 7; public static int FILTER_NICKNAME = 23; public static boolean hasFilter(byte[] filter) { return filter != null && filter.length > 0; } public static boolean isNameAndNumberOnly(byte[] filter) { // For vcard 2.0: VERSION,N,TEL is mandatory // For vcard 3.0, VERSION,N,FN,TEL is mandatory // So we only need to make sure that no other fields except optionally // NICKNAME is set // Check that an explicit filter is not set. If not, this means // return everything if (!hasFilter(filter)) { Log.v(TAG, "No filter set. isNameAndNumberOnly=false"); return false; } // Check bytes 0-4 are all 0 for (int i = 0; i <= 4; i++) { if (filter[i] != 0) { return false; } } // On byte 5, only BIT_NICKNAME can be set, so make sure // rest of bits are not set if ((filter[5] & 0x7F) > 0) { return false; } // Check byte 6 is not set if (filter[6] != 0) { return false; } // Check if bit#3-6 is set. Return false if so. if ((filter[7] & 0x78) > 0) { return false; } return true; } public static boolean isFilterBitSet(byte[] filter, int filterBit) { if (hasFilter(filter)) { int byteNumber = 7 - filterBit / 8; int bitNumber = filterBit % 8; if (byteNumber < filter.length) { return (filter[byteNumber] & (1 << bitNumber)) > 0; } } return false; } public static VCardComposer createFilteredVCardComposer(final Context ctx, final int vcardType, final byte[] filter) { int vType = vcardType; /* boolean isNameNumberOnly = isNameAndNumberOnly(filter); if (isNameNumberOnly) { if (V) Log.v(TAG, "Creating Name/Number only VCardComposer..."); vType |= VCardConfig.FLAG_NAME_NUMBER_ONLY_EXPORT; } else { */ boolean includePhoto = BluetoothPbapConfig.includePhotosInVcard() && (!hasFilter(filter) || isFilterBitSet(filter, FILTER_PHOTO)); if (!includePhoto) { if (V) Log.v(TAG, "Excluding images from VCardComposer..."); vType |= VCardConfig.FLAG_REFRAIN_IMAGE_EXPORT; } //} return new VCardComposer(ctx, vType, true); } public static boolean isProfileSet(Context context) { Cursor c = context.getContentResolver().query( Profile.CONTENT_VCARD_URI, new String[] { Profile._ID }, null, null, null); boolean isSet = (c != null && c.getCount() > 0); if (c != null) { c.close(); + c = null; } return isSet; } public static String getProfileName(Context context) { Cursor c = context.getContentResolver().query( Profile.CONTENT_URI, new String[] { Profile.DISPLAY_NAME}, null, null, null); String ownerName =null; if (c!= null && c.moveToFirst()) { ownerName = c.getString(0); } if (c != null) { c.close(); + c = null; } return ownerName; } public static final String createProfileVCard(Context ctx, final int vcardType,final byte[] filter) { VCardComposer composer = null; String vcard = null; try { composer = createFilteredVCardComposer(ctx, vcardType, filter); if (composer .init(Profile.CONTENT_URI, null, null, null, null, Uri .withAppendedPath(Profile.CONTENT_URI, RawContactsEntity.CONTENT_URI .getLastPathSegment()))) { vcard = composer.createOneEntry(); } else { Log.e(TAG, "Unable to create profile vcard. Error initializing composer: " + composer.getErrorReason()); } } catch (Throwable t) { Log.e(TAG, "Unable to create profile vcard.", t); } if (composer != null) { try { composer.terminate(); } catch (Throwable t) { } } return vcard; } public static boolean createProfileVCardFile(File file, Context context) { // File defaultFile = new // File(OppApplicationConfig.OPP_OWNER_VCARD_PATH); FileInputStream is = null; FileOutputStream os = null; boolean success = true; try { AssetFileDescriptor fd = context.getContentResolver() .openAssetFileDescriptor(Profile.CONTENT_VCARD_URI, "r"); if(fd == null) { return false; } is = fd.createInputStream(); os = new FileOutputStream(file); Utils.copyStream(is, os, 200); } catch (Throwable t) { Log.e(TAG, "Unable to create default contact vcard file", t); success = false; } Utils.safeCloseStream(is); Utils.safeCloseStream(os); return success; } }
false
true
public static VCardComposer createFilteredVCardComposer(final Context ctx, final int vcardType, final byte[] filter) { int vType = vcardType; /* boolean isNameNumberOnly = isNameAndNumberOnly(filter); if (isNameNumberOnly) { if (V) Log.v(TAG, "Creating Name/Number only VCardComposer..."); vType |= VCardConfig.FLAG_NAME_NUMBER_ONLY_EXPORT; } else { */ boolean includePhoto = BluetoothPbapConfig.includePhotosInVcard() && (!hasFilter(filter) || isFilterBitSet(filter, FILTER_PHOTO)); if (!includePhoto) { if (V) Log.v(TAG, "Excluding images from VCardComposer..."); vType |= VCardConfig.FLAG_REFRAIN_IMAGE_EXPORT; } //} return new VCardComposer(ctx, vType, true); } public static boolean isProfileSet(Context context) { Cursor c = context.getContentResolver().query( Profile.CONTENT_VCARD_URI, new String[] { Profile._ID }, null, null, null); boolean isSet = (c != null && c.getCount() > 0); if (c != null) { c.close(); } return isSet; } public static String getProfileName(Context context) { Cursor c = context.getContentResolver().query( Profile.CONTENT_URI, new String[] { Profile.DISPLAY_NAME}, null, null, null); String ownerName =null; if (c!= null && c.moveToFirst()) { ownerName = c.getString(0); } if (c != null) { c.close(); } return ownerName; } public static final String createProfileVCard(Context ctx, final int vcardType,final byte[] filter) { VCardComposer composer = null; String vcard = null; try { composer = createFilteredVCardComposer(ctx, vcardType, filter); if (composer .init(Profile.CONTENT_URI, null, null, null, null, Uri .withAppendedPath(Profile.CONTENT_URI, RawContactsEntity.CONTENT_URI .getLastPathSegment()))) { vcard = composer.createOneEntry(); } else { Log.e(TAG, "Unable to create profile vcard. Error initializing composer: " + composer.getErrorReason()); } } catch (Throwable t) { Log.e(TAG, "Unable to create profile vcard.", t); } if (composer != null) { try { composer.terminate(); } catch (Throwable t) { } } return vcard; } public static boolean createProfileVCardFile(File file, Context context) { // File defaultFile = new // File(OppApplicationConfig.OPP_OWNER_VCARD_PATH); FileInputStream is = null; FileOutputStream os = null; boolean success = true; try { AssetFileDescriptor fd = context.getContentResolver() .openAssetFileDescriptor(Profile.CONTENT_VCARD_URI, "r"); if(fd == null) { return false; } is = fd.createInputStream(); os = new FileOutputStream(file); Utils.copyStream(is, os, 200); } catch (Throwable t) { Log.e(TAG, "Unable to create default contact vcard file", t); success = false; } Utils.safeCloseStream(is); Utils.safeCloseStream(os); return success; } }
public static VCardComposer createFilteredVCardComposer(final Context ctx, final int vcardType, final byte[] filter) { int vType = vcardType; /* boolean isNameNumberOnly = isNameAndNumberOnly(filter); if (isNameNumberOnly) { if (V) Log.v(TAG, "Creating Name/Number only VCardComposer..."); vType |= VCardConfig.FLAG_NAME_NUMBER_ONLY_EXPORT; } else { */ boolean includePhoto = BluetoothPbapConfig.includePhotosInVcard() && (!hasFilter(filter) || isFilterBitSet(filter, FILTER_PHOTO)); if (!includePhoto) { if (V) Log.v(TAG, "Excluding images from VCardComposer..."); vType |= VCardConfig.FLAG_REFRAIN_IMAGE_EXPORT; } //} return new VCardComposer(ctx, vType, true); } public static boolean isProfileSet(Context context) { Cursor c = context.getContentResolver().query( Profile.CONTENT_VCARD_URI, new String[] { Profile._ID }, null, null, null); boolean isSet = (c != null && c.getCount() > 0); if (c != null) { c.close(); c = null; } return isSet; } public static String getProfileName(Context context) { Cursor c = context.getContentResolver().query( Profile.CONTENT_URI, new String[] { Profile.DISPLAY_NAME}, null, null, null); String ownerName =null; if (c!= null && c.moveToFirst()) { ownerName = c.getString(0); } if (c != null) { c.close(); c = null; } return ownerName; } public static final String createProfileVCard(Context ctx, final int vcardType,final byte[] filter) { VCardComposer composer = null; String vcard = null; try { composer = createFilteredVCardComposer(ctx, vcardType, filter); if (composer .init(Profile.CONTENT_URI, null, null, null, null, Uri .withAppendedPath(Profile.CONTENT_URI, RawContactsEntity.CONTENT_URI .getLastPathSegment()))) { vcard = composer.createOneEntry(); } else { Log.e(TAG, "Unable to create profile vcard. Error initializing composer: " + composer.getErrorReason()); } } catch (Throwable t) { Log.e(TAG, "Unable to create profile vcard.", t); } if (composer != null) { try { composer.terminate(); } catch (Throwable t) { } } return vcard; } public static boolean createProfileVCardFile(File file, Context context) { // File defaultFile = new // File(OppApplicationConfig.OPP_OWNER_VCARD_PATH); FileInputStream is = null; FileOutputStream os = null; boolean success = true; try { AssetFileDescriptor fd = context.getContentResolver() .openAssetFileDescriptor(Profile.CONTENT_VCARD_URI, "r"); if(fd == null) { return false; } is = fd.createInputStream(); os = new FileOutputStream(file); Utils.copyStream(is, os, 200); } catch (Throwable t) { Log.e(TAG, "Unable to create default contact vcard file", t); success = false; } Utils.safeCloseStream(is); Utils.safeCloseStream(os); return success; } }
diff --git a/lms/lms-portlet/src/main/java/hu/advancedweb/service/impl/ExamAnswerLocalServiceImpl.java b/lms/lms-portlet/src/main/java/hu/advancedweb/service/impl/ExamAnswerLocalServiceImpl.java index f677a18..2c0e0be 100644 --- a/lms/lms-portlet/src/main/java/hu/advancedweb/service/impl/ExamAnswerLocalServiceImpl.java +++ b/lms/lms-portlet/src/main/java/hu/advancedweb/service/impl/ExamAnswerLocalServiceImpl.java @@ -1,56 +1,57 @@ package hu.advancedweb.service.impl; import hu.advancedweb.model.ExamAnswer; import hu.advancedweb.service.base.ExamAnswerLocalServiceBaseImpl; import java.util.Date; import java.util.List; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.liferay.portal.kernel.exception.SystemException; /** * The implementation of the exam answer local service. * * <p> * All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the * {@link hu.advancedweb.service.ExamAnswerLocalService} interface. * * <p> * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the * same VM. * </p> * * @author Brian Wing Shun Chan * @see hu.advancedweb.service.base.ExamAnswerLocalServiceBaseImpl * @see hu.advancedweb.service.ExamAnswerLocalServiceUtil */ public class ExamAnswerLocalServiceImpl extends ExamAnswerLocalServiceBaseImpl { /* * NOTE FOR DEVELOPERS: * * Never reference this interface directly. Always use {@link hu.advancedweb.service.ExamAnswerLocalServiceUtil} to access the exam answer local service. */ public ExamAnswer createExamAnswer(long companyId, long groupId, long userId, String answers, Date date, long examConfigId) throws SystemException { List<ExamAnswer> list = getExamAnswerPersistence().findByCompanyId_GroupId_UserId_ExamConfigId(companyId, groupId, userId, examConfigId); Preconditions.checkArgument(list.isEmpty()); ExamAnswer result = createExamAnswer(counterLocalService.increment()); result.setCompanyId(companyId); result.setGroupId(groupId); result.setUserId(userId); result.setAnswers(answers); result.setDate(date); result.setExamConfigId(examConfigId); + result.resetOriginalValues(); result = updateExamAnswer(result); return result; } public ExamAnswer getExamAnswer(long companyId, long groupId, long userId, long examConfigId) throws SystemException { return Iterables.getFirst(getExamAnswerPersistence().findByCompanyId_GroupId_UserId_ExamConfigId(companyId, groupId, userId, examConfigId), null); } }
true
true
public ExamAnswer createExamAnswer(long companyId, long groupId, long userId, String answers, Date date, long examConfigId) throws SystemException { List<ExamAnswer> list = getExamAnswerPersistence().findByCompanyId_GroupId_UserId_ExamConfigId(companyId, groupId, userId, examConfigId); Preconditions.checkArgument(list.isEmpty()); ExamAnswer result = createExamAnswer(counterLocalService.increment()); result.setCompanyId(companyId); result.setGroupId(groupId); result.setUserId(userId); result.setAnswers(answers); result.setDate(date); result.setExamConfigId(examConfigId); result = updateExamAnswer(result); return result; }
public ExamAnswer createExamAnswer(long companyId, long groupId, long userId, String answers, Date date, long examConfigId) throws SystemException { List<ExamAnswer> list = getExamAnswerPersistence().findByCompanyId_GroupId_UserId_ExamConfigId(companyId, groupId, userId, examConfigId); Preconditions.checkArgument(list.isEmpty()); ExamAnswer result = createExamAnswer(counterLocalService.increment()); result.setCompanyId(companyId); result.setGroupId(groupId); result.setUserId(userId); result.setAnswers(answers); result.setDate(date); result.setExamConfigId(examConfigId); result.resetOriginalValues(); result = updateExamAnswer(result); return result; }
diff --git a/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/plugins/contribs/OverlappingMutationsAggregationPlugin.java b/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/plugins/contribs/OverlappingMutationsAggregationPlugin.java index fa0227a1..a5fdac81 100644 --- a/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/plugins/contribs/OverlappingMutationsAggregationPlugin.java +++ b/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/plugins/contribs/OverlappingMutationsAggregationPlugin.java @@ -1,116 +1,116 @@ /* * Copyright (C) 2012 SeqWare * * 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.github.seqware.queryengine.plugins.contribs; import com.github.seqware.queryengine.model.Feature; import com.github.seqware.queryengine.model.FeatureSet; import com.github.seqware.queryengine.plugins.runners.MapperInterface; import com.github.seqware.queryengine.plugins.runners.ReducerInterface; import com.github.seqware.queryengine.plugins.recipes.FilteredFileOutputPlugin; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.hadoop.io.Text; /** * This plug-in implements an experiment with overlapping mutations in map * reduce * * @author dyuen * @version $Id: $Id */ public class OverlappingMutationsAggregationPlugin extends FilteredFileOutputPlugin { private Text text = new Text(); private Text textKey = new Text(); @Override public void map(long position, Map<FeatureSet, Collection<Feature>> atoms, MapperInterface<Text, Text> mapperInterface) { // identify mutuations that are actually at this position Set<Feature> featuresAtCurrentLocation = new HashSet<Feature>(); for (FeatureSet fs : atoms.keySet()) { for (Feature f : atoms.get(fs)) { if (f.getStart() == position) { featuresAtCurrentLocation.add(f); } } } for (FeatureSet fs : atoms.keySet()) { for (Feature f : atoms.get(fs)) { String fOverlapID = f.getTagByKey("id").getValue().toString(); for (Feature positionFeature : featuresAtCurrentLocation) { String positionFeatureVarID = calculateVarID(positionFeature); String positionOverlapID = positionFeature.getTagByKey("id").getValue().toString(); - String fFeatureVarID = calculateVarID(positionFeature); + String fFeatureVarID = calculateVarID(f); if (positionFeatureVarID.equals(fFeatureVarID)){ continue; } textKey.set(positionFeatureVarID); text.set(fOverlapID); // ( "10:100008435-100008436_G->A MU1157731" , "MU000001") mapperInterface.write(textKey, text); // display the reverse overlap as well textKey.set(fFeatureVarID); text.set(positionOverlapID); // ( "10:other_mutation MU000001" , "MU000001") mapperInterface.write(textKey, text); } } } } @Override public void reduce(Text key, Iterable<Text> values, ReducerInterface<Text, Text> reducerInterface) { // values Set<Text> seenSet = new HashSet<Text>(); String newFeatStr = ""; boolean first = true; for (Text val : values) { if (seenSet.contains(val)){ continue; } seenSet.add(val); String[] fsArr = val.toString().split(","); for (String currFS : fsArr) { if (first) { first = false; newFeatStr += currFS; } else { newFeatStr += "," + currFS; } } } // ( "10:100008435-100008436_G->A MU1157731" , "MU000001 , MU000002, MU00003") text.set(key.toString() + "\t" + newFeatStr); reducerInterface.write(text, null); } private String calculateVarID(Feature positionFeature) { String ref = positionFeature.getTagByKey("ref_base").getValue().toString(); String var = positionFeature.getTagByKey("call_base").getValue().toString(); String id = positionFeature.getTagByKey("id").getValue().toString(); String varID = positionFeature.getSeqid() + ":" + positionFeature.getStart() + "-" + positionFeature.getStop() + "_" + ref + "->" + var + "\t" + id; return varID; } }
true
true
public void map(long position, Map<FeatureSet, Collection<Feature>> atoms, MapperInterface<Text, Text> mapperInterface) { // identify mutuations that are actually at this position Set<Feature> featuresAtCurrentLocation = new HashSet<Feature>(); for (FeatureSet fs : atoms.keySet()) { for (Feature f : atoms.get(fs)) { if (f.getStart() == position) { featuresAtCurrentLocation.add(f); } } } for (FeatureSet fs : atoms.keySet()) { for (Feature f : atoms.get(fs)) { String fOverlapID = f.getTagByKey("id").getValue().toString(); for (Feature positionFeature : featuresAtCurrentLocation) { String positionFeatureVarID = calculateVarID(positionFeature); String positionOverlapID = positionFeature.getTagByKey("id").getValue().toString(); String fFeatureVarID = calculateVarID(positionFeature); if (positionFeatureVarID.equals(fFeatureVarID)){ continue; } textKey.set(positionFeatureVarID); text.set(fOverlapID); // ( "10:100008435-100008436_G->A MU1157731" , "MU000001") mapperInterface.write(textKey, text); // display the reverse overlap as well textKey.set(fFeatureVarID); text.set(positionOverlapID); // ( "10:other_mutation MU000001" , "MU000001") mapperInterface.write(textKey, text); } } } }
public void map(long position, Map<FeatureSet, Collection<Feature>> atoms, MapperInterface<Text, Text> mapperInterface) { // identify mutuations that are actually at this position Set<Feature> featuresAtCurrentLocation = new HashSet<Feature>(); for (FeatureSet fs : atoms.keySet()) { for (Feature f : atoms.get(fs)) { if (f.getStart() == position) { featuresAtCurrentLocation.add(f); } } } for (FeatureSet fs : atoms.keySet()) { for (Feature f : atoms.get(fs)) { String fOverlapID = f.getTagByKey("id").getValue().toString(); for (Feature positionFeature : featuresAtCurrentLocation) { String positionFeatureVarID = calculateVarID(positionFeature); String positionOverlapID = positionFeature.getTagByKey("id").getValue().toString(); String fFeatureVarID = calculateVarID(f); if (positionFeatureVarID.equals(fFeatureVarID)){ continue; } textKey.set(positionFeatureVarID); text.set(fOverlapID); // ( "10:100008435-100008436_G->A MU1157731" , "MU000001") mapperInterface.write(textKey, text); // display the reverse overlap as well textKey.set(fFeatureVarID); text.set(positionOverlapID); // ( "10:other_mutation MU000001" , "MU000001") mapperInterface.write(textKey, text); } } } }
diff --git a/src/jpcsp/HLE/SyscallHandler.java b/src/jpcsp/HLE/SyscallHandler.java index 6c7403a3..5edadb38 100644 --- a/src/jpcsp/HLE/SyscallHandler.java +++ b/src/jpcsp/HLE/SyscallHandler.java @@ -1,914 +1,914 @@ /* This file is part of jpcsp. Jpcsp 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. Jpcsp 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 Jpcsp. If not, see <http://www.gnu.org/licenses/>. */ package jpcsp.HLE; import jpcsp.Emulator; import jpcsp.GeneralJpcspException; import jpcsp.HLE.modules.HLEModuleManager; import jpcsp.HLE.kernel.Managers; import jpcsp.Allegrex.CpuState; public class SyscallHandler { // Change this to return the number of cycles used? public static void syscall(int code) { int gpr[] = Emulator.getProcessor().cpu.gpr; ThreadMan.getInstance().clearSyscallFreeCycles(); // Some syscalls implementation throw GeneralJpcspException, // and Processor isn't setup to catch exceptions so we'll do it // here for now, or we could just stop throwing exceptions. // Also we need to decide whether to pass arguments to the functions, // or let them read the registers they want themselves. try { // Currently using FW1.50 codes switch(code) { // case 0x2000: //sceKernelRegisterSubIntrHandler // case 0x2001: // sceKernelReleaseSubIntrHandler // case 0x2002: //sceKernelEnableSubIntr // case 0x2003: //sceKernelDisableSubIntr // case 0x2004: //sceKernelSuspendSubIntr // case 0x2005: //sceKernelResumeSubIntr // case 0x2006: //sceKernelIsSubInterruptOccurred // case 0x2007: //QueryIntrHandlerInfo // case 0x2008: //sceKernelRegisterUserSpaceIntrStack // case 0x2009: //_sceKernelReturnFromCallback // case 0x200a: //sceKernelRegisterThreadEventHandler // case 0x200b: //sceKernelReleaseThreadEventHandler // case 0x200c: //sceKernelReferThreadEventHandlerStatus case 0x200d: ThreadMan.getInstance().ThreadMan_sceKernelCreateCallback(gpr[4], gpr[5], gpr[6]); break; // case 0x200e: //sceKernelDeleteCallback // case 0x200f: //sceKernelNotifyCallback // case 0x2010: //sceKernelCancelCallback // case 0x2011: //sceKernelGetCallbackCount case 0x2012: ThreadMan.getInstance().ThreadMan_sceKernelCheckCallback(); break; case 0x2013: ThreadMan.getInstance().ThreadMan_sceKernelReferCallbackStatus(gpr[4], gpr[5]); break; case 0x2014: ThreadMan.getInstance().ThreadMan_sceKernelSleepThread(); break; case 0x2015: ThreadMan.getInstance().ThreadMan_sceKernelSleepThreadCB(); break; case 0x2016: ThreadMan.getInstance().ThreadMan_sceKernelWakeupThread(gpr[4]); break; //case 0x2017: ///sceKernelCancelWakeupThread //case 0x2018: //sceKernelSuspendThread //case 0x2019: //sceKernelResumeThread case 0x201a: ThreadMan.getInstance().ThreadMan_sceKernelWaitThreadEnd(gpr[4], gpr[5]); break; - case 0x201b: - ThreadMan.getInstance().ThreadMan_sceKernelWaitThreadEndCB(gpr[4], gpr[5]); - break; +// case 0x201b: +// ThreadMan.getInstance().ThreadMan_sceKernelWaitThreadEndCB(gpr[4], gpr[5]); +// break; case 0x201c: ThreadMan.getInstance().ThreadMan_sceKernelDelayThread(gpr[4]); break; case 0x201d: ThreadMan.getInstance().ThreadMan_sceKernelDelayThreadCB(gpr[4]); break; //sceKernelDelaySysClockThread(0x201e), // sceKernelDelaySysClockThreadCB(0x201f), case 0x2020: ThreadMan.getInstance().ThreadMan_sceKernelCreateSema(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x2021: ThreadMan.getInstance().ThreadMan_sceKernelDeleteSema(gpr[4]); break; case 0x2022: ThreadMan.getInstance().ThreadMan_sceKernelSignalSema(gpr[4], gpr[5]); break; case 0x2023: ThreadMan.getInstance().ThreadMan_sceKernelWaitSema(gpr[4], gpr[5], gpr[6]); break; case 0x2024: ThreadMan.getInstance().ThreadMan_sceKernelWaitSemaCB(gpr[4], gpr[5], gpr[6]); break; case 0x2025: ThreadMan.getInstance().ThreadMan_sceKernelPollSema(gpr[4], gpr[5]); break; case 0x2026: ThreadMan.getInstance().ThreadMan_sceKernelCancelSema(gpr[4]); // not in pspsdk, params guessed break; case 0x2027: ThreadMan.getInstance().ThreadMan_sceKernelReferSemaStatus(gpr[4], gpr[5]); break; case 0x2028: Managers.eventFlags.sceKernelCreateEventFlag(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2029: Managers.eventFlags.sceKernelDeleteEventFlag(gpr[4]); break; case 0x202a: Managers.eventFlags.sceKernelSetEventFlag(gpr[4], gpr[5]); break; case 0x202b: Managers.eventFlags.sceKernelClearEventFlag(gpr[4], gpr[5]); break; case 0x202c: Managers.eventFlags.sceKernelWaitEventFlag(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x202d: Managers.eventFlags.sceKernelWaitEventFlagCB(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x202e: Managers.eventFlags.sceKernelPollEventFlag(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x202f: Managers.eventFlags.sceKernelCancelEventFlag(gpr[4], gpr[5], gpr[6]); // not in pspsdk, params guessed break; case 0x2030: Managers.eventFlags.sceKernelReferEventFlagStatus(gpr[4], gpr[5]); break; // sceKernelCreateMbx(0x2031), // sceKernelDeleteMbx(0x2032), // sceKernelSendMbx(0x2033), // sceKernelReceiveMbx(0x2034), // sceKernelReceiveMbxCB(0x2035), // sceKernelPollMbx(0x2036), // sceKernelCancelReceiveMbx(0x2037), // sceKernelReferMbxStatus(0x2038), // sceKernelCreateMsgPipe(0x2039), // sceKernelDeleteMsgPipe(0x203a), // sceKernelSendMsgPipe(0x203b), // sceKernelSendMsgPipeCB(0x203c), // sceKernelTrySendMsgPipe(0x203d), // sceKernelReceiveMsgPipe(0x203e), // sceKernelReceiveMsgPipeCB(0x203f), // sceKernelTryReceiveMsgPipe(0x2040), // sceKernelCancelMsgPipe(0x2041), // sceKernelReferMsgPipeStatus(0x2042), case 0x2043: Managers.vpl.sceKernelCreateVpl(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x2044: Managers.vpl.sceKernelDeleteVpl(gpr[4]); break; case 0x2045: Managers.vpl.sceKernelAllocateVpl(gpr[4], gpr[5], gpr[6], gpr[8]); break; case 0x2046: Managers.vpl.sceKernelAllocateVplCB(gpr[4], gpr[5], gpr[6], gpr[8]); break; case 0x2047: Managers.vpl.sceKernelTryAllocateVpl(gpr[4], gpr[5], gpr[8]); break; case 0x2048: Managers.vpl.sceKernelFreeVpl(gpr[4], gpr[5]); break; case 0x2049: Managers.vpl.sceKernelCancelVpl(gpr[4], gpr[5]); break; case 0x204a: Managers.vpl.sceKernelReferVplStatus(gpr[4], gpr[5]); break; case 0x204b: Managers.fpl.sceKernelCreateFpl(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; case 0x204c: Managers.fpl.sceKernelDeleteFpl(gpr[4]); break; case 0x204d: Managers.fpl.sceKernelAllocateFpl(gpr[4], gpr[5], gpr[6]); break; case 0x204e: Managers.fpl.sceKernelAllocateFplCB(gpr[4], gpr[5], gpr[6]); break; case 0x204f: Managers.fpl.sceKernelTryAllocateFpl(gpr[4], gpr[5]); break; case 0x2050: Managers.fpl.sceKernelFreeFpl(gpr[4], gpr[5]); break; case 0x2051: Managers.fpl.sceKernelCancelFpl(gpr[4], gpr[5]); break; case 0x2052: Managers.fpl.sceKernelReferFplStatus(gpr[4], gpr[5]); break; // ThreadManForUser_0E927AED(0x2053), case 0x2054: Managers.systime.sceKernelUSec2SysClock(gpr[4], gpr[5]); break; // sceKernelUSec2SysClockWide(0x2055), case 0x2056: Managers.systime.sceKernelSysClock2USec(gpr[4], gpr[5], gpr[6]); break; // sceKernelSysClock2USecWide(0x2057), case 0x2058: Managers.systime.sceKernelGetSystemTime(gpr[4]); break; case 0x2059: Managers.systime.sceKernelGetSystemTimeWide(); break; case 0x205a: Managers.systime.sceKernelGetSystemTimeLow(); break; // sceKernelSetAlarm(0x205b), // sceKernelSetSysClockAlarm(0x205c), // sceKernelCancelAlarm(0x205d), // sceKernelReferAlarmStatus(0x205e), // sceKernelCreateVTimer(0x205f), // sceKernelDeleteVTimer(0x2060), // sceKernelGetVTimerBase(0x2061), // sceKernelGetVTimerBaseWide(0x2062), // sceKernelGetVTimerTime(0x2063), // sceKernelGetVTimerTimeWide(0x2064), // sceKernelSetVTimerTime(0x2065), // sceKernelSetVTimerTimeWide(0x2066), // sceKernelStartVTimer(0x2067), // sceKernelStopVTimer(0x2068), // sceKernelSetVTimerHandler(0x2069), // sceKernelSetVTimerHandlerWide(0x206a), // sceKernelCancelVTimerHandler(0x206b), // sceKernelReferVTimerStatus(0x206c), case 0x206d: ThreadMan.getInstance().ThreadMan_sceKernelCreateThread(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; case 0x206e: ThreadMan.getInstance().ThreadMan_sceKernelDeleteThread(gpr[4]); break; case 0x206f: ThreadMan.getInstance().ThreadMan_sceKernelStartThread(gpr[4], gpr[5], gpr[6]); break; case 0x2070: case 0x2071: ThreadMan.getInstance().ThreadMan_sceKernelExitThread(gpr[4]); break; case 0x2072: ThreadMan.getInstance().ThreadMan_sceKernelExitDeleteThread(gpr[4]); break; case 0x2073: ThreadMan.getInstance().ThreadMan_sceKernelTerminateThread(gpr[4]); break; case 0x2074: ThreadMan.getInstance().ThreadMan_sceKernelTerminateDeleteThread(gpr[4]); break; // sceKernelSuspendDispatchThread(0x2075), //sceKernelResumeDispatchThread(0x2076), case 0x2077: ThreadMan.getInstance().ThreadMan_sceKernelChangeCurrentThreadAttr(gpr[4], gpr[5]); break; case 0x2078: ThreadMan.getInstance().ThreadMan_sceKernelChangeThreadPriority(gpr[4], gpr[5]); break; // sceKernelRotateThreadReadyQueue(0x2079), // sceKernelReleaseWaitThread(0x207a), case 0x207b: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadId(); break; case 0x207c: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadCurrentPriority(); break; case 0x207d: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadExitStatus(gpr[4]); break; case 0x207e: ThreadMan.getInstance().ThreadMan_sceKernelCheckThreadStack(); break; case 0x207f: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadStackFreeSize(gpr[4]); break; case 0x2080: ThreadMan.getInstance().ThreadMan_sceKernelReferThreadStatus(gpr[4], gpr[5]); break; // sceKernelReferThreadRunStatus(0x2081), // sceKernelReferSystemStatus(0x2082), case 0x2083: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadmanIdList(gpr[4], gpr[5], gpr[6], gpr[7]); break; // sceKernelGetThreadmanIdType(0x2084), // sceKernelReferThreadProfiler(0x2085), // sceKernelReferGlobalProfiler(0x2086), case 0x2087: pspiofilemgr.getInstance().sceIoPollAsync(gpr[4], gpr[5]); break; case 0x2088: pspiofilemgr.getInstance().sceIoWaitAsync(gpr[4], gpr[5]); break; case 0x2089: pspiofilemgr.getInstance().sceIoWaitAsyncCB(gpr[4], gpr[5]); break; case 0x208a: pspiofilemgr.getInstance().sceIoGetAsyncStat(gpr[4], gpr[5], gpr[6]); break; // sceIoChangeAsyncPriority(0x208b), // sceIoSetAsyncCallback(0x208c), case 0x208d: pspiofilemgr.getInstance().sceIoClose(gpr[4]); break; case 0x208e: pspiofilemgr.getInstance().sceIoCloseAsync(gpr[4]); break; case 0x208f: pspiofilemgr.getInstance().sceIoOpen(gpr[4], gpr[5], gpr[6]); break; case 0x2090: pspiofilemgr.getInstance().sceIoOpenAsync(gpr[4], gpr[5], gpr[6]); break; case 0x2091: pspiofilemgr.getInstance().sceIoRead(gpr[4], gpr[5], gpr[6]); break; case 0x2092: pspiofilemgr.getInstance().sceIoReadAsync(gpr[4], gpr[5], gpr[6]); break; case 0x2093: pspiofilemgr.getInstance().sceIoWrite(gpr[4], gpr[5], gpr[6]); break; case 0x2094: pspiofilemgr.getInstance().sceIoWriteAsync(gpr[4], gpr[5], gpr[6]); break; case 0x2095: pspiofilemgr.getInstance().sceIoLseek( gpr[4], ((((long)gpr[6]) & 0xFFFFFFFFL) | (((long)gpr[7])<<32)), gpr[8]); break; case 0x2096: pspiofilemgr.getInstance().sceIoLseekAsync( gpr[4], ((((long)gpr[6]) & 0xFFFFFFFFL) | (((long)gpr[7])<<32)), gpr[8]); break; case 0x2097: pspiofilemgr.getInstance().sceIoLseek32( gpr[4], gpr[5], gpr[6]); break; case 0x2098: pspiofilemgr.getInstance().sceIoLseek32Async( gpr[4], gpr[5], gpr[6]); break; // sceIoIoctl(0x2099), // sceIoIoctlAsync(0x209a), case 0x209b: pspiofilemgr.getInstance().sceIoDopen(gpr[4]); break; case 0x209c: pspiofilemgr.getInstance().sceIoDread(gpr[4], gpr[5]); break; case 0x209d: pspiofilemgr.getInstance().sceIoDclose(gpr[4]); break; // sceIoRemove(0x209e), case 0x209f: pspiofilemgr.getInstance().sceIoMkdir(gpr[4], gpr[5]); break; // sceIoRmdir(0x20a0), case 0x20a1: pspiofilemgr.getInstance().sceIoChdir(gpr[4]); break; case 0x20a2: pspiofilemgr.getInstance().sceIoSync(gpr[4], gpr[5]); break; case 0x20a3: pspiofilemgr.getInstance().sceIoGetstat(gpr[4], gpr[5]); break; // sceIoChstat(0x20a4), // sceIoRename(0x20a5), case 0x20a6: pspiofilemgr.getInstance().sceIoDevctl(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; // sceIoGetDevType(0x20a7), case 0x20a8: pspiofilemgr.getInstance().sceIoAssign(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; // sceIoUnassign(0x20a9), // sceIoCancel(0x20aa), // IoFileMgrForUser_5C2BE2CC(0x20ab), // sceKernelStdioRead(0x20ac), // sceKernelStdioLseek(0x20ad), // sceKernelStdioSendChar(0x20ae), // sceKernelStdioWrite(0x20af), // sceKernelStdioClose(0x20b0), //sceKernelStdioOpen(0x20b1), case 0x20b5: psputils.getInstance().sceKernelDcacheInvalidateRange(gpr[4], gpr[5]); break; // sceKernelIcacheInvalidateRange(0x20b6), // sceKernelUtilsMd5Digest(0x20b7), // sceKernelUtilsMd5BlockInit(0x20b8), // sceKernelUtilsMd5BlockUpdate(0x20b9), // sceKernelUtilsMd5BlockResult(0x20ba), // sceKernelUtilsSha1Digest(0x20bb), // sceKernelUtilsSha1BlockInit(0x20bc), // sceKernelUtilsSha1BlockUpdate(0x20bd), // sceKernelUtilsSha1BlockResult(0x20be), case 0x20bf: psputils.getInstance().sceKernelUtilsMt19937Init(gpr[4], gpr[5]); break; case 0x20c0: psputils.getInstance().sceKernelUtilsMt19937UInt(gpr[4]); break; case 0x20c1: psputils.getInstance().sceKernelGetGPI(); break; case 0x20c2: psputils.getInstance().sceKernelSetGPO(gpr[4]); break; case 0x20c3: psputils.getInstance().sceKernelLibcClock(); break; case 0x20c4: psputils.getInstance().sceKernelLibcTime(gpr[4]); break; case 0x20c5: psputils.getInstance().sceKernelLibcGettimeofday(gpr[4], gpr[5]); break; case 0x20c6: psputils.getInstance().sceKernelDcacheWritebackAll(); break; case 0x20c7: psputils.getInstance().sceKernelDcacheWritebackInvalidateAll(); break; case 0x20c8: psputils.getInstance().sceKernelDcacheWritebackRange(gpr[4], gpr[5]); break; case 0x20c9: psputils.getInstance().sceKernelDcacheWritebackInvalidateRange(gpr[4], gpr[5]); break; // sceKernelDcacheProbe(0x20ca), // sceKernelDcacheReadTag(0x20cb), // sceKernelIcacheInvalidateAll(0x20cc), // sceKernelIcacheProbe(0x20cd), // sceKernelIcacheReadTag(0x20ce), // sceKernelLoadModule(0x20cf), // sceKernelLoadModuleByID(0x20d0), // sceKernelLoadModuleMs(0x20d1), // sceKernelLoadModuleBufferUsbWlan(0x20d2), // sceKernelStartModule(0x20d3), // sceKernelStopModule(0x20d4), // sceKernelUnloadModule(0x20d5), // sceKernelSelfStopUnloadModule(0x20d6), // sceKernelStopUnloadSelfModule(0x20d7), // sceKernelGetModuleIdList(0x20d8), // sceKernelQueryModuleInfo(0x20d9), // ModuleMgrForUser_F0A26395(0x20da), // ModuleMgrForUser_D8B73127(0x20db), case 0x20dc: pspSysMem.getInstance().sceKernelMaxFreeMemSize(); break; case 0x20dd: pspSysMem.getInstance().sceKernelTotalFreeMemSize(); break; case 0x20de: pspSysMem.getInstance().sceKernelAllocPartitionMemory(gpr[4], gpr[5], gpr[6], gpr[7],gpr[8]); break; case 0x20df: pspSysMem.getInstance().sceKernelFreePartitionMemory(gpr[4]); break; case 0x20e0: pspSysMem.getInstance().sceKernelGetBlockHeadAddr(gpr[4]); break; // SysMemUserForUser_13A5ABEF(0x20e1), case 0x20e2: pspSysMem.getInstance().sceKernelDevkitVersion(); break; // sceKernelPowerLock(0x20e3), // sceKernelPowerUnlock(0x20e4), // sceKernelPowerTick(0x20e5), // sceSuspendForUser_3E0271D3(0x20e6), // sceSuspendForUser_A14F40B2(0x20e7), // sceSuspendForUser_A569E425(0x20e8), case 0x20e9: LoadExec.getInstance().sceKernelLoadExec(gpr[4], gpr[5]); break; // sceKernelExitGameWithStatus(0x20ea), case 0x20eb: LoadExec.getInstance().sceKernelExitGame(); break; case 0x20ec: LoadExec.getInstance().sceKernelRegisterExitCallback(gpr[4]); break; // sceDmacMemcpy(0x20ed), // sceDmacTryMemcpy(0x20ee), case 0x20ef: pspge.getInstance().sceGeEdramGetSize(); break; case 0x20f0: pspge.getInstance().sceGeEdramGetAddr(); break; //sceGeEdramSetAddrTranslation(0x20f1), // sceGeGetCmd(0x20f2), // sceGeGetMtx(0x20f3), // sceGeSaveContext(0x20f4), // sceGeRestoreContext(0x20f5), case 0x20f6: pspge.getInstance().sceGeListEnQueue(gpr[4], gpr[5], gpr[6], gpr[7]); break; // sceGeListEnQueueHead(0x20f7), case 0x20f8: pspge.getInstance().sceGeListDeQueue(gpr[4]); break; case 0x20f9: pspge.getInstance().sceGeListUpdateStallAddr(gpr[4], gpr[5]); break; /* ge sync case 0x20fa: pspge.getInstance().sceGeListSync(gpr[4], gpr[5]); break; */ case 0x20fb: pspge.getInstance().sceGeDrawSync(gpr[4]); break; // sceGeBreak(0x20fc), // sceGeContinue(0x20fd), /* ge callback case 0x20fe: pspge.getInstance().sceGeSetCallback(gpr[4]); break; case 0x20ff: pspge.getInstance().sceGeUnsetCallback(gpr[4]); break; */ /* case 0x2100: psprtc.getInstance().sceRtcGetTickResolution(); break; case 0x2101: psprtc.getInstance().sceRtcGetCurrentTick(gpr[4]); break; // sceRtc_011F03C1(0x2102), // sceRtc_029CA3B3(0x2103), // sceRtcGetCurrentClock(0x2104), case 0x2105: psprtc.getInstance().sceRtcGetCurrentClockLocalTime(gpr[4]); break;*/ // sceRtcConvertUtcToLocalTime(0x2106), // sceRtcConvertLocalTimeToUTC(0x2107), // sceRtcIsLeapYear(0x2108), // sceRtcGetDaysInMonth(0x2109), // sceRtcGetDayOfWeek(0x210a), // sceRtcCheckValid(0x210b), // sceRtcSetTime_t(0x210c), // sceRtcGetTime_t(0x210d), // sceRtcSetDosTime(0x210e), // sceRtcGetDosTime(0x210f), // sceRtcSetWin32FileTime(0x2110), // sceRtcGetWin32FileTime(0x2111), // sceRtcSetTick(0x2112), // sceRtcGetTick(0x2113), // sceRtcCompareTick(0x2114), // sceRtcTickAddTicks(0x2115), // sceRtcTickAddMicroseconds(0x2116), // sceRtcTickAddSeconds(0x2117), // sceRtcTickAddMinutes(0x2118), // sceRtcTickAddHours(0x2119), // sceRtcTickAddDays(0x211a), // sceRtcTickAddWeeks(0x211b), // sceRtcTickAddMonths(0x211c), // sceRtcTickAddYears(0x211d), // sceRtcFormatRFC2822(0x211e), // sceRtcFormatRFC2822LocalTime(0x211f), // sceRtcFormatRFC3339(0x2120), // sceRtcFormatRFC3339LocalTime(0x2121), // sceRtcParseDateTime(0x2122), // sceRtcParseRFC3339(0x2123), /* case 0x2124: pspAudio.getInstance().sceAudioOutput(gpr[4], gpr[5], gpr[6]); break; case 0x2125: pspAudio.getInstance().sceAudioOutputBlocking(gpr[4], gpr[5], gpr[6]); break; case 0x2126: pspAudio.getInstance().sceAudioOutputPanned(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2127: pspAudio.getInstance().sceAudioOutputPannedBlocking(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2128: pspAudio.getInstance().sceAudioChReserve(gpr[4], gpr[5], gpr[6]); break; //case 0x2129: pspAudio.getInstance().sceAudioOneshotOutput(); break; case 0x212a: pspAudio.getInstance().sceAudioChRelease(gpr[4]); break; case 0x212b: pspAudio.getInstance().sceAudioGetChannelRestLength(gpr[4]); break; case 0x212c: pspAudio.getInstance().sceAudioSetChannelDataLen(gpr[4], gpr[5]); break; //case 0x212d: pspAudio.getInstance().sceAudioChangeChannelConfig(gpr[4], gpr[5]); break; case 0x212e: pspAudio.getInstance().sceAudioChangeChannelVolume(gpr[4], gpr[5], gpr[6]); break; //case 0x212f: pspAudio.getInstance().sceAudio_38553111(); break; //case 0x2130: pspAudio.getInstance().sceAudio_5C37C0AE(); break; //case 0x2131: pspAudio.getInstance().sceAudio_E0727056(); break; //case 0x2132: pspAudio.getInstance().sceAudioInputBlocking(gpr[4], gpr[5], gpr[6]); break; //case 0x2133: pspAudio.getInstance().sceAudioInput(gpr[4], gpr[5], gpr[6]); break; //case 0x2134: pspAudio.getInstance().sceAudioGetInputLength(); break; //case 0x2135: pspAudio.getInstance().sceAudioWaitInputEnd(); break; //case 0x2136: pspAudio.getInstance().sceAudioInputInit(gpr[4], gpr[5], gpr[6]); break; //case 0x2137: pspAudio.getInstance().sceAudio_E926D3FB(); break; //case 0x2138: pspAudio.getInstance().sceAudio_A633048E(); break; case 0x2139: pspAudio.getInstance().sceAudioGetChannelRestLen(gpr[4]); break; */ case 0x213a: pspdisplay.getInstance().sceDisplaySetMode(gpr[4], gpr[5], gpr[6]); break; // sceDisplayGetMode(0x213b), // sceDisplayGetFramePerSec(0x213c), // sceDisplaySetHoldMode(0x213d), // sceDisplaySetResumeMode(0x213e), case 0x213f: pspdisplay.getInstance().sceDisplaySetFrameBuf(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2140: pspdisplay.getInstance().sceDisplayGetFrameBuf(gpr[4], gpr[5], gpr[6], gpr[7]); break; // sceDisplayIsForeground(0x2141), // sceDisplayGetBrightness(0x2142), // sceDisplayGetVcount(0x2143), case 0x2143: pspdisplay.getInstance().sceDisplayGetVcount(); break; // sceDisplayIsVblank(0x2144), case 0x2145: pspdisplay.getInstance().sceDisplayWaitVblank(); break; case 0x2146: pspdisplay.getInstance().sceDisplayWaitVblankCB(); break; case 0x2147: pspdisplay.getInstance().sceDisplayWaitVblankStart(); break; case 0x2148: pspdisplay.getInstance().sceDisplayWaitVblankStartCB(); break; case 0x2149: pspdisplay.getInstance().sceDisplayGetCurrentHcount(); break; case 0x214a: pspdisplay.getInstance().sceDisplayGetAccumulatedHcount(); break; // sceDisplay_A83EF139(0x214b), /* case 0x214c: pspctrl.getInstance().sceCtrlSetSamplingCycle(gpr[4]); break; case 0x214d: pspctrl.getInstance().sceCtrlGetSamplingCycle(gpr[4]); break; case 0x214e: pspctrl.getInstance().sceCtrlSetSamplingMode(gpr[4]); break; case 0x214f: pspctrl.getInstance().sceCtrlGetSamplingMode(gpr[4]); break; case 0x2150: pspctrl.getInstance().sceCtrlPeekBufferPositive(gpr[4], gpr[5]); break; case 0x2151: pspctrl.getInstance().sceCtrlPeekBufferNegative(gpr[4], gpr[5]); break; case 0x2152: pspctrl.getInstance().sceCtrlReadBufferPositive(gpr[4], gpr[5]); break; case 0x2153: pspctrl.getInstance().sceCtrlReadBufferNegative(gpr[4], gpr[5]); break; case 0x2154: pspctrl.getInstance().sceCtrlPeekLatch(gpr[4]); break; case 0x2155: pspctrl.getInstance().sceCtrlReadLatch(gpr[4]); break;*/ // sceCtrl_A7144800(0x2156), // sceCtrl_687660FA(0x2157), // sceCtrl_348D99D4(0x2158), // sceCtrl_AF5960F3(0x2159), // sceCtrl_A68FD260(0x215a), // sceCtrl_6841BE1A(0x215b), // sceHprmRegisterCallback(0x215c), // sceHprmUnregisterCallback(0x215d), // sceHprm_71B5FB67(0x215e), // sceHprmIsRemoteExist(0x215f), // sceHprmIsHeadphoneExist(0x2160), // sceHprmIsMicrophoneExist(0x2161), // sceHprmPeekCurrentKey(0x2162), // sceHprmPeekLatch(0x2163), // sceHprmReadLatch(0x2164), // scePower_2B51FE2F(0x2165), // scePower_442BFBAC(0x2166), /// scePowerTick(0x2167), // scePowerGetIdleTimer(0x2168), // scePowerIdleTimerEnable(0x2169), // scePowerIdleTimerDisable(0x216a), // scePowerBatteryUpdateInfo(0x216b), // scePower_E8E4E204(0x216c), // scePowerGetLowBatteryCapacity(0x216d), // scePowerIsPowerOnline(0x216e), // scePowerIsBatteryExist(0x216f), // scePowerIsBatteryCharging(0x2170), // scePowerGetBatteryChargingStatus(0x2171), // scePowerIsLowBattery(0x2172), // scePower_78A1A796(0x2173), // scePowerGetBatteryRemainCapacity(0x2174), // scePower_FD18A0FF(0x2175), //// scePowerGetBatteryLifePercent(0x2176), // scePowerGetBatteryLifeTime(0x2177), //// scePowerGetBatteryTemp(0x2178), // scePowerGetBatteryElec(0x2179), // scePowerGetBatteryVolt(0x217a), // scePower_23436A4A(0x217b), // scePower_0CD21B1F(0x217c), // scePower_165CE085(0x217d), // scePower_23C31FFE(0x217e), // scePower_FA97A599(0x217f), // scePower_B3EDD801(0x2180), // scePowerLock(0x2181), // scePowerUnlock(0x2182), // scePowerCancelRequest(0x2183), // scePowerIsRequest(0x2184), // scePowerRequestStandby(0x2185), // scePowerRequestSuspend(0x2186), // scePower_2875994B(0x2187), // scePowerEncodeUBattery(0x2188), // scePowerGetResumeCount(0x2189), // scePowerRegisterCallback(0x218a), // scePowerUnregisterCallback(0x218b), // scePowerUnregitserCallback(0x218c), // scePowerSetCpuClockFrequency(0x218d), /// scePowerSetBusClockFrequency(0x218e), // scePowerGetCpuClockFrequency(0x218f), // scePowerGetBusClockFrequency(0x2190), // scePowerGetCpuClockFrequencyInt(0x2191), // scePowerGetBusClockFrequencyInt(0x2192), // scePower_34F9C463(0x2193), // scePowerGetCpuClockFrequencyFloat(0x2194), // scePowerGetBusClockFrequencyFloat(0x2195), // scePower_EA382A27(0x2196), // scePowerSetClockFrequency(0x2197), // sceUsbStart(0x2198), // sceUsbStop(0x2199), // sceUsbGetState(0x219a), // sceUsbGetDrvList(0x219b), // sceUsbGetDrvState(0x219c), // sceUsbActivate(0x219d), // sceUsbDeactivate(0x219e), // sceUsbWaitState(0x219f), // sceUsbWaitCancel(0x21a0), // sceOpenPSIDGetOpenPSID(0x21a1), // sceSircsSend(0x21a2), // sceUmdCheckMedium(0x21a3), // sceUmdActivate(0x21a4), // sceUmdDeactivate(0x21a5), // sceUmdWaitDriveStat(0x21a6), // sceUmdWaitDriveStatWithTimer(0x21a7), // sceUmdWaitDriveStatCB(0x21a8), // sceUmdCancelWaitDriveStat(0x21a9), // sceUmdGetDriveStat(0x21aa), // sceUmdGetErrorStat(0x21ab), // sceUmdGetDiscInfo(0x21ac), // sceUmdRegisterUMDCallBack(0x21ad), // sceUmdUnRegisterUMDCallBack(0x21ae), // sceWlanDevIsPowerOn(0x21af), // sceWlanGetSwitchState(0x21b0), // sceWlanGetEtherAddr(0x21b1), // sceWlanDevAttach(0x21b2), // sceWlanDevDetach(0x21b3), // sceWlanDrv_lib_19E51F54(0x21b4), // sceWlanDevIsGameMode(0x21b5), // sceWlanGPPrevEstablishActive(0x21b6), // sceWlanGPSend(0x21b7), // sceWlanGPRecv(0x21b8), // sceWlanGPRegisterCallback(0x21b9), // sceWlanGPUnRegisterCallback(0x21ba), // sceWlanDrv_lib_81579D36(0x21bb), // sceWlanDrv_lib_5BAA1FE5(0x21bc), // sceWlanDrv_lib_4C14BACA(0x21bd), // sceWlanDrv_lib_2D0FAE4E(0x21be), // sceWlanDrv_lib_56F467CA(0x21bf), // sceWlanDrv_lib_FE8A0B46(0x21c0), // sceWlanDrv_lib_40B0AA4A(0x21c1), // sceWlanDevSetGPIO(0x21c2), // sceWlanDevGetStateGPIO(0x21c3), // sceWlanDrv_lib_8D5F551B(0x21c4), // sceVaudioOutputBlocking(0x21c5), // sceVaudioChReserve(0x21c6), // sceVaudioChRelease(0x21c7), // sceVaudio_346FBE94(0x21c8), // sceRegExit(0x21c9), // sceRegOpenRegistry(0x21ca), // sceRegCloseRegistry(0x21cb), // sceRegRemoveRegistry(0x21cc), // sceReg_1D8A762E(0x21cd), // sceReg_0CAE832B(0x21ce), // sceRegFlushRegistry(0x21cf), // sceReg_0D69BF40(0x21d0), // sceRegCreateKey(0x21d1), // sceRegSetKeyValue(0x21d2), // sceRegGetKeyInfo(0x21d3), // sceRegGetKeyValue(0x21d4), // sceRegGetKeysNum(0x21d5), // sceRegGetKeys(0x21d6), // sceReg_4CA16893(0x21d7), // sceRegRemoveKey(0x21d8), // sceRegKickBackDiscover(0x21d9), // sceRegGetKeyValueByName(0x21da), // sceUtilityGameSharingInitStart(0x21db), // sceUtilityGameSharingShutdownStart(0x21dc), // sceUtilityGameSharingUpdate(0x21dd), // sceUtilityGameSharingGetStatus(0x21de), // sceNetplayDialogInitStart(0x21df), // sceNetplayDialogShutdownStart(0x21e0), // sceNetplayDialogUpdate(0x21e1), // sceNetplayDialogGetStatus(0x21e2), // sceUtilityNetconfInitStart(0x21e3), // sceUtilityNetconfShutdownStart(0x21e4), // sceUtilityNetconfUpdate(0x21e5), // sceUtilityNetconfGetStatus(0x21e6), // sceUtilitySavedataInitStart(0x21e7), // sceUtilitySavedataShutdownStart(0x21e8), // sceUtilitySavedataUpdate(0x21e9), // sceUtilitySavedataGetStatus(0x21ea), // sceUtility_2995D020(0x21eb), // sceUtility_B62A4061(0x21ec), // sceUtility_ED0FAD38(0x21ed), // sceUtility_88BC7406(0x21ee), // sceUtilityMsgDialogInitStart(0x21ef), // sceUtilityMsgDialogShutdownStart(0x21f0), // sceUtilityMsgDialogUpdate(0x21f1), // sceUtilityMsgDialogGetStatus(0x21f2), // sceUtilityOskInitStart(0x21f3), // sceUtilityOskShutdownStart(0x21f4), // sceUtilityOskUpdate(0x21f5), // sceUtilityOskGetStatus(0x21f6), // sceUtilitySetSystemParamInt(0x21f7), // sceUtilitySetSystemParamString(0x21f8), // sceUtilityGetSystemParamInt(0x21f9), // sceUtilityGetSystemParamString(0x21fa), // sceUtilityCheckNetParam(0x21fb), // sceUtilityGetNetParam(0x21fc), // sceUtility_private_17CB4D96(0x21fd), // sceUtility_private_EE7AC503(0x21fe), // sceUtility_private_5FF96ED3(0x21ff), // sceUtility_private_9C9DD5BC(0x2200), // sceUtility_private_4405BA38(0x2201), // sceUtility_private_1DFA62EF(0x2202), // sceUtilityDialogSetStatus(0x2203), // sceUtilityDialogGetType(0x2204), // sceUtilityDialogGetParam(0x2205), // sceUtility_private_EF5BC2D1(0x2206), // sceUtilityDialogGetSpeed(0x2207), // sceUtility_private_19461966(0x2208), // sceUtilityDialogSetThreadId(0x2209), // sceUtilityDialogLoadModule(0x220a), // sceUtilityDialogPowerLock(0x220b), // sceUtilityDialogPowerUnlock(0x220c), // sceUtilityCreateNetParam(0x220d), //sceUtilityDeleteNetParam(0x220e), //sceUtilityCopyNetParam(0x220f), // sceUtilitySetNetParam(0x2210); case 0xfffff: // special code for unmapped imports Modules.log.error(String.format("Unmapped import @ 0x%08X", Emulator.getProcessor().cpu.pc)); Emulator.PauseEmu(); break; default: { // Try and handle as an HLE module export boolean handled = HLEModuleManager.getInstance().handleSyscall(code); if (!handled) { CpuState cpu = Emulator.getProcessor().cpu; // At least set a decent return value cpu.gpr[2] = 0; //Emulator.getProcessor().gpr[2] = 0xb515ca11; // Display debug info String params = String.format("%08x %08x %08x", cpu.gpr[4], cpu.gpr[5], cpu.gpr[6]); for (jpcsp.Debugger.DisassemblerModule.syscallsFirm15.calls c : jpcsp.Debugger.DisassemblerModule.syscallsFirm15.calls.values()) { if (c.getSyscall() == code) { Modules.log.warn("Unsupported syscall " + Integer.toHexString(code) + " " + c + " " + params); return; } } Modules.log.warn("Unsupported syscall " + Integer.toHexString(code) + " " + params); } } break; } } catch(GeneralJpcspException e) { System.out.println(e.getMessage()); } } }
true
true
public static void syscall(int code) { int gpr[] = Emulator.getProcessor().cpu.gpr; ThreadMan.getInstance().clearSyscallFreeCycles(); // Some syscalls implementation throw GeneralJpcspException, // and Processor isn't setup to catch exceptions so we'll do it // here for now, or we could just stop throwing exceptions. // Also we need to decide whether to pass arguments to the functions, // or let them read the registers they want themselves. try { // Currently using FW1.50 codes switch(code) { // case 0x2000: //sceKernelRegisterSubIntrHandler // case 0x2001: // sceKernelReleaseSubIntrHandler // case 0x2002: //sceKernelEnableSubIntr // case 0x2003: //sceKernelDisableSubIntr // case 0x2004: //sceKernelSuspendSubIntr // case 0x2005: //sceKernelResumeSubIntr // case 0x2006: //sceKernelIsSubInterruptOccurred // case 0x2007: //QueryIntrHandlerInfo // case 0x2008: //sceKernelRegisterUserSpaceIntrStack // case 0x2009: //_sceKernelReturnFromCallback // case 0x200a: //sceKernelRegisterThreadEventHandler // case 0x200b: //sceKernelReleaseThreadEventHandler // case 0x200c: //sceKernelReferThreadEventHandlerStatus case 0x200d: ThreadMan.getInstance().ThreadMan_sceKernelCreateCallback(gpr[4], gpr[5], gpr[6]); break; // case 0x200e: //sceKernelDeleteCallback // case 0x200f: //sceKernelNotifyCallback // case 0x2010: //sceKernelCancelCallback // case 0x2011: //sceKernelGetCallbackCount case 0x2012: ThreadMan.getInstance().ThreadMan_sceKernelCheckCallback(); break; case 0x2013: ThreadMan.getInstance().ThreadMan_sceKernelReferCallbackStatus(gpr[4], gpr[5]); break; case 0x2014: ThreadMan.getInstance().ThreadMan_sceKernelSleepThread(); break; case 0x2015: ThreadMan.getInstance().ThreadMan_sceKernelSleepThreadCB(); break; case 0x2016: ThreadMan.getInstance().ThreadMan_sceKernelWakeupThread(gpr[4]); break; //case 0x2017: ///sceKernelCancelWakeupThread //case 0x2018: //sceKernelSuspendThread //case 0x2019: //sceKernelResumeThread case 0x201a: ThreadMan.getInstance().ThreadMan_sceKernelWaitThreadEnd(gpr[4], gpr[5]); break; case 0x201b: ThreadMan.getInstance().ThreadMan_sceKernelWaitThreadEndCB(gpr[4], gpr[5]); break; case 0x201c: ThreadMan.getInstance().ThreadMan_sceKernelDelayThread(gpr[4]); break; case 0x201d: ThreadMan.getInstance().ThreadMan_sceKernelDelayThreadCB(gpr[4]); break; //sceKernelDelaySysClockThread(0x201e), // sceKernelDelaySysClockThreadCB(0x201f), case 0x2020: ThreadMan.getInstance().ThreadMan_sceKernelCreateSema(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x2021: ThreadMan.getInstance().ThreadMan_sceKernelDeleteSema(gpr[4]); break; case 0x2022: ThreadMan.getInstance().ThreadMan_sceKernelSignalSema(gpr[4], gpr[5]); break; case 0x2023: ThreadMan.getInstance().ThreadMan_sceKernelWaitSema(gpr[4], gpr[5], gpr[6]); break; case 0x2024: ThreadMan.getInstance().ThreadMan_sceKernelWaitSemaCB(gpr[4], gpr[5], gpr[6]); break; case 0x2025: ThreadMan.getInstance().ThreadMan_sceKernelPollSema(gpr[4], gpr[5]); break; case 0x2026: ThreadMan.getInstance().ThreadMan_sceKernelCancelSema(gpr[4]); // not in pspsdk, params guessed break; case 0x2027: ThreadMan.getInstance().ThreadMan_sceKernelReferSemaStatus(gpr[4], gpr[5]); break; case 0x2028: Managers.eventFlags.sceKernelCreateEventFlag(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2029: Managers.eventFlags.sceKernelDeleteEventFlag(gpr[4]); break; case 0x202a: Managers.eventFlags.sceKernelSetEventFlag(gpr[4], gpr[5]); break; case 0x202b: Managers.eventFlags.sceKernelClearEventFlag(gpr[4], gpr[5]); break; case 0x202c: Managers.eventFlags.sceKernelWaitEventFlag(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x202d: Managers.eventFlags.sceKernelWaitEventFlagCB(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x202e: Managers.eventFlags.sceKernelPollEventFlag(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x202f: Managers.eventFlags.sceKernelCancelEventFlag(gpr[4], gpr[5], gpr[6]); // not in pspsdk, params guessed break; case 0x2030: Managers.eventFlags.sceKernelReferEventFlagStatus(gpr[4], gpr[5]); break; // sceKernelCreateMbx(0x2031), // sceKernelDeleteMbx(0x2032), // sceKernelSendMbx(0x2033), // sceKernelReceiveMbx(0x2034), // sceKernelReceiveMbxCB(0x2035), // sceKernelPollMbx(0x2036), // sceKernelCancelReceiveMbx(0x2037), // sceKernelReferMbxStatus(0x2038), // sceKernelCreateMsgPipe(0x2039), // sceKernelDeleteMsgPipe(0x203a), // sceKernelSendMsgPipe(0x203b), // sceKernelSendMsgPipeCB(0x203c), // sceKernelTrySendMsgPipe(0x203d), // sceKernelReceiveMsgPipe(0x203e), // sceKernelReceiveMsgPipeCB(0x203f), // sceKernelTryReceiveMsgPipe(0x2040), // sceKernelCancelMsgPipe(0x2041), // sceKernelReferMsgPipeStatus(0x2042), case 0x2043: Managers.vpl.sceKernelCreateVpl(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x2044: Managers.vpl.sceKernelDeleteVpl(gpr[4]); break; case 0x2045: Managers.vpl.sceKernelAllocateVpl(gpr[4], gpr[5], gpr[6], gpr[8]); break; case 0x2046: Managers.vpl.sceKernelAllocateVplCB(gpr[4], gpr[5], gpr[6], gpr[8]); break; case 0x2047: Managers.vpl.sceKernelTryAllocateVpl(gpr[4], gpr[5], gpr[8]); break; case 0x2048: Managers.vpl.sceKernelFreeVpl(gpr[4], gpr[5]); break; case 0x2049: Managers.vpl.sceKernelCancelVpl(gpr[4], gpr[5]); break; case 0x204a: Managers.vpl.sceKernelReferVplStatus(gpr[4], gpr[5]); break; case 0x204b: Managers.fpl.sceKernelCreateFpl(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; case 0x204c: Managers.fpl.sceKernelDeleteFpl(gpr[4]); break; case 0x204d: Managers.fpl.sceKernelAllocateFpl(gpr[4], gpr[5], gpr[6]); break; case 0x204e: Managers.fpl.sceKernelAllocateFplCB(gpr[4], gpr[5], gpr[6]); break; case 0x204f: Managers.fpl.sceKernelTryAllocateFpl(gpr[4], gpr[5]); break; case 0x2050: Managers.fpl.sceKernelFreeFpl(gpr[4], gpr[5]); break; case 0x2051: Managers.fpl.sceKernelCancelFpl(gpr[4], gpr[5]); break; case 0x2052: Managers.fpl.sceKernelReferFplStatus(gpr[4], gpr[5]); break; // ThreadManForUser_0E927AED(0x2053), case 0x2054: Managers.systime.sceKernelUSec2SysClock(gpr[4], gpr[5]); break; // sceKernelUSec2SysClockWide(0x2055), case 0x2056: Managers.systime.sceKernelSysClock2USec(gpr[4], gpr[5], gpr[6]); break; // sceKernelSysClock2USecWide(0x2057), case 0x2058: Managers.systime.sceKernelGetSystemTime(gpr[4]); break; case 0x2059: Managers.systime.sceKernelGetSystemTimeWide(); break; case 0x205a: Managers.systime.sceKernelGetSystemTimeLow(); break; // sceKernelSetAlarm(0x205b), // sceKernelSetSysClockAlarm(0x205c), // sceKernelCancelAlarm(0x205d), // sceKernelReferAlarmStatus(0x205e), // sceKernelCreateVTimer(0x205f), // sceKernelDeleteVTimer(0x2060), // sceKernelGetVTimerBase(0x2061), // sceKernelGetVTimerBaseWide(0x2062), // sceKernelGetVTimerTime(0x2063), // sceKernelGetVTimerTimeWide(0x2064), // sceKernelSetVTimerTime(0x2065), // sceKernelSetVTimerTimeWide(0x2066), // sceKernelStartVTimer(0x2067), // sceKernelStopVTimer(0x2068), // sceKernelSetVTimerHandler(0x2069), // sceKernelSetVTimerHandlerWide(0x206a), // sceKernelCancelVTimerHandler(0x206b), // sceKernelReferVTimerStatus(0x206c), case 0x206d: ThreadMan.getInstance().ThreadMan_sceKernelCreateThread(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; case 0x206e: ThreadMan.getInstance().ThreadMan_sceKernelDeleteThread(gpr[4]); break; case 0x206f: ThreadMan.getInstance().ThreadMan_sceKernelStartThread(gpr[4], gpr[5], gpr[6]); break; case 0x2070: case 0x2071: ThreadMan.getInstance().ThreadMan_sceKernelExitThread(gpr[4]); break; case 0x2072: ThreadMan.getInstance().ThreadMan_sceKernelExitDeleteThread(gpr[4]); break; case 0x2073: ThreadMan.getInstance().ThreadMan_sceKernelTerminateThread(gpr[4]); break; case 0x2074: ThreadMan.getInstance().ThreadMan_sceKernelTerminateDeleteThread(gpr[4]); break; // sceKernelSuspendDispatchThread(0x2075), //sceKernelResumeDispatchThread(0x2076), case 0x2077: ThreadMan.getInstance().ThreadMan_sceKernelChangeCurrentThreadAttr(gpr[4], gpr[5]); break; case 0x2078: ThreadMan.getInstance().ThreadMan_sceKernelChangeThreadPriority(gpr[4], gpr[5]); break; // sceKernelRotateThreadReadyQueue(0x2079), // sceKernelReleaseWaitThread(0x207a), case 0x207b: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadId(); break; case 0x207c: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadCurrentPriority(); break; case 0x207d: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadExitStatus(gpr[4]); break; case 0x207e: ThreadMan.getInstance().ThreadMan_sceKernelCheckThreadStack(); break; case 0x207f: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadStackFreeSize(gpr[4]); break; case 0x2080: ThreadMan.getInstance().ThreadMan_sceKernelReferThreadStatus(gpr[4], gpr[5]); break; // sceKernelReferThreadRunStatus(0x2081), // sceKernelReferSystemStatus(0x2082), case 0x2083: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadmanIdList(gpr[4], gpr[5], gpr[6], gpr[7]); break; // sceKernelGetThreadmanIdType(0x2084), // sceKernelReferThreadProfiler(0x2085), // sceKernelReferGlobalProfiler(0x2086), case 0x2087: pspiofilemgr.getInstance().sceIoPollAsync(gpr[4], gpr[5]); break; case 0x2088: pspiofilemgr.getInstance().sceIoWaitAsync(gpr[4], gpr[5]); break; case 0x2089: pspiofilemgr.getInstance().sceIoWaitAsyncCB(gpr[4], gpr[5]); break; case 0x208a: pspiofilemgr.getInstance().sceIoGetAsyncStat(gpr[4], gpr[5], gpr[6]); break; // sceIoChangeAsyncPriority(0x208b), // sceIoSetAsyncCallback(0x208c), case 0x208d: pspiofilemgr.getInstance().sceIoClose(gpr[4]); break; case 0x208e: pspiofilemgr.getInstance().sceIoCloseAsync(gpr[4]); break; case 0x208f: pspiofilemgr.getInstance().sceIoOpen(gpr[4], gpr[5], gpr[6]); break; case 0x2090: pspiofilemgr.getInstance().sceIoOpenAsync(gpr[4], gpr[5], gpr[6]); break; case 0x2091: pspiofilemgr.getInstance().sceIoRead(gpr[4], gpr[5], gpr[6]); break; case 0x2092: pspiofilemgr.getInstance().sceIoReadAsync(gpr[4], gpr[5], gpr[6]); break; case 0x2093: pspiofilemgr.getInstance().sceIoWrite(gpr[4], gpr[5], gpr[6]); break; case 0x2094: pspiofilemgr.getInstance().sceIoWriteAsync(gpr[4], gpr[5], gpr[6]); break; case 0x2095: pspiofilemgr.getInstance().sceIoLseek( gpr[4], ((((long)gpr[6]) & 0xFFFFFFFFL) | (((long)gpr[7])<<32)), gpr[8]); break; case 0x2096: pspiofilemgr.getInstance().sceIoLseekAsync( gpr[4], ((((long)gpr[6]) & 0xFFFFFFFFL) | (((long)gpr[7])<<32)), gpr[8]); break; case 0x2097: pspiofilemgr.getInstance().sceIoLseek32( gpr[4], gpr[5], gpr[6]); break; case 0x2098: pspiofilemgr.getInstance().sceIoLseek32Async( gpr[4], gpr[5], gpr[6]); break; // sceIoIoctl(0x2099), // sceIoIoctlAsync(0x209a), case 0x209b: pspiofilemgr.getInstance().sceIoDopen(gpr[4]); break; case 0x209c: pspiofilemgr.getInstance().sceIoDread(gpr[4], gpr[5]); break; case 0x209d: pspiofilemgr.getInstance().sceIoDclose(gpr[4]); break; // sceIoRemove(0x209e), case 0x209f: pspiofilemgr.getInstance().sceIoMkdir(gpr[4], gpr[5]); break; // sceIoRmdir(0x20a0), case 0x20a1: pspiofilemgr.getInstance().sceIoChdir(gpr[4]); break; case 0x20a2: pspiofilemgr.getInstance().sceIoSync(gpr[4], gpr[5]); break; case 0x20a3: pspiofilemgr.getInstance().sceIoGetstat(gpr[4], gpr[5]); break; // sceIoChstat(0x20a4), // sceIoRename(0x20a5), case 0x20a6: pspiofilemgr.getInstance().sceIoDevctl(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; // sceIoGetDevType(0x20a7), case 0x20a8: pspiofilemgr.getInstance().sceIoAssign(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; // sceIoUnassign(0x20a9), // sceIoCancel(0x20aa), // IoFileMgrForUser_5C2BE2CC(0x20ab), // sceKernelStdioRead(0x20ac), // sceKernelStdioLseek(0x20ad), // sceKernelStdioSendChar(0x20ae), // sceKernelStdioWrite(0x20af), // sceKernelStdioClose(0x20b0), //sceKernelStdioOpen(0x20b1), case 0x20b5: psputils.getInstance().sceKernelDcacheInvalidateRange(gpr[4], gpr[5]); break; // sceKernelIcacheInvalidateRange(0x20b6), // sceKernelUtilsMd5Digest(0x20b7), // sceKernelUtilsMd5BlockInit(0x20b8), // sceKernelUtilsMd5BlockUpdate(0x20b9), // sceKernelUtilsMd5BlockResult(0x20ba), // sceKernelUtilsSha1Digest(0x20bb), // sceKernelUtilsSha1BlockInit(0x20bc), // sceKernelUtilsSha1BlockUpdate(0x20bd), // sceKernelUtilsSha1BlockResult(0x20be), case 0x20bf: psputils.getInstance().sceKernelUtilsMt19937Init(gpr[4], gpr[5]); break; case 0x20c0: psputils.getInstance().sceKernelUtilsMt19937UInt(gpr[4]); break; case 0x20c1: psputils.getInstance().sceKernelGetGPI(); break; case 0x20c2: psputils.getInstance().sceKernelSetGPO(gpr[4]); break; case 0x20c3: psputils.getInstance().sceKernelLibcClock(); break; case 0x20c4: psputils.getInstance().sceKernelLibcTime(gpr[4]); break; case 0x20c5: psputils.getInstance().sceKernelLibcGettimeofday(gpr[4], gpr[5]); break; case 0x20c6: psputils.getInstance().sceKernelDcacheWritebackAll(); break; case 0x20c7: psputils.getInstance().sceKernelDcacheWritebackInvalidateAll(); break; case 0x20c8: psputils.getInstance().sceKernelDcacheWritebackRange(gpr[4], gpr[5]); break; case 0x20c9: psputils.getInstance().sceKernelDcacheWritebackInvalidateRange(gpr[4], gpr[5]); break; // sceKernelDcacheProbe(0x20ca), // sceKernelDcacheReadTag(0x20cb), // sceKernelIcacheInvalidateAll(0x20cc), // sceKernelIcacheProbe(0x20cd), // sceKernelIcacheReadTag(0x20ce), // sceKernelLoadModule(0x20cf), // sceKernelLoadModuleByID(0x20d0), // sceKernelLoadModuleMs(0x20d1), // sceKernelLoadModuleBufferUsbWlan(0x20d2), // sceKernelStartModule(0x20d3), // sceKernelStopModule(0x20d4), // sceKernelUnloadModule(0x20d5), // sceKernelSelfStopUnloadModule(0x20d6), // sceKernelStopUnloadSelfModule(0x20d7), // sceKernelGetModuleIdList(0x20d8), // sceKernelQueryModuleInfo(0x20d9), // ModuleMgrForUser_F0A26395(0x20da), // ModuleMgrForUser_D8B73127(0x20db), case 0x20dc: pspSysMem.getInstance().sceKernelMaxFreeMemSize(); break; case 0x20dd: pspSysMem.getInstance().sceKernelTotalFreeMemSize(); break; case 0x20de: pspSysMem.getInstance().sceKernelAllocPartitionMemory(gpr[4], gpr[5], gpr[6], gpr[7],gpr[8]); break; case 0x20df: pspSysMem.getInstance().sceKernelFreePartitionMemory(gpr[4]); break; case 0x20e0: pspSysMem.getInstance().sceKernelGetBlockHeadAddr(gpr[4]); break; // SysMemUserForUser_13A5ABEF(0x20e1), case 0x20e2: pspSysMem.getInstance().sceKernelDevkitVersion(); break; // sceKernelPowerLock(0x20e3), // sceKernelPowerUnlock(0x20e4), // sceKernelPowerTick(0x20e5), // sceSuspendForUser_3E0271D3(0x20e6), // sceSuspendForUser_A14F40B2(0x20e7), // sceSuspendForUser_A569E425(0x20e8), case 0x20e9: LoadExec.getInstance().sceKernelLoadExec(gpr[4], gpr[5]); break; // sceKernelExitGameWithStatus(0x20ea), case 0x20eb: LoadExec.getInstance().sceKernelExitGame(); break; case 0x20ec: LoadExec.getInstance().sceKernelRegisterExitCallback(gpr[4]); break; // sceDmacMemcpy(0x20ed), // sceDmacTryMemcpy(0x20ee), case 0x20ef: pspge.getInstance().sceGeEdramGetSize(); break; case 0x20f0: pspge.getInstance().sceGeEdramGetAddr(); break; //sceGeEdramSetAddrTranslation(0x20f1), // sceGeGetCmd(0x20f2), // sceGeGetMtx(0x20f3), // sceGeSaveContext(0x20f4), // sceGeRestoreContext(0x20f5), case 0x20f6: pspge.getInstance().sceGeListEnQueue(gpr[4], gpr[5], gpr[6], gpr[7]); break; // sceGeListEnQueueHead(0x20f7), case 0x20f8: pspge.getInstance().sceGeListDeQueue(gpr[4]); break; case 0x20f9: pspge.getInstance().sceGeListUpdateStallAddr(gpr[4], gpr[5]); break; /* ge sync case 0x20fa: pspge.getInstance().sceGeListSync(gpr[4], gpr[5]); break; */ case 0x20fb: pspge.getInstance().sceGeDrawSync(gpr[4]); break; // sceGeBreak(0x20fc), // sceGeContinue(0x20fd), /* ge callback case 0x20fe: pspge.getInstance().sceGeSetCallback(gpr[4]); break; case 0x20ff: pspge.getInstance().sceGeUnsetCallback(gpr[4]); break; */ /* case 0x2100: psprtc.getInstance().sceRtcGetTickResolution(); break; case 0x2101: psprtc.getInstance().sceRtcGetCurrentTick(gpr[4]); break; // sceRtc_011F03C1(0x2102), // sceRtc_029CA3B3(0x2103), // sceRtcGetCurrentClock(0x2104), case 0x2105: psprtc.getInstance().sceRtcGetCurrentClockLocalTime(gpr[4]); break;*/ // sceRtcConvertUtcToLocalTime(0x2106), // sceRtcConvertLocalTimeToUTC(0x2107), // sceRtcIsLeapYear(0x2108), // sceRtcGetDaysInMonth(0x2109), // sceRtcGetDayOfWeek(0x210a), // sceRtcCheckValid(0x210b), // sceRtcSetTime_t(0x210c), // sceRtcGetTime_t(0x210d), // sceRtcSetDosTime(0x210e), // sceRtcGetDosTime(0x210f), // sceRtcSetWin32FileTime(0x2110), // sceRtcGetWin32FileTime(0x2111), // sceRtcSetTick(0x2112), // sceRtcGetTick(0x2113), // sceRtcCompareTick(0x2114), // sceRtcTickAddTicks(0x2115), // sceRtcTickAddMicroseconds(0x2116), // sceRtcTickAddSeconds(0x2117), // sceRtcTickAddMinutes(0x2118), // sceRtcTickAddHours(0x2119), // sceRtcTickAddDays(0x211a), // sceRtcTickAddWeeks(0x211b), // sceRtcTickAddMonths(0x211c), // sceRtcTickAddYears(0x211d), // sceRtcFormatRFC2822(0x211e), // sceRtcFormatRFC2822LocalTime(0x211f), // sceRtcFormatRFC3339(0x2120), // sceRtcFormatRFC3339LocalTime(0x2121), // sceRtcParseDateTime(0x2122), // sceRtcParseRFC3339(0x2123), /* case 0x2124: pspAudio.getInstance().sceAudioOutput(gpr[4], gpr[5], gpr[6]); break; case 0x2125: pspAudio.getInstance().sceAudioOutputBlocking(gpr[4], gpr[5], gpr[6]); break; case 0x2126: pspAudio.getInstance().sceAudioOutputPanned(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2127: pspAudio.getInstance().sceAudioOutputPannedBlocking(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2128: pspAudio.getInstance().sceAudioChReserve(gpr[4], gpr[5], gpr[6]); break; //case 0x2129: pspAudio.getInstance().sceAudioOneshotOutput(); break; case 0x212a: pspAudio.getInstance().sceAudioChRelease(gpr[4]); break; case 0x212b: pspAudio.getInstance().sceAudioGetChannelRestLength(gpr[4]); break; case 0x212c: pspAudio.getInstance().sceAudioSetChannelDataLen(gpr[4], gpr[5]); break; //case 0x212d: pspAudio.getInstance().sceAudioChangeChannelConfig(gpr[4], gpr[5]); break; case 0x212e: pspAudio.getInstance().sceAudioChangeChannelVolume(gpr[4], gpr[5], gpr[6]); break; //case 0x212f: pspAudio.getInstance().sceAudio_38553111(); break; //case 0x2130: pspAudio.getInstance().sceAudio_5C37C0AE(); break; //case 0x2131: pspAudio.getInstance().sceAudio_E0727056(); break; //case 0x2132: pspAudio.getInstance().sceAudioInputBlocking(gpr[4], gpr[5], gpr[6]); break; //case 0x2133: pspAudio.getInstance().sceAudioInput(gpr[4], gpr[5], gpr[6]); break; //case 0x2134: pspAudio.getInstance().sceAudioGetInputLength(); break; //case 0x2135: pspAudio.getInstance().sceAudioWaitInputEnd(); break; //case 0x2136: pspAudio.getInstance().sceAudioInputInit(gpr[4], gpr[5], gpr[6]); break; //case 0x2137: pspAudio.getInstance().sceAudio_E926D3FB(); break; //case 0x2138: pspAudio.getInstance().sceAudio_A633048E(); break; case 0x2139: pspAudio.getInstance().sceAudioGetChannelRestLen(gpr[4]); break; */ case 0x213a: pspdisplay.getInstance().sceDisplaySetMode(gpr[4], gpr[5], gpr[6]); break; // sceDisplayGetMode(0x213b), // sceDisplayGetFramePerSec(0x213c), // sceDisplaySetHoldMode(0x213d), // sceDisplaySetResumeMode(0x213e), case 0x213f: pspdisplay.getInstance().sceDisplaySetFrameBuf(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2140: pspdisplay.getInstance().sceDisplayGetFrameBuf(gpr[4], gpr[5], gpr[6], gpr[7]); break; // sceDisplayIsForeground(0x2141), // sceDisplayGetBrightness(0x2142), // sceDisplayGetVcount(0x2143), case 0x2143: pspdisplay.getInstance().sceDisplayGetVcount(); break; // sceDisplayIsVblank(0x2144), case 0x2145: pspdisplay.getInstance().sceDisplayWaitVblank(); break; case 0x2146: pspdisplay.getInstance().sceDisplayWaitVblankCB(); break; case 0x2147: pspdisplay.getInstance().sceDisplayWaitVblankStart(); break; case 0x2148: pspdisplay.getInstance().sceDisplayWaitVblankStartCB(); break; case 0x2149: pspdisplay.getInstance().sceDisplayGetCurrentHcount(); break; case 0x214a: pspdisplay.getInstance().sceDisplayGetAccumulatedHcount(); break; // sceDisplay_A83EF139(0x214b), /* case 0x214c: pspctrl.getInstance().sceCtrlSetSamplingCycle(gpr[4]); break; case 0x214d: pspctrl.getInstance().sceCtrlGetSamplingCycle(gpr[4]); break; case 0x214e: pspctrl.getInstance().sceCtrlSetSamplingMode(gpr[4]); break; case 0x214f: pspctrl.getInstance().sceCtrlGetSamplingMode(gpr[4]); break; case 0x2150: pspctrl.getInstance().sceCtrlPeekBufferPositive(gpr[4], gpr[5]); break; case 0x2151: pspctrl.getInstance().sceCtrlPeekBufferNegative(gpr[4], gpr[5]); break; case 0x2152: pspctrl.getInstance().sceCtrlReadBufferPositive(gpr[4], gpr[5]); break; case 0x2153: pspctrl.getInstance().sceCtrlReadBufferNegative(gpr[4], gpr[5]); break; case 0x2154: pspctrl.getInstance().sceCtrlPeekLatch(gpr[4]); break; case 0x2155: pspctrl.getInstance().sceCtrlReadLatch(gpr[4]); break;*/ // sceCtrl_A7144800(0x2156), // sceCtrl_687660FA(0x2157), // sceCtrl_348D99D4(0x2158), // sceCtrl_AF5960F3(0x2159), // sceCtrl_A68FD260(0x215a), // sceCtrl_6841BE1A(0x215b), // sceHprmRegisterCallback(0x215c), // sceHprmUnregisterCallback(0x215d), // sceHprm_71B5FB67(0x215e), // sceHprmIsRemoteExist(0x215f), // sceHprmIsHeadphoneExist(0x2160), // sceHprmIsMicrophoneExist(0x2161), // sceHprmPeekCurrentKey(0x2162), // sceHprmPeekLatch(0x2163), // sceHprmReadLatch(0x2164), // scePower_2B51FE2F(0x2165), // scePower_442BFBAC(0x2166), /// scePowerTick(0x2167), // scePowerGetIdleTimer(0x2168), // scePowerIdleTimerEnable(0x2169), // scePowerIdleTimerDisable(0x216a), // scePowerBatteryUpdateInfo(0x216b), // scePower_E8E4E204(0x216c), // scePowerGetLowBatteryCapacity(0x216d), // scePowerIsPowerOnline(0x216e), // scePowerIsBatteryExist(0x216f), // scePowerIsBatteryCharging(0x2170), // scePowerGetBatteryChargingStatus(0x2171), // scePowerIsLowBattery(0x2172), // scePower_78A1A796(0x2173), // scePowerGetBatteryRemainCapacity(0x2174), // scePower_FD18A0FF(0x2175), //// scePowerGetBatteryLifePercent(0x2176), // scePowerGetBatteryLifeTime(0x2177), //// scePowerGetBatteryTemp(0x2178), // scePowerGetBatteryElec(0x2179), // scePowerGetBatteryVolt(0x217a), // scePower_23436A4A(0x217b), // scePower_0CD21B1F(0x217c), // scePower_165CE085(0x217d), // scePower_23C31FFE(0x217e), // scePower_FA97A599(0x217f), // scePower_B3EDD801(0x2180), // scePowerLock(0x2181), // scePowerUnlock(0x2182), // scePowerCancelRequest(0x2183), // scePowerIsRequest(0x2184), // scePowerRequestStandby(0x2185), // scePowerRequestSuspend(0x2186), // scePower_2875994B(0x2187), // scePowerEncodeUBattery(0x2188), // scePowerGetResumeCount(0x2189), // scePowerRegisterCallback(0x218a), // scePowerUnregisterCallback(0x218b), // scePowerUnregitserCallback(0x218c), // scePowerSetCpuClockFrequency(0x218d), /// scePowerSetBusClockFrequency(0x218e), // scePowerGetCpuClockFrequency(0x218f), // scePowerGetBusClockFrequency(0x2190), // scePowerGetCpuClockFrequencyInt(0x2191), // scePowerGetBusClockFrequencyInt(0x2192), // scePower_34F9C463(0x2193), // scePowerGetCpuClockFrequencyFloat(0x2194), // scePowerGetBusClockFrequencyFloat(0x2195), // scePower_EA382A27(0x2196), // scePowerSetClockFrequency(0x2197), // sceUsbStart(0x2198), // sceUsbStop(0x2199), // sceUsbGetState(0x219a), // sceUsbGetDrvList(0x219b), // sceUsbGetDrvState(0x219c), // sceUsbActivate(0x219d), // sceUsbDeactivate(0x219e), // sceUsbWaitState(0x219f), // sceUsbWaitCancel(0x21a0), // sceOpenPSIDGetOpenPSID(0x21a1), // sceSircsSend(0x21a2), // sceUmdCheckMedium(0x21a3), // sceUmdActivate(0x21a4), // sceUmdDeactivate(0x21a5), // sceUmdWaitDriveStat(0x21a6), // sceUmdWaitDriveStatWithTimer(0x21a7), // sceUmdWaitDriveStatCB(0x21a8), // sceUmdCancelWaitDriveStat(0x21a9), // sceUmdGetDriveStat(0x21aa), // sceUmdGetErrorStat(0x21ab), // sceUmdGetDiscInfo(0x21ac), // sceUmdRegisterUMDCallBack(0x21ad), // sceUmdUnRegisterUMDCallBack(0x21ae), // sceWlanDevIsPowerOn(0x21af), // sceWlanGetSwitchState(0x21b0), // sceWlanGetEtherAddr(0x21b1), // sceWlanDevAttach(0x21b2), // sceWlanDevDetach(0x21b3), // sceWlanDrv_lib_19E51F54(0x21b4), // sceWlanDevIsGameMode(0x21b5), // sceWlanGPPrevEstablishActive(0x21b6), // sceWlanGPSend(0x21b7), // sceWlanGPRecv(0x21b8), // sceWlanGPRegisterCallback(0x21b9), // sceWlanGPUnRegisterCallback(0x21ba), // sceWlanDrv_lib_81579D36(0x21bb), // sceWlanDrv_lib_5BAA1FE5(0x21bc), // sceWlanDrv_lib_4C14BACA(0x21bd), // sceWlanDrv_lib_2D0FAE4E(0x21be), // sceWlanDrv_lib_56F467CA(0x21bf), // sceWlanDrv_lib_FE8A0B46(0x21c0), // sceWlanDrv_lib_40B0AA4A(0x21c1), // sceWlanDevSetGPIO(0x21c2), // sceWlanDevGetStateGPIO(0x21c3), // sceWlanDrv_lib_8D5F551B(0x21c4), // sceVaudioOutputBlocking(0x21c5), // sceVaudioChReserve(0x21c6), // sceVaudioChRelease(0x21c7), // sceVaudio_346FBE94(0x21c8), // sceRegExit(0x21c9), // sceRegOpenRegistry(0x21ca), // sceRegCloseRegistry(0x21cb), // sceRegRemoveRegistry(0x21cc), // sceReg_1D8A762E(0x21cd), // sceReg_0CAE832B(0x21ce), // sceRegFlushRegistry(0x21cf), // sceReg_0D69BF40(0x21d0), // sceRegCreateKey(0x21d1), // sceRegSetKeyValue(0x21d2), // sceRegGetKeyInfo(0x21d3), // sceRegGetKeyValue(0x21d4), // sceRegGetKeysNum(0x21d5), // sceRegGetKeys(0x21d6), // sceReg_4CA16893(0x21d7), // sceRegRemoveKey(0x21d8), // sceRegKickBackDiscover(0x21d9), // sceRegGetKeyValueByName(0x21da), // sceUtilityGameSharingInitStart(0x21db), // sceUtilityGameSharingShutdownStart(0x21dc), // sceUtilityGameSharingUpdate(0x21dd), // sceUtilityGameSharingGetStatus(0x21de), // sceNetplayDialogInitStart(0x21df), // sceNetplayDialogShutdownStart(0x21e0), // sceNetplayDialogUpdate(0x21e1), // sceNetplayDialogGetStatus(0x21e2), // sceUtilityNetconfInitStart(0x21e3), // sceUtilityNetconfShutdownStart(0x21e4), // sceUtilityNetconfUpdate(0x21e5), // sceUtilityNetconfGetStatus(0x21e6), // sceUtilitySavedataInitStart(0x21e7), // sceUtilitySavedataShutdownStart(0x21e8), // sceUtilitySavedataUpdate(0x21e9), // sceUtilitySavedataGetStatus(0x21ea), // sceUtility_2995D020(0x21eb), // sceUtility_B62A4061(0x21ec), // sceUtility_ED0FAD38(0x21ed), // sceUtility_88BC7406(0x21ee), // sceUtilityMsgDialogInitStart(0x21ef), // sceUtilityMsgDialogShutdownStart(0x21f0), // sceUtilityMsgDialogUpdate(0x21f1), // sceUtilityMsgDialogGetStatus(0x21f2), // sceUtilityOskInitStart(0x21f3), // sceUtilityOskShutdownStart(0x21f4), // sceUtilityOskUpdate(0x21f5), // sceUtilityOskGetStatus(0x21f6), // sceUtilitySetSystemParamInt(0x21f7), // sceUtilitySetSystemParamString(0x21f8), // sceUtilityGetSystemParamInt(0x21f9), // sceUtilityGetSystemParamString(0x21fa), // sceUtilityCheckNetParam(0x21fb), // sceUtilityGetNetParam(0x21fc), // sceUtility_private_17CB4D96(0x21fd), // sceUtility_private_EE7AC503(0x21fe), // sceUtility_private_5FF96ED3(0x21ff), // sceUtility_private_9C9DD5BC(0x2200), // sceUtility_private_4405BA38(0x2201), // sceUtility_private_1DFA62EF(0x2202), // sceUtilityDialogSetStatus(0x2203), // sceUtilityDialogGetType(0x2204), // sceUtilityDialogGetParam(0x2205), // sceUtility_private_EF5BC2D1(0x2206), // sceUtilityDialogGetSpeed(0x2207), // sceUtility_private_19461966(0x2208), // sceUtilityDialogSetThreadId(0x2209), // sceUtilityDialogLoadModule(0x220a), // sceUtilityDialogPowerLock(0x220b), // sceUtilityDialogPowerUnlock(0x220c), // sceUtilityCreateNetParam(0x220d), //sceUtilityDeleteNetParam(0x220e), //sceUtilityCopyNetParam(0x220f), // sceUtilitySetNetParam(0x2210); case 0xfffff: // special code for unmapped imports Modules.log.error(String.format("Unmapped import @ 0x%08X", Emulator.getProcessor().cpu.pc)); Emulator.PauseEmu(); break; default: { // Try and handle as an HLE module export boolean handled = HLEModuleManager.getInstance().handleSyscall(code); if (!handled) { CpuState cpu = Emulator.getProcessor().cpu; // At least set a decent return value cpu.gpr[2] = 0; //Emulator.getProcessor().gpr[2] = 0xb515ca11; // Display debug info String params = String.format("%08x %08x %08x", cpu.gpr[4], cpu.gpr[5], cpu.gpr[6]); for (jpcsp.Debugger.DisassemblerModule.syscallsFirm15.calls c : jpcsp.Debugger.DisassemblerModule.syscallsFirm15.calls.values()) { if (c.getSyscall() == code) { Modules.log.warn("Unsupported syscall " + Integer.toHexString(code) + " " + c + " " + params); return; } } Modules.log.warn("Unsupported syscall " + Integer.toHexString(code) + " " + params); } } break; } } catch(GeneralJpcspException e) { System.out.println(e.getMessage()); } }
public static void syscall(int code) { int gpr[] = Emulator.getProcessor().cpu.gpr; ThreadMan.getInstance().clearSyscallFreeCycles(); // Some syscalls implementation throw GeneralJpcspException, // and Processor isn't setup to catch exceptions so we'll do it // here for now, or we could just stop throwing exceptions. // Also we need to decide whether to pass arguments to the functions, // or let them read the registers they want themselves. try { // Currently using FW1.50 codes switch(code) { // case 0x2000: //sceKernelRegisterSubIntrHandler // case 0x2001: // sceKernelReleaseSubIntrHandler // case 0x2002: //sceKernelEnableSubIntr // case 0x2003: //sceKernelDisableSubIntr // case 0x2004: //sceKernelSuspendSubIntr // case 0x2005: //sceKernelResumeSubIntr // case 0x2006: //sceKernelIsSubInterruptOccurred // case 0x2007: //QueryIntrHandlerInfo // case 0x2008: //sceKernelRegisterUserSpaceIntrStack // case 0x2009: //_sceKernelReturnFromCallback // case 0x200a: //sceKernelRegisterThreadEventHandler // case 0x200b: //sceKernelReleaseThreadEventHandler // case 0x200c: //sceKernelReferThreadEventHandlerStatus case 0x200d: ThreadMan.getInstance().ThreadMan_sceKernelCreateCallback(gpr[4], gpr[5], gpr[6]); break; // case 0x200e: //sceKernelDeleteCallback // case 0x200f: //sceKernelNotifyCallback // case 0x2010: //sceKernelCancelCallback // case 0x2011: //sceKernelGetCallbackCount case 0x2012: ThreadMan.getInstance().ThreadMan_sceKernelCheckCallback(); break; case 0x2013: ThreadMan.getInstance().ThreadMan_sceKernelReferCallbackStatus(gpr[4], gpr[5]); break; case 0x2014: ThreadMan.getInstance().ThreadMan_sceKernelSleepThread(); break; case 0x2015: ThreadMan.getInstance().ThreadMan_sceKernelSleepThreadCB(); break; case 0x2016: ThreadMan.getInstance().ThreadMan_sceKernelWakeupThread(gpr[4]); break; //case 0x2017: ///sceKernelCancelWakeupThread //case 0x2018: //sceKernelSuspendThread //case 0x2019: //sceKernelResumeThread case 0x201a: ThreadMan.getInstance().ThreadMan_sceKernelWaitThreadEnd(gpr[4], gpr[5]); break; // case 0x201b: // ThreadMan.getInstance().ThreadMan_sceKernelWaitThreadEndCB(gpr[4], gpr[5]); // break; case 0x201c: ThreadMan.getInstance().ThreadMan_sceKernelDelayThread(gpr[4]); break; case 0x201d: ThreadMan.getInstance().ThreadMan_sceKernelDelayThreadCB(gpr[4]); break; //sceKernelDelaySysClockThread(0x201e), // sceKernelDelaySysClockThreadCB(0x201f), case 0x2020: ThreadMan.getInstance().ThreadMan_sceKernelCreateSema(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x2021: ThreadMan.getInstance().ThreadMan_sceKernelDeleteSema(gpr[4]); break; case 0x2022: ThreadMan.getInstance().ThreadMan_sceKernelSignalSema(gpr[4], gpr[5]); break; case 0x2023: ThreadMan.getInstance().ThreadMan_sceKernelWaitSema(gpr[4], gpr[5], gpr[6]); break; case 0x2024: ThreadMan.getInstance().ThreadMan_sceKernelWaitSemaCB(gpr[4], gpr[5], gpr[6]); break; case 0x2025: ThreadMan.getInstance().ThreadMan_sceKernelPollSema(gpr[4], gpr[5]); break; case 0x2026: ThreadMan.getInstance().ThreadMan_sceKernelCancelSema(gpr[4]); // not in pspsdk, params guessed break; case 0x2027: ThreadMan.getInstance().ThreadMan_sceKernelReferSemaStatus(gpr[4], gpr[5]); break; case 0x2028: Managers.eventFlags.sceKernelCreateEventFlag(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2029: Managers.eventFlags.sceKernelDeleteEventFlag(gpr[4]); break; case 0x202a: Managers.eventFlags.sceKernelSetEventFlag(gpr[4], gpr[5]); break; case 0x202b: Managers.eventFlags.sceKernelClearEventFlag(gpr[4], gpr[5]); break; case 0x202c: Managers.eventFlags.sceKernelWaitEventFlag(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x202d: Managers.eventFlags.sceKernelWaitEventFlagCB(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x202e: Managers.eventFlags.sceKernelPollEventFlag(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x202f: Managers.eventFlags.sceKernelCancelEventFlag(gpr[4], gpr[5], gpr[6]); // not in pspsdk, params guessed break; case 0x2030: Managers.eventFlags.sceKernelReferEventFlagStatus(gpr[4], gpr[5]); break; // sceKernelCreateMbx(0x2031), // sceKernelDeleteMbx(0x2032), // sceKernelSendMbx(0x2033), // sceKernelReceiveMbx(0x2034), // sceKernelReceiveMbxCB(0x2035), // sceKernelPollMbx(0x2036), // sceKernelCancelReceiveMbx(0x2037), // sceKernelReferMbxStatus(0x2038), // sceKernelCreateMsgPipe(0x2039), // sceKernelDeleteMsgPipe(0x203a), // sceKernelSendMsgPipe(0x203b), // sceKernelSendMsgPipeCB(0x203c), // sceKernelTrySendMsgPipe(0x203d), // sceKernelReceiveMsgPipe(0x203e), // sceKernelReceiveMsgPipeCB(0x203f), // sceKernelTryReceiveMsgPipe(0x2040), // sceKernelCancelMsgPipe(0x2041), // sceKernelReferMsgPipeStatus(0x2042), case 0x2043: Managers.vpl.sceKernelCreateVpl(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8]); break; case 0x2044: Managers.vpl.sceKernelDeleteVpl(gpr[4]); break; case 0x2045: Managers.vpl.sceKernelAllocateVpl(gpr[4], gpr[5], gpr[6], gpr[8]); break; case 0x2046: Managers.vpl.sceKernelAllocateVplCB(gpr[4], gpr[5], gpr[6], gpr[8]); break; case 0x2047: Managers.vpl.sceKernelTryAllocateVpl(gpr[4], gpr[5], gpr[8]); break; case 0x2048: Managers.vpl.sceKernelFreeVpl(gpr[4], gpr[5]); break; case 0x2049: Managers.vpl.sceKernelCancelVpl(gpr[4], gpr[5]); break; case 0x204a: Managers.vpl.sceKernelReferVplStatus(gpr[4], gpr[5]); break; case 0x204b: Managers.fpl.sceKernelCreateFpl(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; case 0x204c: Managers.fpl.sceKernelDeleteFpl(gpr[4]); break; case 0x204d: Managers.fpl.sceKernelAllocateFpl(gpr[4], gpr[5], gpr[6]); break; case 0x204e: Managers.fpl.sceKernelAllocateFplCB(gpr[4], gpr[5], gpr[6]); break; case 0x204f: Managers.fpl.sceKernelTryAllocateFpl(gpr[4], gpr[5]); break; case 0x2050: Managers.fpl.sceKernelFreeFpl(gpr[4], gpr[5]); break; case 0x2051: Managers.fpl.sceKernelCancelFpl(gpr[4], gpr[5]); break; case 0x2052: Managers.fpl.sceKernelReferFplStatus(gpr[4], gpr[5]); break; // ThreadManForUser_0E927AED(0x2053), case 0x2054: Managers.systime.sceKernelUSec2SysClock(gpr[4], gpr[5]); break; // sceKernelUSec2SysClockWide(0x2055), case 0x2056: Managers.systime.sceKernelSysClock2USec(gpr[4], gpr[5], gpr[6]); break; // sceKernelSysClock2USecWide(0x2057), case 0x2058: Managers.systime.sceKernelGetSystemTime(gpr[4]); break; case 0x2059: Managers.systime.sceKernelGetSystemTimeWide(); break; case 0x205a: Managers.systime.sceKernelGetSystemTimeLow(); break; // sceKernelSetAlarm(0x205b), // sceKernelSetSysClockAlarm(0x205c), // sceKernelCancelAlarm(0x205d), // sceKernelReferAlarmStatus(0x205e), // sceKernelCreateVTimer(0x205f), // sceKernelDeleteVTimer(0x2060), // sceKernelGetVTimerBase(0x2061), // sceKernelGetVTimerBaseWide(0x2062), // sceKernelGetVTimerTime(0x2063), // sceKernelGetVTimerTimeWide(0x2064), // sceKernelSetVTimerTime(0x2065), // sceKernelSetVTimerTimeWide(0x2066), // sceKernelStartVTimer(0x2067), // sceKernelStopVTimer(0x2068), // sceKernelSetVTimerHandler(0x2069), // sceKernelSetVTimerHandlerWide(0x206a), // sceKernelCancelVTimerHandler(0x206b), // sceKernelReferVTimerStatus(0x206c), case 0x206d: ThreadMan.getInstance().ThreadMan_sceKernelCreateThread(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; case 0x206e: ThreadMan.getInstance().ThreadMan_sceKernelDeleteThread(gpr[4]); break; case 0x206f: ThreadMan.getInstance().ThreadMan_sceKernelStartThread(gpr[4], gpr[5], gpr[6]); break; case 0x2070: case 0x2071: ThreadMan.getInstance().ThreadMan_sceKernelExitThread(gpr[4]); break; case 0x2072: ThreadMan.getInstance().ThreadMan_sceKernelExitDeleteThread(gpr[4]); break; case 0x2073: ThreadMan.getInstance().ThreadMan_sceKernelTerminateThread(gpr[4]); break; case 0x2074: ThreadMan.getInstance().ThreadMan_sceKernelTerminateDeleteThread(gpr[4]); break; // sceKernelSuspendDispatchThread(0x2075), //sceKernelResumeDispatchThread(0x2076), case 0x2077: ThreadMan.getInstance().ThreadMan_sceKernelChangeCurrentThreadAttr(gpr[4], gpr[5]); break; case 0x2078: ThreadMan.getInstance().ThreadMan_sceKernelChangeThreadPriority(gpr[4], gpr[5]); break; // sceKernelRotateThreadReadyQueue(0x2079), // sceKernelReleaseWaitThread(0x207a), case 0x207b: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadId(); break; case 0x207c: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadCurrentPriority(); break; case 0x207d: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadExitStatus(gpr[4]); break; case 0x207e: ThreadMan.getInstance().ThreadMan_sceKernelCheckThreadStack(); break; case 0x207f: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadStackFreeSize(gpr[4]); break; case 0x2080: ThreadMan.getInstance().ThreadMan_sceKernelReferThreadStatus(gpr[4], gpr[5]); break; // sceKernelReferThreadRunStatus(0x2081), // sceKernelReferSystemStatus(0x2082), case 0x2083: ThreadMan.getInstance().ThreadMan_sceKernelGetThreadmanIdList(gpr[4], gpr[5], gpr[6], gpr[7]); break; // sceKernelGetThreadmanIdType(0x2084), // sceKernelReferThreadProfiler(0x2085), // sceKernelReferGlobalProfiler(0x2086), case 0x2087: pspiofilemgr.getInstance().sceIoPollAsync(gpr[4], gpr[5]); break; case 0x2088: pspiofilemgr.getInstance().sceIoWaitAsync(gpr[4], gpr[5]); break; case 0x2089: pspiofilemgr.getInstance().sceIoWaitAsyncCB(gpr[4], gpr[5]); break; case 0x208a: pspiofilemgr.getInstance().sceIoGetAsyncStat(gpr[4], gpr[5], gpr[6]); break; // sceIoChangeAsyncPriority(0x208b), // sceIoSetAsyncCallback(0x208c), case 0x208d: pspiofilemgr.getInstance().sceIoClose(gpr[4]); break; case 0x208e: pspiofilemgr.getInstance().sceIoCloseAsync(gpr[4]); break; case 0x208f: pspiofilemgr.getInstance().sceIoOpen(gpr[4], gpr[5], gpr[6]); break; case 0x2090: pspiofilemgr.getInstance().sceIoOpenAsync(gpr[4], gpr[5], gpr[6]); break; case 0x2091: pspiofilemgr.getInstance().sceIoRead(gpr[4], gpr[5], gpr[6]); break; case 0x2092: pspiofilemgr.getInstance().sceIoReadAsync(gpr[4], gpr[5], gpr[6]); break; case 0x2093: pspiofilemgr.getInstance().sceIoWrite(gpr[4], gpr[5], gpr[6]); break; case 0x2094: pspiofilemgr.getInstance().sceIoWriteAsync(gpr[4], gpr[5], gpr[6]); break; case 0x2095: pspiofilemgr.getInstance().sceIoLseek( gpr[4], ((((long)gpr[6]) & 0xFFFFFFFFL) | (((long)gpr[7])<<32)), gpr[8]); break; case 0x2096: pspiofilemgr.getInstance().sceIoLseekAsync( gpr[4], ((((long)gpr[6]) & 0xFFFFFFFFL) | (((long)gpr[7])<<32)), gpr[8]); break; case 0x2097: pspiofilemgr.getInstance().sceIoLseek32( gpr[4], gpr[5], gpr[6]); break; case 0x2098: pspiofilemgr.getInstance().sceIoLseek32Async( gpr[4], gpr[5], gpr[6]); break; // sceIoIoctl(0x2099), // sceIoIoctlAsync(0x209a), case 0x209b: pspiofilemgr.getInstance().sceIoDopen(gpr[4]); break; case 0x209c: pspiofilemgr.getInstance().sceIoDread(gpr[4], gpr[5]); break; case 0x209d: pspiofilemgr.getInstance().sceIoDclose(gpr[4]); break; // sceIoRemove(0x209e), case 0x209f: pspiofilemgr.getInstance().sceIoMkdir(gpr[4], gpr[5]); break; // sceIoRmdir(0x20a0), case 0x20a1: pspiofilemgr.getInstance().sceIoChdir(gpr[4]); break; case 0x20a2: pspiofilemgr.getInstance().sceIoSync(gpr[4], gpr[5]); break; case 0x20a3: pspiofilemgr.getInstance().sceIoGetstat(gpr[4], gpr[5]); break; // sceIoChstat(0x20a4), // sceIoRename(0x20a5), case 0x20a6: pspiofilemgr.getInstance().sceIoDevctl(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; // sceIoGetDevType(0x20a7), case 0x20a8: pspiofilemgr.getInstance().sceIoAssign(gpr[4], gpr[5], gpr[6], gpr[7], gpr[8], gpr[9]); break; // sceIoUnassign(0x20a9), // sceIoCancel(0x20aa), // IoFileMgrForUser_5C2BE2CC(0x20ab), // sceKernelStdioRead(0x20ac), // sceKernelStdioLseek(0x20ad), // sceKernelStdioSendChar(0x20ae), // sceKernelStdioWrite(0x20af), // sceKernelStdioClose(0x20b0), //sceKernelStdioOpen(0x20b1), case 0x20b5: psputils.getInstance().sceKernelDcacheInvalidateRange(gpr[4], gpr[5]); break; // sceKernelIcacheInvalidateRange(0x20b6), // sceKernelUtilsMd5Digest(0x20b7), // sceKernelUtilsMd5BlockInit(0x20b8), // sceKernelUtilsMd5BlockUpdate(0x20b9), // sceKernelUtilsMd5BlockResult(0x20ba), // sceKernelUtilsSha1Digest(0x20bb), // sceKernelUtilsSha1BlockInit(0x20bc), // sceKernelUtilsSha1BlockUpdate(0x20bd), // sceKernelUtilsSha1BlockResult(0x20be), case 0x20bf: psputils.getInstance().sceKernelUtilsMt19937Init(gpr[4], gpr[5]); break; case 0x20c0: psputils.getInstance().sceKernelUtilsMt19937UInt(gpr[4]); break; case 0x20c1: psputils.getInstance().sceKernelGetGPI(); break; case 0x20c2: psputils.getInstance().sceKernelSetGPO(gpr[4]); break; case 0x20c3: psputils.getInstance().sceKernelLibcClock(); break; case 0x20c4: psputils.getInstance().sceKernelLibcTime(gpr[4]); break; case 0x20c5: psputils.getInstance().sceKernelLibcGettimeofday(gpr[4], gpr[5]); break; case 0x20c6: psputils.getInstance().sceKernelDcacheWritebackAll(); break; case 0x20c7: psputils.getInstance().sceKernelDcacheWritebackInvalidateAll(); break; case 0x20c8: psputils.getInstance().sceKernelDcacheWritebackRange(gpr[4], gpr[5]); break; case 0x20c9: psputils.getInstance().sceKernelDcacheWritebackInvalidateRange(gpr[4], gpr[5]); break; // sceKernelDcacheProbe(0x20ca), // sceKernelDcacheReadTag(0x20cb), // sceKernelIcacheInvalidateAll(0x20cc), // sceKernelIcacheProbe(0x20cd), // sceKernelIcacheReadTag(0x20ce), // sceKernelLoadModule(0x20cf), // sceKernelLoadModuleByID(0x20d0), // sceKernelLoadModuleMs(0x20d1), // sceKernelLoadModuleBufferUsbWlan(0x20d2), // sceKernelStartModule(0x20d3), // sceKernelStopModule(0x20d4), // sceKernelUnloadModule(0x20d5), // sceKernelSelfStopUnloadModule(0x20d6), // sceKernelStopUnloadSelfModule(0x20d7), // sceKernelGetModuleIdList(0x20d8), // sceKernelQueryModuleInfo(0x20d9), // ModuleMgrForUser_F0A26395(0x20da), // ModuleMgrForUser_D8B73127(0x20db), case 0x20dc: pspSysMem.getInstance().sceKernelMaxFreeMemSize(); break; case 0x20dd: pspSysMem.getInstance().sceKernelTotalFreeMemSize(); break; case 0x20de: pspSysMem.getInstance().sceKernelAllocPartitionMemory(gpr[4], gpr[5], gpr[6], gpr[7],gpr[8]); break; case 0x20df: pspSysMem.getInstance().sceKernelFreePartitionMemory(gpr[4]); break; case 0x20e0: pspSysMem.getInstance().sceKernelGetBlockHeadAddr(gpr[4]); break; // SysMemUserForUser_13A5ABEF(0x20e1), case 0x20e2: pspSysMem.getInstance().sceKernelDevkitVersion(); break; // sceKernelPowerLock(0x20e3), // sceKernelPowerUnlock(0x20e4), // sceKernelPowerTick(0x20e5), // sceSuspendForUser_3E0271D3(0x20e6), // sceSuspendForUser_A14F40B2(0x20e7), // sceSuspendForUser_A569E425(0x20e8), case 0x20e9: LoadExec.getInstance().sceKernelLoadExec(gpr[4], gpr[5]); break; // sceKernelExitGameWithStatus(0x20ea), case 0x20eb: LoadExec.getInstance().sceKernelExitGame(); break; case 0x20ec: LoadExec.getInstance().sceKernelRegisterExitCallback(gpr[4]); break; // sceDmacMemcpy(0x20ed), // sceDmacTryMemcpy(0x20ee), case 0x20ef: pspge.getInstance().sceGeEdramGetSize(); break; case 0x20f0: pspge.getInstance().sceGeEdramGetAddr(); break; //sceGeEdramSetAddrTranslation(0x20f1), // sceGeGetCmd(0x20f2), // sceGeGetMtx(0x20f3), // sceGeSaveContext(0x20f4), // sceGeRestoreContext(0x20f5), case 0x20f6: pspge.getInstance().sceGeListEnQueue(gpr[4], gpr[5], gpr[6], gpr[7]); break; // sceGeListEnQueueHead(0x20f7), case 0x20f8: pspge.getInstance().sceGeListDeQueue(gpr[4]); break; case 0x20f9: pspge.getInstance().sceGeListUpdateStallAddr(gpr[4], gpr[5]); break; /* ge sync case 0x20fa: pspge.getInstance().sceGeListSync(gpr[4], gpr[5]); break; */ case 0x20fb: pspge.getInstance().sceGeDrawSync(gpr[4]); break; // sceGeBreak(0x20fc), // sceGeContinue(0x20fd), /* ge callback case 0x20fe: pspge.getInstance().sceGeSetCallback(gpr[4]); break; case 0x20ff: pspge.getInstance().sceGeUnsetCallback(gpr[4]); break; */ /* case 0x2100: psprtc.getInstance().sceRtcGetTickResolution(); break; case 0x2101: psprtc.getInstance().sceRtcGetCurrentTick(gpr[4]); break; // sceRtc_011F03C1(0x2102), // sceRtc_029CA3B3(0x2103), // sceRtcGetCurrentClock(0x2104), case 0x2105: psprtc.getInstance().sceRtcGetCurrentClockLocalTime(gpr[4]); break;*/ // sceRtcConvertUtcToLocalTime(0x2106), // sceRtcConvertLocalTimeToUTC(0x2107), // sceRtcIsLeapYear(0x2108), // sceRtcGetDaysInMonth(0x2109), // sceRtcGetDayOfWeek(0x210a), // sceRtcCheckValid(0x210b), // sceRtcSetTime_t(0x210c), // sceRtcGetTime_t(0x210d), // sceRtcSetDosTime(0x210e), // sceRtcGetDosTime(0x210f), // sceRtcSetWin32FileTime(0x2110), // sceRtcGetWin32FileTime(0x2111), // sceRtcSetTick(0x2112), // sceRtcGetTick(0x2113), // sceRtcCompareTick(0x2114), // sceRtcTickAddTicks(0x2115), // sceRtcTickAddMicroseconds(0x2116), // sceRtcTickAddSeconds(0x2117), // sceRtcTickAddMinutes(0x2118), // sceRtcTickAddHours(0x2119), // sceRtcTickAddDays(0x211a), // sceRtcTickAddWeeks(0x211b), // sceRtcTickAddMonths(0x211c), // sceRtcTickAddYears(0x211d), // sceRtcFormatRFC2822(0x211e), // sceRtcFormatRFC2822LocalTime(0x211f), // sceRtcFormatRFC3339(0x2120), // sceRtcFormatRFC3339LocalTime(0x2121), // sceRtcParseDateTime(0x2122), // sceRtcParseRFC3339(0x2123), /* case 0x2124: pspAudio.getInstance().sceAudioOutput(gpr[4], gpr[5], gpr[6]); break; case 0x2125: pspAudio.getInstance().sceAudioOutputBlocking(gpr[4], gpr[5], gpr[6]); break; case 0x2126: pspAudio.getInstance().sceAudioOutputPanned(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2127: pspAudio.getInstance().sceAudioOutputPannedBlocking(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2128: pspAudio.getInstance().sceAudioChReserve(gpr[4], gpr[5], gpr[6]); break; //case 0x2129: pspAudio.getInstance().sceAudioOneshotOutput(); break; case 0x212a: pspAudio.getInstance().sceAudioChRelease(gpr[4]); break; case 0x212b: pspAudio.getInstance().sceAudioGetChannelRestLength(gpr[4]); break; case 0x212c: pspAudio.getInstance().sceAudioSetChannelDataLen(gpr[4], gpr[5]); break; //case 0x212d: pspAudio.getInstance().sceAudioChangeChannelConfig(gpr[4], gpr[5]); break; case 0x212e: pspAudio.getInstance().sceAudioChangeChannelVolume(gpr[4], gpr[5], gpr[6]); break; //case 0x212f: pspAudio.getInstance().sceAudio_38553111(); break; //case 0x2130: pspAudio.getInstance().sceAudio_5C37C0AE(); break; //case 0x2131: pspAudio.getInstance().sceAudio_E0727056(); break; //case 0x2132: pspAudio.getInstance().sceAudioInputBlocking(gpr[4], gpr[5], gpr[6]); break; //case 0x2133: pspAudio.getInstance().sceAudioInput(gpr[4], gpr[5], gpr[6]); break; //case 0x2134: pspAudio.getInstance().sceAudioGetInputLength(); break; //case 0x2135: pspAudio.getInstance().sceAudioWaitInputEnd(); break; //case 0x2136: pspAudio.getInstance().sceAudioInputInit(gpr[4], gpr[5], gpr[6]); break; //case 0x2137: pspAudio.getInstance().sceAudio_E926D3FB(); break; //case 0x2138: pspAudio.getInstance().sceAudio_A633048E(); break; case 0x2139: pspAudio.getInstance().sceAudioGetChannelRestLen(gpr[4]); break; */ case 0x213a: pspdisplay.getInstance().sceDisplaySetMode(gpr[4], gpr[5], gpr[6]); break; // sceDisplayGetMode(0x213b), // sceDisplayGetFramePerSec(0x213c), // sceDisplaySetHoldMode(0x213d), // sceDisplaySetResumeMode(0x213e), case 0x213f: pspdisplay.getInstance().sceDisplaySetFrameBuf(gpr[4], gpr[5], gpr[6], gpr[7]); break; case 0x2140: pspdisplay.getInstance().sceDisplayGetFrameBuf(gpr[4], gpr[5], gpr[6], gpr[7]); break; // sceDisplayIsForeground(0x2141), // sceDisplayGetBrightness(0x2142), // sceDisplayGetVcount(0x2143), case 0x2143: pspdisplay.getInstance().sceDisplayGetVcount(); break; // sceDisplayIsVblank(0x2144), case 0x2145: pspdisplay.getInstance().sceDisplayWaitVblank(); break; case 0x2146: pspdisplay.getInstance().sceDisplayWaitVblankCB(); break; case 0x2147: pspdisplay.getInstance().sceDisplayWaitVblankStart(); break; case 0x2148: pspdisplay.getInstance().sceDisplayWaitVblankStartCB(); break; case 0x2149: pspdisplay.getInstance().sceDisplayGetCurrentHcount(); break; case 0x214a: pspdisplay.getInstance().sceDisplayGetAccumulatedHcount(); break; // sceDisplay_A83EF139(0x214b), /* case 0x214c: pspctrl.getInstance().sceCtrlSetSamplingCycle(gpr[4]); break; case 0x214d: pspctrl.getInstance().sceCtrlGetSamplingCycle(gpr[4]); break; case 0x214e: pspctrl.getInstance().sceCtrlSetSamplingMode(gpr[4]); break; case 0x214f: pspctrl.getInstance().sceCtrlGetSamplingMode(gpr[4]); break; case 0x2150: pspctrl.getInstance().sceCtrlPeekBufferPositive(gpr[4], gpr[5]); break; case 0x2151: pspctrl.getInstance().sceCtrlPeekBufferNegative(gpr[4], gpr[5]); break; case 0x2152: pspctrl.getInstance().sceCtrlReadBufferPositive(gpr[4], gpr[5]); break; case 0x2153: pspctrl.getInstance().sceCtrlReadBufferNegative(gpr[4], gpr[5]); break; case 0x2154: pspctrl.getInstance().sceCtrlPeekLatch(gpr[4]); break; case 0x2155: pspctrl.getInstance().sceCtrlReadLatch(gpr[4]); break;*/ // sceCtrl_A7144800(0x2156), // sceCtrl_687660FA(0x2157), // sceCtrl_348D99D4(0x2158), // sceCtrl_AF5960F3(0x2159), // sceCtrl_A68FD260(0x215a), // sceCtrl_6841BE1A(0x215b), // sceHprmRegisterCallback(0x215c), // sceHprmUnregisterCallback(0x215d), // sceHprm_71B5FB67(0x215e), // sceHprmIsRemoteExist(0x215f), // sceHprmIsHeadphoneExist(0x2160), // sceHprmIsMicrophoneExist(0x2161), // sceHprmPeekCurrentKey(0x2162), // sceHprmPeekLatch(0x2163), // sceHprmReadLatch(0x2164), // scePower_2B51FE2F(0x2165), // scePower_442BFBAC(0x2166), /// scePowerTick(0x2167), // scePowerGetIdleTimer(0x2168), // scePowerIdleTimerEnable(0x2169), // scePowerIdleTimerDisable(0x216a), // scePowerBatteryUpdateInfo(0x216b), // scePower_E8E4E204(0x216c), // scePowerGetLowBatteryCapacity(0x216d), // scePowerIsPowerOnline(0x216e), // scePowerIsBatteryExist(0x216f), // scePowerIsBatteryCharging(0x2170), // scePowerGetBatteryChargingStatus(0x2171), // scePowerIsLowBattery(0x2172), // scePower_78A1A796(0x2173), // scePowerGetBatteryRemainCapacity(0x2174), // scePower_FD18A0FF(0x2175), //// scePowerGetBatteryLifePercent(0x2176), // scePowerGetBatteryLifeTime(0x2177), //// scePowerGetBatteryTemp(0x2178), // scePowerGetBatteryElec(0x2179), // scePowerGetBatteryVolt(0x217a), // scePower_23436A4A(0x217b), // scePower_0CD21B1F(0x217c), // scePower_165CE085(0x217d), // scePower_23C31FFE(0x217e), // scePower_FA97A599(0x217f), // scePower_B3EDD801(0x2180), // scePowerLock(0x2181), // scePowerUnlock(0x2182), // scePowerCancelRequest(0x2183), // scePowerIsRequest(0x2184), // scePowerRequestStandby(0x2185), // scePowerRequestSuspend(0x2186), // scePower_2875994B(0x2187), // scePowerEncodeUBattery(0x2188), // scePowerGetResumeCount(0x2189), // scePowerRegisterCallback(0x218a), // scePowerUnregisterCallback(0x218b), // scePowerUnregitserCallback(0x218c), // scePowerSetCpuClockFrequency(0x218d), /// scePowerSetBusClockFrequency(0x218e), // scePowerGetCpuClockFrequency(0x218f), // scePowerGetBusClockFrequency(0x2190), // scePowerGetCpuClockFrequencyInt(0x2191), // scePowerGetBusClockFrequencyInt(0x2192), // scePower_34F9C463(0x2193), // scePowerGetCpuClockFrequencyFloat(0x2194), // scePowerGetBusClockFrequencyFloat(0x2195), // scePower_EA382A27(0x2196), // scePowerSetClockFrequency(0x2197), // sceUsbStart(0x2198), // sceUsbStop(0x2199), // sceUsbGetState(0x219a), // sceUsbGetDrvList(0x219b), // sceUsbGetDrvState(0x219c), // sceUsbActivate(0x219d), // sceUsbDeactivate(0x219e), // sceUsbWaitState(0x219f), // sceUsbWaitCancel(0x21a0), // sceOpenPSIDGetOpenPSID(0x21a1), // sceSircsSend(0x21a2), // sceUmdCheckMedium(0x21a3), // sceUmdActivate(0x21a4), // sceUmdDeactivate(0x21a5), // sceUmdWaitDriveStat(0x21a6), // sceUmdWaitDriveStatWithTimer(0x21a7), // sceUmdWaitDriveStatCB(0x21a8), // sceUmdCancelWaitDriveStat(0x21a9), // sceUmdGetDriveStat(0x21aa), // sceUmdGetErrorStat(0x21ab), // sceUmdGetDiscInfo(0x21ac), // sceUmdRegisterUMDCallBack(0x21ad), // sceUmdUnRegisterUMDCallBack(0x21ae), // sceWlanDevIsPowerOn(0x21af), // sceWlanGetSwitchState(0x21b0), // sceWlanGetEtherAddr(0x21b1), // sceWlanDevAttach(0x21b2), // sceWlanDevDetach(0x21b3), // sceWlanDrv_lib_19E51F54(0x21b4), // sceWlanDevIsGameMode(0x21b5), // sceWlanGPPrevEstablishActive(0x21b6), // sceWlanGPSend(0x21b7), // sceWlanGPRecv(0x21b8), // sceWlanGPRegisterCallback(0x21b9), // sceWlanGPUnRegisterCallback(0x21ba), // sceWlanDrv_lib_81579D36(0x21bb), // sceWlanDrv_lib_5BAA1FE5(0x21bc), // sceWlanDrv_lib_4C14BACA(0x21bd), // sceWlanDrv_lib_2D0FAE4E(0x21be), // sceWlanDrv_lib_56F467CA(0x21bf), // sceWlanDrv_lib_FE8A0B46(0x21c0), // sceWlanDrv_lib_40B0AA4A(0x21c1), // sceWlanDevSetGPIO(0x21c2), // sceWlanDevGetStateGPIO(0x21c3), // sceWlanDrv_lib_8D5F551B(0x21c4), // sceVaudioOutputBlocking(0x21c5), // sceVaudioChReserve(0x21c6), // sceVaudioChRelease(0x21c7), // sceVaudio_346FBE94(0x21c8), // sceRegExit(0x21c9), // sceRegOpenRegistry(0x21ca), // sceRegCloseRegistry(0x21cb), // sceRegRemoveRegistry(0x21cc), // sceReg_1D8A762E(0x21cd), // sceReg_0CAE832B(0x21ce), // sceRegFlushRegistry(0x21cf), // sceReg_0D69BF40(0x21d0), // sceRegCreateKey(0x21d1), // sceRegSetKeyValue(0x21d2), // sceRegGetKeyInfo(0x21d3), // sceRegGetKeyValue(0x21d4), // sceRegGetKeysNum(0x21d5), // sceRegGetKeys(0x21d6), // sceReg_4CA16893(0x21d7), // sceRegRemoveKey(0x21d8), // sceRegKickBackDiscover(0x21d9), // sceRegGetKeyValueByName(0x21da), // sceUtilityGameSharingInitStart(0x21db), // sceUtilityGameSharingShutdownStart(0x21dc), // sceUtilityGameSharingUpdate(0x21dd), // sceUtilityGameSharingGetStatus(0x21de), // sceNetplayDialogInitStart(0x21df), // sceNetplayDialogShutdownStart(0x21e0), // sceNetplayDialogUpdate(0x21e1), // sceNetplayDialogGetStatus(0x21e2), // sceUtilityNetconfInitStart(0x21e3), // sceUtilityNetconfShutdownStart(0x21e4), // sceUtilityNetconfUpdate(0x21e5), // sceUtilityNetconfGetStatus(0x21e6), // sceUtilitySavedataInitStart(0x21e7), // sceUtilitySavedataShutdownStart(0x21e8), // sceUtilitySavedataUpdate(0x21e9), // sceUtilitySavedataGetStatus(0x21ea), // sceUtility_2995D020(0x21eb), // sceUtility_B62A4061(0x21ec), // sceUtility_ED0FAD38(0x21ed), // sceUtility_88BC7406(0x21ee), // sceUtilityMsgDialogInitStart(0x21ef), // sceUtilityMsgDialogShutdownStart(0x21f0), // sceUtilityMsgDialogUpdate(0x21f1), // sceUtilityMsgDialogGetStatus(0x21f2), // sceUtilityOskInitStart(0x21f3), // sceUtilityOskShutdownStart(0x21f4), // sceUtilityOskUpdate(0x21f5), // sceUtilityOskGetStatus(0x21f6), // sceUtilitySetSystemParamInt(0x21f7), // sceUtilitySetSystemParamString(0x21f8), // sceUtilityGetSystemParamInt(0x21f9), // sceUtilityGetSystemParamString(0x21fa), // sceUtilityCheckNetParam(0x21fb), // sceUtilityGetNetParam(0x21fc), // sceUtility_private_17CB4D96(0x21fd), // sceUtility_private_EE7AC503(0x21fe), // sceUtility_private_5FF96ED3(0x21ff), // sceUtility_private_9C9DD5BC(0x2200), // sceUtility_private_4405BA38(0x2201), // sceUtility_private_1DFA62EF(0x2202), // sceUtilityDialogSetStatus(0x2203), // sceUtilityDialogGetType(0x2204), // sceUtilityDialogGetParam(0x2205), // sceUtility_private_EF5BC2D1(0x2206), // sceUtilityDialogGetSpeed(0x2207), // sceUtility_private_19461966(0x2208), // sceUtilityDialogSetThreadId(0x2209), // sceUtilityDialogLoadModule(0x220a), // sceUtilityDialogPowerLock(0x220b), // sceUtilityDialogPowerUnlock(0x220c), // sceUtilityCreateNetParam(0x220d), //sceUtilityDeleteNetParam(0x220e), //sceUtilityCopyNetParam(0x220f), // sceUtilitySetNetParam(0x2210); case 0xfffff: // special code for unmapped imports Modules.log.error(String.format("Unmapped import @ 0x%08X", Emulator.getProcessor().cpu.pc)); Emulator.PauseEmu(); break; default: { // Try and handle as an HLE module export boolean handled = HLEModuleManager.getInstance().handleSyscall(code); if (!handled) { CpuState cpu = Emulator.getProcessor().cpu; // At least set a decent return value cpu.gpr[2] = 0; //Emulator.getProcessor().gpr[2] = 0xb515ca11; // Display debug info String params = String.format("%08x %08x %08x", cpu.gpr[4], cpu.gpr[5], cpu.gpr[6]); for (jpcsp.Debugger.DisassemblerModule.syscallsFirm15.calls c : jpcsp.Debugger.DisassemblerModule.syscallsFirm15.calls.values()) { if (c.getSyscall() == code) { Modules.log.warn("Unsupported syscall " + Integer.toHexString(code) + " " + c + " " + params); return; } } Modules.log.warn("Unsupported syscall " + Integer.toHexString(code) + " " + params); } } break; } } catch(GeneralJpcspException e) { System.out.println(e.getMessage()); } }
diff --git a/src/main/java/org/apache/ode/jacob/vpu/JacobVPU.java b/src/main/java/org/apache/ode/jacob/vpu/JacobVPU.java index 2a20fdd..db136de 100644 --- a/src/main/java/org/apache/ode/jacob/vpu/JacobVPU.java +++ b/src/main/java/org/apache/ode/jacob/vpu/JacobVPU.java @@ -1,492 +1,496 @@ /* * 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.ode.jacob.vpu; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ode.jacob.*; import org.apache.ode.jacob.soup.*; import org.apache.ode.utils.CollectionUtils; import org.apache.ode.utils.ObjectPrinter; import org.apache.ode.utils.msg.MessageBundle; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Stack; /** * The JACOB Virtual Processing Unit ("VPU"). * * @author Maciej Szefler <a href="mailto:[email protected]" /> */ public final class JacobVPU { private static final Log __log = LogFactory.getLog(JacobVPU.class); /** * Internationalization messages. */ private static final JacobMessages __msgs = MessageBundle.getMessages(JacobMessages.class); /** * Thread-local for associating a thread with a VPU. Needs to be stored in a stack to allow reentrance. */ static final ThreadLocal<Stack<JacobThread>> __activeJacobThread = new ThreadLocal<Stack<JacobThread>>(); private static final Method REDUCE_METHOD; /** * Resolve the {@link JacobRunnable#run} method statically */ static { try { REDUCE_METHOD = JacobRunnable.class.getMethod("run", CollectionUtils.EMPTY_CLASS_ARRAY); } catch (Exception e) { throw new Error("Cannot resolve 'run' method", e); } } /** * Persisted cross-VPU state (state of the channels) */ private ExecutionQueue _executionQueue; private Map<Class, Object> _extensions = new HashMap<Class, Object>(); /** * Classloader used for loading object continuations. */ private ClassLoader _classLoader = getClass().getClassLoader(); private int _cycle; private Statistics _statistics = new Statistics(); /** * The fault "register" of the VPU . */ private RuntimeException _fault; /** * Default constructor. */ public JacobVPU() { } /** * Re-hydration constructor. * * @param executionQueue previously saved execution context */ public JacobVPU(ExecutionQueue executionQueue) { setContext(executionQueue); } /** * Instantiation constructor; used to initialize context with the concretion * of a process abstraction. * * @param context virgin context object * @param concretion the process */ public JacobVPU(ExecutionQueue context, JacobRunnable concretion) { setContext(context); inject(concretion); } /** * Execute one VPU cycle. * * @return <code>true</code> if the run queue is not empty after this cycle, <code>false</code> otherwise. */ public boolean execute() { if (__log.isTraceEnabled()) { __log.trace(ObjectPrinter.stringifyMethodEnter("execute", CollectionUtils.EMPTY_OBJECT_ARRAY)); } if (_executionQueue == null) { throw new IllegalStateException("No state object for VPU!"); } if (_fault != null) { throw _fault; } if (!_executionQueue.hasReactions()) { return false; } _cycle = _executionQueue.cycle(); Continuation rqe = _executionQueue.dequeueReaction(); JacobThreadImpl jt = new JacobThreadImpl(rqe); long ctime = System.currentTimeMillis(); try { jt.run(); } catch (RuntimeException re) { _fault = re; throw re; } long rtime = System.currentTimeMillis() - ctime; ++_statistics.numCycles; _statistics.totalRunTimeMs += rtime; _statistics.incRunTime(jt._targetStr, rtime); return true; } public void flush() { if (__log.isTraceEnabled()) { __log.trace(ObjectPrinter.stringifyMethodEnter("flush", CollectionUtils.EMPTY_OBJECT_ARRAY)); } _executionQueue.flush(); } /** * Set the state of of the VPU; this is analagous to loading a CPU with a * thread's context (re-hydration). * * @param executionQueue * process executionQueue (state) */ public void setContext(ExecutionQueue executionQueue) { if (__log.isTraceEnabled()) { __log.trace(ObjectPrinter.stringifyMethodEnter("setContext", new Object[] { "executionQueue", executionQueue })); } _executionQueue = executionQueue; _executionQueue.setClassLoader(_classLoader); } public void registerExtension(Class extensionClass, Object obj) { if (__log.isTraceEnabled()) { __log.trace(ObjectPrinter .stringifyMethodEnter("registerExtension", new Object[] { "extensionClass", extensionClass, "obj", obj })); } _extensions.put(extensionClass, obj); } /** * Add an item to the run queue. */ public void addReaction(JacobObject jo, Method method, Object[] args, String desc) { if (__log.isTraceEnabled()) { __log.trace(ObjectPrinter.stringifyMethodEnter("addReaction", new Object[] { "jo", jo, "method", method, "args", args, "desc", desc })); } Continuation continuation = new Continuation(jo, method, args); continuation.setDescription(desc); _executionQueue.enqueueReaction(continuation); ++_statistics.runQueueEntries; } /** * Get the active Jacob thread, i.e. the one associated with the current Java thread. */ public static JacobThread activeJacobThread() { return __activeJacobThread.get().peek(); } /** * Inject a concretion into the process context. This amounts to chaning the * process context from <code>P</code> to <code>P|Q</code> where * <code>P</code> is the previous process context and <code>Q</code> is * the injected process. This method is equivalent to the parallel operator, * but is intended to be used from outside of an active {@link JacobThread}. */ public void inject(JacobRunnable concretion) { if (__log.isDebugEnabled()) { __log.debug("injecting " + concretion); } addReaction(concretion, REDUCE_METHOD, CollectionUtils.EMPTY_OBJECT_ARRAY, (__log.isInfoEnabled() ? concretion.toString() : null)); } static String stringifyMethods(Class kind) { StringBuffer buf = new StringBuffer(); Method[] methods = kind.getMethods(); boolean found = false; for (Method method : methods) { if (method.getDeclaringClass() == Object.class) { continue; } if (found) { buf.append(" & "); } buf.append(method.getName()).append('('); Class[] argTypes = method.getParameterTypes(); for (int j = 0; j < argTypes.length; ++j) { if (j > 0) { buf.append(", "); } buf.append(argTypes[j].getName()); } buf.append(") {...}"); found = true; } return buf.toString(); } static String stringify(Object[] list) { if (list == null) { return ""; } StringBuffer buf = new StringBuffer(); for (int i = 0; i < list.length; ++i) { if (i > 0) { buf.append(','); } buf.append(list[i]); } return buf.toString(); } public void setClassLoader(ClassLoader classLoader) { _classLoader = classLoader; if (_executionQueue != null) { _executionQueue.setClassLoader(classLoader); } } /** * Dump the state of the VPU for debugging purposes. */ public void dumpState() { _statistics.printToStream(System.err); _executionQueue.dumpState(System.err); } public boolean isComplete() { return _executionQueue.isComplete(); } private class JacobThreadImpl implements Runnable, JacobThread { private final JacobObject _methodBody; private final Object[] _args; private final Method _method; /** Text string identifying the left side of the reduction (for debug). */ private String _source; /** Text string identifying the target class and method (for debug) . */ private String _targetStr = "Unknown"; JacobThreadImpl(Continuation rqe) { assert rqe != null; _methodBody = rqe.getClosure(); _args = rqe.getArgs(); _source = rqe.getDescription(); _method = rqe.getMethod(); if (__log.isDebugEnabled()) { StringBuffer buf = new StringBuffer(_methodBody.getClass().getName()); buf.append('.'); buf.append(rqe.getMethod()); _targetStr = buf.toString(); } } public void instance(JacobRunnable template) { String desc = null; if (__log.isTraceEnabled()) { __log.trace(_cycle + ": " + template); desc = template.toString(); } _statistics.numReductionsStruct++; addReaction(template, REDUCE_METHOD, CollectionUtils.EMPTY_OBJECT_ARRAY, desc); } public Channel message(Channel channel, Method method, Object[] args) { if (__log.isTraceEnabled()) { __log.trace(_cycle + ": " + channel + " ! " + method.getName() + "(" + stringify(args) + ")"); } _statistics.messagesSent++; SynchChannel replyChannel = null; // Check for synchronous methods; create a synchronization channel if (method.getReturnType() != void.class) { if (method.getReturnType() != SynchChannel.class) { throw new IllegalStateException( "ChannelListener method can only return SynchChannel: " + method); } replyChannel = (SynchChannel) newChannel(SynchChannel.class, "", "Reply Channel"); Object[] newArgs = new Object[args.length + 1]; System.arraycopy(args, 0, newArgs, 0, args.length); newArgs[args.length] = replyChannel; args = newArgs; } CommChannel chnl = (CommChannel) ChannelFactory.getBackend(channel); CommGroup grp = new CommGroup(false); CommSend send = new CommSend(chnl, method, args); grp.add(send); _executionQueue.add(grp); return replyChannel; } public Channel newChannel(Class channelType, String creator, String description) { CommChannel chnl = new CommChannel(channelType); chnl.setDescription(description); _executionQueue.add(chnl); Channel ret = ChannelFactory.createChannel(chnl, channelType); if (__log.isTraceEnabled()) __log.trace(_cycle + ": new " + ret); _statistics.channelsCreated++; return ret; } public String exportChannel(Channel channel) { if (__log.isTraceEnabled()) { __log.trace(_cycle + ": export<" + channel + ">"); } CommChannel chnl = (CommChannel) ChannelFactory.getBackend(channel); return _executionQueue.createExport(chnl); } public Channel importChannel(String channelId, Class channelType) { CommChannel cframe = _executionQueue.consumeExport(channelId); return ChannelFactory.createChannel(cframe, channelType); } public void object(boolean replicate, ChannelListener[] ml) { if (__log.isTraceEnabled()) { StringBuffer msg = new StringBuffer(); msg.append(_cycle); msg.append(": "); for (int i = 0; i < ml.length; ++i) { if (i != 0) msg.append(" + "); msg.append(ml[i].getChannel()); msg.append(" ? "); msg.append(ml.toString()); } __log.debug(msg.toString()); } _statistics.numContinuations++; CommGroup grp = new CommGroup(replicate); for (int i = 0; i < ml.length; ++i) { CommChannel chnl = (CommChannel) ChannelFactory .getBackend(ml[i].getChannel()); // TODO see below.. // oframe.setDebugInfo(fillDebugInfo()); CommRecv recv = new CommRecv(chnl, ml[i]); grp.add(recv); } _executionQueue.add(grp); } public void object(boolean replicate, ChannelListener methodList) throws IllegalArgumentException { object(replicate, new ChannelListener[] { methodList }); } /* UNUSED private DebugInfo fillDebugInfo() { // Some of the debug information is a bit lengthy, so lets not put // it in all the time... eh. DebugInfo frame = new DebugInfo(); frame.setCreator(_source); Exception ex = new Exception(); StackTraceElement[] st = ex.getStackTrace(); if (st.length > 2) { StackTraceElement[] stcut = new StackTraceElement[st.length - 2]; System.arraycopy(st, 2, stcut, 0, stcut.length); frame.setLocation(stcut); } return frame; } */ public Object getExtension(Class extensionClass) { return _extensions.get(extensionClass); } public void run() { assert _methodBody != null; assert _method != null; assert _method.getDeclaringClass().isAssignableFrom(_methodBody.getClass()); if (__log.isTraceEnabled()) { __log.trace(_cycle + ": " + _source); } Object[] args; SynchChannel synchChannel; if (_method.getReturnType() != void.class) { args = new Object[_args.length - 1]; System.arraycopy(_args, 0, args, 0, args.length); synchChannel = (SynchChannel) _args[args.length]; } else { args = _args; synchChannel = null; } stackThread(); long ctime = System.currentTimeMillis(); try { _method.invoke(_methodBody, args); if (synchChannel != null) { synchChannel.ret(); } } catch (IllegalAccessException iae) { String msg = __msgs.msgMethodNotAccessible(_method.getName(), _method.getDeclaringClass().getName()); __log.error(msg, iae); throw new RuntimeException(msg, iae); } catch (InvocationTargetException e) { - String msg = __msgs.msgClientMethodException(_method.getName(), - _methodBody.getClass().getName()); - __log.error(msg, e.getTargetException()); - throw new RuntimeException(e.getTargetException()); + if (e.getTargetException() instanceof RuntimeException) { + throw (RuntimeException) e.getTargetException(); + } else { + String msg = __msgs.msgClientMethodException(_method.getName(), + _methodBody.getClass().getName()); + __log.error(msg, e.getTargetException()); + throw new RuntimeException(e.getTargetException()); + } } finally { ctime = System.currentTimeMillis() - ctime; _statistics.totalClientTimeMs += ctime; unstackThread(); } } public String toString() { return "PT[ " + _methodBody + " ]"; } private void stackThread() { Stack<JacobThread> currStack = __activeJacobThread.get(); if (currStack == null) { currStack = new Stack<JacobThread>(); __activeJacobThread.set(currStack); } currStack.push(this); } private JacobThread unstackThread() { Stack<JacobThread> currStack = __activeJacobThread.get(); assert currStack != null; return currStack.pop(); } } }
true
true
public void run() { assert _methodBody != null; assert _method != null; assert _method.getDeclaringClass().isAssignableFrom(_methodBody.getClass()); if (__log.isTraceEnabled()) { __log.trace(_cycle + ": " + _source); } Object[] args; SynchChannel synchChannel; if (_method.getReturnType() != void.class) { args = new Object[_args.length - 1]; System.arraycopy(_args, 0, args, 0, args.length); synchChannel = (SynchChannel) _args[args.length]; } else { args = _args; synchChannel = null; } stackThread(); long ctime = System.currentTimeMillis(); try { _method.invoke(_methodBody, args); if (synchChannel != null) { synchChannel.ret(); } } catch (IllegalAccessException iae) { String msg = __msgs.msgMethodNotAccessible(_method.getName(), _method.getDeclaringClass().getName()); __log.error(msg, iae); throw new RuntimeException(msg, iae); } catch (InvocationTargetException e) { String msg = __msgs.msgClientMethodException(_method.getName(), _methodBody.getClass().getName()); __log.error(msg, e.getTargetException()); throw new RuntimeException(e.getTargetException()); } finally { ctime = System.currentTimeMillis() - ctime; _statistics.totalClientTimeMs += ctime; unstackThread(); } }
public void run() { assert _methodBody != null; assert _method != null; assert _method.getDeclaringClass().isAssignableFrom(_methodBody.getClass()); if (__log.isTraceEnabled()) { __log.trace(_cycle + ": " + _source); } Object[] args; SynchChannel synchChannel; if (_method.getReturnType() != void.class) { args = new Object[_args.length - 1]; System.arraycopy(_args, 0, args, 0, args.length); synchChannel = (SynchChannel) _args[args.length]; } else { args = _args; synchChannel = null; } stackThread(); long ctime = System.currentTimeMillis(); try { _method.invoke(_methodBody, args); if (synchChannel != null) { synchChannel.ret(); } } catch (IllegalAccessException iae) { String msg = __msgs.msgMethodNotAccessible(_method.getName(), _method.getDeclaringClass().getName()); __log.error(msg, iae); throw new RuntimeException(msg, iae); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } else { String msg = __msgs.msgClientMethodException(_method.getName(), _methodBody.getClass().getName()); __log.error(msg, e.getTargetException()); throw new RuntimeException(e.getTargetException()); } } finally { ctime = System.currentTimeMillis() - ctime; _statistics.totalClientTimeMs += ctime; unstackThread(); } }
diff --git a/org.emftext.sdk.concretesyntax.resource.cs/src/org/emftext/sdk/concretesyntax/resource/cs/mopp/CsHoverTextProvider.java b/org.emftext.sdk.concretesyntax.resource.cs/src/org/emftext/sdk/concretesyntax/resource/cs/mopp/CsHoverTextProvider.java index cd44fb805..3e326f6e8 100644 --- a/org.emftext.sdk.concretesyntax.resource.cs/src/org/emftext/sdk/concretesyntax/resource/cs/mopp/CsHoverTextProvider.java +++ b/org.emftext.sdk.concretesyntax.resource.cs/src/org/emftext/sdk/concretesyntax/resource/cs/mopp/CsHoverTextProvider.java @@ -1,88 +1,94 @@ package org.emftext.sdk.concretesyntax.resource.cs.mopp; import java.util.ArrayList; import java.util.List; import org.eclipse.emf.codegen.ecore.genmodel.GenClass; import org.eclipse.emf.codegen.ecore.genmodel.GenFeature; import org.eclipse.emf.codegen.ecore.genmodel.GenPackage; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EStructuralFeature; import org.emftext.sdk.concretesyntax.resource.cs.util.CsStringUtil; public class CsHoverTextProvider implements org.emftext.sdk.concretesyntax.resource.cs.ICsHoverTextProvider { public java.lang.String getHoverText(EObject object) { if (object == null) { return null; } String htmlForObject = getHTML(object); if (object instanceof GenClass) { // for generator classes we do also show the properties of the // corresponding EClass GenClass genClass = (GenClass) object; EClass ecoreClass = genClass.getEcoreClass(); - String htmlForEClass = getHTML(ecoreClass); - return htmlForEClass + "<br/><br/>" + htmlForObject; + if (ecoreClass != null) { + String htmlForEClass = getHTML(ecoreClass); + return htmlForEClass + "<br/><br/>" + htmlForObject; + } } if (object instanceof GenPackage) { // for generator package we do also show the properties of the // corresponding EPackage GenPackage genPackage = (GenPackage) object; EPackage ecorePackage = genPackage.getEcorePackage(); - String htmlForEPackage = getHTML(ecorePackage); - return htmlForEPackage + "<br/><br/>" + htmlForObject; + if (ecorePackage != null) { + String htmlForEPackage = getHTML(ecorePackage); + return htmlForEPackage + "<br/><br/>" + htmlForObject; + } } if (object instanceof GenFeature) { // for generator features we do also show the properties of the // corresponding EClass GenFeature genFeature = (GenFeature) object; EStructuralFeature ecoreFeature = genFeature.getEcoreFeature(); - String htmlForEFeature = getHTML(ecoreFeature); - // and we want to show the type of the feature - EClassifier type = ecoreFeature.getEType(); - String htmlForEType = getHTML(type); - return htmlForEFeature + "<br/><br/>Type:<br/>" + htmlForEType + "<br/><br/>" + htmlForObject; + if (ecoreFeature != null) { + String htmlForEFeature = getHTML(ecoreFeature); + // and we want to show the type of the feature + EClassifier type = ecoreFeature.getEType(); + String htmlForEType = getHTML(type); + return htmlForEFeature + "<br/><br/>Type:<br/>" + htmlForEType + "<br/><br/>" + htmlForObject; + } } return htmlForObject; } private java.lang.String getHTML(EObject object) { if (object == null) { return ""; } EClass eClass = object.eClass(); List<String> booleanAttributes = new ArrayList<String>(); StringBuffer nonBooleanAttributes = new StringBuffer(); for (EAttribute attribute : eClass.getEAllAttributes()) { Object value = null; try { value = object.eGet(attribute); } catch (Exception e) { // Exception in eGet, do nothing } if (value != null && value.toString() != null && !value.toString().equals("[]")) { if ("EBoolean".equals(attribute.getEType().getName()) && value instanceof Boolean) { Boolean booleanValue = (Boolean) value; if (booleanValue) { booleanAttributes.add(attribute.getName()); } } else { nonBooleanAttributes.append("<br />" + attribute.getName() + ": " + object.eGet(attribute).toString()); } } } String booleanAttributeValue = CsStringUtil.explode(booleanAttributes, ", "); if (booleanAttributeValue.length() > 0) { booleanAttributeValue = " (" + booleanAttributeValue + ")"; } String label = "<strong>" + eClass.getName() + booleanAttributeValue + "</strong>"; label += nonBooleanAttributes.toString(); return label; } }
false
true
public java.lang.String getHoverText(EObject object) { if (object == null) { return null; } String htmlForObject = getHTML(object); if (object instanceof GenClass) { // for generator classes we do also show the properties of the // corresponding EClass GenClass genClass = (GenClass) object; EClass ecoreClass = genClass.getEcoreClass(); String htmlForEClass = getHTML(ecoreClass); return htmlForEClass + "<br/><br/>" + htmlForObject; } if (object instanceof GenPackage) { // for generator package we do also show the properties of the // corresponding EPackage GenPackage genPackage = (GenPackage) object; EPackage ecorePackage = genPackage.getEcorePackage(); String htmlForEPackage = getHTML(ecorePackage); return htmlForEPackage + "<br/><br/>" + htmlForObject; } if (object instanceof GenFeature) { // for generator features we do also show the properties of the // corresponding EClass GenFeature genFeature = (GenFeature) object; EStructuralFeature ecoreFeature = genFeature.getEcoreFeature(); String htmlForEFeature = getHTML(ecoreFeature); // and we want to show the type of the feature EClassifier type = ecoreFeature.getEType(); String htmlForEType = getHTML(type); return htmlForEFeature + "<br/><br/>Type:<br/>" + htmlForEType + "<br/><br/>" + htmlForObject; } return htmlForObject; }
public java.lang.String getHoverText(EObject object) { if (object == null) { return null; } String htmlForObject = getHTML(object); if (object instanceof GenClass) { // for generator classes we do also show the properties of the // corresponding EClass GenClass genClass = (GenClass) object; EClass ecoreClass = genClass.getEcoreClass(); if (ecoreClass != null) { String htmlForEClass = getHTML(ecoreClass); return htmlForEClass + "<br/><br/>" + htmlForObject; } } if (object instanceof GenPackage) { // for generator package we do also show the properties of the // corresponding EPackage GenPackage genPackage = (GenPackage) object; EPackage ecorePackage = genPackage.getEcorePackage(); if (ecorePackage != null) { String htmlForEPackage = getHTML(ecorePackage); return htmlForEPackage + "<br/><br/>" + htmlForObject; } } if (object instanceof GenFeature) { // for generator features we do also show the properties of the // corresponding EClass GenFeature genFeature = (GenFeature) object; EStructuralFeature ecoreFeature = genFeature.getEcoreFeature(); if (ecoreFeature != null) { String htmlForEFeature = getHTML(ecoreFeature); // and we want to show the type of the feature EClassifier type = ecoreFeature.getEType(); String htmlForEType = getHTML(type); return htmlForEFeature + "<br/><br/>Type:<br/>" + htmlForEType + "<br/><br/>" + htmlForObject; } } return htmlForObject; }
diff --git a/src/main/java/net/vhati/modmanager/core/XMLPatcher.java b/src/main/java/net/vhati/modmanager/core/XMLPatcher.java index 4737f7f..14673e7 100644 --- a/src/main/java/net/vhati/modmanager/core/XMLPatcher.java +++ b/src/main/java/net/vhati/modmanager/core/XMLPatcher.java @@ -1,571 +1,571 @@ package net.vhati.modmanager.core; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.vhati.modmanager.core.SloppyXMLParser; import org.jdom2.Attribute; import org.jdom2.Content; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Namespace; import org.jdom2.filter.AbstractFilter; import org.jdom2.filter.ElementFilter; import org.jdom2.filter.Filter; import org.jdom2.input.JDOMParseException; import org.jdom2.input.SAXBuilder; /** * Programmatically edits existing XML with instructions from another XML doc. * Other tags are simply appended as-is. */ public class XMLPatcher { protected Namespace modNS; protected Namespace modAppendNS; protected Namespace modOverwriteNS; public XMLPatcher() { modNS = Namespace.getNamespace( "mod", "mod" ); modAppendNS = Namespace.getNamespace( "mod-append", "mod-append" ); modOverwriteNS = Namespace.getNamespace( "mod-overwrite", "mod-overwrite" ); } public Document patch( Document mainDoc, Document appendDoc ) { Document resultDoc = mainDoc.clone(); Element resultRoot = resultDoc.getRootElement(); Element appendRoot = appendDoc.getRootElement(); ElementFilter modFilter = new ElementFilter( modNS ); for ( Content content : appendRoot.getContent() ) { if ( modFilter.matches( content ) ) { Element node = (Element)content; boolean handled = false; List<Element> matchedNodes = handleModFind( resultRoot, node ); if ( matchedNodes != null ) { handled = true; for ( Element matchedNode : matchedNodes ) { handleModCommands( matchedNode, node ); } } if ( !handled ) { throw new IllegalArgumentException( String.format( "Unrecognized mod tag <%s> (%s).", node.getName(), getPathToRoot(node) ) ); } } else { resultRoot.addContent( content.clone() ); } } return resultDoc; } /** * Returns find results if node is a find tag, or null if it's not. * * An empty list will be returned if there were no matches. * * TODO: Throw an exception in callers if results are required. */ protected List<Element> handleModFind( Element contextNode, Element node ) { List<Element> result = null; if ( node.getNamespace().equals( modNS ) ) { if ( node.getName().equals( "findName" ) ) { String searchName = node.getAttributeValue( "name" ); String searchType = node.getAttributeValue( "type" ); boolean searchReverse = getAttributeBooleanValue( node, "reverse", true ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", 1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchName == null || searchName.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> requires a name attribute (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchType != null && searchType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Map<String,String> attrMap = new HashMap<String,String>(); attrMap.put( "name", searchName ); LikeFilter searchFilter = new LikeFilter( searchType, attrMap, null ); List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } - if ( matchedNodes.isEmpty() ) + if ( panic && matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } else if ( node.getName().equals( "findLike" ) ) { String searchType = node.getAttributeValue( "type" ); boolean searchReverse = getAttributeBooleanValue( node, "reverse", false ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", -1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchType != null && searchType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Map<String,String> attrMap = new HashMap<String,String>(); String searchValue = null; Element selectorNode = node.getChild( "selector", modNS ); if ( selectorNode != null ) { for ( Attribute attr : selectorNode.getAttributes() ) { if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) { // Blank element values can't be detected as different from absent values (never null). // Forbid "" attributes for consistency. :/ if ( attr.getValue().length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> attributes, when present, can't be empty (%s).", selectorNode.getName(), getPathToRoot(selectorNode) ) ); attrMap.put( attr.getName(), attr.getValue() ); } } searchValue = selectorNode.getTextTrim(); // Never null, but often "". if ( searchValue.length() > 0 ) searchValue = null; } LikeFilter searchFilter = new LikeFilter( searchType, attrMap, searchValue ); List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } - if ( matchedNodes.isEmpty() ) + if ( panic && matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } else if ( node.getName().equals( "findWithChildLike" ) ) { String searchType = node.getAttributeValue( "type" ); String searchChildType = node.getAttributeValue( "child-type" ); boolean searchReverse = getAttributeBooleanValue( node, "reverse", false ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", -1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchType != null && searchType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchChildType != null && searchChildType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> child-type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Map<String,String> attrMap = new HashMap<String,String>(); String searchValue = null; Element selectorNode = node.getChild( "selector", modNS ); if ( selectorNode != null ) { for ( Attribute attr : selectorNode.getAttributes() ) { if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) { // TODO: Forbid "" attributes, because blank value doesn't work? attrMap.put( attr.getName(), attr.getValue() ); } } searchValue = selectorNode.getTextTrim(); // Never null, but often "". if ( searchValue.length() > 0 ) searchValue = null; } LikeFilter searchChildFilter = new LikeFilter( searchChildType, attrMap, searchValue ); WithChildFilter searchFilter = new WithChildFilter( searchType, searchChildFilter ); List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } - if ( matchedNodes.isEmpty() ) + if ( panic && matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } else if ( node.getName().equals( "findComposite" ) ) { boolean searchReverse = getAttributeBooleanValue( node, "reverse", false ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", -1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Element parNode = node.getChild( "par", modNS ); if ( parNode == null ) throw new IllegalArgumentException( String.format( "<%s> requires a <par> tag (%s).", node.getName(), getPathToRoot(node) ) ); List<Element> matchedNodes = handleModPar( contextNode, parNode ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } - if ( matchedNodes.isEmpty() ) + if ( panic && matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } } return result; } /** * Returns collated find results (and par results, handled recursively), or null if node wasn't a par. * * Unique results from all finds will be combined and sorted in the order they appear under contextNode. */ protected List<Element> handleModPar( Element contextNode, Element node ) { List<Element> result = null; if ( node.getNamespace().equals( modNS ) ) { if ( node.getName().equals( "par" ) ) { String parOp = node.getAttributeValue( "op" ); if ( parOp == null || (!parOp.equals("AND") && !parOp.equals("OR")) ) throw new IllegalArgumentException( String.format( "Invalid \"op\" attribute (%s). Must be 'AND' or 'OR'.", getPathToRoot(node) ) ); boolean isAnd = parOp.equals("AND"); boolean isOr = parOp.equals("OR"); Set<Element> candidateSet = new HashSet<Element>(); for ( Element criteriaNode : node.getChildren() ) { List<Element> candidates; if ( criteriaNode.getName().equals( "par" ) && criteriaNode.getNamespace().equals( modNS ) ) { candidates = handleModPar( contextNode, criteriaNode ); } else { candidates = handleModFind( contextNode, criteriaNode ); if ( candidates == null ) throw new IllegalArgumentException( String.format( "Invalid <par> search criteria <%s> (%s). Must be a <find...> or <par>.", criteriaNode.getName(), getPathToRoot(criteriaNode) ) ); } if ( isOr || candidateSet.isEmpty() ) { candidateSet.addAll( candidates ); } else if ( isAnd ) { candidateSet.retainAll( candidates ); } } Map<Integer,Element> orderedCandidateMap = new TreeMap<Integer,Element>(); for ( Element candidate : candidateSet ) { int index = contextNode.indexOf( candidate ); orderedCandidateMap.put( new Integer(index), candidate ); } List<Element> matchedNodes = new ArrayList<Element>( orderedCandidateMap.values() ); result = matchedNodes; } } return result; } /** * Performs child mod-commands under node, against contextNode. * * TODO: Maybe have handleModCommand() returning null when unrecognized, * or an object with flags to continue or stop looping commands at * contextNode (e.g., halting after removeTag). */ protected void handleModCommands( Element contextNode, Element node ) { for ( Element cmdNode : node.getChildren() ) { boolean handled = false; if ( cmdNode.getNamespace().equals( modNS ) ) { // Handle nested finds. List<Element> matchedNodes = handleModFind( contextNode, cmdNode ); if ( matchedNodes != null ) { handled = true; for ( Element matchedNode : matchedNodes ) { handleModCommands( matchedNode, cmdNode ); } } else if ( cmdNode.getName().equals( "selector" ) ) { handled = true; // No-op. } else if ( cmdNode.getName().equals( "par" ) ) { handled = true; // No-op. } else if ( cmdNode.getName().equals( "setAttributes" ) ) { handled = true; for ( Attribute attrib : cmdNode.getAttributes() ) { contextNode.setAttribute( attrib.clone() ); } } else if ( cmdNode.getName().equals( "setValue" ) ) { handled = true; contextNode.setText( cmdNode.getTextTrim() ); } else if ( cmdNode.getName().equals( "removeTag" ) ) { handled = true; contextNode.detach(); break; } } else if ( cmdNode.getNamespace().equals( modAppendNS ) ) { // Append cmdNode (sans namespace) to the contextNode. handled = true; Element newNode = cmdNode.clone(); newNode.setNamespace( null ); contextNode.addContent( newNode ); } else if ( cmdNode.getNamespace().equals( modOverwriteNS ) ) { // Remove the first child with the same type and insert cmdNode at its position. // Or just append if nothing was replaced. handled = true; Element newNode = cmdNode.clone(); newNode.setNamespace( null ); Element doomedNode = contextNode.getChild( cmdNode.getName(), null ); if ( doomedNode != null ) { int doomedIndex = contextNode.indexOf( doomedNode ); doomedNode.detach(); contextNode.addContent( doomedIndex, newNode ); } else { contextNode.addContent( newNode ); } } if ( !handled ) { throw new IllegalArgumentException( String.format( "Unrecognized mod tag <%s> (%s).", cmdNode.getName(), getPathToRoot(cmdNode) ) ); } } } /** * Returns a string describing this element's location. * * Example: /root/event(SOME_NAME)/choice/text */ protected String getPathToRoot( Element node ) { StringBuilder buf = new StringBuilder(); String chunk; String tmp; while ( node != null ) { chunk = "/"+ node.getName(); tmp = node.getAttributeValue( "name" ); if ( tmp != null && tmp.length() > 0 ) chunk += "("+ tmp +")"; buf.insert( 0, chunk ); node = node.getParentElement(); } return buf.toString(); } /** * Returns the boolean value of an attribute, or a default when the attribute is null. * Only 'true' and 'false' are accepted. */ protected boolean getAttributeBooleanValue( Element node, String attrName, boolean defaultValue ) { String tmp = node.getAttributeValue( attrName ); if ( tmp == null ) return defaultValue; if ( tmp.equals( "true" ) ) { return true; } else if ( tmp.equals( "false" ) ) { return false; } else { throw new IllegalArgumentException( String.format( "Invalid boolean attribute \"%s\" (%s). Must be 'true' or 'false'.", attrName, getPathToRoot(node) ) ); } } /** * Returns the int value of an attribute, or a default when the attribute is null. */ protected int getAttributeIntValue( Element node, String attrName, int defaultValue ) { String tmp = node.getAttributeValue( attrName ); if ( tmp == null ) return defaultValue; try { return Integer.parseInt( tmp ); } catch ( NumberFormatException e ) { throw new IllegalArgumentException( String.format( "Invalid int attribute \"%s\" (%s).", attrName, getPathToRoot(node) ) ); } } /** * Matches elements with equal type/attributes/value. * Null args are ignored. A blank type or value arg is ignored. * All given attributes must be present on a candidate to match. * Attribute values in the map must not be null. */ protected static class LikeFilter extends AbstractFilter<Element> { private String type = null;; private Map<String,String> attrMap = null; private String value = null; public LikeFilter( String type, Element selectorNode ) { this.type = type; if ( selectorNode.hasAttributes() ) { this.attrMap = new HashMap<String,String>(); for ( Attribute attr : selectorNode.getAttributes() ) { attrMap.put( attr.getName(), attr.getValue() ); } } this.value = selectorNode.getTextTrim(); if ( this.value.length() == 0 ) this.value = null; } public LikeFilter( String type, Map<String,String> attrMap, String value ) { super(); if ( type != null && type.length() == 0 ) type = null; if ( value != null && value.length() == 0 ) value = null; this.type = type; this.attrMap = attrMap; this.value = value; } @Override public Element filter( Object content ) { if ( content instanceof Element == false ) return null; Element node = (Element)content; String tmp; if ( type != null ) { if ( type.equals( node.getName() ) == false ) { return null; } } if ( attrMap != null ) { for ( Map.Entry<String,String> entry : attrMap.entrySet() ) { String attrName = entry.getKey(); String attrValue = entry.getValue(); tmp = node.getAttributeValue( attrName ); if ( attrValue.equals( tmp ) == false ) { return null; } } } if ( value != null ) { if ( value.equals( node.getTextTrim() ) == false ) { return null; } } return node; } } /** * Matches elements with child elements that match a filter. * If the filter is null, matches all elements with children. */ protected static class WithChildFilter extends AbstractFilter<Element> { private String type; private Filter<Element> childFilter; public WithChildFilter( Filter<Element> childFilter ) { this( null, childFilter ); } public WithChildFilter( String type, Filter<Element> childFilter ) { this.type = type; this.childFilter = childFilter; } @Override public Element filter( Object content ) { if ( content instanceof Element == false ) return null; Element node = (Element)content; if ( type != null ) { if ( type.equals( node.getName() ) == false ) { return null; } } if ( childFilter != null ) { if ( node.getContent( childFilter ).isEmpty() ) return null; } else if ( node.getChildren().isEmpty() ) { return null; } return node; } } }
false
true
protected List<Element> handleModFind( Element contextNode, Element node ) { List<Element> result = null; if ( node.getNamespace().equals( modNS ) ) { if ( node.getName().equals( "findName" ) ) { String searchName = node.getAttributeValue( "name" ); String searchType = node.getAttributeValue( "type" ); boolean searchReverse = getAttributeBooleanValue( node, "reverse", true ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", 1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchName == null || searchName.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> requires a name attribute (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchType != null && searchType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Map<String,String> attrMap = new HashMap<String,String>(); attrMap.put( "name", searchName ); LikeFilter searchFilter = new LikeFilter( searchType, attrMap, null ); List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } if ( matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } else if ( node.getName().equals( "findLike" ) ) { String searchType = node.getAttributeValue( "type" ); boolean searchReverse = getAttributeBooleanValue( node, "reverse", false ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", -1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchType != null && searchType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Map<String,String> attrMap = new HashMap<String,String>(); String searchValue = null; Element selectorNode = node.getChild( "selector", modNS ); if ( selectorNode != null ) { for ( Attribute attr : selectorNode.getAttributes() ) { if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) { // Blank element values can't be detected as different from absent values (never null). // Forbid "" attributes for consistency. :/ if ( attr.getValue().length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> attributes, when present, can't be empty (%s).", selectorNode.getName(), getPathToRoot(selectorNode) ) ); attrMap.put( attr.getName(), attr.getValue() ); } } searchValue = selectorNode.getTextTrim(); // Never null, but often "". if ( searchValue.length() > 0 ) searchValue = null; } LikeFilter searchFilter = new LikeFilter( searchType, attrMap, searchValue ); List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } if ( matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } else if ( node.getName().equals( "findWithChildLike" ) ) { String searchType = node.getAttributeValue( "type" ); String searchChildType = node.getAttributeValue( "child-type" ); boolean searchReverse = getAttributeBooleanValue( node, "reverse", false ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", -1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchType != null && searchType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchChildType != null && searchChildType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> child-type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Map<String,String> attrMap = new HashMap<String,String>(); String searchValue = null; Element selectorNode = node.getChild( "selector", modNS ); if ( selectorNode != null ) { for ( Attribute attr : selectorNode.getAttributes() ) { if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) { // TODO: Forbid "" attributes, because blank value doesn't work? attrMap.put( attr.getName(), attr.getValue() ); } } searchValue = selectorNode.getTextTrim(); // Never null, but often "". if ( searchValue.length() > 0 ) searchValue = null; } LikeFilter searchChildFilter = new LikeFilter( searchChildType, attrMap, searchValue ); WithChildFilter searchFilter = new WithChildFilter( searchType, searchChildFilter ); List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } if ( matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } else if ( node.getName().equals( "findComposite" ) ) { boolean searchReverse = getAttributeBooleanValue( node, "reverse", false ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", -1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Element parNode = node.getChild( "par", modNS ); if ( parNode == null ) throw new IllegalArgumentException( String.format( "<%s> requires a <par> tag (%s).", node.getName(), getPathToRoot(node) ) ); List<Element> matchedNodes = handleModPar( contextNode, parNode ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } if ( matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } } return result; }
protected List<Element> handleModFind( Element contextNode, Element node ) { List<Element> result = null; if ( node.getNamespace().equals( modNS ) ) { if ( node.getName().equals( "findName" ) ) { String searchName = node.getAttributeValue( "name" ); String searchType = node.getAttributeValue( "type" ); boolean searchReverse = getAttributeBooleanValue( node, "reverse", true ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", 1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchName == null || searchName.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> requires a name attribute (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchType != null && searchType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Map<String,String> attrMap = new HashMap<String,String>(); attrMap.put( "name", searchName ); LikeFilter searchFilter = new LikeFilter( searchType, attrMap, null ); List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } if ( panic && matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } else if ( node.getName().equals( "findLike" ) ) { String searchType = node.getAttributeValue( "type" ); boolean searchReverse = getAttributeBooleanValue( node, "reverse", false ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", -1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchType != null && searchType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Map<String,String> attrMap = new HashMap<String,String>(); String searchValue = null; Element selectorNode = node.getChild( "selector", modNS ); if ( selectorNode != null ) { for ( Attribute attr : selectorNode.getAttributes() ) { if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) { // Blank element values can't be detected as different from absent values (never null). // Forbid "" attributes for consistency. :/ if ( attr.getValue().length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> attributes, when present, can't be empty (%s).", selectorNode.getName(), getPathToRoot(selectorNode) ) ); attrMap.put( attr.getName(), attr.getValue() ); } } searchValue = selectorNode.getTextTrim(); // Never null, but often "". if ( searchValue.length() > 0 ) searchValue = null; } LikeFilter searchFilter = new LikeFilter( searchType, attrMap, searchValue ); List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } if ( panic && matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } else if ( node.getName().equals( "findWithChildLike" ) ) { String searchType = node.getAttributeValue( "type" ); String searchChildType = node.getAttributeValue( "child-type" ); boolean searchReverse = getAttributeBooleanValue( node, "reverse", false ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", -1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchType != null && searchType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchChildType != null && searchChildType.length() == 0 ) throw new IllegalArgumentException( String.format( "<%s> child-type attribute, when present, can't be empty (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Map<String,String> attrMap = new HashMap<String,String>(); String searchValue = null; Element selectorNode = node.getChild( "selector", modNS ); if ( selectorNode != null ) { for ( Attribute attr : selectorNode.getAttributes() ) { if ( attr.getNamespace().equals( Namespace.NO_NAMESPACE ) ) { // TODO: Forbid "" attributes, because blank value doesn't work? attrMap.put( attr.getName(), attr.getValue() ); } } searchValue = selectorNode.getTextTrim(); // Never null, but often "". if ( searchValue.length() > 0 ) searchValue = null; } LikeFilter searchChildFilter = new LikeFilter( searchChildType, attrMap, searchValue ); WithChildFilter searchFilter = new WithChildFilter( searchType, searchChildFilter ); List<Element> matchedNodes = new ArrayList<Element>( contextNode.getContent( searchFilter ) ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } if ( panic && matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } else if ( node.getName().equals( "findComposite" ) ) { boolean searchReverse = getAttributeBooleanValue( node, "reverse", false ); int searchStart = getAttributeIntValue( node, "start", 0 ); int searchLimit = getAttributeIntValue( node, "limit", -1 ); boolean panic = getAttributeBooleanValue( node, "panic", false ); if ( searchStart < 0 ) throw new IllegalArgumentException( String.format( "<%s> 'start' attribute is not >= 0 (%s).", node.getName(), getPathToRoot(node) ) ); if ( searchLimit < -1 ) throw new IllegalArgumentException( String.format( "<%s> 'limit' attribute is not >= -1 (%s).", node.getName(), getPathToRoot(node) ) ); Element parNode = node.getChild( "par", modNS ); if ( parNode == null ) throw new IllegalArgumentException( String.format( "<%s> requires a <par> tag (%s).", node.getName(), getPathToRoot(node) ) ); List<Element> matchedNodes = handleModPar( contextNode, parNode ); if ( searchReverse ) Collections.reverse( matchedNodes ); if ( searchStart < matchedNodes.size() ) { if ( searchLimit > -1 ) { matchedNodes = matchedNodes.subList( searchStart, Math.max( matchedNodes.size(), searchStart + searchLimit ) ); } else if ( searchStart > 0 ) { matchedNodes = matchedNodes.subList( searchStart, matchedNodes.size() ); } } if ( panic && matchedNodes.isEmpty() ) throw new NoSuchElementException( String.format( "<%s> was set to require results but found none (%s).", node.getName(), getPathToRoot(node) ) ); result = matchedNodes; } } return result; }
diff --git a/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/hdf5/HDF5TreeExplorer.java b/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/hdf5/HDF5TreeExplorer.java index fcc1237..78acdc3 100644 --- a/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/hdf5/HDF5TreeExplorer.java +++ b/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/hdf5/HDF5TreeExplorer.java @@ -1,705 +1,705 @@ /* * Copyright 2012 Diamond Light Source Ltd. * * 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 uk.ac.diamond.scisoft.analysis.rcp.hdf5; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.ArrayUtils; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreePath; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PartInitException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.dataset.ILazyDataset; import uk.ac.diamond.scisoft.analysis.dataset.IndexIterator; import uk.ac.diamond.scisoft.analysis.hdf5.HDF5Attribute; import uk.ac.diamond.scisoft.analysis.hdf5.HDF5Dataset; import uk.ac.diamond.scisoft.analysis.hdf5.HDF5File; import uk.ac.diamond.scisoft.analysis.hdf5.HDF5Group; import uk.ac.diamond.scisoft.analysis.hdf5.HDF5Node; import uk.ac.diamond.scisoft.analysis.hdf5.HDF5NodeLink; import uk.ac.diamond.scisoft.analysis.io.DataHolder; import uk.ac.diamond.scisoft.analysis.io.HDF5Loader; import uk.ac.diamond.scisoft.analysis.rcp.explorers.AbstractExplorer; import uk.ac.diamond.scisoft.analysis.rcp.explorers.MetadataSelection; import uk.ac.diamond.scisoft.analysis.rcp.inspector.AxisChoice; import uk.ac.diamond.scisoft.analysis.rcp.inspector.AxisSelection; import uk.ac.diamond.scisoft.analysis.rcp.inspector.DatasetSelection; import uk.ac.diamond.scisoft.analysis.rcp.inspector.DatasetSelection.InspectorType; import uk.ac.diamond.scisoft.analysis.rcp.views.AsciiTextView; import uk.ac.gda.monitor.IMonitor; public class HDF5TreeExplorer extends AbstractExplorer implements ISelectionProvider { private static final Logger logger = LoggerFactory.getLogger(HDF5TreeExplorer.class); HDF5File tree = null; private HDF5TableTree tableTree = null; private Display display; private ILazyDataset cData; // chosen dataset List<AxisSelection> axes; // list of axes for each dimension private String filename; /** * Separator between (full) file name and node path */ public static final String HDF5FILENAME_NODEPATH_SEPARATOR = "#"; public static class HDF5Selection extends DatasetSelection { private String fileName; private String node; public HDF5Selection(InspectorType type, String filename, String node, List<AxisSelection> axes, ILazyDataset... dataset) { super(type, axes, dataset); this.fileName = filename; this.node = node; } @Override public boolean equals(Object other) { if (super.equals(other) && other instanceof HDF5Selection) { HDF5Selection that = (HDF5Selection) other; if (fileName == null && that.fileName == null) return node.equals(that.node); if (fileName != null && fileName.equals(that.fileName)) return node.equals(that.node); } return false; } @Override public int hashCode() { int hash = super.hashCode(); hash = hash * 17 + node.hashCode(); return hash; } @Override public String toString() { return node + " = " + super.toString(); } public String getFileName() { return fileName; } public String getNode() { return node; } } private HDF5Selection hdf5Selection; private Set<ISelectionChangedListener> cListeners; private Listener contextListener = null; private DataHolder holder; private boolean isOldGDA = false; // true if file has NXentry/program_name < GDAVERSION public HDF5TreeExplorer(Composite parent, IWorkbenchPartSite partSite, ISelectionChangedListener valueSelect) { super(parent, partSite, valueSelect); display = parent.getDisplay(); setLayout(new FillLayout()); if (metaValueListener != null) { contextListener = new Listener() { @Override public void handleEvent(Event event) { handleContextClick(); } }; } Listener singleListener = new Listener() { @Override public void handleEvent(Event event) { if (event.button == 1) handleSingleClick(); } }; tableTree = new HDF5TableTree(this, singleListener, new Listener() { @Override public void handleEvent(Event event) { if (event.button == 1) handleDoubleClick(); } }, contextListener); cListeners = new HashSet<ISelectionChangedListener>(); axes = new ArrayList<AxisSelection>(); } /** * populate a selection object */ public void selectHDF5Node(HDF5NodeLink link, InspectorType type) { if (link == null) return; if (handleSelectedNode(link)) { // provide selection setSelection(new HDF5Selection(type, filename, link.getFullName(), axes, cData)); } else logger.error("Could not process update of selected node: {}", link.getName()); } private boolean handleSelectedNode(HDF5NodeLink link) { if (processTextNode(link)) { return false; } if (!processSelectedNode(link)) return false; if (cData == null) return false; return true; } /** * Handle a node given by the path * @param path */ public void handleNode(String path) { HDF5NodeLink link = tree.findNodeLink(path); if (link != null) { if (handleSelectedNode(link)) { // provide selection setSelection(new HDF5Selection(InspectorType.LINE, filename, link.getName(), axes, cData)); return; } logger.debug("Could not handle selected node: {}", link.getName()); } logger.debug("Could not find selected node: {}", path); } private void handleContextClick() { IStructuredSelection selection = tableTree.getSelection(); try { // check if selection is valid for plotting if (selection != null) { Object obj = selection.getFirstElement(); String metaName = null; if (obj instanceof HDF5NodeLink) { metaName = ((HDF5NodeLink) obj).getFullName(); } else if (obj instanceof HDF5Attribute) { metaName = ((HDF5Attribute) obj).getFullName(); } if (metaName != null) { SelectionChangedEvent ce = new SelectionChangedEvent(this, new MetadataSelection(metaName)); metaValueListener.selectionChanged(ce); } } } catch (Exception e) { logger.error("Error processing selection: {}", e.getMessage()); } } private void handleSingleClick() { // Single click passes the standard tree selection on. IStructuredSelection selection = tableTree.getSelection(); SelectionChangedEvent e = new SelectionChangedEvent(this, selection); for (ISelectionChangedListener s : cListeners) s.selectionChanged(e); } private void handleDoubleClick() { final Cursor cursor = getCursor(); Cursor tempCursor = getDisplay().getSystemCursor(SWT.CURSOR_WAIT); if (tempCursor != null) setCursor(tempCursor); IStructuredSelection selection = tableTree.getSelection(); try { // check if selection is valid for plotting if (selection != null && selection.getFirstElement() instanceof HDF5NodeLink) { HDF5NodeLink link = (HDF5NodeLink) selection.getFirstElement(); selectHDF5Node(link, InspectorType.LINE); } } catch (Exception e) { logger.error("Error processing selection: {}", e.getMessage()); } finally { if (tempCursor != null) setCursor(cursor); } } private boolean processTextNode(HDF5NodeLink link) { HDF5Node node = link.getDestination(); if (!(node instanceof HDF5Dataset)) return false; HDF5Dataset dataset = (HDF5Dataset) node; if (!dataset.isString()) return false; try { getTextView().setData(dataset.getString()); return true; } catch (Exception e) { logger.error("Error processing text node {}: {}", link.getName(), e); } return false; } private static final String NXAXES = "axes"; private static final String NXAXIS = "axis"; private static final String NXLABEL = "label"; private static final String NXPRIMARY = "primary"; private static final String NXSIGNAL = "signal"; private static final String NXDATA = "NXdata"; private static final String NXNAME = "long_name"; private static final String SDS = "SDS"; private boolean processSelectedNode(HDF5NodeLink link) { // two cases: axis and primary or axes // iterate through each child to find axes and primary attributes HDF5Node node = link.getDestination(); List<AxisChoice> choices = new ArrayList<AxisChoice>(); HDF5Attribute axesAttr = null; HDF5Group gNode = null; HDF5Dataset dNode = null; // see if chosen node is a NXdata class HDF5Attribute stringAttr = node.getAttribute(HDF5File.NXCLASS); String nxClass = stringAttr != null ? stringAttr.getFirstElement() : null; if (nxClass == null || nxClass.equals(SDS)) { if (!(node instanceof HDF5Dataset)) return false; dNode = (HDF5Dataset) node; if (!dNode.isSupported()) return false; cData = dNode.getDataset(); axesAttr = dNode.getAttribute(NXAXES); gNode = (HDF5Group) link.getSource(); // before hunting for axes } else if (nxClass.equals(NXDATA)) { assert node instanceof HDF5Group; gNode = (HDF5Group) node; // find data (signal=1) and check for axes attribute Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator(); while (iter.hasNext()) { HDF5NodeLink l = iter.next(); if (l.isDestinationADataset()) { dNode = (HDF5Dataset) l.getDestination(); if (dNode.containsAttribute(NXSIGNAL) && dNode.isSupported()) { cData = dNode.getDataset(); axesAttr = dNode.getAttribute(NXAXES); break; // only one signal per NXdata item } dNode = null; } } } if (dNode == null) return false; // find possible long name stringAttr = dNode.getAttribute(NXNAME); if (stringAttr != null && stringAttr.isString()) cData.setName(stringAttr.getFirstElement()); // remove extraneous dimensions cData.squeeze(true); // set up slices int[] shape = cData.getShape(); int rank = shape.length; // scan children for SDS as possible axes (could be referenced by axes) @SuppressWarnings("null") Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator(); while (iter.hasNext()) { HDF5NodeLink l = iter.next(); if (l.isDestinationADataset()) { HDF5Dataset d = (HDF5Dataset) l.getDestination(); if (!d.isSupported() || d.isString() || dNode == d || d.containsAttribute(NXSIGNAL)) continue; ILazyDataset a = d.getDataset(); try { int[] s = a.getShape(); s = AbstractDataset.squeezeShape(s, true); if (s.length != 0) // don't make a 0D dataset a.squeeze(true); int[] ashape = a.getShape(); AxisChoice choice = new AxisChoice(a); stringAttr = d.getAttribute(NXNAME); if (stringAttr != null && stringAttr.isString()) choice.setLongName(stringAttr.getFirstElement()); HDF5Attribute attr = d.getAttribute(NXAXIS); HDF5Attribute attr_label = d.getAttribute(NXLABEL); int[] intAxis = null; if (attr != null) { if (attr.isString()) { String[] str = attr.getFirstElement().split(","); if (str.length == ashape.length) { intAxis = new int[str.length]; for (int i = 0; i < str.length; i++) { int j = Integer.parseInt(str[i]) - 1; - intAxis[i] = isOldGDA ? j : rank - j; // fix Fortran (column-major) dimension + intAxis[i] = isOldGDA ? j : rank - 1 - j; // fix Fortran (column-major) dimension } } } else { AbstractDataset attrd = attr.getValue(); if (attrd.getSize() == ashape.length) { intAxis = new int[attrd.getSize()]; IndexIterator it = attrd.getIterator(); int i = 0; while (it.hasNext()) { int j = (int) attrd.getElementLongAbs(it.index) - 1; - intAxis[i++] = isOldGDA ? j : rank - j; // fix Fortran (column-major) dimension + intAxis[i++] = isOldGDA ? j : rank - 1 - j; // fix Fortran (column-major) dimension } } } if (intAxis == null) { logger.warn("Axis attribute {} does not match rank", a.getName()); } else { // check that axis attribute matches data dimensions for (int i = 0; i < intAxis.length; i++) { int al = ashape[i]; int il = intAxis[i]; if (il < 0 || il >= rank || al != shape[il]) { intAxis = null; logger.warn("Axis attribute {} does not match shape", a.getName()); break; } } } } if (intAxis == null) { // remedy bogus or missing axis attribute by simply pairing matching dimension // lengths to the signal dataset shape (this may be wrong as transposes in // common dimension lengths can occur) logger.warn("Creating index mapping from axis shape"); Map<Integer, Integer> dims = new LinkedHashMap<Integer, Integer>(); for (int i = 0; i < rank; i++) { dims.put(i, shape[i]); } intAxis = new int[ashape.length]; for (int i = 0; i < intAxis.length; i++) { int al = ashape[i]; intAxis[i] = -1; for (int k : dims.keySet()) { if (al == dims.get(k)) { // find first signal dimension length that matches intAxis[i] = k; dims.remove(k); break; } } if (intAxis[i] == -1) throw new IllegalArgumentException( "Axis dimension does not match any data dimension"); } } choice.setIndexMapping(intAxis); if (attr_label != null) { if (attr_label.isString()) { int j = Integer.parseInt(attr_label.getFirstElement()) - 1; - choice.setAxisNumber(isOldGDA ? j : rank - j); // fix Fortran (column-major) dimension + choice.setAxisNumber(isOldGDA ? j : rank - 1 - j); // fix Fortran (column-major) dimension } else { int j = attr_label.getValue().getInt(0) - 1; - choice.setAxisNumber(isOldGDA ? j : rank - j); // fix Fortran (column-major) dimension + choice.setAxisNumber(isOldGDA ? j : rank - 1 - j); // fix Fortran (column-major) dimension } } else choice.setAxisNumber(intAxis[intAxis.length-1]); attr = d.getAttribute(NXPRIMARY); if (attr != null) { if (attr.isString()) { Integer intPrimary = Integer.parseInt(attr.getFirstElement()); choice.setPrimary(intPrimary); } else { AbstractDataset attrd = attr.getValue(); choice.setPrimary(attrd.getInt(0)); } } choices.add(choice); } catch (Exception e) { logger.warn("Axis attributes in {} are invalid - {}", a.getName(), e.getMessage()); continue; } } } List<String> aNames = new ArrayList<String>(); if (axesAttr != null) { // check axes attribute for list axes String axesStr = axesAttr.getFirstElement().trim(); if (axesStr.startsWith("[")) { // strip opening and closing brackets axesStr = axesStr.substring(1, axesStr.length() - 1); } // check if axes referenced by data's @axes tag exists String[] names = null; names = axesStr.split("[:,]"); for (String s : names) { boolean flg = false; for (AxisChoice c : choices) { if (c.equals(s)) { if (c.getRank() == 1) { // FIXME for N-D axes SDSes // this needs a standard, e.g. axis SDS can span signal dataset dimensions flg = true; break; } logger.warn("Referenced axis {} in tree node {} is not 1D", s, node); } } if (flg) { aNames.add(s); } else { logger.warn("Referenced axis {} does not exist in tree node {}", s, node); aNames.add(null); } } } // set up AxisSelector // build up list of choice per dimension axes.clear(); for (int i = 0; i < rank; i++) { int dim = shape[i]; AxisSelection aSel = new AxisSelection(dim); axes.add(i, null); // expand list for (AxisChoice c : choices) { if (c.getAxisNumber() == i) { // add if choice has been designated as for this dimension aSel.addChoice(c, c.getPrimary()); } else if (c.isDimensionUsed(i)) { // add if axis index mapping refers to this dimension aSel.addChoice(c, 0); } else if (aNames.contains(c.getName())) { // add if name is in list of axis names aSel.addChoice(c, 1); } } // add in an automatically generated axis with top order so it appears after primary axes AbstractDataset axis = AbstractDataset.arange(dim, AbstractDataset.INT32); axis.setName("dim:" + (i + 1)); AxisChoice newChoice = new AxisChoice(axis); newChoice.setAxisNumber(i); aSel.addChoice(newChoice, aSel.getMaxOrder() + 1); aSel.reorderChoices(); aSel.selectAxis(0); axes.set(i, aSel); } return true; } @Override public void dispose() { cListeners.clear(); super.dispose(); } private AsciiTextView getTextView() { AsciiTextView textView = null; // check if Dataset Table View is open try { textView = (AsciiTextView) site.getPage().showView(AsciiTextView.ID); } catch (PartInitException e) { logger.error("All over now! Cannot find ASCII text view: {} ", e); } return textView; } @Override public DataHolder loadFile(String fileName, IMonitor mon) throws Exception { if (fileName == filename) return holder; return new HDF5Loader(fileName).loadFile(mon); } @Override public void loadFileAndDisplay(String fileName, IMonitor mon) throws Exception { HDF5File ltree = new HDF5Loader(fileName).loadTree(mon); if (ltree != null) { holder = new DataHolder(); Map<String, ILazyDataset> map = HDF5Loader.createDatasetsMap(ltree.getGroup()); for (String n : map.keySet()) { holder.addDataset(n, map.get(n)); } holder.setMetadata(HDF5Loader.createMetaData(ltree)); setFilename(fileName); setHDF5Tree(ltree); } } /** * @return loaded tree or null */ public HDF5File getHDF5Tree() { return tree; } public void setHDF5Tree(HDF5File htree) { if (htree == null) return; tree = htree; isOldGDA = checkForOldGDAFile(); if (display != null) display.asyncExec(new Runnable() { @Override public void run() { tableTree.setInput(tree.getNodeLink()); display.update(); } }); } private static final String NXENTRY = "NXentry"; private static final String NXPROGRAM = "program_name"; private static final String GDAVERSIONSTRING = "GDA "; private static final int GDAMAJOR = 8; private static final int GDAMINOR = 20; private boolean checkForOldGDAFile() { Iterator<HDF5NodeLink> iter = tree.getGroup().getNodeLinkIterator(); while (iter.hasNext()) { HDF5NodeLink link = iter.next(); if (link.isDestinationAGroup()) { HDF5Group g = (HDF5Group) link.getDestination(); HDF5Attribute stringAttr = g.getAttribute(HDF5File.NXCLASS); if (stringAttr != null && stringAttr.isString() && NXENTRY.equals(stringAttr.getFirstElement())) { if (g.containsDataset(NXPROGRAM)) { HDF5Dataset d = g.getDataset(NXPROGRAM); if (d.isString()) { String s = d.getString().trim(); int i = s.indexOf(GDAVERSIONSTRING); if (i >= 0) { String v = s.substring(i+4, s.lastIndexOf(".")); int j = v.indexOf("."); int maj = Integer.parseInt(v.substring(0, j)); int min = Integer.parseInt(v.substring(j+1, v.length())); return maj < GDAMAJOR || (maj == GDAMAJOR && min < GDAMINOR); } } } } } } return false; } public void expandAll() { tableTree.expandAll(); } public void expandToLevel(int level) { tableTree.expandToLevel(level); } public void expandToLevel(Object link, int level) { tableTree.expandToLevel(link, level); } public TreePath[] getExpandedTreePaths() { return tableTree.getExpandedTreePaths(); } // selection provider interface @Override public void addSelectionChangedListener(ISelectionChangedListener listener) { if (cListeners.add(listener)) { return; } } @Override public ISelection getSelection() { return hdf5Selection; } @Override public void removeSelectionChangedListener(ISelectionChangedListener listener) { if (cListeners.remove(listener)) return; } @Override public void setSelection(ISelection selection) { if (selection instanceof HDF5Selection) hdf5Selection = (HDF5Selection) selection; else return; SelectionChangedEvent e = new SelectionChangedEvent(this, hdf5Selection); for (ISelectionChangedListener s : cListeners) s.selectionChanged(e); } /** * Set full name for file (including path) * @param fileName */ public void setFilename(String fileName) { filename = fileName; } public HDF5TableTree getTableTree(){ return tableTree; } }
false
true
private boolean processSelectedNode(HDF5NodeLink link) { // two cases: axis and primary or axes // iterate through each child to find axes and primary attributes HDF5Node node = link.getDestination(); List<AxisChoice> choices = new ArrayList<AxisChoice>(); HDF5Attribute axesAttr = null; HDF5Group gNode = null; HDF5Dataset dNode = null; // see if chosen node is a NXdata class HDF5Attribute stringAttr = node.getAttribute(HDF5File.NXCLASS); String nxClass = stringAttr != null ? stringAttr.getFirstElement() : null; if (nxClass == null || nxClass.equals(SDS)) { if (!(node instanceof HDF5Dataset)) return false; dNode = (HDF5Dataset) node; if (!dNode.isSupported()) return false; cData = dNode.getDataset(); axesAttr = dNode.getAttribute(NXAXES); gNode = (HDF5Group) link.getSource(); // before hunting for axes } else if (nxClass.equals(NXDATA)) { assert node instanceof HDF5Group; gNode = (HDF5Group) node; // find data (signal=1) and check for axes attribute Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator(); while (iter.hasNext()) { HDF5NodeLink l = iter.next(); if (l.isDestinationADataset()) { dNode = (HDF5Dataset) l.getDestination(); if (dNode.containsAttribute(NXSIGNAL) && dNode.isSupported()) { cData = dNode.getDataset(); axesAttr = dNode.getAttribute(NXAXES); break; // only one signal per NXdata item } dNode = null; } } } if (dNode == null) return false; // find possible long name stringAttr = dNode.getAttribute(NXNAME); if (stringAttr != null && stringAttr.isString()) cData.setName(stringAttr.getFirstElement()); // remove extraneous dimensions cData.squeeze(true); // set up slices int[] shape = cData.getShape(); int rank = shape.length; // scan children for SDS as possible axes (could be referenced by axes) @SuppressWarnings("null") Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator(); while (iter.hasNext()) { HDF5NodeLink l = iter.next(); if (l.isDestinationADataset()) { HDF5Dataset d = (HDF5Dataset) l.getDestination(); if (!d.isSupported() || d.isString() || dNode == d || d.containsAttribute(NXSIGNAL)) continue; ILazyDataset a = d.getDataset(); try { int[] s = a.getShape(); s = AbstractDataset.squeezeShape(s, true); if (s.length != 0) // don't make a 0D dataset a.squeeze(true); int[] ashape = a.getShape(); AxisChoice choice = new AxisChoice(a); stringAttr = d.getAttribute(NXNAME); if (stringAttr != null && stringAttr.isString()) choice.setLongName(stringAttr.getFirstElement()); HDF5Attribute attr = d.getAttribute(NXAXIS); HDF5Attribute attr_label = d.getAttribute(NXLABEL); int[] intAxis = null; if (attr != null) { if (attr.isString()) { String[] str = attr.getFirstElement().split(","); if (str.length == ashape.length) { intAxis = new int[str.length]; for (int i = 0; i < str.length; i++) { int j = Integer.parseInt(str[i]) - 1; intAxis[i] = isOldGDA ? j : rank - j; // fix Fortran (column-major) dimension } } } else { AbstractDataset attrd = attr.getValue(); if (attrd.getSize() == ashape.length) { intAxis = new int[attrd.getSize()]; IndexIterator it = attrd.getIterator(); int i = 0; while (it.hasNext()) { int j = (int) attrd.getElementLongAbs(it.index) - 1; intAxis[i++] = isOldGDA ? j : rank - j; // fix Fortran (column-major) dimension } } } if (intAxis == null) { logger.warn("Axis attribute {} does not match rank", a.getName()); } else { // check that axis attribute matches data dimensions for (int i = 0; i < intAxis.length; i++) { int al = ashape[i]; int il = intAxis[i]; if (il < 0 || il >= rank || al != shape[il]) { intAxis = null; logger.warn("Axis attribute {} does not match shape", a.getName()); break; } } } } if (intAxis == null) { // remedy bogus or missing axis attribute by simply pairing matching dimension // lengths to the signal dataset shape (this may be wrong as transposes in // common dimension lengths can occur) logger.warn("Creating index mapping from axis shape"); Map<Integer, Integer> dims = new LinkedHashMap<Integer, Integer>(); for (int i = 0; i < rank; i++) { dims.put(i, shape[i]); } intAxis = new int[ashape.length]; for (int i = 0; i < intAxis.length; i++) { int al = ashape[i]; intAxis[i] = -1; for (int k : dims.keySet()) { if (al == dims.get(k)) { // find first signal dimension length that matches intAxis[i] = k; dims.remove(k); break; } } if (intAxis[i] == -1) throw new IllegalArgumentException( "Axis dimension does not match any data dimension"); } } choice.setIndexMapping(intAxis); if (attr_label != null) { if (attr_label.isString()) { int j = Integer.parseInt(attr_label.getFirstElement()) - 1; choice.setAxisNumber(isOldGDA ? j : rank - j); // fix Fortran (column-major) dimension } else { int j = attr_label.getValue().getInt(0) - 1; choice.setAxisNumber(isOldGDA ? j : rank - j); // fix Fortran (column-major) dimension } } else choice.setAxisNumber(intAxis[intAxis.length-1]); attr = d.getAttribute(NXPRIMARY); if (attr != null) { if (attr.isString()) { Integer intPrimary = Integer.parseInt(attr.getFirstElement()); choice.setPrimary(intPrimary); } else { AbstractDataset attrd = attr.getValue(); choice.setPrimary(attrd.getInt(0)); } } choices.add(choice); } catch (Exception e) { logger.warn("Axis attributes in {} are invalid - {}", a.getName(), e.getMessage()); continue; } } } List<String> aNames = new ArrayList<String>(); if (axesAttr != null) { // check axes attribute for list axes String axesStr = axesAttr.getFirstElement().trim(); if (axesStr.startsWith("[")) { // strip opening and closing brackets axesStr = axesStr.substring(1, axesStr.length() - 1); } // check if axes referenced by data's @axes tag exists String[] names = null; names = axesStr.split("[:,]"); for (String s : names) { boolean flg = false; for (AxisChoice c : choices) { if (c.equals(s)) { if (c.getRank() == 1) { // FIXME for N-D axes SDSes // this needs a standard, e.g. axis SDS can span signal dataset dimensions flg = true; break; } logger.warn("Referenced axis {} in tree node {} is not 1D", s, node); } } if (flg) { aNames.add(s); } else { logger.warn("Referenced axis {} does not exist in tree node {}", s, node); aNames.add(null); } } } // set up AxisSelector // build up list of choice per dimension axes.clear(); for (int i = 0; i < rank; i++) { int dim = shape[i]; AxisSelection aSel = new AxisSelection(dim); axes.add(i, null); // expand list for (AxisChoice c : choices) { if (c.getAxisNumber() == i) { // add if choice has been designated as for this dimension aSel.addChoice(c, c.getPrimary()); } else if (c.isDimensionUsed(i)) { // add if axis index mapping refers to this dimension aSel.addChoice(c, 0); } else if (aNames.contains(c.getName())) { // add if name is in list of axis names aSel.addChoice(c, 1); } } // add in an automatically generated axis with top order so it appears after primary axes AbstractDataset axis = AbstractDataset.arange(dim, AbstractDataset.INT32); axis.setName("dim:" + (i + 1)); AxisChoice newChoice = new AxisChoice(axis); newChoice.setAxisNumber(i); aSel.addChoice(newChoice, aSel.getMaxOrder() + 1); aSel.reorderChoices(); aSel.selectAxis(0); axes.set(i, aSel); } return true; }
private boolean processSelectedNode(HDF5NodeLink link) { // two cases: axis and primary or axes // iterate through each child to find axes and primary attributes HDF5Node node = link.getDestination(); List<AxisChoice> choices = new ArrayList<AxisChoice>(); HDF5Attribute axesAttr = null; HDF5Group gNode = null; HDF5Dataset dNode = null; // see if chosen node is a NXdata class HDF5Attribute stringAttr = node.getAttribute(HDF5File.NXCLASS); String nxClass = stringAttr != null ? stringAttr.getFirstElement() : null; if (nxClass == null || nxClass.equals(SDS)) { if (!(node instanceof HDF5Dataset)) return false; dNode = (HDF5Dataset) node; if (!dNode.isSupported()) return false; cData = dNode.getDataset(); axesAttr = dNode.getAttribute(NXAXES); gNode = (HDF5Group) link.getSource(); // before hunting for axes } else if (nxClass.equals(NXDATA)) { assert node instanceof HDF5Group; gNode = (HDF5Group) node; // find data (signal=1) and check for axes attribute Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator(); while (iter.hasNext()) { HDF5NodeLink l = iter.next(); if (l.isDestinationADataset()) { dNode = (HDF5Dataset) l.getDestination(); if (dNode.containsAttribute(NXSIGNAL) && dNode.isSupported()) { cData = dNode.getDataset(); axesAttr = dNode.getAttribute(NXAXES); break; // only one signal per NXdata item } dNode = null; } } } if (dNode == null) return false; // find possible long name stringAttr = dNode.getAttribute(NXNAME); if (stringAttr != null && stringAttr.isString()) cData.setName(stringAttr.getFirstElement()); // remove extraneous dimensions cData.squeeze(true); // set up slices int[] shape = cData.getShape(); int rank = shape.length; // scan children for SDS as possible axes (could be referenced by axes) @SuppressWarnings("null") Iterator<HDF5NodeLink> iter = gNode.getNodeLinkIterator(); while (iter.hasNext()) { HDF5NodeLink l = iter.next(); if (l.isDestinationADataset()) { HDF5Dataset d = (HDF5Dataset) l.getDestination(); if (!d.isSupported() || d.isString() || dNode == d || d.containsAttribute(NXSIGNAL)) continue; ILazyDataset a = d.getDataset(); try { int[] s = a.getShape(); s = AbstractDataset.squeezeShape(s, true); if (s.length != 0) // don't make a 0D dataset a.squeeze(true); int[] ashape = a.getShape(); AxisChoice choice = new AxisChoice(a); stringAttr = d.getAttribute(NXNAME); if (stringAttr != null && stringAttr.isString()) choice.setLongName(stringAttr.getFirstElement()); HDF5Attribute attr = d.getAttribute(NXAXIS); HDF5Attribute attr_label = d.getAttribute(NXLABEL); int[] intAxis = null; if (attr != null) { if (attr.isString()) { String[] str = attr.getFirstElement().split(","); if (str.length == ashape.length) { intAxis = new int[str.length]; for (int i = 0; i < str.length; i++) { int j = Integer.parseInt(str[i]) - 1; intAxis[i] = isOldGDA ? j : rank - 1 - j; // fix Fortran (column-major) dimension } } } else { AbstractDataset attrd = attr.getValue(); if (attrd.getSize() == ashape.length) { intAxis = new int[attrd.getSize()]; IndexIterator it = attrd.getIterator(); int i = 0; while (it.hasNext()) { int j = (int) attrd.getElementLongAbs(it.index) - 1; intAxis[i++] = isOldGDA ? j : rank - 1 - j; // fix Fortran (column-major) dimension } } } if (intAxis == null) { logger.warn("Axis attribute {} does not match rank", a.getName()); } else { // check that axis attribute matches data dimensions for (int i = 0; i < intAxis.length; i++) { int al = ashape[i]; int il = intAxis[i]; if (il < 0 || il >= rank || al != shape[il]) { intAxis = null; logger.warn("Axis attribute {} does not match shape", a.getName()); break; } } } } if (intAxis == null) { // remedy bogus or missing axis attribute by simply pairing matching dimension // lengths to the signal dataset shape (this may be wrong as transposes in // common dimension lengths can occur) logger.warn("Creating index mapping from axis shape"); Map<Integer, Integer> dims = new LinkedHashMap<Integer, Integer>(); for (int i = 0; i < rank; i++) { dims.put(i, shape[i]); } intAxis = new int[ashape.length]; for (int i = 0; i < intAxis.length; i++) { int al = ashape[i]; intAxis[i] = -1; for (int k : dims.keySet()) { if (al == dims.get(k)) { // find first signal dimension length that matches intAxis[i] = k; dims.remove(k); break; } } if (intAxis[i] == -1) throw new IllegalArgumentException( "Axis dimension does not match any data dimension"); } } choice.setIndexMapping(intAxis); if (attr_label != null) { if (attr_label.isString()) { int j = Integer.parseInt(attr_label.getFirstElement()) - 1; choice.setAxisNumber(isOldGDA ? j : rank - 1 - j); // fix Fortran (column-major) dimension } else { int j = attr_label.getValue().getInt(0) - 1; choice.setAxisNumber(isOldGDA ? j : rank - 1 - j); // fix Fortran (column-major) dimension } } else choice.setAxisNumber(intAxis[intAxis.length-1]); attr = d.getAttribute(NXPRIMARY); if (attr != null) { if (attr.isString()) { Integer intPrimary = Integer.parseInt(attr.getFirstElement()); choice.setPrimary(intPrimary); } else { AbstractDataset attrd = attr.getValue(); choice.setPrimary(attrd.getInt(0)); } } choices.add(choice); } catch (Exception e) { logger.warn("Axis attributes in {} are invalid - {}", a.getName(), e.getMessage()); continue; } } } List<String> aNames = new ArrayList<String>(); if (axesAttr != null) { // check axes attribute for list axes String axesStr = axesAttr.getFirstElement().trim(); if (axesStr.startsWith("[")) { // strip opening and closing brackets axesStr = axesStr.substring(1, axesStr.length() - 1); } // check if axes referenced by data's @axes tag exists String[] names = null; names = axesStr.split("[:,]"); for (String s : names) { boolean flg = false; for (AxisChoice c : choices) { if (c.equals(s)) { if (c.getRank() == 1) { // FIXME for N-D axes SDSes // this needs a standard, e.g. axis SDS can span signal dataset dimensions flg = true; break; } logger.warn("Referenced axis {} in tree node {} is not 1D", s, node); } } if (flg) { aNames.add(s); } else { logger.warn("Referenced axis {} does not exist in tree node {}", s, node); aNames.add(null); } } } // set up AxisSelector // build up list of choice per dimension axes.clear(); for (int i = 0; i < rank; i++) { int dim = shape[i]; AxisSelection aSel = new AxisSelection(dim); axes.add(i, null); // expand list for (AxisChoice c : choices) { if (c.getAxisNumber() == i) { // add if choice has been designated as for this dimension aSel.addChoice(c, c.getPrimary()); } else if (c.isDimensionUsed(i)) { // add if axis index mapping refers to this dimension aSel.addChoice(c, 0); } else if (aNames.contains(c.getName())) { // add if name is in list of axis names aSel.addChoice(c, 1); } } // add in an automatically generated axis with top order so it appears after primary axes AbstractDataset axis = AbstractDataset.arange(dim, AbstractDataset.INT32); axis.setName("dim:" + (i + 1)); AxisChoice newChoice = new AxisChoice(axis); newChoice.setAxisNumber(i); aSel.addChoice(newChoice, aSel.getMaxOrder() + 1); aSel.reorderChoices(); aSel.selectAxis(0); axes.set(i, aSel); } return true; }
diff --git a/src/com/mojang/mojam/entity/animation/ItemFallAnimation.java b/src/com/mojang/mojam/entity/animation/ItemFallAnimation.java index 3b2fc7d9..72dfd86b 100644 --- a/src/com/mojang/mojam/entity/animation/ItemFallAnimation.java +++ b/src/com/mojang/mojam/entity/animation/ItemFallAnimation.java @@ -1,32 +1,35 @@ package com.mojang.mojam.entity.animation; import com.mojang.mojam.level.tile.HoleTile; import com.mojang.mojam.level.tile.Tile; import com.mojang.mojam.screen.Bitmap; import com.mojang.mojam.screen.Screen; public class ItemFallAnimation extends Animation { Bitmap fallingImage; boolean isHarvester = false; public ItemFallAnimation(double x, double y, Bitmap fallingImage) { super(x, y, 60); // @random this.fallingImage = fallingImage; } public void render(Screen screen) { int anim; anim = life * 12 / duration; double posY = pos.y; if (!isHarvester) posY += Tile.HEIGHT; screen.blit(fallingImage, pos.x, posY - anim*3); - Tile tileBelow = level.getTile((int)pos.x/Tile.WIDTH, (int)pos.y/Tile.WIDTH+1); - if (tileBelow.getName() != HoleTile.NAME) tileBelow.render(screen); + Tile tileBelow; + for(int i = 1; i <= 2; i++) { + tileBelow = level.getTile((int)pos.x/Tile.WIDTH, (int)pos.y/Tile.WIDTH+i); + if (tileBelow.getName() != HoleTile.NAME) tileBelow.render(screen); + } } public void setHarvester(){ isHarvester = true; } }
true
true
public void render(Screen screen) { int anim; anim = life * 12 / duration; double posY = pos.y; if (!isHarvester) posY += Tile.HEIGHT; screen.blit(fallingImage, pos.x, posY - anim*3); Tile tileBelow = level.getTile((int)pos.x/Tile.WIDTH, (int)pos.y/Tile.WIDTH+1); if (tileBelow.getName() != HoleTile.NAME) tileBelow.render(screen); }
public void render(Screen screen) { int anim; anim = life * 12 / duration; double posY = pos.y; if (!isHarvester) posY += Tile.HEIGHT; screen.blit(fallingImage, pos.x, posY - anim*3); Tile tileBelow; for(int i = 1; i <= 2; i++) { tileBelow = level.getTile((int)pos.x/Tile.WIDTH, (int)pos.y/Tile.WIDTH+i); if (tileBelow.getName() != HoleTile.NAME) tileBelow.render(screen); } }
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java b/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java index 987594c88..71c8f8c8d 100644 --- a/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java +++ b/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java @@ -1,507 +1,507 @@ 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.HashMap; import java.util.List; import java.util.Map; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.CannedTokenStream; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.analysis.MockPayloadAnalyzer; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.IntField; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.FieldInfo.IndexOptions; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.FieldCache; import org.apache.lucene.store.Directory; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.English; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.LuceneTestCase.SuppressCodecs; import org.apache.lucene.util._TestUtil; // TODO: we really need to test indexingoffsets, but then getting only docs / docs + freqs. // not all codecs store prx separate... // TODO: fix sep codec to index offsets so we can greatly reduce this list! @SuppressCodecs({"MockFixedIntBlock", "MockVariableIntBlock", "MockSep", "MockRandom"}) public class TestPostingsOffsets extends LuceneTestCase { IndexWriterConfig iwc; public void setUp() throws Exception { super.setUp(); iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())); } public void testBasic() throws Exception { Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc); Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); if (random().nextBoolean()) { ft.setStoreTermVectors(true); ft.setStoreTermVectorPositions(random().nextBoolean()); ft.setStoreTermVectorOffsets(random().nextBoolean()); } Token[] tokens = new Token[] { makeToken("a", 1, 0, 6), makeToken("b", 1, 8, 9), makeToken("a", 1, 9, 17), makeToken("c", 1, 19, 50), }; doc.add(new Field("content", new CannedTokenStream(tokens), ft)); w.addDocument(doc); IndexReader r = w.getReader(); w.close(); DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("a"), true); assertNotNull(dp); assertEquals(0, dp.nextDoc()); assertEquals(2, dp.freq()); assertEquals(0, dp.nextPosition()); assertEquals(0, dp.startOffset()); assertEquals(6, dp.endOffset()); assertEquals(2, dp.nextPosition()); assertEquals(9, dp.startOffset()); assertEquals(17, dp.endOffset()); assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc()); dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("b"), true); assertNotNull(dp); assertEquals(0, dp.nextDoc()); assertEquals(1, dp.freq()); assertEquals(1, dp.nextPosition()); assertEquals(8, dp.startOffset()); assertEquals(9, dp.endOffset()); assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc()); dp = MultiFields.getTermPositionsEnum(r, null, "content", new BytesRef("c"), true); assertNotNull(dp); assertEquals(0, dp.nextDoc()); assertEquals(1, dp.freq()); assertEquals(3, dp.nextPosition()); assertEquals(19, dp.startOffset()); assertEquals(50, dp.endOffset()); assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc()); r.close(); dir.close(); } public void testSkipping() throws Exception { doTestNumbers(false); } public void testPayloads() throws Exception { doTestNumbers(true); } public void doTestNumbers(boolean withPayloads) throws Exception { Directory dir = newDirectory(); Analyzer analyzer = withPayloads ? new MockPayloadAnalyzer() : new MockAnalyzer(random()); iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, analyzer); iwc.setMergePolicy(newLogMergePolicy()); // will rely on docids a bit for skipping RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc); FieldType ft = new FieldType(TextField.TYPE_STORED); ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); if (random().nextBoolean()) { ft.setStoreTermVectors(true); ft.setStoreTermVectorOffsets(random().nextBoolean()); ft.setStoreTermVectorPositions(random().nextBoolean()); } int numDocs = atLeast(500); for (int i = 0; i < numDocs; i++) { Document doc = new Document(); doc.add(new Field("numbers", English.intToEnglish(i), ft)); doc.add(new Field("oddeven", (i % 2) == 0 ? "even" : "odd", ft)); doc.add(new StringField("id", "" + i, Field.Store.NO)); w.addDocument(doc); } IndexReader reader = w.getReader(); w.close(); String terms[] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "hundred" }; for (String term : terms) { DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(reader, null, "numbers", new BytesRef(term), true); int doc; while((doc = dp.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { String storedNumbers = reader.document(doc).get("numbers"); int freq = dp.freq(); for (int i = 0; i < freq; i++) { dp.nextPosition(); int start = dp.startOffset(); assert start >= 0; int end = dp.endOffset(); assert end >= 0 && end >= start; // check that the offsets correspond to the term in the src text assertTrue(storedNumbers.substring(start, end).equals(term)); if (withPayloads) { // check that we have a payload and it starts with "pos" assertTrue(dp.hasPayload()); BytesRef payload = dp.getPayload(); assertTrue(payload.utf8ToString().startsWith("pos:")); } // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer! } } } // check we can skip correctly int numSkippingTests = atLeast(50); for (int j = 0; j < numSkippingTests; j++) { int num = _TestUtil.nextInt(random(), 100, Math.min(numDocs-1, 999)); DocsAndPositionsEnum dp = MultiFields.getTermPositionsEnum(reader, null, "numbers", new BytesRef("hundred"), true); int doc = dp.advance(num); assertEquals(num, doc); int freq = dp.freq(); for (int i = 0; i < freq; i++) { String storedNumbers = reader.document(doc).get("numbers"); dp.nextPosition(); int start = dp.startOffset(); assert start >= 0; int end = dp.endOffset(); assert end >= 0 && end >= start; // check that the offsets correspond to the term in the src text assertTrue(storedNumbers.substring(start, end).equals("hundred")); if (withPayloads) { // check that we have a payload and it starts with "pos" assertTrue(dp.hasPayload()); BytesRef payload = dp.getPayload(); assertTrue(payload.utf8ToString().startsWith("pos:")); } // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer! } } // check that other fields (without offsets) work correctly for (int i = 0; i < numDocs; i++) { DocsEnum dp = MultiFields.getTermDocsEnum(reader, null, "id", new BytesRef("" + i), false); assertEquals(i, dp.nextDoc()); assertEquals(DocIdSetIterator.NO_MORE_DOCS, dp.nextDoc()); } reader.close(); dir.close(); } public void testRandom() throws Exception { // token -> docID -> tokens final Map<String,Map<Integer,List<Token>>> actualTokens = new HashMap<String,Map<Integer,List<Token>>>(); Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc); final int numDocs = atLeast(20); //final int numDocs = atLeast(5); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); // TODO: randomize what IndexOptions we use; also test // changing this up in one IW buffered segment...: ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); if (random().nextBoolean()) { ft.setStoreTermVectors(true); ft.setStoreTermVectorOffsets(random().nextBoolean()); ft.setStoreTermVectorPositions(random().nextBoolean()); } for(int docCount=0;docCount<numDocs;docCount++) { Document doc = new Document(); doc.add(new IntField("id", docCount, Field.Store.NO)); List<Token> tokens = new ArrayList<Token>(); final int numTokens = atLeast(100); //final int numTokens = atLeast(20); int pos = -1; int offset = 0; //System.out.println("doc id=" + docCount); for(int tokenCount=0;tokenCount<numTokens;tokenCount++) { final String text; if (random().nextBoolean()) { text = "a"; } else if (random().nextBoolean()) { text = "b"; } else if (random().nextBoolean()) { text = "c"; } else { text = "d"; } int posIncr = random().nextBoolean() ? 1 : random().nextInt(5); if (tokenCount == 0 && posIncr == 0) { posIncr = 1; } final int offIncr = random().nextBoolean() ? 0 : random().nextInt(5); final int tokenOffset = random().nextInt(5); final Token token = makeToken(text, posIncr, offset+offIncr, offset+offIncr+tokenOffset); if (!actualTokens.containsKey(text)) { actualTokens.put(text, new HashMap<Integer,List<Token>>()); } final Map<Integer,List<Token>> postingsByDoc = actualTokens.get(text); if (!postingsByDoc.containsKey(docCount)) { postingsByDoc.put(docCount, new ArrayList<Token>()); } postingsByDoc.get(docCount).add(token); tokens.add(token); pos += posIncr; // stuff abs position into type: token.setType(""+pos); offset += offIncr + tokenOffset; //System.out.println(" " + token + " posIncr=" + token.getPositionIncrement() + " pos=" + pos + " off=" + token.startOffset() + "/" + token.endOffset() + " (freq=" + postingsByDoc.get(docCount).size() + ")"); } doc.add(new Field("content", new CannedTokenStream(tokens.toArray(new Token[tokens.size()])), ft)); w.addDocument(doc); } final DirectoryReader r = w.getReader(); w.close(); final String[] terms = new String[] {"a", "b", "c", "d"}; for(IndexReader reader : r.getSequentialSubReaders()) { // TODO: improve this AtomicReader sub = (AtomicReader) reader; //System.out.println("\nsub=" + sub); final TermsEnum termsEnum = sub.fields().terms("content").iterator(null); DocsEnum docs = null; DocsAndPositionsEnum docsAndPositions = null; DocsAndPositionsEnum docsAndPositionsAndOffsets = null; final int docIDToID[] = FieldCache.DEFAULT.getInts(sub, "id", false); for(String term : terms) { //System.out.println(" term=" + term); if (termsEnum.seekExact(new BytesRef(term), random().nextBoolean())) { docs = termsEnum.docs(null, docs, true); assertNotNull(docs); int doc; //System.out.println(" doc/freq"); while((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]); //System.out.println(" doc=" + docIDToID[doc] + " docID=" + doc + " " + expected.size() + " freq"); assertNotNull(expected); assertEquals(expected.size(), docs.freq()); } docsAndPositions = termsEnum.docsAndPositions(null, docsAndPositions, false); assertNotNull(docsAndPositions); //System.out.println(" doc/freq/pos"); while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]); //System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq"); assertNotNull(expected); assertEquals(expected.size(), docsAndPositions.freq()); for(Token token : expected) { int pos = Integer.parseInt(token.type()); //System.out.println(" pos=" + pos); assertEquals(pos, docsAndPositions.nextPosition()); } } docsAndPositionsAndOffsets = termsEnum.docsAndPositions(null, docsAndPositions, true); assertNotNull(docsAndPositionsAndOffsets); //System.out.println(" doc/freq/pos/offs"); - while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { + while((doc = docsAndPositionsAndOffsets.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]); //System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq"); assertNotNull(expected); - assertEquals(expected.size(), docsAndPositions.freq()); + assertEquals(expected.size(), docsAndPositionsAndOffsets.freq()); for(Token token : expected) { int pos = Integer.parseInt(token.type()); //System.out.println(" pos=" + pos); - assertEquals(pos, docsAndPositions.nextPosition()); - assertEquals(token.startOffset(), docsAndPositions.startOffset()); - assertEquals(token.endOffset(), docsAndPositions.endOffset()); + assertEquals(pos, docsAndPositionsAndOffsets.nextPosition()); + assertEquals(token.startOffset(), docsAndPositionsAndOffsets.startOffset()); + assertEquals(token.endOffset(), docsAndPositionsAndOffsets.endOffset()); } } } } // TODO: test advance: } r.close(); dir.close(); } public void testWithUnindexedFields() throws Exception { Directory dir = newDirectory(); RandomIndexWriter riw = new RandomIndexWriter(random(), dir, iwc); for (int i = 0; i < 100; i++) { Document doc = new Document(); // ensure at least one doc is indexed with offsets if (i < 99 && random().nextInt(2) == 0) { // stored only FieldType ft = new FieldType(); ft.setIndexed(false); ft.setStored(true); doc.add(new Field("foo", "boo!", ft)); } else { FieldType ft = new FieldType(TextField.TYPE_STORED); ft.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); if (random().nextBoolean()) { // store some term vectors for the checkindex cross-check ft.setStoreTermVectors(true); ft.setStoreTermVectorPositions(true); ft.setStoreTermVectorOffsets(true); } doc.add(new Field("foo", "bar", ft)); } riw.addDocument(doc); } CompositeReader ir = riw.getReader(); SlowCompositeReaderWrapper slow = new SlowCompositeReaderWrapper(ir); FieldInfos fis = slow.getFieldInfos(); assertEquals(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, fis.fieldInfo("foo").getIndexOptions()); slow.close(); ir.close(); riw.close(); dir.close(); } public void testAddFieldTwice() throws Exception { Directory dir = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), dir); Document doc = new Document(); FieldType customType3 = new FieldType(TextField.TYPE_STORED); customType3.setStoreTermVectors(true); customType3.setStoreTermVectorPositions(true); customType3.setStoreTermVectorOffsets(true); customType3.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); doc.add(new Field("content3", "here is more content with aaa aaa aaa", customType3)); doc.add(new Field("content3", "here is more content with aaa aaa aaa", customType3)); iw.addDocument(doc); iw.close(); dir.close(); // checkindex } // NOTE: the next two tests aren't that good as we need an EvilToken... public void testNegativeOffsets() throws Exception { try { checkTokens(new Token[] { makeToken("foo", 1, -1, -1) }); fail(); } catch (IllegalArgumentException expected) { //expected } } public void testIllegalOffsets() throws Exception { try { checkTokens(new Token[] { makeToken("foo", 1, 1, 0) }); fail(); } catch (IllegalArgumentException expected) { //expected } } public void testBackwardsOffsets() throws Exception { try { checkTokens(new Token[] { makeToken("foo", 1, 0, 3), makeToken("foo", 1, 4, 7), makeToken("foo", 0, 3, 6) }); fail(); } catch (IllegalArgumentException expected) { // expected } } public void testStackedTokens() throws Exception { checkTokens(new Token[] { makeToken("foo", 1, 0, 3), makeToken("foo", 0, 0, 3), makeToken("foo", 0, 0, 3) }); } public void testLegalbutVeryLargeOffsets() throws Exception { Directory dir = newDirectory(); IndexWriter iw = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, null)); Document doc = new Document(); Token t1 = new Token("foo", 0, Integer.MAX_VALUE-500); if (random().nextBoolean()) { t1.setPayload(new BytesRef("test")); } Token t2 = new Token("foo", Integer.MAX_VALUE-500, Integer.MAX_VALUE); TokenStream tokenStream = new CannedTokenStream( new Token[] { t1, t2 } ); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); // store some term vectors for the checkindex cross-check ft.setStoreTermVectors(true); ft.setStoreTermVectorPositions(true); ft.setStoreTermVectorOffsets(true); Field field = new Field("foo", tokenStream, ft); doc.add(field); iw.addDocument(doc); iw.close(); dir.close(); } // TODO: more tests with other possibilities private void checkTokens(Token[] tokens) throws IOException { Directory dir = newDirectory(); RandomIndexWriter riw = new RandomIndexWriter(random(), dir, iwc); boolean success = false; try { FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); // store some term vectors for the checkindex cross-check ft.setStoreTermVectors(true); ft.setStoreTermVectorPositions(true); ft.setStoreTermVectorOffsets(true); Document doc = new Document(); doc.add(new Field("body", new CannedTokenStream(tokens), ft)); riw.addDocument(doc); success = true; } finally { if (success) { IOUtils.close(riw, dir); } else { IOUtils.closeWhileHandlingException(riw, dir); } } } private Token makeToken(String text, int posIncr, int startOffset, int endOffset) { final Token t = new Token(); t.append(text); t.setPositionIncrement(posIncr); t.setOffset(startOffset, endOffset); return t; } }
false
true
public void testRandom() throws Exception { // token -> docID -> tokens final Map<String,Map<Integer,List<Token>>> actualTokens = new HashMap<String,Map<Integer,List<Token>>>(); Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc); final int numDocs = atLeast(20); //final int numDocs = atLeast(5); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); // TODO: randomize what IndexOptions we use; also test // changing this up in one IW buffered segment...: ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); if (random().nextBoolean()) { ft.setStoreTermVectors(true); ft.setStoreTermVectorOffsets(random().nextBoolean()); ft.setStoreTermVectorPositions(random().nextBoolean()); } for(int docCount=0;docCount<numDocs;docCount++) { Document doc = new Document(); doc.add(new IntField("id", docCount, Field.Store.NO)); List<Token> tokens = new ArrayList<Token>(); final int numTokens = atLeast(100); //final int numTokens = atLeast(20); int pos = -1; int offset = 0; //System.out.println("doc id=" + docCount); for(int tokenCount=0;tokenCount<numTokens;tokenCount++) { final String text; if (random().nextBoolean()) { text = "a"; } else if (random().nextBoolean()) { text = "b"; } else if (random().nextBoolean()) { text = "c"; } else { text = "d"; } int posIncr = random().nextBoolean() ? 1 : random().nextInt(5); if (tokenCount == 0 && posIncr == 0) { posIncr = 1; } final int offIncr = random().nextBoolean() ? 0 : random().nextInt(5); final int tokenOffset = random().nextInt(5); final Token token = makeToken(text, posIncr, offset+offIncr, offset+offIncr+tokenOffset); if (!actualTokens.containsKey(text)) { actualTokens.put(text, new HashMap<Integer,List<Token>>()); } final Map<Integer,List<Token>> postingsByDoc = actualTokens.get(text); if (!postingsByDoc.containsKey(docCount)) { postingsByDoc.put(docCount, new ArrayList<Token>()); } postingsByDoc.get(docCount).add(token); tokens.add(token); pos += posIncr; // stuff abs position into type: token.setType(""+pos); offset += offIncr + tokenOffset; //System.out.println(" " + token + " posIncr=" + token.getPositionIncrement() + " pos=" + pos + " off=" + token.startOffset() + "/" + token.endOffset() + " (freq=" + postingsByDoc.get(docCount).size() + ")"); } doc.add(new Field("content", new CannedTokenStream(tokens.toArray(new Token[tokens.size()])), ft)); w.addDocument(doc); } final DirectoryReader r = w.getReader(); w.close(); final String[] terms = new String[] {"a", "b", "c", "d"}; for(IndexReader reader : r.getSequentialSubReaders()) { // TODO: improve this AtomicReader sub = (AtomicReader) reader; //System.out.println("\nsub=" + sub); final TermsEnum termsEnum = sub.fields().terms("content").iterator(null); DocsEnum docs = null; DocsAndPositionsEnum docsAndPositions = null; DocsAndPositionsEnum docsAndPositionsAndOffsets = null; final int docIDToID[] = FieldCache.DEFAULT.getInts(sub, "id", false); for(String term : terms) { //System.out.println(" term=" + term); if (termsEnum.seekExact(new BytesRef(term), random().nextBoolean())) { docs = termsEnum.docs(null, docs, true); assertNotNull(docs); int doc; //System.out.println(" doc/freq"); while((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]); //System.out.println(" doc=" + docIDToID[doc] + " docID=" + doc + " " + expected.size() + " freq"); assertNotNull(expected); assertEquals(expected.size(), docs.freq()); } docsAndPositions = termsEnum.docsAndPositions(null, docsAndPositions, false); assertNotNull(docsAndPositions); //System.out.println(" doc/freq/pos"); while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]); //System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq"); assertNotNull(expected); assertEquals(expected.size(), docsAndPositions.freq()); for(Token token : expected) { int pos = Integer.parseInt(token.type()); //System.out.println(" pos=" + pos); assertEquals(pos, docsAndPositions.nextPosition()); } } docsAndPositionsAndOffsets = termsEnum.docsAndPositions(null, docsAndPositions, true); assertNotNull(docsAndPositionsAndOffsets); //System.out.println(" doc/freq/pos/offs"); while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]); //System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq"); assertNotNull(expected); assertEquals(expected.size(), docsAndPositions.freq()); for(Token token : expected) { int pos = Integer.parseInt(token.type()); //System.out.println(" pos=" + pos); assertEquals(pos, docsAndPositions.nextPosition()); assertEquals(token.startOffset(), docsAndPositions.startOffset()); assertEquals(token.endOffset(), docsAndPositions.endOffset()); } } } } // TODO: test advance: } r.close(); dir.close(); }
public void testRandom() throws Exception { // token -> docID -> tokens final Map<String,Map<Integer,List<Token>>> actualTokens = new HashMap<String,Map<Integer,List<Token>>>(); Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc); final int numDocs = atLeast(20); //final int numDocs = atLeast(5); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); // TODO: randomize what IndexOptions we use; also test // changing this up in one IW buffered segment...: ft.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); if (random().nextBoolean()) { ft.setStoreTermVectors(true); ft.setStoreTermVectorOffsets(random().nextBoolean()); ft.setStoreTermVectorPositions(random().nextBoolean()); } for(int docCount=0;docCount<numDocs;docCount++) { Document doc = new Document(); doc.add(new IntField("id", docCount, Field.Store.NO)); List<Token> tokens = new ArrayList<Token>(); final int numTokens = atLeast(100); //final int numTokens = atLeast(20); int pos = -1; int offset = 0; //System.out.println("doc id=" + docCount); for(int tokenCount=0;tokenCount<numTokens;tokenCount++) { final String text; if (random().nextBoolean()) { text = "a"; } else if (random().nextBoolean()) { text = "b"; } else if (random().nextBoolean()) { text = "c"; } else { text = "d"; } int posIncr = random().nextBoolean() ? 1 : random().nextInt(5); if (tokenCount == 0 && posIncr == 0) { posIncr = 1; } final int offIncr = random().nextBoolean() ? 0 : random().nextInt(5); final int tokenOffset = random().nextInt(5); final Token token = makeToken(text, posIncr, offset+offIncr, offset+offIncr+tokenOffset); if (!actualTokens.containsKey(text)) { actualTokens.put(text, new HashMap<Integer,List<Token>>()); } final Map<Integer,List<Token>> postingsByDoc = actualTokens.get(text); if (!postingsByDoc.containsKey(docCount)) { postingsByDoc.put(docCount, new ArrayList<Token>()); } postingsByDoc.get(docCount).add(token); tokens.add(token); pos += posIncr; // stuff abs position into type: token.setType(""+pos); offset += offIncr + tokenOffset; //System.out.println(" " + token + " posIncr=" + token.getPositionIncrement() + " pos=" + pos + " off=" + token.startOffset() + "/" + token.endOffset() + " (freq=" + postingsByDoc.get(docCount).size() + ")"); } doc.add(new Field("content", new CannedTokenStream(tokens.toArray(new Token[tokens.size()])), ft)); w.addDocument(doc); } final DirectoryReader r = w.getReader(); w.close(); final String[] terms = new String[] {"a", "b", "c", "d"}; for(IndexReader reader : r.getSequentialSubReaders()) { // TODO: improve this AtomicReader sub = (AtomicReader) reader; //System.out.println("\nsub=" + sub); final TermsEnum termsEnum = sub.fields().terms("content").iterator(null); DocsEnum docs = null; DocsAndPositionsEnum docsAndPositions = null; DocsAndPositionsEnum docsAndPositionsAndOffsets = null; final int docIDToID[] = FieldCache.DEFAULT.getInts(sub, "id", false); for(String term : terms) { //System.out.println(" term=" + term); if (termsEnum.seekExact(new BytesRef(term), random().nextBoolean())) { docs = termsEnum.docs(null, docs, true); assertNotNull(docs); int doc; //System.out.println(" doc/freq"); while((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]); //System.out.println(" doc=" + docIDToID[doc] + " docID=" + doc + " " + expected.size() + " freq"); assertNotNull(expected); assertEquals(expected.size(), docs.freq()); } docsAndPositions = termsEnum.docsAndPositions(null, docsAndPositions, false); assertNotNull(docsAndPositions); //System.out.println(" doc/freq/pos"); while((doc = docsAndPositions.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]); //System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq"); assertNotNull(expected); assertEquals(expected.size(), docsAndPositions.freq()); for(Token token : expected) { int pos = Integer.parseInt(token.type()); //System.out.println(" pos=" + pos); assertEquals(pos, docsAndPositions.nextPosition()); } } docsAndPositionsAndOffsets = termsEnum.docsAndPositions(null, docsAndPositions, true); assertNotNull(docsAndPositionsAndOffsets); //System.out.println(" doc/freq/pos/offs"); while((doc = docsAndPositionsAndOffsets.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { final List<Token> expected = actualTokens.get(term).get(docIDToID[doc]); //System.out.println(" doc=" + docIDToID[doc] + " " + expected.size() + " freq"); assertNotNull(expected); assertEquals(expected.size(), docsAndPositionsAndOffsets.freq()); for(Token token : expected) { int pos = Integer.parseInt(token.type()); //System.out.println(" pos=" + pos); assertEquals(pos, docsAndPositionsAndOffsets.nextPosition()); assertEquals(token.startOffset(), docsAndPositionsAndOffsets.startOffset()); assertEquals(token.endOffset(), docsAndPositionsAndOffsets.endOffset()); } } } } // TODO: test advance: } r.close(); dir.close(); }
diff --git a/src/com/deliciousdroid/client/Update.java b/src/com/deliciousdroid/client/Update.java index 7d06a2d..c705f14 100644 --- a/src/com/deliciousdroid/client/Update.java +++ b/src/com/deliciousdroid/client/Update.java @@ -1,65 +1,66 @@ /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid 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. * * DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.client; import com.deliciousdroid.util.DateParser; public class Update { private long lastUpdate; private int inboxNew; public long getLastUpdate(){ return lastUpdate; } public int getInboxNew(){ return inboxNew; } public Update(long update, int inbox){ lastUpdate = update; inboxNew = inbox; } public static Update valueOf(String updateResponse){ try { int start = updateResponse.indexOf("<update"); int end = updateResponse.indexOf("/>", start); String updateElement = updateResponse.substring(start, end); int timestart = updateElement.indexOf("time="); int timeend = updateElement.indexOf("\"", timestart + 7); String time = updateElement.substring(timestart + 6, timeend); long updateTime = DateParser.parseTime(time); int inboxstart = updateElement.indexOf("inboxnew"); int inboxend = updateElement.indexOf("\"", inboxstart + 10); - int inbox = Integer.parseInt(updateElement.substring(inboxstart + 10, inboxend)); + //int inbox = Integer.parseInt(updateElement.substring(inboxstart + 10, inboxend)); + int inbox = 0; return new Update(updateTime, inbox); } catch (java.text.ParseException e) { e.printStackTrace(); } return null; } }
true
true
public static Update valueOf(String updateResponse){ try { int start = updateResponse.indexOf("<update"); int end = updateResponse.indexOf("/>", start); String updateElement = updateResponse.substring(start, end); int timestart = updateElement.indexOf("time="); int timeend = updateElement.indexOf("\"", timestart + 7); String time = updateElement.substring(timestart + 6, timeend); long updateTime = DateParser.parseTime(time); int inboxstart = updateElement.indexOf("inboxnew"); int inboxend = updateElement.indexOf("\"", inboxstart + 10); int inbox = Integer.parseInt(updateElement.substring(inboxstart + 10, inboxend)); return new Update(updateTime, inbox); } catch (java.text.ParseException e) { e.printStackTrace(); } return null; }
public static Update valueOf(String updateResponse){ try { int start = updateResponse.indexOf("<update"); int end = updateResponse.indexOf("/>", start); String updateElement = updateResponse.substring(start, end); int timestart = updateElement.indexOf("time="); int timeend = updateElement.indexOf("\"", timestart + 7); String time = updateElement.substring(timestart + 6, timeend); long updateTime = DateParser.parseTime(time); int inboxstart = updateElement.indexOf("inboxnew"); int inboxend = updateElement.indexOf("\"", inboxstart + 10); //int inbox = Integer.parseInt(updateElement.substring(inboxstart + 10, inboxend)); int inbox = 0; return new Update(updateTime, inbox); } catch (java.text.ParseException e) { e.printStackTrace(); } return null; }
diff --git a/reports/jars/ChartsCustomizers/src/main/java/com/ovirt/reports/jasper/ScatterChartCustomizer.java b/reports/jars/ChartsCustomizers/src/main/java/com/ovirt/reports/jasper/ScatterChartCustomizer.java index d41782c..10b5c9a 100644 --- a/reports/jars/ChartsCustomizers/src/main/java/com/ovirt/reports/jasper/ScatterChartCustomizer.java +++ b/reports/jars/ChartsCustomizers/src/main/java/com/ovirt/reports/jasper/ScatterChartCustomizer.java @@ -1,48 +1,48 @@ package com.ovirt.reports.jasper; import java.awt.Color; import java.awt.Font; import org.jfree.chart.JFreeChart; import org.jfree.chart.block.BlockBorder; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.plot.XYPlot; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.TextAnchor; import net.sf.jasperreports.engine.JRChart; import net.sf.jasperreports.engine.JRChartCustomizer; public class ScatterChartCustomizer implements JRChartCustomizer { public void customize(JFreeChart chart, JRChart jasperChart) { XYPlot categoryPlot = chart.getXYPlot(); Marker ymarker = new ValueMarker(50); ymarker.setLabel("50% Usage"); - ymarker.setLabelFont(new Font("DejaVu Sans", Font.BOLD, 11)); + ymarker.setLabelFont(new Font("SansSerif", Font.BOLD, 11)); ymarker.setPaint(Color.black); ymarker.setLabelAnchor(RectangleAnchor.TOP_LEFT); ymarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT); Marker xmarker = new ValueMarker(50); xmarker.setLabel("50% Usage"); - xmarker.setLabelFont(new Font("DejaVu Sans", Font.BOLD, 11)); + xmarker.setLabelFont(new Font("SansSerif", Font.BOLD, 11)); xmarker.setPaint(Color.black); xmarker.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT); xmarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT); categoryPlot.addDomainMarker(ymarker); categoryPlot.addRangeMarker(xmarker); categoryPlot.setNoDataMessage("No Data Available"); float[] red = new float[3]; Color.RGBtoHSB(255, 0, 0, red); for (int i=1; i <= categoryPlot.getDataset().getSeriesCount(); i++) { if (categoryPlot.getDataset().getSeriesKey(i-1).toString().contains("Deleted".subSequence(0, 4))) { categoryPlot.getRenderer().setSeriesPaint(i-1, Color.getHSBColor(red[0], red[1], red[2])); } } categoryPlot.getDomainAxis().setTickMarksVisible(true); chart.getLegend().setFrame(BlockBorder.NONE); } }
false
true
public void customize(JFreeChart chart, JRChart jasperChart) { XYPlot categoryPlot = chart.getXYPlot(); Marker ymarker = new ValueMarker(50); ymarker.setLabel("50% Usage"); ymarker.setLabelFont(new Font("DejaVu Sans", Font.BOLD, 11)); ymarker.setPaint(Color.black); ymarker.setLabelAnchor(RectangleAnchor.TOP_LEFT); ymarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT); Marker xmarker = new ValueMarker(50); xmarker.setLabel("50% Usage"); xmarker.setLabelFont(new Font("DejaVu Sans", Font.BOLD, 11)); xmarker.setPaint(Color.black); xmarker.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT); xmarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT); categoryPlot.addDomainMarker(ymarker); categoryPlot.addRangeMarker(xmarker); categoryPlot.setNoDataMessage("No Data Available"); float[] red = new float[3]; Color.RGBtoHSB(255, 0, 0, red); for (int i=1; i <= categoryPlot.getDataset().getSeriesCount(); i++) { if (categoryPlot.getDataset().getSeriesKey(i-1).toString().contains("Deleted".subSequence(0, 4))) { categoryPlot.getRenderer().setSeriesPaint(i-1, Color.getHSBColor(red[0], red[1], red[2])); } } categoryPlot.getDomainAxis().setTickMarksVisible(true); chart.getLegend().setFrame(BlockBorder.NONE); }
public void customize(JFreeChart chart, JRChart jasperChart) { XYPlot categoryPlot = chart.getXYPlot(); Marker ymarker = new ValueMarker(50); ymarker.setLabel("50% Usage"); ymarker.setLabelFont(new Font("SansSerif", Font.BOLD, 11)); ymarker.setPaint(Color.black); ymarker.setLabelAnchor(RectangleAnchor.TOP_LEFT); ymarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT); Marker xmarker = new ValueMarker(50); xmarker.setLabel("50% Usage"); xmarker.setLabelFont(new Font("SansSerif", Font.BOLD, 11)); xmarker.setPaint(Color.black); xmarker.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT); xmarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT); categoryPlot.addDomainMarker(ymarker); categoryPlot.addRangeMarker(xmarker); categoryPlot.setNoDataMessage("No Data Available"); float[] red = new float[3]; Color.RGBtoHSB(255, 0, 0, red); for (int i=1; i <= categoryPlot.getDataset().getSeriesCount(); i++) { if (categoryPlot.getDataset().getSeriesKey(i-1).toString().contains("Deleted".subSequence(0, 4))) { categoryPlot.getRenderer().setSeriesPaint(i-1, Color.getHSBColor(red[0], red[1], red[2])); } } categoryPlot.getDomainAxis().setTickMarksVisible(true); chart.getLegend().setFrame(BlockBorder.NONE); }
diff --git a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/ir/util/ActorInterpreter.java b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/ir/util/ActorInterpreter.java index 09aacbd00..91ab779d2 100644 --- a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/ir/util/ActorInterpreter.java +++ b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/ir/util/ActorInterpreter.java @@ -1,567 +1,571 @@ /* * Copyright (c) 2009-2011, IETR/INSA of Rennes * 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 IETR/INSA of Rennes 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 net.sf.orcc.ir.util; import java.util.Collections; import java.util.List; import net.sf.dftools.graph.Edge; import net.sf.orcc.OrccRuntimeException; import net.sf.orcc.df.Action; import net.sf.orcc.df.Actor; import net.sf.orcc.df.Argument; import net.sf.orcc.df.Pattern; import net.sf.orcc.df.Port; import net.sf.orcc.df.State; import net.sf.orcc.df.Transition; import net.sf.orcc.df.Unit; import net.sf.orcc.ir.Arg; import net.sf.orcc.ir.ArgByVal; import net.sf.orcc.ir.ExprString; import net.sf.orcc.ir.Expression; import net.sf.orcc.ir.InstAssign; import net.sf.orcc.ir.InstCall; import net.sf.orcc.ir.InstLoad; import net.sf.orcc.ir.InstPhi; import net.sf.orcc.ir.InstReturn; import net.sf.orcc.ir.InstSpecific; import net.sf.orcc.ir.InstStore; import net.sf.orcc.ir.NodeIf; import net.sf.orcc.ir.NodeWhile; import net.sf.orcc.ir.Param; import net.sf.orcc.ir.Procedure; import net.sf.orcc.ir.Type; import net.sf.orcc.ir.TypeList; import net.sf.orcc.ir.Var; import net.sf.orcc.util.OrccUtil; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; /** * This class defines an interpreter for an actor. The interpreter can * {@link #initialize()} and {@link #schedule()} the actor. * * @author Pierre-Laurent Lagalaye * @author Matthieu Wipliez * */ public class ActorInterpreter extends AbstractActorVisitor<Object> { /** * branch being visited */ protected int branch; protected ExpressionEvaluator exprInterpreter; /** * Actor's FSM current state */ private State fsmState; /** * Actor's constant parameters to be set at initialization time */ protected List<Argument> arguments; /** * Creates a new interpreter with no actor and no parameters. * */ public ActorInterpreter() { this.arguments = Collections.emptyList(); exprInterpreter = new ExpressionEvaluator(); } /** * Creates a new interpreter. * * @param actor * the actor to interpret * @param parameters * parameters of the instance of the given actor */ public ActorInterpreter(Actor actor, List<Argument> arguments) { this.arguments = arguments; exprInterpreter = new ExpressionEvaluator(); setActor(actor); } /** * Allocates the variables of the given pattern. * * @param pattern * a pattern */ final protected void allocatePattern(Pattern pattern) { for (Port port : pattern.getPorts()) { Var var = pattern.getVariable(port); Object value = ValueUtil.createArray((TypeList) var.getType()); var.setValue(value); } } /** * Calls the given native procedure. Does nothing by default. This method * may be overridden if one wishes to call native procedures. * * @param procedure * a native procedure * @return the result of calling the given procedure */ protected Object callNativeProcedure(Procedure procedure, List<Arg> parameters) { return null; } /** * Calls the print procedure. Prints to stdout by default. This method may * be overridden. * * @param procedure * a native procedure * @param arguments * arguments of the procedure */ protected void callPrintProcedure(Procedure procedure, List<Arg> arguments) { for (Arg arg : arguments) { if (arg.isByVal()) { Expression expr = ((ArgByVal) arg).getValue(); if (expr.isExprString()) { // String characters rework for escaped control // management String str = ((ExprString) expr).getValue(); String unescaped = OrccUtil.getUnescapedString(str); System.out.print(unescaped); } else { Object value = exprInterpreter.doSwitch(expr); System.out.print(String.valueOf(value)); } } } } @Override public Object caseInstAssign(InstAssign instr) { try { Var target = instr.getTarget().getVariable(); target.setValue(exprInterpreter.doSwitch(instr.getValue())); } catch (OrccRuntimeException e) { String file; if (actor == null) { file = ""; } else { file = actor.getFileName(); } throw new OrccRuntimeException(file, instr.getLineNumber(), "", e); } return null; } @Override public Object caseInstCall(InstCall call) { // Get called procedure Procedure proc = call.getProcedure(); // Set the input parameters of the called procedure if any List<Arg> callParams = call.getParameters(); // Special "print" case if (call.isPrint()) { callPrintProcedure(proc, callParams); } else if (proc.isNative()) { Object result = callNativeProcedure(proc, callParams); if (call.hasResult()) { call.getTarget().getVariable().setValue(result); } } else { List<Param> procParams = proc.getParameters(); for (int i = 0; i < callParams.size(); i++) { Var procVar = procParams.get(i).getVariable(); Arg arg = callParams.get(i); if (arg.isByVal()) { Expression value = ((ArgByVal) arg).getValue(); procVar.setValue(exprInterpreter.doSwitch(value)); } } // Interpret procedure body Object result = doSwitch(proc); if (call.hasResult()) { call.getTarget().getVariable().setValue(result); } } return null; } @Override public Object caseInstLoad(InstLoad instr) { Var target = instr.getTarget().getVariable(); Var source = instr.getSource().getVariable(); if (instr.getIndexes().isEmpty()) { target.setValue(source.getValue()); } else { try { Object array = source.getValue(); Object[] indexes = new Object[instr.getIndexes().size()]; int i = 0; for (Expression index : instr.getIndexes()) { indexes[i++] = exprInterpreter.doSwitch(index); } Type type = ((TypeList) source.getType()).getInnermostType(); Object value = ValueUtil.get(type, array, indexes); target.setValue(value); } catch (IndexOutOfBoundsException e) { throw new OrccRuntimeException( "Array index out of bounds at line " + instr.getLineNumber()); } } return null; } @Override public Object caseInstPhi(InstPhi phi) { Expression value = phi.getValues().get(branch); phi.getTarget().getVariable().setValue(exprInterpreter.doSwitch(value)); return null; } @Override public Object caseInstReturn(InstReturn instr) { if (instr.getValue() == null) { return null; } return exprInterpreter.doSwitch(instr.getValue()); } @Override public Object caseInstSpecific(InstSpecific instr) { throw new OrccRuntimeException("does not know how to interpret a " + "specific instruction"); } @Override public Object caseInstStore(InstStore instr) { Var target = instr.getTarget().getVariable(); Object value = exprInterpreter.doSwitch(instr.getValue()); if (instr.getIndexes().isEmpty()) { target.setValue(value); } else { try { Object array = target.getValue(); Object[] indexes = new Object[instr.getIndexes().size()]; int i = 0; for (Expression index : instr.getIndexes()) { indexes[i++] = exprInterpreter.doSwitch(index); } Type type = ((TypeList) target.getType()).getInnermostType(); ValueUtil.set(type, array, value, indexes); } catch (IndexOutOfBoundsException e) { throw new OrccRuntimeException( "Array index out of bounds at line " + instr.getLineNumber()); } } return null; } @Override public Object caseNodeIf(NodeIf node) { // Interpret first expression ("if" condition) Object condition = exprInterpreter.doSwitch(node.getCondition()); Object ret; // if (condition is true) if (ValueUtil.isBool(condition)) { int oldBranch = branch; if (ValueUtil.isTrue(condition)) { doSwitch(node.getThenNodes()); branch = 0; } else { doSwitch(node.getElseNodes()); branch = 1; } ret = doSwitch(node.getJoinNode()); branch = oldBranch; } else { throw new OrccRuntimeException("Condition " + new ExpressionPrinter().doSwitch(node.getCondition()) + " not boolean at line " + node.getLineNumber() + "\n"); } return ret; } @Override public Object caseNodeWhile(NodeWhile node) { int oldBranch = branch; branch = 0; doSwitch(node.getJoinNode()); // Interpret first expression ("while" condition) Object condition = exprInterpreter.doSwitch(node.getCondition()); // while (condition is true) do branch = 1; while (ValueUtil.isTrue(condition)) { doSwitch(node.getNodes()); doSwitch(node.getJoinNode()); // Interpret next value of "while" condition condition = exprInterpreter.doSwitch(node.getCondition()); } branch = oldBranch; return null; } @Override public Object caseProcedure(Procedure procedure) { // Allocate local List variables for (Var local : procedure.getLocals()) { Type type = local.getType(); if (type.isList()) { Object value = ValueUtil .createArray((TypeList) local.getType()); local.setValue(value); } } return super.caseProcedure(procedure); } /** * Returns true if the action has no output pattern, or if it has an output * pattern and there is enough room in the FIFOs to satisfy it. * * @param outputPattern * output pattern of an action * @return true if the pattern is empty or satisfiable */ protected boolean checkOutputPattern(Pattern outputPattern) { return true; } /** * Executes the given action. This implementation allocates input/output * pattern and executes the body. Should be overriden by implementations to * perform read/write from/to FIFOs. * * @param action * an action */ protected void execute(Action action) { Pattern input = action.getInputPattern(); Pattern output = action.getOutputPattern(); allocatePattern(input); allocatePattern(output); doSwitch(action.getBody()); } /** * Returns the current FSM state. * * @return the current FSM state */ public final State getFsmState() { return fsmState; } /** * Get the next schedulable action to be executed for this actor * * @return the schedulable action or null */ public final Action getNextAction() { // Check next schedulable action in respect of the priority order for (Action action : actor.getActionsOutsideFsm()) { if (isSchedulable(action)) { if (checkOutputPattern(action.getOutputPattern())) { return action; } return null; } } if (actor.hasFsm()) { // Then check for next FSM transition for (Edge edge : fsmState.getOutgoing()) { Transition transition = (Transition) edge; Action action = transition.getAction(); if (isSchedulable(action)) { // Update FSM state if (checkOutputPattern(action.getOutputPattern())) { fsmState = (State) transition.getTarget(); return action; } return null; } } } return null; } /** * Initialize interpreted actor. That is to say constant parameters, * initialized state variables, allocation and initialization of state * arrays. */ public void initialize() { try { // initializes actors parameters from instance map for (Argument argument : arguments) { - Object value = exprInterpreter.doSwitch(argument.getValue()); - argument.getVariable().setValue(value); + Var parameter = actor.getParameter(argument.getVariable() + .getName()); + if (parameter != null) { + parameter.setValue(exprInterpreter.doSwitch(argument + .getValue())); + } } // initializes state variables for (Var stateVar : actor.getStateVars()) { initializeVar(stateVar); } // initializes runtime value of constants declared in units Resource resource = actor.eResource(); if (resource != null) { ResourceSet set = resource.getResourceSet(); for (Resource res : set.getResources()) { EObject eObject = res.getContents().get(0); if (eObject instanceof Unit) { Unit unit = (Unit) eObject; for (Var var : unit.getConstants()) { if (var.getValue() == null) { initializeVar(var); } } } } } // Get initializing procedure if any for (Action action : actor.getInitializes()) { if (isSchedulable(action)) { execute(action); continue; } } } catch (OrccRuntimeException ex) { throw new OrccRuntimeException("Runtime exception thrown by actor " + actor.getName(), ex); } } /** * Initializes the given variable. * * @param variable * a variable */ protected void initializeVar(Var variable) { Type type = variable.getType(); Expression initConst = variable.getInitialValue(); if (initConst == null) { if (type.isList()) { // allocate empty array variable variable.setValue(ValueUtil.createArray((TypeList) type)); } } else { // evaluate initial constant value if (type.isList()) { exprInterpreter.setType((TypeList) type); } variable.setValue(exprInterpreter.doSwitch(initConst)); } } /** * Returns true if the given action is schedulable. This implementation * allocates the peek pattern and calls the scheduler procedure. This method * should be overridden to define how to test the schedulability of an * action. * * @param action * an action * @return true if the given action is schedulable */ protected boolean isSchedulable(Action action) { Pattern pattern = action.getPeekPattern(); allocatePattern(pattern); Object result = doSwitch(action.getScheduler()); return ValueUtil.isTrue(result); } /** * Schedule next schedulable action if any * * @return <code>true</code> if an action was scheduled, <code>false</code> * otherwise */ public boolean schedule() { try { // "Synchronous-like" scheduling policy : schedule only 1 action per // actor at each "schedule" (network logical cycle) call Action action = getNextAction(); if (action == null) { return false; } else { execute(action); return true; } } catch (OrccRuntimeException ex) { throw new OrccRuntimeException("Runtime exception thrown by actor " + actor.getName(), ex); } } /** * Sets the actor interpreter by this interpreter. * * @param actor * an actor */ protected void setActor(Actor actor) { this.actor = actor; // set fsm state to initial state (if any) if (actor.hasFsm()) { fsmState = actor.getFsm().getInitialState(); } else { fsmState = null; } } }
true
true
public void initialize() { try { // initializes actors parameters from instance map for (Argument argument : arguments) { Object value = exprInterpreter.doSwitch(argument.getValue()); argument.getVariable().setValue(value); } // initializes state variables for (Var stateVar : actor.getStateVars()) { initializeVar(stateVar); } // initializes runtime value of constants declared in units Resource resource = actor.eResource(); if (resource != null) { ResourceSet set = resource.getResourceSet(); for (Resource res : set.getResources()) { EObject eObject = res.getContents().get(0); if (eObject instanceof Unit) { Unit unit = (Unit) eObject; for (Var var : unit.getConstants()) { if (var.getValue() == null) { initializeVar(var); } } } } } // Get initializing procedure if any for (Action action : actor.getInitializes()) { if (isSchedulable(action)) { execute(action); continue; } } } catch (OrccRuntimeException ex) { throw new OrccRuntimeException("Runtime exception thrown by actor " + actor.getName(), ex); } }
public void initialize() { try { // initializes actors parameters from instance map for (Argument argument : arguments) { Var parameter = actor.getParameter(argument.getVariable() .getName()); if (parameter != null) { parameter.setValue(exprInterpreter.doSwitch(argument .getValue())); } } // initializes state variables for (Var stateVar : actor.getStateVars()) { initializeVar(stateVar); } // initializes runtime value of constants declared in units Resource resource = actor.eResource(); if (resource != null) { ResourceSet set = resource.getResourceSet(); for (Resource res : set.getResources()) { EObject eObject = res.getContents().get(0); if (eObject instanceof Unit) { Unit unit = (Unit) eObject; for (Var var : unit.getConstants()) { if (var.getValue() == null) { initializeVar(var); } } } } } // Get initializing procedure if any for (Action action : actor.getInitializes()) { if (isSchedulable(action)) { execute(action); continue; } } } catch (OrccRuntimeException ex) { throw new OrccRuntimeException("Runtime exception thrown by actor " + actor.getName(), ex); } }
diff --git a/org.eclipse.riena.monitor.client/src/org/eclipse/riena/internal/monitor/client/DefaultStore.java b/org.eclipse.riena.monitor.client/src/org/eclipse/riena/internal/monitor/client/DefaultStore.java index b0507749a..fe5d675cc 100644 --- a/org.eclipse.riena.monitor.client/src/org/eclipse/riena/internal/monitor/client/DefaultStore.java +++ b/org.eclipse.riena.monitor.client/src/org/eclipse/riena/internal/monitor/client/DefaultStore.java @@ -1,231 +1,231 @@ /******************************************************************************* * Copyright (c) 2007, 2008 compeople AG 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: * compeople AG - initial API and implementation *******************************************************************************/ package org.eclipse.riena.internal.monitor.client; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.Platform; import org.eclipse.equinox.log.Logger; import org.eclipse.riena.core.util.IOUtils; import org.eclipse.riena.monitor.client.IStore; import org.eclipse.riena.monitor.common.Collectible; import org.osgi.service.log.LogService; /** * TODO config */ public class DefaultStore implements IStore { private File storeFolder; private static final String TRANSFER_FILE_EXTENSION = ".trans"; //$NON-NLS-1$ private static final String COLLECT_FILE_EXTENSION = ".coll"; //$NON-NLS-1$ private static final String DEL_FILE_EXTENSION = ".del"; //$NON-NLS-1$ private static final Logger LOGGER = Activator.getDefault().getLogger(DefaultStore.class); public DefaultStore() { // System.out.println("Platform.getConfigurationLocation: " + Platform.getConfigurationLocation().getURL()); // System.out.println("Platform.getInstallLocation: " + Platform.getInstallLocation().getURL()); // System.out.println("Platform.getInstanceLocation: " + Platform.getInstanceLocation().getURL()); // System.out.println("Platform.getLocation: " + Platform.getLocation()); // System.out.println("Platform.getLogFileLocation: " + Platform.getLogFileLocation()); // System.out.println("Platform.getUserLocation: " + Platform.getUserLocation().getURL()); // TODO What is the best place to store the stuff?? storeFolder = new File(Platform.getUserLocation().getURL().getFile(), ".collectiblestore"); storeFolder.mkdirs(); Assert.isTrue(storeFolder.exists()); Assert.isTrue(storeFolder.isDirectory()); LOGGER.log(LogService.LOG_DEBUG, "DefaultStore at " + storeFolder); } /* * (non-Javadoc) * * @see * org.eclipse.riena.internal.monitor.client.ICollectibleStore#collect(org * .eclipse.riena.monitor.core.Collectible) */ public synchronized boolean collect(final Collectible<?> collectible) { ObjectOutputStream objectos = null; try { File file = getFile(collectible, COLLECT_FILE_EXTENSION); OutputStream fos = new FileOutputStream(file); OutputStream encos = getEncryptor(fos); OutputStream gzipos = getCompressor(encos); objectos = new ObjectOutputStream(gzipos); objectos.writeObject(collectible); } catch (IOException e) { // TODO Error handling!!? e.printStackTrace(); return false; } finally { IOUtils.close(objectos); } return true; } /* * (non-Javadoc) * * @see org.eclipse.riena.monitor.client.IStore#prepareForTransfer * (java.lang.String) */ public void prepareTransferables(final String category) { File[] trans = storeFolder.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(category) && name.endsWith(COLLECT_FILE_EXTENSION); } }); for (File file : trans) { String name = file.getName().replace(COLLECT_FILE_EXTENSION, TRANSFER_FILE_EXTENSION); file.renameTo(new File(file.getParent(), name)); } } /* * (non-Javadoc) * * @see org.eclipse.riena.monitor.client.IStore#getTransferables(java * .lang.String) */ - public synchronized List<Collectible<?>> retrieveTransferables(String category) { + public synchronized List<Collectible<?>> retrieveTransferables(final String category) { File[] transferables = storeFolder.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { - return name.endsWith(TRANSFER_FILE_EXTENSION); + return name.startsWith(category) && name.endsWith(TRANSFER_FILE_EXTENSION); } }); List<Collectible<?>> collectibles = new ArrayList<Collectible<?>>(); for (File transferable : transferables) { ObjectInputStream objectis = null; try { InputStream fis = new FileInputStream(transferable); InputStream decris = getDecryptor(fis); InputStream gzipis = getDecompressor(decris); objectis = new ObjectInputStream(gzipis); Collectible<?> collectible = (Collectible<?>) objectis.readObject(); collectibles.add(collectible); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { IOUtils.close(objectis); } } return collectibles; } /** * Get the decryptor for storing the collectibles. * <p> * <b>Note: </b>This hook method is intended to be overwritten to provide * encrypted storage on the local file system on the client. Otherwise no * encryption will be used. * * @param is * @return */ protected InputStream getDecryptor(InputStream is) throws IOException { return is; } /** * * Get the encryptor for retrieving the collectibles. * <p> * <b>Note: </b>This hook method is intended to be overwritten to provide * encrypted storage on the local file system on the client. Otherwise no * encryption will be used. * * @param os * @return */ protected OutputStream getEncryptor(OutputStream os) throws IOException { return os; } /** * Get the compressor for storing the collectibles. * <p> * <b>Note: </b>This hook method may be overwritten to provide another * compressing technology. This method uses GZIP. * * @param os * @return * @throws IOException */ protected OutputStream getCompressor(OutputStream os) throws IOException { return new GZIPOutputStream(os); } /** * * Get the encryptor for retrieving the collectibles. * <p> * <b>Note: </b>This hook method is intended to be overwritten to provide * encrypted storage on the local file system on the client. Otherwise no * encryption will be used. * * @param is * @return * @throws IOException */ protected InputStream getDecompressor(InputStream is) throws IOException { return new GZIPInputStream(is); } /* * (non-Javadoc) * * @see org.eclipse.riena.monitor.client.IStore#commitTransferred( * java.util.List) */ public synchronized void commitTransferred(List<Collectible<?>> collectibles) { for (Collectible<?> collectible : collectibles) { File transferred = getFile(collectible, TRANSFER_FILE_EXTENSION); if (!transferred.delete()) { File toDelete = new File(transferred, DEL_FILE_EXTENSION); transferred.renameTo(toDelete); toDelete.deleteOnExit(); } } } private File getFile(Collectible<?> collectible, String extension) { return new File(storeFolder, collectible.getCategory() + "-" + collectible.getUUID().toString() + extension); //$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.eclipse.riena.monitor.client.IStore#flush() */ public void flush() { // nothing to do here } }
false
true
public synchronized List<Collectible<?>> retrieveTransferables(String category) { File[] transferables = storeFolder.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(TRANSFER_FILE_EXTENSION); } }); List<Collectible<?>> collectibles = new ArrayList<Collectible<?>>(); for (File transferable : transferables) { ObjectInputStream objectis = null; try { InputStream fis = new FileInputStream(transferable); InputStream decris = getDecryptor(fis); InputStream gzipis = getDecompressor(decris); objectis = new ObjectInputStream(gzipis); Collectible<?> collectible = (Collectible<?>) objectis.readObject(); collectibles.add(collectible); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { IOUtils.close(objectis); } } return collectibles; }
public synchronized List<Collectible<?>> retrieveTransferables(final String category) { File[] transferables = storeFolder.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(category) && name.endsWith(TRANSFER_FILE_EXTENSION); } }); List<Collectible<?>> collectibles = new ArrayList<Collectible<?>>(); for (File transferable : transferables) { ObjectInputStream objectis = null; try { InputStream fis = new FileInputStream(transferable); InputStream decris = getDecryptor(fis); InputStream gzipis = getDecompressor(decris); objectis = new ObjectInputStream(gzipis); Collectible<?> collectible = (Collectible<?>) objectis.readObject(); collectibles.add(collectible); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { IOUtils.close(objectis); } } return collectibles; }
diff --git a/src/com/reil/bukkit/rBorder/BorderPlugin.java b/src/com/reil/bukkit/rBorder/BorderPlugin.java index 920ae12..466670a 100644 --- a/src/com/reil/bukkit/rBorder/BorderPlugin.java +++ b/src/com/reil/bukkit/rBorder/BorderPlugin.java @@ -1,101 +1,108 @@ package com.reil.bukkit.rBorder; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.event.Event; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginLoader; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class BorderPlugin extends JavaPlugin{ Logger log = Logger.getLogger("Minecraft"); File Folder; Properties Props = new Properties(); int SpawnX; int SpawnZ; int BorderSizeSq; int BorderSize; String BorderAlert; String BorderAlertSpawn; Location SpawnLocation; rBorderListener Listener = new rBorderListener(this); rBorderVehicleListener Listener2 = new rBorderVehicleListener(this); /* If a player has an X and Z between +-DefiniteSquare, there is no need to calculate distance. */ int DefiniteSquare; public BorderPlugin(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader) { super(pluginLoader, instance, desc, folder, plugin, cLoader); this.Folder = folder; } - public void onEnable() { + public void onEnable(){ // Open plugin properties (just the border size, for now) try { FileInputStream file = new FileInputStream(Folder + "/rBorder.properties"); Props.load(file); file.close(); } catch (FileNotFoundException e) { - e.printStackTrace(); + log.info("[rBorder] Can't find properties file! Creating file and using defaults."); + File createMe = new File(Folder + "/rBorder.properties"); + try { + createMe.createNewFile(); + } catch (IOException e1) { + e1.printStackTrace(); + } } catch (IOException e) { e.printStackTrace(); } PluginManager loader = getServer().getPluginManager(); loader.registerEvent(Event.Type.PLAYER_MOVE, Listener, Event.Priority.Highest, this); loader.registerEvent(Event.Type.PLAYER_TELEPORT, Listener, Event.Priority.Highest, this); loader.registerEvent(Event.Type.PLAYER_JOIN, Listener, Event.Priority.Highest, this); loader.registerEvent(Event.Type.VEHICLE_MOVE, Listener2, Event.Priority.Highest, this); - BorderSize = new Integer(Props.getProperty("size", "5000")); + BorderSize = new Integer(Props.getProperty("size", "1400")); BorderAlert = Props.getProperty("Alert" , "You have reached the border!"); BorderAlertSpawn = Props.getProperty("AlertSpawn", "You logged in outside the border!"); + Props.setProperty("size", Integer.toString(BorderSize)); Props.setProperty("Alert", BorderAlert); Props.setProperty("AlertSpawn", BorderAlertSpawn); BorderSizeSq = BorderSize * BorderSize; DefiniteSquare = (int) Math.sqrt(.5 * BorderSizeSq); log.info("[rBorder] Loaded. Size:" + BorderSize); SpawnLocation = getServer().getWorlds()[0].getSpawnLocation(); SpawnX = SpawnLocation.getBlockX(); SpawnZ = SpawnLocation.getBlockZ(); log.info("[rBorder]: Spawn location:" + SpawnLocation.getBlockX() + ", " + SpawnLocation.getBlockY() + ", " + SpawnLocation.getBlockZ()+ "."); try { Props.store(new FileOutputStream(Folder + "/rBorder.properties"), "Border Plugin properties"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void onDisable() { } public boolean inBorder(Location checkHere) { int X = Math.abs(SpawnX - checkHere.getBlockX()); int Z = Math.abs(SpawnZ - checkHere.getBlockZ()); // If statements are cheaper than squaring twice! // Definitely in the circle? if (X < DefiniteSquare && Z < DefiniteSquare) return true; // Definitely not in the circle? if (X > BorderSize || Z > BorderSize) return false; // Must know for sure. if ( X*X + Z*Z > BorderSizeSq ) return false; else return true; } }
false
true
public void onEnable() { // Open plugin properties (just the border size, for now) try { FileInputStream file = new FileInputStream(Folder + "/rBorder.properties"); Props.load(file); file.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } PluginManager loader = getServer().getPluginManager(); loader.registerEvent(Event.Type.PLAYER_MOVE, Listener, Event.Priority.Highest, this); loader.registerEvent(Event.Type.PLAYER_TELEPORT, Listener, Event.Priority.Highest, this); loader.registerEvent(Event.Type.PLAYER_JOIN, Listener, Event.Priority.Highest, this); loader.registerEvent(Event.Type.VEHICLE_MOVE, Listener2, Event.Priority.Highest, this); BorderSize = new Integer(Props.getProperty("size", "5000")); BorderAlert = Props.getProperty("Alert" , "You have reached the border!"); BorderAlertSpawn = Props.getProperty("AlertSpawn", "You logged in outside the border!"); Props.setProperty("Alert", BorderAlert); Props.setProperty("AlertSpawn", BorderAlertSpawn); BorderSizeSq = BorderSize * BorderSize; DefiniteSquare = (int) Math.sqrt(.5 * BorderSizeSq); log.info("[rBorder] Loaded. Size:" + BorderSize); SpawnLocation = getServer().getWorlds()[0].getSpawnLocation(); SpawnX = SpawnLocation.getBlockX(); SpawnZ = SpawnLocation.getBlockZ(); log.info("[rBorder]: Spawn location:" + SpawnLocation.getBlockX() + ", " + SpawnLocation.getBlockY() + ", " + SpawnLocation.getBlockZ()+ "."); try { Props.store(new FileOutputStream(Folder + "/rBorder.properties"), "Border Plugin properties"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void onEnable(){ // Open plugin properties (just the border size, for now) try { FileInputStream file = new FileInputStream(Folder + "/rBorder.properties"); Props.load(file); file.close(); } catch (FileNotFoundException e) { log.info("[rBorder] Can't find properties file! Creating file and using defaults."); File createMe = new File(Folder + "/rBorder.properties"); try { createMe.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } PluginManager loader = getServer().getPluginManager(); loader.registerEvent(Event.Type.PLAYER_MOVE, Listener, Event.Priority.Highest, this); loader.registerEvent(Event.Type.PLAYER_TELEPORT, Listener, Event.Priority.Highest, this); loader.registerEvent(Event.Type.PLAYER_JOIN, Listener, Event.Priority.Highest, this); loader.registerEvent(Event.Type.VEHICLE_MOVE, Listener2, Event.Priority.Highest, this); BorderSize = new Integer(Props.getProperty("size", "1400")); BorderAlert = Props.getProperty("Alert" , "You have reached the border!"); BorderAlertSpawn = Props.getProperty("AlertSpawn", "You logged in outside the border!"); Props.setProperty("size", Integer.toString(BorderSize)); Props.setProperty("Alert", BorderAlert); Props.setProperty("AlertSpawn", BorderAlertSpawn); BorderSizeSq = BorderSize * BorderSize; DefiniteSquare = (int) Math.sqrt(.5 * BorderSizeSq); log.info("[rBorder] Loaded. Size:" + BorderSize); SpawnLocation = getServer().getWorlds()[0].getSpawnLocation(); SpawnX = SpawnLocation.getBlockX(); SpawnZ = SpawnLocation.getBlockZ(); log.info("[rBorder]: Spawn location:" + SpawnLocation.getBlockX() + ", " + SpawnLocation.getBlockY() + ", " + SpawnLocation.getBlockZ()+ "."); try { Props.store(new FileOutputStream(Folder + "/rBorder.properties"), "Border Plugin properties"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
diff --git a/src/main/java/com/threewks/thundr/test/mock/servlet/MockHttpServletResponse.java b/src/main/java/com/threewks/thundr/test/mock/servlet/MockHttpServletResponse.java index 9fe8a95..6d38403 100644 --- a/src/main/java/com/threewks/thundr/test/mock/servlet/MockHttpServletResponse.java +++ b/src/main/java/com/threewks/thundr/test/mock/servlet/MockHttpServletResponse.java @@ -1,282 +1,290 @@ /* * This file is a component of thundr, a software library from 3wks. * Read more: http://www.3wks.com.au/thundr * Copyright (C) 2013 3wks, <[email protected]> * * 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.threewks.thundr.test.mock.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import jodd.io.StringOutputStream; import com.threewks.thundr.exception.BaseException; public class MockHttpServletResponse implements HttpServletResponse { private Map<String, String> headers = new HashMap<String, String>(); private String characterEncoding = "utf-8"; private String contentType = null; private StringOutputStream sos; private int contentLength; private boolean committed = false; private List<Cookie> cookies = new ArrayList<Cookie>(); private int status = -1; private ServletOutputStream servletOutputStream; private PrintWriter writer; public String content() { if (writer != null) { writer.flush(); } if (servletOutputStream != null) { try { servletOutputStream.flush(); } catch (IOException e) { throw new BaseException(e); } } return sos.toString(); } public int status() { return status; } public int getContentLength() { return contentLength; } @Override public String getCharacterEncoding() { return characterEncoding; } @Override public String getContentType() { return contentType; } @Override public ServletOutputStream getOutputStream() throws IOException { if (writer != null) { throw new IllegalStateException("This request attempted to get a ServletOutputStream after getting a PrintWriter from the HttpServletRepsonse"); } if (servletOutputStream == null) { sos = createOutputStream(); servletOutputStream = new ServletOutputStream() { @Override public void write(int arg0) throws IOException { sos.write(arg0); } + @Override + public void write(byte[] b) throws IOException { + sos.write(b); + } + @Override + public void write(byte[] b, int off, int len) throws IOException { + sos.write(b, off, len); + } }; } return servletOutputStream; } @Override public PrintWriter getWriter() throws IOException { if (servletOutputStream != null) { throw new IllegalStateException("This request attempted to get a PrintWriter after getting a ServletOutputStream from the HttpServletRepsonse"); } if (writer == null) { sos = createOutputStream(); writer = new PrintWriter(sos, true); } return writer; } @Override public void setCharacterEncoding(String charset) { this.characterEncoding = charset; } @Override public void setContentLength(int len) { this.contentLength = len; } @Override public void setContentType(String type) { this.contentType = type; } @Override public void setBufferSize(int size) { } @Override public int getBufferSize() { return 0; } @Override public void flushBuffer() throws IOException { sos.flush(); } @Override public void resetBuffer() { } @Override public boolean isCommitted() { return committed; } @Override public void reset() { } @Override public void setLocale(Locale loc) { } @Override public Locale getLocale() { return Locale.getDefault(); } @Override public void addCookie(Cookie cookie) { cookies.add(cookie); } @Override public boolean containsHeader(String name) { return headers.containsKey(name); } @Override public String encodeURL(String url) { return url; } @Override public String encodeRedirectURL(String url) { return url; } @Override public String encodeUrl(String url) { return url; } @Override public String encodeRedirectUrl(String url) { return url; } @Override public void sendError(int sc, String msg) throws IOException { sendError(sc); } @Override public void sendError(int sc) throws IOException { if (committed) { throw new IllegalStateException("Response already committed"); } this.status = sc; committed = true; } @Override public void sendRedirect(String location) throws IOException { if (committed) { throw new IllegalStateException("Response already committed"); } committed = true; } @Override public void setDateHeader(String name, long date) { headers.put(name, Long.toString(date)); } @Override public void addDateHeader(String name, long date) { headers.put(name, Long.toString(date)); } @Override public void setHeader(String name, String value) { headers.put(name, value); } @Override public void addHeader(String name, String value) { headers.put(name, value); } @Override public void setIntHeader(String name, int value) { headers.put(name, Integer.toString(value)); } @Override public void addIntHeader(String name, int value) { headers.put(name, Integer.toString(value)); } @Override public void setStatus(int sc) { if (committed) { throw new IllegalStateException("Response already committed"); } this.status = sc; } @Override public void setStatus(int sc, String sm) { setStatus(sc); } @SuppressWarnings("serial") private StringOutputStream createOutputStream() { sos = new StringOutputStream(characterEncoding) { @Override public void flush() throws IOException { committed = true; super.flush(); } @Override public void close() { } }; return sos; } public List<Cookie> getCookies() { return cookies; } @SuppressWarnings("unchecked") public <T> T header(String name) { return (T) headers.get(name); } }
true
true
public ServletOutputStream getOutputStream() throws IOException { if (writer != null) { throw new IllegalStateException("This request attempted to get a ServletOutputStream after getting a PrintWriter from the HttpServletRepsonse"); } if (servletOutputStream == null) { sos = createOutputStream(); servletOutputStream = new ServletOutputStream() { @Override public void write(int arg0) throws IOException { sos.write(arg0); } }; } return servletOutputStream; }
public ServletOutputStream getOutputStream() throws IOException { if (writer != null) { throw new IllegalStateException("This request attempted to get a ServletOutputStream after getting a PrintWriter from the HttpServletRepsonse"); } if (servletOutputStream == null) { sos = createOutputStream(); servletOutputStream = new ServletOutputStream() { @Override public void write(int arg0) throws IOException { sos.write(arg0); } @Override public void write(byte[] b) throws IOException { sos.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { sos.write(b, off, len); } }; } return servletOutputStream; }
diff --git a/src/gwt/src/org/rstudio/core/client/BrowseCap.java b/src/gwt/src/org/rstudio/core/client/BrowseCap.java index b554a0452e..6be462e598 100644 --- a/src/gwt/src/org/rstudio/core/client/BrowseCap.java +++ b/src/gwt/src/org/rstudio/core/client/BrowseCap.java @@ -1,110 +1,110 @@ /* * BrowseCap.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client; import org.rstudio.core.client.theme.ThemeFonts; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Document; public class BrowseCap { public static double getFontSkew() { if (hasMetaKey()) return -1; else if (FIXED_UBUNTU_MONO) return 0.4; else return 0; } public static final BrowseCap INSTANCE = GWT.create(BrowseCap.class); public boolean suppressBraceHighlighting() { return false; } public boolean aceVerticalScrollBarIssue() { return false; } public boolean suppressBrowserForwardBack() { return false; } public boolean hasWindowFind() { return true; } public static boolean hasMetaKey() { return OPERATING_SYSTEM.equals("macintosh"); } public static boolean isLinux() { return OPERATING_SYSTEM.equals("linux"); } public static boolean isChrome() { return isUserAgent("chrome"); } private static native final boolean isUserAgent(String uaTest) /*-{ var ua = navigator.userAgent.toLowerCase(); if (ua.indexOf(uaTest) != -1) return true; else return false; }-*/; private static native final String getOperatingSystem() /*-{ var ua = navigator.userAgent.toLowerCase(); if (ua.indexOf("linux") != -1) { return "linux"; } else if (ua.indexOf("macintosh") != -1) { return "macintosh"; } return "windows"; }-*/; private static final String OPERATING_SYSTEM = getOperatingSystem(); private static final boolean getFixedUbuntuMono() { if (isLinux()) { String fixedWidthFont = ThemeFonts.getFixedWidthFont(); return (StringUtil.notNull(fixedWidthFont).equals("\"Ubuntu Mono\"")); } else { - return true; + return false; } } private static final boolean FIXED_UBUNTU_MONO = getFixedUbuntuMono(); static { Document.get().getBody().addClassName(OPERATING_SYSTEM); if (FIXED_UBUNTU_MONO) Document.get().getBody().addClassName("ubuntu_mono"); } }
true
true
private static final boolean getFixedUbuntuMono() { if (isLinux()) { String fixedWidthFont = ThemeFonts.getFixedWidthFont(); return (StringUtil.notNull(fixedWidthFont).equals("\"Ubuntu Mono\"")); } else { return true; } }
private static final boolean getFixedUbuntuMono() { if (isLinux()) { String fixedWidthFont = ThemeFonts.getFixedWidthFont(); return (StringUtil.notNull(fixedWidthFont).equals("\"Ubuntu Mono\"")); } else { return false; } }
diff --git a/src/java/org/apache/cassandra/db/SliceFromReadCommand.java b/src/java/org/apache/cassandra/db/SliceFromReadCommand.java index a9bbaf038..889038db3 100644 --- a/src/java/org/apache/cassandra/db/SliceFromReadCommand.java +++ b/src/java/org/apache/cassandra/db/SliceFromReadCommand.java @@ -1,172 +1,173 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.db.filter.IDiskAtomFilter; import org.apache.cassandra.db.filter.QueryFilter; import org.apache.cassandra.db.filter.QueryPath; import org.apache.cassandra.db.filter.SliceQueryFilter; import org.apache.cassandra.io.IVersionedSerializer; import org.apache.cassandra.service.RowDataResolver; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.thrift.ColumnParent; import org.apache.cassandra.utils.ByteBufferUtil; public class SliceFromReadCommand extends ReadCommand { static final Logger logger = LoggerFactory.getLogger(SliceFromReadCommand.class); public final SliceQueryFilter filter; public SliceFromReadCommand(String table, ByteBuffer key, ColumnParent column_parent, ByteBuffer start, ByteBuffer finish, boolean reversed, int count) { this(table, key, new QueryPath(column_parent), start, finish, reversed, count); } public SliceFromReadCommand(String table, ByteBuffer key, QueryPath path, ByteBuffer start, ByteBuffer finish, boolean reversed, int count) { this(table, key, path, new SliceQueryFilter(start, finish, reversed, count)); } public SliceFromReadCommand(String table, ByteBuffer key, QueryPath path, SliceQueryFilter filter) { super(table, key, path, CMD_TYPE_GET_SLICE); this.filter = filter; } public ReadCommand copy() { ReadCommand readCommand = new SliceFromReadCommand(table, key, queryPath, filter); readCommand.setDigestQuery(isDigestQuery()); return readCommand; } public Row getRow(Table table) { DecoratedKey dk = StorageService.getPartitioner().decorateKey(key); return table.getRow(new QueryFilter(dk, queryPath, filter)); } @Override public ReadCommand maybeGenerateRetryCommand(RowDataResolver resolver, Row row) { int maxLiveColumns = resolver.getMaxLiveCount(); int count = filter.count; // We generate a retry if at least one node reply with count live columns but after merge we have less - // than the total number of column we are interested in (which may be < count on a retry) - if (maxLiveColumns >= count) + // than the total number of column we are interested in (which may be < count on a retry). + // So in particular, if no host returned count live columns, we know it's not a short read. + if (maxLiveColumns < count) return null; int liveCountInRow = row == null || row.cf == null ? 0 : filter.getLiveCount(row.cf); if (liveCountInRow < getOriginalRequestedCount()) { // We asked t (= count) live columns and got l (=liveCountInRow) ones. // From that, we can estimate that on this row, for x requested // columns, only l/t end up live after reconciliation. So for next // round we want to ask x column so that x * (l/t) == t, i.e. x = t^2/l. int retryCount = liveCountInRow == 0 ? count + 1 : ((count * count) / liveCountInRow) + 1; SliceQueryFilter newFilter = filter.withUpdatedCount(retryCount); return new RetriedSliceFromReadCommand(table, key, queryPath, newFilter, getOriginalRequestedCount()); } return null; } @Override public void maybeTrim(Row row) { if ((row == null) || (row.cf == null)) return; filter.trim(row.cf, getOriginalRequestedCount()); } public IDiskAtomFilter filter() { return filter; } /** * The original number of columns requested by the user. * This can be different from count when the slice command is a retry (see * RetriedSliceFromReadCommand) */ protected int getOriginalRequestedCount() { return filter.count; } @Override public String toString() { return "SliceFromReadCommand(" + "table='" + table + '\'' + ", key='" + ByteBufferUtil.bytesToHex(key) + '\'' + ", column_parent='" + queryPath + '\'' + ", filter='" + filter + '\'' + ')'; } } class SliceFromReadCommandSerializer implements IVersionedSerializer<ReadCommand> { public void serialize(ReadCommand rm, DataOutput dos, int version) throws IOException { SliceFromReadCommand realRM = (SliceFromReadCommand)rm; dos.writeBoolean(realRM.isDigestQuery()); dos.writeUTF(realRM.table); ByteBufferUtil.writeWithShortLength(realRM.key, dos); realRM.queryPath.serialize(dos); SliceQueryFilter.serializer.serialize(realRM.filter, dos, version); } public ReadCommand deserialize(DataInput dis, int version) throws IOException { boolean isDigest = dis.readBoolean(); String table = dis.readUTF(); ByteBuffer key = ByteBufferUtil.readWithShortLength(dis); QueryPath path = QueryPath.deserialize(dis); SliceQueryFilter filter = SliceQueryFilter.serializer.deserialize(dis, version); SliceFromReadCommand rm = new SliceFromReadCommand(table, key, path, filter); rm.setDigestQuery(isDigest); return rm; } public long serializedSize(ReadCommand cmd, int version) { TypeSizes sizes = TypeSizes.NATIVE; SliceFromReadCommand command = (SliceFromReadCommand) cmd; int keySize = command.key.remaining(); int size = sizes.sizeof(cmd.isDigestQuery()); // boolean size += sizes.sizeof(command.table); size += sizes.sizeof((short) keySize) + keySize; size += command.queryPath.serializedSize(sizes); size += SliceQueryFilter.serializer.serializedSize(command.filter, version); return size; } }
true
true
public ReadCommand maybeGenerateRetryCommand(RowDataResolver resolver, Row row) { int maxLiveColumns = resolver.getMaxLiveCount(); int count = filter.count; // We generate a retry if at least one node reply with count live columns but after merge we have less // than the total number of column we are interested in (which may be < count on a retry) if (maxLiveColumns >= count) return null; int liveCountInRow = row == null || row.cf == null ? 0 : filter.getLiveCount(row.cf); if (liveCountInRow < getOriginalRequestedCount()) { // We asked t (= count) live columns and got l (=liveCountInRow) ones. // From that, we can estimate that on this row, for x requested // columns, only l/t end up live after reconciliation. So for next // round we want to ask x column so that x * (l/t) == t, i.e. x = t^2/l. int retryCount = liveCountInRow == 0 ? count + 1 : ((count * count) / liveCountInRow) + 1; SliceQueryFilter newFilter = filter.withUpdatedCount(retryCount); return new RetriedSliceFromReadCommand(table, key, queryPath, newFilter, getOriginalRequestedCount()); } return null; }
public ReadCommand maybeGenerateRetryCommand(RowDataResolver resolver, Row row) { int maxLiveColumns = resolver.getMaxLiveCount(); int count = filter.count; // We generate a retry if at least one node reply with count live columns but after merge we have less // than the total number of column we are interested in (which may be < count on a retry). // So in particular, if no host returned count live columns, we know it's not a short read. if (maxLiveColumns < count) return null; int liveCountInRow = row == null || row.cf == null ? 0 : filter.getLiveCount(row.cf); if (liveCountInRow < getOriginalRequestedCount()) { // We asked t (= count) live columns and got l (=liveCountInRow) ones. // From that, we can estimate that on this row, for x requested // columns, only l/t end up live after reconciliation. So for next // round we want to ask x column so that x * (l/t) == t, i.e. x = t^2/l. int retryCount = liveCountInRow == 0 ? count + 1 : ((count * count) / liveCountInRow) + 1; SliceQueryFilter newFilter = filter.withUpdatedCount(retryCount); return new RetriedSliceFromReadCommand(table, key, queryPath, newFilter, getOriginalRequestedCount()); } return null; }
diff --git a/frontend/client/src/autotest/tko/DynamicGraphingFrontend.java b/frontend/client/src/autotest/tko/DynamicGraphingFrontend.java index 2c1aa132..d2aca597 100644 --- a/frontend/client/src/autotest/tko/DynamicGraphingFrontend.java +++ b/frontend/client/src/autotest/tko/DynamicGraphingFrontend.java @@ -1,96 +1,97 @@ package autotest.tko; import autotest.common.JsonRpcCallback; import autotest.common.ui.TabView; import autotest.tko.PreconfigSelector.PreconfigHandler; import autotest.tko.TableView.TableSwitchListener; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONValue; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.ClickListener; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.Widget; import java.util.Map; public abstract class DynamicGraphingFrontend extends GraphingFrontend implements ClickListener, PreconfigHandler { protected PreconfigSelector preconfig; protected Button graphButton = new Button("Graph"); protected Plot plot; private TabView parent; public DynamicGraphingFrontend(final TabView parent, Plot plot, String preconfigType) { this.parent = parent; this.plot = plot; plot.setDrilldownTrigger(); preconfig = new PreconfigSelector(preconfigType, this); graphButton.addClickListener(this); } @Override public void onClick(Widget sender) { if (sender != graphButton) { super.onClick(sender); return; } parent.updateHistory(); plot.setVisible(false); embeddingLink.setVisible(false); graphButton.setEnabled(false); JSONObject params = buildParams(); if (params == null) { + graphButton.setEnabled(true); return; } plot.refresh(params, new JsonRpcCallback() { @Override public void onSuccess(JSONValue result) { plot.setVisible(true); embeddingLink.setVisible(true); graphButton.setEnabled(true); } @Override public void onError(JSONObject errorObject) { super.onError(errorObject); graphButton.setEnabled(true); } }); } protected abstract JSONObject buildParams(); @Override public void refresh() { // Nothing to refresh } protected void commonInitialization() { table.setWidget(table.getRowCount(), 1, graphButton); table.setWidget(table.getRowCount(), 0, plot); table.getFlexCellFormatter().setColSpan(table.getRowCount() - 1, 0, 3); table.setWidget(table.getRowCount(), 2, embeddingLink); table.getFlexCellFormatter().setHorizontalAlignment( table.getRowCount() - 1, 2, HasHorizontalAlignment.ALIGN_RIGHT); plot.setVisible(false); embeddingLink.setVisible(false); initWidget(table); } public void handlePreconfig(Map<String, String> preconfigParameters) { handleHistoryArguments(preconfigParameters); } @Override protected void setListener(TableSwitchListener listener) { super.setListener(listener); plot.setListener(listener); } }
true
true
public void onClick(Widget sender) { if (sender != graphButton) { super.onClick(sender); return; } parent.updateHistory(); plot.setVisible(false); embeddingLink.setVisible(false); graphButton.setEnabled(false); JSONObject params = buildParams(); if (params == null) { return; } plot.refresh(params, new JsonRpcCallback() { @Override public void onSuccess(JSONValue result) { plot.setVisible(true); embeddingLink.setVisible(true); graphButton.setEnabled(true); } @Override public void onError(JSONObject errorObject) { super.onError(errorObject); graphButton.setEnabled(true); } }); }
public void onClick(Widget sender) { if (sender != graphButton) { super.onClick(sender); return; } parent.updateHistory(); plot.setVisible(false); embeddingLink.setVisible(false); graphButton.setEnabled(false); JSONObject params = buildParams(); if (params == null) { graphButton.setEnabled(true); return; } plot.refresh(params, new JsonRpcCallback() { @Override public void onSuccess(JSONValue result) { plot.setVisible(true); embeddingLink.setVisible(true); graphButton.setEnabled(true); } @Override public void onError(JSONObject errorObject) { super.onError(errorObject); graphButton.setEnabled(true); } }); }
diff --git a/src/org/mozilla/javascript/Context.java b/src/org/mozilla/javascript/Context.java index 4fb991b3..9c194033 100644 --- a/src/org/mozilla/javascript/Context.java +++ b/src/org/mozilla/javascript/Context.java @@ -1,2519 +1,2522 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Bob Jervis * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.CharArrayWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Hashtable; import java.util.Locale; import org.mozilla.javascript.debug.DebuggableScript; import org.mozilla.javascript.debug.Debugger; import org.mozilla.javascript.xml.XMLLib; /** * This class represents the runtime context of an executing script. * * Before executing a script, an instance of Context must be created * and associated with the thread that will be executing the script. * The Context will be used to store information about the executing * of the script such as the call stack. Contexts are associated with * the current thread using the {@link #call(ContextAction)} * or {@link #enter()} methods.<p> * * Different forms of script execution are supported. Scripts may be * evaluated from the source directly, or first compiled and then later * executed. Interactive execution is also supported.<p> * * Some aspects of script execution, such as type conversions and * object creation, may be accessed directly through methods of * Context. * * @see Scriptable * @author Norris Boyd * @author Brendan Eich */ public class Context { /** * Language versions. * * All integral values are reserved for future version numbers. */ /** * The unknown version. */ public static final int VERSION_UNKNOWN = -1; /** * The default version. */ public static final int VERSION_DEFAULT = 0; /** * JavaScript 1.0 */ public static final int VERSION_1_0 = 100; /** * JavaScript 1.1 */ public static final int VERSION_1_1 = 110; /** * JavaScript 1.2 */ public static final int VERSION_1_2 = 120; /** * JavaScript 1.3 */ public static final int VERSION_1_3 = 130; /** * JavaScript 1.4 */ public static final int VERSION_1_4 = 140; /** * JavaScript 1.5 */ public static final int VERSION_1_5 = 150; /** * JavaScript 1.6 */ public static final int VERSION_1_6 = 160; /** * JavaScript 1.7 */ public static final int VERSION_1_7 = 170; /** * Controls behaviour of <tt>Date.prototype.getYear()</tt>. * If <tt>hasFeature(FEATURE_NON_ECMA_GET_YEAR)</tt> returns true, * Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000. * The default behavior of {@link #hasFeature(int)} is always to subtruct * 1900 as rquired by ECMAScript B.2.4. */ public static final int FEATURE_NON_ECMA_GET_YEAR = 1; /** * Control if member expression as function name extension is available. * If <tt>hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME)</tt> returns * true, allow <tt>function memberExpression(args) { body }</tt> to be * syntax sugar for <tt>memberExpression = function(args) { body }</tt>, * when memberExpression is not a simple identifier. * See ECMAScript-262, section 11.2 for definition of memberExpression. * By default {@link #hasFeature(int)} returns false. */ public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME = 2; /** * Control if reserved keywords are treated as identifiers. * If <tt>hasFeature(RESERVED_KEYWORD_AS_IDENTIFIER)</tt> returns true, * treat future reserved keyword (see Ecma-262, section 7.5.3) as ordinary * identifiers but warn about this usage. * * By default {@link #hasFeature(int)} returns false. */ public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER = 3; /** * Control if <tt>toString()</tt> should returns the same result * as <tt>toSource()</tt> when applied to objects and arrays. * If <tt>hasFeature(FEATURE_TO_STRING_AS_SOURCE)</tt> returns true, * calling <tt>toString()</tt> on JS objects gives the same result as * calling <tt>toSource()</tt>. That is it returns JS source with code * to create an object with all enumeratable fields of the original object * instead of printing <tt>[object <i>result of * {@link Scriptable#getClassName()}</i>]</tt>. * <p> * By default {@link #hasFeature(int)} returns true only if * the current JS version is set to {@link #VERSION_1_2}. */ public static final int FEATURE_TO_STRING_AS_SOURCE = 4; /** * Control if properties <tt>__proto__</tt> and <tt>__parent__</tt> * are treated specially. * If <tt>hasFeature(FEATURE_PARENT_PROTO_PROPERTIES)</tt> returns true, * treat <tt>__parent__</tt> and <tt>__proto__</tt> as special properties. * <p> * The properties allow to query and set scope and prototype chains for the * objects. The special meaning of the properties is available * only when they are used as the right hand side of the dot operator. * For example, while <tt>x.__proto__ = y</tt> changes the prototype * chain of the object <tt>x</tt> to point to <tt>y</tt>, * <tt>x["__proto__"] = y</tt> simply assigns a new value to the property * <tt>__proto__</tt> in <tt>x</tt> even when the feature is on. * * By default {@link #hasFeature(int)} returns true. */ public static final int FEATURE_PARENT_PROTO_PROPERTIES = 5; /** * @deprecated In previous releases, this name was given to * FEATURE_PARENT_PROTO_PROPERTIES. */ public static final int FEATURE_PARENT_PROTO_PROPRTIES = 5; /** * Control if support for E4X(ECMAScript for XML) extension is available. * If hasFeature(FEATURE_E4X) returns true, the XML syntax is available. * <p> * By default {@link #hasFeature(int)} returns true if * the current JS version is set to {@link #VERSION_DEFAULT} * or is at least {@link #VERSION_1_6}. * @since 1.6 Release 1 */ public static final int FEATURE_E4X = 6; /** * Control if dynamic scope should be used for name access. * If hasFeature(FEATURE_DYNAMIC_SCOPE) returns true, then the name lookup * during name resolution will use the top scope of the script or function * which is at the top of JS execution stack instead of the top scope of the * script or function from the current stack frame if the top scope of * the top stack frame contains the top scope of the current stack frame * on its prototype chain. * <p> * This is useful to define shared scope containing functions that can * be called from scripts and functions using private scopes. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.6 Release 1 */ public static final int FEATURE_DYNAMIC_SCOPE = 7; /** * Control if strict variable mode is enabled. * When the feature is on Rhino reports runtime errors if assignment * to a global variable that does not exist is executed. When the feature * is off such assignments creates new variable in the global scope as * required by ECMA 262. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.6 Release 1 */ public static final int FEATURE_STRICT_VARS = 8; /** * Control if strict eval mode is enabled. * When the feature is on Rhino reports runtime errors if non-string * argument is passed to the eval function. When the feature is off * eval simply return non-string argument as is without performing any * evaluation as required by ECMA 262. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.6 Release 1 */ public static final int FEATURE_STRICT_EVAL = 9; /** * When the feature is on Rhino will add a "fileName" and "lineNumber" * properties to Error objects automatically. When the feature is off, you * have to explicitly pass them as the second and third argument to the * Error constructor. Note that neither behaviour is fully ECMA 262 * compliant (as 262 doesn't specify a three-arg constructor), but keeping * the feature off results in Error objects that don't have * additional non-ECMA properties when constructed using the ECMA-defined * single-arg constructor and is thus desirable if a stricter ECMA * compliance is desired, specifically adherence to the point 15.11.5. of * the standard. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.6 Release 6 */ public static final int FEATURE_LOCATION_INFORMATION_IN_ERROR = 10; /** * Controls whether JS 1.5 'strict mode' is enabled. * When the feature is on, Rhino reports more than a dozen different * warnings. When the feature is off, these warnings are not generated. * FEATURE_STRICT_MODE implies FEATURE_STRICT_VARS and FEATURE_STRICT_EVAL. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.6 Release 6 */ public static final int FEATURE_STRICT_MODE = 11; /** * Controls whether a warning should be treated as an error. * @since 1.6 Release 6 */ public static final int FEATURE_WARNING_AS_ERROR = 12; /** * Enables enhanced access to Java. * Specifically, controls whether private and protected members can be * accessed, and whether scripts can catch all Java exceptions. * <p> * Note that this feature should only be enabled for trusted scripts. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.7 Release 1 */ public static final int FEATURE_ENHANCED_JAVA_ACCESS = 13; public static final String languageVersionProperty = "language version"; public static final String errorReporterProperty = "error reporter"; /** * Convenient value to use as zero-length array of objects. */ public static final Object[] emptyArgs = ScriptRuntime.emptyArgs; /** * Create a new Context. * * Note that the Context must be associated with a thread before * it can be used to execute a script. * @deprecated use {@link ContextFactory#enter()} or * {@link ContextFactory#call(ContextAction)} instead. */ public Context() { this(ContextFactory.getGlobal()); } Context(ContextFactory factory) { assert factory != null; this.factory = factory; setLanguageVersion(VERSION_DEFAULT); optimizationLevel = codegenClass != null ? 0 : -1; maximumInterpreterStackDepth = Integer.MAX_VALUE; } /** * Get the current Context. * * The current Context is per-thread; this method looks up * the Context associated with the current thread. <p> * * @return the Context associated with the current thread, or * null if no context is associated with the current * thread. * @see ContextFactory#enterContext() * @see ContextFactory#call(ContextAction) */ public static Context getCurrentContext() { Object helper = VMBridge.instance.getThreadContextHelper(); return VMBridge.instance.getContext(helper); } /** * Same as calling {@link ContextFactory#enterContext()} on the global * ContextFactory instance. * @deprecated use {@link ContextFactory#enter()} or * {@link ContextFactory#call(ContextAction)} instead as this method relies * on usage of a static singleton "global" ContextFactory. * @return a Context associated with the current thread * @see #getCurrentContext() * @see #exit() * @see #call(ContextAction) */ public static Context enter() { return enter(null); } /** * Get a Context associated with the current thread, using * the given Context if need be. * <p> * The same as <code>enter()</code> except that <code>cx</code> * is associated with the current thread and returned if * the current thread has no associated context and <code>cx</code> * is not associated with any other thread. * @param cx a Context to associate with the thread if possible * @return a Context associated with the current thread * @deprecated use {@link ContextFactory#enterContext(Context)} instead as * this method relies on usage of a static singleton "global" ContextFactory. * @see ContextFactory#enterContext(Context) * @see ContextFactory#call(ContextAction) */ public static Context enter(Context cx) { return enter(cx, ContextFactory.getGlobal()); } static final Context enter(Context cx, ContextFactory factory) { Object helper = VMBridge.instance.getThreadContextHelper(); Context old = VMBridge.instance.getContext(helper); if (old != null) { cx = old; } else { if (cx == null) { cx = factory.makeContext(); if (cx.enterCount != 0) { throw new IllegalStateException("factory.makeContext() returned Context instance already associated with some thread"); } factory.onContextCreated(cx); if (factory.isSealed() && !cx.isSealed()) { cx.seal(null); } } else { if (cx.enterCount != 0) { throw new IllegalStateException("can not use Context instance already associated with some thread"); } } VMBridge.instance.setContext(helper, cx); } ++cx.enterCount; return cx; } /** * Exit a block of code requiring a Context. * * Calling <code>exit()</code> will remove the association between * the current thread and a Context if the prior call to * {@link ContextFactory#enterContext()} on this thread newly associated a * Context with this thread. Once the current thread no longer has an * associated Context, it cannot be used to execute JavaScript until it is * again associated with a Context. * @see ContextFactory#enterContext() */ public static void exit() { Object helper = VMBridge.instance.getThreadContextHelper(); Context cx = VMBridge.instance.getContext(helper); if (cx == null) { throw new IllegalStateException( "Calling Context.exit without previous Context.enter"); } if (cx.enterCount < 1) Kit.codeBug(); if (--cx.enterCount == 0) { VMBridge.instance.setContext(helper, null); cx.factory.onContextReleased(cx); } } /** * Call {@link ContextAction#run(Context cx)} * using the Context instance associated with the current thread. * If no Context is associated with the thread, then * <tt>ContextFactory.getGlobal().makeContext()</tt> will be called to * construct new Context instance. The instance will be temporary * associated with the thread during call to * {@link ContextAction#run(Context)}. * @deprecated use {@link ContextFactory#call(ContextAction)} instead as * this method relies on usage of a static singleton "global" * ContextFactory. * @return The result of {@link ContextAction#run(Context)}. */ public static Object call(ContextAction action) { return call(ContextFactory.getGlobal(), action); } /** * Call {@link * Callable#call(Context cx, Scriptable scope, Scriptable thisObj, * Object[] args)} * using the Context instance associated with the current thread. * If no Context is associated with the thread, then * {@link ContextFactory#makeContext()} will be called to construct * new Context instance. The instance will be temporary associated * with the thread during call to {@link ContextAction#run(Context)}. * <p> * It is allowed but not advisable to use null for <tt>factory</tt> * argument in which case the global static singleton ContextFactory * instance will be used to create new context instances. * @see ContextFactory#call(ContextAction) */ public static Object call(ContextFactory factory, final Callable callable, final Scriptable scope, final Scriptable thisObj, final Object[] args) { if(factory == null) { factory = ContextFactory.getGlobal(); } return call(factory, new ContextAction() { public Object run(Context cx) { return callable.call(cx, scope, thisObj, args); } }); } /** * The method implements {@links ContextFactory#call(ContextAction)} logic. */ static Object call(ContextFactory factory, ContextAction action) { Context cx = enter(null, factory); try { return action.run(cx); } finally { exit(); } } /** * @deprecated * @see ContextFactory#addListener(ContextFactory.Listener) * @see ContextFactory#getGlobal() */ public static void addContextListener(ContextListener listener) { // Special workaround for the debugger String DBG = "org.mozilla.javascript.tools.debugger.Main"; if (DBG.equals(listener.getClass().getName())) { Class cl = listener.getClass(); Class factoryClass = Kit.classOrNull( "org.mozilla.javascript.ContextFactory"); Class[] sig = { factoryClass }; Object[] args = { ContextFactory.getGlobal() }; try { Method m = cl.getMethod("attachTo", sig); m.invoke(listener, args); } catch (Exception ex) { RuntimeException rex = new RuntimeException(); Kit.initCause(rex, ex); throw rex; } return; } ContextFactory.getGlobal().addListener(listener); } /** * @deprecated * @see ContextFactory#removeListener(ContextFactory.Listener) * @see ContextFactory#getGlobal() */ public static void removeContextListener(ContextListener listener) { ContextFactory.getGlobal().addListener(listener); } /** * Return {@link ContextFactory} instance used to create this Context. */ public final ContextFactory getFactory() { return factory; } /** * Checks if this is a sealed Context. A sealed Context instance does not * allow to modify any of its properties and will throw an exception * on any such attempt. * @see #seal(Object sealKey) */ public final boolean isSealed() { return sealed; } /** * Seal this Context object so any attempt to modify any of its properties * including calling {@link #enter()} and {@link #exit()} methods will * throw an exception. * <p> * If <tt>sealKey</tt> is not null, calling * {@link #unseal(Object sealKey)} with the same key unseals * the object. If <tt>sealKey</tt> is null, unsealing is no longer possible. * * @see #isSealed() * @see #unseal(Object) */ public final void seal(Object sealKey) { if (sealed) onSealedMutation(); sealed = true; this.sealKey = sealKey; } /** * Unseal previously sealed Context object. * The <tt>sealKey</tt> argument should not be null and should match * <tt>sealKey</tt> suplied with the last call to * {@link #seal(Object)} or an exception will be thrown. * * @see #isSealed() * @see #seal(Object sealKey) */ public final void unseal(Object sealKey) { if (sealKey == null) throw new IllegalArgumentException(); if (this.sealKey != sealKey) throw new IllegalArgumentException(); if (!sealed) throw new IllegalStateException(); sealed = false; this.sealKey = null; } static void onSealedMutation() { throw new IllegalStateException(); } /** * Get the current language version. * <p> * The language version number affects JavaScript semantics as detailed * in the overview documentation. * * @return an integer that is one of VERSION_1_0, VERSION_1_1, etc. */ public final int getLanguageVersion() { return version; } /** * Set the language version. * * <p> * Setting the language version will affect functions and scripts compiled * subsequently. See the overview documentation for version-specific * behavior. * * @param version the version as specified by VERSION_1_0, VERSION_1_1, etc. */ public void setLanguageVersion(int version) { if (sealed) onSealedMutation(); checkLanguageVersion(version); Object listeners = propertyListeners; if (listeners != null && version != this.version) { firePropertyChangeImpl(listeners, languageVersionProperty, new Integer(this.version), new Integer(version)); } this.version = version; } public static boolean isValidLanguageVersion(int version) { switch (version) { case VERSION_DEFAULT: case VERSION_1_0: case VERSION_1_1: case VERSION_1_2: case VERSION_1_3: case VERSION_1_4: case VERSION_1_5: case VERSION_1_6: case VERSION_1_7: return true; } return false; } public static void checkLanguageVersion(int version) { if (isValidLanguageVersion(version)) { return; } throw new IllegalArgumentException("Bad language version: "+version); } /** * Get the implementation version. * * <p> * The implementation version is of the form * <pre> * "<i>name langVer</i> <code>release</code> <i>relNum date</i>" * </pre> * where <i>name</i> is the name of the product, <i>langVer</i> is * the language version, <i>relNum</i> is the release number, and * <i>date</i> is the release date for that specific * release in the form "yyyy mm dd". * * @return a string that encodes the product, language version, release * number, and date. */ public final String getImplementationVersion() { // XXX Probably it would be better to embed this directly into source // with special build preprocessing but that would require some ant // tweaking and then replacing token in resource files was simpler if (implementationVersion == null) { implementationVersion = ScriptRuntime.getMessage0("implementation.version"); } return implementationVersion; } /** * Get the current error reporter. * * @see org.mozilla.javascript.ErrorReporter */ public final ErrorReporter getErrorReporter() { if (errorReporter == null) { return DefaultErrorReporter.instance; } return errorReporter; } /** * Change the current error reporter. * * @return the previous error reporter * @see org.mozilla.javascript.ErrorReporter */ public final ErrorReporter setErrorReporter(ErrorReporter reporter) { if (sealed) onSealedMutation(); if (reporter == null) throw new IllegalArgumentException(); ErrorReporter old = getErrorReporter(); if (reporter == old) { return old; } Object listeners = propertyListeners; if (listeners != null) { firePropertyChangeImpl(listeners, errorReporterProperty, old, reporter); } this.errorReporter = reporter; return old; } /** * Get the current locale. Returns the default locale if none has * been set. * * @see java.util.Locale */ public final Locale getLocale() { if (locale == null) locale = Locale.getDefault(); return locale; } /** * Set the current locale. * * @see java.util.Locale */ public final Locale setLocale(Locale loc) { if (sealed) onSealedMutation(); Locale result = locale; locale = loc; return result; } /** * Register an object to receive notifications when a bound property * has changed * @see java.beans.PropertyChangeEvent * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) * @param l the listener */ public final void addPropertyChangeListener(PropertyChangeListener l) { if (sealed) onSealedMutation(); propertyListeners = Kit.addListener(propertyListeners, l); } /** * Remove an object from the list of objects registered to receive * notification of changes to a bounded property * @see java.beans.PropertyChangeEvent * @see #addPropertyChangeListener(java.beans.PropertyChangeListener) * @param l the listener */ public final void removePropertyChangeListener(PropertyChangeListener l) { if (sealed) onSealedMutation(); propertyListeners = Kit.removeListener(propertyListeners, l); } /** * Notify any registered listeners that a bounded property has changed * @see #addPropertyChangeListener(java.beans.PropertyChangeListener) * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) * @see java.beans.PropertyChangeListener * @see java.beans.PropertyChangeEvent * @param property the bound property * @param oldValue the old value * @param newValue the new value */ final void firePropertyChange(String property, Object oldValue, Object newValue) { Object listeners = propertyListeners; if (listeners != null) { firePropertyChangeImpl(listeners, property, oldValue, newValue); } } private void firePropertyChangeImpl(Object listeners, String property, Object oldValue, Object newValue) { for (int i = 0; ; ++i) { Object l = Kit.getListener(listeners, i); if (l == null) break; if (l instanceof PropertyChangeListener) { PropertyChangeListener pcl = (PropertyChangeListener)l; pcl.propertyChange(new PropertyChangeEvent( this, property, oldValue, newValue)); } } } /** * Report a warning using the error reporter for the current thread. * * @param message the warning message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @see org.mozilla.javascript.ErrorReporter */ public static void reportWarning(String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = Context.getContext(); if (cx.hasFeature(FEATURE_WARNING_AS_ERROR)) reportError(message, sourceName, lineno, lineSource, lineOffset); else cx.getErrorReporter().warning(message, sourceName, lineno, lineSource, lineOffset); } /** * Report a warning using the error reporter for the current thread. * * @param message the warning message to report * @see org.mozilla.javascript.ErrorReporter */ public static void reportWarning(String message) { int[] linep = { 0 }; String filename = getSourcePositionFromStack(linep); Context.reportWarning(message, filename, linep[0], null, 0); } public static void reportWarning(String message, Throwable t) { int[] linep = { 0 }; String filename = getSourcePositionFromStack(linep); Writer sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(message); t.printStackTrace(pw); pw.flush(); Context.reportWarning(sw.toString(), filename, linep[0], null, 0); } /** * Report an error using the error reporter for the current thread. * * @param message the error message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @see org.mozilla.javascript.ErrorReporter */ public static void reportError(String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = getCurrentContext(); if (cx != null) { cx.getErrorReporter().error(message, sourceName, lineno, lineSource, lineOffset); } else { throw new EvaluatorException(message, sourceName, lineno, lineSource, lineOffset); } } /** * Report an error using the error reporter for the current thread. * * @param message the error message to report * @see org.mozilla.javascript.ErrorReporter */ public static void reportError(String message) { int[] linep = { 0 }; String filename = getSourcePositionFromStack(linep); Context.reportError(message, filename, linep[0], null, 0); } /** * Report a runtime error using the error reporter for the current thread. * * @param message the error message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @return a runtime exception that will be thrown to terminate the * execution of the script * @see org.mozilla.javascript.ErrorReporter */ public static EvaluatorException reportRuntimeError(String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = getCurrentContext(); if (cx != null) { return cx.getErrorReporter(). runtimeError(message, sourceName, lineno, lineSource, lineOffset); } else { throw new EvaluatorException(message, sourceName, lineno, lineSource, lineOffset); } } static EvaluatorException reportRuntimeError0(String messageId) { String msg = ScriptRuntime.getMessage0(messageId); return reportRuntimeError(msg); } static EvaluatorException reportRuntimeError1(String messageId, Object arg1) { String msg = ScriptRuntime.getMessage1(messageId, arg1); return reportRuntimeError(msg); } static EvaluatorException reportRuntimeError2(String messageId, Object arg1, Object arg2) { String msg = ScriptRuntime.getMessage2(messageId, arg1, arg2); return reportRuntimeError(msg); } static EvaluatorException reportRuntimeError3(String messageId, Object arg1, Object arg2, Object arg3) { String msg = ScriptRuntime.getMessage3(messageId, arg1, arg2, arg3); return reportRuntimeError(msg); } static EvaluatorException reportRuntimeError4(String messageId, Object arg1, Object arg2, Object arg3, Object arg4) { String msg = ScriptRuntime.getMessage4(messageId, arg1, arg2, arg3, arg4); return reportRuntimeError(msg); } /** * Report a runtime error using the error reporter for the current thread. * * @param message the error message to report * @see org.mozilla.javascript.ErrorReporter */ public static EvaluatorException reportRuntimeError(String message) { int[] linep = { 0 }; String filename = getSourcePositionFromStack(linep); return Context.reportRuntimeError(message, filename, linep[0], null, 0); } /** * Initialize the standard objects. * * Creates instances of the standard objects and their constructors * (Object, String, Number, Date, etc.), setting up 'scope' to act * as a global object as in ECMA 15.1.<p> * * This method must be called to initialize a scope before scripts * can be evaluated in that scope.<p> * * This method does not affect the Context it is called upon. * * @return the initialized scope */ public final ScriptableObject initStandardObjects() { return initStandardObjects(null, false); } /** * Initialize the standard objects. * * Creates instances of the standard objects and their constructors * (Object, String, Number, Date, etc.), setting up 'scope' to act * as a global object as in ECMA 15.1.<p> * * This method must be called to initialize a scope before scripts * can be evaluated in that scope.<p> * * This method does not affect the Context it is called upon. * * @param scope the scope to initialize, or null, in which case a new * object will be created to serve as the scope * @return the initialized scope. The method returns the value of the scope * argument if it is not null or newly allocated scope object which * is an instance {@link ScriptableObject}. */ public final Scriptable initStandardObjects(ScriptableObject scope) { return initStandardObjects(scope, false); } /** * Initialize the standard objects. * * Creates instances of the standard objects and their constructors * (Object, String, Number, Date, etc.), setting up 'scope' to act * as a global object as in ECMA 15.1.<p> * * This method must be called to initialize a scope before scripts * can be evaluated in that scope.<p> * * This method does not affect the Context it is called upon.<p> * * This form of the method also allows for creating "sealed" standard * objects. An object that is sealed cannot have properties added, changed, * or removed. This is useful to create a "superglobal" that can be shared * among several top-level objects. Note that sealing is not allowed in * the current ECMA/ISO language specification, but is likely for * the next version. * * @param scope the scope to initialize, or null, in which case a new * object will be created to serve as the scope * @param sealed whether or not to create sealed standard objects that * cannot be modified. * @return the initialized scope. The method returns the value of the scope * argument if it is not null or newly allocated scope object. * @since 1.4R3 */ public ScriptableObject initStandardObjects(ScriptableObject scope, boolean sealed) { return ScriptRuntime.initStandardObjects(this, scope, sealed); } /** * Get the singleton object that represents the JavaScript Undefined value. */ public static Object getUndefinedValue() { return Undefined.instance; } /** * Evaluate a JavaScript source string. * * The provided source name and line number are used for error messages * and for producing debug information. * * @param scope the scope to execute in * @param source the JavaScript source * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security * information about the origin or owner of the script. For * implementations that don't care about security, this value * may be null. * @return the result of evaluating the string * @see org.mozilla.javascript.SecurityController */ public final Object evaluateString(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain) { Script script = compileString(source, sourceName, lineno, securityDomain); if (script != null) { return script.exec(this, scope); } else { return null; } } /** * Evaluate a reader as JavaScript source. * * All characters of the reader are consumed. * * @param scope the scope to execute in * @param in the Reader to get JavaScript source from * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security * information about the origin or owner of the script. For * implementations that don't care about security, this value * may be null. * @return the result of evaluating the source * * @exception IOException if an IOException was generated by the Reader */ public final Object evaluateReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { Script script = compileReader(scope, in, sourceName, lineno, securityDomain); if (script != null) { return script.exec(this, scope); } else { return null; } } /** * Check whether a string is ready to be compiled. * <p> * stringIsCompilableUnit is intended to support interactive compilation of * javascript. If compiling the string would result in an error * that might be fixed by appending more source, this method * returns false. In every other case, it returns true. * <p> * Interactive shells may accumulate source lines, using this * method after each new line is appended to check whether the * statement being entered is complete. * * @param source the source buffer to check * @return whether the source is ready for compilation * @since 1.4 Release 2 */ public final boolean stringIsCompilableUnit(String source) { boolean errorseen = false; CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); // no source name or source text manager, because we're just // going to throw away the result. compilerEnv.setGeneratingSource(false); Parser p = new Parser(compilerEnv, DefaultErrorReporter.instance); try { p.parse(source, null, 1); } catch (EvaluatorException ee) { errorseen = true; } // Return false only if an error occurred as a result of reading past // the end of the file, i.e. if the source could be fixed by // appending more source. if (errorseen && p.eof()) return false; else return true; } /** * @deprecated * @see #compileReader(Reader in, String sourceName, int lineno, * Object securityDomain) */ public final Script compileReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { return compileReader(in, sourceName, lineno, securityDomain); } /** * Compiles the source in the given reader. * <p> * Returns a script that may later be executed. * Will consume all the source in the reader. * * @param in the input reader * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number for reporting errors * @param securityDomain an arbitrary object that specifies security * information about the origin or owner of the script. For * implementations that don't care about security, this value * may be null. * @return a script that may later be executed * @exception IOException if an IOException was generated by the Reader * @see org.mozilla.javascript.Script */ public final Script compileReader(Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { if (lineno < 0) { // For compatibility IllegalArgumentException can not be thrown here lineno = 0; } return (Script) compileImpl(null, in, null, sourceName, lineno, securityDomain, false, null, null); } /** * Compiles the source in the given string. * <p> * Returns a script that may later be executed. * * @param source the source string * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number for reporting errors * @param securityDomain an arbitrary object that specifies security * information about the origin or owner of the script. For * implementations that don't care about security, this value * may be null. * @return a script that may later be executed * @see org.mozilla.javascript.Script */ public final Script compileString(String source, String sourceName, int lineno, Object securityDomain) { if (lineno < 0) { // For compatibility IllegalArgumentException can not be thrown here lineno = 0; } return compileString(source, null, null, sourceName, lineno, securityDomain); } final Script compileString(String source, Evaluator compiler, ErrorReporter compilationErrorReporter, String sourceName, int lineno, Object securityDomain) { try { return (Script) compileImpl(null, null, source, sourceName, lineno, securityDomain, false, compiler, compilationErrorReporter); } catch (IOException ex) { // Should not happen when dealing with source as string throw new RuntimeException(); } } /** * Compile a JavaScript function. * <p> * The function source must be a function definition as defined by * ECMA (e.g., "function f(a) { return a; }"). * * @param scope the scope to compile relative to * @param source the function definition source * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security * information about the origin or owner of the script. For * implementations that don't care about security, this value * may be null. * @return a Function that may later be called * @see org.mozilla.javascript.Function */ public final Function compileFunction(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain) { return compileFunction(scope, source, null, null, sourceName, lineno, securityDomain); } final Function compileFunction(Scriptable scope, String source, Evaluator compiler, ErrorReporter compilationErrorReporter, String sourceName, int lineno, Object securityDomain) { try { return (Function) compileImpl(scope, null, source, sourceName, lineno, securityDomain, true, compiler, compilationErrorReporter); } catch (IOException ioe) { // Should never happen because we just made the reader // from a String throw new RuntimeException(); } } /** * Decompile the script. * <p> * The canonical source of the script is returned. * * @param script the script to decompile * @param indent the number of spaces to indent the result * @return a string representing the script source */ public final String decompileScript(Script script, int indent) { NativeFunction scriptImpl = (NativeFunction) script; return scriptImpl.decompile(indent, 0); } /** * Decompile a JavaScript Function. * <p> * Decompiles a previously compiled JavaScript function object to * canonical source. * <p> * Returns function body of '[native code]' if no decompilation * information is available. * * @param fun the JavaScript function to decompile * @param indent the number of spaces to indent the result * @return a string representing the function source */ public final String decompileFunction(Function fun, int indent) { if (fun instanceof BaseFunction) return ((BaseFunction)fun).decompile(indent, 0); else return "function " + fun.getClassName() + "() {\n\t[native code]\n}\n"; } /** * Decompile the body of a JavaScript Function. * <p> * Decompiles the body a previously compiled JavaScript Function * object to canonical source, omitting the function header and * trailing brace. * * Returns '[native code]' if no decompilation information is available. * * @param fun the JavaScript function to decompile * @param indent the number of spaces to indent the result * @return a string representing the function body source. */ public final String decompileFunctionBody(Function fun, int indent) { if (fun instanceof BaseFunction) { BaseFunction bf = (BaseFunction)fun; return bf.decompile(indent, Decompiler.ONLY_BODY_FLAG); } // ALERT: not sure what the right response here is. return "[native code]\n"; } /** * Create a new JavaScript object. * * Equivalent to evaluating "new Object()". * @param scope the scope to search for the constructor and to evaluate * against * @return the new object */ public final Scriptable newObject(Scriptable scope) { return newObject(scope, "Object", ScriptRuntime.emptyArgs); } /** * Create a new JavaScript object by executing the named constructor. * * The call <code>newObject(scope, "Foo")</code> is equivalent to * evaluating "new Foo()". * * @param scope the scope to search for the constructor and to evaluate against * @param constructorName the name of the constructor to call * @return the new object */ public final Scriptable newObject(Scriptable scope, String constructorName) { return newObject(scope, constructorName, ScriptRuntime.emptyArgs); } /** * Creates a new JavaScript object by executing the named constructor. * * Searches <code>scope</code> for the named constructor, calls it with * the given arguments, and returns the result.<p> * * The code * <pre> * Object[] args = { "a", "b" }; * newObject(scope, "Foo", args)</pre> * is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo * constructor has been defined in <code>scope</code>. * * @param scope The scope to search for the constructor and to evaluate * against * @param constructorName the name of the constructor to call * @param args the array of arguments for the constructor * @return the new object */ public final Scriptable newObject(Scriptable scope, String constructorName, Object[] args) { scope = ScriptableObject.getTopLevelScope(scope); Function ctor = ScriptRuntime.getExistingCtor(this, scope, constructorName); if (args == null) { args = ScriptRuntime.emptyArgs; } return ctor.construct(this, scope, args); } /** * Create an array with a specified initial length. * <p> * @param scope the scope to create the object in * @param length the initial length (JavaScript arrays may have * additional properties added dynamically). * @return the new array object */ public final Scriptable newArray(Scriptable scope, int length) { NativeArray result = new NativeArray(length); ScriptRuntime.setObjectProtoAndParent(result, scope); return result; } /** * Create an array with a set of initial elements. * * @param scope the scope to create the object in. * @param elements the initial elements. Each object in this array * must be an acceptable JavaScript type and type * of array should be exactly Object[], not * SomeObjectSubclass[]. * @return the new array object. */ public final Scriptable newArray(Scriptable scope, Object[] elements) { if (elements.getClass().getComponentType() != ScriptRuntime.ObjectClass) throw new IllegalArgumentException(); NativeArray result = new NativeArray(elements); ScriptRuntime.setObjectProtoAndParent(result, scope); return result; } /** * Get the elements of a JavaScript array. * <p> * If the object defines a length property convertible to double number, * then the number is converted Uint32 value as defined in Ecma 9.6 * and Java array of that size is allocated. * The array is initialized with the values obtained by * calling get() on object for each value of i in [0,length-1]. If * there is not a defined value for a property the Undefined value * is used to initialize the corresponding element in the array. The * Java array is then returned. * If the object doesn't define a length property or it is not a number, * empty array is returned. * @param object the JavaScript array or array-like object * @return a Java array of objects * @since 1.4 release 2 */ public final Object[] getElements(Scriptable object) { return ScriptRuntime.getArrayElements(object); } /** * Convert the value to a JavaScript boolean value. * <p> * See ECMA 9.2. * * @param value a JavaScript value * @return the corresponding boolean value converted using * the ECMA rules */ public static boolean toBoolean(Object value) { return ScriptRuntime.toBoolean(value); } /** * Convert the value to a JavaScript Number value. * <p> * Returns a Java double for the JavaScript Number. * <p> * See ECMA 9.3. * * @param value a JavaScript value * @return the corresponding double value converted using * the ECMA rules */ public static double toNumber(Object value) { return ScriptRuntime.toNumber(value); } /** * Convert the value to a JavaScript String value. * <p> * See ECMA 9.8. * <p> * @param value a JavaScript value * @return the corresponding String value converted using * the ECMA rules */ public static String toString(Object value) { return ScriptRuntime.toString(value); } /** * Convert the value to an JavaScript object value. * <p> * Note that a scope must be provided to look up the constructors * for Number, Boolean, and String. * <p> * See ECMA 9.9. * <p> * Additionally, arbitrary Java objects and classes will be * wrapped in a Scriptable object with its Java fields and methods * reflected as JavaScript properties of the object. * * @param value any Java object * @param scope global scope containing constructors for Number, * Boolean, and String * @return new JavaScript object */ public static Scriptable toObject(Object value, Scriptable scope) { return ScriptRuntime.toObject(scope, value); } /** * @deprecated * @see #toObject(Object, Scriptable) */ public static Scriptable toObject(Object value, Scriptable scope, Class staticType) { return ScriptRuntime.toObject(scope, value); } /** * Convenient method to convert java value to its closest representation * in JavaScript. * <p> * If value is an instance of String, Number, Boolean, Function or * Scriptable, it is returned as it and will be treated as the corresponding * JavaScript type of string, number, boolean, function and object. * <p> * Note that for Number instances during any arithmetic operation in * JavaScript the engine will always use the result of * <tt>Number.doubleValue()</tt> resulting in a precision loss if * the number can not fit into double. * <p> * If value is an instance of Character, it will be converted to string of * length 1 and its JavaScript type will be string. * <p> * The rest of values will be wrapped as LiveConnect objects * by calling {@link WrapFactory#wrap(Context cx, Scriptable scope, * Object obj, Class staticType)} as in: * <pre> * Context cx = Context.getCurrentContext(); * return cx.getWrapFactory().wrap(cx, scope, value, null); * </pre> * * @param value any Java object * @param scope top scope object * @return value suitable to pass to any API that takes JavaScript values. */ public static Object javaToJS(Object value, Scriptable scope) { if (value instanceof String || value instanceof Number || value instanceof Boolean || value instanceof Scriptable) { return value; } else if (value instanceof Character) { return String.valueOf(((Character)value).charValue()); } else { Context cx = Context.getContext(); return cx.getWrapFactory().wrap(cx, scope, value, null); } } /** * Convert a JavaScript value into the desired type. * Uses the semantics defined with LiveConnect3 and throws an * Illegal argument exception if the conversion cannot be performed. * @param value the JavaScript value to convert * @param desiredType the Java type to convert to. Primitive Java * types are represented using the TYPE fields in the corresponding * wrapper class in java.lang. * @return the converted value * @throws EvaluatorException if the conversion cannot be performed */ public static Object jsToJava(Object value, Class desiredType) throws EvaluatorException { return NativeJavaObject.coerceTypeImpl(desiredType, value); } /** * @deprecated * @see #jsToJava(Object, Class) * @throws IllegalArgumentException if the conversion cannot be performed. * Note that {@link #jsToJava(Object, Class)} throws * {@link EvaluatorException} instead. */ public static Object toType(Object value, Class desiredType) throws IllegalArgumentException { try { return jsToJava(value, desiredType); } catch (EvaluatorException ex) { IllegalArgumentException ex2 = new IllegalArgumentException(ex.getMessage()); Kit.initCause(ex2, ex); throw ex2; } } /** * Rethrow the exception wrapping it as the script runtime exception. * Unless the exception is instance of {@link EcmaError} or * {@link EvaluatorException} it will be wrapped as * {@link WrappedException}, a subclass of {@link EvaluatorException}. * The resulting exception object always contains * source name and line number of script that triggered exception. * <p> * This method always throws an exception, its return value is provided * only for convenience to allow a usage like: * <pre> * throw Context.throwAsScriptRuntimeEx(ex); * </pre> * to indicate that code after the method is unreachable. * @throws EvaluatorException * @throws EcmaError */ public static RuntimeException throwAsScriptRuntimeEx(Throwable e) { while ((e instanceof InvocationTargetException)) { e = ((InvocationTargetException) e).getTargetException(); } // special handling of Error so scripts would not catch them if (e instanceof Error) { Context cx = getContext(); if (cx == null || !cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)) { throw (Error)e; } } if (e instanceof RhinoException) { throw (RhinoException)e; } throw new WrappedException(e); } /** * Tell whether debug information is being generated. * @since 1.3 */ public final boolean isGeneratingDebug() { return generatingDebug; } /** * Specify whether or not debug information should be generated. * <p> * Setting the generation of debug information on will set the * optimization level to zero. * @since 1.3 */ public final void setGeneratingDebug(boolean generatingDebug) { if (sealed) onSealedMutation(); generatingDebugChanged = true; if (generatingDebug && getOptimizationLevel() > 0) setOptimizationLevel(0); this.generatingDebug = generatingDebug; } /** * Tell whether source information is being generated. * @since 1.3 */ public final boolean isGeneratingSource() { return generatingSource; } /** * Specify whether or not source information should be generated. * <p> * Without source information, evaluating the "toString" method * on JavaScript functions produces only "[native code]" for * the body of the function. * Note that code generated without source is not fully ECMA * conformant. * @since 1.3 */ public final void setGeneratingSource(boolean generatingSource) { if (sealed) onSealedMutation(); this.generatingSource = generatingSource; } /** * Get the current optimization level. * <p> * The optimization level is expressed as an integer between -1 and * 9. * @since 1.3 * */ public final int getOptimizationLevel() { return optimizationLevel; } /** * Set the current optimization level. * <p> * The optimization level is expected to be an integer between -1 and * 9. Any negative values will be interpreted as -1, and any values * greater than 9 will be interpreted as 9. * An optimization level of -1 indicates that interpretive mode will * always be used. Levels 0 through 9 indicate that class files may * be generated. Higher optimization levels trade off compile time * performance for runtime performance. * The optimizer level can't be set greater than -1 if the optimizer * package doesn't exist at run time. * @param optimizationLevel an integer indicating the level of * optimization to perform * @since 1.3 * */ public final void setOptimizationLevel(int optimizationLevel) { if (sealed) onSealedMutation(); if (optimizationLevel == -2) { // To be compatible with Cocoon fork optimizationLevel = -1; } checkOptimizationLevel(optimizationLevel); if (codegenClass == null) optimizationLevel = -1; this.optimizationLevel = optimizationLevel; } public static boolean isValidOptimizationLevel(int optimizationLevel) { return -1 <= optimizationLevel && optimizationLevel <= 9; } public static void checkOptimizationLevel(int optimizationLevel) { if (isValidOptimizationLevel(optimizationLevel)) { return; } throw new IllegalArgumentException( "Optimization level outside [-1..9]: "+optimizationLevel); } /** * Returns the maximum stack depth (in terms of number of call frames) * allowed in a single invocation of interpreter. If the set depth would be * exceeded, the interpreter will throw an EvaluatorException in the script. * Defaults to Integer.MAX_VALUE. The setting only has effect for * interpreted functions (those compiled with optimization level set to -1). * As the interpreter doesn't use the Java stack but rather manages its own * stack in the heap memory, a runaway recursion in interpreted code would * eventually consume all available memory and cause OutOfMemoryError * instead of a StackOverflowError limited to only a single thread. This * setting helps prevent such situations. * * @return The current maximum interpreter stack depth. */ public final int getMaximumInterpreterStackDepth() { return maximumInterpreterStackDepth; } /** * Sets the maximum stack depth (in terms of number of call frames) * allowed in a single invocation of interpreter. If the set depth would be * exceeded, the interpreter will throw an EvaluatorException in the script. * Defaults to Integer.MAX_VALUE. The setting only has effect for * interpreted functions (those compiled with optimization level set to -1). * As the interpreter doesn't use the Java stack but rather manages its own * stack in the heap memory, a runaway recursion in interpreted code would * eventually consume all available memory and cause OutOfMemoryError * instead of a StackOverflowError limited to only a single thread. This * setting helps prevent such situations. * * @param max the new maximum interpreter stack depth * @throws IllegalStateException if this context's optimization level is not * -1 * @throws IllegalArgumentException if the new depth is not at least 1 */ public final void setMaximumInterpreterStackDepth(int max) { if(sealed) onSealedMutation(); if(optimizationLevel != -1) { throw new IllegalStateException("Cannot set maximumInterpreterStackDepth when optimizationLevel != -1"); } if(max < 1) { throw new IllegalArgumentException("Cannot set maximumInterpreterStackDepth to less than 1"); } maximumInterpreterStackDepth = max; } /** * Set the security controller for this context. * <p> SecurityController may only be set if it is currently null * and {@link SecurityController#hasGlobal()} is <tt>false</tt>. * Otherwise a SecurityException is thrown. * @param controller a SecurityController object * @throws SecurityException if there is already a SecurityController * object for this Context or globally installed. * @see SecurityController#initGlobal(SecurityController controller) * @see SecurityController#hasGlobal() */ public final void setSecurityController(SecurityController controller) { if (sealed) onSealedMutation(); if (controller == null) throw new IllegalArgumentException(); if (securityController != null) { throw new SecurityException("Can not overwrite existing SecurityController object"); } if (SecurityController.hasGlobal()) { throw new SecurityException("Can not overwrite existing global SecurityController object"); } securityController = controller; } /** * Set the LiveConnect access filter for this context. * <p> {@link ClassShutter} may only be set if it is currently null. * Otherwise a SecurityException is thrown. * @param shutter a ClassShutter object * @throws SecurityException if there is already a ClassShutter * object for this Context */ public final void setClassShutter(ClassShutter shutter) { if (sealed) onSealedMutation(); if (shutter == null) throw new IllegalArgumentException(); if (classShutter != null) { throw new SecurityException("Cannot overwrite existing " + "ClassShutter object"); } classShutter = shutter; } final ClassShutter getClassShutter() { return classShutter; } /** * Get a value corresponding to a key. * <p> * Since the Context is associated with a thread it can be * used to maintain values that can be later retrieved using * the current thread. * <p> * Note that the values are maintained with the Context, so * if the Context is disassociated from the thread the values * cannot be retrieved. Also, if private data is to be maintained * in this manner the key should be a java.lang.Object * whose reference is not divulged to untrusted code. * @param key the key used to lookup the value * @return a value previously stored using putThreadLocal. */ public final Object getThreadLocal(Object key) { if (hashtable == null) return null; return hashtable.get(key); } /** * Put a value that can later be retrieved using a given key. * <p> * @param key the key used to index the value * @param value the value to save */ public final void putThreadLocal(Object key, Object value) { if (sealed) onSealedMutation(); if (hashtable == null) hashtable = new Hashtable(); hashtable.put(key, value); } /** * Remove values from thread-local storage. * @param key the key for the entry to remove. * @since 1.5 release 2 */ public final void removeThreadLocal(Object key) { if (sealed) onSealedMutation(); if (hashtable == null) return; hashtable.remove(key); } /** * @deprecated * @see #FEATURE_DYNAMIC_SCOPE * @see #hasFeature(int) */ public final boolean hasCompileFunctionsWithDynamicScope() { return compileFunctionsWithDynamicScopeFlag; } /** * @deprecated * @see #FEATURE_DYNAMIC_SCOPE * @see #hasFeature(int) */ public final void setCompileFunctionsWithDynamicScope(boolean flag) { if (sealed) onSealedMutation(); compileFunctionsWithDynamicScopeFlag = flag; } /** * @deprecated * @see ClassCache#get(Scriptable) * @see ClassCache#setCachingEnabled(boolean) */ public static void setCachingEnabled(boolean cachingEnabled) { } /** * Set a WrapFactory for this Context. * <p> * The WrapFactory allows custom object wrapping behavior for * Java object manipulated with JavaScript. * @see WrapFactory * @since 1.5 Release 4 */ public final void setWrapFactory(WrapFactory wrapFactory) { if (sealed) onSealedMutation(); if (wrapFactory == null) throw new IllegalArgumentException(); this.wrapFactory = wrapFactory; } /** * Return the current WrapFactory, or null if none is defined. * @see WrapFactory * @since 1.5 Release 4 */ public final WrapFactory getWrapFactory() { if (wrapFactory == null) { wrapFactory = new WrapFactory(); } return wrapFactory; } /** * Return the current debugger. * @return the debugger, or null if none is attached. */ public final Debugger getDebugger() { return debugger; } /** * Return the debugger context data associated with current context. * @return the debugger data, or null if debugger is not attached */ public final Object getDebuggerContextData() { return debuggerData; } /** * Set the associated debugger. * @param debugger the debugger to be used on callbacks from * the engine. * @param contextData arbitrary object that debugger can use to store * per Context data. */ public final void setDebugger(Debugger debugger, Object contextData) { if (sealed) onSealedMutation(); this.debugger = debugger; debuggerData = contextData; } /** * Return DebuggableScript instance if any associated with the script. * If callable supports DebuggableScript implementation, the method * returns it. Otherwise null is returned. */ public static DebuggableScript getDebuggableView(Script script) { if (script instanceof NativeFunction) { return ((NativeFunction)script).getDebuggableView(); } return null; } /** * Controls certain aspects of script semantics. * Should be overwritten to alter default behavior. * <p> * The default implementation calls * {@link ContextFactory#hasFeature(Context cx, int featureIndex)} * that allows to customize Context behavior without introducing * Context subclasses. {@link ContextFactory} documentation gives * an example of hasFeature implementation. * * @param featureIndex feature index to check * @return true if the <code>featureIndex</code> feature is turned on * @see #FEATURE_NON_ECMA_GET_YEAR * @see #FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME * @see #FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER * @see #FEATURE_TO_STRING_AS_SOURCE * @see #FEATURE_PARENT_PROTO_PROPRTIES * @see #FEATURE_E4X * @see #FEATURE_DYNAMIC_SCOPE * @see #FEATURE_STRICT_VARS * @see #FEATURE_STRICT_EVAL * @see #FEATURE_LOCATION_INFORMATION_IN_ERROR * @see #FEATURE_STRICT_MODE * @see #FEATURE_WARNING_AS_ERROR * @see #FEATURE_ENHANCED_JAVA_ACCESS */ public boolean hasFeature(int featureIndex) { ContextFactory f = getFactory(); return f.hasFeature(this, featureIndex); } /** Returns an object which specifies an E4X implementation to use within this <code>Context</code>. Note that the XMLLib.Factory interface should be considered experimental. The default implementation uses the implementation provided by this <code>Context</code>'s {@link ContextFactory}. @return An XMLLib.Factory. Should not return <code>null</code> if {@link #FEATURE_E4X} is enabled. See {@link #hasFeature}. */ public XMLLib.Factory getE4xImplementationFactory() { return getFactory().getE4xImplementationFactory(); } /** * Get threshold of executed instructions counter that triggers call to * <code>observeInstructionCount()</code>. * When the threshold is zero, instruction counting is disabled, * otherwise each time the run-time executes at least the threshold value * of script instructions, <code>observeInstructionCount()</code> will * be called. */ public final int getInstructionObserverThreshold() { return instructionThreshold; } /** * Set threshold of executed instructions counter that triggers call to * <code>observeInstructionCount()</code>. * When the threshold is zero, instruction counting is disabled, * otherwise each time the run-time executes at least the threshold value * of script instructions, <code>observeInstructionCount()</code> will * be called.<p/> * Note that the meaning of "instruction" is not guaranteed to be * consistent between compiled and interpretive modes: executing a given * script or function in the different modes will result in different * instruction counts against the threshold. * {@link #setGenerateObserverCount} is called with true if * <code>threshold</code> is greater than zero, false otherwise. * @param threshold The instruction threshold */ public final void setInstructionObserverThreshold(int threshold) { if (sealed) onSealedMutation(); if (threshold < 0) throw new IllegalArgumentException(); instructionThreshold = threshold; setGenerateObserverCount(threshold > 0); } /** * Turn on or off generation of code with callbacks to * track the count of executed instructions. * Currently only affects JVM byte code generation: this slows down the * generated code, but code generated without the callbacks will not * be counted toward instruction thresholds. Rhino's interpretive * mode does instruction counting without inserting callbacks, so * there is no requirement to compile code differently. * @param generateObserverCount if true, generated code will contain * calls to accumulate an estimate of the instructions executed. */ public void setGenerateObserverCount(boolean generateObserverCount) { this.generateObserverCount = generateObserverCount; } /** * Allow application to monitor counter of executed script instructions * in Context subclasses. * Run-time calls this when instruction counting is enabled and the counter * reaches limit set by <code>setInstructionObserverThreshold()</code>. * The method is useful to observe long running scripts and if necessary * to terminate them. * <p> * The instruction counting support is available only for interpreted * scripts generated when the optimization level is set to -1. * <p> * The default implementation calls * {@link ContextFactory#observeInstructionCount(Context cx, * int instructionCount)} * that allows to customize Context behavior without introducing * Context subclasses. * * @param instructionCount amount of script instruction executed since * last call to <code>observeInstructionCount</code> * @throws Error to terminate the script * @see #setOptimizationLevel(int) */ protected void observeInstructionCount(int instructionCount) { ContextFactory f = getFactory(); f.observeInstructionCount(this, instructionCount); } /** * Create class loader for generated classes. * The method calls {@link ContextFactory#createClassLoader(ClassLoader)} * using the result of {@link #getFactory()}. */ public GeneratedClassLoader createClassLoader(ClassLoader parent) { ContextFactory f = getFactory(); return f.createClassLoader(parent); } public final ClassLoader getApplicationClassLoader() { if (applicationClassLoader == null) { ContextFactory f = getFactory(); ClassLoader loader = f.getApplicationClassLoader(); if (loader == null) { ClassLoader threadLoader = VMBridge.instance.getCurrentThreadClassLoader(); if (threadLoader != null && Kit.testIfCanLoadRhinoClasses(threadLoader)) { // Thread.getContextClassLoader is not cached since // its caching prevents it from GC which may lead to // a memory leak and hides updates to // Thread.getContextClassLoader return threadLoader; } // Thread.getContextClassLoader can not load Rhino classes, // try to use the loader of ContextFactory or Context // subclasses. Class fClass = f.getClass(); if (fClass != ScriptRuntime.ContextFactoryClass) { loader = fClass.getClassLoader(); } else { loader = getClass().getClassLoader(); } } applicationClassLoader = loader; } return applicationClassLoader; } public final void setApplicationClassLoader(ClassLoader loader) { if (sealed) onSealedMutation(); if (loader == null) { // restore default behaviour applicationClassLoader = null; return; } if (!Kit.testIfCanLoadRhinoClasses(loader)) { throw new IllegalArgumentException( "Loader can not resolve Rhino classes"); } applicationClassLoader = loader; } /********** end of API **********/ /** * Internal method that reports an error for missing calls to * enter(). */ static Context getContext() { Context cx = getCurrentContext(); if (cx == null) { throw new RuntimeException( "No Context associated with current Thread"); } return cx; } private Object compileImpl(Scriptable scope, Reader sourceReader, String sourceString, String sourceName, int lineno, Object securityDomain, boolean returnFunction, Evaluator compiler, ErrorReporter compilationErrorReporter) throws IOException { + if(sourceName == null) { + sourceName = "unnamed script"; + } if (securityDomain != null && getSecurityController() == null) { throw new IllegalArgumentException( "securityDomain should be null if setSecurityController() was never called"); } // One of sourceReader or sourceString has to be null if (!(sourceReader == null ^ sourceString == null)) Kit.codeBug(); // scope should be given if and only if compiling function if (!(scope == null ^ returnFunction)) Kit.codeBug(); CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); if (compilationErrorReporter == null) { compilationErrorReporter = compilerEnv.getErrorReporter(); } if (debugger != null) { if (sourceReader != null) { sourceString = Kit.readReader(sourceReader); sourceReader = null; } } Parser p = new Parser(compilerEnv, compilationErrorReporter); if (returnFunction) { p.calledByCompileFunction = true; } ScriptOrFnNode tree; if (sourceString != null) { tree = p.parse(sourceString, sourceName, lineno); } else { tree = p.parse(sourceReader, sourceName, lineno); } if (returnFunction) { if (!(tree.getFunctionCount() == 1 && tree.getFirstChild() != null && tree.getFirstChild().getType() == Token.FUNCTION)) { // XXX: the check just look for the first child // and allows for more nodes after it for compatibility // with sources like function() {};;; throw new IllegalArgumentException( "compileFunction only accepts source with single JS function: "+sourceString); } } if (compiler == null) { compiler = createCompiler(); } String encodedSource = p.getEncodedSource(); Object bytecode = compiler.compile(compilerEnv, tree, encodedSource, returnFunction); if (debugger != null) { if (sourceString == null) Kit.codeBug(); if (bytecode instanceof DebuggableScript) { DebuggableScript dscript = (DebuggableScript)bytecode; notifyDebugger_r(this, dscript, sourceString); } else { throw new RuntimeException("NOT SUPPORTED"); } } Object result; if (returnFunction) { result = compiler.createFunctionObject(this, scope, bytecode, securityDomain); } else { result = compiler.createScriptObject(bytecode, securityDomain); } return result; } private static void notifyDebugger_r(Context cx, DebuggableScript dscript, String debugSource) { cx.debugger.handleCompilationDone(cx, dscript, debugSource); for (int i = 0; i != dscript.getFunctionCount(); ++i) { notifyDebugger_r(cx, dscript.getFunction(i), debugSource); } } private static Class codegenClass = Kit.classOrNull( "org.mozilla.javascript.optimizer.Codegen"); private static Class interpreterClass = Kit.classOrNull( "org.mozilla.javascript.Interpreter"); private Evaluator createCompiler() { Evaluator result = null; if (optimizationLevel >= 0 && codegenClass != null) { result = (Evaluator)Kit.newInstanceOrNull(codegenClass); } if (result == null) { result = createInterpreter(); } return result; } static Evaluator createInterpreter() { return (Evaluator)Kit.newInstanceOrNull(interpreterClass); } static String getSourcePositionFromStack(int[] linep) { Context cx = getCurrentContext(); if (cx == null) return null; if (cx.lastInterpreterFrame != null) { Evaluator evaluator = createInterpreter(); if (evaluator != null) return evaluator.getSourcePositionFromStack(cx, linep); } /** * A bit of a hack, but the only way to get filename and line * number from an enclosing frame. */ CharArrayWriter writer = new CharArrayWriter(); RuntimeException re = new RuntimeException(); re.printStackTrace(new PrintWriter(writer)); String s = writer.toString(); int open = -1; int close = -1; int colon = -1; for (int i=0; i < s.length(); i++) { char c = s.charAt(i); if (c == ':') colon = i; else if (c == '(') open = i; else if (c == ')') close = i; else if (c == '\n' && open != -1 && close != -1 && colon != -1 && open < colon && colon < close) { String fileStr = s.substring(open + 1, colon); if (!fileStr.endsWith(".java")) { String lineStr = s.substring(colon + 1, close); try { linep[0] = Integer.parseInt(lineStr); if (linep[0] < 0) { linep[0] = 0; } return fileStr; } catch (NumberFormatException e) { // fall through } } open = close = colon = -1; } } return null; } RegExpProxy getRegExpProxy() { if (regExpProxy == null) { Class cl = Kit.classOrNull( "org.mozilla.javascript.regexp.RegExpImpl"); if (cl != null) { regExpProxy = (RegExpProxy)Kit.newInstanceOrNull(cl); } } return regExpProxy; } final boolean isVersionECMA1() { return version == VERSION_DEFAULT || version >= VERSION_1_3; } // The method must NOT be public or protected SecurityController getSecurityController() { SecurityController global = SecurityController.global(); if (global != null) { return global; } return securityController; } public final boolean isGeneratingDebugChanged() { return generatingDebugChanged; } /** * Add a name to the list of names forcing the creation of real * activation objects for functions. * * @param name the name of the object to add to the list */ public void addActivationName(String name) { if (sealed) onSealedMutation(); if (activationNames == null) activationNames = new Hashtable(5); activationNames.put(name, name); } /** * Check whether the name is in the list of names of objects * forcing the creation of activation objects. * * @param name the name of the object to test * * @return true if an function activation object is needed. */ public final boolean isActivationNeeded(String name) { return activationNames != null && activationNames.containsKey(name); } /** * Remove a name from the list of names forcing the creation of real * activation objects for functions. * * @param name the name of the object to remove from the list */ public void removeActivationName(String name) { if (sealed) onSealedMutation(); if (activationNames != null) activationNames.remove(name); } private static String implementationVersion; private final ContextFactory factory; private boolean sealed; private Object sealKey; Scriptable topCallScope; NativeCall currentActivationCall; XMLLib cachedXMLLib; // for Objects, Arrays to tag themselves as being printed out, // so they don't print themselves out recursively. // Use ObjToIntMap instead of java.util.HashSet for JDK 1.1 compatibility ObjToIntMap iterating; Object interpreterSecurityDomain; int version; private SecurityController securityController; private ClassShutter classShutter; private ErrorReporter errorReporter; RegExpProxy regExpProxy; private Locale locale; private boolean generatingDebug; private boolean generatingDebugChanged; private boolean generatingSource=true; boolean compileFunctionsWithDynamicScopeFlag; boolean useDynamicScope; private int optimizationLevel; private int maximumInterpreterStackDepth; private WrapFactory wrapFactory; Debugger debugger; private Object debuggerData; private int enterCount; private Object propertyListeners; private Hashtable hashtable; private ClassLoader applicationClassLoader; /** * This is the list of names of objects forcing the creation of * function activation records. */ Hashtable activationNames; // For the interpreter to store the last frame for error reports etc. Object lastInterpreterFrame; // For the interpreter to store information about previous invocations // interpreter invocations ObjArray previousInterpreterInvocations; // For instruction counting (interpreter only) int instructionCount; int instructionThreshold; // It can be used to return the second index-like result from function int scratchIndex; // It can be used to return the second uint32 result from function long scratchUint32; // It can be used to return the second Scriptable result from function Scriptable scratchScriptable; // Generate an observer count on compiled code public boolean generateObserverCount = false; }
true
true
private Object compileImpl(Scriptable scope, Reader sourceReader, String sourceString, String sourceName, int lineno, Object securityDomain, boolean returnFunction, Evaluator compiler, ErrorReporter compilationErrorReporter) throws IOException { if (securityDomain != null && getSecurityController() == null) { throw new IllegalArgumentException( "securityDomain should be null if setSecurityController() was never called"); } // One of sourceReader or sourceString has to be null if (!(sourceReader == null ^ sourceString == null)) Kit.codeBug(); // scope should be given if and only if compiling function if (!(scope == null ^ returnFunction)) Kit.codeBug(); CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); if (compilationErrorReporter == null) { compilationErrorReporter = compilerEnv.getErrorReporter(); } if (debugger != null) { if (sourceReader != null) { sourceString = Kit.readReader(sourceReader); sourceReader = null; } } Parser p = new Parser(compilerEnv, compilationErrorReporter); if (returnFunction) { p.calledByCompileFunction = true; } ScriptOrFnNode tree; if (sourceString != null) { tree = p.parse(sourceString, sourceName, lineno); } else { tree = p.parse(sourceReader, sourceName, lineno); } if (returnFunction) { if (!(tree.getFunctionCount() == 1 && tree.getFirstChild() != null && tree.getFirstChild().getType() == Token.FUNCTION)) { // XXX: the check just look for the first child // and allows for more nodes after it for compatibility // with sources like function() {};;; throw new IllegalArgumentException( "compileFunction only accepts source with single JS function: "+sourceString); } } if (compiler == null) { compiler = createCompiler(); } String encodedSource = p.getEncodedSource(); Object bytecode = compiler.compile(compilerEnv, tree, encodedSource, returnFunction); if (debugger != null) { if (sourceString == null) Kit.codeBug(); if (bytecode instanceof DebuggableScript) { DebuggableScript dscript = (DebuggableScript)bytecode; notifyDebugger_r(this, dscript, sourceString); } else { throw new RuntimeException("NOT SUPPORTED"); } } Object result; if (returnFunction) { result = compiler.createFunctionObject(this, scope, bytecode, securityDomain); } else { result = compiler.createScriptObject(bytecode, securityDomain); } return result; }
private Object compileImpl(Scriptable scope, Reader sourceReader, String sourceString, String sourceName, int lineno, Object securityDomain, boolean returnFunction, Evaluator compiler, ErrorReporter compilationErrorReporter) throws IOException { if(sourceName == null) { sourceName = "unnamed script"; } if (securityDomain != null && getSecurityController() == null) { throw new IllegalArgumentException( "securityDomain should be null if setSecurityController() was never called"); } // One of sourceReader or sourceString has to be null if (!(sourceReader == null ^ sourceString == null)) Kit.codeBug(); // scope should be given if and only if compiling function if (!(scope == null ^ returnFunction)) Kit.codeBug(); CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); if (compilationErrorReporter == null) { compilationErrorReporter = compilerEnv.getErrorReporter(); } if (debugger != null) { if (sourceReader != null) { sourceString = Kit.readReader(sourceReader); sourceReader = null; } } Parser p = new Parser(compilerEnv, compilationErrorReporter); if (returnFunction) { p.calledByCompileFunction = true; } ScriptOrFnNode tree; if (sourceString != null) { tree = p.parse(sourceString, sourceName, lineno); } else { tree = p.parse(sourceReader, sourceName, lineno); } if (returnFunction) { if (!(tree.getFunctionCount() == 1 && tree.getFirstChild() != null && tree.getFirstChild().getType() == Token.FUNCTION)) { // XXX: the check just look for the first child // and allows for more nodes after it for compatibility // with sources like function() {};;; throw new IllegalArgumentException( "compileFunction only accepts source with single JS function: "+sourceString); } } if (compiler == null) { compiler = createCompiler(); } String encodedSource = p.getEncodedSource(); Object bytecode = compiler.compile(compilerEnv, tree, encodedSource, returnFunction); if (debugger != null) { if (sourceString == null) Kit.codeBug(); if (bytecode instanceof DebuggableScript) { DebuggableScript dscript = (DebuggableScript)bytecode; notifyDebugger_r(this, dscript, sourceString); } else { throw new RuntimeException("NOT SUPPORTED"); } } Object result; if (returnFunction) { result = compiler.createFunctionObject(this, scope, bytecode, securityDomain); } else { result = compiler.createScriptObject(bytecode, securityDomain); } return result; }
diff --git a/source/myorders/MyCostOrder.java b/source/myorders/MyCostOrder.java index c9dbfae..cebdc44 100644 --- a/source/myorders/MyCostOrder.java +++ b/source/myorders/MyCostOrder.java @@ -1,71 +1,72 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package myorders; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import model.Order; import ru.peppers.R; import android.content.Context; /** * * @author papas */ public class MyCostOrder extends Order { private Date _registrationtime; private Date _invitationtime; private Date _departuretime; public MyCostOrder(Context context,String index, Integer nominalcost, Date registrationtime, String addressdeparture, Integer carClass, String comment, String addressarrival,Integer paymenttype,Date invitationtime,Date departuretime) { super(context,nominalcost,addressdeparture, carClass, comment, addressarrival,paymenttype,index); //TODO:wrong index _registrationtime = registrationtime; _invitationtime = invitationtime; _departuretime = departuretime; } public String toString(){ String pred = ""; if(_departuretime!=null) pred = "П "+getTimeString(_departuretime)+", "; else pred = getTimeString(_registrationtime)+", "; String over = ""; if(_nominalcost!=null) over = ", "+_nominalcost+" "+_context.getString(R.string.currency); return pred+_addressdeparture+over; } public ArrayList<String> toArrayList(){ ArrayList<String> array = new ArrayList<String>(); array.addAll(getAbonentArray()); if(_departuretime!=null) array.add(_context.getString(R.string.accepted)+" "+getTimeString(_departuretime)); array.add(_context.getString(R.string.date)+" "+getTimeString(_registrationtime)); + if(_invitationtime!=null) array.add(_context.getString(R.string.date_invite)+" "+getTimeString(_invitationtime)); array.add(_context.getString(R.string.adress)+" "+_addressdeparture); array.add(_context.getString(R.string.where)+" "+_addressarrival); array.add(_context.getString(R.string.car_class)+" " + getCarClass()); array.add(_context.getString(R.string.cost_type)+" "+getPayment()); if(_nominalcost!=null) array.add(_context.getString(R.string.cost)+" "+_nominalcost+" "+_context.getString(R.string.currency)); if(_comment!=null) array.add(_comment); return array; } private String getTimeString(Date date) { SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); return dateFormat.format(date); } }
true
true
public ArrayList<String> toArrayList(){ ArrayList<String> array = new ArrayList<String>(); array.addAll(getAbonentArray()); if(_departuretime!=null) array.add(_context.getString(R.string.accepted)+" "+getTimeString(_departuretime)); array.add(_context.getString(R.string.date)+" "+getTimeString(_registrationtime)); array.add(_context.getString(R.string.date_invite)+" "+getTimeString(_invitationtime)); array.add(_context.getString(R.string.adress)+" "+_addressdeparture); array.add(_context.getString(R.string.where)+" "+_addressarrival); array.add(_context.getString(R.string.car_class)+" " + getCarClass()); array.add(_context.getString(R.string.cost_type)+" "+getPayment()); if(_nominalcost!=null) array.add(_context.getString(R.string.cost)+" "+_nominalcost+" "+_context.getString(R.string.currency)); if(_comment!=null) array.add(_comment); return array; }
public ArrayList<String> toArrayList(){ ArrayList<String> array = new ArrayList<String>(); array.addAll(getAbonentArray()); if(_departuretime!=null) array.add(_context.getString(R.string.accepted)+" "+getTimeString(_departuretime)); array.add(_context.getString(R.string.date)+" "+getTimeString(_registrationtime)); if(_invitationtime!=null) array.add(_context.getString(R.string.date_invite)+" "+getTimeString(_invitationtime)); array.add(_context.getString(R.string.adress)+" "+_addressdeparture); array.add(_context.getString(R.string.where)+" "+_addressarrival); array.add(_context.getString(R.string.car_class)+" " + getCarClass()); array.add(_context.getString(R.string.cost_type)+" "+getPayment()); if(_nominalcost!=null) array.add(_context.getString(R.string.cost)+" "+_nominalcost+" "+_context.getString(R.string.currency)); if(_comment!=null) array.add(_comment); return array; }
diff --git a/cadpage/src/net/anei/cadpage/parsers/INMadisonCountyParser.java b/cadpage/src/net/anei/cadpage/parsers/INMadisonCountyParser.java index 4b7b0d527..e9522873e 100644 --- a/cadpage/src/net/anei/cadpage/parsers/INMadisonCountyParser.java +++ b/cadpage/src/net/anei/cadpage/parsers/INMadisonCountyParser.java @@ -1,39 +1,39 @@ package net.anei.cadpage.parsers; import java.util.Properties; import net.anei.cadpage.Log; import net.anei.cadpage.SmsMsgInfo.Data; /* Madison County (Alexandria), IN Contact: Pamela Stigall <[email protected]> Sender: [email protected] Unit:ST40 UnitSts: Loc:6302 APOLLO DR Venue:RICHLA TWP Inc:Brush Fire Date:10/17/2010 Time:18:49 ON GEMINI / 1 ST HOUSE SOUTH EAST END Addtl:TRASH FIRE ON THE GROUND/WHI MODULAR WHI VAN SITTING IN DRIVE Unit:AM45 UnitSts: Loc:6197 N SR 9 Venue:RICHLA TWP Inc:EMS Call Date:10/17/2010 Time:01:12 56 YOM / ADV HE DOESNT FEEL GOOD / VOMITING A Addtl:ND NO APPITITE ALL DAY / WILL BE WATING OUTSI DE RESD: Unit:ST40 UnitSts: Loc:E 400N/100E Venue:RICHLA TWP Inc:Brush Fire Date:10/15/2010 Time:14:33 OPEN BURN BETWEEEN 100E AND ALEX PIKE/ S SIDE Addtl: OF ROAD Unit:ST40 UnitSts: Loc:3551 N SR 9 Venue:LAFAYE TWP TOM WOOD HONDA Inc:Accidnt PI Date:10/14/2010 Time:07:43 UNKNOWN 2 VEHS Addtl: */ public class INMadisonCountyParser extends SmsMsgParser { private static final String[] keywords = new String[] {"Unit", "UnitSts", "Loc", "Venue", "Inc", "Date", "Addtl"}; @Override public boolean isPageMsg(String body) { return body.startsWith("Unit:"); } @Override protected void parse(String body, Data data) { Log.v("DecodeMadisonCountyPage: Message Body of:" + body); data.defState="IN"; data.defCity = "MADISON COUNTY"; Properties props = parseMessage(body, keywords); body = body.trim(); data.strUnit = props.getProperty("Unit", ""); - data.strAddress = props.getProperty("Loc", ""); + parseAddress(props.getProperty("Loc", ""), data); data.strCall = props.getProperty("Inc", ""); } }
true
true
protected void parse(String body, Data data) { Log.v("DecodeMadisonCountyPage: Message Body of:" + body); data.defState="IN"; data.defCity = "MADISON COUNTY"; Properties props = parseMessage(body, keywords); body = body.trim(); data.strUnit = props.getProperty("Unit", ""); data.strAddress = props.getProperty("Loc", ""); data.strCall = props.getProperty("Inc", ""); }
protected void parse(String body, Data data) { Log.v("DecodeMadisonCountyPage: Message Body of:" + body); data.defState="IN"; data.defCity = "MADISON COUNTY"; Properties props = parseMessage(body, keywords); body = body.trim(); data.strUnit = props.getProperty("Unit", ""); parseAddress(props.getProperty("Loc", ""), data); data.strCall = props.getProperty("Inc", ""); }
diff --git a/source/com/mucommander/file/impl/local/LocalFile.java b/source/com/mucommander/file/impl/local/LocalFile.java index 84f10b34..9e6bb3f1 100644 --- a/source/com/mucommander/file/impl/local/LocalFile.java +++ b/source/com/mucommander/file/impl/local/LocalFile.java @@ -1,1028 +1,1028 @@ /* * This file is part of muCommander, http://www.mucommander.com * Copyright (C) 2002-2008 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.file.impl.local; import com.mucommander.Debug; import com.mucommander.file.AbstractFile; import com.mucommander.file.FileFactory; import com.mucommander.file.FileProtocols; import com.mucommander.file.FileURL; import com.mucommander.file.filter.FilenameFilter; import com.mucommander.file.util.Kernel32API; import com.mucommander.file.util.POSIX; import com.mucommander.io.BufferPool; import com.mucommander.io.FileTransferException; import com.mucommander.io.RandomAccessInputStream; import com.mucommander.io.RandomAccessOutputStream; import com.mucommander.process.AbstractProcess; import com.mucommander.runtime.JavaVersions; import com.mucommander.runtime.OsFamilies; import com.mucommander.runtime.OsFamily; import com.sun.jna.ptr.LongByReference; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.regex.Matcher; /** * LocalFile provides access to files located on a locally-mounted filesystem. * Note that despite the class' name, LocalFile instances may indifferently be residing on a local hard drive, * or on a remote server mounted locally by the operating system. * * <p>The associated {@link FileURL} protocol is {@link FileProtocols#FILE}. The host part should be {@link FileURL#LOCALHOST}, * except for Windows UNC URLs (see below). Native path separators ('/' or '\\' depending on the OS) can be used * in the path part. * * <p>Here are a few examples of valid local file URLs: * <code> * file://localhost/C:\winnt\system32\<br> * file://localhost/usr/bin/gcc<br> * file://localhost/~<br> * file://home/maxence/..<br> * </code> * * <p>Windows UNC paths can be represented as FileURL instances, using the host part of the URL. The URL format for * those is the following:<br> * <code>file:\\server\share</code> .<br> * * <p>Under Windows, LocalFile will translate those URLs back into a UNC path. For example, a LocalFile created with the * <code>file://garfield/stuff</code> FileURL will have the <code>getAbsolutePath()</code> method return * <code>\\garfield\stuff</code>. Note that this UNC path translation doesn't happen on OSes other than Windows, which * would not be able to handle the path. * * <p>Access to local files is provided by the <code>java.io</code> API, {@link #getUnderlyingFileObject()} allows * to retrieve an <code>java.io.File</code> instance corresponding to this LocalFile. * * @author Maxence Bernard */ public class LocalFile extends AbstractFile { private File file; private String parentFilePath; private String absPath; /** True if this file has a Windows-style UNC path. Can be true only under Windows. */ private boolean isUNC; /** Caches the parent folder, initially null until getParent() gets called */ private AbstractFile parent; /** Indicates whether the parent folder instance has been retrieved and cached or not (parent can be null) */ private boolean parentValueSet; /** Underlying local filesystem's path separator: "/" under UNIX systems, "\" under Windows and OS/2 */ public final static String SEPARATOR = File.separator; /** true if the underlying local filesystem uses drives assigned to letters (e.g. A:\, C:\, ...) instead * of having single a root folder '/' */ public final static boolean USES_ROOT_DRIVES = OsFamilies.WINDOWS.isCurrent() || OsFamilies.OS_2.isCurrent(); /** Are we running Windows ? */ private final static boolean IS_WINDOWS; static { IS_WINDOWS = OsFamilies.WINDOWS.isCurrent(); // Prevents Windows from poping up a message box when it cannot find a file. Those message box are triggered by // java.io.File methods when operating on removable drives such as floppy or CD-ROM drives which have no disk // inserted. // This has been fixed in Java 1.6 b55 but this fixes previous versions of Java. // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4089199 if(IS_WINDOWS) Kernel32API.INSTANCE.SetErrorMode(Kernel32API.SEM_NOOPENFILEERRORBOX); } /** * Creates a new instance of LocalFile. The given FileURL's protocol should be {@link FileProtocols#FILE}, and the * host {@link FileURL#LOCALHOST}. */ public LocalFile(FileURL fileURL) throws IOException { super(fileURL); String path = fileURL.getPath(); // If OS is Windows and hostname is not 'localhost', translate the path back into a Windows-style UNC path // in the form \\hostname\share\path . String hostname = fileURL.getHost(); if(IS_WINDOWS && !FileURL.LOCALHOST.equals(hostname)) { path = "\\\\"+hostname+fileURL.getPath().replace('/', '\\'); // Replace leading / char by \ isUNC = true; } this.file = new File(path); // Throw an exception is the file's path is not absolute. if(!file.isAbsolute()) throw new IOException(); this.parentFilePath = file.getParent(); this.absPath = file.getAbsolutePath(); // removes trailing separator (if any) this.absPath = absPath.endsWith(SEPARATOR)?absPath.substring(0,absPath.length()-1):absPath; } /** * Returns the user home folder. Most if not all OSes have one, but in the unlikely event that the OS doesn't have * one or that the folder cannot be resolved, <code>null</code> will be returned. * * @return the user home folder */ public static AbstractFile getUserHome() { String userHomePath = System.getProperty("user.home"); if(userHomePath==null) return null; return FileFactory.getFile(userHomePath); } /** * Returns the total and free space on the volume where this file resides. * * <p>Using this method to retrieve both free space and volume space is more efficient than calling * {@link #getFreeSpace()} and {@link #getTotalSpace()} separately -- the underlying method retrieving both * attributes at the same time.</p> * * @return a {totalSpace, freeSpace} long array, both values can be null if the information could not be retrieved */ public long[] getVolumeInfo() { // Under Java 1.6 and up, use the (new) java.io.File methods if(JavaVersions.JAVA_1_6.isCurrentOrHigher()) { return new long[] { getTotalSpace(), getFreeSpace() }; } // Under Java 1.5 or lower, use native methods return getNativeVolumeInfo(); } /** * Uses platform dependant functions to retrieve the total and free space on the volume where this file resides. * * @return a {totalSpace, freeSpace} long array, both values can be null if the information could not be retrieved */ protected long[] getNativeVolumeInfo() { // BufferedReader br = null; String absPath = getAbsolutePath(); long dfInfo[] = new long[]{-1, -1}; try { // OS is Windows if(IS_WINDOWS) { // // Parses the output of 'dir "filePath"' command to retrieve free space information // // // 'dir' command returns free space on the last line // //Process process = PlatformManager.execute("dir \""+absPath+"\"", this); // //Process process = Runtime.getRuntime().exec(new String[] {"dir", absPath}, null, new File(getAbsolutePath())); // Process process = Runtime.getRuntime().exec(PlatformManager.getDefaultShellCommand() + " dir \""+absPath+"\""); // // // Check that the process was correctly started // if(process!=null) { // br = new BufferedReader(new InputStreamReader(process.getInputStream())); // String line; // String lastLine = null; // // Retrieves last line of dir // while((line=br.readLine())!=null) { // if(!line.trim().equals("")) // lastLine = line; // } // // // Last dir line may look like something this (might vary depending on system's language, below in French): // // 6 Rep(s) 14 767 521 792 octets libres // if(lastLine!=null) { // StringTokenizer st = new StringTokenizer(lastLine, " \t\n\r\f,."); // // Discard first token // st.nextToken(); // // // Concatenates as many contiguous groups of numbers // String token; // String freeSpace = ""; // while(st.hasMoreTokens()) { // token = st.nextToken(); // char c = token.charAt(0); // if(c>='0' && c<='9') // freeSpace += token; // else if(!freeSpace.equals("")) // break; // } // // dfInfo[1] = Long.parseLong(freeSpace); // } // } // Retrieves the total and free space information using the GetDiskFreeSpaceEx function of the // Kernel32 API. LongByReference totalSpaceLBR = new LongByReference(); LongByReference freeSpaceLBR = new LongByReference(); if(Kernel32API.INSTANCE.GetDiskFreeSpaceEx(absPath, null, totalSpaceLBR, freeSpaceLBR)) { dfInfo[0] = totalSpaceLBR.getValue(); dfInfo[1] = freeSpaceLBR.getValue(); } else { if(Debug.ON) Debug.trace("Call to GetDiskFreeSpaceEx failed, absPath="+absPath); } } else if(OsFamily.getCurrent().isUnixBased()) { // // Parses the output of 'df -k "filePath"' command on UNIX-based systems to retrieve free and total space information // // // 'df -k' returns totals in block of 1K = 1024 bytes // Process process = Runtime.getRuntime().exec(new String[]{"df", "-k", absPath}, null, file); // // // Check that the process was correctly started // if(process!=null) { // br = new BufferedReader(new InputStreamReader(process.getInputStream())); // // Discard the first line ("Filesystem 1K-blocks Used Avail Capacity Mounted on"); // br.readLine(); // String line = br.readLine(); // // // Sample lines: // // /dev/disk0s2 116538416 109846712 6179704 95% / // // automount -fstab [202] 0 0 0 100% /automount/Servers // // /dev/disk2s2 2520 1548 972 61% /Volumes/muCommander 0.8 // // // We're interested in the '1K-blocks' and 'Avail' fields (only). // // The 'Filesystem' and 'Mounted On' fields can contain spaces (e.g. 'automount -fstab [202]' and // // '/Volumes/muCommander 0.8' resp.) and therefore be made of several tokens. A stable way to // // determine the position of the fields we're interested in is to look for the last token that // // starts with a '/' character which should necessarily correspond to the first token of the // // 'Mounted on' field. The '1K-blocks' and 'Avail' fields are 4 and 2 tokens away from it // // respectively. // // // Start by tokenizing the whole line // Vector tokenV = new Vector(); // if(line!=null) { // StringTokenizer st = new StringTokenizer(line); // while(st.hasMoreTokens()) // tokenV.add(st.nextToken()); // } // // int nbTokens = tokenV.size(); // if(nbTokens<6) { // // This shouldn't normally happen // if(Debug.ON) Debug.trace("Failed to parse output of df -k "+absPath+" line="+line); // return dfInfo; // } // // // Find the last token starting with '/' // int pos = nbTokens-1; // while(!((String)tokenV.elementAt(pos)).startsWith("/")) { // if(pos==0) { // // This shouldn't normally happen // if(Debug.ON) Debug.trace("Failed to parse output of df -k "+absPath+" line="+line); // return dfInfo; // } // // --pos; // } // // // '1-blocks' field (total space) // dfInfo[0] = Long.parseLong((String)tokenV.elementAt(pos-4)) * 1024; // // 'Avail' field (free space) // dfInfo[1] = Long.parseLong((String)tokenV.elementAt(pos-2)) * 1024; // } // Retrieves the total and free space information using the POSIX statvfs function POSIX.STATVFSSTRUCT struct = new POSIX.STATVFSSTRUCT(); if(POSIX.INSTANCE.statvfs(absPath, struct)==0) { - dfInfo[0] = struct.f_blocks * struct.f_frsize; - dfInfo[1] = struct.f_bfree * struct.f_frsize; + dfInfo[0] = struct.f_blocks * (long)struct.f_frsize; + dfInfo[1] = struct.f_bfree * (long)struct.f_frsize; } } } catch(Throwable e) { // JNA throws a java.lang.UnsatisfiedLinkError if the native can't be found if(com.mucommander.Debug.ON) { com.mucommander.Debug.trace("Exception thrown while retrieving volume info: "+e); e.printStackTrace(); } } // finally { // if(br!=null) // try { br.close(); } catch(IOException e) {} // } return dfInfo; } /** * Attemps to detect if this file is the root of a removable media drive (floppy, CD, DVD, USB drive...). * This method produces accurate results only under Windows. * * @return <code>true</code> if this file is the root of a removable media drive (floppy, CD, DVD, USB drive...). */ public boolean guessRemovableDrive() { if(IS_WINDOWS) { int driveType = Kernel32API.INSTANCE.GetDriveType(getAbsolutePath(true)); if(driveType!=Kernel32API.DRIVE_UNKNOWN) return driveType==Kernel32API.DRIVE_REMOVABLE || driveType==Kernel32API.DRIVE_CDROM; } // For other OS that have root drives (OS/2), a weak way to characterize removable drives is by checking if the // corresponding root folder is read-only. return hasRootDrives() && isRoot() && !file.canWrite(); } /** * Returns <code>true</code> if the underlying local filesystem uses drives assigned to letters (e.g. A:\, C:\, ...) * instead of having a single root folder '/' under which mount points are attached. * This is <code>true</code> for the following platforms: * <ul> * <li>Windows</li> * <li>OS/2</li> * <li>Any other platform that has '\' for a path separator</li> * </ul> * * @return <code>true</code> if the underlying local filesystem uses drives assigned to letters */ public static boolean hasRootDrives() { return IS_WINDOWS || OsFamilies.OS_2.isCurrent() || "\\".equals(SEPARATOR); } /** * Returns a <code>java.io.File</code> instance corresponding to this file. */ public Object getUnderlyingFileObject() { return file; } ///////////////////////////////////////// // AbstractFile methods implementation // ///////////////////////////////////////// public boolean isSymlink() { // Note: this value must not be cached as its value can change over time (canonical path can change) AbstractFile parent = getParent(); String canonPath = getCanonicalPath(false); if(parent==null || canonPath==null) return false; else { String parentCanonPath = parent.getCanonicalPath(true); return !canonPath.equals(parentCanonPath+getName()); } } public long getDate() { return file.lastModified(); } public boolean canChangeDate() { return true; } public boolean changeDate(long lastModified) { // java.io.File#setLastModified(long) throws an IllegalArgumentException if time is negative. // If specified time is negative, set it to 0 (01/01/1970). if(lastModified < 0) lastModified = 0; return file.setLastModified(lastModified); } public long getSize() { return file.length(); } public AbstractFile getParent() { // Retrieve parent AbstractFile and cache it if (!parentValueSet) { if(parentFilePath !=null) { FileURL parentURL = getURL().getParent(); if(parentURL != null) { parent = FileFactory.getFile(parentURL); } } parentValueSet = true; } return parent; } public void setParent(AbstractFile parent) { this.parent = parent; this.parentValueSet = true; } public boolean exists() { return file.exists(); } public boolean getPermission(int access, int permission) { if(access!= USER_ACCESS) return false; if(permission==READ_PERMISSION) return file.canRead(); else if(permission==WRITE_PERMISSION) return file.canWrite(); else if(permission==EXECUTE_PERMISSION && JavaVersions.JAVA_1_6.isCurrentOrHigher()) return file.canExecute(); return false; } public boolean setPermission(int access, int permission, boolean enabled) { if(access!= USER_ACCESS || JavaVersions.JAVA_1_6.isCurrentLower()) return false; if(permission==READ_PERMISSION) return file.setReadable(enabled); else if(permission==WRITE_PERMISSION) return file.setWritable(enabled); else if(permission==EXECUTE_PERMISSION && JavaVersions.JAVA_1_6.isCurrentOrHigher()) return file.setExecutable(enabled); return false; } public boolean canGetPermission(int access, int permission) { // getPermission is limited to the user access type if(access!=USER_ACCESS) return false; // Windows only supports write permission: files are either read-only or read-write if(IS_WINDOWS) return permission==WRITE_PERMISSION; // Execute permission is supported only under Java 1.6 (and on platforms other than Windows) return permission!=EXECUTE_PERMISSION || JavaVersions.JAVA_1_6.isCurrentOrHigher(); } public boolean canSetPermission(int access, int permission) { // setPermission is limited to the user access type if(access!=USER_ACCESS || JavaVersions.JAVA_1_6.isCurrentLower()) return false; // Windows only supports write permission: files are either read-only or read-write return !IS_WINDOWS || permission==WRITE_PERMISSION; } /** * Always returns <code>null</code>, this information is not available unfortunately. */ public String getOwner() { return null; } /** * Always returns <code>false</code>, this information is not available unfortunately. */ public boolean canGetOwner() { return false; } /** * Always returns <code>null</code>, this information is not available unfortunately. */ public String getGroup() { return null; } /** * Always returns <code>false</code>, this information is not available unfortunately. */ public boolean canGetGroup() { return false; } public boolean isDirectory() { // This test is not necessary anymore now that 'No disk' error dialogs are disabled entirely (using Kernel32 // DLL's SetErrorMode function). Leaving this code commented for a while in case the problem comes back. // // To avoid drive seeks and potential 'floppy drive not available' dialog under Win32 // // triggered by java.io.File.isDirectory() // if(IS_WINDOWS && guessFloppyDrive()) // return true; return file.isDirectory(); } /** * Implementation notes: the returned <code>InputStream</code> uses a NIO {@link FileChannel} under the hood to * benefit from <code>InterruptibleChannel</code> and allow a thread waiting for an I/O to be gracefully interrupted * using <code>Thread#interrupt()</code>. */ public InputStream getInputStream() throws IOException { return new LocalInputStream(new FileInputStream(file).getChannel()); } /** * Implementation notes: the returned <code>InputStream</code> uses a NIO {@link FileChannel} under the hood to * benefit from <code>InterruptibleChannel</code> and allow a thread waiting for an I/O to be gracefully interrupted * using <code>Thread#interrupt()</code>. */ public OutputStream getOutputStream(boolean append) throws IOException { return new LocalOutputStream(new FileOutputStream(absPath, append).getChannel()); } public boolean hasRandomAccessInputStream() { return true; } /** * Implementation notes: the returned <code>InputStream</code> uses a NIO {@link FileChannel} under the hood to * benefit from <code>InterruptibleChannel</code> and allow a thread waiting for an I/O to be gracefully interrupted * using <code>Thread#interrupt()</code>. */ public RandomAccessInputStream getRandomAccessInputStream() throws IOException { return new LocalRandomAccessInputStream(new RandomAccessFile(file, "r").getChannel()); } public boolean hasRandomAccessOutputStream() { return true; } /** * Implementation notes: the returned <code>InputStream</code> uses a NIO {@link FileChannel} under the hood to * benefit from <code>InterruptibleChannel</code> and allow a thread waiting for an I/O to be gracefully interrupted * using <code>Thread#interrupt()</code>. */ public RandomAccessOutputStream getRandomAccessOutputStream() throws IOException { return new LocalRandomAccessOutputStream(new RandomAccessFile(file, "rw").getChannel()); } public void delete() throws IOException { boolean ret = file.delete(); if(!ret) throw new IOException(); } public AbstractFile[] ls() throws IOException { return ls(null); } public void mkdir() throws IOException { if(!new File(absPath).mkdir()) throw new IOException(); } public long getFreeSpace() { if(JavaVersions.JAVA_1_6.isCurrentOrHigher()) return file.getFreeSpace(); return getVolumeInfo()[1]; } public long getTotalSpace() { if(JavaVersions.JAVA_1_6.isCurrentOrHigher()) return file.getTotalSpace(); return getVolumeInfo()[0]; } /** * Always returns <code>true</code>. * @return <code>true</code> */ public boolean canRunProcess() { return true; } /** * Returns a process executing the specied local command. * @param tokens describes the command and its arguments. * @throws IOException if an error occured while creating the process. */ public AbstractProcess runProcess(String[] tokens) throws IOException { if(!isDirectory()) { if(Debug.ON) Debug.trace("Tried to create a process using a file as a working directory."); throw new IOException(file + " is not a directory"); } return new LocalProcess(tokens, file); } //////////////////////// // Overridden methods // //////////////////////// public String getName() { // If this file has no parent, return: // - the drive's name under OSes with root drives such as Windows, e.g. "C:" // - "/" under Unix-based systems if(parentFilePath==null) return hasRootDrives()?absPath:"/"; return file.getName(); } public String getAbsolutePath() { // Append separator for root folders (C:\ , /) and for directories if(parentFilePath ==null || (isDirectory() && !absPath.endsWith(SEPARATOR))) return absPath+SEPARATOR; return absPath; } public String getCanonicalPath() { // This test is not necessary anymore now that 'No disk' error dialogs are disabled entirely (using Kernel32 // DLL's SetErrorMode function). Leaving this code commented for a while in case the problem comes back. // // To avoid drive seeks and potential 'floppy drive not available' dialog under Win32 // // triggered by java.io.File.getCanonicalPath() // if(IS_WINDOWS && guessFloppyDrive()) // return absPath; // Note: canonical path must not be cached as its resolution can change over time, for instance // if a file 'Test' is renamed to 'test' in the same folder, its canonical path would still be 'Test' // if it was resolved prior to the renaming and thus be recognized as a symbolic link try { String canonicalPath = file.getCanonicalPath(); // Append separator for directories if(isDirectory() && !canonicalPath.endsWith(SEPARATOR)) canonicalPath = canonicalPath + SEPARATOR; return canonicalPath; } catch(IOException e) { return absPath; } } public String getSeparator() { return SEPARATOR; } public AbstractFile[] ls(FilenameFilter filenameFilter) throws IOException { String names[] = file.list(); if(names==null) throw new IOException(); if(filenameFilter!=null) names = filenameFilter.filter(names); AbstractFile children[] = new AbstractFile[names.length]; FileURL childURL; for(int i=0; i<names.length; i++) { // Clone the FileURL of this file and set the child's path, this is more efficient than creating a new // FileURL instance from scratch. childURL = (FileURL)fileURL.clone(); if(isUNC) // Special case for UNC paths which include the hostname in it childURL.setPath(addTrailingSeparator(fileURL.getPath())+names[i]); else childURL.setPath(absPath+SEPARATOR+names[i]); // Retrieves an AbstractFile (LocalFile or AbstractArchiveFile) instance potentially fetched from the // LRU cache and reuse this file as parent children[i] = FileFactory.getFile(childURL, this); } return children; } /** * Overrides {@link AbstractFile#moveTo(AbstractFile)} to move/rename the file directly if the destination file * is also a local file. */ public boolean moveTo(AbstractFile destFile) throws FileTransferException { if(!destFile.getURL().getProtocol().equals(FileProtocols.FILE)) { return super.moveTo(destFile); } // If destination file is not a LocalFile nor has a LocalFile ancestor (for instance an archive entry), // renaming won't work so use the default moveTo() implementation instead destFile = destFile.getTopAncestor(); if(!(destFile instanceof LocalFile)) { return super.moveTo(destFile); } // Fail in some situations where java.io.File#renameTo() doesn't, such as if the destination already exists. // Note that java.io.File#renameTo()'s implementation is system-dependant, so it's always a good idea to // perform all those checks even if some are not necessary on this or that platform. checkCopyPrerequisites(destFile, true); // Move file return file.renameTo(((LocalFile)destFile).file); } public boolean isHidden() { return file.isHidden(); } /** * Overridden for performance reasons. */ public int getPermissionGetMask() { // Windows only supports write permission for user: files are either read-only or read-write if(IS_WINDOWS) return 128; // Get permission support is limited to the user access type. Executable permission flag is only available under // Java 1.6 and up. return JavaVersions.JAVA_1_6.isCurrentOrHigher()? 448 // rwx------ (700 octal) :384; // rw------- (300 octal) } /** * Overridden for performance reasons. */ public int getPermissionSetMask() { // Windows only supports write permission for user: files are either read-only or read-write if(IS_WINDOWS) return 128; // Set permission support is only available under Java 1.6 and up and is limited to the user access type return JavaVersions.JAVA_1_6.isCurrentOrHigher()? 448 // rwx------ (700 octal) :0; // --------- (0 octal) } /** * Overridden for performance reasons. This method doesn't iterate like {@link AbstractFile#getRoot()} to resolve * the root file. */ public AbstractFile getRoot() throws IOException { if(IS_WINDOWS) { // Extract drive letter from the path Matcher matcher = windowsDriveRootPattern.matcher(absPath); if(matcher.matches()) return FileFactory.getFile(absPath.substring(matcher.start(), matcher.end())); } else if(SEPARATOR.equals("/")) { return FileFactory.getFile("/"); } return super.getRoot(); } /** * Overridden to return {@link #SHOULD_NOT_HINT} under Windows when the destination file is located on a different * drive from this file (e.g. C:\ and E:\). */ public int getMoveToHint(AbstractFile destFile) { int moveHint = super.getMoveToHint(destFile); if(moveHint!=SHOULD_HINT && moveHint!=MUST_HINT) return moveHint; // This check is necessary under Windows because java.io.File#renameTo(java.io.File) does not return false // if the destination file is located on a different drive, contrary for example to Mac OS X where renameTo // returns false in this case. // Not doing this under Windows would mean files would get moved between drives with renameTo, which doesn't // allow the transfer to be monitored. // Note that Windows UNC paths are handled by the super method when comparing hosts for equality. if(IS_WINDOWS) { try { if(!getRoot().equals(destFile.getRoot())) return SHOULD_NOT_HINT; } catch(IOException e) { return SHOULD_NOT_HINT; } } return moveHint; } /////////////////// // Inner classes // /////////////////// /** * LocalRandomAccessInputStream extends RandomAccessInputStream to provide random read access to a LocalFile. * This implementation uses a NIO <code>FileChannel</code> under the hood to benefit from * <code>InterruptibleChannel</code> and allow a thread waiting for an I/O to be gracefully interrupted using * <code>Thread#interrupt()</code>. */ public static class LocalRandomAccessInputStream extends RandomAccessInputStream { private final FileChannel channel; private final ByteBuffer bb; private LocalRandomAccessInputStream(FileChannel channel) { this.channel = channel; this.bb = BufferPool.getByteBuffer(); } public int read() throws IOException { synchronized(bb) { bb.position(0); bb.limit(1); int nbRead = channel.read(bb); if(nbRead<=0) return nbRead; return 0xFF&bb.get(0); } } public int read(byte b[], int off, int len) throws IOException { synchronized(bb) { bb.position(0); bb.limit(Math.min(bb.capacity(), len)); int nbRead = channel.read(bb); if(nbRead<=0) return nbRead; bb.position(0); bb.get(b, off, nbRead); return nbRead; } } public void close() throws IOException { BufferPool.releaseByteBuffer(bb); channel.close(); } public long getOffset() throws IOException { return channel.position(); } public long getLength() throws IOException { return channel.size(); } public void seek(long offset) throws IOException { channel.position(offset); } } /** * A replacement for <code>java.io.FileInputStream</code> that uses a NIO {@link FileChannel} under the hood to * benefit from <code>InterruptibleChannel</code> and allow a thread waiting for an I/O to be gracefully interrupted * using <code>Thread#interrupt()</code>. * * <p>This class simply delegates all its methods to a * {@link com.mucommander.file.impl.local.LocalFile.LocalRandomAccessInputStream} instance. Therefore, this class * does not derive from {@link com.mucommander.io.RandomAccessInputStream}, preventing random-access methods from * being used.</p> * */ public static class LocalInputStream extends FilterInputStream { public LocalInputStream(FileChannel channel) { super(new LocalRandomAccessInputStream(channel)); } } /** * A replacement for <code>java.io.FileOutputStream</code> that uses a NIO {@link FileChannel} under the hood to * benefit from <code>InterruptibleChannel</code> and allow a thread waiting for an I/O to be gracefully interrupted * using <code>Thread#interrupt()</code>. * * <p>This class simply delegates all its methods to a * {@link com.mucommander.file.impl.local.LocalFile.LocalRandomAccessOutputStream} instance. Therefore, this class * does not derive from {@link com.mucommander.io.RandomAccessOutputStream}, preventing random-access methods from * being used.</p> * */ public static class LocalOutputStream extends FilterOutputStream { public LocalOutputStream(FileChannel channel) { super(new LocalRandomAccessOutputStream(channel)); } // Note: this method is not proxied by FilterOutputStream(!) public void write(byte b[]) throws IOException { out.write(b); } // Note: this method is not proxied by FilterOutputStream(!) public void write(byte b[], int off, int len) throws IOException { out.write(b, off, len); } } /** * LocalRandomAccessOutputStream extends RandomAccessOutputStream to provide random write access to a LocalFile. * This implementation uses a NIO <code>FileChannel</code> under the hood to benefit from * <code>InterruptibleChannel</code> and allow a thread waiting for an I/O to be gracefully interrupted using * <code>Thread#interrupt()</code>. */ public static class LocalRandomAccessOutputStream extends RandomAccessOutputStream { private final FileChannel channel; private final ByteBuffer bb; public LocalRandomAccessOutputStream(FileChannel channel) { this.channel = channel; this.bb = BufferPool.getByteBuffer(); } public void write(int i) throws IOException { synchronized(bb) { bb.position(0); bb.limit(1); bb.put((byte)i); bb.position(0); channel.write(bb); } } public void write(byte b[]) throws IOException { write(b, 0, b.length); } public void write(byte b[], int off, int len) throws IOException { int nbToWrite; synchronized(bb) { do { bb.position(0); nbToWrite = Math.min(bb.capacity(), len); bb.limit(nbToWrite); bb.put(b, off, nbToWrite); bb.position(0); nbToWrite = channel.write(bb); len -= nbToWrite; off += nbToWrite; } while(len>0); } } public void setLength(long newLength) throws IOException { long currentLength = getLength(); if(newLength==currentLength) return; long currentPos = channel.position(); if(newLength<currentLength) { // Truncate the file and position the offset to the new EOF if it was beyond channel.truncate(newLength); if(currentPos>newLength) channel.position(newLength); } else { // Expand the file by positionning the offset at the new EOF and writing a byte, and reposition the // offset to where it was channel.position(newLength-1); // Note: newLength cannot be 0 write(0); channel.position(currentPos); } } public void close() throws IOException { BufferPool.releaseByteBuffer(bb); channel.close(); } public long getOffset() throws IOException { return channel.position(); } public long getLength() throws IOException { return channel.size(); } public void seek(long offset) throws IOException { channel.position(offset); } } }
true
true
protected long[] getNativeVolumeInfo() { // BufferedReader br = null; String absPath = getAbsolutePath(); long dfInfo[] = new long[]{-1, -1}; try { // OS is Windows if(IS_WINDOWS) { // // Parses the output of 'dir "filePath"' command to retrieve free space information // // // 'dir' command returns free space on the last line // //Process process = PlatformManager.execute("dir \""+absPath+"\"", this); // //Process process = Runtime.getRuntime().exec(new String[] {"dir", absPath}, null, new File(getAbsolutePath())); // Process process = Runtime.getRuntime().exec(PlatformManager.getDefaultShellCommand() + " dir \""+absPath+"\""); // // // Check that the process was correctly started // if(process!=null) { // br = new BufferedReader(new InputStreamReader(process.getInputStream())); // String line; // String lastLine = null; // // Retrieves last line of dir // while((line=br.readLine())!=null) { // if(!line.trim().equals("")) // lastLine = line; // } // // // Last dir line may look like something this (might vary depending on system's language, below in French): // // 6 Rep(s) 14 767 521 792 octets libres // if(lastLine!=null) { // StringTokenizer st = new StringTokenizer(lastLine, " \t\n\r\f,."); // // Discard first token // st.nextToken(); // // // Concatenates as many contiguous groups of numbers // String token; // String freeSpace = ""; // while(st.hasMoreTokens()) { // token = st.nextToken(); // char c = token.charAt(0); // if(c>='0' && c<='9') // freeSpace += token; // else if(!freeSpace.equals("")) // break; // } // // dfInfo[1] = Long.parseLong(freeSpace); // } // } // Retrieves the total and free space information using the GetDiskFreeSpaceEx function of the // Kernel32 API. LongByReference totalSpaceLBR = new LongByReference(); LongByReference freeSpaceLBR = new LongByReference(); if(Kernel32API.INSTANCE.GetDiskFreeSpaceEx(absPath, null, totalSpaceLBR, freeSpaceLBR)) { dfInfo[0] = totalSpaceLBR.getValue(); dfInfo[1] = freeSpaceLBR.getValue(); } else { if(Debug.ON) Debug.trace("Call to GetDiskFreeSpaceEx failed, absPath="+absPath); } } else if(OsFamily.getCurrent().isUnixBased()) { // // Parses the output of 'df -k "filePath"' command on UNIX-based systems to retrieve free and total space information // // // 'df -k' returns totals in block of 1K = 1024 bytes // Process process = Runtime.getRuntime().exec(new String[]{"df", "-k", absPath}, null, file); // // // Check that the process was correctly started // if(process!=null) { // br = new BufferedReader(new InputStreamReader(process.getInputStream())); // // Discard the first line ("Filesystem 1K-blocks Used Avail Capacity Mounted on"); // br.readLine(); // String line = br.readLine(); // // // Sample lines: // // /dev/disk0s2 116538416 109846712 6179704 95% / // // automount -fstab [202] 0 0 0 100% /automount/Servers // // /dev/disk2s2 2520 1548 972 61% /Volumes/muCommander 0.8 // // // We're interested in the '1K-blocks' and 'Avail' fields (only). // // The 'Filesystem' and 'Mounted On' fields can contain spaces (e.g. 'automount -fstab [202]' and // // '/Volumes/muCommander 0.8' resp.) and therefore be made of several tokens. A stable way to // // determine the position of the fields we're interested in is to look for the last token that // // starts with a '/' character which should necessarily correspond to the first token of the // // 'Mounted on' field. The '1K-blocks' and 'Avail' fields are 4 and 2 tokens away from it // // respectively. // // // Start by tokenizing the whole line // Vector tokenV = new Vector(); // if(line!=null) { // StringTokenizer st = new StringTokenizer(line); // while(st.hasMoreTokens()) // tokenV.add(st.nextToken()); // } // // int nbTokens = tokenV.size(); // if(nbTokens<6) { // // This shouldn't normally happen // if(Debug.ON) Debug.trace("Failed to parse output of df -k "+absPath+" line="+line); // return dfInfo; // } // // // Find the last token starting with '/' // int pos = nbTokens-1; // while(!((String)tokenV.elementAt(pos)).startsWith("/")) { // if(pos==0) { // // This shouldn't normally happen // if(Debug.ON) Debug.trace("Failed to parse output of df -k "+absPath+" line="+line); // return dfInfo; // } // // --pos; // } // // // '1-blocks' field (total space) // dfInfo[0] = Long.parseLong((String)tokenV.elementAt(pos-4)) * 1024; // // 'Avail' field (free space) // dfInfo[1] = Long.parseLong((String)tokenV.elementAt(pos-2)) * 1024; // } // Retrieves the total and free space information using the POSIX statvfs function POSIX.STATVFSSTRUCT struct = new POSIX.STATVFSSTRUCT(); if(POSIX.INSTANCE.statvfs(absPath, struct)==0) { dfInfo[0] = struct.f_blocks * struct.f_frsize; dfInfo[1] = struct.f_bfree * struct.f_frsize; } } } catch(Throwable e) { // JNA throws a java.lang.UnsatisfiedLinkError if the native can't be found if(com.mucommander.Debug.ON) { com.mucommander.Debug.trace("Exception thrown while retrieving volume info: "+e); e.printStackTrace(); } } // finally { // if(br!=null) // try { br.close(); } catch(IOException e) {} // } return dfInfo; }
protected long[] getNativeVolumeInfo() { // BufferedReader br = null; String absPath = getAbsolutePath(); long dfInfo[] = new long[]{-1, -1}; try { // OS is Windows if(IS_WINDOWS) { // // Parses the output of 'dir "filePath"' command to retrieve free space information // // // 'dir' command returns free space on the last line // //Process process = PlatformManager.execute("dir \""+absPath+"\"", this); // //Process process = Runtime.getRuntime().exec(new String[] {"dir", absPath}, null, new File(getAbsolutePath())); // Process process = Runtime.getRuntime().exec(PlatformManager.getDefaultShellCommand() + " dir \""+absPath+"\""); // // // Check that the process was correctly started // if(process!=null) { // br = new BufferedReader(new InputStreamReader(process.getInputStream())); // String line; // String lastLine = null; // // Retrieves last line of dir // while((line=br.readLine())!=null) { // if(!line.trim().equals("")) // lastLine = line; // } // // // Last dir line may look like something this (might vary depending on system's language, below in French): // // 6 Rep(s) 14 767 521 792 octets libres // if(lastLine!=null) { // StringTokenizer st = new StringTokenizer(lastLine, " \t\n\r\f,."); // // Discard first token // st.nextToken(); // // // Concatenates as many contiguous groups of numbers // String token; // String freeSpace = ""; // while(st.hasMoreTokens()) { // token = st.nextToken(); // char c = token.charAt(0); // if(c>='0' && c<='9') // freeSpace += token; // else if(!freeSpace.equals("")) // break; // } // // dfInfo[1] = Long.parseLong(freeSpace); // } // } // Retrieves the total and free space information using the GetDiskFreeSpaceEx function of the // Kernel32 API. LongByReference totalSpaceLBR = new LongByReference(); LongByReference freeSpaceLBR = new LongByReference(); if(Kernel32API.INSTANCE.GetDiskFreeSpaceEx(absPath, null, totalSpaceLBR, freeSpaceLBR)) { dfInfo[0] = totalSpaceLBR.getValue(); dfInfo[1] = freeSpaceLBR.getValue(); } else { if(Debug.ON) Debug.trace("Call to GetDiskFreeSpaceEx failed, absPath="+absPath); } } else if(OsFamily.getCurrent().isUnixBased()) { // // Parses the output of 'df -k "filePath"' command on UNIX-based systems to retrieve free and total space information // // // 'df -k' returns totals in block of 1K = 1024 bytes // Process process = Runtime.getRuntime().exec(new String[]{"df", "-k", absPath}, null, file); // // // Check that the process was correctly started // if(process!=null) { // br = new BufferedReader(new InputStreamReader(process.getInputStream())); // // Discard the first line ("Filesystem 1K-blocks Used Avail Capacity Mounted on"); // br.readLine(); // String line = br.readLine(); // // // Sample lines: // // /dev/disk0s2 116538416 109846712 6179704 95% / // // automount -fstab [202] 0 0 0 100% /automount/Servers // // /dev/disk2s2 2520 1548 972 61% /Volumes/muCommander 0.8 // // // We're interested in the '1K-blocks' and 'Avail' fields (only). // // The 'Filesystem' and 'Mounted On' fields can contain spaces (e.g. 'automount -fstab [202]' and // // '/Volumes/muCommander 0.8' resp.) and therefore be made of several tokens. A stable way to // // determine the position of the fields we're interested in is to look for the last token that // // starts with a '/' character which should necessarily correspond to the first token of the // // 'Mounted on' field. The '1K-blocks' and 'Avail' fields are 4 and 2 tokens away from it // // respectively. // // // Start by tokenizing the whole line // Vector tokenV = new Vector(); // if(line!=null) { // StringTokenizer st = new StringTokenizer(line); // while(st.hasMoreTokens()) // tokenV.add(st.nextToken()); // } // // int nbTokens = tokenV.size(); // if(nbTokens<6) { // // This shouldn't normally happen // if(Debug.ON) Debug.trace("Failed to parse output of df -k "+absPath+" line="+line); // return dfInfo; // } // // // Find the last token starting with '/' // int pos = nbTokens-1; // while(!((String)tokenV.elementAt(pos)).startsWith("/")) { // if(pos==0) { // // This shouldn't normally happen // if(Debug.ON) Debug.trace("Failed to parse output of df -k "+absPath+" line="+line); // return dfInfo; // } // // --pos; // } // // // '1-blocks' field (total space) // dfInfo[0] = Long.parseLong((String)tokenV.elementAt(pos-4)) * 1024; // // 'Avail' field (free space) // dfInfo[1] = Long.parseLong((String)tokenV.elementAt(pos-2)) * 1024; // } // Retrieves the total and free space information using the POSIX statvfs function POSIX.STATVFSSTRUCT struct = new POSIX.STATVFSSTRUCT(); if(POSIX.INSTANCE.statvfs(absPath, struct)==0) { dfInfo[0] = struct.f_blocks * (long)struct.f_frsize; dfInfo[1] = struct.f_bfree * (long)struct.f_frsize; } } } catch(Throwable e) { // JNA throws a java.lang.UnsatisfiedLinkError if the native can't be found if(com.mucommander.Debug.ON) { com.mucommander.Debug.trace("Exception thrown while retrieving volume info: "+e); e.printStackTrace(); } } // finally { // if(br!=null) // try { br.close(); } catch(IOException e) {} // } return dfInfo; }
diff --git a/src/main/java/be/darnell/mc/FuzzyMessenger/commands/EmoteCommand.java b/src/main/java/be/darnell/mc/FuzzyMessenger/commands/EmoteCommand.java index 0be417f..b36ca93 100644 --- a/src/main/java/be/darnell/mc/FuzzyMessenger/commands/EmoteCommand.java +++ b/src/main/java/be/darnell/mc/FuzzyMessenger/commands/EmoteCommand.java @@ -1,73 +1,73 @@ /* * Copyright (c) 2013 cedeel. * 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. * * The name of the author may not 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 be.darnell.mc.FuzzyMessenger.commands; import be.darnell.mc.FuzzyMessenger.MuteManager; import be.darnell.mc.FuzzyMessenger.PrivateMessaging; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class EmoteCommand implements CommandExecutor { private MuteManager manager; public EmoteCommand(MuteManager mm) { manager = mm; } @Override public boolean onCommand(CommandSender sender, Command command, String alias, String... args) { emote(sender, PrivateMessaging.constructMessage(args, 0)); return true; } private void emote(CommandSender sender, String message) { if (sender instanceof Player) { Player player = (Player) sender; if (player.hasPermission("fuzzymessenger.me")) { - if (manager.getAll().containsKey(player.getName())) { + if (manager.isMuted(player)) { player.sendMessage(ChatColor.RED + "You can't use emotes while muted."); } else { Bukkit.getServer().broadcastMessage(ChatColor.DARK_GRAY + "* " + ChatColor.WHITE + player.getDisplayName() + " " + message + ChatColor.DARK_GRAY + " *"); } } else { player.sendMessage(ChatColor.RED + "You don't have permission to use emotes."); } } else { Bukkit.getServer().broadcastMessage(ChatColor.DARK_GRAY + "* " + ChatColor.WHITE + "Console " + message + ChatColor.DARK_GRAY + " *"); } } }
true
true
private void emote(CommandSender sender, String message) { if (sender instanceof Player) { Player player = (Player) sender; if (player.hasPermission("fuzzymessenger.me")) { if (manager.getAll().containsKey(player.getName())) { player.sendMessage(ChatColor.RED + "You can't use emotes while muted."); } else { Bukkit.getServer().broadcastMessage(ChatColor.DARK_GRAY + "* " + ChatColor.WHITE + player.getDisplayName() + " " + message + ChatColor.DARK_GRAY + " *"); } } else { player.sendMessage(ChatColor.RED + "You don't have permission to use emotes."); } } else { Bukkit.getServer().broadcastMessage(ChatColor.DARK_GRAY + "* " + ChatColor.WHITE + "Console " + message + ChatColor.DARK_GRAY + " *"); } }
private void emote(CommandSender sender, String message) { if (sender instanceof Player) { Player player = (Player) sender; if (player.hasPermission("fuzzymessenger.me")) { if (manager.isMuted(player)) { player.sendMessage(ChatColor.RED + "You can't use emotes while muted."); } else { Bukkit.getServer().broadcastMessage(ChatColor.DARK_GRAY + "* " + ChatColor.WHITE + player.getDisplayName() + " " + message + ChatColor.DARK_GRAY + " *"); } } else { player.sendMessage(ChatColor.RED + "You don't have permission to use emotes."); } } else { Bukkit.getServer().broadcastMessage(ChatColor.DARK_GRAY + "* " + ChatColor.WHITE + "Console " + message + ChatColor.DARK_GRAY + " *"); } }
diff --git a/org.eclipse.mylyn.wikitext.ui/src/org/eclipse/mylyn/internal/wikitext/ui/util/InformationPresenterUtil.java b/org.eclipse.mylyn.wikitext.ui/src/org/eclipse/mylyn/internal/wikitext/ui/util/InformationPresenterUtil.java index d8249b8f..6833ce9b 100644 --- a/org.eclipse.mylyn.wikitext.ui/src/org/eclipse/mylyn/internal/wikitext/ui/util/InformationPresenterUtil.java +++ b/org.eclipse.mylyn.wikitext.ui/src/org/eclipse/mylyn/internal/wikitext/ui/util/InformationPresenterUtil.java @@ -1,195 +1,197 @@ /******************************************************************************* * Copyright (c) 2007, 2008 David Green 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: * David Green - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.wikitext.ui.util; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.text.AbstractInformationControlManager; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.DefaultInformationControl.IInformationPresenter; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.IInformationProviderExtension; import org.eclipse.jface.text.information.IInformationProviderExtension2; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.mylyn.internal.wikitext.ui.editor.syntax.FastMarkupPartitioner; import org.eclipse.mylyn.wikitext.ui.viewer.HtmlTextPresenter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; /** * * @author David Green */ public class InformationPresenterUtil { /** * @see InformationPresenter#setSizeConstraints(int, int, boolean, boolean) */ public static class SizeConstraint { int horizontalWidthInChars; int verticalWidthInChars; boolean enforceAsMinimumSize; boolean enforceAsMaximumSize; /** * @see InformationPresenter#setSizeConstraints(int, int, boolean, boolean) */ public SizeConstraint(int horizontalWidthInChars, int verticalWidthInChars, boolean enforceAsMinimumSize, boolean enforceAsMaximumSize) { super(); this.horizontalWidthInChars = horizontalWidthInChars; this.verticalWidthInChars = verticalWidthInChars; this.enforceAsMinimumSize = enforceAsMinimumSize; this.enforceAsMaximumSize = enforceAsMaximumSize; } } @SuppressWarnings("deprecation") private static final class InformationProvider implements IInformationProvider, IInformationProviderExtension, IInformationProviderExtension2 { private final IRegion hoverRegion; private final Object hoverInfo; private final IInformationControlCreator controlCreator; InformationProvider(IRegion hoverRegion, Object info, IInformationControlCreator controlCreator) { this.hoverRegion = hoverRegion; this.hoverInfo = info; this.controlCreator = controlCreator; } public IRegion getSubject(ITextViewer textViewer, int invocationOffset) { return hoverRegion; } public String getInformation(ITextViewer textViewer, IRegion subject) { return hoverInfo.toString(); } public Object getInformation2(ITextViewer textViewer, IRegion subject) { return hoverInfo; } public IInformationControlCreator getInformationPresenterControlCreator() { return controlCreator; } } private static final String DATA_INFORMATION_PRESENTER = InformationPresenterUtil.class.getName() + "#informationPresenter"; //$NON-NLS-1$ private static final String DATA_INFORMATION_CONTROL_CREATOR = InformationPresenterUtil.class.getName() + "#informationControlCreator"; //$NON-NLS-1$ /** * Get an information presenter to present the provided HTML content. The returned presenter is ready for displaying * the information, all that is left to do is call {@link InformationPresenter#showInformation()}. * * @param viewer * the viewer for which the information control should be created * @param constraint * the size constraint * @param toolBarManager * the tool bar manager, or null if there should be none * @param htmlContent * the HTML content to be displayed by the information presenter. * * @return the presenter */ public static InformationPresenter getHtmlInformationPresenter(ISourceViewer viewer, SizeConstraint constraint, final ToolBarManager toolBarManager, String htmlContent) { Control control = viewer.getTextWidget(); InformationPresenter presenter = (InformationPresenter) control.getData(DATA_INFORMATION_PRESENTER); - int offset = 0; + // bug 270059: ensure that the size/positioning math works by specifying the offet of the + // current selection. + int offset = viewer.getSelectedRange().x; IInformationControlCreator informationControlCreator; if (presenter == null) { informationControlCreator = new IInformationControlCreator() { @SuppressWarnings("deprecation") public IInformationControl createInformationControl(Shell shell) { try { // try reflection to access 3.4 APIs // DefaultInformationControl(Shell parent, ToolBarManager toolBarManager, IInformationPresenter presenter); return DefaultInformationControl.class.getConstructor(Shell.class, ToolBarManager.class, IInformationPresenter.class) .newInstance(shell, toolBarManager, new HtmlTextPresenter()); } catch (NoSuchMethodException e) { // no way with 3.3 to get V_SCROLL and a ToolBarManager return new DefaultInformationControl(shell, SWT.RESIZE, SWT.V_SCROLL | SWT.H_SCROLL, new HtmlTextPresenter()); } catch (Exception e) { throw new IllegalStateException(e); } } }; presenter = new InformationPresenter(informationControlCreator) { @Override public IInformationProvider getInformationProvider(String contentType) { IInformationProvider informationProvider = super.getInformationProvider(contentType); if (informationProvider == null) { informationProvider = super.getInformationProvider(IDocument.DEFAULT_CONTENT_TYPE); } return informationProvider; } }; presenter.install(viewer); presenter.setAnchor(AbstractInformationControlManager.ANCHOR_BOTTOM); presenter.setMargins(6, 6); // default values from AbstractInformationControlManager presenter.setOffset(offset); presenter.install(viewer); final InformationPresenter informationPresenter = presenter; viewer.getTextWidget().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { try { informationPresenter.uninstall(); } catch (Exception e2) { } informationPresenter.dispose(); } }); control.setData(DATA_INFORMATION_PRESENTER, presenter); control.setData(DATA_INFORMATION_CONTROL_CREATOR, informationControlCreator); } else { informationControlCreator = (IInformationControlCreator) control.getData(DATA_INFORMATION_CONTROL_CREATOR); presenter.disposeInformationControl(); } presenter.setSizeConstraints(constraint.horizontalWidthInChars, constraint.verticalWidthInChars, constraint.enforceAsMinimumSize, constraint.enforceAsMaximumSize); InformationProvider informationProvider = new InformationProvider(new org.eclipse.jface.text.Region(offset, 0), htmlContent, informationControlCreator); for (String contentType : FastMarkupPartitioner.ALL_CONTENT_TYPES) { presenter.setInformationProvider(informationProvider, contentType); } presenter.setInformationProvider(informationProvider, IDocument.DEFAULT_CONTENT_TYPE); return presenter; } }
true
true
public static InformationPresenter getHtmlInformationPresenter(ISourceViewer viewer, SizeConstraint constraint, final ToolBarManager toolBarManager, String htmlContent) { Control control = viewer.getTextWidget(); InformationPresenter presenter = (InformationPresenter) control.getData(DATA_INFORMATION_PRESENTER); int offset = 0; IInformationControlCreator informationControlCreator; if (presenter == null) { informationControlCreator = new IInformationControlCreator() { @SuppressWarnings("deprecation") public IInformationControl createInformationControl(Shell shell) { try { // try reflection to access 3.4 APIs // DefaultInformationControl(Shell parent, ToolBarManager toolBarManager, IInformationPresenter presenter); return DefaultInformationControl.class.getConstructor(Shell.class, ToolBarManager.class, IInformationPresenter.class) .newInstance(shell, toolBarManager, new HtmlTextPresenter()); } catch (NoSuchMethodException e) { // no way with 3.3 to get V_SCROLL and a ToolBarManager return new DefaultInformationControl(shell, SWT.RESIZE, SWT.V_SCROLL | SWT.H_SCROLL, new HtmlTextPresenter()); } catch (Exception e) { throw new IllegalStateException(e); } } }; presenter = new InformationPresenter(informationControlCreator) { @Override public IInformationProvider getInformationProvider(String contentType) { IInformationProvider informationProvider = super.getInformationProvider(contentType); if (informationProvider == null) { informationProvider = super.getInformationProvider(IDocument.DEFAULT_CONTENT_TYPE); } return informationProvider; } }; presenter.install(viewer); presenter.setAnchor(AbstractInformationControlManager.ANCHOR_BOTTOM); presenter.setMargins(6, 6); // default values from AbstractInformationControlManager presenter.setOffset(offset); presenter.install(viewer); final InformationPresenter informationPresenter = presenter; viewer.getTextWidget().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { try { informationPresenter.uninstall(); } catch (Exception e2) { } informationPresenter.dispose(); } }); control.setData(DATA_INFORMATION_PRESENTER, presenter); control.setData(DATA_INFORMATION_CONTROL_CREATOR, informationControlCreator); } else { informationControlCreator = (IInformationControlCreator) control.getData(DATA_INFORMATION_CONTROL_CREATOR); presenter.disposeInformationControl(); } presenter.setSizeConstraints(constraint.horizontalWidthInChars, constraint.verticalWidthInChars, constraint.enforceAsMinimumSize, constraint.enforceAsMaximumSize); InformationProvider informationProvider = new InformationProvider(new org.eclipse.jface.text.Region(offset, 0), htmlContent, informationControlCreator); for (String contentType : FastMarkupPartitioner.ALL_CONTENT_TYPES) { presenter.setInformationProvider(informationProvider, contentType); } presenter.setInformationProvider(informationProvider, IDocument.DEFAULT_CONTENT_TYPE); return presenter; }
public static InformationPresenter getHtmlInformationPresenter(ISourceViewer viewer, SizeConstraint constraint, final ToolBarManager toolBarManager, String htmlContent) { Control control = viewer.getTextWidget(); InformationPresenter presenter = (InformationPresenter) control.getData(DATA_INFORMATION_PRESENTER); // bug 270059: ensure that the size/positioning math works by specifying the offet of the // current selection. int offset = viewer.getSelectedRange().x; IInformationControlCreator informationControlCreator; if (presenter == null) { informationControlCreator = new IInformationControlCreator() { @SuppressWarnings("deprecation") public IInformationControl createInformationControl(Shell shell) { try { // try reflection to access 3.4 APIs // DefaultInformationControl(Shell parent, ToolBarManager toolBarManager, IInformationPresenter presenter); return DefaultInformationControl.class.getConstructor(Shell.class, ToolBarManager.class, IInformationPresenter.class) .newInstance(shell, toolBarManager, new HtmlTextPresenter()); } catch (NoSuchMethodException e) { // no way with 3.3 to get V_SCROLL and a ToolBarManager return new DefaultInformationControl(shell, SWT.RESIZE, SWT.V_SCROLL | SWT.H_SCROLL, new HtmlTextPresenter()); } catch (Exception e) { throw new IllegalStateException(e); } } }; presenter = new InformationPresenter(informationControlCreator) { @Override public IInformationProvider getInformationProvider(String contentType) { IInformationProvider informationProvider = super.getInformationProvider(contentType); if (informationProvider == null) { informationProvider = super.getInformationProvider(IDocument.DEFAULT_CONTENT_TYPE); } return informationProvider; } }; presenter.install(viewer); presenter.setAnchor(AbstractInformationControlManager.ANCHOR_BOTTOM); presenter.setMargins(6, 6); // default values from AbstractInformationControlManager presenter.setOffset(offset); presenter.install(viewer); final InformationPresenter informationPresenter = presenter; viewer.getTextWidget().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { try { informationPresenter.uninstall(); } catch (Exception e2) { } informationPresenter.dispose(); } }); control.setData(DATA_INFORMATION_PRESENTER, presenter); control.setData(DATA_INFORMATION_CONTROL_CREATOR, informationControlCreator); } else { informationControlCreator = (IInformationControlCreator) control.getData(DATA_INFORMATION_CONTROL_CREATOR); presenter.disposeInformationControl(); } presenter.setSizeConstraints(constraint.horizontalWidthInChars, constraint.verticalWidthInChars, constraint.enforceAsMinimumSize, constraint.enforceAsMaximumSize); InformationProvider informationProvider = new InformationProvider(new org.eclipse.jface.text.Region(offset, 0), htmlContent, informationControlCreator); for (String contentType : FastMarkupPartitioner.ALL_CONTENT_TYPES) { presenter.setInformationProvider(informationProvider, contentType); } presenter.setInformationProvider(informationProvider, IDocument.DEFAULT_CONTENT_TYPE); return presenter; }
diff --git a/hotel-application/hotel-webapps/hotel-inhouse-web/src/main/java/net/mklew/hotelms/inhouse/web/modules/views/top/NewReservation.java b/hotel-application/hotel-webapps/hotel-inhouse-web/src/main/java/net/mklew/hotelms/inhouse/web/modules/views/top/NewReservation.java index 53295c6b..7c48b4f4 100644 --- a/hotel-application/hotel-webapps/hotel-inhouse-web/src/main/java/net/mklew/hotelms/inhouse/web/modules/views/top/NewReservation.java +++ b/hotel-application/hotel-webapps/hotel-inhouse-web/src/main/java/net/mklew/hotelms/inhouse/web/modules/views/top/NewReservation.java @@ -1,59 +1,59 @@ package net.mklew.hotelms.inhouse.web.modules.views.top; import net.mklew.hotelms.domain.room.Room; import net.mklew.hotelms.domain.room.RoomName; import net.mklew.hotelms.domain.room.RoomType; import org.objectledge.context.Context; import org.objectledge.i18n.I18nContext; import org.objectledge.modules.views.BasicLedgeTopView; import org.objectledge.parameters.Parameters; import org.objectledge.pipeline.ProcessingException; import org.objectledge.templating.TemplatingContext; import org.objectledge.web.HttpContext; import org.objectledge.web.mvc.MVCContext; import java.util.*; /** * @author Marek Lewandowski <[email protected]> * @since 11/3/12 * Time: 1:32 PM */ public class NewReservation extends BasicLedgeTopView { /** * Constructs a builder instance. * * @param context application context for use by this builder. */ public NewReservation(Context context) { super(context); } @Override public void process(Parameters parameters, TemplatingContext templatingContext, MVCContext mvcContext, HttpContext httpContext, I18nContext i18nContext) throws ProcessingException { Collection<RoomType> roomTypes = new ArrayList<>(); // TODO fetch room types from repository RoomType luxury = new RoomType("luxury"); RoomType cheap = new RoomType("cheap"); RoomType niceOne = new RoomType("nice one"); roomTypes.addAll(Arrays.asList(luxury, cheap, niceOne)); templatingContext.put("roomTypes", roomTypes); // TODO fetch rooms from repository // TODO add comparable to Room and compare it by room names // TODO pass Set (so its ordered) to templatingContext instead of collection - Room L100 = new Room(luxury, new RoomName("100", "L")); - Room L101 = new Room(luxury, new RoomName("101", "L")); - Room L102 = new Room(luxury, new RoomName("102", "L")); - Room C103 = new Room(cheap, new RoomName("103", "C")); - Room C104 = new Room(cheap, new RoomName("104", "C")); - Room N105 = new Room(niceOne, new RoomName("105", "N")); + Room L100 = new Room(luxury, new RoomName("100", "L"), 1); + Room L101 = new Room(luxury, new RoomName("101", "L"), 0); + Room L102 = new Room(luxury, new RoomName("102", "L"), 3); + Room C103 = new Room(cheap, new RoomName("103", "C"), 4); + Room C104 = new Room(cheap, new RoomName("104", "C"), 5); + Room N105 = new Room(niceOne, new RoomName("105", "N"), 2); Collection<Room> rooms = Arrays.asList(L100, L101, L102, C103, C104, N105); templatingContext.put("rooms", rooms); } }
true
true
public void process(Parameters parameters, TemplatingContext templatingContext, MVCContext mvcContext, HttpContext httpContext, I18nContext i18nContext) throws ProcessingException { Collection<RoomType> roomTypes = new ArrayList<>(); // TODO fetch room types from repository RoomType luxury = new RoomType("luxury"); RoomType cheap = new RoomType("cheap"); RoomType niceOne = new RoomType("nice one"); roomTypes.addAll(Arrays.asList(luxury, cheap, niceOne)); templatingContext.put("roomTypes", roomTypes); // TODO fetch rooms from repository // TODO add comparable to Room and compare it by room names // TODO pass Set (so its ordered) to templatingContext instead of collection Room L100 = new Room(luxury, new RoomName("100", "L")); Room L101 = new Room(luxury, new RoomName("101", "L")); Room L102 = new Room(luxury, new RoomName("102", "L")); Room C103 = new Room(cheap, new RoomName("103", "C")); Room C104 = new Room(cheap, new RoomName("104", "C")); Room N105 = new Room(niceOne, new RoomName("105", "N")); Collection<Room> rooms = Arrays.asList(L100, L101, L102, C103, C104, N105); templatingContext.put("rooms", rooms); }
public void process(Parameters parameters, TemplatingContext templatingContext, MVCContext mvcContext, HttpContext httpContext, I18nContext i18nContext) throws ProcessingException { Collection<RoomType> roomTypes = new ArrayList<>(); // TODO fetch room types from repository RoomType luxury = new RoomType("luxury"); RoomType cheap = new RoomType("cheap"); RoomType niceOne = new RoomType("nice one"); roomTypes.addAll(Arrays.asList(luxury, cheap, niceOne)); templatingContext.put("roomTypes", roomTypes); // TODO fetch rooms from repository // TODO add comparable to Room and compare it by room names // TODO pass Set (so its ordered) to templatingContext instead of collection Room L100 = new Room(luxury, new RoomName("100", "L"), 1); Room L101 = new Room(luxury, new RoomName("101", "L"), 0); Room L102 = new Room(luxury, new RoomName("102", "L"), 3); Room C103 = new Room(cheap, new RoomName("103", "C"), 4); Room C104 = new Room(cheap, new RoomName("104", "C"), 5); Room N105 = new Room(niceOne, new RoomName("105", "N"), 2); Collection<Room> rooms = Arrays.asList(L100, L101, L102, C103, C104, N105); templatingContext.put("rooms", rooms); }
diff --git a/src/me/Miny/Paypassage/config/ConfigurationHandler.java b/src/me/Miny/Paypassage/config/ConfigurationHandler.java index 9dab223..0c9cb9d 100644 --- a/src/me/Miny/Paypassage/config/ConfigurationHandler.java +++ b/src/me/Miny/Paypassage/config/ConfigurationHandler.java @@ -1,272 +1,272 @@ package me.Miny.Paypassage.config; import java.io.File; import java.io.IOException; import me.Miny.Paypassage.Paypassage; import me.Miny.Paypassage.logger.LoggerUtility; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; /** * * @author ibhh */ public class ConfigurationHandler { private YamlConfiguration language_config; private Paypassage plugin; /** * Creates a new ConfigurationHandler * * @param plugin * Needed for saving configs */ public ConfigurationHandler(Paypassage plugin) { this.plugin = plugin; } /** * Returns the current language configuration * * @return YamlConfiguration */ public YamlConfiguration getLanguage_config() { return language_config; } /** * * @return plugin.getConifg(); */ public FileConfiguration getConfig() { return plugin.getConfig(); } /** * Called on start * * @return true if config was successfully loaded, false if it failed; */ public boolean onStart() { // loading main config try { plugin.getConfig().options().copyDefaults(true); plugin.saveConfig(); plugin.reloadConfig(); plugin.getLoggerUtility().log("Config loaded", LoggerUtility.Level.DEBUG); } catch (Exception e) { plugin.getLoggerUtility().log("Cannot create config!", LoggerUtility.Level.ERROR); e.printStackTrace(); plugin.onDisable(); } createLanguageConfig(); return true; } /** * Creates the language config and added defaults */ private void createLanguageConfig() { for (int i = 0; i < 2; i++) { String a = ""; if (i == 0) { a = "de"; } else { a = "en"; } File folder = new File(plugin.getDataFolder() + File.separator); folder.mkdirs(); File configl = new File(plugin.getDataFolder() + File.separator + "language_" + a + ".yml"); if (!configl.exists()) { try { configl.createNewFile(); } catch (IOException ex) { plugin.getLoggerUtility().log("Couldnt create new config file!", LoggerUtility.Level.ERROR); } } language_config = YamlConfiguration.loadConfiguration(configl); if (i == 0) { // permission output language_config.addDefault("permission.error", "Wir haben ein Problem! Dies darfst Du nicht machen!"); // privacy output language_config.addDefault("privacy.notification.1", "Dieses plugin speichert nutzerbezogene Daten in eine Datei"); language_config.addDefault("privacy.notification.2", "\"/pp allowtracking\" um den Plugin dies zu erlauben"); language_config.addDefault("privacy.notification.3", "\"/pp denytracking\" um deine Daten zu anonymisieren"); language_config.addDefault("privacy.notification.denied", "Das Plugin speichert nun keine nutzerbezogene Daten mehr"); language_config.addDefault("privacy.notification.allowed", "Das Plugin speichert deine Daten, wende Dich an einen Admin um diese z.B. loeschen zu lassen"); language_config.addDefault("creation.sign.notification1", "Bitte mache einen rechtsklick auf das Schild"); language_config.addDefault("creation.sign.notification2", "Schild akzeptiert"); language_config.addDefault("creation.sign.notification3", "Du hast bereits ein Schild ausgewaehlt."); language_config.addDefault("creation.sign.notification4", "Bitte gehe zum Zielpunkt und mache \"pp setdestination\""); language_config.addDefault("creation.sign.notification5", "Zielpunkt gesetzt. Waehle nun einen Preis mit /pp setprice [Preis]"); language_config.addDefault("creation.sign.notification.cancel", "Erstellung eines PP Schildes abgebrochen!"); language_config.addDefault("creation.sign.notification.success", "Erstellung eines PP Schildes abgeschlossen."); language_config.addDefault("interact.sign.notification.confirm", "Willst Du dich f�r %f [Geldeinheit] teleportieren? Bestaetige mit /pp confirm"); language_config.addDefault("interact.sign.notification.success", "Teleportiert."); language_config.addDefault("interact.sign.notification.error.nomoney", "Du hast nicht genug [Geldeinheit]!"); language_config.addDefault("creation.sign.nopaypassagesign", "Du musst ein \"[Paypassage]\" Schild auswaehlen"); // reload command language_config.addDefault("commands.reload.name", "reload"); language_config.addDefault("commands.reload.permission", "Paypassage.reload"); language_config.addDefault("commands.reload.description", "Laedt das Plugin neu"); language_config.addDefault("commands.reload.usage", "/pp reload"); language_config.addDefault("commands.help.name", "help"); language_config.addDefault("commands.help.permission", "Paypassage.help"); language_config.addDefault("commands.help.description", "Zeigt die Hilfe an"); language_config.addDefault("commands.help.usage", "/pp help"); language_config.addDefault("commands.version.name", "version"); language_config.addDefault("commands.version.permission", "Paypassage.version"); language_config.addDefault("commands.version.description", "Zeigt die Version an"); language_config.addDefault("commands.version.usage", "/pp help"); // privacy commands language_config.addDefault("commands.denytracking.name", "denytracking"); language_config.addDefault("commands.denytracking.permission", "Paypassage.user"); language_config.addDefault("commands.denytracking.description", "Zwingt das Plugin deine Daten zu anonymisieren"); language_config.addDefault("commands.denytracking.usage", "/pp denytracking"); language_config.addDefault("commands.allowtracking.name", "allowtracking"); language_config.addDefault("commands.allowtracking.permission", "Paypassage.user"); language_config.addDefault("commands.allowtracking.description", "Erlaubt dem Plugin deine Daten zu speichern"); language_config.addDefault("commands.allowtracking.usage", "/pp allowtracking"); //PP Sign commands // create command language_config.addDefault("commands.create.name", "create"); language_config.addDefault("commands.create.permission", "Paypassage.create"); language_config.addDefault("commands.create.description", "Erstellt ein neues Paypassage Schild"); - language_config.addDefault("commands.create.usage", "/pp create"); + language_config.addDefault("commands.create.usage", "/pp create [name]"); language_config.addDefault("commands.confirm.name", "confirm"); language_config.addDefault("commands.confirm.permission", "Paypassage.teleport"); language_config.addDefault("commands.confirm.description", "Bestaetigt einen Teleport"); language_config.addDefault("commands.confirm.usage", "/pp confirm"); // cancel command language_config.addDefault("commands.cancel.name", "cancel"); language_config.addDefault("commands.cancel.permission", "Paypassage.create"); language_config.addDefault("commands.cancel.description", "Bricht das erstellen eines PP Schildes ab."); language_config.addDefault("commands.cancel.usage", "/pp cancel"); //setdestination command language_config.addDefault("commands.setdestination.name", "setdestination"); language_config.addDefault("commands.setdestination.permission", "Paypassage.create"); language_config.addDefault("commands.setdestination.description", "Setz Zielpunkt des Teleports."); language_config.addDefault("commands.setdestination.usage", "/pp setdestination"); language_config.addDefault("commands.setprice.name", "setprice"); language_config.addDefault("commands.setprice.permission", "Paypassage.create"); language_config.addDefault("commands.setprice.description", "Setzt die Kosten des Schildes"); - language_config.addDefault("commands.setprice.usage", "/pp setprice"); + language_config.addDefault("commands.setprice.usage", "/pp setprice [price]"); } else { language_config.addDefault("permission.error", "we have a problem! You musnt do this!"); language_config.addDefault("privacy.notification.1", "this plugin saves your interact events to a log"); language_config.addDefault("privacy.notification.2", "\"/pp allowtracking\" to allow the plugin to save your data"); language_config.addDefault("privacy.notification.3", "\"/pp denytracking\" to anonymise your data"); language_config.addDefault("privacy.notification.denied", "The plugin anonymises your data now"); language_config.addDefault("privacy.notification.allowed", "The plugin saves your data now, to delete the data, please tell an admin"); language_config.addDefault("creation.sign.notification1", "Please do a right-click on a sign"); language_config.addDefault("creation.sign.notification2", "Sign accepted"); language_config.addDefault("creation.sign.notification3", "You have already choosen a sign."); language_config.addDefault("creation.sign.notification4", "Please go to the destination and do \"/pp setdestination\""); language_config.addDefault("creation.sign.notification5", "Destination set! Please choose the price with /pp setprice [price]"); language_config.addDefault("creation.sign.notification.cancel", "Canceled creation off a PP sign!"); language_config.addDefault("creation.sign.notification.success", "PP sign created."); language_config.addDefault("interact.sign.notification.confirm", "Do you want to teleport you for %f [Money]? Please execute /pp confirm"); language_config.addDefault("interact.sign.notification.success", "Teleported!"); language_config.addDefault("interact.sign.notification.error.nomoney", "You haven't got enough money to use this sign!"); language_config.addDefault("creation.sign.nopaypassagesign", "You must choose a \"[Paypassage]\" sign!"); // reload command language_config.addDefault("commands.reload.name", "reload"); language_config.addDefault("commands.reload.permission", "Paypassage.reload"); language_config.addDefault("commands.reload.description", "Reloads the plugin"); language_config.addDefault("commands.reload.usage", "/pp reload"); language_config.addDefault("commands.help.name", "help"); language_config.addDefault("commands.help.permission", "Paypassage.help"); language_config.addDefault("commands.help.description", "Shows help"); language_config.addDefault("commands.help.usage", "/pp help"); language_config.addDefault("commands.version.name", "version"); language_config.addDefault("commands.version.permission", "Paypassage.version"); language_config.addDefault("commands.version.description", "Shows current version"); language_config.addDefault("commands.version.usage", "/pp help"); language_config.addDefault("commands.denytracking.name", "denytracking"); language_config.addDefault("commands.denytracking.permission", "Paypassage.user"); language_config.addDefault("commands.denytracking.description", "forces the plugin to anonymise your data"); language_config.addDefault("commands.denytracking.usage", "/pp denytracking"); language_config.addDefault("commands.allowtracking.name", "allowtracking"); language_config.addDefault("commands.allowtracking.permission", "Paypassage.user"); language_config.addDefault("commands.allowtracking.description", "Allows the plugin to save userdata"); language_config.addDefault("commands.allowtracking.usage", "/pp allowtracking"); language_config.addDefault("commands.create.name", "create"); language_config.addDefault("commands.create.permission", "Paypassage.create"); language_config.addDefault("commands.create.description", "Creates a new Paypassage sign"); - language_config.addDefault("commands.create.usage", "/pp create"); + language_config.addDefault("commands.create.usage", "/pp create [name]"); language_config.addDefault("commands.confirm.name", "confirm"); language_config.addDefault("commands.confirm.permission", "Paypassage.teleport"); language_config.addDefault("commands.confirm.description", "Confirms a teleport"); language_config.addDefault("commands.confirm.usage", "/pp confirm"); // cancel command language_config.addDefault("commands.cancel.name", "cancel"); language_config.addDefault("commands.cancel.permission", "Paypassage.create"); language_config.addDefault("commands.cancel.description", "Stops the creating of a PP sign."); language_config.addDefault("commands.cancel.usage", "/pp cancel"); language_config.addDefault("commands.setdestination.name", "setdestination"); language_config.addDefault("commands.setdestination.permission", "Paypassage.create"); language_config.addDefault("commands.setdestination.description", "Sets destination of a Paypassage sign"); language_config.addDefault("commands.setdestination.usage", "/pp setdestination"); language_config.addDefault("commands.setprice.name", "setprice"); language_config.addDefault("commands.setprice.permission", "Paypassage.create"); language_config.addDefault("commands.setprice.description", "Sets the price of the sign"); - language_config.addDefault("commands.setprice.usage", "/pp setprice"); + language_config.addDefault("commands.setprice.usage", "/pp setprice [price]"); } try { language_config.options().copyDefaults(true); language_config.save(configl); } catch (IOException ex) { ex.printStackTrace(); plugin.getLoggerUtility().log("Couldnt save language config!", LoggerUtility.Level.ERROR); } } File configl = new File(plugin.getDataFolder() + File.separator + "language_" + plugin.getConfig().getString("language") + ".yml"); try { language_config = YamlConfiguration.loadConfiguration(configl); } catch (Exception e) { e.printStackTrace(); plugin.getLoggerUtility().log("Couldnt load language config!", LoggerUtility.Level.ERROR); plugin.getConfig().set("language", "en"); plugin.saveConfig(); plugin.onDisable(); return; } plugin.getLoggerUtility().log("language config loaded", LoggerUtility.Level.DEBUG); } }
false
true
private void createLanguageConfig() { for (int i = 0; i < 2; i++) { String a = ""; if (i == 0) { a = "de"; } else { a = "en"; } File folder = new File(plugin.getDataFolder() + File.separator); folder.mkdirs(); File configl = new File(plugin.getDataFolder() + File.separator + "language_" + a + ".yml"); if (!configl.exists()) { try { configl.createNewFile(); } catch (IOException ex) { plugin.getLoggerUtility().log("Couldnt create new config file!", LoggerUtility.Level.ERROR); } } language_config = YamlConfiguration.loadConfiguration(configl); if (i == 0) { // permission output language_config.addDefault("permission.error", "Wir haben ein Problem! Dies darfst Du nicht machen!"); // privacy output language_config.addDefault("privacy.notification.1", "Dieses plugin speichert nutzerbezogene Daten in eine Datei"); language_config.addDefault("privacy.notification.2", "\"/pp allowtracking\" um den Plugin dies zu erlauben"); language_config.addDefault("privacy.notification.3", "\"/pp denytracking\" um deine Daten zu anonymisieren"); language_config.addDefault("privacy.notification.denied", "Das Plugin speichert nun keine nutzerbezogene Daten mehr"); language_config.addDefault("privacy.notification.allowed", "Das Plugin speichert deine Daten, wende Dich an einen Admin um diese z.B. loeschen zu lassen"); language_config.addDefault("creation.sign.notification1", "Bitte mache einen rechtsklick auf das Schild"); language_config.addDefault("creation.sign.notification2", "Schild akzeptiert"); language_config.addDefault("creation.sign.notification3", "Du hast bereits ein Schild ausgewaehlt."); language_config.addDefault("creation.sign.notification4", "Bitte gehe zum Zielpunkt und mache \"pp setdestination\""); language_config.addDefault("creation.sign.notification5", "Zielpunkt gesetzt. Waehle nun einen Preis mit /pp setprice [Preis]"); language_config.addDefault("creation.sign.notification.cancel", "Erstellung eines PP Schildes abgebrochen!"); language_config.addDefault("creation.sign.notification.success", "Erstellung eines PP Schildes abgeschlossen."); language_config.addDefault("interact.sign.notification.confirm", "Willst Du dich f�r %f [Geldeinheit] teleportieren? Bestaetige mit /pp confirm"); language_config.addDefault("interact.sign.notification.success", "Teleportiert."); language_config.addDefault("interact.sign.notification.error.nomoney", "Du hast nicht genug [Geldeinheit]!"); language_config.addDefault("creation.sign.nopaypassagesign", "Du musst ein \"[Paypassage]\" Schild auswaehlen"); // reload command language_config.addDefault("commands.reload.name", "reload"); language_config.addDefault("commands.reload.permission", "Paypassage.reload"); language_config.addDefault("commands.reload.description", "Laedt das Plugin neu"); language_config.addDefault("commands.reload.usage", "/pp reload"); language_config.addDefault("commands.help.name", "help"); language_config.addDefault("commands.help.permission", "Paypassage.help"); language_config.addDefault("commands.help.description", "Zeigt die Hilfe an"); language_config.addDefault("commands.help.usage", "/pp help"); language_config.addDefault("commands.version.name", "version"); language_config.addDefault("commands.version.permission", "Paypassage.version"); language_config.addDefault("commands.version.description", "Zeigt die Version an"); language_config.addDefault("commands.version.usage", "/pp help"); // privacy commands language_config.addDefault("commands.denytracking.name", "denytracking"); language_config.addDefault("commands.denytracking.permission", "Paypassage.user"); language_config.addDefault("commands.denytracking.description", "Zwingt das Plugin deine Daten zu anonymisieren"); language_config.addDefault("commands.denytracking.usage", "/pp denytracking"); language_config.addDefault("commands.allowtracking.name", "allowtracking"); language_config.addDefault("commands.allowtracking.permission", "Paypassage.user"); language_config.addDefault("commands.allowtracking.description", "Erlaubt dem Plugin deine Daten zu speichern"); language_config.addDefault("commands.allowtracking.usage", "/pp allowtracking"); //PP Sign commands // create command language_config.addDefault("commands.create.name", "create"); language_config.addDefault("commands.create.permission", "Paypassage.create"); language_config.addDefault("commands.create.description", "Erstellt ein neues Paypassage Schild"); language_config.addDefault("commands.create.usage", "/pp create"); language_config.addDefault("commands.confirm.name", "confirm"); language_config.addDefault("commands.confirm.permission", "Paypassage.teleport"); language_config.addDefault("commands.confirm.description", "Bestaetigt einen Teleport"); language_config.addDefault("commands.confirm.usage", "/pp confirm"); // cancel command language_config.addDefault("commands.cancel.name", "cancel"); language_config.addDefault("commands.cancel.permission", "Paypassage.create"); language_config.addDefault("commands.cancel.description", "Bricht das erstellen eines PP Schildes ab."); language_config.addDefault("commands.cancel.usage", "/pp cancel"); //setdestination command language_config.addDefault("commands.setdestination.name", "setdestination"); language_config.addDefault("commands.setdestination.permission", "Paypassage.create"); language_config.addDefault("commands.setdestination.description", "Setz Zielpunkt des Teleports."); language_config.addDefault("commands.setdestination.usage", "/pp setdestination"); language_config.addDefault("commands.setprice.name", "setprice"); language_config.addDefault("commands.setprice.permission", "Paypassage.create"); language_config.addDefault("commands.setprice.description", "Setzt die Kosten des Schildes"); language_config.addDefault("commands.setprice.usage", "/pp setprice"); } else { language_config.addDefault("permission.error", "we have a problem! You musnt do this!"); language_config.addDefault("privacy.notification.1", "this plugin saves your interact events to a log"); language_config.addDefault("privacy.notification.2", "\"/pp allowtracking\" to allow the plugin to save your data"); language_config.addDefault("privacy.notification.3", "\"/pp denytracking\" to anonymise your data"); language_config.addDefault("privacy.notification.denied", "The plugin anonymises your data now"); language_config.addDefault("privacy.notification.allowed", "The plugin saves your data now, to delete the data, please tell an admin"); language_config.addDefault("creation.sign.notification1", "Please do a right-click on a sign"); language_config.addDefault("creation.sign.notification2", "Sign accepted"); language_config.addDefault("creation.sign.notification3", "You have already choosen a sign."); language_config.addDefault("creation.sign.notification4", "Please go to the destination and do \"/pp setdestination\""); language_config.addDefault("creation.sign.notification5", "Destination set! Please choose the price with /pp setprice [price]"); language_config.addDefault("creation.sign.notification.cancel", "Canceled creation off a PP sign!"); language_config.addDefault("creation.sign.notification.success", "PP sign created."); language_config.addDefault("interact.sign.notification.confirm", "Do you want to teleport you for %f [Money]? Please execute /pp confirm"); language_config.addDefault("interact.sign.notification.success", "Teleported!"); language_config.addDefault("interact.sign.notification.error.nomoney", "You haven't got enough money to use this sign!"); language_config.addDefault("creation.sign.nopaypassagesign", "You must choose a \"[Paypassage]\" sign!"); // reload command language_config.addDefault("commands.reload.name", "reload"); language_config.addDefault("commands.reload.permission", "Paypassage.reload"); language_config.addDefault("commands.reload.description", "Reloads the plugin"); language_config.addDefault("commands.reload.usage", "/pp reload"); language_config.addDefault("commands.help.name", "help"); language_config.addDefault("commands.help.permission", "Paypassage.help"); language_config.addDefault("commands.help.description", "Shows help"); language_config.addDefault("commands.help.usage", "/pp help"); language_config.addDefault("commands.version.name", "version"); language_config.addDefault("commands.version.permission", "Paypassage.version"); language_config.addDefault("commands.version.description", "Shows current version"); language_config.addDefault("commands.version.usage", "/pp help"); language_config.addDefault("commands.denytracking.name", "denytracking"); language_config.addDefault("commands.denytracking.permission", "Paypassage.user"); language_config.addDefault("commands.denytracking.description", "forces the plugin to anonymise your data"); language_config.addDefault("commands.denytracking.usage", "/pp denytracking"); language_config.addDefault("commands.allowtracking.name", "allowtracking"); language_config.addDefault("commands.allowtracking.permission", "Paypassage.user"); language_config.addDefault("commands.allowtracking.description", "Allows the plugin to save userdata"); language_config.addDefault("commands.allowtracking.usage", "/pp allowtracking"); language_config.addDefault("commands.create.name", "create"); language_config.addDefault("commands.create.permission", "Paypassage.create"); language_config.addDefault("commands.create.description", "Creates a new Paypassage sign"); language_config.addDefault("commands.create.usage", "/pp create"); language_config.addDefault("commands.confirm.name", "confirm"); language_config.addDefault("commands.confirm.permission", "Paypassage.teleport"); language_config.addDefault("commands.confirm.description", "Confirms a teleport"); language_config.addDefault("commands.confirm.usage", "/pp confirm"); // cancel command language_config.addDefault("commands.cancel.name", "cancel"); language_config.addDefault("commands.cancel.permission", "Paypassage.create"); language_config.addDefault("commands.cancel.description", "Stops the creating of a PP sign."); language_config.addDefault("commands.cancel.usage", "/pp cancel"); language_config.addDefault("commands.setdestination.name", "setdestination"); language_config.addDefault("commands.setdestination.permission", "Paypassage.create"); language_config.addDefault("commands.setdestination.description", "Sets destination of a Paypassage sign"); language_config.addDefault("commands.setdestination.usage", "/pp setdestination"); language_config.addDefault("commands.setprice.name", "setprice"); language_config.addDefault("commands.setprice.permission", "Paypassage.create"); language_config.addDefault("commands.setprice.description", "Sets the price of the sign"); language_config.addDefault("commands.setprice.usage", "/pp setprice"); } try { language_config.options().copyDefaults(true); language_config.save(configl); } catch (IOException ex) { ex.printStackTrace(); plugin.getLoggerUtility().log("Couldnt save language config!", LoggerUtility.Level.ERROR); } } File configl = new File(plugin.getDataFolder() + File.separator + "language_" + plugin.getConfig().getString("language") + ".yml"); try { language_config = YamlConfiguration.loadConfiguration(configl); } catch (Exception e) { e.printStackTrace(); plugin.getLoggerUtility().log("Couldnt load language config!", LoggerUtility.Level.ERROR); plugin.getConfig().set("language", "en"); plugin.saveConfig(); plugin.onDisable(); return; } plugin.getLoggerUtility().log("language config loaded", LoggerUtility.Level.DEBUG); }
private void createLanguageConfig() { for (int i = 0; i < 2; i++) { String a = ""; if (i == 0) { a = "de"; } else { a = "en"; } File folder = new File(plugin.getDataFolder() + File.separator); folder.mkdirs(); File configl = new File(plugin.getDataFolder() + File.separator + "language_" + a + ".yml"); if (!configl.exists()) { try { configl.createNewFile(); } catch (IOException ex) { plugin.getLoggerUtility().log("Couldnt create new config file!", LoggerUtility.Level.ERROR); } } language_config = YamlConfiguration.loadConfiguration(configl); if (i == 0) { // permission output language_config.addDefault("permission.error", "Wir haben ein Problem! Dies darfst Du nicht machen!"); // privacy output language_config.addDefault("privacy.notification.1", "Dieses plugin speichert nutzerbezogene Daten in eine Datei"); language_config.addDefault("privacy.notification.2", "\"/pp allowtracking\" um den Plugin dies zu erlauben"); language_config.addDefault("privacy.notification.3", "\"/pp denytracking\" um deine Daten zu anonymisieren"); language_config.addDefault("privacy.notification.denied", "Das Plugin speichert nun keine nutzerbezogene Daten mehr"); language_config.addDefault("privacy.notification.allowed", "Das Plugin speichert deine Daten, wende Dich an einen Admin um diese z.B. loeschen zu lassen"); language_config.addDefault("creation.sign.notification1", "Bitte mache einen rechtsklick auf das Schild"); language_config.addDefault("creation.sign.notification2", "Schild akzeptiert"); language_config.addDefault("creation.sign.notification3", "Du hast bereits ein Schild ausgewaehlt."); language_config.addDefault("creation.sign.notification4", "Bitte gehe zum Zielpunkt und mache \"pp setdestination\""); language_config.addDefault("creation.sign.notification5", "Zielpunkt gesetzt. Waehle nun einen Preis mit /pp setprice [Preis]"); language_config.addDefault("creation.sign.notification.cancel", "Erstellung eines PP Schildes abgebrochen!"); language_config.addDefault("creation.sign.notification.success", "Erstellung eines PP Schildes abgeschlossen."); language_config.addDefault("interact.sign.notification.confirm", "Willst Du dich f�r %f [Geldeinheit] teleportieren? Bestaetige mit /pp confirm"); language_config.addDefault("interact.sign.notification.success", "Teleportiert."); language_config.addDefault("interact.sign.notification.error.nomoney", "Du hast nicht genug [Geldeinheit]!"); language_config.addDefault("creation.sign.nopaypassagesign", "Du musst ein \"[Paypassage]\" Schild auswaehlen"); // reload command language_config.addDefault("commands.reload.name", "reload"); language_config.addDefault("commands.reload.permission", "Paypassage.reload"); language_config.addDefault("commands.reload.description", "Laedt das Plugin neu"); language_config.addDefault("commands.reload.usage", "/pp reload"); language_config.addDefault("commands.help.name", "help"); language_config.addDefault("commands.help.permission", "Paypassage.help"); language_config.addDefault("commands.help.description", "Zeigt die Hilfe an"); language_config.addDefault("commands.help.usage", "/pp help"); language_config.addDefault("commands.version.name", "version"); language_config.addDefault("commands.version.permission", "Paypassage.version"); language_config.addDefault("commands.version.description", "Zeigt die Version an"); language_config.addDefault("commands.version.usage", "/pp help"); // privacy commands language_config.addDefault("commands.denytracking.name", "denytracking"); language_config.addDefault("commands.denytracking.permission", "Paypassage.user"); language_config.addDefault("commands.denytracking.description", "Zwingt das Plugin deine Daten zu anonymisieren"); language_config.addDefault("commands.denytracking.usage", "/pp denytracking"); language_config.addDefault("commands.allowtracking.name", "allowtracking"); language_config.addDefault("commands.allowtracking.permission", "Paypassage.user"); language_config.addDefault("commands.allowtracking.description", "Erlaubt dem Plugin deine Daten zu speichern"); language_config.addDefault("commands.allowtracking.usage", "/pp allowtracking"); //PP Sign commands // create command language_config.addDefault("commands.create.name", "create"); language_config.addDefault("commands.create.permission", "Paypassage.create"); language_config.addDefault("commands.create.description", "Erstellt ein neues Paypassage Schild"); language_config.addDefault("commands.create.usage", "/pp create [name]"); language_config.addDefault("commands.confirm.name", "confirm"); language_config.addDefault("commands.confirm.permission", "Paypassage.teleport"); language_config.addDefault("commands.confirm.description", "Bestaetigt einen Teleport"); language_config.addDefault("commands.confirm.usage", "/pp confirm"); // cancel command language_config.addDefault("commands.cancel.name", "cancel"); language_config.addDefault("commands.cancel.permission", "Paypassage.create"); language_config.addDefault("commands.cancel.description", "Bricht das erstellen eines PP Schildes ab."); language_config.addDefault("commands.cancel.usage", "/pp cancel"); //setdestination command language_config.addDefault("commands.setdestination.name", "setdestination"); language_config.addDefault("commands.setdestination.permission", "Paypassage.create"); language_config.addDefault("commands.setdestination.description", "Setz Zielpunkt des Teleports."); language_config.addDefault("commands.setdestination.usage", "/pp setdestination"); language_config.addDefault("commands.setprice.name", "setprice"); language_config.addDefault("commands.setprice.permission", "Paypassage.create"); language_config.addDefault("commands.setprice.description", "Setzt die Kosten des Schildes"); language_config.addDefault("commands.setprice.usage", "/pp setprice [price]"); } else { language_config.addDefault("permission.error", "we have a problem! You musnt do this!"); language_config.addDefault("privacy.notification.1", "this plugin saves your interact events to a log"); language_config.addDefault("privacy.notification.2", "\"/pp allowtracking\" to allow the plugin to save your data"); language_config.addDefault("privacy.notification.3", "\"/pp denytracking\" to anonymise your data"); language_config.addDefault("privacy.notification.denied", "The plugin anonymises your data now"); language_config.addDefault("privacy.notification.allowed", "The plugin saves your data now, to delete the data, please tell an admin"); language_config.addDefault("creation.sign.notification1", "Please do a right-click on a sign"); language_config.addDefault("creation.sign.notification2", "Sign accepted"); language_config.addDefault("creation.sign.notification3", "You have already choosen a sign."); language_config.addDefault("creation.sign.notification4", "Please go to the destination and do \"/pp setdestination\""); language_config.addDefault("creation.sign.notification5", "Destination set! Please choose the price with /pp setprice [price]"); language_config.addDefault("creation.sign.notification.cancel", "Canceled creation off a PP sign!"); language_config.addDefault("creation.sign.notification.success", "PP sign created."); language_config.addDefault("interact.sign.notification.confirm", "Do you want to teleport you for %f [Money]? Please execute /pp confirm"); language_config.addDefault("interact.sign.notification.success", "Teleported!"); language_config.addDefault("interact.sign.notification.error.nomoney", "You haven't got enough money to use this sign!"); language_config.addDefault("creation.sign.nopaypassagesign", "You must choose a \"[Paypassage]\" sign!"); // reload command language_config.addDefault("commands.reload.name", "reload"); language_config.addDefault("commands.reload.permission", "Paypassage.reload"); language_config.addDefault("commands.reload.description", "Reloads the plugin"); language_config.addDefault("commands.reload.usage", "/pp reload"); language_config.addDefault("commands.help.name", "help"); language_config.addDefault("commands.help.permission", "Paypassage.help"); language_config.addDefault("commands.help.description", "Shows help"); language_config.addDefault("commands.help.usage", "/pp help"); language_config.addDefault("commands.version.name", "version"); language_config.addDefault("commands.version.permission", "Paypassage.version"); language_config.addDefault("commands.version.description", "Shows current version"); language_config.addDefault("commands.version.usage", "/pp help"); language_config.addDefault("commands.denytracking.name", "denytracking"); language_config.addDefault("commands.denytracking.permission", "Paypassage.user"); language_config.addDefault("commands.denytracking.description", "forces the plugin to anonymise your data"); language_config.addDefault("commands.denytracking.usage", "/pp denytracking"); language_config.addDefault("commands.allowtracking.name", "allowtracking"); language_config.addDefault("commands.allowtracking.permission", "Paypassage.user"); language_config.addDefault("commands.allowtracking.description", "Allows the plugin to save userdata"); language_config.addDefault("commands.allowtracking.usage", "/pp allowtracking"); language_config.addDefault("commands.create.name", "create"); language_config.addDefault("commands.create.permission", "Paypassage.create"); language_config.addDefault("commands.create.description", "Creates a new Paypassage sign"); language_config.addDefault("commands.create.usage", "/pp create [name]"); language_config.addDefault("commands.confirm.name", "confirm"); language_config.addDefault("commands.confirm.permission", "Paypassage.teleport"); language_config.addDefault("commands.confirm.description", "Confirms a teleport"); language_config.addDefault("commands.confirm.usage", "/pp confirm"); // cancel command language_config.addDefault("commands.cancel.name", "cancel"); language_config.addDefault("commands.cancel.permission", "Paypassage.create"); language_config.addDefault("commands.cancel.description", "Stops the creating of a PP sign."); language_config.addDefault("commands.cancel.usage", "/pp cancel"); language_config.addDefault("commands.setdestination.name", "setdestination"); language_config.addDefault("commands.setdestination.permission", "Paypassage.create"); language_config.addDefault("commands.setdestination.description", "Sets destination of a Paypassage sign"); language_config.addDefault("commands.setdestination.usage", "/pp setdestination"); language_config.addDefault("commands.setprice.name", "setprice"); language_config.addDefault("commands.setprice.permission", "Paypassage.create"); language_config.addDefault("commands.setprice.description", "Sets the price of the sign"); language_config.addDefault("commands.setprice.usage", "/pp setprice [price]"); } try { language_config.options().copyDefaults(true); language_config.save(configl); } catch (IOException ex) { ex.printStackTrace(); plugin.getLoggerUtility().log("Couldnt save language config!", LoggerUtility.Level.ERROR); } } File configl = new File(plugin.getDataFolder() + File.separator + "language_" + plugin.getConfig().getString("language") + ".yml"); try { language_config = YamlConfiguration.loadConfiguration(configl); } catch (Exception e) { e.printStackTrace(); plugin.getLoggerUtility().log("Couldnt load language config!", LoggerUtility.Level.ERROR); plugin.getConfig().set("language", "en"); plugin.saveConfig(); plugin.onDisable(); return; } plugin.getLoggerUtility().log("language config loaded", LoggerUtility.Level.DEBUG); }
diff --git a/clueGame/HumanPlayer.java b/clueGame/HumanPlayer.java index 195b1fa..a57977f 100644 --- a/clueGame/HumanPlayer.java +++ b/clueGame/HumanPlayer.java @@ -1,9 +1,9 @@ package clueGame; public class HumanPlayer extends Player { public HumanPlayer(String name, int startX, int startY) { - super(name, startX, startX); + super(name, startX, startY); } }
true
true
public HumanPlayer(String name, int startX, int startY) { super(name, startX, startX); }
public HumanPlayer(String name, int startX, int startY) { super(name, startX, startY); }
diff --git a/src/org/drftpd/slave/FileRemoteFile.java b/src/org/drftpd/slave/FileRemoteFile.java index 7fff4e76..23c5238b 100644 --- a/src/org/drftpd/slave/FileRemoteFile.java +++ b/src/org/drftpd/slave/FileRemoteFile.java @@ -1,389 +1,394 @@ /* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD 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. * * DrFTPD 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 DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.drftpd.slave; import org.apache.log4j.Logger; import org.drftpd.remotefile.AbstractLightRemoteFile; import org.drftpd.remotefile.LightRemoteFileInterface; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; /** * A wrapper for java.io.File to the net.sf.drftpd.RemoteFile structure. * * @author mog * @version $Id$ */ public class FileRemoteFile extends AbstractLightRemoteFile { private static final Logger logger = Logger.getLogger(FileRemoteFile.class); Hashtable _filefiles; String _path; RootCollection _roots; private boolean isDirectory; private boolean isFile; private long lastModified; private long length; public FileRemoteFile(RootCollection rootBasket) throws IOException { this(rootBasket, ""); } public FileRemoteFile(RootCollection roots, String path) throws IOException { _path = path; _roots = roots; List files = roots.getMultipleFiles(path); File firstFile; // sanity checking { { Iterator iter = files.iterator(); firstFile = (File) iter.next(); isFile = firstFile.isFile(); isDirectory = firstFile.isDirectory(); if ((isFile && isDirectory) || (!isFile && !isDirectory)) { throw new IOException("isFile && isDirectory: " + path); } checkSymlink(firstFile); while (iter.hasNext()) { File file = (File) iter.next(); checkSymlink(file); if ((isFile != file.isFile()) || (isDirectory != file.isDirectory())) { throw new IOException( "roots are out of sync, file&dir mix: " + path); } } } if (isFile && (files.size() > 1)) { ArrayList checksummers = new ArrayList(files.size()); for (Iterator iter = files.iterator(); iter.hasNext();) { File file = (File) iter.next(); Checksummer checksummer = new Checksummer(file); checksummer.start(); checksummers.add(checksummer); } while (true) { boolean waiting = false; for (Iterator iter = checksummers.iterator(); iter.hasNext();) { Checksummer cs = (Checksummer) iter.next(); if (cs.isAlive()) { waiting = true; try { synchronized (cs) { - cs.wait(); + cs.wait(10000); // wait a max of 10 seconds + // race condition could + // occur between above + // isAlive() statement and + // when the Checksummer + // finishes } } catch (InterruptedException e) { } break; } } if (!waiting) { break; } } Iterator iter = checksummers.iterator(); long checksum = ((Checksummer) iter.next()).getCheckSum() .getValue(); for (; iter.hasNext();) { Checksummer cs = (Checksummer) iter.next(); if (cs.getCheckSum().getValue() != checksum) { throw new IOException( "File collisions with different checksums - " + files); } } iter = files.iterator(); iter.next(); for (; iter.hasNext();) { File file = (File) iter.next(); file.delete(); logger.info("Deleted colliding and identical file: " + file.getPath()); iter.remove(); } } } // end sanity checking if (isDirectory) { length = 0; } else { length = firstFile.length(); } lastModified = firstFile.lastModified(); } public static void checkSymlink(File file) throws IOException { if (!file.getCanonicalPath().equalsIgnoreCase(file.getAbsolutePath())) { throw new InvalidDirectoryException("Not following symlink: " + file.getAbsolutePath()); } } /** * @return true if directory contained no files and is now deleted, false * otherwise. * @throws IOException */ private static boolean isEmpty(File dir) throws IOException { File[] listfiles = dir.listFiles(); if (listfiles == null) { throw new RuntimeException("Not a directory or IO error: " + dir); } for (int i = 0; i < listfiles.length; i++) { File file = listfiles[i]; if (file.isFile()) { return false; } } for (int i = 0; i < listfiles.length; i++) { File file = listfiles[i]; // parent directory not empty if (!isEmpty(file)) { return false; } } if (!dir.delete()) { throw new IOException("Permission denied deleting " + dir.getPath()); } return true; } private void buildFileFiles() throws IOException { if (_filefiles != null) { return; } _filefiles = new Hashtable(); if (!isDirectory()) { throw new IllegalArgumentException( "listFiles() called on !isDirectory()"); } for (Iterator iter = _roots.iterator(); iter.hasNext();) { Root root = (Root) iter.next(); File file = new File(root.getPath() + "/" + _path); if (!file.exists()) { continue; } if (!file.isDirectory()) { throw new RuntimeException(file.getPath() + " is not a directory, attempt to getFiles() on it"); } if (!file.canRead()) { throw new RuntimeException("Cannot read: " + file); } File[] tmpFiles = file.listFiles(); //returns null if not a dir, blah! if (tmpFiles == null) { throw new NullPointerException("list() on " + file + " returned null"); } for (int i = 0; i < tmpFiles.length; i++) { // try { if (tmpFiles[i].isDirectory() && isEmpty(tmpFiles[i])) { continue; } FileRemoteFile listfile = new FileRemoteFile(_roots, _path + File.separatorChar + tmpFiles[i].getName()); _filefiles.put(tmpFiles[i].getName(), listfile); // } catch (IOException e) { // e.printStackTrace(); // } } } if (!getName().equals("") && _filefiles.isEmpty()) { throw new RuntimeException("Empty (not-root) directory " + getPath() + ", shouldn't happen"); } } public Collection getFiles() { try { buildFileFiles(); return _filefiles.values(); } catch (IOException e) { logger.debug("RuntimeException here", new Throwable()); throw new RuntimeException(e); } } public String getGroupname() { return "drftpd"; } public String getName() { return _path.substring(_path.lastIndexOf(File.separatorChar) + 1); } public String getParent() { throw new UnsupportedOperationException(); //return file.getParent(); } public String getPath() { return _path; //throw new UnsupportedOperationException(); //return file.getPath(); } public Collection getSlaves() { return new ArrayList(); } public String getUsername() { return "drftpd"; } public boolean isDeleted() { return false; } public boolean isDirectory() { return isDirectory; } public boolean isFile() { return isFile; } public long lastModified() { return lastModified; } public long length() { return length; } /** * Returns an array of FileRemoteFile:s representing the contents of the * directory this FileRemoteFile represents. */ public LightRemoteFileInterface[] listFiles() { return (LightRemoteFileInterface[]) getFiles().toArray(new FileRemoteFile[0]); } public static class InvalidDirectoryException extends IOException { /** * Constructor for InvalidDirectoryException. */ public InvalidDirectoryException() { super(); } /** * Constructor for InvalidDirectoryException. * @param arg0 */ public InvalidDirectoryException(String arg0) { super(arg0); } } } class Checksummer extends Thread { private static final Logger logger = Logger.getLogger(Checksummer.class); private File _f; private CRC32 _checkSum; private IOException _e; public Checksummer(File f) { super("Checksummer - " + f.getPath()); _f = f; } /** * @return */ public CRC32 getCheckSum() { return _checkSum; } public void run() { synchronized (this) { _checkSum = new CRC32(); try { CheckedInputStream cis = new CheckedInputStream(new FileInputStream( _f), _checkSum); byte[] b = new byte[1024]; while (cis.read(b) > 0) ; } catch (IOException e) { logger.warn("", e); _e = e; } notifyAll(); } } }
true
true
public FileRemoteFile(RootCollection roots, String path) throws IOException { _path = path; _roots = roots; List files = roots.getMultipleFiles(path); File firstFile; // sanity checking { { Iterator iter = files.iterator(); firstFile = (File) iter.next(); isFile = firstFile.isFile(); isDirectory = firstFile.isDirectory(); if ((isFile && isDirectory) || (!isFile && !isDirectory)) { throw new IOException("isFile && isDirectory: " + path); } checkSymlink(firstFile); while (iter.hasNext()) { File file = (File) iter.next(); checkSymlink(file); if ((isFile != file.isFile()) || (isDirectory != file.isDirectory())) { throw new IOException( "roots are out of sync, file&dir mix: " + path); } } } if (isFile && (files.size() > 1)) { ArrayList checksummers = new ArrayList(files.size()); for (Iterator iter = files.iterator(); iter.hasNext();) { File file = (File) iter.next(); Checksummer checksummer = new Checksummer(file); checksummer.start(); checksummers.add(checksummer); } while (true) { boolean waiting = false; for (Iterator iter = checksummers.iterator(); iter.hasNext();) { Checksummer cs = (Checksummer) iter.next(); if (cs.isAlive()) { waiting = true; try { synchronized (cs) { cs.wait(); } } catch (InterruptedException e) { } break; } } if (!waiting) { break; } } Iterator iter = checksummers.iterator(); long checksum = ((Checksummer) iter.next()).getCheckSum() .getValue(); for (; iter.hasNext();) { Checksummer cs = (Checksummer) iter.next(); if (cs.getCheckSum().getValue() != checksum) { throw new IOException( "File collisions with different checksums - " + files); } } iter = files.iterator(); iter.next(); for (; iter.hasNext();) { File file = (File) iter.next(); file.delete(); logger.info("Deleted colliding and identical file: " + file.getPath()); iter.remove(); } } } // end sanity checking if (isDirectory) { length = 0; } else { length = firstFile.length(); } lastModified = firstFile.lastModified(); }
public FileRemoteFile(RootCollection roots, String path) throws IOException { _path = path; _roots = roots; List files = roots.getMultipleFiles(path); File firstFile; // sanity checking { { Iterator iter = files.iterator(); firstFile = (File) iter.next(); isFile = firstFile.isFile(); isDirectory = firstFile.isDirectory(); if ((isFile && isDirectory) || (!isFile && !isDirectory)) { throw new IOException("isFile && isDirectory: " + path); } checkSymlink(firstFile); while (iter.hasNext()) { File file = (File) iter.next(); checkSymlink(file); if ((isFile != file.isFile()) || (isDirectory != file.isDirectory())) { throw new IOException( "roots are out of sync, file&dir mix: " + path); } } } if (isFile && (files.size() > 1)) { ArrayList checksummers = new ArrayList(files.size()); for (Iterator iter = files.iterator(); iter.hasNext();) { File file = (File) iter.next(); Checksummer checksummer = new Checksummer(file); checksummer.start(); checksummers.add(checksummer); } while (true) { boolean waiting = false; for (Iterator iter = checksummers.iterator(); iter.hasNext();) { Checksummer cs = (Checksummer) iter.next(); if (cs.isAlive()) { waiting = true; try { synchronized (cs) { cs.wait(10000); // wait a max of 10 seconds // race condition could // occur between above // isAlive() statement and // when the Checksummer // finishes } } catch (InterruptedException e) { } break; } } if (!waiting) { break; } } Iterator iter = checksummers.iterator(); long checksum = ((Checksummer) iter.next()).getCheckSum() .getValue(); for (; iter.hasNext();) { Checksummer cs = (Checksummer) iter.next(); if (cs.getCheckSum().getValue() != checksum) { throw new IOException( "File collisions with different checksums - " + files); } } iter = files.iterator(); iter.next(); for (; iter.hasNext();) { File file = (File) iter.next(); file.delete(); logger.info("Deleted colliding and identical file: " + file.getPath()); iter.remove(); } } } // end sanity checking if (isDirectory) { length = 0; } else { length = firstFile.length(); } lastModified = firstFile.lastModified(); }
diff --git a/freeplane_plugin_script/src/org/freeplane/plugin/script/addons/AddOnInstallerPanel.java b/freeplane_plugin_script/src/org/freeplane/plugin/script/addons/AddOnInstallerPanel.java index 08cfdd76a..9fe0ba6ce 100644 --- a/freeplane_plugin_script/src/org/freeplane/plugin/script/addons/AddOnInstallerPanel.java +++ b/freeplane_plugin_script/src/org/freeplane/plugin/script/addons/AddOnInstallerPanel.java @@ -1,273 +1,273 @@ package org.freeplane.plugin.script.addons; import java.awt.Component; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.freeplane.core.resources.ResourceController; import org.freeplane.core.ui.MenuBuilder; import org.freeplane.core.ui.components.UITools; import org.freeplane.core.util.FileUtils; import org.freeplane.core.util.FreeplaneIconUtils; import org.freeplane.core.util.LogUtils; import org.freeplane.core.util.TextUtils; import org.freeplane.features.map.MapModel; import org.freeplane.features.map.mindmapmode.MMapModel; import org.freeplane.features.mode.Controller; import org.freeplane.features.mode.ModeController; import org.freeplane.features.mode.mindmapmode.MModeController; import org.freeplane.features.url.mindmapmode.MFileManager; import org.freeplane.main.addons.AddOnProperties; import org.freeplane.main.addons.AddOnsController; import org.freeplane.plugin.script.ScriptingEngine; import org.freeplane.plugin.script.ScriptingPermissions; import com.jgoodies.forms.factories.DefaultComponentFactory; import com.jgoodies.forms.factories.FormFactory; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.RowSpec; @SuppressWarnings("serial") public class AddOnInstallerPanel extends JPanel { private ManageAddOnsPanel manageAddOnsPanel; private ManageAddOnsPanel manageThemesPanel; private JButton installButton; private JTextField urlField; public AddOnInstallerPanel(final ManageAddOnsPanel manageAddOnsPanel, ManageAddOnsPanel manageThemesPanel) { this.manageAddOnsPanel = manageAddOnsPanel; this.manageThemesPanel = manageThemesPanel; setLayout(new FormLayout(new ColumnSpec[] { ColumnSpec.decode("default:grow"),}, new RowSpec[] { FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,})); // // Search // add(DefaultComponentFactory.getInstance().createSeparator(getTitleText("search")), "1, 2"); add(createVisitAddOnPageButton(), "1, 4, left, default"); add(Box.createVerticalStrut(20), "1, 6"); // // Install from known location // add(DefaultComponentFactory.getInstance().createSeparator(getTitleText("install.from.known.location")), "1, 7"); installButton = createInstallButton(); urlField = createUrlField(installButton); final JButton selectFile = createFileChooser(urlField); installButton.addActionListener(createInstallActionListener()); final Box box = Box.createHorizontalBox(); box.add(urlField); box.add(selectFile); add(box, "1, 9"); add(installButton, "1, 11, right, default"); // setBackground(Color.WHITE); } private static String getText(String key, Object... parameters) { return ManageAddOnsDialog.getText(key, parameters); } private static String getTitleText(final String key) { final String titleStyle = "<html><b><font size='+1'>"; return titleStyle + getText(key); } private JButton createVisitAddOnPageButton() { try { final String addOnsUriString = TextUtils.removeTranslateComment(TextUtils.getText("addons.site")); // parse the URI on creation of the dialog to test the URI syntax early final URI addOnsUri = new URI(addOnsUriString); return UITools.createHtmlLinkStyleButton(addOnsUri, getText("visit.addon.page")); } catch (URISyntaxException ex) { // bad translation? throw new RuntimeException(ex); } } private JButton createInstallButton() { final JButton installButton = new JButton(); MenuBuilder.setLabelAndMnemonic(installButton, getText("install")); installButton.setEnabled(false); // FIXME: get rid of that installButton.setMargin(new Insets(0, 25, 0, 25)); return installButton; } private ActionListener createInstallActionListener() { return new ActionListener() { public void actionPerformed(ActionEvent e) { final Controller controller = Controller.getCurrentController(); try { LogUtils.info("installing add-on from " + urlField.getText()); controller.getViewController().setWaitingCursor(true); final URL url = toURL(urlField.getText()); setStatusInfo(getText("status.installing")); final ModeController modeController = controller.getModeController(MModeController.MODENAME); final MFileManager fileManager = (MFileManager) MFileManager.getController(modeController); MapModel newMap = new MMapModel(); if (!fileManager.loadCatchExceptions(url, newMap)) { LogUtils.warn("can not load " + url); return; } controller.getModeController().getMapController().fireMapCreated(newMap); AddOnProperties addOn = (AddOnProperties) ScriptingEngine.executeScript(newMap.getRootNode(), getInstallScriptSource(), ScriptingPermissions.getPermissiveScriptingPermissions()); if (addOn != null) { setStatusInfo(getText("status.success", addOn.getName())); AddOnsController.getController().registerInstalledAddOn(addOn); final ManageAddOnsPanel managementPanel = addOn.isTheme() ? manageThemesPanel : manageAddOnsPanel; managementPanel.getTableModel().addAddOn(addOn); urlField.setText(""); ((JTabbedPane)getParent()).setSelectedComponent(managementPanel); selectLastAddOn(managementPanel); } } catch (Exception ex) { UITools.errorMessage(getText("error", ex.toString())); } finally { controller.getViewController().setWaitingCursor(false); } } private String getInstallScriptSource() throws IOException { final ResourceController resourceController = ResourceController.getResourceController(); final File scriptDir = new File(resourceController.getInstallationBaseDir(), "scripts"); final File installScript = new File(scriptDir, "installScriptAddOn.groovy"); if (!installScript.exists()) - throw new RuntimeException("internal error: installer not found"); + throw new RuntimeException("internal error: installer not found at " + installScript); return FileUtils.slurpFile(installScript); } private URL toURL(String urlText) throws MalformedURLException { try { return new URL(urlText); } catch (Exception e2) { return new File(urlText).toURI().toURL(); } } }; } private void selectLastAddOn(JComponent managementPanel) { try { JTable table = findJTable(managementPanel); final int row = table.getModel().getRowCount() - 1; table.getSelectionModel().setSelectionInterval(row, row); } catch (Exception e) { LogUtils.warn("cannot select just installed add-on", e); } } private JTable findJTable(JComponent child) { for (Component component : child.getComponents()) { if (component instanceof JTable) { return (JTable) component; } else if (component instanceof JComponent) { final JTable findResult = findJTable((JComponent) component); if (findResult != null) return findResult; } } return null; } private JButton createFileChooser(final JTextField urlField) { final JButton selectFile = new JButton(getText("search.file"), FreeplaneIconUtils.createImageIconByResourceKey("OpenAction.icon")); final JFileChooser fileChooser = new JFileChooser(); selectFile.setToolTipText(getText("select.tooltip")); selectFile.setMaximumSize(UITools.MAX_BUTTON_DIMENSION); selectFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fileChooser.showOpenDialog(urlField); final File selectedFile = fileChooser.getSelectedFile(); if (selectedFile != null) urlField.setText(selectedFile.getAbsolutePath()); } }); return selectFile; } private JTextField createUrlField(final JButton install) { final JTextField urlField = new JTextField(); // urlField.setColumns(100); urlField.setToolTipText(getText("install.tooltip")); urlField.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { updateImpl(e); } public void removeUpdate(DocumentEvent e) { updateImpl(e); } public void changedUpdate(DocumentEvent e) { updateImpl(e); } private void updateImpl(DocumentEvent e) { install.setEnabled(e.getDocument().getLength() > 0); } }); urlField.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { install.requestFocusInWindow(); install.doClick(); } } }); return urlField; } JButton getInstallButton() { return installButton; } JTextField getUrlField() { return urlField; } private static void setStatusInfo(final String message) { Controller.getCurrentController().getViewController().out(message); } }
true
true
private ActionListener createInstallActionListener() { return new ActionListener() { public void actionPerformed(ActionEvent e) { final Controller controller = Controller.getCurrentController(); try { LogUtils.info("installing add-on from " + urlField.getText()); controller.getViewController().setWaitingCursor(true); final URL url = toURL(urlField.getText()); setStatusInfo(getText("status.installing")); final ModeController modeController = controller.getModeController(MModeController.MODENAME); final MFileManager fileManager = (MFileManager) MFileManager.getController(modeController); MapModel newMap = new MMapModel(); if (!fileManager.loadCatchExceptions(url, newMap)) { LogUtils.warn("can not load " + url); return; } controller.getModeController().getMapController().fireMapCreated(newMap); AddOnProperties addOn = (AddOnProperties) ScriptingEngine.executeScript(newMap.getRootNode(), getInstallScriptSource(), ScriptingPermissions.getPermissiveScriptingPermissions()); if (addOn != null) { setStatusInfo(getText("status.success", addOn.getName())); AddOnsController.getController().registerInstalledAddOn(addOn); final ManageAddOnsPanel managementPanel = addOn.isTheme() ? manageThemesPanel : manageAddOnsPanel; managementPanel.getTableModel().addAddOn(addOn); urlField.setText(""); ((JTabbedPane)getParent()).setSelectedComponent(managementPanel); selectLastAddOn(managementPanel); } } catch (Exception ex) { UITools.errorMessage(getText("error", ex.toString())); } finally { controller.getViewController().setWaitingCursor(false); } } private String getInstallScriptSource() throws IOException { final ResourceController resourceController = ResourceController.getResourceController(); final File scriptDir = new File(resourceController.getInstallationBaseDir(), "scripts"); final File installScript = new File(scriptDir, "installScriptAddOn.groovy"); if (!installScript.exists()) throw new RuntimeException("internal error: installer not found"); return FileUtils.slurpFile(installScript); } private URL toURL(String urlText) throws MalformedURLException { try { return new URL(urlText); } catch (Exception e2) { return new File(urlText).toURI().toURL(); } } }; }
private ActionListener createInstallActionListener() { return new ActionListener() { public void actionPerformed(ActionEvent e) { final Controller controller = Controller.getCurrentController(); try { LogUtils.info("installing add-on from " + urlField.getText()); controller.getViewController().setWaitingCursor(true); final URL url = toURL(urlField.getText()); setStatusInfo(getText("status.installing")); final ModeController modeController = controller.getModeController(MModeController.MODENAME); final MFileManager fileManager = (MFileManager) MFileManager.getController(modeController); MapModel newMap = new MMapModel(); if (!fileManager.loadCatchExceptions(url, newMap)) { LogUtils.warn("can not load " + url); return; } controller.getModeController().getMapController().fireMapCreated(newMap); AddOnProperties addOn = (AddOnProperties) ScriptingEngine.executeScript(newMap.getRootNode(), getInstallScriptSource(), ScriptingPermissions.getPermissiveScriptingPermissions()); if (addOn != null) { setStatusInfo(getText("status.success", addOn.getName())); AddOnsController.getController().registerInstalledAddOn(addOn); final ManageAddOnsPanel managementPanel = addOn.isTheme() ? manageThemesPanel : manageAddOnsPanel; managementPanel.getTableModel().addAddOn(addOn); urlField.setText(""); ((JTabbedPane)getParent()).setSelectedComponent(managementPanel); selectLastAddOn(managementPanel); } } catch (Exception ex) { UITools.errorMessage(getText("error", ex.toString())); } finally { controller.getViewController().setWaitingCursor(false); } } private String getInstallScriptSource() throws IOException { final ResourceController resourceController = ResourceController.getResourceController(); final File scriptDir = new File(resourceController.getInstallationBaseDir(), "scripts"); final File installScript = new File(scriptDir, "installScriptAddOn.groovy"); if (!installScript.exists()) throw new RuntimeException("internal error: installer not found at " + installScript); return FileUtils.slurpFile(installScript); } private URL toURL(String urlText) throws MalformedURLException { try { return new URL(urlText); } catch (Exception e2) { return new File(urlText).toURI().toURL(); } } }; }
diff --git a/src/net/java/sip/communicator/impl/gui/main/authorization/AuthorizationRequestedDialog.java b/src/net/java/sip/communicator/impl/gui/main/authorization/AuthorizationRequestedDialog.java index 7020a5d88..5b8146d42 100644 --- a/src/net/java/sip/communicator/impl/gui/main/authorization/AuthorizationRequestedDialog.java +++ b/src/net/java/sip/communicator/impl/gui/main/authorization/AuthorizationRequestedDialog.java @@ -1,225 +1,225 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.main.authorization; import java.awt.*; import java.awt.event.*; import javax.swing.*; import net.java.sip.communicator.impl.gui.customcontrols.*; import net.java.sip.communicator.impl.gui.i18n.*; import net.java.sip.communicator.impl.gui.lookandfeel.*; import net.java.sip.communicator.impl.gui.main.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.protocol.*; /** * * @author Yana Stamcheva */ public class AuthorizationRequestedDialog extends SIPCommDialog implements ActionListener { public static final int ACCEPT_CODE = 0; public static final int REJECT_CODE = 1; public static final int IGNORE_CODE = 2; public static final int ERROR_CODE = -1; private JTextArea infoTextArea = new JTextArea(); private JEditorPane requestPane = new JEditorPane(); private JEditorPane responsePane = new JEditorPane(); private JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); private JPanel northPanel = new JPanel(new BorderLayout()); private JPanel titlePanel = new JPanel(new GridLayout(0, 1)); private JLabel titleLabel = new JLabel(); private JLabel iconLabel = new JLabel(new ImageIcon( ImageLoader.getImage(ImageLoader.AUTHORIZATION_ICON))); private JButton acceptButton = new JButton(Messages.getString("accept")); private JButton rejectButton = new JButton(Messages.getString("reject")); private JButton ignoreButton = new JButton(Messages.getString("ignore")); private JScrollPane requestScrollPane = new JScrollPane(); private JScrollPane responseScrollPane = new JScrollPane(); private JPanel mainPanel = new JPanel(new BorderLayout(10, 10)); private JPanel reasonsPanel = new JPanel(new GridLayout(0, 1, 5, 5)); private String title = Messages.getString("authorizationRequested"); private Object lock = new Object(); private int result; /** * Constructs the <tt>RequestAuthorisationDialog</tt>. * * @param contact The <tt>Contact</tt>, which requires authorisation. * @param request The <tt>AuthorizationRequest</tt> that will be sent. */ public AuthorizationRequestedDialog(MainFrame mainFrame, Contact contact, AuthorizationRequest request) { super(mainFrame); this.setModal(false); this.setTitle(title); titleLabel.setHorizontalAlignment(JLabel.CENTER); titleLabel.setFont(Constants.FONT.deriveFont(Font.BOLD, 18f)); titleLabel.setText(title); infoTextArea.setText(Messages.getString("authorizationRequestedInfo", contact.getDisplayName())); this.infoTextArea.setFont(Constants.FONT.deriveFont(Font.BOLD, 12f)); this.infoTextArea.setLineWrap(true); this.infoTextArea.setWrapStyleWord(true); this.infoTextArea.setOpaque(false); this.infoTextArea.setEditable(false); this.titlePanel.add(titleLabel); this.titlePanel.add(infoTextArea); this.northPanel.add(iconLabel, BorderLayout.WEST); this.northPanel.add(titlePanel, BorderLayout.CENTER); if(request.getReason() != null && !request.getReason().equals("")) { this.requestScrollPane.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(3, 3, 3, 3), SIPCommBorders.getBoldRoundBorder())); this.requestPane.setEditable(false); this.requestPane.setOpaque(false); this.requestPane.setText(request.getReason()); this.requestScrollPane.getViewport().add(requestPane); this.reasonsPanel.add(requestScrollPane); this.mainPanel.setPreferredSize(new Dimension(550, 400)); } else { - this.mainPanel.setPreferredSize(new Dimension(550, 300)); + this.mainPanel.setPreferredSize(new Dimension(550, 350)); } this.responseScrollPane.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(3, 3, 3, 3), SIPCommBorders.getBoldRoundBorder())); this.responseScrollPane.getViewport().add(responsePane); this.reasonsPanel.add(responseScrollPane); this.acceptButton.setName("accept"); this.rejectButton.setName("reject"); this.ignoreButton.setName("ignore"); this.getRootPane().setDefaultButton(acceptButton); this.acceptButton.addActionListener(this); this.rejectButton.addActionListener(this); this.ignoreButton.addActionListener(this); this.acceptButton.setMnemonic( Messages.getString("mnemonic.acceptButton").charAt(0)); this.rejectButton.setMnemonic( Messages.getString("mnemonic.rejectButton").charAt(0)); this.ignoreButton.setMnemonic( Messages.getString("mnemonic.ignoreButton").charAt(0)); this.buttonsPanel.add(acceptButton); this.buttonsPanel.add(rejectButton); this.buttonsPanel.add(ignoreButton); this.mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.mainPanel.add(northPanel, BorderLayout.NORTH); this.mainPanel.add(reasonsPanel, BorderLayout.CENTER); this.mainPanel.add(buttonsPanel, BorderLayout.SOUTH); this.getContentPane().add(mainPanel); } /** * Shows this modal dialog. * @return the result code, which shows what was the choice of the user */ public int showDialog() { this.setVisible(true); synchronized (lock) { try { lock.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } /** * Handles the <tt>ActionEvent</tt> triggered when one user clicks * on one of the buttons. */ public void actionPerformed(ActionEvent e) { JButton button = (JButton)e.getSource(); String name = button.getName(); if (name.equals("accept")) { this.result = ACCEPT_CODE; } else if (name.equals("reject")) { this.result = REJECT_CODE; } else if (name.equals("ignore")) { this.result = IGNORE_CODE; } else { this.result = ERROR_CODE; } synchronized (lock) { lock.notify(); } this.dispose(); } /** * Returns the response reason, which has been entered from the user to * explain it's response on the request. * @return the response reason of the user */ public String getResponseReason() { return this.responsePane.getText(); } protected void close(boolean isEscaped) { this.ignoreButton.doClick(); } }
true
true
public AuthorizationRequestedDialog(MainFrame mainFrame, Contact contact, AuthorizationRequest request) { super(mainFrame); this.setModal(false); this.setTitle(title); titleLabel.setHorizontalAlignment(JLabel.CENTER); titleLabel.setFont(Constants.FONT.deriveFont(Font.BOLD, 18f)); titleLabel.setText(title); infoTextArea.setText(Messages.getString("authorizationRequestedInfo", contact.getDisplayName())); this.infoTextArea.setFont(Constants.FONT.deriveFont(Font.BOLD, 12f)); this.infoTextArea.setLineWrap(true); this.infoTextArea.setWrapStyleWord(true); this.infoTextArea.setOpaque(false); this.infoTextArea.setEditable(false); this.titlePanel.add(titleLabel); this.titlePanel.add(infoTextArea); this.northPanel.add(iconLabel, BorderLayout.WEST); this.northPanel.add(titlePanel, BorderLayout.CENTER); if(request.getReason() != null && !request.getReason().equals("")) { this.requestScrollPane.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(3, 3, 3, 3), SIPCommBorders.getBoldRoundBorder())); this.requestPane.setEditable(false); this.requestPane.setOpaque(false); this.requestPane.setText(request.getReason()); this.requestScrollPane.getViewport().add(requestPane); this.reasonsPanel.add(requestScrollPane); this.mainPanel.setPreferredSize(new Dimension(550, 400)); } else { this.mainPanel.setPreferredSize(new Dimension(550, 300)); } this.responseScrollPane.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(3, 3, 3, 3), SIPCommBorders.getBoldRoundBorder())); this.responseScrollPane.getViewport().add(responsePane); this.reasonsPanel.add(responseScrollPane); this.acceptButton.setName("accept"); this.rejectButton.setName("reject"); this.ignoreButton.setName("ignore"); this.getRootPane().setDefaultButton(acceptButton); this.acceptButton.addActionListener(this); this.rejectButton.addActionListener(this); this.ignoreButton.addActionListener(this); this.acceptButton.setMnemonic( Messages.getString("mnemonic.acceptButton").charAt(0)); this.rejectButton.setMnemonic( Messages.getString("mnemonic.rejectButton").charAt(0)); this.ignoreButton.setMnemonic( Messages.getString("mnemonic.ignoreButton").charAt(0)); this.buttonsPanel.add(acceptButton); this.buttonsPanel.add(rejectButton); this.buttonsPanel.add(ignoreButton); this.mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.mainPanel.add(northPanel, BorderLayout.NORTH); this.mainPanel.add(reasonsPanel, BorderLayout.CENTER); this.mainPanel.add(buttonsPanel, BorderLayout.SOUTH); this.getContentPane().add(mainPanel); }
public AuthorizationRequestedDialog(MainFrame mainFrame, Contact contact, AuthorizationRequest request) { super(mainFrame); this.setModal(false); this.setTitle(title); titleLabel.setHorizontalAlignment(JLabel.CENTER); titleLabel.setFont(Constants.FONT.deriveFont(Font.BOLD, 18f)); titleLabel.setText(title); infoTextArea.setText(Messages.getString("authorizationRequestedInfo", contact.getDisplayName())); this.infoTextArea.setFont(Constants.FONT.deriveFont(Font.BOLD, 12f)); this.infoTextArea.setLineWrap(true); this.infoTextArea.setWrapStyleWord(true); this.infoTextArea.setOpaque(false); this.infoTextArea.setEditable(false); this.titlePanel.add(titleLabel); this.titlePanel.add(infoTextArea); this.northPanel.add(iconLabel, BorderLayout.WEST); this.northPanel.add(titlePanel, BorderLayout.CENTER); if(request.getReason() != null && !request.getReason().equals("")) { this.requestScrollPane.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(3, 3, 3, 3), SIPCommBorders.getBoldRoundBorder())); this.requestPane.setEditable(false); this.requestPane.setOpaque(false); this.requestPane.setText(request.getReason()); this.requestScrollPane.getViewport().add(requestPane); this.reasonsPanel.add(requestScrollPane); this.mainPanel.setPreferredSize(new Dimension(550, 400)); } else { this.mainPanel.setPreferredSize(new Dimension(550, 350)); } this.responseScrollPane.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(3, 3, 3, 3), SIPCommBorders.getBoldRoundBorder())); this.responseScrollPane.getViewport().add(responsePane); this.reasonsPanel.add(responseScrollPane); this.acceptButton.setName("accept"); this.rejectButton.setName("reject"); this.ignoreButton.setName("ignore"); this.getRootPane().setDefaultButton(acceptButton); this.acceptButton.addActionListener(this); this.rejectButton.addActionListener(this); this.ignoreButton.addActionListener(this); this.acceptButton.setMnemonic( Messages.getString("mnemonic.acceptButton").charAt(0)); this.rejectButton.setMnemonic( Messages.getString("mnemonic.rejectButton").charAt(0)); this.ignoreButton.setMnemonic( Messages.getString("mnemonic.ignoreButton").charAt(0)); this.buttonsPanel.add(acceptButton); this.buttonsPanel.add(rejectButton); this.buttonsPanel.add(ignoreButton); this.mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.mainPanel.add(northPanel, BorderLayout.NORTH); this.mainPanel.add(reasonsPanel, BorderLayout.CENTER); this.mainPanel.add(buttonsPanel, BorderLayout.SOUTH); this.getContentPane().add(mainPanel); }
diff --git a/src/org/jruby/debug/DebugEventHook.java b/src/org/jruby/debug/DebugEventHook.java index 2e8d3b2..47cde7c 100644 --- a/src/org/jruby/debug/DebugEventHook.java +++ b/src/org/jruby/debug/DebugEventHook.java @@ -1,626 +1,625 @@ /* * header & license * Copyright (c) 2007-2008 Martin Krauskopf * Copyright (c) 2007 Peter Brant * * 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.jruby.debug; import java.io.File; import org.jruby.*; import org.jruby.debug.DebugContext.StopReason; import org.jruby.debug.DebugFrame.Info; import org.jruby.debug.Debugger.DebugContextPair; import org.jruby.exceptions.RaiseException; import org.jruby.runtime.Block; import org.jruby.runtime.EventHook; import org.jruby.runtime.RubyEvent; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import static org.jruby.runtime.RubyEvent.*; final class DebugEventHook extends EventHook { private final Debugger debugger; private final Ruby runtime; private int hookCount; private int lastDebuggedThnum; private int lastCheck; private boolean inDebugger; public DebugEventHook(final Debugger debugger, final Ruby runtime) { this.debugger = debugger; lastDebuggedThnum = -1; this.runtime = runtime; } @Override public boolean isInterestedInEvent(RubyEvent event) { return true; } @Override public void eventHandler(final ThreadContext tCtx, String event, final String file, final int line, final String methodName, final IRubyObject klass) { RubyThread currThread = tCtx.getThread(); DebugContextPair contexts = debugger.threadContextLookup(currThread, true); // return if thread is marked as 'ignored'. debugger's threads are marked this way if (contexts.debugContext.isIgnored()) { return; } /* ignore a skipped section of code */ if (contexts.debugContext.isSkipped()) { cleanUp(contexts.debugContext); return; } /** Ignore JRuby core classes by default. Consider option for enabling it. */ if (Util.isJRubyCore(file)) { return; } if (contexts.debugContext.isSuspended()) { RubyThread.stop(tCtx, currThread); } synchronized (this) { if (isInDebugger()) { return; } setInDebugger(true); try { processEvent(tCtx, Util.typeForEvent(event), Util.relativizeToPWD(file), line, methodName, klass, contexts); } finally { setInDebugger(false); } } } @SuppressWarnings("fallthrough") private void processEvent(final ThreadContext tCtx, final RubyEvent event, final String file, final int line, final String methodName, final IRubyObject klass, DebugContextPair contexts) { if (debugger.isDebug()) { Util.logEvent(event, file, line, methodName, klass); } // one-based; jruby by default passes zero-based hookCount++; Ruby _runtime = tCtx.getRuntime(); IRubyObject breakpoint = getNil(); IRubyObject binding = getNil(); IRubyObject context = contexts.context; DebugContext debugContext = contexts.debugContext; // debug("jrubydebug> %s:%d [%s] %s\n", file, line, EVENT_NAMES[event], methodName); boolean moved = false; if (!debugContext.isForceMove() || debugContext.getLastLine() != line || debugContext.getLastFile() == null || !Util.areSameFiles(debugContext.getLastFile(), file)) { debugContext.setEnableBreakpoint(true); moved = true; } // else if(event != RUBY_EVENT_RETURN && event != RUBY_EVENT_C_RETURN) { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // goto cleanup; // } else { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // } if (LINE == event) { debugContext.setStepped(true); } switch (event) { case LINE: if (debugContext.getStackSize() == 0) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { updateTopFrame(event, debugContext, tCtx, file, line, methodName); } if (debugger.isTracing() || debugContext.isTracing()) { IRubyObject[] args = new IRubyObject[]{ _runtime.newString(file), _runtime.newFixnum(line) }; context.callMethod(tCtx, DebugContext.AT_TRACING, args); } if (debugContext.getDestFrame() == -1 || debugContext.getStackSize() == debugContext.getDestFrame()) { if (moved || !debugContext.isForceMove()) { debugContext.setStopNext(debugContext.getStopNext() - 1); } if (debugContext.getStopNext() < 0) { debugContext.setStopNext(-1); } if (moved || (debugContext.isStepped() && !debugContext.isForceMove())) { debugContext.setStopLine(debugContext.getStopLine() - 1); debugContext.setStepped(false); } } else if (debugContext.getStackSize() < debugContext.getDestFrame()) { debugContext.setStopNext(0); } if (debugContext.getStopNext() == 0 || debugContext.getStopLine() == 0 || !(breakpoint = checkBreakpointsByPos(debugContext, file, line)).isNil()) { binding = (tCtx != null ? RubyBinding.newBinding(_runtime, tCtx.currentBinding()) : getNil()); saveTopBinding(debugContext, binding); debugContext.setStopReason(DebugContext.StopReason.STEP); /* Check breakpoint expression. */ if (!breakpoint.isNil()) { if (!checkBreakpointExpression(tCtx, breakpoint, binding)) { break; } if (!checkBreakpointHitCondition(breakpoint)) { break; } if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } } /* reset all pointers */ debugContext.setDestFrame(-1); debugContext.setStopLine(-1); debugContext.setStopNext(-1); callAtLine(tCtx, context, debugContext, _runtime, file, line); } break; case CALL: saveCallFrame(event, tCtx, file, line, methodName, debugContext); breakpoint = checkBreakpointsByMethod(debugContext, klass, methodName); if (!breakpoint.isNil()) { DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } if (tCtx != null && binding.isNil()) { binding = RubyBinding.newBinding(_runtime, tCtx.currentBinding()); } saveTopBinding(debugContext, binding); if(!checkBreakpointExpression(tCtx, breakpoint, binding)) { break; } if(!checkBreakpointHitCondition(breakpoint)) { break; } if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } callAtLine(tCtx, context, debugContext, _runtime, file, line); } break; case C_CALL: if(cCallNewFrameP(klass)) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { updateTopFrame(event, debugContext, tCtx, file, line, methodName); } break; case C_RETURN: /* note if a block is given we fall through! */ if (!cCallNewFrameP(klass)) { break; } case RETURN: case END: if (debugContext.getStackSize() == debugContext.getStopFrame()) { debugContext.setStopNext(1); debugContext.setStopFrame(0); } while (debugContext.getStackSize() > 0) { DebugFrame topFrame = debugContext.popFrame(); String origMethodName = topFrame.getOrigMethodName(); if ((origMethodName == null && methodName == null) || (origMethodName != null && origMethodName.equals(methodName))) { break; } } debugContext.setEnableBreakpoint(true); break; case CLASS: resetTopFrameMethodName(debugContext); saveCallFrame(event, tCtx, file, line, methodName, debugContext); break; case RAISE: updateTopFrame(event, debugContext, tCtx, file, line, methodName); // XXX Implement post mortem debugging IRubyObject exception = _runtime.getGlobalVariables().get("$!"); // Might happen if the current ThreadContext is within 'defined?' if (exception.isNil()) { - assert tCtx.isWithinDefined() : "$! should be nil only when within defined?"; break; } if (_runtime.getClass("SystemExit").isInstance(exception)) { // Can't do this because this unhooks the event hook causing // a ConcurrentModificationException because the runtime // is still iterating over event hooks. Shouldn't really // matter. We're on our way out regardless. // debugger.stop(runtime); break; } if (debugger.getCatchpoints().isNil() || debugger.getCatchpoints().isEmpty()) { break; } RubyArray ancestors = exception.getType().ancestors(tCtx); int l = ancestors.getLength(); for (int i = 0; i < l; i++) { RubyModule module = (RubyModule)ancestors.get(i); IRubyObject modName = module.name(); IRubyObject hitCount = debugger.getCatchpoints().op_aref(tCtx, modName); if (!hitCount.isNil()) { hitCount = _runtime.newFixnum(RubyFixnum.fix2int(hitCount) + 1); debugger.getCatchpoints().op_aset(tCtx, modName, hitCount); debugContext.setStopReason(DebugContext.StopReason.CATCHPOINT); context.callMethod(tCtx, DebugContext.AT_CATCHPOINT, exception); DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } if (tCtx != null && binding.isNil()) { binding = RubyBinding.newBinding(_runtime, tCtx.currentBinding()); } saveTopBinding(debugContext, binding); callAtLine(tCtx, context, debugContext, _runtime, file, line); break; } } break; default: throw new IllegalArgumentException("unknown event type: " + event); } cleanUp(debugContext); } private IRubyObject getNil() { return runtime.getNil(); } private IRubyObject getBreakpoints() { return debugger.getBreakpoints(); } private void cleanUp(DebugContext debugContext) { debugContext.setStopReason(StopReason.NONE); /* check that all contexts point to alive threads */ if(hookCount - lastCheck > 3000) { debugger.checkThreadContexts(runtime); lastCheck = hookCount; } } private void saveCallFrame(final RubyEvent event, final ThreadContext tCtx, final String file, final int line, final String methodName, final DebugContext debugContext) { IRubyObject binding = (debugger.isKeepFrameBinding()) ? RubyBinding.newBinding(tCtx.getRuntime(), tCtx.currentBinding()) : tCtx.getRuntime().getNil(); DebugFrame debugFrame = new DebugFrame(); debugFrame.setFile(file); debugFrame.setLine(line); debugFrame.setBinding(binding); debugFrame.setMethodName(methodName); debugFrame.setOrigMethodName(methodName); debugFrame.setDead(false); debugFrame.setSelf(tCtx.getFrameSelf()); Info info = debugFrame.getInfo(); info.setFrame(tCtx.getCurrentFrame()); info.setScope(tCtx.getCurrentScope().getStaticScope()); info.setDynaVars(event == LINE ? tCtx.getCurrentScope() : null); debugContext.addFrame(debugFrame); if (debugger.isTrackFrameArgs()) { copyScalarArgs(tCtx, debugFrame); } else { debugFrame.setArgValues(runtime.getNil()); } } private boolean isArgValueSmall(IRubyObject value) { return value == RubyObject.UNDEF || value instanceof RubyFixnum || value instanceof RubyFloat || value instanceof RubyNil || value instanceof RubyModule || value instanceof RubyFile || value instanceof RubyBoolean || value instanceof RubySymbol; } /** Save scalar arguments or a class name. */ private void copyScalarArgs(ThreadContext tCtx, DebugFrame debugFrame) { RubyArray args = runtime.newArray(tCtx.getCurrentScope().getArgValues()); int len = args.getLength(); for (int i = 0; i < len; i++) { IRubyObject obj = args.entry(i); if (obj == null) { obj = runtime.getNil(); } if (! isArgValueSmall(obj)) { args.store(i, runtime.newString(obj.getType().getName())); } } debugFrame.setArgValues(args); } private void updateTopFrame(RubyEvent event, DebugContext debug_context, ThreadContext tCtx, String file, int line, String methodName) { DebugFrame topFrame = getTopFrame(debug_context); if (topFrame != null) { topFrame.setSelf(tCtx.getFrameSelf()); topFrame.setFile(file); topFrame.setLine(line); topFrame.setMethodName(methodName); topFrame.getInfo().setDynaVars(tCtx.getCurrentScope()); } } private DebugFrame getTopFrame(final DebugContext debugContext) { if (debugContext.getStackSize() == 0) { return null; } else { return debugContext.getTopFrame(); } } private IRubyObject checkBreakpointsByPos(DebugContext debugContext, String file, int line) { if (!debugContext.isEnableBreakpoint()) { return getNil(); } if (checkBreakpointByPos(debugContext.getBreakpoint(), file, line)) { return debugContext.getBreakpoint(); } RubyArray arr = getBreakpoints().convertToArray(); if (arr.isEmpty()) { return getNil(); } for (int i = 0; i < arr.size(); i++) { IRubyObject breakpoint = arr.entry(i); if (checkBreakpointByPos(breakpoint, file, line)) { return breakpoint; } } return getNil(); } private boolean checkBreakpointByPos(IRubyObject breakpoint, String file, int line) { if (breakpoint.isNil()) { return false; } DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct(); if (!debugBreakpoint.isEnabled()) { return false; } if (debugBreakpoint.getType() != DebugBreakpoint.Type.POS) { return false; } if (debugBreakpoint.getPos().getLine() != line) { return false; } String source = debugBreakpoint.getSource().toString(); if (source.startsWith("./")) { source = source.substring(2); } if (file.startsWith("./")) { file = file.substring(2); } return source.endsWith(file) || file.endsWith(source); } private IRubyObject checkBreakpointsByMethod(DebugContext debugContext, IRubyObject klass, String methodName) { if (!debugContext.isEnableBreakpoint()) { return getNil(); } if (checkBreakpointByMethod(debugContext.getBreakpoint(), klass, methodName)) { return debugContext.getBreakpoint(); } RubyArray arr = getBreakpoints().convertToArray(); if (arr.isEmpty()) { return getNil(); } for (int i = 0; i < arr.size(); i++) { IRubyObject breakpoint = arr.entry(i); if (checkBreakpointByMethod(breakpoint, klass, methodName)) { return breakpoint; } } return getNil(); } private boolean checkBreakpointByMethod(IRubyObject breakpoint, IRubyObject klass, String methodName) { if (breakpoint.isNil()) { return false; } DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct(); if (!debugBreakpoint.isEnabled()) { return false; } if (debugBreakpoint.getType() != DebugBreakpoint.Type.METHOD) { return false; } if (! debugBreakpoint.getPos().getMethodName().equals(methodName)) { return false; } RubyString source = debugBreakpoint.getSource().asString(); if (source.eql(klass.asString())) { return true; } if (klass instanceof MetaClass && source.eql(((MetaClass)klass).getAttached().asString())) { return true; } return false; } private boolean checkBreakpointExpression(ThreadContext tCtx, IRubyObject breakpoint, IRubyObject binding) { DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct(); if (debugBreakpoint.getExpr().isNil()) { return true; } try { IRubyObject result = RubyKernel.eval( tCtx, breakpoint, new IRubyObject[] { debugBreakpoint.getExpr(), binding }, Block.NULL_BLOCK); return result.isTrue(); } catch (RaiseException e) { // XXX Seems like we should tell the user about this, but this how // ruby-debug behaves return false; } } private boolean checkBreakpointHitCondition(IRubyObject breakpoint) { DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct(); debugBreakpoint.setHitCount(debugBreakpoint.getHitCount()+1); if (debugBreakpoint.getHitCondition() == null) { return true; } switch (debugBreakpoint.getHitCondition()) { case NONE: return true; case GE: if (debugBreakpoint.getHitCount() >= debugBreakpoint.getHitValue()) { return true; } break; case EQ: if (debugBreakpoint.getHitCount() == debugBreakpoint.getHitValue()) { return true; } break; case MOD: if (debugBreakpoint.getHitCount() % debugBreakpoint.getHitValue() == 0) { return true; } break; default: throw new IllegalArgumentException("unknown hit condition: " + debugBreakpoint.getHitCondition()); } return false; } private void saveTopBinding(DebugContext context, IRubyObject binding) { DebugFrame debugFrame = getTopFrame(context); if (debugFrame != null) { debugFrame.setBinding(binding); } } private IRubyObject callAtLine(ThreadContext tCtx, IRubyObject context, DebugContext debugContext, Ruby runtime, String file, int line) { return callAtLine(tCtx, context, debugContext, runtime.newString(file), runtime.newFixnum(line)); } private IRubyObject callAtLine(ThreadContext tCtx, IRubyObject context, DebugContext debugContext, IRubyObject file, IRubyObject line) { lastDebuggedThnum = debugContext.getThnum(); saveCurrentPosition(debugContext); IRubyObject[] args = new IRubyObject[]{ file, line }; return context.callMethod(tCtx, DebugContext.AT_LINE, args); } private void saveCurrentPosition(final DebugContext debugContext) { DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame == null) { return; } debugContext.setLastFile(debugFrame.getFile()); debugContext.setLastLine(debugFrame.getLine()); debugContext.setEnableBreakpoint(false); debugContext.setStepped(false); debugContext.setForceMove(false); } private boolean cCallNewFrameP(IRubyObject klass) { klass = realClass(klass); // TODO - block_given? // if(rb_block_given_p()) return true; String cName = klass.getType().getName(); return "Proc".equals(cName) || "RubyKernel".equals(cName) || "Module".equals(cName); } private IRubyObject realClass(IRubyObject klass) { if (klass instanceof MetaClass) { return ((MetaClass)klass).getRealClass(); } return klass; } private void resetTopFrameMethodName(DebugContext debugContext) { DebugFrame topFrame = getTopFrame(debugContext); if (topFrame != null) { topFrame.setMethodName(""); } } private boolean isInDebugger() { return inDebugger; } private void setInDebugger(boolean inDebugger) { this.inDebugger = inDebugger; } int getLastDebuggedThnum() { return lastDebuggedThnum; } }
true
true
private void processEvent(final ThreadContext tCtx, final RubyEvent event, final String file, final int line, final String methodName, final IRubyObject klass, DebugContextPair contexts) { if (debugger.isDebug()) { Util.logEvent(event, file, line, methodName, klass); } // one-based; jruby by default passes zero-based hookCount++; Ruby _runtime = tCtx.getRuntime(); IRubyObject breakpoint = getNil(); IRubyObject binding = getNil(); IRubyObject context = contexts.context; DebugContext debugContext = contexts.debugContext; // debug("jrubydebug> %s:%d [%s] %s\n", file, line, EVENT_NAMES[event], methodName); boolean moved = false; if (!debugContext.isForceMove() || debugContext.getLastLine() != line || debugContext.getLastFile() == null || !Util.areSameFiles(debugContext.getLastFile(), file)) { debugContext.setEnableBreakpoint(true); moved = true; } // else if(event != RUBY_EVENT_RETURN && event != RUBY_EVENT_C_RETURN) { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // goto cleanup; // } else { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // } if (LINE == event) { debugContext.setStepped(true); } switch (event) { case LINE: if (debugContext.getStackSize() == 0) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { updateTopFrame(event, debugContext, tCtx, file, line, methodName); } if (debugger.isTracing() || debugContext.isTracing()) { IRubyObject[] args = new IRubyObject[]{ _runtime.newString(file), _runtime.newFixnum(line) }; context.callMethod(tCtx, DebugContext.AT_TRACING, args); } if (debugContext.getDestFrame() == -1 || debugContext.getStackSize() == debugContext.getDestFrame()) { if (moved || !debugContext.isForceMove()) { debugContext.setStopNext(debugContext.getStopNext() - 1); } if (debugContext.getStopNext() < 0) { debugContext.setStopNext(-1); } if (moved || (debugContext.isStepped() && !debugContext.isForceMove())) { debugContext.setStopLine(debugContext.getStopLine() - 1); debugContext.setStepped(false); } } else if (debugContext.getStackSize() < debugContext.getDestFrame()) { debugContext.setStopNext(0); } if (debugContext.getStopNext() == 0 || debugContext.getStopLine() == 0 || !(breakpoint = checkBreakpointsByPos(debugContext, file, line)).isNil()) { binding = (tCtx != null ? RubyBinding.newBinding(_runtime, tCtx.currentBinding()) : getNil()); saveTopBinding(debugContext, binding); debugContext.setStopReason(DebugContext.StopReason.STEP); /* Check breakpoint expression. */ if (!breakpoint.isNil()) { if (!checkBreakpointExpression(tCtx, breakpoint, binding)) { break; } if (!checkBreakpointHitCondition(breakpoint)) { break; } if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } } /* reset all pointers */ debugContext.setDestFrame(-1); debugContext.setStopLine(-1); debugContext.setStopNext(-1); callAtLine(tCtx, context, debugContext, _runtime, file, line); } break; case CALL: saveCallFrame(event, tCtx, file, line, methodName, debugContext); breakpoint = checkBreakpointsByMethod(debugContext, klass, methodName); if (!breakpoint.isNil()) { DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } if (tCtx != null && binding.isNil()) { binding = RubyBinding.newBinding(_runtime, tCtx.currentBinding()); } saveTopBinding(debugContext, binding); if(!checkBreakpointExpression(tCtx, breakpoint, binding)) { break; } if(!checkBreakpointHitCondition(breakpoint)) { break; } if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } callAtLine(tCtx, context, debugContext, _runtime, file, line); } break; case C_CALL: if(cCallNewFrameP(klass)) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { updateTopFrame(event, debugContext, tCtx, file, line, methodName); } break; case C_RETURN: /* note if a block is given we fall through! */ if (!cCallNewFrameP(klass)) { break; } case RETURN: case END: if (debugContext.getStackSize() == debugContext.getStopFrame()) { debugContext.setStopNext(1); debugContext.setStopFrame(0); } while (debugContext.getStackSize() > 0) { DebugFrame topFrame = debugContext.popFrame(); String origMethodName = topFrame.getOrigMethodName(); if ((origMethodName == null && methodName == null) || (origMethodName != null && origMethodName.equals(methodName))) { break; } } debugContext.setEnableBreakpoint(true); break; case CLASS: resetTopFrameMethodName(debugContext); saveCallFrame(event, tCtx, file, line, methodName, debugContext); break; case RAISE: updateTopFrame(event, debugContext, tCtx, file, line, methodName); // XXX Implement post mortem debugging IRubyObject exception = _runtime.getGlobalVariables().get("$!"); // Might happen if the current ThreadContext is within 'defined?' if (exception.isNil()) { assert tCtx.isWithinDefined() : "$! should be nil only when within defined?"; break; } if (_runtime.getClass("SystemExit").isInstance(exception)) { // Can't do this because this unhooks the event hook causing // a ConcurrentModificationException because the runtime // is still iterating over event hooks. Shouldn't really // matter. We're on our way out regardless. // debugger.stop(runtime); break; } if (debugger.getCatchpoints().isNil() || debugger.getCatchpoints().isEmpty()) { break; } RubyArray ancestors = exception.getType().ancestors(tCtx); int l = ancestors.getLength(); for (int i = 0; i < l; i++) { RubyModule module = (RubyModule)ancestors.get(i); IRubyObject modName = module.name(); IRubyObject hitCount = debugger.getCatchpoints().op_aref(tCtx, modName); if (!hitCount.isNil()) { hitCount = _runtime.newFixnum(RubyFixnum.fix2int(hitCount) + 1); debugger.getCatchpoints().op_aset(tCtx, modName, hitCount); debugContext.setStopReason(DebugContext.StopReason.CATCHPOINT); context.callMethod(tCtx, DebugContext.AT_CATCHPOINT, exception); DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } if (tCtx != null && binding.isNil()) { binding = RubyBinding.newBinding(_runtime, tCtx.currentBinding()); } saveTopBinding(debugContext, binding); callAtLine(tCtx, context, debugContext, _runtime, file, line); break; } } break; default: throw new IllegalArgumentException("unknown event type: " + event); } cleanUp(debugContext); }
private void processEvent(final ThreadContext tCtx, final RubyEvent event, final String file, final int line, final String methodName, final IRubyObject klass, DebugContextPair contexts) { if (debugger.isDebug()) { Util.logEvent(event, file, line, methodName, klass); } // one-based; jruby by default passes zero-based hookCount++; Ruby _runtime = tCtx.getRuntime(); IRubyObject breakpoint = getNil(); IRubyObject binding = getNil(); IRubyObject context = contexts.context; DebugContext debugContext = contexts.debugContext; // debug("jrubydebug> %s:%d [%s] %s\n", file, line, EVENT_NAMES[event], methodName); boolean moved = false; if (!debugContext.isForceMove() || debugContext.getLastLine() != line || debugContext.getLastFile() == null || !Util.areSameFiles(debugContext.getLastFile(), file)) { debugContext.setEnableBreakpoint(true); moved = true; } // else if(event != RUBY_EVENT_RETURN && event != RUBY_EVENT_C_RETURN) { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // goto cleanup; // } else { // if(debug == Qtrue) // fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName)); // } if (LINE == event) { debugContext.setStepped(true); } switch (event) { case LINE: if (debugContext.getStackSize() == 0) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { updateTopFrame(event, debugContext, tCtx, file, line, methodName); } if (debugger.isTracing() || debugContext.isTracing()) { IRubyObject[] args = new IRubyObject[]{ _runtime.newString(file), _runtime.newFixnum(line) }; context.callMethod(tCtx, DebugContext.AT_TRACING, args); } if (debugContext.getDestFrame() == -1 || debugContext.getStackSize() == debugContext.getDestFrame()) { if (moved || !debugContext.isForceMove()) { debugContext.setStopNext(debugContext.getStopNext() - 1); } if (debugContext.getStopNext() < 0) { debugContext.setStopNext(-1); } if (moved || (debugContext.isStepped() && !debugContext.isForceMove())) { debugContext.setStopLine(debugContext.getStopLine() - 1); debugContext.setStepped(false); } } else if (debugContext.getStackSize() < debugContext.getDestFrame()) { debugContext.setStopNext(0); } if (debugContext.getStopNext() == 0 || debugContext.getStopLine() == 0 || !(breakpoint = checkBreakpointsByPos(debugContext, file, line)).isNil()) { binding = (tCtx != null ? RubyBinding.newBinding(_runtime, tCtx.currentBinding()) : getNil()); saveTopBinding(debugContext, binding); debugContext.setStopReason(DebugContext.StopReason.STEP); /* Check breakpoint expression. */ if (!breakpoint.isNil()) { if (!checkBreakpointExpression(tCtx, breakpoint, binding)) { break; } if (!checkBreakpointHitCondition(breakpoint)) { break; } if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } } /* reset all pointers */ debugContext.setDestFrame(-1); debugContext.setStopLine(-1); debugContext.setStopNext(-1); callAtLine(tCtx, context, debugContext, _runtime, file, line); } break; case CALL: saveCallFrame(event, tCtx, file, line, methodName, debugContext); breakpoint = checkBreakpointsByMethod(debugContext, klass, methodName); if (!breakpoint.isNil()) { DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } if (tCtx != null && binding.isNil()) { binding = RubyBinding.newBinding(_runtime, tCtx.currentBinding()); } saveTopBinding(debugContext, binding); if(!checkBreakpointExpression(tCtx, breakpoint, binding)) { break; } if(!checkBreakpointHitCondition(breakpoint)) { break; } if (breakpoint != debugContext.getBreakpoint()) { debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT); context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint); } else { debugContext.setBreakpoint(getNil()); } callAtLine(tCtx, context, debugContext, _runtime, file, line); } break; case C_CALL: if(cCallNewFrameP(klass)) { saveCallFrame(event, tCtx, file, line, methodName, debugContext); } else { updateTopFrame(event, debugContext, tCtx, file, line, methodName); } break; case C_RETURN: /* note if a block is given we fall through! */ if (!cCallNewFrameP(klass)) { break; } case RETURN: case END: if (debugContext.getStackSize() == debugContext.getStopFrame()) { debugContext.setStopNext(1); debugContext.setStopFrame(0); } while (debugContext.getStackSize() > 0) { DebugFrame topFrame = debugContext.popFrame(); String origMethodName = topFrame.getOrigMethodName(); if ((origMethodName == null && methodName == null) || (origMethodName != null && origMethodName.equals(methodName))) { break; } } debugContext.setEnableBreakpoint(true); break; case CLASS: resetTopFrameMethodName(debugContext); saveCallFrame(event, tCtx, file, line, methodName, debugContext); break; case RAISE: updateTopFrame(event, debugContext, tCtx, file, line, methodName); // XXX Implement post mortem debugging IRubyObject exception = _runtime.getGlobalVariables().get("$!"); // Might happen if the current ThreadContext is within 'defined?' if (exception.isNil()) { break; } if (_runtime.getClass("SystemExit").isInstance(exception)) { // Can't do this because this unhooks the event hook causing // a ConcurrentModificationException because the runtime // is still iterating over event hooks. Shouldn't really // matter. We're on our way out regardless. // debugger.stop(runtime); break; } if (debugger.getCatchpoints().isNil() || debugger.getCatchpoints().isEmpty()) { break; } RubyArray ancestors = exception.getType().ancestors(tCtx); int l = ancestors.getLength(); for (int i = 0; i < l; i++) { RubyModule module = (RubyModule)ancestors.get(i); IRubyObject modName = module.name(); IRubyObject hitCount = debugger.getCatchpoints().op_aref(tCtx, modName); if (!hitCount.isNil()) { hitCount = _runtime.newFixnum(RubyFixnum.fix2int(hitCount) + 1); debugger.getCatchpoints().op_aset(tCtx, modName, hitCount); debugContext.setStopReason(DebugContext.StopReason.CATCHPOINT); context.callMethod(tCtx, DebugContext.AT_CATCHPOINT, exception); DebugFrame debugFrame = getTopFrame(debugContext); if (debugFrame != null) { binding = debugFrame.getBinding(); } if (tCtx != null && binding.isNil()) { binding = RubyBinding.newBinding(_runtime, tCtx.currentBinding()); } saveTopBinding(debugContext, binding); callAtLine(tCtx, context, debugContext, _runtime, file, line); break; } } break; default: throw new IllegalArgumentException("unknown event type: " + event); } cleanUp(debugContext); }
diff --git a/src/presentation/StatisticPanel.java b/src/presentation/StatisticPanel.java index 414189e..ef71106 100644 --- a/src/presentation/StatisticPanel.java +++ b/src/presentation/StatisticPanel.java @@ -1,145 +1,145 @@ package presentation; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.table.DefaultTableModel; import presentation.action.StatisticPanelListener; /** * Presentation class for the statistic tab. * * @author Kerub * */ public class StatisticPanel extends JPanel { private JPanel upperPanel; private JPanel lowerPanel; private JButton weekButton; private JButton monthButton; private JButton yearButton; private JLabel amountSold; private JLabel cashIn; private JLabel titel; private JLabel firstEmpty; private JLabel secondEmpty; private JLabel thirdEmpty; private JLabel rubrik; private JScrollPane firstPane; private JScrollPane secondPane; private JScrollPane thirdPane; private JTable titleTable; private JTable amountTable; private JTable cashInTable; public StatisticPanel() { } public void initActions() { this.addWeekButtonListener(new StatisticPanelListener(this)); this.addMonthButtonListener(new StatisticPanelListener(this)); this.addYearButtonListener(new StatisticPanelListener(this)); } public void addWeekButtonListener(ActionListener al) { weekButton.addActionListener(al); } public void addMonthButtonListener(ActionListener al) { monthButton.addActionListener(al); } public void addYearButtonListener(ActionListener al) { yearButton.addActionListener(al); } public void initStatistic() { setBorder(new EmptyBorder(50, 30, 50, 50)); setLayout(new BorderLayout(50, 50)); upperPanel = new JPanel(new GridLayout(1, 3, 40, 40)); - lowerPanel = new JPanel(new GridLayout(1, 3)); + lowerPanel = new JPanel(new GridLayout(1, 3, 20, 20)); weekButton = new JButton("Vecka"); upperPanel.add(weekButton); monthButton = new JButton("M�nad"); upperPanel.add(monthButton); yearButton = new JButton("�r"); upperPanel.add(yearButton); /*titel = new JLabel("Titel"); titel.setBounds(16, 332, 83, 14); add(titel); amountSold = new JLabel("Antal s�lda"); amountSold.setBounds(170, 332, 83, 14); add(amountSold); cashIn = new JLabel("Int�kter"); cashIn.setBounds(349, 332, 46, 14); add(cashIn);*/ String [] [] title = {{"Exempel"}}; String titleColumns[] = {"Titel"}; DefaultTableModel titleModel = new DefaultTableModel(title, titleColumns); titleTable = new JTable(titleModel); String [] [] amount = {{"Exempel"}}; String amountColumns[] = {"Antal"}; DefaultTableModel columnsModel = new DefaultTableModel(amount, amountColumns); amountTable = new JTable(columnsModel); String [] [] cashIn = {{"Exempel"}}; String cashInColumns [] = {"Int�kter"}; DefaultTableModel cashInModel = new DefaultTableModel(cashIn, cashInColumns); cashInTable = new JTable(cashInModel); firstPane = new JScrollPane(titleTable); firstPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); firstPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); firstPane.setViewportBorder(new LineBorder(Color.BLUE)); secondPane = new JScrollPane(amountTable); secondPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); secondPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); secondPane.setViewportBorder(new LineBorder(Color.BLUE)); thirdPane = new JScrollPane(cashInTable); thirdPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); thirdPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); thirdPane.setViewportBorder(new LineBorder(Color.BLUE)); /*firstEmpty = new JLabel(""); firstEmpty.setBounds(10, 357, 89, 114); add(firstEmpty); secondEmpty = new JLabel(""); secondEmpty.setBounds(164, 357, 102, 114); add(secondEmpty); thirdEmpty = new JLabel(""); thirdEmpty.setBounds(322, 357, 89, 114); add(thirdEmpty);*/ rubrik = new JLabel("B�sts�ljande b�cker", JLabel.CENTER); lowerPanel.add(firstPane); lowerPanel.add(secondPane); lowerPanel.add(thirdPane); this.add(rubrik, BorderLayout.SOUTH); this.add(upperPanel, BorderLayout.NORTH); this.add(lowerPanel, BorderLayout.CENTER); } }
true
true
public void initStatistic() { setBorder(new EmptyBorder(50, 30, 50, 50)); setLayout(new BorderLayout(50, 50)); upperPanel = new JPanel(new GridLayout(1, 3, 40, 40)); lowerPanel = new JPanel(new GridLayout(1, 3)); weekButton = new JButton("Vecka"); upperPanel.add(weekButton); monthButton = new JButton("M�nad"); upperPanel.add(monthButton); yearButton = new JButton("�r"); upperPanel.add(yearButton); /*titel = new JLabel("Titel"); titel.setBounds(16, 332, 83, 14); add(titel); amountSold = new JLabel("Antal s�lda"); amountSold.setBounds(170, 332, 83, 14); add(amountSold); cashIn = new JLabel("Int�kter"); cashIn.setBounds(349, 332, 46, 14); add(cashIn);*/ String [] [] title = {{"Exempel"}}; String titleColumns[] = {"Titel"}; DefaultTableModel titleModel = new DefaultTableModel(title, titleColumns); titleTable = new JTable(titleModel); String [] [] amount = {{"Exempel"}}; String amountColumns[] = {"Antal"}; DefaultTableModel columnsModel = new DefaultTableModel(amount, amountColumns); amountTable = new JTable(columnsModel); String [] [] cashIn = {{"Exempel"}}; String cashInColumns [] = {"Int�kter"}; DefaultTableModel cashInModel = new DefaultTableModel(cashIn, cashInColumns); cashInTable = new JTable(cashInModel); firstPane = new JScrollPane(titleTable); firstPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); firstPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); firstPane.setViewportBorder(new LineBorder(Color.BLUE)); secondPane = new JScrollPane(amountTable); secondPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); secondPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); secondPane.setViewportBorder(new LineBorder(Color.BLUE)); thirdPane = new JScrollPane(cashInTable); thirdPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); thirdPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); thirdPane.setViewportBorder(new LineBorder(Color.BLUE)); /*firstEmpty = new JLabel(""); firstEmpty.setBounds(10, 357, 89, 114); add(firstEmpty); secondEmpty = new JLabel(""); secondEmpty.setBounds(164, 357, 102, 114); add(secondEmpty); thirdEmpty = new JLabel(""); thirdEmpty.setBounds(322, 357, 89, 114); add(thirdEmpty);*/ rubrik = new JLabel("B�sts�ljande b�cker", JLabel.CENTER); lowerPanel.add(firstPane); lowerPanel.add(secondPane); lowerPanel.add(thirdPane); this.add(rubrik, BorderLayout.SOUTH); this.add(upperPanel, BorderLayout.NORTH); this.add(lowerPanel, BorderLayout.CENTER); }
public void initStatistic() { setBorder(new EmptyBorder(50, 30, 50, 50)); setLayout(new BorderLayout(50, 50)); upperPanel = new JPanel(new GridLayout(1, 3, 40, 40)); lowerPanel = new JPanel(new GridLayout(1, 3, 20, 20)); weekButton = new JButton("Vecka"); upperPanel.add(weekButton); monthButton = new JButton("M�nad"); upperPanel.add(monthButton); yearButton = new JButton("�r"); upperPanel.add(yearButton); /*titel = new JLabel("Titel"); titel.setBounds(16, 332, 83, 14); add(titel); amountSold = new JLabel("Antal s�lda"); amountSold.setBounds(170, 332, 83, 14); add(amountSold); cashIn = new JLabel("Int�kter"); cashIn.setBounds(349, 332, 46, 14); add(cashIn);*/ String [] [] title = {{"Exempel"}}; String titleColumns[] = {"Titel"}; DefaultTableModel titleModel = new DefaultTableModel(title, titleColumns); titleTable = new JTable(titleModel); String [] [] amount = {{"Exempel"}}; String amountColumns[] = {"Antal"}; DefaultTableModel columnsModel = new DefaultTableModel(amount, amountColumns); amountTable = new JTable(columnsModel); String [] [] cashIn = {{"Exempel"}}; String cashInColumns [] = {"Int�kter"}; DefaultTableModel cashInModel = new DefaultTableModel(cashIn, cashInColumns); cashInTable = new JTable(cashInModel); firstPane = new JScrollPane(titleTable); firstPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); firstPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); firstPane.setViewportBorder(new LineBorder(Color.BLUE)); secondPane = new JScrollPane(amountTable); secondPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); secondPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); secondPane.setViewportBorder(new LineBorder(Color.BLUE)); thirdPane = new JScrollPane(cashInTable); thirdPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); thirdPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); thirdPane.setViewportBorder(new LineBorder(Color.BLUE)); /*firstEmpty = new JLabel(""); firstEmpty.setBounds(10, 357, 89, 114); add(firstEmpty); secondEmpty = new JLabel(""); secondEmpty.setBounds(164, 357, 102, 114); add(secondEmpty); thirdEmpty = new JLabel(""); thirdEmpty.setBounds(322, 357, 89, 114); add(thirdEmpty);*/ rubrik = new JLabel("B�sts�ljande b�cker", JLabel.CENTER); lowerPanel.add(firstPane); lowerPanel.add(secondPane); lowerPanel.add(thirdPane); this.add(rubrik, BorderLayout.SOUTH); this.add(upperPanel, BorderLayout.NORTH); this.add(lowerPanel, BorderLayout.CENTER); }
diff --git a/src/test/java/com/clearspring/thetan/metricCatcher/JSONMetricTest.java b/src/test/java/com/clearspring/thetan/metricCatcher/JSONMetricTest.java index 4d34f58..3156607 100644 --- a/src/test/java/com/clearspring/thetan/metricCatcher/JSONMetricTest.java +++ b/src/test/java/com/clearspring/thetan/metricCatcher/JSONMetricTest.java @@ -1,40 +1,40 @@ package com.clearspring.thetan.metricCatcher; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.yammer.metrics.core.GaugeMetric; public class JSONMetricTest { JSONMetric jsonMetric; @Before public void setUp() throws Exception { jsonMetric = new JSONMetric(); } @After public void tearDown() throws Exception { } @Test public void testSetType_MetricType() { - jsonMetric.setType(MetricType.GAUGE); + jsonMetric.setType("gauge"); assertEquals(MetricType.GAUGE, jsonMetric.getType()); } @Test public void testSetType_TypeName() { jsonMetric.setType("gauge"); assertEquals(MetricType.GAUGE, jsonMetric.getType()); } @Test public void testGetKlass_TypeName() { jsonMetric.setType("gauge"); assertEquals(GaugeMetric.class, jsonMetric.getMetricClass()); } }
true
true
public void testSetType_MetricType() { jsonMetric.setType(MetricType.GAUGE); assertEquals(MetricType.GAUGE, jsonMetric.getType()); }
public void testSetType_MetricType() { jsonMetric.setType("gauge"); assertEquals(MetricType.GAUGE, jsonMetric.getType()); }
diff --git a/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UIResponseForm.java b/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UIResponseForm.java index c28fbbf00..c6c33793f 100644 --- a/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UIResponseForm.java +++ b/eXoApplication/faq/webapp/src/main/java/org/exoplatform/faq/webui/popup/UIResponseForm.java @@ -1,774 +1,777 @@ /* * Copyright (C) 2003-2008 eXo Platform SAS. * * 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 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 org.exoplatform.faq.webui.popup; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import org.exoplatform.container.PortalContainer; import org.exoplatform.faq.service.Answer; import org.exoplatform.faq.service.Category; import org.exoplatform.faq.service.FAQService; import org.exoplatform.faq.service.FAQSetting; import org.exoplatform.faq.service.FileAttachment; import org.exoplatform.faq.service.Question; import org.exoplatform.faq.service.QuestionLanguage; import org.exoplatform.faq.service.impl.MultiLanguages; import org.exoplatform.faq.webui.FAQUtils; import org.exoplatform.faq.webui.UIFAQContainer; import org.exoplatform.faq.webui.UIFAQPortlet; import org.exoplatform.faq.webui.UIQuestions; import org.exoplatform.faq.webui.ValidatorDataInput; import org.exoplatform.forum.service.ForumService; import org.exoplatform.forum.service.Post; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.web.application.ApplicationMessage; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIApplication; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormCheckBoxInput; import org.exoplatform.webui.form.UIFormInputInfo; import org.exoplatform.webui.form.UIFormInputWithActions; import org.exoplatform.webui.form.UIFormSelectBox; import org.exoplatform.webui.form.UIFormStringInput; import org.exoplatform.webui.form.UIFormTextAreaInput; import org.exoplatform.webui.form.UIFormWYSIWYGInput; import org.exoplatform.webui.form.UIFormInputWithActions.ActionData; /** * Created by The eXo Platform SAS * Author : Mai Van Ha * [email protected] * Apr 17, 2008 ,3:19:00 PM */ @ComponentConfig( lifecycle = UIFormLifecycle.class , template = "app:/templates/faq/webui/popup/UIResponseForm.gtmpl", events = { @EventConfig(listeners = UIResponseForm.AddNewAnswerActionListener.class), @EventConfig(listeners = UIResponseForm.SaveActionListener.class), @EventConfig(listeners = UIResponseForm.CancelActionListener.class), @EventConfig(listeners = UIResponseForm.AddRelationActionListener.class), @EventConfig(listeners = UIResponseForm.AttachmentActionListener.class), @EventConfig(listeners = UIResponseForm.RemoveAttachmentActionListener.class), @EventConfig(listeners = UIResponseForm.RemoveRelationActionListener.class), @EventConfig(listeners = UIResponseForm.ViewEditQuestionActionListener.class), @EventConfig(listeners = UIResponseForm.ChangeQuestionActionListener.class) } ) public class UIResponseForm extends UIForm implements UIPopupComponent { private static final String QUESTION_CONTENT = "QuestionTitle" ; private static final String QUESTION_DETAIL = "QuestionContent" ; private static final String QUESTION_LANGUAGE = "Language" ; private static final String RESPONSE_CONTENT = "QuestionRespone" ; private static final String ATTATCH_MENTS = "QuestionAttach" ; private static final String REMOVE_FILE_ATTACH = "RemoveFile" ; private static final String FILE_ATTACHMENTS = "FileAttach" ; private static final String SHOW_ANSWER = "QuestionShowAnswer" ; private static final String IS_APPROVED = "IsApproved" ; private static Question question_ = null ; private static FAQService faqService = (FAQService)PortalContainer.getInstance().getComponentInstanceOfType(FAQService.class) ; @SuppressWarnings("unused") private boolean isViewEditQuestion_ = false; @SuppressWarnings("unused") private String questionDetail = new String(); private String questionContent = new String(); // form input : private UIFormStringInput inputQuestionContent_ ; private UIFormTextAreaInput inputQuestionDetail_ ; private UIFormSelectBox questionLanguages_ ; private UIFormWYSIWYGInput inputResponseQuestion_ ; private UIFormInputWithActions inputAttachment_ ; @SuppressWarnings("unchecked") private UIFormCheckBoxInput checkShowAnswer_ ; private UIFormCheckBoxInput<Boolean> isApproved_ ; // question infor : private String questionId_ = new String() ; private List<String> listRelationQuestion = new ArrayList<String>() ; private List<String> listQuestIdRela = new ArrayList<String>() ; private List<FileAttachment> listFileAttach_ = new ArrayList<FileAttachment>() ; // form variable: private List<QuestionLanguage> listQuestionLanguage = new ArrayList<QuestionLanguage>() ; private List<SelectItemOption<String>> listLanguageToReponse = new ArrayList<SelectItemOption<String>>() ; @SuppressWarnings("unused") private String questionChanged_ = new String() ; @SuppressWarnings("unused") private String responseContent_ = new String () ; private String languageIsResponsed = "" ; private String link_ = "" ; private boolean isChildren_ = false ; private FAQSetting faqSetting_; private List<Answer> listAnswers = new ArrayList<Answer>(); private int posOfResponse = 0; private boolean cateIsApprovedAnswer_ = true; private long currentDate = new Date().getTime(); public void activate() throws Exception { } public void deActivate() throws Exception { } public String getLink() {return link_;} public void setLink(String link) { this.link_ = link;} public void setFAQSetting(FAQSetting faqSetting) {this.faqSetting_= faqSetting;} public UIResponseForm() throws Exception { isChildren_ = false ; inputQuestionContent_ = new UIFormStringInput(QUESTION_CONTENT, QUESTION_CONTENT, null) ; inputQuestionDetail_ = new UIFormTextAreaInput(QUESTION_DETAIL, QUESTION_DETAIL, null) ; inputResponseQuestion_ = new UIFormWYSIWYGInput(RESPONSE_CONTENT, null, null , true) ; checkShowAnswer_ = new UIFormCheckBoxInput<Boolean>(SHOW_ANSWER, SHOW_ANSWER, false) ; isApproved_ = new UIFormCheckBoxInput<Boolean>(IS_APPROVED, IS_APPROVED, false) ; inputAttachment_ = new UIFormInputWithActions(ATTATCH_MENTS) ; inputAttachment_.addUIFormInput( new UIFormInputInfo(FILE_ATTACHMENTS, FILE_ATTACHMENTS, null) ) ; this.setActions(new String[]{"Attachment", "AddRelation", "Save", "Cancel"}) ; } @SuppressWarnings("unused") private int numberOfAnswer(){ return listAnswers.size(); } @SuppressWarnings("unused") private void setListRelation() throws Exception { String[] relations = question_.getRelations() ; this.setListIdQuesRela(Arrays.asList(relations)) ; if(relations != null && relations.length > 0){ SessionProvider sessionProvider = FAQUtils.getSystemProvider(); for(String relation : relations) { listRelationQuestion.add(faqService.getQuestionById(relation, sessionProvider).getQuestion()) ; } sessionProvider.close(); } } public void setQuestionId(Question question, String languageViewed, boolean cateIsApprovedAnswer){ this.cateIsApprovedAnswer_ = cateIsApprovedAnswer; listAnswers = new ArrayList<Answer>(); SessionProvider sessionProvider = FAQUtils.getSystemProvider(); try{ if(listQuestIdRela!= null && !listQuestIdRela.isEmpty()) { listRelationQuestion.clear() ; listQuestIdRela.clear() ; } question_ = question ; posOfResponse = 0; if(languageViewed != null && languageViewed.trim().length() > 0) { languageIsResponsed = languageViewed ; } else { languageIsResponsed = question.getLanguage(); } QuestionLanguage questionLanguage = new QuestionLanguage() ; questionLanguage.setLanguage(question.getLanguage()) ; questionLanguage.setDetail(question.getDetail()) ; questionLanguage.setQuestion(question.getQuestion()); questionLanguage.setAnswers(question.getAnswers()) ; listQuestionLanguage.add(questionLanguage) ; listQuestionLanguage.addAll(faqService.getQuestionLanguages(question_.getId(), sessionProvider)) ; for(QuestionLanguage language : listQuestionLanguage) { listLanguageToReponse.add(new SelectItemOption<String>(language.getLanguage(), language.getLanguage())) ; if(language.getLanguage().equals(languageIsResponsed)) { questionChanged_ = language.getDetail() ; inputQuestionContent_.setValue(language.getQuestion()); inputQuestionDetail_.setValue(language.getDetail()) ; questionDetail = language.getDetail(); questionContent = language.getQuestion(); if(language.getAnswers() != null && language.getAnswers().length > 0) { inputResponseQuestion_.setValue(language.getAnswers()[0].getResponses()) ; } listAnswers.addAll(Arrays.asList(language.getAnswers())); if(listAnswers.isEmpty()){ listAnswers.add(new Answer(FAQUtils.getCurrentUser(), cateIsApprovedAnswer_)); } } } this.setListRelation(sessionProvider); setListFileAttach(question.getAttachMent()) ; } catch (Exception e) { e.printStackTrace() ; } this.questionId_ = question.getId() ; checkShowAnswer_.setChecked(question_.isActivated()) ; isApproved_.setChecked(question_.isApproved()) ; try{ inputAttachment_.setActionField(FILE_ATTACHMENTS, getUploadFileList()) ; } catch (Exception e) { e.printStackTrace() ; } questionLanguages_ = new UIFormSelectBox(QUESTION_LANGUAGE, QUESTION_LANGUAGE, getListLanguageToReponse()) ; questionLanguages_.setSelectedValues(new String[]{languageIsResponsed}) ; questionLanguages_.setOnChange("ChangeQuestion") ; addChild(inputQuestionContent_) ; addChild(inputQuestionDetail_) ; addChild(questionLanguages_) ; addChild(inputResponseQuestion_) ; addChild(isApproved_) ; addChild(checkShowAnswer_) ; addChild(inputAttachment_) ; sessionProvider.close(); } @SuppressWarnings("unused") private String getValue(String id){ if(id.equals("QuestionTitle")) return questionContent; else return questionDetail; } public String getQuestionId(){ return questionId_ ; } public List<ActionData> getUploadFileList() { List<ActionData> uploadedFiles = new ArrayList<ActionData>() ; for(FileAttachment attachdata : listFileAttach_) { ActionData fileUpload = new ActionData() ; fileUpload.setActionListener("Download") ; fileUpload.setActionParameter(attachdata.getPath()); fileUpload.setActionType(ActionData.TYPE_ICON) ; fileUpload.setCssIconClass("AttachmentIcon") ; // "AttachmentIcon ZipFileIcon" fileUpload.setActionName(attachdata.getName() + " ("+attachdata.getSize()+" B)" ) ; fileUpload.setShowLabel(true) ; uploadedFiles.add(fileUpload) ; ActionData removeAction = new ActionData() ; removeAction.setActionListener("RemoveAttachment") ; removeAction.setActionName(REMOVE_FILE_ATTACH); removeAction.setActionParameter(attachdata.getPath()); removeAction.setCssIconClass("LabelLink"); removeAction.setActionType(ActionData.TYPE_LINK) ; uploadedFiles.add(removeAction) ; } return uploadedFiles ; } public void setListFileAttach(List<FileAttachment> listFileAttachment){ listFileAttach_.addAll(listFileAttachment) ; } public void setListFileAttach(FileAttachment fileAttachment){ listFileAttach_.add(fileAttachment) ; } @SuppressWarnings("unused") private List<FileAttachment> getListFile() { return listFileAttach_ ; } @SuppressWarnings("unused") private String getLanguageIsResponse() { return this.languageIsResponsed ; } public void refreshUploadFileList() throws Exception { ((UIFormInputWithActions)this.getChildById(ATTATCH_MENTS)).setActionField(FILE_ATTACHMENTS, getUploadFileList()) ; } private void setListRelation(SessionProvider sessionProvider) throws Exception { String[] relations = question_.getRelations() ; this.setListIdQuesRela(Arrays.asList(relations)) ; if(relations != null && relations.length > 0) for(String relation : relations) { listRelationQuestion.add(faqService.getQuestionById(relation, sessionProvider).getDetail()) ; } } public List<String> getListRelation() { return listRelationQuestion ; } @SuppressWarnings("unused") private List<SelectItemOption<String>> getListLanguageToReponse() { return listLanguageToReponse ; } public List<String> getListIdQuesRela() { return this.listQuestIdRela ; } public void setListIdQuesRela(List<String> listId) { if(!listQuestIdRela.isEmpty()) { listQuestIdRela.clear() ; } listQuestIdRela.addAll(listId) ; } public void setListRelationQuestion(List<String> listQuestionContent) { this.listRelationQuestion.clear() ; this.listRelationQuestion.addAll(listQuestionContent) ; } @SuppressWarnings("unused") private List<String> getListRelationQuestion() { return this.listRelationQuestion ; } public void setIsChildren(boolean isChildren) { this.isChildren_ = isChildren ; this.removeChildById(QUESTION_CONTENT) ; this.removeChildById(QUESTION_DETAIL) ; this.removeChildById(QUESTION_LANGUAGE) ; this.removeChildById(RESPONSE_CONTENT) ; this.removeChildById(ATTATCH_MENTS) ; this.removeChildById(IS_APPROVED) ; this.removeChildById(SHOW_ANSWER) ; listFileAttach_.clear() ; listLanguageToReponse.clear() ; listQuestIdRela.clear() ; listQuestionLanguage.clear() ; listRelationQuestion.clear() ; } private boolean compareTowArraies(String[] array1, String[] array2){ List<String> list1 = new ArrayList<String>(); list1.addAll(Arrays.asList(array1)); int count = 0; for(String str : array2){ if(list1.contains(str)) count ++; } if(count == array1.length && count == array2.length) return true; return false; } private double[] getMarkVoteAnswer(List<Double> listMarkResponse){ double[] markVoteResponse = new double[listMarkResponse.size()]; int i = 0; for(Double d : listMarkResponse){ markVoteResponse[i++] = d; } return markVoteResponse; } // action : static public class SaveActionListener extends EventListener<UIResponseForm> { @SuppressWarnings("unchecked") public void execute(Event<UIResponseForm> event) throws Exception { ValidatorDataInput validatorDataInput = new ValidatorDataInput() ; UIResponseForm responseForm = event.getSource() ; String questionContent = responseForm.inputQuestionContent_.getValue() ; if(questionContent == null || questionContent.trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.question-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } questionContent = questionContent.replaceAll("<", "&lt;").replaceAll(">", "&gt;") ; String questionDetail = responseForm.inputQuestionDetail_.getValue(); if(!validatorDataInput.fckContentIsNotEmpty(questionDetail)) questionDetail = " "; String responseQuestionContent = responseForm.inputResponseQuestion_.getValue() ; java.util.Date date = new java.util.Date(); if(responseQuestionContent != null && responseQuestionContent.trim().length() >0 && validatorDataInput.fckContentIsNotEmpty(responseQuestionContent)) { if(!responseForm.listAnswers.isEmpty() && responseForm.listAnswers.size() > 0){ responseForm.listAnswers.get(responseForm.posOfResponse).setResponses(responseQuestionContent); } else { Answer answer = new Answer(FAQUtils.getCurrentUser(), responseForm.cateIsApprovedAnswer_); answer.setResponses(responseQuestionContent); responseForm.listAnswers.add(answer); } } else if(!responseForm.listAnswers.isEmpty() && responseForm.listAnswers.size() > 0){ responseForm.listAnswers.remove(responseForm.posOfResponse); } if(responseForm.listAnswers.isEmpty()){ UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } if(question_.getLanguage().equals(responseForm.languageIsResponsed)) { question_.setQuestion(questionContent); question_.setDetail(questionDetail) ; question_.setAnswers(responseForm.listAnswers.toArray(new Answer[]{})); } else { question_.setQuestion(responseForm.listQuestionLanguage.get(0).getQuestion().replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; question_.setDetail(responseForm.listQuestionLanguage.get(0).getDetail().replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; question_.setAnswers(responseForm.listQuestionLanguage.get(0).getAnswers()); } for(QuestionLanguage questionLanguage : responseForm.listQuestionLanguage) { if(questionLanguage.getLanguage().equals(responseForm.languageIsResponsed) && !question_.getLanguage().equals(responseForm.languageIsResponsed)) { questionLanguage.setQuestion(questionContent) ; questionLanguage.setDetail(questionDetail) ; questionLanguage.setAnswers(responseForm.listAnswers.toArray(new Answer[]{})); break; } } // set relateion of question: question_.setRelations(responseForm.getListIdQuesRela().toArray(new String[]{})) ; // set show question: question_.setApproved(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(IS_APPROVED)).isChecked()) ; question_.setActivated(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(SHOW_ANSWER)).isChecked()) ; question_.setAttachMent(responseForm.listFileAttach_) ; Node questionNode = null ; //link UIFAQPortlet portlet = responseForm.getAncestorOfType(UIFAQPortlet.class) ; UIQuestions questions = portlet.getChild(UIFAQContainer.class).getChild(UIQuestions.class) ; String link = responseForm.getLink().replaceFirst("UIResponseForm", "UIQuestions").replaceFirst("Attachment", "ViewQuestion").replaceAll("&amp;", "&"); String selectedNode = Util.getUIPortal().getSelectedNode().getUri() ; String portalName = "/" + Util.getUIPortal().getName() ; if(link.indexOf(portalName) > 0) { if(link.indexOf(portalName + "/" + selectedNode) < 0){ link = link.replaceFirst(portalName, portalName + "/" + selectedNode) ; } } PortalRequestContext portalContext = Util.getPortalRequestContext(); String url = portalContext.getRequest().getRequestURL().toString(); url = url.replaceFirst("http://", "") ; url = url.substring(0, url.indexOf("/")) ; url = "http://" + url; String path = questions.getPathService(question_.getCategoryId())+"/"+question_.getCategoryId() ; link = link.replaceFirst("OBJECTID", path); link = url + link; question_.setLink(link) ; SessionProvider sessionProvider = FAQUtils.getSystemProvider(); try{ FAQUtils.getEmailSetting(responseForm.faqSetting_, false, false); questionNode = faqService.saveQuestion(question_, false, sessionProvider,responseForm.faqSetting_) ; FAQSetting faqSetting = new FAQSetting(); FAQUtils.getPorletPreference(faqSetting); if(faqSetting.getIsDiscussForum()) { String pathTopic = question_.getPathTopicDiscuss(); if(pathTopic != null && pathTopic.length() > 0) { ForumService forumService = (ForumService) PortalContainer.getInstance().getComponentInstanceOfType(ForumService.class); String []ids = pathTopic.split("/"); Post post; int l = question_.getAnswers().length; for (int i = 0; i < l; ++i) { String postId = question_.getAnswers()[i].getPostId(); try { if(postId != null && postId.length() > 0){ post = forumService.getPost(sessionProvider, ids[0], ids[1], ids[2], postId); if(post == null) { post = new Post(); post.setOwner(question_.getAnswers()[i].getResponseBy()); post.setName("Re: " + question_.getQuestion()); post.setIcon("ViewIcon"); question_.getAnswers()[i].setPostId(post.getId()); + post.setMessage(question_.getAnswers()[i].getResponses()); + forumService.savePost(sessionProvider, ids[0], ids[1], ids[2], post, true, ""); + }else { + post.setMessage(question_.getAnswers()[i].getResponses()); + forumService.savePost(sessionProvider, ids[0], ids[1], ids[2], post, false, ""); } - post.setMessage(question_.getAnswers()[i].getResponses()); - forumService.savePost(sessionProvider, ids[0], ids[1], ids[2], post, false, ""); } else { post = new Post(); post.setOwner(question_.getAnswers()[i].getResponseBy()); post.setName("Re: " + question_.getQuestion()); post.setIcon("ViewIcon"); post.setMessage(question_.getAnswers()[i].getResponses()); forumService.savePost(sessionProvider, ids[0], ids[1], ids[2], post, true, ""); question_.getAnswers()[i].setPostId(post.getId()); } } catch (Exception e) { e.printStackTrace(); } } } } faqService.saveAnswer(question_.getId(), question_.getAnswers(), sessionProvider); MultiLanguages multiLanguages = new MultiLanguages() ; for(int i = 1; i < responseForm.listQuestionLanguage.size(); i ++) { multiLanguages.addLanguage(questionNode, responseForm.listQuestionLanguage.get(i)) ; multiLanguages.saveAnswer(questionNode, responseForm.listQuestionLanguage.get(i)); } } catch (PathNotFoundException e) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-deleted", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } catch (Exception e) { e.printStackTrace() ; } if(question_.getAnswers() == null || question_.getAnswers().length < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-invalid", new String[]{question_.getLanguage()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } //cancel if(!responseForm.isChildren_) { questions.setIsNotChangeLanguage() ; UIPopupAction popupAction = portlet.getChild(UIPopupAction.class) ; popupAction.deActivate() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; event.getRequestContext().addUIComponentToUpdateByAjax(questions.getAncestorOfType(UIFAQContainer.class)) ; if(questionNode!= null && !("" + questions.getCategoryId()).equals(question_.getCategoryId())) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; Category category = faqService.getCategoryById(question_.getCategoryId(), sessionProvider) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-moved", new Object[]{category.getName()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } } else { UIQuestionManagerForm questionManagerForm = responseForm.getParent() ; UIQuestionForm questionForm = questionManagerForm.getChild(UIQuestionForm.class) ; if(questionManagerForm.isEditQuestion && responseForm.getQuestionId().equals(questionForm.getQuestionId())) { questionForm.setIsChildOfManager(true) ; questionForm.setQuestionId(question_) ; } questionManagerForm.isResponseQuestion = false ; UIPopupContainer popupContainer = questionManagerForm.getParent() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer) ; } sessionProvider.close(); } } static public class CancelActionListener extends EventListener<UIResponseForm> { public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm response = event.getSource() ; UIFAQPortlet portlet = response.getAncestorOfType(UIFAQPortlet.class) ; if(!response.isChildren_) { UIPopupAction popupAction = portlet.getChild(UIPopupAction.class) ; popupAction.deActivate() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; } else { UIQuestionManagerForm questionManagerForm = portlet.findFirstComponentOfType(UIQuestionManagerForm.class) ; questionManagerForm.isResponseQuestion = false ; UIPopupContainer popupContainer = questionManagerForm.getAncestorOfType(UIPopupContainer.class) ; UIAttachMentForm attachMentForm = popupContainer.findFirstComponentOfType(UIAttachMentForm.class) ; if(attachMentForm != null) { UIPopupAction popupAction = popupContainer.getChild(UIPopupAction.class) ; popupAction.deActivate() ; } else { UIAddRelationForm addRelationForm = popupContainer.findFirstComponentOfType(UIAddRelationForm.class) ; if(addRelationForm != null) { UIPopupAction popupAction = popupContainer.getChild(UIPopupAction.class) ; popupAction.deActivate() ; } } event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer) ; } } } static public class AddRelationActionListener extends EventListener<UIResponseForm> { public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm response = event.getSource() ; UIPopupContainer popupContainer = response.getAncestorOfType(UIPopupContainer.class); UIPopupAction popupAction = popupContainer.getChild(UIPopupAction.class).setRendered(true) ; UIAddRelationForm addRelationForm = popupAction.activate(UIAddRelationForm.class, 500) ; addRelationForm.setQuestionId(response.questionId_) ; addRelationForm.setRelationed(response.getListIdQuesRela()) ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; } } static public class AttachmentActionListener extends EventListener<UIResponseForm> { public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm response = event.getSource() ; UIPopupContainer popupContainer = response.getAncestorOfType(UIPopupContainer.class) ; UIPopupAction uiChildPopup = popupContainer.getChild(UIPopupAction.class).setRendered(true) ; UIAttachMentForm attachMentForm = uiChildPopup.activate(UIAttachMentForm.class, 550) ; attachMentForm.setResponse(true) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiChildPopup) ; } } static public class RemoveAttachmentActionListener extends EventListener<UIResponseForm> { @SuppressWarnings("static-access") public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm questionForm = event.getSource() ; String attFileId = event.getRequestContext().getRequestParameter(OBJECTID); for (FileAttachment att : questionForm.listFileAttach_) { if (att.getPath()!= null && att.getPath().equals(attFileId)) { questionForm.listFileAttach_.remove(att) ; break; } else if(att.getId() != null && att.getId().equals(attFileId)) { questionForm.listFileAttach_.remove(att) ; break; } } questionForm.refreshUploadFileList() ; event.getRequestContext().addUIComponentToUpdateByAjax(questionForm) ; } } static public class RemoveRelationActionListener extends EventListener<UIResponseForm> { public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm questionForm = event.getSource() ; String quesId = event.getRequestContext().getRequestParameter(OBJECTID); for(int i = 0 ; i < questionForm.listQuestIdRela.size(); i ++) { if(questionForm.listQuestIdRela.get(i).equals(quesId)) { questionForm.listRelationQuestion.remove(i) ; break ; } } questionForm.listQuestIdRela.remove(quesId) ; event.getRequestContext().addUIComponentToUpdateByAjax(questionForm) ; } } static public class AddNewAnswerActionListener extends EventListener<UIResponseForm> { @SuppressWarnings("unchecked") public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm responseForm = event.getSource(); String pos = event.getRequestContext().getRequestParameter(OBJECTID); UIFormWYSIWYGInput formWYSIWYGInput = responseForm.getChildById(RESPONSE_CONTENT); String responseContent = formWYSIWYGInput.getValue(); java.util.Date date = new java.util.Date(); String user = FAQUtils.getCurrentUser(); if(pos.equals("New")){ ValidatorDataInput validatorDataInput = new ValidatorDataInput(); if(responseContent != null && validatorDataInput.fckContentIsNotEmpty(responseContent)){ if(responseForm.listAnswers.isEmpty()){ Answer answer = new Answer(user, responseForm.cateIsApprovedAnswer_); answer.setResponses(responseContent); responseForm.listAnswers.add(answer); } else { responseForm.listAnswers.get(responseForm.posOfResponse).setResponses(responseContent); } responseForm.posOfResponse = responseForm.listAnswers.size(); responseForm.listAnswers.add(new Answer(user, responseForm.cateIsApprovedAnswer_)); formWYSIWYGInput.setValue(""); } else if(!responseForm.listAnswers.isEmpty() && responseForm.listAnswers.size() != responseForm.posOfResponse + 1){ responseForm.listAnswers.remove(responseForm.posOfResponse); responseForm.posOfResponse = responseForm.listAnswers.size(); responseForm.listAnswers.add(new Answer(user, responseForm.cateIsApprovedAnswer_)); formWYSIWYGInput.setValue(""); } } else { int newPosResponse = Integer.parseInt(pos); if(newPosResponse == responseForm.posOfResponse) return; ValidatorDataInput validatorDataInput = new ValidatorDataInput(); if(responseContent == null || !validatorDataInput.fckContentIsNotEmpty(responseContent)){ responseForm.listAnswers.remove(responseForm.posOfResponse); if(responseForm.posOfResponse < newPosResponse) newPosResponse--; } else if(!responseContent.equals(responseForm.listAnswers.get(responseForm.posOfResponse))){ responseForm.listAnswers.get(responseForm.posOfResponse).setResponses(responseContent); } formWYSIWYGInput.setValue(responseForm.listAnswers.get(newPosResponse).getResponses()); responseForm.posOfResponse = newPosResponse; } event.getRequestContext().addUIComponentToUpdateByAjax(responseForm); } } static public class ViewEditQuestionActionListener extends EventListener<UIResponseForm> { public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm responseForm = event.getSource(); responseForm.isViewEditQuestion_ = true; event.getRequestContext().addUIComponentToUpdateByAjax(responseForm); } } static public class ChangeQuestionActionListener extends EventListener<UIResponseForm> { @SuppressWarnings("static-access") public void execute(Event<UIResponseForm> event) throws Exception { UIResponseForm responseForm = event.getSource() ; String language = responseForm.questionLanguages_.getValue() ; if(responseForm.languageIsResponsed != null && language.equals(responseForm.languageIsResponsed)) return ; String responseContent = responseForm.inputResponseQuestion_.getValue() ; String questionDetail = responseForm.inputQuestionDetail_.getValue() ; String questionContent = responseForm.inputQuestionContent_.getValue(); if(questionContent == null || questionContent.trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.question-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } ValidatorDataInput validatorDataInput = new ValidatorDataInput(); if(!validatorDataInput.fckContentIsNotEmpty(questionDetail)) questionDetail = " "; java.util.Date date = new java.util.Date(); String user = FAQUtils.getCurrentUser(); for(QuestionLanguage questionLanguage : responseForm.listQuestionLanguage) { if(questionLanguage.getLanguage().equals(responseForm.languageIsResponsed)) { if(responseContent!= null && validatorDataInput.fckContentIsNotEmpty(responseContent)) { if(responseForm.listAnswers.isEmpty()){ Answer answer = new Answer(user, responseForm.cateIsApprovedAnswer_); answer.setResponses(responseContent); responseForm.listAnswers.add(answer); } else { responseForm.listAnswers.get(responseForm.posOfResponse).setResponses(responseContent); } questionLanguage.setAnswers(responseForm.listAnswers.toArray(new Answer[]{})) ; } else { if(!responseForm.listAnswers.isEmpty() && responseForm.listAnswers.size() > responseForm.posOfResponse){ responseForm.listAnswers.remove(responseForm.posOfResponse); } if(responseForm.listAnswers.isEmpty()){ questionLanguage.setAnswers(new Answer[]{}); } else { questionLanguage.setAnswers(responseForm.listAnswers.toArray(new Answer[]{})) ; } } questionLanguage.setDetail(questionDetail.replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; questionLanguage.setQuestion(questionContent.replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; break ; } } for(QuestionLanguage questionLanguage : responseForm.listQuestionLanguage) { if(questionLanguage.getLanguage().equals(language)) { responseForm.languageIsResponsed = language ; responseForm.inputQuestionDetail_.setValue(questionLanguage.getDetail()) ; responseForm.inputQuestionContent_.setValue(questionLanguage.getQuestion()) ; responseForm.questionDetail = questionLanguage.getDetail(); responseForm.questionContent = questionLanguage.getQuestion(); if(questionLanguage.getAnswers() != null && questionLanguage.getAnswers().length > 0) responseForm.inputResponseQuestion_.setValue(questionLanguage.getAnswers()[0].getResponses()) ; else responseForm.inputResponseQuestion_.setValue("") ; responseForm.posOfResponse = 0; responseForm.listAnswers.clear(); responseForm.listAnswers.addAll(Arrays.asList(questionLanguage.getAnswers())); if(responseForm.listAnswers.isEmpty()){ Answer answer = new Answer(user, responseForm.cateIsApprovedAnswer_); responseForm.listAnswers.add(answer); } break ; } } responseForm.isViewEditQuestion_ = false; event.getRequestContext().addUIComponentToUpdateByAjax(responseForm) ; } } }
false
true
public void execute(Event<UIResponseForm> event) throws Exception { ValidatorDataInput validatorDataInput = new ValidatorDataInput() ; UIResponseForm responseForm = event.getSource() ; String questionContent = responseForm.inputQuestionContent_.getValue() ; if(questionContent == null || questionContent.trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.question-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } questionContent = questionContent.replaceAll("<", "&lt;").replaceAll(">", "&gt;") ; String questionDetail = responseForm.inputQuestionDetail_.getValue(); if(!validatorDataInput.fckContentIsNotEmpty(questionDetail)) questionDetail = " "; String responseQuestionContent = responseForm.inputResponseQuestion_.getValue() ; java.util.Date date = new java.util.Date(); if(responseQuestionContent != null && responseQuestionContent.trim().length() >0 && validatorDataInput.fckContentIsNotEmpty(responseQuestionContent)) { if(!responseForm.listAnswers.isEmpty() && responseForm.listAnswers.size() > 0){ responseForm.listAnswers.get(responseForm.posOfResponse).setResponses(responseQuestionContent); } else { Answer answer = new Answer(FAQUtils.getCurrentUser(), responseForm.cateIsApprovedAnswer_); answer.setResponses(responseQuestionContent); responseForm.listAnswers.add(answer); } } else if(!responseForm.listAnswers.isEmpty() && responseForm.listAnswers.size() > 0){ responseForm.listAnswers.remove(responseForm.posOfResponse); } if(responseForm.listAnswers.isEmpty()){ UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } if(question_.getLanguage().equals(responseForm.languageIsResponsed)) { question_.setQuestion(questionContent); question_.setDetail(questionDetail) ; question_.setAnswers(responseForm.listAnswers.toArray(new Answer[]{})); } else { question_.setQuestion(responseForm.listQuestionLanguage.get(0).getQuestion().replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; question_.setDetail(responseForm.listQuestionLanguage.get(0).getDetail().replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; question_.setAnswers(responseForm.listQuestionLanguage.get(0).getAnswers()); } for(QuestionLanguage questionLanguage : responseForm.listQuestionLanguage) { if(questionLanguage.getLanguage().equals(responseForm.languageIsResponsed) && !question_.getLanguage().equals(responseForm.languageIsResponsed)) { questionLanguage.setQuestion(questionContent) ; questionLanguage.setDetail(questionDetail) ; questionLanguage.setAnswers(responseForm.listAnswers.toArray(new Answer[]{})); break; } } // set relateion of question: question_.setRelations(responseForm.getListIdQuesRela().toArray(new String[]{})) ; // set show question: question_.setApproved(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(IS_APPROVED)).isChecked()) ; question_.setActivated(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(SHOW_ANSWER)).isChecked()) ; question_.setAttachMent(responseForm.listFileAttach_) ; Node questionNode = null ; //link UIFAQPortlet portlet = responseForm.getAncestorOfType(UIFAQPortlet.class) ; UIQuestions questions = portlet.getChild(UIFAQContainer.class).getChild(UIQuestions.class) ; String link = responseForm.getLink().replaceFirst("UIResponseForm", "UIQuestions").replaceFirst("Attachment", "ViewQuestion").replaceAll("&amp;", "&"); String selectedNode = Util.getUIPortal().getSelectedNode().getUri() ; String portalName = "/" + Util.getUIPortal().getName() ; if(link.indexOf(portalName) > 0) { if(link.indexOf(portalName + "/" + selectedNode) < 0){ link = link.replaceFirst(portalName, portalName + "/" + selectedNode) ; } } PortalRequestContext portalContext = Util.getPortalRequestContext(); String url = portalContext.getRequest().getRequestURL().toString(); url = url.replaceFirst("http://", "") ; url = url.substring(0, url.indexOf("/")) ; url = "http://" + url; String path = questions.getPathService(question_.getCategoryId())+"/"+question_.getCategoryId() ; link = link.replaceFirst("OBJECTID", path); link = url + link; question_.setLink(link) ; SessionProvider sessionProvider = FAQUtils.getSystemProvider(); try{ FAQUtils.getEmailSetting(responseForm.faqSetting_, false, false); questionNode = faqService.saveQuestion(question_, false, sessionProvider,responseForm.faqSetting_) ; FAQSetting faqSetting = new FAQSetting(); FAQUtils.getPorletPreference(faqSetting); if(faqSetting.getIsDiscussForum()) { String pathTopic = question_.getPathTopicDiscuss(); if(pathTopic != null && pathTopic.length() > 0) { ForumService forumService = (ForumService) PortalContainer.getInstance().getComponentInstanceOfType(ForumService.class); String []ids = pathTopic.split("/"); Post post; int l = question_.getAnswers().length; for (int i = 0; i < l; ++i) { String postId = question_.getAnswers()[i].getPostId(); try { if(postId != null && postId.length() > 0){ post = forumService.getPost(sessionProvider, ids[0], ids[1], ids[2], postId); if(post == null) { post = new Post(); post.setOwner(question_.getAnswers()[i].getResponseBy()); post.setName("Re: " + question_.getQuestion()); post.setIcon("ViewIcon"); question_.getAnswers()[i].setPostId(post.getId()); } post.setMessage(question_.getAnswers()[i].getResponses()); forumService.savePost(sessionProvider, ids[0], ids[1], ids[2], post, false, ""); } else { post = new Post(); post.setOwner(question_.getAnswers()[i].getResponseBy()); post.setName("Re: " + question_.getQuestion()); post.setIcon("ViewIcon"); post.setMessage(question_.getAnswers()[i].getResponses()); forumService.savePost(sessionProvider, ids[0], ids[1], ids[2], post, true, ""); question_.getAnswers()[i].setPostId(post.getId()); } } catch (Exception e) { e.printStackTrace(); } } } } faqService.saveAnswer(question_.getId(), question_.getAnswers(), sessionProvider); MultiLanguages multiLanguages = new MultiLanguages() ; for(int i = 1; i < responseForm.listQuestionLanguage.size(); i ++) { multiLanguages.addLanguage(questionNode, responseForm.listQuestionLanguage.get(i)) ; multiLanguages.saveAnswer(questionNode, responseForm.listQuestionLanguage.get(i)); } } catch (PathNotFoundException e) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-deleted", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } catch (Exception e) { e.printStackTrace() ; } if(question_.getAnswers() == null || question_.getAnswers().length < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-invalid", new String[]{question_.getLanguage()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } //cancel if(!responseForm.isChildren_) { questions.setIsNotChangeLanguage() ; UIPopupAction popupAction = portlet.getChild(UIPopupAction.class) ; popupAction.deActivate() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; event.getRequestContext().addUIComponentToUpdateByAjax(questions.getAncestorOfType(UIFAQContainer.class)) ; if(questionNode!= null && !("" + questions.getCategoryId()).equals(question_.getCategoryId())) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; Category category = faqService.getCategoryById(question_.getCategoryId(), sessionProvider) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-moved", new Object[]{category.getName()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } } else { UIQuestionManagerForm questionManagerForm = responseForm.getParent() ; UIQuestionForm questionForm = questionManagerForm.getChild(UIQuestionForm.class) ; if(questionManagerForm.isEditQuestion && responseForm.getQuestionId().equals(questionForm.getQuestionId())) { questionForm.setIsChildOfManager(true) ; questionForm.setQuestionId(question_) ; } questionManagerForm.isResponseQuestion = false ; UIPopupContainer popupContainer = questionManagerForm.getParent() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer) ; } sessionProvider.close(); }
public void execute(Event<UIResponseForm> event) throws Exception { ValidatorDataInput validatorDataInput = new ValidatorDataInput() ; UIResponseForm responseForm = event.getSource() ; String questionContent = responseForm.inputQuestionContent_.getValue() ; if(questionContent == null || questionContent.trim().length() < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.question-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } questionContent = questionContent.replaceAll("<", "&lt;").replaceAll(">", "&gt;") ; String questionDetail = responseForm.inputQuestionDetail_.getValue(); if(!validatorDataInput.fckContentIsNotEmpty(questionDetail)) questionDetail = " "; String responseQuestionContent = responseForm.inputResponseQuestion_.getValue() ; java.util.Date date = new java.util.Date(); if(responseQuestionContent != null && responseQuestionContent.trim().length() >0 && validatorDataInput.fckContentIsNotEmpty(responseQuestionContent)) { if(!responseForm.listAnswers.isEmpty() && responseForm.listAnswers.size() > 0){ responseForm.listAnswers.get(responseForm.posOfResponse).setResponses(responseQuestionContent); } else { Answer answer = new Answer(FAQUtils.getCurrentUser(), responseForm.cateIsApprovedAnswer_); answer.setResponses(responseQuestionContent); responseForm.listAnswers.add(answer); } } else if(!responseForm.listAnswers.isEmpty() && responseForm.listAnswers.size() > 0){ responseForm.listAnswers.remove(responseForm.posOfResponse); } if(responseForm.listAnswers.isEmpty()){ UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-null", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; return ; } if(question_.getLanguage().equals(responseForm.languageIsResponsed)) { question_.setQuestion(questionContent); question_.setDetail(questionDetail) ; question_.setAnswers(responseForm.listAnswers.toArray(new Answer[]{})); } else { question_.setQuestion(responseForm.listQuestionLanguage.get(0).getQuestion().replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; question_.setDetail(responseForm.listQuestionLanguage.get(0).getDetail().replaceAll("<", "&lt;").replaceAll(">", "&gt;")) ; question_.setAnswers(responseForm.listQuestionLanguage.get(0).getAnswers()); } for(QuestionLanguage questionLanguage : responseForm.listQuestionLanguage) { if(questionLanguage.getLanguage().equals(responseForm.languageIsResponsed) && !question_.getLanguage().equals(responseForm.languageIsResponsed)) { questionLanguage.setQuestion(questionContent) ; questionLanguage.setDetail(questionDetail) ; questionLanguage.setAnswers(responseForm.listAnswers.toArray(new Answer[]{})); break; } } // set relateion of question: question_.setRelations(responseForm.getListIdQuesRela().toArray(new String[]{})) ; // set show question: question_.setApproved(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(IS_APPROVED)).isChecked()) ; question_.setActivated(((UIFormCheckBoxInput<Boolean>)responseForm.getChildById(SHOW_ANSWER)).isChecked()) ; question_.setAttachMent(responseForm.listFileAttach_) ; Node questionNode = null ; //link UIFAQPortlet portlet = responseForm.getAncestorOfType(UIFAQPortlet.class) ; UIQuestions questions = portlet.getChild(UIFAQContainer.class).getChild(UIQuestions.class) ; String link = responseForm.getLink().replaceFirst("UIResponseForm", "UIQuestions").replaceFirst("Attachment", "ViewQuestion").replaceAll("&amp;", "&"); String selectedNode = Util.getUIPortal().getSelectedNode().getUri() ; String portalName = "/" + Util.getUIPortal().getName() ; if(link.indexOf(portalName) > 0) { if(link.indexOf(portalName + "/" + selectedNode) < 0){ link = link.replaceFirst(portalName, portalName + "/" + selectedNode) ; } } PortalRequestContext portalContext = Util.getPortalRequestContext(); String url = portalContext.getRequest().getRequestURL().toString(); url = url.replaceFirst("http://", "") ; url = url.substring(0, url.indexOf("/")) ; url = "http://" + url; String path = questions.getPathService(question_.getCategoryId())+"/"+question_.getCategoryId() ; link = link.replaceFirst("OBJECTID", path); link = url + link; question_.setLink(link) ; SessionProvider sessionProvider = FAQUtils.getSystemProvider(); try{ FAQUtils.getEmailSetting(responseForm.faqSetting_, false, false); questionNode = faqService.saveQuestion(question_, false, sessionProvider,responseForm.faqSetting_) ; FAQSetting faqSetting = new FAQSetting(); FAQUtils.getPorletPreference(faqSetting); if(faqSetting.getIsDiscussForum()) { String pathTopic = question_.getPathTopicDiscuss(); if(pathTopic != null && pathTopic.length() > 0) { ForumService forumService = (ForumService) PortalContainer.getInstance().getComponentInstanceOfType(ForumService.class); String []ids = pathTopic.split("/"); Post post; int l = question_.getAnswers().length; for (int i = 0; i < l; ++i) { String postId = question_.getAnswers()[i].getPostId(); try { if(postId != null && postId.length() > 0){ post = forumService.getPost(sessionProvider, ids[0], ids[1], ids[2], postId); if(post == null) { post = new Post(); post.setOwner(question_.getAnswers()[i].getResponseBy()); post.setName("Re: " + question_.getQuestion()); post.setIcon("ViewIcon"); question_.getAnswers()[i].setPostId(post.getId()); post.setMessage(question_.getAnswers()[i].getResponses()); forumService.savePost(sessionProvider, ids[0], ids[1], ids[2], post, true, ""); }else { post.setMessage(question_.getAnswers()[i].getResponses()); forumService.savePost(sessionProvider, ids[0], ids[1], ids[2], post, false, ""); } } else { post = new Post(); post.setOwner(question_.getAnswers()[i].getResponseBy()); post.setName("Re: " + question_.getQuestion()); post.setIcon("ViewIcon"); post.setMessage(question_.getAnswers()[i].getResponses()); forumService.savePost(sessionProvider, ids[0], ids[1], ids[2], post, true, ""); question_.getAnswers()[i].setPostId(post.getId()); } } catch (Exception e) { e.printStackTrace(); } } } } faqService.saveAnswer(question_.getId(), question_.getAnswers(), sessionProvider); MultiLanguages multiLanguages = new MultiLanguages() ; for(int i = 1; i < responseForm.listQuestionLanguage.size(); i ++) { multiLanguages.addLanguage(questionNode, responseForm.listQuestionLanguage.get(i)) ; multiLanguages.saveAnswer(questionNode, responseForm.listQuestionLanguage.get(i)); } } catch (PathNotFoundException e) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-deleted", null, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } catch (Exception e) { e.printStackTrace() ; } if(question_.getAnswers() == null || question_.getAnswers().length < 1) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; uiApplication.addMessage(new ApplicationMessage("UIResponseForm.msg.response-invalid", new String[]{question_.getLanguage()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } //cancel if(!responseForm.isChildren_) { questions.setIsNotChangeLanguage() ; UIPopupAction popupAction = portlet.getChild(UIPopupAction.class) ; popupAction.deActivate() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupAction) ; event.getRequestContext().addUIComponentToUpdateByAjax(questions.getAncestorOfType(UIFAQContainer.class)) ; if(questionNode!= null && !("" + questions.getCategoryId()).equals(question_.getCategoryId())) { UIApplication uiApplication = responseForm.getAncestorOfType(UIApplication.class) ; Category category = faqService.getCategoryById(question_.getCategoryId(), sessionProvider) ; uiApplication.addMessage(new ApplicationMessage("UIQuestions.msg.question-id-moved", new Object[]{category.getName()}, ApplicationMessage.WARNING)) ; event.getRequestContext().addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ; } } else { UIQuestionManagerForm questionManagerForm = responseForm.getParent() ; UIQuestionForm questionForm = questionManagerForm.getChild(UIQuestionForm.class) ; if(questionManagerForm.isEditQuestion && responseForm.getQuestionId().equals(questionForm.getQuestionId())) { questionForm.setIsChildOfManager(true) ; questionForm.setQuestionId(question_) ; } questionManagerForm.isResponseQuestion = false ; UIPopupContainer popupContainer = questionManagerForm.getParent() ; event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer) ; } sessionProvider.close(); }
diff --git a/src/main/java/com/googlecode/mgwt/ui/client/MGWTSettings.java b/src/main/java/com/googlecode/mgwt/ui/client/MGWTSettings.java index 86ccb3d8..6365da27 100644 --- a/src/main/java/com/googlecode/mgwt/ui/client/MGWTSettings.java +++ b/src/main/java/com/googlecode/mgwt/ui/client/MGWTSettings.java @@ -1,450 +1,450 @@ /* * Copyright 2010 Daniel Kurka * * 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.googlecode.mgwt.ui.client; /** * <p> * MGWTSettings class. * </p> * * @author Daniel Kurka * @version $Id: $ */ public class MGWTSettings { public static class ViewPort { public enum DENSITY { LOW("low-dpi"), MEDIUM("medium-dpi"), HIGH("high-dpi"), DEVICE("device-dpi"); private final String value; private DENSITY(String value) { this.value = value; } public String getValue() { return value; } }; private String width; private String height; private double initialScale = 1; private double minimumScale = 1; private double maximumScale = 1; private boolean userScaleAble = false; private String targetDensity; /** * Set the width of the viewport * * @param value * the width in px * @return the viewport instance */ public ViewPort setWidth(int value) { this.width = "" + value; return this; } /** * Set the height of the viewport * * @param value * the height in px * @return the viewport instance */ public ViewPort setHeight(int value) { this.height = "" + value; return this; } /** * Set width to device width * * Most common for most apps * * @return the viewport instance */ public ViewPort setWidthToDeviceWidth() { this.width = "device-width"; return this; } /** * Set the height to device height * * * @return the viewport instance */ public ViewPort setHeightToDeviceHeight() { this.height = "device-height"; return this; } /** * <p> * android only * </p> * set the target density in dpi * * * @param value * the target density in dpi * @return the viewport instance */ public ViewPort setTargetDensity(int value) { targetDensity = "" + value; return this; } /** * <p> * android only * </p> * * set the target density * * @param d * the density to use * @return the viewport instance */ public ViewPort setTargetDensity(DENSITY d) { targetDensity = d.getValue(); return this; } /** * Should the viewport be scalable by the user * * @param userScaleAble * ture to allow scaling * @return the viewport instance */ public ViewPort setUserScaleAble(boolean userScaleAble) { this.userScaleAble = userScaleAble; return this; } /** * set the minimum scaling of the viewport * * @param minimumScale * the scale to use * @return the viewport instance */ public ViewPort setMinimumScale(double minimumScale) { this.minimumScale = minimumScale; return this; } /** * Set the maximum scale of the viewport * * @param maximumScale * the scale to use * @return the viewport instance */ public ViewPort setMaximumScale(double maximumScale) { this.maximumScale = maximumScale; return this; } /** * set the initial scale of the viewport * * @param initialScale * the scale to use * @return the viewport instance */ public ViewPort setInitialScale(double initialScale) { this.initialScale = initialScale; return this; } /** * get the content for the viewport meta tag * * @return content of the viewport meta tag */ public String getContent() { StringBuffer buffer = new StringBuffer(); // initial scale buffer.append("initial-scale=" + initialScale); // minimum scale buffer.append(",minimum-scale=" + minimumScale); // maximum scale buffer.append(",maximum-scale=" + maximumScale); // width if (width != null) { - buffer.append("width=" + width); + buffer.append(",width=" + width); } // height if (height != null) { buffer.append(",height=" + height); } // user scaleable if (!userScaleAble) { buffer.append(",user-scalable=no"); } if (targetDensity != null && MGWT.getOsDetection().isAndroid()) { buffer.append(",target-density=" + targetDensity); } return buffer.toString(); } } /** * <p> * ios only * </p> * * All possible styles for the statusbar if the app is running in fullscreen * * @author Daniel Kurka * */ public enum StatusBarStyle { DEFAULT, BLACK, BLACK_TRANSLUCENT; }; private ViewPort viewPort; private boolean gloss; private String iconUrl; private String startUrl; private boolean fullscreen; private String statusBar; private boolean preventScrolling; private boolean disablePhoneNumberDetection; private StatusBarStyle statusBarStyle; /** * Get the viewport for the mgwt app * * @return the viewport */ public ViewPort getViewPort() { return viewPort; } /** * Set the viewport the the mgwt app * * @param viewPort * the viewport to use */ public void setViewPort(ViewPort viewPort) { this.viewPort = viewPort; } /** * If the app is added to the home screen on an ios device we can select if * we like a gloss added to the icon of the app * * <p> * only relevant on ios devices * </p> * * @return true if gloss should be added, otherwise false */ public boolean isAddGlosToIcon() { return gloss; } /** * If the app is added to the home screen on an ios device we can select if * we like a gloss added to the icon of the app * * <p> * only relevant on ios devices * </p> * * @param gloss * true if gloss should be added, otherwise false */ public void setAddGlosToIcon(boolean gloss) { this.gloss = gloss; } /** * The icon url to use on the home screen on ios * * @return the icon url */ public String getIconUrl() { return iconUrl; } /** * Set the icon url to use on the home screen on ios * * @param url * the url of the icon to use */ public void setIconUrl(String url) { this.iconUrl = url; } /** * Get the url to the image to use at startup if running on home screen * * @return the url of the image */ public String getStartUrl() { return startUrl; } /** * Set the url to the image to use at startup if running on home screen * * @param startUrl * the url to use */ public void setStartUrl(String startUrl) { this.startUrl = startUrl; } /** * Can the app be used in full screen mode * * @return true if the app can be used in full screen mode */ public boolean isFullscreen() { return fullscreen; } /** * Can the app be used in full screen * * @param fullscreen * true if app can be run in full screen */ public void setFullscreen(boolean fullscreen) { this.fullscreen = fullscreen; } /** * <p> * Getter for the field <code>statusBar</code>. * </p> * * @return a {@link java.lang.String} object. */ public String getStatusBar() { return statusBar; } /** * <p> * Setter for the field <code>statusBar</code>. * </p> * * @param statusBar * a {@link java.lang.String} object. */ public void setStatusBar(String statusBar) { this.statusBar = statusBar; } /** * Should mgwt prevent default scrolling behaviour * * @return true if mgwt should prevent default scrolling behaviour */ public boolean isPreventScrolling() { return preventScrolling; } /** * Should mgwt prevent default scrolling behaviour * * @param preventScrolling * true if mgwt should prevent default scrolling behaviour */ public void setPreventScrolling(boolean preventScrolling) { this.preventScrolling = preventScrolling; } /** * <p> * ios only * </p> * disable the auto dection of phonenumbers in your app * * @param disablePhoneNumberDetection * true to disable */ public void setDisablePhoneNumberDetection(boolean disablePhoneNumberDetection) { this.disablePhoneNumberDetection = disablePhoneNumberDetection; } /** * * <p> * ios only * </p> * disable the auto dection of phonenumbers in your app * * @return true to disable */ public boolean isDisablePhoneNumberDetection() { return disablePhoneNumberDetection; } /** * <p> * ios only * </p> * * set the style of the status bar if the app is running in full screen * * @param statusBarStyle * the style to use */ public void setStatusBarStyle(StatusBarStyle statusBarStyle) { this.statusBarStyle = statusBarStyle; } /** * <p> * ios only * </p> * * get the style of the status bar if the app is running in full screen * * @return statusBarStyle the style to use */ public StatusBarStyle getStatusBarStyle() { return statusBarStyle; } }
true
true
public String getContent() { StringBuffer buffer = new StringBuffer(); // initial scale buffer.append("initial-scale=" + initialScale); // minimum scale buffer.append(",minimum-scale=" + minimumScale); // maximum scale buffer.append(",maximum-scale=" + maximumScale); // width if (width != null) { buffer.append("width=" + width); } // height if (height != null) { buffer.append(",height=" + height); } // user scaleable if (!userScaleAble) { buffer.append(",user-scalable=no"); } if (targetDensity != null && MGWT.getOsDetection().isAndroid()) { buffer.append(",target-density=" + targetDensity); } return buffer.toString(); }
public String getContent() { StringBuffer buffer = new StringBuffer(); // initial scale buffer.append("initial-scale=" + initialScale); // minimum scale buffer.append(",minimum-scale=" + minimumScale); // maximum scale buffer.append(",maximum-scale=" + maximumScale); // width if (width != null) { buffer.append(",width=" + width); } // height if (height != null) { buffer.append(",height=" + height); } // user scaleable if (!userScaleAble) { buffer.append(",user-scalable=no"); } if (targetDensity != null && MGWT.getOsDetection().isAndroid()) { buffer.append(",target-density=" + targetDensity); } return buffer.toString(); }
diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java index b2f5d42c..3ec5ea23 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java @@ -1,504 +1,504 @@ /* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.visualization.utilities; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.vivoweb.webapp.util.ModelUtils; import com.google.gson.Gson; import com.hp.hpl.jena.iri.IRI; import com.hp.hpl.jena.iri.IRIFactory; import com.hp.hpl.jena.iri.Violation; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.RDFNode; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions; import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty; import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants; import edu.cornell.mannlib.vitro.webapp.filestorage.FileServingHelper; import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels; import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.GenericQueryMap; import edu.cornell.mannlib.vitro.webapp.visualization.visutils.AllPropertiesQueryRunner; import edu.cornell.mannlib.vitro.webapp.visualization.visutils.GenericQueryRunner; import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryRunner; import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions; import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler; /** * This request handler is used when you need helpful information to add more context * to the visualization. It does not have any code for generating the visualization, * just fires sparql queries to get info for specific cases like, * 1. thumbnail/image location for a particular individual * 2. profile information for a particular individual like label, moniker etc * 3. person level vis url for a particular individual * etc. * @author cdtank */ public class UtilitiesRequestHandler implements VisualizationRequestHandler { public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, Dataset dataset) throws MalformedQueryParametersException { String individualURI = vitroRequest.getParameter( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); String visMode = vitroRequest.getParameter( VisualizationFrameworkConstants.VIS_MODE_KEY); /* * If the info being requested is about a profile which includes the name, moniker * & image url. * */ if (VisualizationFrameworkConstants.PROFILE_INFO_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String filterRule = "?predicate = j.2:mainImage " + "|| ?predicate = core:preferredTitle " + "|| ?predicate = rdfs:label"; QueryRunner<GenericQueryMap> profileQueryHandler = new AllPropertiesQueryRunner(individualURI, filterRule, dataset, log); GenericQueryMap profilePropertiesToValues = profileQueryHandler.getQueryResult(); Gson profileInformation = new Gson(); return profileInformation.toJson(profilePropertiesToValues); } else if (VisualizationFrameworkConstants.IMAGE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * If the url being requested is about a standalone image, which is used when we * want to render an image & other info for a co-author OR ego for that matter. * */ Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("downloadLocation", QueryFieldLabels.THUMBNAIL_LOCATION_URL); fieldLabelToOutputFieldLabel.put("fileName", QueryFieldLabels.THUMBNAIL_FILENAME); String whereClause = "<" + individualURI + "> j.2:thumbnailImage ?thumbnailImage . " + "?thumbnailImage j.2:downloadLocation " + "?downloadLocation ; j.2:filename ?fileName ."; QueryRunner<ResultSet> imageQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, "", whereClause, "", dataset); return getThumbnailInformation(imageQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else if (VisualizationFrameworkConstants.ARE_PUBLICATIONS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?document) AS ?numOfPublications)"; String whereClause = "<" + individualURI + "> rdf:type foaf:Person ;" + " core:relatedBy ?authorshipNode . \n" + "?authorshipNode rdf:type core:Authorship ;" + " core:relates ?document . \n" + "?document rdf:type bibo:Document ."; String groupOrderClause = "GROUP BY ?" + QueryFieldLabels.AUTHOR_URL + " \n"; QueryRunner<ResultSet> numberOfPublicationsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); Gson publicationsInformation = new Gson(); return publicationsInformation.toJson(getNumberOfPublicationsForIndividual( numberOfPublicationsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.ARE_GRANTS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?Grant) AS ?numOfGrants)"; - String grantType = "http://vivoweb.org/ontology#Grant"; + String grantType = "http://vivoweb.org/ontology/core#Grant"; ObjectProperty predicate = ModelUtils.getPropertyForRoleInClass(grantType, vitroRequest.getWebappDaoFactory()); String roleToGrantPredicate = "<" + predicate.getURI() + ">"; String whereClause = "{ <" + individualURI + "> rdf:type foaf:Person ;" + " <http://purl.obolibrary.org/obo/RO_0000053> ?Role . \n" + "?Role rdf:type core:PrincipalInvestigatorRole . \n" + "?Role " + roleToGrantPredicate + " ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " <http://purl.obolibrary.org/obo/RO_0000053> ?Role . \n" + "?Role rdf:type core:CoPrincipalInvestigatorRole . \n" + "?Role " + roleToGrantPredicate + " ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " <http://purl.obolibrary.org/obo/RO_0000053> ?Role . \n" + "?Role rdf:type core:InvestigatorRole. \n" + "?Role vitro:mostSpecificType ?subclass . \n" + "?Role " + roleToGrantPredicate + " ?Grant . \n" + "FILTER (?subclass != core:PrincipalInvestigatorRole && " + "?subclass != core:CoPrincipalInvestigatorRole)}"; QueryRunner<ResultSet> numberOfGrantsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, "", dataset); Gson grantsInformation = new Gson(); return grantsInformation.toJson(getNumberOfGrantsForIndividual( numberOfGrantsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.COAUTHOR_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COAUTHORSHIP_VIS_SHORT_URL + "/" + individualLocalName; } ParamMap coAuthorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COAUTHOR_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coAuthorProfileURLParams); } else if (VisualizationFrameworkConstants.COPI_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COINVESTIGATOR_VIS_SHORT_URL + "/" + individualLocalName; } /* * By default we will be generating profile url else some specific url like * coPI vis url for that individual. * */ ParamMap coInvestigatorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COPI_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coInvestigatorProfileURLParams); } else if (VisualizationFrameworkConstants.PERSON_LEVEL_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * By default we will be generating profile url else some specific url like * coAuthorShip vis url for that individual. * */ ParamMap personLevelURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.RENDER_MODE_KEY, VisualizationFrameworkConstants.STANDALONE_RENDER_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, personLevelURLParams); } else if (VisualizationFrameworkConstants.HIGHEST_LEVEL_ORGANIZATION_VIS_MODE .equalsIgnoreCase(visMode)) { String staffProvidedHighestLevelOrganization = ConfigurationProperties .getBean(vitroRequest).getProperty("visualization.topLevelOrg"); /* * First checking if the staff has provided highest level organization in * deploy.properties if so use to temporal graph vis. * */ if (StringUtils.isNotBlank(staffProvidedHighestLevelOrganization)) { /* * To test for the validity of the URI submitted. * */ IRIFactory iRIFactory = IRIFactory.jenaImplementation(); IRI iri = iRIFactory.create(staffProvidedHighestLevelOrganization); if (iri.hasViolation(false)) { String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); log.error("Highest Level Organization URI provided is invalid " + errorMsg); } else { ParamMap highestLevelOrganizationTemporalGraphVisURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, staffProvidedHighestLevelOrganization, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.ENTITY_COMPARISON_VIS); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, highestLevelOrganizationTemporalGraphVisURLParams); } } Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("organization", QueryFieldLabels.ORGANIZATION_URL); fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); String aggregationRules = "(count(?organization) AS ?numOfChildren)"; String whereClause = "?organization rdf:type foaf:Organization ;" + " rdfs:label ?organizationLabel . \n" + "OPTIONAL { ?organization core:http://purl.obolibrary.org/obo/BFO_0000051 ?subOrg . \n" + " ?subOrg rdf:type foaf:Organization } . \n" + "OPTIONAL { ?organization core:http://purl.obolibrary.org/obo/BFO_0000050 ?parent } . \n" + " ?parent rdf:type foaf:Organization } . \n" + "FILTER ( !bound(?parent) ). \n"; String groupOrderClause = "GROUP BY ?organization ?organizationLabel \n" + "ORDER BY DESC(?numOfChildren)\n" + "LIMIT 1\n"; QueryRunner<ResultSet> highestLevelOrganizationQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); return getHighestLevelOrganizationTemporalGraphVisURL( highestLevelOrganizationQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else { ParamMap individualProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI); return UrlBuilder.getUrl(VisualizationFrameworkConstants.INDIVIDUAL_URL_PREFIX, individualProfileURLParams); } } private String getHighestLevelOrganizationTemporalGraphVisURL(ResultSet resultSet, Map<String, String> fieldLabelToOutputFieldLabel, VitroRequest vitroRequest) { GenericQueryMap queryResult = new GenericQueryMap(); while (resultSet.hasNext()) { QuerySolution solution = resultSet.nextSolution(); RDFNode organizationNode = solution.get( fieldLabelToOutputFieldLabel .get("organization")); if (organizationNode != null) { queryResult.addEntry(fieldLabelToOutputFieldLabel.get("organization"), organizationNode.toString()); String individualLocalName = UtilityFunctions.getIndividualLocalName( organizationNode.toString(), vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.PUBLICATION_TEMPORAL_VIS_SHORT_URL + "/" + individualLocalName; } ParamMap highestLevelOrganizationTemporalGraphVisURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, organizationNode.toString(), VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.ENTITY_COMPARISON_VIS); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, highestLevelOrganizationTemporalGraphVisURLParams); } RDFNode organizationLabelNode = solution.get( fieldLabelToOutputFieldLabel .get("organizationLabel")); if (organizationLabelNode != null) { queryResult.addEntry(fieldLabelToOutputFieldLabel.get("organizationLabel"), organizationLabelNode.toString()); } RDFNode numberOfChildrenNode = solution.getLiteral("numOfChildren"); if (numberOfChildrenNode != null) { queryResult.addEntry("numOfChildren", String.valueOf(numberOfChildrenNode.asLiteral().getInt())); } } return ""; } private GenericQueryMap getNumberOfGrantsForIndividual(ResultSet resultSet) { GenericQueryMap queryResult = new GenericQueryMap(); while (resultSet.hasNext()) { QuerySolution solution = resultSet.nextSolution(); RDFNode numberOfGrantsNode = solution.getLiteral("numOfGrants"); if (numberOfGrantsNode != null) { queryResult.addEntry("numOfGrants", String.valueOf(numberOfGrantsNode.asLiteral().getInt())); } } return queryResult; } private GenericQueryMap getNumberOfPublicationsForIndividual(ResultSet resultSet) { GenericQueryMap queryResult = new GenericQueryMap(); while (resultSet.hasNext()) { QuerySolution solution = resultSet.nextSolution(); RDFNode numberOfPublicationsNode = solution.getLiteral("numOfPublications"); if (numberOfPublicationsNode != null) { queryResult.addEntry( "numOfPublications", String.valueOf(numberOfPublicationsNode.asLiteral().getInt())); } } return queryResult; } private String getThumbnailInformation(ResultSet resultSet, Map<String, String> fieldLabelToOutputFieldLabel, VitroRequest vitroRequest) { String finalThumbNailLocation = ""; while (resultSet.hasNext()) { QuerySolution solution = resultSet.nextSolution(); RDFNode downloadLocationNode = solution.get( fieldLabelToOutputFieldLabel .get("downloadLocation")); RDFNode fileNameNode = solution.get(fieldLabelToOutputFieldLabel.get("fileName")); if (downloadLocationNode != null && fileNameNode != null) { finalThumbNailLocation = FileServingHelper .getBytestreamAliasUrl(downloadLocationNode.toString(), fileNameNode.toString(), vitroRequest.getSession().getServletContext()); } } return finalThumbNailLocation; } @Override public Map<String, String> generateDataVisualization( VitroRequest vitroRequest, Log log, Dataset dataset) throws MalformedQueryParametersException { throw new UnsupportedOperationException("Utilities does not provide Data Response."); } @Override public ResponseValues generateStandardVisualization( VitroRequest vitroRequest, Log log, Dataset dataset) throws MalformedQueryParametersException { throw new UnsupportedOperationException("Utilities does not provide Standard Response."); } @Override public ResponseValues generateVisualizationForShortURLRequests( Map<String, String> parameters, VitroRequest vitroRequest, Log log, Dataset dataSource) throws MalformedQueryParametersException { throw new UnsupportedOperationException("Utilities Visualization does not provide " + "Short URL Response."); } @Override public Actions getRequiredPrivileges() { // TODO Auto-generated method stub return null; } }
true
true
public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, Dataset dataset) throws MalformedQueryParametersException { String individualURI = vitroRequest.getParameter( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); String visMode = vitroRequest.getParameter( VisualizationFrameworkConstants.VIS_MODE_KEY); /* * If the info being requested is about a profile which includes the name, moniker * & image url. * */ if (VisualizationFrameworkConstants.PROFILE_INFO_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String filterRule = "?predicate = j.2:mainImage " + "|| ?predicate = core:preferredTitle " + "|| ?predicate = rdfs:label"; QueryRunner<GenericQueryMap> profileQueryHandler = new AllPropertiesQueryRunner(individualURI, filterRule, dataset, log); GenericQueryMap profilePropertiesToValues = profileQueryHandler.getQueryResult(); Gson profileInformation = new Gson(); return profileInformation.toJson(profilePropertiesToValues); } else if (VisualizationFrameworkConstants.IMAGE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * If the url being requested is about a standalone image, which is used when we * want to render an image & other info for a co-author OR ego for that matter. * */ Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("downloadLocation", QueryFieldLabels.THUMBNAIL_LOCATION_URL); fieldLabelToOutputFieldLabel.put("fileName", QueryFieldLabels.THUMBNAIL_FILENAME); String whereClause = "<" + individualURI + "> j.2:thumbnailImage ?thumbnailImage . " + "?thumbnailImage j.2:downloadLocation " + "?downloadLocation ; j.2:filename ?fileName ."; QueryRunner<ResultSet> imageQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, "", whereClause, "", dataset); return getThumbnailInformation(imageQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else if (VisualizationFrameworkConstants.ARE_PUBLICATIONS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?document) AS ?numOfPublications)"; String whereClause = "<" + individualURI + "> rdf:type foaf:Person ;" + " core:relatedBy ?authorshipNode . \n" + "?authorshipNode rdf:type core:Authorship ;" + " core:relates ?document . \n" + "?document rdf:type bibo:Document ."; String groupOrderClause = "GROUP BY ?" + QueryFieldLabels.AUTHOR_URL + " \n"; QueryRunner<ResultSet> numberOfPublicationsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); Gson publicationsInformation = new Gson(); return publicationsInformation.toJson(getNumberOfPublicationsForIndividual( numberOfPublicationsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.ARE_GRANTS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?Grant) AS ?numOfGrants)"; String grantType = "http://vivoweb.org/ontology#Grant"; ObjectProperty predicate = ModelUtils.getPropertyForRoleInClass(grantType, vitroRequest.getWebappDaoFactory()); String roleToGrantPredicate = "<" + predicate.getURI() + ">"; String whereClause = "{ <" + individualURI + "> rdf:type foaf:Person ;" + " <http://purl.obolibrary.org/obo/RO_0000053> ?Role . \n" + "?Role rdf:type core:PrincipalInvestigatorRole . \n" + "?Role " + roleToGrantPredicate + " ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " <http://purl.obolibrary.org/obo/RO_0000053> ?Role . \n" + "?Role rdf:type core:CoPrincipalInvestigatorRole . \n" + "?Role " + roleToGrantPredicate + " ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " <http://purl.obolibrary.org/obo/RO_0000053> ?Role . \n" + "?Role rdf:type core:InvestigatorRole. \n" + "?Role vitro:mostSpecificType ?subclass . \n" + "?Role " + roleToGrantPredicate + " ?Grant . \n" + "FILTER (?subclass != core:PrincipalInvestigatorRole && " + "?subclass != core:CoPrincipalInvestigatorRole)}"; QueryRunner<ResultSet> numberOfGrantsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, "", dataset); Gson grantsInformation = new Gson(); return grantsInformation.toJson(getNumberOfGrantsForIndividual( numberOfGrantsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.COAUTHOR_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COAUTHORSHIP_VIS_SHORT_URL + "/" + individualLocalName; } ParamMap coAuthorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COAUTHOR_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coAuthorProfileURLParams); } else if (VisualizationFrameworkConstants.COPI_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COINVESTIGATOR_VIS_SHORT_URL + "/" + individualLocalName; } /* * By default we will be generating profile url else some specific url like * coPI vis url for that individual. * */ ParamMap coInvestigatorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COPI_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coInvestigatorProfileURLParams); } else if (VisualizationFrameworkConstants.PERSON_LEVEL_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * By default we will be generating profile url else some specific url like * coAuthorShip vis url for that individual. * */ ParamMap personLevelURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.RENDER_MODE_KEY, VisualizationFrameworkConstants.STANDALONE_RENDER_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, personLevelURLParams); } else if (VisualizationFrameworkConstants.HIGHEST_LEVEL_ORGANIZATION_VIS_MODE .equalsIgnoreCase(visMode)) { String staffProvidedHighestLevelOrganization = ConfigurationProperties .getBean(vitroRequest).getProperty("visualization.topLevelOrg"); /* * First checking if the staff has provided highest level organization in * deploy.properties if so use to temporal graph vis. * */ if (StringUtils.isNotBlank(staffProvidedHighestLevelOrganization)) { /* * To test for the validity of the URI submitted. * */ IRIFactory iRIFactory = IRIFactory.jenaImplementation(); IRI iri = iRIFactory.create(staffProvidedHighestLevelOrganization); if (iri.hasViolation(false)) { String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); log.error("Highest Level Organization URI provided is invalid " + errorMsg); } else { ParamMap highestLevelOrganizationTemporalGraphVisURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, staffProvidedHighestLevelOrganization, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.ENTITY_COMPARISON_VIS); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, highestLevelOrganizationTemporalGraphVisURLParams); } } Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("organization", QueryFieldLabels.ORGANIZATION_URL); fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); String aggregationRules = "(count(?organization) AS ?numOfChildren)"; String whereClause = "?organization rdf:type foaf:Organization ;" + " rdfs:label ?organizationLabel . \n" + "OPTIONAL { ?organization core:http://purl.obolibrary.org/obo/BFO_0000051 ?subOrg . \n" + " ?subOrg rdf:type foaf:Organization } . \n" + "OPTIONAL { ?organization core:http://purl.obolibrary.org/obo/BFO_0000050 ?parent } . \n" + " ?parent rdf:type foaf:Organization } . \n" + "FILTER ( !bound(?parent) ). \n"; String groupOrderClause = "GROUP BY ?organization ?organizationLabel \n" + "ORDER BY DESC(?numOfChildren)\n" + "LIMIT 1\n"; QueryRunner<ResultSet> highestLevelOrganizationQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); return getHighestLevelOrganizationTemporalGraphVisURL( highestLevelOrganizationQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else { ParamMap individualProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI); return UrlBuilder.getUrl(VisualizationFrameworkConstants.INDIVIDUAL_URL_PREFIX, individualProfileURLParams); } }
public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, Dataset dataset) throws MalformedQueryParametersException { String individualURI = vitroRequest.getParameter( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); String visMode = vitroRequest.getParameter( VisualizationFrameworkConstants.VIS_MODE_KEY); /* * If the info being requested is about a profile which includes the name, moniker * & image url. * */ if (VisualizationFrameworkConstants.PROFILE_INFO_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String filterRule = "?predicate = j.2:mainImage " + "|| ?predicate = core:preferredTitle " + "|| ?predicate = rdfs:label"; QueryRunner<GenericQueryMap> profileQueryHandler = new AllPropertiesQueryRunner(individualURI, filterRule, dataset, log); GenericQueryMap profilePropertiesToValues = profileQueryHandler.getQueryResult(); Gson profileInformation = new Gson(); return profileInformation.toJson(profilePropertiesToValues); } else if (VisualizationFrameworkConstants.IMAGE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * If the url being requested is about a standalone image, which is used when we * want to render an image & other info for a co-author OR ego for that matter. * */ Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("downloadLocation", QueryFieldLabels.THUMBNAIL_LOCATION_URL); fieldLabelToOutputFieldLabel.put("fileName", QueryFieldLabels.THUMBNAIL_FILENAME); String whereClause = "<" + individualURI + "> j.2:thumbnailImage ?thumbnailImage . " + "?thumbnailImage j.2:downloadLocation " + "?downloadLocation ; j.2:filename ?fileName ."; QueryRunner<ResultSet> imageQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, "", whereClause, "", dataset); return getThumbnailInformation(imageQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else if (VisualizationFrameworkConstants.ARE_PUBLICATIONS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?document) AS ?numOfPublications)"; String whereClause = "<" + individualURI + "> rdf:type foaf:Person ;" + " core:relatedBy ?authorshipNode . \n" + "?authorshipNode rdf:type core:Authorship ;" + " core:relates ?document . \n" + "?document rdf:type bibo:Document ."; String groupOrderClause = "GROUP BY ?" + QueryFieldLabels.AUTHOR_URL + " \n"; QueryRunner<ResultSet> numberOfPublicationsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); Gson publicationsInformation = new Gson(); return publicationsInformation.toJson(getNumberOfPublicationsForIndividual( numberOfPublicationsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.ARE_GRANTS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?Grant) AS ?numOfGrants)"; String grantType = "http://vivoweb.org/ontology/core#Grant"; ObjectProperty predicate = ModelUtils.getPropertyForRoleInClass(grantType, vitroRequest.getWebappDaoFactory()); String roleToGrantPredicate = "<" + predicate.getURI() + ">"; String whereClause = "{ <" + individualURI + "> rdf:type foaf:Person ;" + " <http://purl.obolibrary.org/obo/RO_0000053> ?Role . \n" + "?Role rdf:type core:PrincipalInvestigatorRole . \n" + "?Role " + roleToGrantPredicate + " ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " <http://purl.obolibrary.org/obo/RO_0000053> ?Role . \n" + "?Role rdf:type core:CoPrincipalInvestigatorRole . \n" + "?Role " + roleToGrantPredicate + " ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " <http://purl.obolibrary.org/obo/RO_0000053> ?Role . \n" + "?Role rdf:type core:InvestigatorRole. \n" + "?Role vitro:mostSpecificType ?subclass . \n" + "?Role " + roleToGrantPredicate + " ?Grant . \n" + "FILTER (?subclass != core:PrincipalInvestigatorRole && " + "?subclass != core:CoPrincipalInvestigatorRole)}"; QueryRunner<ResultSet> numberOfGrantsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, "", dataset); Gson grantsInformation = new Gson(); return grantsInformation.toJson(getNumberOfGrantsForIndividual( numberOfGrantsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.COAUTHOR_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COAUTHORSHIP_VIS_SHORT_URL + "/" + individualLocalName; } ParamMap coAuthorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COAUTHOR_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coAuthorProfileURLParams); } else if (VisualizationFrameworkConstants.COPI_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COINVESTIGATOR_VIS_SHORT_URL + "/" + individualLocalName; } /* * By default we will be generating profile url else some specific url like * coPI vis url for that individual. * */ ParamMap coInvestigatorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COPI_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coInvestigatorProfileURLParams); } else if (VisualizationFrameworkConstants.PERSON_LEVEL_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * By default we will be generating profile url else some specific url like * coAuthorShip vis url for that individual. * */ ParamMap personLevelURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.RENDER_MODE_KEY, VisualizationFrameworkConstants.STANDALONE_RENDER_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, personLevelURLParams); } else if (VisualizationFrameworkConstants.HIGHEST_LEVEL_ORGANIZATION_VIS_MODE .equalsIgnoreCase(visMode)) { String staffProvidedHighestLevelOrganization = ConfigurationProperties .getBean(vitroRequest).getProperty("visualization.topLevelOrg"); /* * First checking if the staff has provided highest level organization in * deploy.properties if so use to temporal graph vis. * */ if (StringUtils.isNotBlank(staffProvidedHighestLevelOrganization)) { /* * To test for the validity of the URI submitted. * */ IRIFactory iRIFactory = IRIFactory.jenaImplementation(); IRI iri = iRIFactory.create(staffProvidedHighestLevelOrganization); if (iri.hasViolation(false)) { String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); log.error("Highest Level Organization URI provided is invalid " + errorMsg); } else { ParamMap highestLevelOrganizationTemporalGraphVisURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, staffProvidedHighestLevelOrganization, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.ENTITY_COMPARISON_VIS); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, highestLevelOrganizationTemporalGraphVisURLParams); } } Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("organization", QueryFieldLabels.ORGANIZATION_URL); fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); String aggregationRules = "(count(?organization) AS ?numOfChildren)"; String whereClause = "?organization rdf:type foaf:Organization ;" + " rdfs:label ?organizationLabel . \n" + "OPTIONAL { ?organization core:http://purl.obolibrary.org/obo/BFO_0000051 ?subOrg . \n" + " ?subOrg rdf:type foaf:Organization } . \n" + "OPTIONAL { ?organization core:http://purl.obolibrary.org/obo/BFO_0000050 ?parent } . \n" + " ?parent rdf:type foaf:Organization } . \n" + "FILTER ( !bound(?parent) ). \n"; String groupOrderClause = "GROUP BY ?organization ?organizationLabel \n" + "ORDER BY DESC(?numOfChildren)\n" + "LIMIT 1\n"; QueryRunner<ResultSet> highestLevelOrganizationQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); return getHighestLevelOrganizationTemporalGraphVisURL( highestLevelOrganizationQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else { ParamMap individualProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI); return UrlBuilder.getUrl(VisualizationFrameworkConstants.INDIVIDUAL_URL_PREFIX, individualProfileURLParams); } }
diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java index d1d8785e4..a6553b59a 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java @@ -1,1029 +1,1029 @@ /******************************************************************************* * Copyright (c) 2000, 2005 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.jface.text.source; import java.util.Stack; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Layout; import org.eclipse.jface.internal.text.NonDeletingPositionUpdater; import org.eclipse.jface.internal.text.source.TextInvocationContext; import org.eclipse.jface.text.AbstractHoverInformationControlManager; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DocumentRewriteSession; import org.eclipse.jface.text.DocumentRewriteSessionType; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension4; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ISlaveDocumentManager; import org.eclipse.jface.text.ISlaveDocumentManagerExtension; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextViewer; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.formatter.FormattingContext; import org.eclipse.jface.text.formatter.FormattingContextProperties; import org.eclipse.jface.text.formatter.IContentFormatter; import org.eclipse.jface.text.formatter.IContentFormatterExtension; import org.eclipse.jface.text.formatter.IFormattingContext; import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; import org.eclipse.jface.text.information.IInformationPresenter; import org.eclipse.jface.text.presentation.IPresentationReconciler; import org.eclipse.jface.text.projection.ChildDocument; import org.eclipse.jface.text.quickassist.IQuickAssistAssistant; import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext; import org.eclipse.jface.text.reconciler.IReconciler; /** * SWT based implementation of * {@link org.eclipse.jface.text.source.ISourceViewer} and its extension * interfaces. The same rules apply as for * {@link org.eclipse.jface.text.TextViewer}. A source viewer uses an * <code>IVerticalRuler</code> as its annotation presentation area. The * vertical ruler is a small strip shown left of the viewer's text widget. A * source viewer uses an <code>IOverviewRuler</code> as its presentation area * for the annotation overview. The overview ruler is a small strip shown right * of the viewer's text widget. * <p> * Clients are supposed to instantiate a source viewer and subsequently to * communicate with it exclusively using the <code>ISourceViewer</code> * interface.</p> * <p> * Clients may subclass this class but should expect some breakage by future releases.</p> */ public class SourceViewer extends TextViewer implements ISourceViewer, ISourceViewerExtension, ISourceViewerExtension2, ISourceViewerExtension3 { /** * Layout of a source viewer. Vertical ruler, text widget, and overview ruler are shown side by side. */ protected class RulerLayout extends Layout { /** The gap between the text viewer and the vertical ruler. */ protected int fGap; /** * Creates a new ruler layout with the given gap between text viewer and vertical ruler. * * @param gap the gap between text viewer and vertical ruler */ public RulerLayout(int gap) { fGap= gap; } /* * @see Layout#computeSize(Composite, int, int, boolean) */ protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) { Control[] children= composite.getChildren(); Point s= children[children.length - 1].computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache); if (fVerticalRuler != null && fIsVerticalRulerVisible) s.x += fVerticalRuler.getWidth() + fGap; return s; } /* * @see Layout#layout(Composite, boolean) */ protected void layout(Composite composite, boolean flushCache) { Rectangle clArea= composite.getClientArea(); Rectangle trim= getTextWidget().computeTrim(0, 0, 0, 0); int topTrim= - trim.y; int scrollbarHeight= trim.height - topTrim; // scrollbar is only under the client area int x= clArea.x; int width= clArea.width; if (fOverviewRuler != null && fIsOverviewRulerVisible) { int overviewRulerWidth= fOverviewRuler.getWidth(); fOverviewRuler.getControl().setBounds(clArea.x + clArea.width - overviewRulerWidth - 1, clArea.y + scrollbarHeight, overviewRulerWidth, clArea.height - 3*scrollbarHeight); fOverviewRuler.getHeaderControl().setBounds(clArea.x + clArea.width - overviewRulerWidth - 1, clArea.y, overviewRulerWidth, scrollbarHeight); width -= overviewRulerWidth + fGap; } if (fVerticalRuler != null && fIsVerticalRulerVisible) { int verticalRulerWidth= fVerticalRuler.getWidth(); fVerticalRuler.getControl().setBounds(clArea.x, clArea.y + topTrim, verticalRulerWidth, clArea.height - scrollbarHeight - topTrim); x += verticalRulerWidth + fGap; width -= verticalRulerWidth + fGap; } getTextWidget().setBounds(x, clArea.y, width, clArea.height); } } /** * The size of the gap between the vertical ruler and the text widget * (value <code>2</code>). * <p> * Note: As of 3.2, the text editor framework is no longer using 2 as * gap but 1, see {{@link #GAP_SIZE_1 }. * </p> */ protected final static int GAP_SIZE= 2; /** * The size of the gap between the vertical ruler and the text widget * (value <code>1</code>). * @since 3.2 */ protected final static int GAP_SIZE_1= 1; /** * Partial name of the position category to manage remembered selections. * @since 3.0 */ protected final static String _SELECTION_POSITION_CATEGORY= "__selection_category"; //$NON-NLS-1$ /** * Key of the model annotation model inside the visual annotation model. * @since 3.0 */ protected final static Object MODEL_ANNOTATION_MODEL= new Object(); /** The viewer's content assistant */ protected IContentAssistant fContentAssistant; /** * Flag indicating whether the viewer's content assistant is installed. * @since 2.0 */ protected boolean fContentAssistantInstalled; /** * This viewer's quick assist assistant. * @since 3.2 */ protected IQuickAssistAssistant fQuickAssistAssistant; /** * Flag indicating whether this viewer's quick assist assistant is installed. * @since 3.2 */ protected boolean fQuickAssistAssistantInstalled; /** The viewer's content formatter */ protected IContentFormatter fContentFormatter; /** The viewer's model reconciler */ protected IReconciler fReconciler; /** The viewer's presentation reconciler */ protected IPresentationReconciler fPresentationReconciler; /** The viewer's annotation hover */ protected IAnnotationHover fAnnotationHover; /** * Stack of saved selections in the underlying document * @since 3.0 */ protected final Stack fSelections= new Stack(); /** * Position updater for saved selections * @since 3.0 */ protected IPositionUpdater fSelectionUpdater= null; /** * Position category used by the selection updater * @since 3.0 */ protected String fSelectionCategory; /** * The viewer's overview ruler annotation hover * @since 3.0 */ protected IAnnotationHover fOverviewRulerAnnotationHover; /** * The viewer's information presenter * @since 2.0 */ protected IInformationPresenter fInformationPresenter; /** Visual vertical ruler */ private IVerticalRuler fVerticalRuler; /** Visibility of vertical ruler */ private boolean fIsVerticalRulerVisible; /** The SWT widget used when supporting a vertical ruler */ private Composite fComposite; /** The vertical ruler's annotation model */ private IAnnotationModel fVisualAnnotationModel; /** The viewer's range indicator to be shown in the vertical ruler */ private Annotation fRangeIndicator; /** The viewer's vertical ruler hovering controller */ private AbstractHoverInformationControlManager fVerticalRulerHoveringController; /** * The viewer's overview ruler hovering controller * @since 2.1 */ private AbstractHoverInformationControlManager fOverviewRulerHoveringController; /** * The overview ruler. * @since 2.1 */ private IOverviewRuler fOverviewRuler; /** * The visibility of the overview ruler * @since 2.1 */ private boolean fIsOverviewRulerVisible; /** * Constructs a new source viewer. The vertical ruler is initially visible. * The viewer has not yet been initialized with a source viewer configuration. * * @param parent the parent of the viewer's control * @param ruler the vertical ruler used by this source viewer * @param styles the SWT style bits */ public SourceViewer(Composite parent, IVerticalRuler ruler, int styles) { this(parent, ruler, null, false, styles); } /** * Constructs a new source viewer. The vertical ruler is initially visible. * The overview ruler visibility is controlled by the value of <code>showAnnotationsOverview</code>. * The viewer has not yet been initialized with a source viewer configuration. * * @param parent the parent of the viewer's control * @param verticalRuler the vertical ruler used by this source viewer * @param overviewRuler the overview ruler * @param showAnnotationsOverview <code>true</code> if the overview ruler should be visible, <code>false</code> otherwise * @param styles the SWT style bits * @since 2.1 */ public SourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) { super(); fVerticalRuler= verticalRuler; fIsVerticalRulerVisible= (verticalRuler != null); fOverviewRuler= overviewRuler; fIsOverviewRulerVisible= (showAnnotationsOverview && overviewRuler != null); createControl(parent, styles); } /* * @see TextViewer#createControl(Composite, int) */ protected void createControl(Composite parent, int styles) { if (fVerticalRuler != null || fOverviewRuler != null) { styles= (styles & ~SWT.BORDER); fComposite= new Canvas(parent, SWT.NONE); fComposite.setLayout(createLayout()); parent= fComposite; } super.createControl(parent, styles); if (fVerticalRuler != null) fVerticalRuler.createControl(fComposite, this); if (fOverviewRuler != null) fOverviewRuler.createControl(fComposite, this); } /** * Creates the layout used for this viewer. * Subclasses may override this method. * * @return the layout used for this viewer * @since 3.0 */ protected Layout createLayout() { return new RulerLayout(GAP_SIZE_1); } /* * @see TextViewer#getControl() */ public Control getControl() { if (fComposite != null) return fComposite; return super.getControl(); } /* * @see ISourceViewer#setAnnotationHover(IAnnotationHover) */ public void setAnnotationHover(IAnnotationHover annotationHover) { fAnnotationHover= annotationHover; } /** * Sets the overview ruler's annotation hover of this source viewer. * The annotation hover provides the information to be displayed in a hover * popup window if requested over the overview rulers area. The annotation * hover is assumed to be line oriented. * * @param annotationHover the hover to be used, <code>null</code> is a valid argument * @since 3.0 */ public void setOverviewRulerAnnotationHover(IAnnotationHover annotationHover) { fOverviewRulerAnnotationHover= annotationHover; } /* * @see ISourceViewer#configure(SourceViewerConfiguration) */ public void configure(SourceViewerConfiguration configuration) { if (getTextWidget() == null) return; setDocumentPartitioning(configuration.getConfiguredDocumentPartitioning(this)); // install content type independent plug-ins fPresentationReconciler= configuration.getPresentationReconciler(this); if (fPresentationReconciler != null) fPresentationReconciler.install(this); fReconciler= configuration.getReconciler(this); if (fReconciler != null) fReconciler.install(this); fContentAssistant= configuration.getContentAssistant(this); if (fContentAssistant != null) { fContentAssistant.install(this); fContentAssistantInstalled= true; } fQuickAssistAssistant= configuration.getQuickAssistAssistant(this); if (fQuickAssistAssistant != null) { fQuickAssistAssistant.install(this); fQuickAssistAssistantInstalled= true; } fContentFormatter= configuration.getContentFormatter(this); fInformationPresenter= configuration.getInformationPresenter(this); if (fInformationPresenter != null) fInformationPresenter.install(this); setUndoManager(configuration.getUndoManager(this)); getTextWidget().setTabs(configuration.getTabWidth(this)); setAnnotationHover(configuration.getAnnotationHover(this)); setOverviewRulerAnnotationHover(configuration.getOverviewRulerAnnotationHover(this)); setHoverControlCreator(configuration.getInformationControlCreator(this)); setHyperlinkPresenter(configuration.getHyperlinkPresenter(this)); IHyperlinkDetector[] hyperlinkDetectors= configuration.getHyperlinkDetectors(this); int eventStateMask= configuration.getHyperlinkStateMask(this); setHyperlinkDetectors(hyperlinkDetectors, eventStateMask); // install content type specific plug-ins String[] types= configuration.getConfiguredContentTypes(this); for (int i= 0; i < types.length; i++) { String t= types[i]; setAutoEditStrategies(configuration.getAutoEditStrategies(this, t), t); setTextDoubleClickStrategy(configuration.getDoubleClickStrategy(this, t), t); int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(this, t); if (stateMasks != null) { for (int j= 0; j < stateMasks.length; j++) { int stateMask= stateMasks[j]; setTextHover(configuration.getTextHover(this, t, stateMask), t, stateMask); } } else { setTextHover(configuration.getTextHover(this, t), t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } String[] prefixes= configuration.getIndentPrefixes(this, t); if (prefixes != null && prefixes.length > 0) setIndentPrefixes(prefixes, t); prefixes= configuration.getDefaultPrefixes(this, t); if (prefixes != null && prefixes.length > 0) setDefaultPrefixes(prefixes, t); } activatePlugins(); } /** * After this method has been executed the caller knows that any installed annotation hover has been installed. */ protected void ensureAnnotationHoverManagerInstalled() { if (fVerticalRuler != null && fAnnotationHover != null && fVerticalRulerHoveringController == null && fHoverControlCreator != null) { fVerticalRulerHoveringController= new AnnotationBarHoverManager(fVerticalRuler, this, fAnnotationHover, fHoverControlCreator); fVerticalRulerHoveringController.install(fVerticalRuler.getControl()); } } /** * After this method has been executed the caller knows that any installed overview hover has been installed. */ protected void ensureOverviewHoverManagerInstalled() { if (fOverviewRuler != null && fOverviewRulerAnnotationHover != null && fOverviewRulerHoveringController == null && fHoverControlCreator != null) { fOverviewRulerHoveringController= new OverviewRulerHoverManager(fOverviewRuler, this, fOverviewRulerAnnotationHover, fHoverControlCreator); fOverviewRulerHoveringController.install(fOverviewRuler.getControl()); } } /* * @see TextViewer#activatePlugins() */ public void activatePlugins() { ensureAnnotationHoverManagerInstalled(); ensureOverviewHoverManagerInstalled(); super.activatePlugins(); } /* * @see ISourceViewer#setDocument(IDocument, IAnnotationModel) */ public void setDocument(IDocument document) { setDocument(document, null, -1, -1); } /* * @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int) */ public void setDocument(IDocument document, int visibleRegionOffset, int visibleRegionLength) { setDocument(document, null, visibleRegionOffset, visibleRegionLength); } /* * @see ISourceViewer#setDocument(IDocument, IAnnotationModel) */ public void setDocument(IDocument document, IAnnotationModel annotationModel) { setDocument(document, annotationModel, -1, -1); } /** * Creates the visual annotation model on top of the given annotation model. * * @param annotationModel the wrapped annotation model * @return the visual annotation model on top of the given annotation model * @since 3.0 */ protected IAnnotationModel createVisualAnnotationModel(IAnnotationModel annotationModel) { IAnnotationModelExtension model= new AnnotationModel(); model.addAnnotationModel(MODEL_ANNOTATION_MODEL, annotationModel); return (IAnnotationModel) model; } /** * Disposes the visual annotation model. * * @since 3.1 */ protected void disposeVisualAnnotationModel() { if (fVisualAnnotationModel != null) { if (getDocument() != null) fVisualAnnotationModel.disconnect(getDocument()); if ( fVisualAnnotationModel instanceof IAnnotationModelExtension) ((IAnnotationModelExtension)fVisualAnnotationModel).removeAnnotationModel(MODEL_ANNOTATION_MODEL); fVisualAnnotationModel= null; } } /* * @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int) */ public void setDocument(IDocument document, IAnnotationModel annotationModel, int modelRangeOffset, int modelRangeLength) { if (fVerticalRuler == null && fOverviewRuler == null) { if (modelRangeOffset == -1 && modelRangeLength == -1) super.setDocument(document); else super.setDocument(document, modelRangeOffset, modelRangeLength); } else { disposeVisualAnnotationModel(); if (annotationModel != null && document != null) { fVisualAnnotationModel= createVisualAnnotationModel(annotationModel); fVisualAnnotationModel.connect(document); } if (modelRangeOffset == -1 && modelRangeLength == -1) super.setDocument(document); else super.setDocument(document, modelRangeOffset, modelRangeLength); if (fVerticalRuler != null) fVerticalRuler.setModel(fVisualAnnotationModel); if (fOverviewRuler != null) fOverviewRuler.setModel(fVisualAnnotationModel); } } /* * @see ISourceViewer#getAnnotationModel() */ public IAnnotationModel getAnnotationModel() { if (fVisualAnnotationModel instanceof IAnnotationModelExtension) { IAnnotationModelExtension extension= (IAnnotationModelExtension) fVisualAnnotationModel; return extension.getAnnotationModel(MODEL_ANNOTATION_MODEL); } return null; } /* * @see org.eclipse.jface.text.source.ISourceViewerExtension3#getQuickAssistAssistant() * @since 3.2 */ public IQuickAssistAssistant getQuickAssistAssistant() { return fQuickAssistAssistant; } /* * @see org.eclipse.jface.text.source.ISourceViewerExtension3#getQuickAssistInvocationContext() * @since 3.2 */ public IQuickAssistInvocationContext getQuickAssistInvocationContext() { Point selection= getSelectedRange(); return new TextInvocationContext(this, selection.x, selection.x); } /* * @see org.eclipse.jface.text.source.ISourceViewerExtension2#getVisualAnnotationModel() * @since 3.0 */ public IAnnotationModel getVisualAnnotationModel() { return fVisualAnnotationModel; } /* * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure() * @since 3.0 */ public void unconfigure() { clearRememberedSelection(); if (fPresentationReconciler != null) { fPresentationReconciler.uninstall(); fPresentationReconciler= null; } if (fReconciler != null) { fReconciler.uninstall(); fReconciler= null; } if (fContentAssistant != null) { fContentAssistant.uninstall(); fContentAssistantInstalled= false; fContentAssistant= null; } if (fQuickAssistAssistant != null) { fQuickAssistAssistant.uninstall(); fQuickAssistAssistantInstalled= false; fQuickAssistAssistant= null; } fContentFormatter= null; if (fInformationPresenter != null) { fInformationPresenter.uninstall(); fInformationPresenter= null; } fAutoIndentStrategies= null; fDoubleClickStrategies= null; fTextHovers= null; fIndentChars= null; fDefaultPrefixChars= null; if (fVerticalRulerHoveringController != null) { fVerticalRulerHoveringController.dispose(); fVerticalRulerHoveringController= null; } if (fOverviewRulerHoveringController != null) { fOverviewRulerHoveringController.dispose(); fOverviewRulerHoveringController= null; } if (fUndoManager != null) { fUndoManager.disconnect(); fUndoManager= null; } setHyperlinkDetectors(null, SWT.NONE); } /* * @see org.eclipse.jface.text.TextViewer#handleDispose() */ protected void handleDispose() { unconfigure(); disposeVisualAnnotationModel(); fVerticalRuler= null; fOverviewRuler= null; // http://dev.eclipse.org/bugs/show_bug.cgi?id=15300 fComposite= null; super.handleDispose(); } /* * @see ITextOperationTarget#canDoOperation(int) */ public boolean canDoOperation(int operation) { if (getTextWidget() == null || (!redraws() && operation != FORMAT)) return false; if (operation == CONTENTASSIST_PROPOSALS) return fContentAssistant != null && fContentAssistantInstalled && isEditable(); if (operation == CONTENTASSIST_CONTEXT_INFORMATION) return fContentAssistant != null && fContentAssistantInstalled && isEditable(); if (operation == QUICK_ASSIST) return fQuickAssistAssistant != null && fQuickAssistAssistantInstalled && isEditable(); if (operation == INFORMATION) return fInformationPresenter != null; if (operation == FORMAT) { return fContentFormatter != null && isEditable(); } return super.canDoOperation(operation); } /** * Creates a new formatting context for a format operation. * <p> * After the use of the context, clients are required to call * its <code>dispose</code> method. * * @return The new formatting context * @since 3.0 */ protected IFormattingContext createFormattingContext() { return new FormattingContext(); } /** * Remembers and returns the current selection. The saved selection can be restored * by calling <code>restoreSelection()</code>. * * @return the current selection * @see org.eclipse.jface.text.ITextViewer#getSelectedRange() * @since 3.0 */ protected Point rememberSelection() { final Point selection= getSelectedRange(); final IDocument document= getDocument(); if (fSelections.isEmpty()) { fSelectionCategory= _SELECTION_POSITION_CATEGORY + hashCode(); fSelectionUpdater= new NonDeletingPositionUpdater(fSelectionCategory); document.addPositionCategory(fSelectionCategory); document.addPositionUpdater(fSelectionUpdater); } try { final Position position= new Position(selection.x, selection.y); document.addPosition(fSelectionCategory, position); fSelections.push(position); } catch (BadLocationException exception) { // Should not happen } catch (BadPositionCategoryException exception) { // Should not happen } return selection; } /** * Restores a previously saved selection in the document. * <p> * If no selection was previously saved, nothing happens. * * @since 3.0 */ protected void restoreSelection() { if (!fSelections.isEmpty()) { final IDocument document= getDocument(); final Position position= (Position) fSelections.pop(); try { document.removePosition(fSelectionCategory, position); Point currentSelection= getSelectedRange(); if (currentSelection == null || currentSelection.x != position.getOffset() || currentSelection.y != position.getLength()) setSelectedRange(position.getOffset(), position.getLength()); if (fSelections.isEmpty()) clearRememberedSelection(); } catch (BadPositionCategoryException exception) { // Should not happen } } } protected void clearRememberedSelection() { if (!fSelections.isEmpty()) fSelections.clear(); IDocument document= getDocument(); if (document != null && fSelectionUpdater != null) { document.removePositionUpdater(fSelectionUpdater); try { document.removePositionCategory(fSelectionCategory); } catch (BadPositionCategoryException e) { // ignore } } fSelectionUpdater= null; fSelectionCategory= null; } /* * @see ITextOperationTarget#doOperation(int) */ public void doOperation(int operation) { if (getTextWidget() == null || (!redraws() && operation != FORMAT)) return; switch (operation) { case CONTENTASSIST_PROPOSALS: fContentAssistant.showPossibleCompletions(); return; case CONTENTASSIST_CONTEXT_INFORMATION: fContentAssistant.showContextInformation(); return; case QUICK_ASSIST: // FIXME: must find a way to post to the status line - // String msg= fQuickAssistAssistant.showPossibleQuickAssists(); + /* String msg= */ fQuickAssistAssistant.showPossibleQuickAssists(); // setStatusLineErrorMessage(msg); return; case INFORMATION: fInformationPresenter.showInformation(); return; case FORMAT: { final Point selection= rememberSelection(); final IRewriteTarget target= getRewriteTarget(); final IDocument document= getDocument(); IFormattingContext context= null; DocumentRewriteSession rewriteSession= null; if (document instanceof IDocumentExtension4) { IDocumentExtension4 extension= (IDocumentExtension4) document; rewriteSession= extension.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL); } else { setRedraw(false); startSequentialRewriteMode(false); target.beginCompoundChange(); } try { final String rememberedContents= document.get(); try { if (fContentFormatter instanceof IContentFormatterExtension) { final IContentFormatterExtension extension= (IContentFormatterExtension) fContentFormatter; context= createFormattingContext(); if (selection.y == 0) { context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.TRUE); } else { context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE); context.setProperty(FormattingContextProperties.CONTEXT_REGION, new Region(selection.x, selection.y)); } extension.format(document, context); } else { IRegion r; if (selection.y == 0) { IRegion coverage= getModelCoverage(); r= coverage == null ? new Region(0, 0) : coverage; } else { r= new Region(selection.x, selection.y); } fContentFormatter.format(document, r); } updateSlaveDocuments(document); } catch (RuntimeException x) { // fire wall for https://bugs.eclipse.org/bugs/show_bug.cgi?id=47472 // if something went wrong we undo the changes we just did // TODO to be removed after 3.0 M8 document.set(rememberedContents); throw x; } } finally { if (document instanceof IDocumentExtension4) { IDocumentExtension4 extension= (IDocumentExtension4) document; extension.stopRewriteSession(rewriteSession); } else { target.endCompoundChange(); stopSequentialRewriteMode(); setRedraw(true); } restoreSelection(); if (context != null) context.dispose(); } return; } default: super.doOperation(operation); } } /** * Updates all slave documents of the given document. This default implementation calls <code>updateSlaveDocument</code> * for their current visible range. Subclasses may reimplement. * * @param masterDocument the master document * @since 3.0 */ protected void updateSlaveDocuments(IDocument masterDocument) { ISlaveDocumentManager manager= getSlaveDocumentManager(); if (manager instanceof ISlaveDocumentManagerExtension) { ISlaveDocumentManagerExtension extension= (ISlaveDocumentManagerExtension) manager; IDocument[] slaves= extension.getSlaveDocuments(masterDocument); if (slaves != null) { for (int i= 0; i < slaves.length; i++) { if (slaves[i] instanceof ChildDocument) { ChildDocument child= (ChildDocument) slaves[i]; Position p= child.getParentDocumentRange(); try { if (!updateSlaveDocument(child, p.getOffset(), p.getLength())) child.repairLineInformation(); } catch (BadLocationException e) { // ignore } } } } } } /* * @see ITextOperationTargetExtension#enableOperation(int, boolean) * @since 2.0 */ public void enableOperation(int operation, boolean enable) { switch (operation) { case CONTENTASSIST_PROPOSALS: case CONTENTASSIST_CONTEXT_INFORMATION: { if (fContentAssistant == null) return; if (enable) { if (!fContentAssistantInstalled) { fContentAssistant.install(this); fContentAssistantInstalled= true; } } else if (fContentAssistantInstalled) { fContentAssistant.uninstall(); fContentAssistantInstalled= false; } } case QUICK_ASSIST: { if (fQuickAssistAssistant == null) return; if (enable) { if (!fQuickAssistAssistantInstalled) { fQuickAssistAssistant.install(this); fQuickAssistAssistantInstalled= true; } } else if (fContentAssistantInstalled) { fQuickAssistAssistant.uninstall(); fContentAssistantInstalled= false; } } } } /* * @see ISourceViewer#setRangeIndicator(Annotation) */ public void setRangeIndicator(Annotation rangeIndicator) { fRangeIndicator= rangeIndicator; } /* * @see ISourceViewer#setRangeIndication(int, int, boolean) */ public void setRangeIndication(int start, int length, boolean moveCursor) { if (moveCursor) { setSelectedRange(start, 0); revealRange(start, length); } if (fRangeIndicator != null && fVisualAnnotationModel instanceof IAnnotationModelExtension) { IAnnotationModelExtension extension= (IAnnotationModelExtension) fVisualAnnotationModel; extension.modifyAnnotationPosition(fRangeIndicator, new Position(start, length)); } } /* * @see ISourceViewer#getRangeIndication() */ public IRegion getRangeIndication() { if (fRangeIndicator != null && fVisualAnnotationModel != null) { Position position= fVisualAnnotationModel.getPosition(fRangeIndicator); if (position != null) return new Region(position.getOffset(), position.getLength()); } return null; } /* * @see ISourceViewer#removeRangeIndication() */ public void removeRangeIndication() { if (fRangeIndicator != null && fVisualAnnotationModel != null) fVisualAnnotationModel.removeAnnotation(fRangeIndicator); } /* * @see ISourceViewer#showAnnotations(boolean) */ public void showAnnotations(boolean show) { boolean old= fIsVerticalRulerVisible; fIsVerticalRulerVisible= (show && fVerticalRuler != null); if (old != fIsVerticalRulerVisible) { if (fComposite != null && !fComposite.isDisposed()) fComposite.layout(); if (fIsVerticalRulerVisible) { ensureAnnotationHoverManagerInstalled(); } else if (fVerticalRulerHoveringController != null) { fVerticalRulerHoveringController.dispose(); fVerticalRulerHoveringController= null; } } } /** * Returns the vertical ruler of this viewer. * * @return the vertical ruler of this viewer * @since 3.0 */ protected final IVerticalRuler getVerticalRuler() { return fVerticalRuler; } /* * @see org.eclipse.jface.text.source.ISourceViewerExtension#showAnnotationsOverview(boolean) * @since 2.1 */ public void showAnnotationsOverview(boolean show) { boolean old= fIsOverviewRulerVisible; fIsOverviewRulerVisible= (show && fOverviewRuler != null); if (old != fIsOverviewRulerVisible) { if (fComposite != null && !fComposite.isDisposed()) fComposite.layout(); if (fIsOverviewRulerVisible) { ensureOverviewHoverManagerInstalled(); } else if (fOverviewRulerHoveringController != null) { fOverviewRulerHoveringController.dispose(); fOverviewRulerHoveringController= null; } } } }
true
true
public void doOperation(int operation) { if (getTextWidget() == null || (!redraws() && operation != FORMAT)) return; switch (operation) { case CONTENTASSIST_PROPOSALS: fContentAssistant.showPossibleCompletions(); return; case CONTENTASSIST_CONTEXT_INFORMATION: fContentAssistant.showContextInformation(); return; case QUICK_ASSIST: // FIXME: must find a way to post to the status line // String msg= fQuickAssistAssistant.showPossibleQuickAssists(); // setStatusLineErrorMessage(msg); return; case INFORMATION: fInformationPresenter.showInformation(); return; case FORMAT: { final Point selection= rememberSelection(); final IRewriteTarget target= getRewriteTarget(); final IDocument document= getDocument(); IFormattingContext context= null; DocumentRewriteSession rewriteSession= null; if (document instanceof IDocumentExtension4) { IDocumentExtension4 extension= (IDocumentExtension4) document; rewriteSession= extension.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL); } else { setRedraw(false); startSequentialRewriteMode(false); target.beginCompoundChange(); } try { final String rememberedContents= document.get(); try { if (fContentFormatter instanceof IContentFormatterExtension) { final IContentFormatterExtension extension= (IContentFormatterExtension) fContentFormatter; context= createFormattingContext(); if (selection.y == 0) { context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.TRUE); } else { context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE); context.setProperty(FormattingContextProperties.CONTEXT_REGION, new Region(selection.x, selection.y)); } extension.format(document, context); } else { IRegion r; if (selection.y == 0) { IRegion coverage= getModelCoverage(); r= coverage == null ? new Region(0, 0) : coverage; } else { r= new Region(selection.x, selection.y); } fContentFormatter.format(document, r); } updateSlaveDocuments(document); } catch (RuntimeException x) { // fire wall for https://bugs.eclipse.org/bugs/show_bug.cgi?id=47472 // if something went wrong we undo the changes we just did // TODO to be removed after 3.0 M8 document.set(rememberedContents); throw x; } } finally { if (document instanceof IDocumentExtension4) { IDocumentExtension4 extension= (IDocumentExtension4) document; extension.stopRewriteSession(rewriteSession); } else { target.endCompoundChange(); stopSequentialRewriteMode(); setRedraw(true); } restoreSelection(); if (context != null) context.dispose(); } return; } default: super.doOperation(operation); } }
public void doOperation(int operation) { if (getTextWidget() == null || (!redraws() && operation != FORMAT)) return; switch (operation) { case CONTENTASSIST_PROPOSALS: fContentAssistant.showPossibleCompletions(); return; case CONTENTASSIST_CONTEXT_INFORMATION: fContentAssistant.showContextInformation(); return; case QUICK_ASSIST: // FIXME: must find a way to post to the status line /* String msg= */ fQuickAssistAssistant.showPossibleQuickAssists(); // setStatusLineErrorMessage(msg); return; case INFORMATION: fInformationPresenter.showInformation(); return; case FORMAT: { final Point selection= rememberSelection(); final IRewriteTarget target= getRewriteTarget(); final IDocument document= getDocument(); IFormattingContext context= null; DocumentRewriteSession rewriteSession= null; if (document instanceof IDocumentExtension4) { IDocumentExtension4 extension= (IDocumentExtension4) document; rewriteSession= extension.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL); } else { setRedraw(false); startSequentialRewriteMode(false); target.beginCompoundChange(); } try { final String rememberedContents= document.get(); try { if (fContentFormatter instanceof IContentFormatterExtension) { final IContentFormatterExtension extension= (IContentFormatterExtension) fContentFormatter; context= createFormattingContext(); if (selection.y == 0) { context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.TRUE); } else { context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE); context.setProperty(FormattingContextProperties.CONTEXT_REGION, new Region(selection.x, selection.y)); } extension.format(document, context); } else { IRegion r; if (selection.y == 0) { IRegion coverage= getModelCoverage(); r= coverage == null ? new Region(0, 0) : coverage; } else { r= new Region(selection.x, selection.y); } fContentFormatter.format(document, r); } updateSlaveDocuments(document); } catch (RuntimeException x) { // fire wall for https://bugs.eclipse.org/bugs/show_bug.cgi?id=47472 // if something went wrong we undo the changes we just did // TODO to be removed after 3.0 M8 document.set(rememberedContents); throw x; } } finally { if (document instanceof IDocumentExtension4) { IDocumentExtension4 extension= (IDocumentExtension4) document; extension.stopRewriteSession(rewriteSession); } else { target.endCompoundChange(); stopSequentialRewriteMode(); setRedraw(true); } restoreSelection(); if (context != null) context.dispose(); } return; } default: super.doOperation(operation); } }
diff --git a/src/main/java/net/sf/hajdbc/codec/MultiplexingDecoderFactory.java b/src/main/java/net/sf/hajdbc/codec/MultiplexingDecoderFactory.java index 19c3a965..967db4e0 100644 --- a/src/main/java/net/sf/hajdbc/codec/MultiplexingDecoderFactory.java +++ b/src/main/java/net/sf/hajdbc/codec/MultiplexingDecoderFactory.java @@ -1,60 +1,61 @@ /* * HA-JDBC: High-Availability JDBC * Copyright (C) 2012 Paul Ferraro * * 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, see <http://www.gnu.org/licenses/>. */ package net.sf.hajdbc.codec; import java.io.Serializable; import java.sql.SQLException; import net.sf.hajdbc.IdentifiableMatcher; import net.sf.hajdbc.util.ServiceLoaders; /** * Codec factory that whose decoding behavior is determined by a prefix. * @author Paul Ferraro */ public class MultiplexingDecoderFactory implements DecoderFactory, Serializable { public static final String DELIMITER = ":"; private static final long serialVersionUID = 4413927326976263687L; @Override public Decoder createDecoder(String clusterId) throws SQLException { return new MultiplexingDecoder(clusterId); } private static class MultiplexingDecoder implements Decoder { private final String clusterId; MultiplexingDecoder(String clusterId) { this.clusterId = clusterId; } @Override public String decode(String value) throws SQLException { + if (value == null) return null; int index = value.indexOf(DELIMITER); String id = (index >= 0) ? value.substring(0, index) : null; String source = (index >= 0) ? value.substring(index + 1) : value; CodecFactory factory = ServiceLoaders.findRequiredService(new IdentifiableMatcher<CodecFactory>(id), CodecFactory.class); return factory.createCodec(this.clusterId).decode(source); } } }
true
true
public String decode(String value) throws SQLException { int index = value.indexOf(DELIMITER); String id = (index >= 0) ? value.substring(0, index) : null; String source = (index >= 0) ? value.substring(index + 1) : value; CodecFactory factory = ServiceLoaders.findRequiredService(new IdentifiableMatcher<CodecFactory>(id), CodecFactory.class); return factory.createCodec(this.clusterId).decode(source); }
public String decode(String value) throws SQLException { if (value == null) return null; int index = value.indexOf(DELIMITER); String id = (index >= 0) ? value.substring(0, index) : null; String source = (index >= 0) ? value.substring(index + 1) : value; CodecFactory factory = ServiceLoaders.findRequiredService(new IdentifiableMatcher<CodecFactory>(id), CodecFactory.class); return factory.createCodec(this.clusterId).decode(source); }
diff --git a/iReport/iReport.java b/iReport/iReport.java index 83be4c1..b08dd57 100644 --- a/iReport/iReport.java +++ b/iReport/iReport.java @@ -1,120 +1,120 @@ package iReport; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; public class iReport extends JavaPlugin { public iReport() { } @Override @SuppressWarnings("unused") public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]) { if (cmd.getName().equalsIgnoreCase("greport") && args.length == 1) { String player = sender.getName(); String target = args[0]; Location loc = null; String already = (String) getConfig().get(new StringBuilder("reports.griefing.").append(player).toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("You successfully reported ").append(ChatColor.RED).append(target).toString()); getConfig().set(new StringBuilder("reports.griefing.").append(player).toString(), new StringBuilder(Rlocation.getxyz(this, args[0])).append("; ").append(target).toString()); saveConfig(); return true; } - if (cmd.getName().equalsIgnoreCase("hreport") && args.length == 1) { + if (cmd.getName().equalsIgnoreCase("hreport") && args.length == 2) { String player = sender.getName(); String target = args[0]; String already = (String) getConfig().get(new StringBuilder("reports.hacking.").append(player).toString()); - getConfig().set(new StringBuilder("reports.hacking.").append(player).toString(), new StringBuilder(String.valueOf(already)).append("; ").append(target).toString()); + getConfig().set(new StringBuilder("reports.hacking.").append(player).toString(), new StringBuilder("type: " + args[1]).append("; ").append(target).toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("You successfully reported ").append(ChatColor.RED).append(target).toString()); saveConfig(); return true; } if (cmd.getName().equalsIgnoreCase("sreport") && args.length == 1) { String player = sender.getName(); String target = args[0]; String already = (String) getConfig().get(new StringBuilder("reports.swearing.").append(player).toString()); - getConfig().set(new StringBuilder("reports.swearing.").append(player).toString(), new StringBuilder(String.valueOf(already)).append("; ").append(target).toString()); + getConfig().set(new StringBuilder("reports.swearing.").append(player).toString(), new StringBuilder().append("; ").append(target).toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("You successfully reported ").append(ChatColor.RED).append(target).toString()); saveConfig(); return true; } if (cmd.getName().equalsIgnoreCase("ireport")) { sender.sendMessage(new StringBuilder().append(ChatColor.YELLOW).append("==============================").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/greport - Report a griefer").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/hreport - Report a hacker").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/sreport - Report a swearer").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/ireport - Show this help menu").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.YELLOW).append("==============================").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.GREEN).append("Created by tudse145").toString()); return true; } else return false; } private FileConfiguration customConfig = null; private File customConfigFile = null; public void reloadCustomConfig() { if (customConfigFile == null) customConfigFile = new File(getDataFolder(), "customconfig.yml"); customConfig = YamlConfiguration.loadConfiguration(customConfigFile); // Look for defaults in the jar InputStream defConfigStream = getResource("customconfig.yml"); if (defConfigStream != null) { YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); customConfig.setDefaults(defConfig); } } public FileConfiguration getCustomConfig() { if (customConfig == null) reloadCustomConfig(); return customConfig; } public void saveCustomConfig() { if (customConfig == null || customConfigFile == null) return; try { getCustomConfig().save(customConfigFile); } catch (IOException ex) { getLogger().log(Level.SEVERE, "Could not save config to " + customConfigFile, ex); } } public void createfile() { File List = new File("/iReport/costumconfig.yml"); if (!List.exists()) try { List.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onEnable() { saveConfig(); getConfig().options().copyDefaults(true); saveCustomConfig(); } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]) { if (cmd.getName().equalsIgnoreCase("greport") && args.length == 1) { String player = sender.getName(); String target = args[0]; Location loc = null; String already = (String) getConfig().get(new StringBuilder("reports.griefing.").append(player).toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("You successfully reported ").append(ChatColor.RED).append(target).toString()); getConfig().set(new StringBuilder("reports.griefing.").append(player).toString(), new StringBuilder(Rlocation.getxyz(this, args[0])).append("; ").append(target).toString()); saveConfig(); return true; } if (cmd.getName().equalsIgnoreCase("hreport") && args.length == 1) { String player = sender.getName(); String target = args[0]; String already = (String) getConfig().get(new StringBuilder("reports.hacking.").append(player).toString()); getConfig().set(new StringBuilder("reports.hacking.").append(player).toString(), new StringBuilder(String.valueOf(already)).append("; ").append(target).toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("You successfully reported ").append(ChatColor.RED).append(target).toString()); saveConfig(); return true; } if (cmd.getName().equalsIgnoreCase("sreport") && args.length == 1) { String player = sender.getName(); String target = args[0]; String already = (String) getConfig().get(new StringBuilder("reports.swearing.").append(player).toString()); getConfig().set(new StringBuilder("reports.swearing.").append(player).toString(), new StringBuilder(String.valueOf(already)).append("; ").append(target).toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("You successfully reported ").append(ChatColor.RED).append(target).toString()); saveConfig(); return true; } if (cmd.getName().equalsIgnoreCase("ireport")) { sender.sendMessage(new StringBuilder().append(ChatColor.YELLOW).append("==============================").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/greport - Report a griefer").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/hreport - Report a hacker").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/sreport - Report a swearer").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/ireport - Show this help menu").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.YELLOW).append("==============================").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.GREEN).append("Created by tudse145").toString()); return true; } else return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]) { if (cmd.getName().equalsIgnoreCase("greport") && args.length == 1) { String player = sender.getName(); String target = args[0]; Location loc = null; String already = (String) getConfig().get(new StringBuilder("reports.griefing.").append(player).toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("You successfully reported ").append(ChatColor.RED).append(target).toString()); getConfig().set(new StringBuilder("reports.griefing.").append(player).toString(), new StringBuilder(Rlocation.getxyz(this, args[0])).append("; ").append(target).toString()); saveConfig(); return true; } if (cmd.getName().equalsIgnoreCase("hreport") && args.length == 2) { String player = sender.getName(); String target = args[0]; String already = (String) getConfig().get(new StringBuilder("reports.hacking.").append(player).toString()); getConfig().set(new StringBuilder("reports.hacking.").append(player).toString(), new StringBuilder("type: " + args[1]).append("; ").append(target).toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("You successfully reported ").append(ChatColor.RED).append(target).toString()); saveConfig(); return true; } if (cmd.getName().equalsIgnoreCase("sreport") && args.length == 1) { String player = sender.getName(); String target = args[0]; String already = (String) getConfig().get(new StringBuilder("reports.swearing.").append(player).toString()); getConfig().set(new StringBuilder("reports.swearing.").append(player).toString(), new StringBuilder().append("; ").append(target).toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("You successfully reported ").append(ChatColor.RED).append(target).toString()); saveConfig(); return true; } if (cmd.getName().equalsIgnoreCase("ireport")) { sender.sendMessage(new StringBuilder().append(ChatColor.YELLOW).append("==============================").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/greport - Report a griefer").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/hreport - Report a hacker").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/sreport - Report a swearer").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.BLUE).append("/ireport - Show this help menu").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.YELLOW).append("==============================").toString()); sender.sendMessage(new StringBuilder().append(ChatColor.GREEN).append("Created by tudse145").toString()); return true; } else return false; }
diff --git a/MainBot/trunk/src/AndrewCassidy/PluggableBot/PluggableBot.java b/MainBot/trunk/src/AndrewCassidy/PluggableBot/PluggableBot.java index dfe632e..885d29f 100644 --- a/MainBot/trunk/src/AndrewCassidy/PluggableBot/PluggableBot.java +++ b/MainBot/trunk/src/AndrewCassidy/PluggableBot/PluggableBot.java @@ -1,278 +1,278 @@ /* * PluggableBot.java * * Created on 09 October 2007, 14:04 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package AndrewCassidy.PluggableBot; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import org.jibble.pircbot.PircBot; /** * * @author AndyC */ public class PluggableBot extends PircBot { private static HashMap<String, Plugin> loadedPlugins = new HashMap<String, Plugin>(); private static String nick = "Bob"; private static String server = "irc.freenode.net"; private static String password = "P@ssw0rd"; private static PluggableBot b = new PluggableBot(); private static ArrayList<String> channels = new ArrayList<String>(); private static String admin = ""; public static void main(String[] args) { // add the shutdown hook for cleaning up Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { cleanup(); } }); b.setVerbose(true); try { loadSettings(); } catch (Exception e) { System.err.println("Failed to process config file: " + e.getMessage()); System.exit(0); } b.connect(); } private static void loadSettings() throws Exception { String context = "", line; FileReader fr = new FileReader("config"); BufferedReader br = new BufferedReader(fr); while ((line = br.readLine()) != null) { if (line.startsWith("[") && line.endsWith("]")) { context = line.substring(1, line.length() - 1); } else { if (line.trim().length() == 0) continue; else if (context.equals("nick")) nick = line; else if (context.equals("server")) server = line; else if (context.equals("channels")) channels.add(line); else if (context.equals("plugins")) loadPlugin(line); else if (context.equals("password")) password = line; } } } public static Plugin loadPlugin(String name) { try { ArrayList<URL> paths = new ArrayList<URL>(); File f = new File("plugins/" + name + ".jar"); paths.add(f.toURI().toURL()); File f2 = new File("lib"); for (File ff : f2.listFiles()) paths.add(ff.toURI().toURL()); URL[] urls = new URL[paths.size()]; paths.toArray(urls); URLClassLoader newLoader = new URLClassLoader(urls); Plugin p = (Plugin) newLoader.loadClass(name).newInstance(); loadedPlugins.put(name, p); return p; } catch (Exception ex) { System.err.println("Failed to load plugin: " + ex.getMessage()); ex.printStackTrace(); } return null; } private static void unloadPlugin(String name) { loadedPlugins.get(name).unload(); loadedPlugins.remove(name); System.gc(); System.gc(); System.gc(); } @Override protected void onAction(String sender, String login, String hostname, String target, String action) { for (Plugin p : loadedPlugins.values()) p.onAction(sender, login, hostname, target, action); } @Override protected void onJoin(String channel, String sender, String login, String hostname) { for (Plugin p : loadedPlugins.values()) p.onJoin(channel, sender, login, hostname); } private void connect() { try { b.setName(nick); b.connect(server); for (String s : channels) b.joinChannel(s); } catch (Exception e) { System.err .println("Could not connect to server: " + e.getMessage()); System.exit(0); } } @Override protected void onDisconnect() { while (!b.isConnected()) { try { java.lang.Thread.sleep(60000); } catch (InterruptedException ex) { } connect(); } } @Override protected void onKick(String channel, String kickerNick, String kickerLogin, String kickerHostname, String recipientNick, String reason) { for (Plugin p : loadedPlugins.values()) p.onKick(channel, kickerNick, kickerLogin, kickerHostname, recipientNick, reason); } @Override protected void onMessage(String channel, String sender, String login, String hostname, String message) { if (message.startsWith("!help")) { if (message.trim().split(" ").length == 1) { // loaded plugins String m = "Plugins loaded: "; for (String s : loadedPlugins.keySet()) m += s + ", "; m = m.substring(0, m.length() - 2); sendMessage(channel, m); } else { // try to find loaded plugin help String[] s = message.trim().split(" "); boolean flag = false; for (String string : loadedPlugins.keySet()) { if (string.toLowerCase().equals(s[1].toLowerCase())) { - sendMessage(channel, loadedPlugins.get(s[1]).getHelp()); + sendMessage(channel, loadedPlugins.get(string).getHelp()); flag = true; } } if (!flag) { sendMessage(channel, "Could not find help for the specified plugin"); } } } else { for (Plugin p : loadedPlugins.values()) p.onMessage(channel, sender, login, hostname, message); } } @Override protected void onPart(String channel, String sender, String login, String hostname) { for (Plugin p : loadedPlugins.values()) p.onPart(channel, sender, login, hostname); } @Override protected void onQuit(String sourceNick, String sourceLogin, String sourceHostname, String reason) { for (Plugin p : loadedPlugins.values()) p.onQuit(sourceNick, sourceLogin, sourceHostname, reason); if (sourceNick.equals(admin)) admin = ""; } @Override protected void onPrivateMessage(String sender, String login, String hostname, String message) { if (message.startsWith("identify")) { if (message.substring(9).equals(password)) { admin = nick; b.sendMessage(sender, "identified"); } } else if (message.startsWith("load") && admin.equals(nick)) { loadPlugin(message.substring(5)); b.sendMessage(sender, "loaded"); } else if (admin.equals(nick)) { onAdminMessage(sender, login, hostname, message); for (Plugin p : loadedPlugins.values()) p.onAdminMessage(sender, login, hostname, message); } for (Plugin p : loadedPlugins.values()) p.onPrivateMessage(sender, login, hostname, message); } @Override protected void onNickChange(String oldNick, String login, String hostname, String newNick) { if (oldNick.equals(admin)) admin = newNick; } public static String Nick() { return b.getNick(); } public static void Action(String target, String action) { b.sendAction(target, action); } public static void Message(String target, String action) { b.sendMessage(target, action); } private static void cleanup() { System.out.println("Shutting down..."); for (Plugin p : loadedPlugins.values()) p.unload(); } public void onAdminMessage(String sender, String login, String hostname, String message) { if (message.startsWith("unload")) { unloadPlugin(message.substring(7)); b.sendMessage(sender, "unloaded"); } else if (message.startsWith("reload")) { unloadPlugin(message.substring(7)); loadPlugin(message.substring(7)); b.sendMessage(sender, "reloaded"); } else if (message.startsWith("join")) { b.joinChannel(message.substring(5)); b.sendMessage(sender, "joined"); } else if (message.startsWith("part")) { b.partChannel(message.substring(5)); b.sendMessage(sender, "left"); } } }
true
true
protected void onMessage(String channel, String sender, String login, String hostname, String message) { if (message.startsWith("!help")) { if (message.trim().split(" ").length == 1) { // loaded plugins String m = "Plugins loaded: "; for (String s : loadedPlugins.keySet()) m += s + ", "; m = m.substring(0, m.length() - 2); sendMessage(channel, m); } else { // try to find loaded plugin help String[] s = message.trim().split(" "); boolean flag = false; for (String string : loadedPlugins.keySet()) { if (string.toLowerCase().equals(s[1].toLowerCase())) { sendMessage(channel, loadedPlugins.get(s[1]).getHelp()); flag = true; } } if (!flag) { sendMessage(channel, "Could not find help for the specified plugin"); } } } else { for (Plugin p : loadedPlugins.values()) p.onMessage(channel, sender, login, hostname, message); } }
protected void onMessage(String channel, String sender, String login, String hostname, String message) { if (message.startsWith("!help")) { if (message.trim().split(" ").length == 1) { // loaded plugins String m = "Plugins loaded: "; for (String s : loadedPlugins.keySet()) m += s + ", "; m = m.substring(0, m.length() - 2); sendMessage(channel, m); } else { // try to find loaded plugin help String[] s = message.trim().split(" "); boolean flag = false; for (String string : loadedPlugins.keySet()) { if (string.toLowerCase().equals(s[1].toLowerCase())) { sendMessage(channel, loadedPlugins.get(string).getHelp()); flag = true; } } if (!flag) { sendMessage(channel, "Could not find help for the specified plugin"); } } } else { for (Plugin p : loadedPlugins.values()) p.onMessage(channel, sender, login, hostname, message); } }