Merge branch 'ncep_14.3.1' of ssh://collaborate3.nws.noaa.gov:29418/AWIPS2_Dev_Baseline into master_14.3.1

Former-commit-id: b13e744dbbcc332b9efd0799e87390bdf9bb1df3
This commit is contained in:
Brian.Dyke 2014-08-26 10:56:45 -04:00
commit 59bacf90ac
73 changed files with 26416 additions and 15521 deletions

View file

@ -189,7 +189,7 @@
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
unpack="false"/>
<plugin
id="gov.noaa.nws.ncep.common.dataplugin.ntrans"
@ -212,4 +212,11 @@
version="0.0.0"
unpack="false"/>
<plugin
id="com.raytheon.uf.common.remote.script"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
</feature>

View file

@ -312,4 +312,11 @@
version="0.0.0"
unpack="false"/>
<plugin
id="gov.noaa.nws.ncep.viz.ui.remotescript"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
</feature>

View file

@ -146,4 +146,8 @@
id="com.raytheon.uf.edex.dataprovideragent.feature"
version="0.0.0"/>
<includes
id="com.raytheon.uf.edex.remote.script.feature"
version="0.0.0"/>
</feature>

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry excluding="com/raytheon/uf/common/remote/script/data/" kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.raytheon.uf.common.remote.script</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6

View file

@ -0,0 +1,14 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Common
Bundle-SymbolicName: com.raytheon.uf.common.remote.script
Bundle-Version: 1.14.0.qualifier
Bundle-Vendor: RATHEON
Require-Bundle: com.raytheon.uf.common.serialization;bundle-version="1.12.1174",
com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174",
com.raytheon.uf.common.localization;bundle-version="1.12.1174",
com.raytheon.uf.common.auth;bundle-version="1.12.1174",
org.apache.commons.lang;bundle-version="2.3.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Bundle-ActivationPolicy: lazy
Export-Package: com.raytheon.uf.common.remote.script

View file

@ -0,0 +1,4 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.

View file

@ -0,0 +1,114 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.remote.script;
/**
* Useful constants for remote scripts.
* <p>
* The resource defaults noted here are the ones defined in this class and are
* used when the a property value is not defined. These values can be overridden
* for the EDEX server by defining a property value in the EDEX resources file:
* com.raytheon.uf.edex.remote.script.properties.
* <p>
* Except where noted a given run request may override a value. See
* {@link RemoteScriptRunRequest#putProperty(String, String)}.
*
* <pre>
* Resource properties:
*
* KEY VALUES DESCRIPTION
* ======================================================
* remote.script.directory Localized directories to search for scripts. (default
* remoteScripts). Cannot be overridden in a request.
* remote.script.timeout Kill script process if it doesn't finish by this
* number of seconds (default 30).
* remote.script.use.stderr When true separate standard out and standard error
* (default false).
* remote.script.setup.error Exit error to use when unable to run a script
* (default 99).
* </pre>
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 12, 2014 #2742 rferrel Initial creation
*
* </pre>
*
* @author rferrel
* @version 1.0
*/
public class RemoteScriptConstants {
/**
* Resource key to obtain script directory. Cannot be overridden in script
* properties. See
* {@link RemoteScriptRunRequest#putProperty(String, String)}. .
*/
public static final String scriptDirectoryKey = "remote.script.directory";
/**
* Resource/Property key to obtain execution timeout in seconds. See @{link
* {@link RemoteScriptRunRequest#putProperty(String, String)}.
*/
public static final String scriptTimeoutKey = "remote.script.timeout";
/**
* Resource/Property key to obtain boolean to separate standard error from
* the standard out stream. See
* {@link RemoteScriptRunRequest#putProperty(String, String)}.
*/
public static final String scriptUseStdErrKey = "remote.script.use.stderr";
/**
* Resource/Property key to obtain exit value to use when unable to run the
* script.
*/
public static final String scriptSetupErrrorKey = "remote.script.setup.error";
/**
* Default common static directory for remote scripts. See
* {@link RemoteScriptRunRequest#putProperty(String, String)}.
*/
public static final String scriptDirectoryDefault = "remoteScripts";
/**
* Default time out value in seconds. See
* {@link RemoteScriptRunRequest#putProperty(String, String)}.
*/
public static final String scriptTimeoutDefault = "30";
/**
* Default flag to separate standard error from the standard out stream. See
* {@link RemoteScriptRunRequest#putProperty(String, String)}.
*/
public static final String scriptUseStdErrDefault = "false";
/**
* Error exit value to use when unable to run the script.
*/
public static final String scriptSetUpErrorDefault = "99";
private RemoteScriptConstants() {
}
}

View file

@ -0,0 +1,106 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.remote.script;
import com.raytheon.uf.common.localization.LocalizationContext;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
/**
* This class is a request to obtain listing of remote scripts from desired
* localization directories.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 13, 2014 2742 rferrel Initial creation
*
* </pre>
*
* @author rferrel
* @version 1.0
*/
@DynamicSerialize
public class RemoteScriptListRequest extends RemoteScriptRequest {
/**
* The contexts to search for scripts.
*/
@DynamicSerializeElement
private LocalizationContext[] contexts;
/**
* Default constructor.
*/
public RemoteScriptListRequest() {
}
/**
* Constructor.
*
* @param userId
*/
public RemoteScriptListRequest(String userId, LocalizationContext[] contexts) {
this();
setUserId(userId);
setContexts(contexts);
}
/**
* Getter.
*
* @return contexts
*/
public LocalizationContext[] getContexts() {
return contexts;
}
/**
* Setter.
*
* @param contexts
* - when null contexts is cleared.
*/
public void setContexts(LocalizationContext[] contexts) {
if (contexts != null) {
this.contexts = contexts;
} else {
contexts = new LocalizationContext[0];
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("RemoteScriptListRequest {");
sb.append("userId: ").append(getUserId());
sb.append(", contexts: ").append(getContexts());
sb.append("}");
return sb.toString();
}
}

View file

@ -0,0 +1,163 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.remote.script;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.raytheon.uf.common.localization.IPathManager;
import com.raytheon.uf.common.localization.LocalizationContext;
import com.raytheon.uf.common.localization.LocalizationFile;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
/**
* This contains Localization Context map that is the result of a remote script
* list request. The keys are sorted list of the script file names.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 11, 2014 2742 rferrel Initial creation
*
* </pre>
*
* @author rferrel
* @version 1.0
*/
@DynamicSerialize
public class RemoteScriptListResponse {
/**
* Map of contexts with sorted list of scripts as keys.
*/
@DynamicSerializeElement
private Map<String, List<LocalizationContext>> scripts = new TreeMap<String, List<LocalizationContext>>(
String.CASE_INSENSITIVE_ORDER);
/**
* Default Constructor.
*/
public RemoteScriptListResponse() {
}
/**
* Constructor.
*
* @param scripts
*/
public RemoteScriptListResponse(
Map<String, List<LocalizationContext>> scripts) {
setScripts(scripts);
}
/**
* Getter map of scripts' context lists the script keys are sorted.
*
* @return scripts
*/
public Map<String, List<LocalizationContext>> getScripts() {
return scripts;
}
/**
* Setter.
*
* @param scripts
* - when null scripts are cleared.
*/
public void setScripts(Map<String, List<LocalizationContext>> scripts) {
this.scripts.clear();
if (scripts != null) {
this.scripts.putAll(scripts);
}
}
/**
* Convince method to a add file's script name and context to scripts.
*
* @param lFile
* @return true if not already in the set
*/
public boolean add(LocalizationFile lFile) {
String script = getName(lFile);
LocalizationContext context = lFile.getContext();
List<LocalizationContext> contexts = scripts.get(script);
if (contexts == null) {
contexts = new ArrayList<LocalizationContext>();
scripts.put(script, contexts);
}
if (!contexts.contains(context)) {
contexts.add(context);
return true;
}
return false;
}
/**
* Convince method to remove the file's context from scripts.
*
* @param true - if file's script and context was in scripts.
*/
public boolean remove(LocalizationFile lFile) {
String name = getName(lFile);
List<LocalizationContext> contexts = scripts.get(name);
if (contexts == null) {
return false;
}
if (contexts.remove(contexts)) {
if (contexts.size() == 0) {
scripts.remove(name);
}
return true;
}
return false;
}
/**
* Get the script name of the localized file.
*
* @param lFile
* @return name
*/
private String getName(LocalizationFile lFile) {
String name = lFile.getName().trim();
return name.substring(name.lastIndexOf(IPathManager.SEPARATOR) + 1);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
return String.format("RemoteScriptListResponse: {scripts: %s}",
getScripts());
}
}

View file

@ -0,0 +1,88 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.remote.script;
import com.raytheon.uf.common.auth.req.AbstractPrivilegedRequest;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
/**
* Class with common elements for the remote script requests,
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 11, 2014 2742 rferrel Initial creation
*
* </pre>
*
* @author rferrel
* @version 1.0
*/
@DynamicSerialize
public class RemoteScriptRequest extends AbstractPrivilegedRequest {
/** User making the request. */
@DynamicSerializeElement
private String userId;
/** not authorized message. */
@DynamicSerializeElement
private String notAuthorizedMessage = "Not Authorized";
/**
* Getter.
*
* @return userId
*/
public String getUserId() {
return userId;
}
/**
* Setter.
*
* @param userId
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Getter.
*
* @return notAuthorizedMessage
*/
public String getNotAuthorizedMessage() {
return notAuthorizedMessage;
}
/**
* Setter.
*
* @param notAuthorizedMessage
*/
public void setNotAuthorizedMessage(String notAuthorizedMessage) {
this.notAuthorizedMessage = notAuthorizedMessage;
}
}

View file

@ -0,0 +1,263 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.remote.script;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.text.StrMatcher;
import org.apache.commons.lang.text.StrTokenizer;
import com.raytheon.uf.common.localization.LocalizationContext;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
/**
* This class is a request to run a remote script from desired localization
* directory.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 19, 2014 2743 rferrel Initial creation
*
* </pre>
*
* @author rferrel
* @version 1.0
*/
@DynamicSerialize
public class RemoteScriptRunRequest extends RemoteScriptRequest {
@DynamicSerializeElement
String script;
@DynamicSerializeElement
LocalizationContext context;
/**
* Mapping of resource properties to override. See
* {@link RemoteScriptConstants}.
*/
@DynamicSerializeElement
private Map<String, String> propertyMap = new HashMap<String, String>();
/**
* Command line arguments for the remote script.
*/
@DynamicSerializeElement
private List<String> scriptArguments = new ArrayList<String>();
/**
* Default constructor.
*/
public RemoteScriptRunRequest() {
}
/**
* Constructor.
*
* @param userId
* - user to run the script
* @param filename
* - script's filename located in the script directory. See
* {@link RemoteScriptConstants}.
* @param context
* - The localize directory's context that contains the script.
* See {@link RemoteScriptListResponse#get(String)}
*/
public RemoteScriptRunRequest(String userId, String script,
LocalizationContext context) {
this();
setUserId(userId);
setScript(script);
setContext(context);
}
/**
* Get the context associated with the script's filename. See
* {@link RemoteScriptListResponse#get(String)}.
*
* @return context
*/
public LocalizationContext getContext() {
return context;
}
/**
* Set the context associated with the script's filename. See
* {@link RemoteScriptListResponse#get(String)}.
*
* @param context
*/
public void setContext(LocalizationContext context) {
this.context = context;
}
/**
* Getter for script property map. Recommend this only be used for
* serialization, see {@link RemoteScriptConstants}.
*
* @return propertyMap
*/
public Map<String, String> getPropertyMap() {
return propertyMap;
}
/**
* Setter for script property map. This is used to override the script
* property values for handling the script. Recommend this only be used for
* serialization, see {@link RemoteScriptConstants}.
*
* @param propertyMap
* - when null map cleared so default values will be used
*/
public void setPropertyMap(Map<String, String> propertyMap) {
this.propertyMap.clear();
if (propertyMap != null) {
this.propertyMap.putAll(propertyMap);
}
}
/**
* Override the default resource property, see {@link RemoteScriptConstants}
* .
*
* @param key
* @param value
* @return oldValue - previous value for key
*/
public String putProperty(String key, String value) {
return propertyMap.put(key, value);
}
/**
* Remove property.
*
* @param key
* - property to remove
* @return value - Value removed or null if none
*/
public String removeProperty(String key) {
return propertyMap.remove(key);
}
/**
* Get list of command line arguments for the script in the order sent to
* the process builder. See {@link java.lang.ProcessBuilder#command(List)}.
* Note the full path name to the script to run will be added by the handler
* when sending the request.
*
* @return scriptArguments
*/
public List<String> getScriptArguments() {
return scriptArguments;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
/**
* Set the list of command line arguments for the script in the order they
* are to be sent to the process builder. See
* {@link java.lang.ProcessBuilder#command(List)}. Note the full path name
* to the script to run will be added by the handler when sending the
* request.
*
* @param scriptArguments
*/
public void setScriptArguments(List<String> scriptArguments) {
this.scriptArguments.clear();
if (scriptArguments != null) {
this.scriptArguments.addAll(scriptArguments);
}
}
/**
* Append an argument to the script's argument list.
*
* @param argument
* @return success - true when added to the list
*/
public boolean addScriptArgument(String argument) {
return scriptArguments.add(argument);
}
/**
* This clears the script argument list and breaks arguments into a list
* which becomes the new script argument list. The arguments is split into
* tokens delimited by whitespace. A token may be surrounded by single or
* double quotes. A quote may be escaped within a quoted section by
* duplicating itself.
*
* <pre>
* Examples of lists from java strings:
* "a b c" - Three arguments [a, b, c]
* "1 'a b c'd 3" - Three arguments [1, a b cd, 3]
* "1 \"a b c\"d 3" - Three arguments [1, a b cd, 3]
* "1 'a b ''c'''d 3" - Three arguments [1, a b 'c'd, 3]
* "1 \"a b \"\"c\"\"\"d 3" - Three arguments [1, a b "c"d, 3]
* </pre>
*/
public void parseAndSetScriptArguments(String arguments) {
if (arguments == null || (arguments.trim().length() == 0)) {
clearScriptArguements();
return;
}
String[] args = (new StrTokenizer(arguments, StrMatcher.spaceMatcher(),
StrMatcher.quoteMatcher())).getTokenArray();
setScriptArguments(Arrays.asList(args));
}
/**
* Remove all arguments from the script's argument list.
*/
public void clearScriptArguements() {
scriptArguments.clear();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getName());
sb.append("[ userId: ").append(getUserId());
sb.append(", script: ").append(getScript());
sb.append(", context: ").append(getContext());
sb.append(", propertyMap: ").append(propertyMap);
sb.append(", scriptArguments: ").append(getScriptArguments());
sb.append("]");
return sb.toString();
}
}

View file

@ -0,0 +1,172 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.remote.script;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
/**
* This contains the results from running a remote script.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 19, 2014 2743 rferrel Initial creation
*
* </pre>
*
* @author rferrel
* @version 1.0
*/
@DynamicSerialize
public class RemoteScriptRunResponse {
/**
* The exit status for the script.
*/
@DynamicSerializeElement
private Integer exitStatus;
/**
* The scripts output either just stdout or a combination of stadout and
* stderr. See {@link RemoteScriptConstants}.
*/
@DynamicSerializeElement
private String output = "";
/**
* When requested a separate sting with stderr. See
* {@link RemoteScriptConstants}.
*/
@DynamicSerializeElement
private String error = "";
/**
* When true script process timed out and was killed otherwise false. See
* {@link RemoteScriptConstants}.
*/
@DynamicSerializeElement
private boolean timedOut = false;
/**
* Default Constructor.
*/
public RemoteScriptRunResponse() {
}
/**
* Get the exit status for the process running the script.
*
* @return exitStatus
*/
public Integer getExitStatus() {
return exitStatus;
}
/**
* Set the exit status for script's process. Should only be used by the
* handler and serialization.
*
* @param exitStatus
*/
public void setExitStatus(Integer exitStatus) {
this.exitStatus = exitStatus;
}
/**
* Get the script's output. Based on the request properties this is either
* just stdout or a combination of stdout and stderr. See
* {@link RemoteScriptConstants}.
*
* @return output - never null
*/
public String getOutput() {
return output;
}
/**
* Set the script's output. Based on the request properties this is either
* just stdout or a combination of stdout and stderr. Should only be used by
* the handler and serialization. See {@link RemoteScriptConstants}.
*
* @param output
*/
public void setOutput(String output) {
this.output = (output == null) ? "" : output;
}
/**
* Get script's stderr when not placed in output.
*
* @return error - never null
*/
public String getError() {
return error;
}
/**
* Set script's stderr when not place in output. Should only be used by the
* handler and serialization.
*
* @param error
*/
public void setError(String error) {
this.error = (error == null) ? "" : error;
}
/**
* Flag to indicate script did not finish in the desired number of seconds.
* See {@link RemoteScriptConstants}.
*
* @return true when script process is killed otherwise false
*/
public boolean isTimedOut() {
return timedOut;
}
/**
* Set the timed out flag. Should only be used by the handler and
* serialization. See {@link RemoteScriptConstants}.
*
* @param timeOut
*/
public void setTimedOut(boolean timedOut) {
this.timedOut = timedOut;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuilder sb = new StringBuilder(this.getClass().getName());
sb.append("[");
sb.append("exitStatus: ").append(getExitStatus());
sb.append(", timedOut: ").append(isTimedOut());
sb.append(", error: \"").append(getError()).append("\"");
sb.append(", output: \"").append(getOutput()).append("\"");
sb.append("]");
return sb.toString();
}
}

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.raytheon.uf.edex.remote.script.feature</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.pde.FeatureBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.FeatureNature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1 @@
bin.includes = feature.xml

View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<feature
id="com.raytheon.uf.edex.remote.script.feature"
label="Remote Script Feature"
version="1.0.0.qualifier"
provider-name="RAYTHEON">
<description url="http://www.example.com/description">
[Enter Feature Description here.]
</description>
<copyright url="http://www.example.com/copyright">
[Enter Copyright Description here.]
</copyright>
<license url="http://www.example.com/license">
[Enter License Description here.]
</license>
<plugin
id="com.raytheon.uf.edex.remote.script"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
<plugin
id="com.raytheon.uf.common.remote.script"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
</feature>

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.raytheon.uf.edex.remote.script</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6

View file

@ -0,0 +1,18 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: RemoteScript
Bundle-SymbolicName: com.raytheon.uf.edex.remote.script
Bundle-Version: 1.14.0.qualifier
Bundle-Vendor: RAYTHEON
Require-Bundle: com.raytheon.uf.common.serialization;bundle-version="1.12.1174",
com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174",
com.raytheon.uf.common.localization;bundle-version="1.12.1174",
com.raytheon.uf.common.remote.script;bundle-version="1.0.0",
com.raytheon.uf.common.status;bundle-version="1.12.1174",
com.raytheon.uf.edex.auth;bundle-version="1.12.1174",
com.raytheon.uf.common.auth;bundle-version="1.12.1174",
com.raytheon.uf.common.time;bundle-version="1.12.1174",
com.raytheon.uf.common.util;bundle-version="1.12.1174",
com.raytheon.uf.common.comm;bundle-version="1.12.1174"
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Export-Package: com.raytheon.uf.edex.remote.script

View file

@ -0,0 +1,5 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
res/

View file

@ -0,0 +1,25 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- Instantiate the handler class for RemoteScriptList Handler -->
<bean id="RemoteScriptListHandler"
class="com.raytheon.uf.edex.remote.script.RemoteScriptListHandler"/>
<!-- Register the handler class with the RemoteScriptListRequest Register. -->
<bean id="remoteScriptListHandlerRegistered" factory-bean="handlerRegistry" factory-method="register">
<constructor-arg value="com.raytheon.uf.common.remote.script.RemoteScriptListRequest"/>
<constructor-arg ref="RemoteScriptListHandler"/>
</bean>
<!-- Instantiate the handler class for RemoteScriptRun Handler -->
<bean id="RemoteScriptRunHandler"
class="com.raytheon.uf.edex.remote.script.RemoteScriptRunHandler"/>
<!-- Register the handler class with the RemoteScriptRunRequest Register. -->
<bean id="remoteScriptRunHandlerRegistered" factory-bean="handlerRegistry" factory-method="register">
<constructor-arg value="com.raytheon.uf.common.remote.script.RemoteScriptRunRequest"/>
<constructor-arg ref="RemoteScriptRunHandler"/>
</bean>
</beans>

View file

@ -0,0 +1,21 @@
# The values shown here are the default values in the RemoteScriptConstants class.
# To change a property's default value for the EDEX server do the following:
# 1 - Edit this file and uncomment the desired property line(s).
# (remove the # at the start of the line.)
# 2 - Change the property's value
# 3 - Save the Changes
# 4 - Restart EDEX request.
# The localized directory that contains scripts.
remote.script.directory=ncep/remoteScripts
# Number of seconds to wait for script's process to complete before handler kills the process.
# Note the value will be adjusted to be less then the HttpClient's socket timeout value.
#remote.script.timeout=30
# Default use of standard error. When true Separate the standard output and error streams;
# otherwise combine them into standard out.
#remote.script.use.stderr=false
# Exit error to use when unable to run a script. Must be an integer.
#remote.script.setup.error=99

View file

@ -0,0 +1,174 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.remote.script;
import com.raytheon.uf.common.auth.exception.AuthorizationException;
import com.raytheon.uf.common.auth.user.IUser;
import com.raytheon.uf.common.localization.IPathManager;
import com.raytheon.uf.common.remote.script.RemoteScriptConstants;
import com.raytheon.uf.common.remote.script.RemoteScriptRequest;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.time.util.ITimer;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.common.util.FileUtil;
import com.raytheon.uf.edex.auth.AuthManager;
import com.raytheon.uf.edex.auth.AuthManagerFactory;
import com.raytheon.uf.edex.auth.req.AbstractPrivilegedRequestHandler;
import com.raytheon.uf.edex.auth.resp.AuthorizationResponse;
import com.raytheon.uf.edex.auth.roles.IRoleStorage;
/**
* Abstract class for the remote script handlers. Performs authorization and
* timing of requests.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 12, 2014 2742 rferrel Initial creation
*
* </pre>
*
* @author rferrel
* @version 1.0
*/
public abstract class AbstractRemoteScriptHandler extends
AbstractPrivilegedRequestHandler<RemoteScriptRequest> {
/** Status handler of the handling class using this class. */
protected final transient IUFStatusHandler statusHandler;
/** Common static directory for scripts. */
protected final String scriptsDirectory;
/** The handler's roleId defined in the common remoteScriptAdminRoles.xml */
protected final String roleId;
/**
* Application name. This must match the application tag in the user role
* file.
*/
private static final String APPLICATION = "Remote Script";
/**
* Construct.
*
* @param statusHandler
*/
public AbstractRemoteScriptHandler(String roleId) {
this.statusHandler = UFStatus.getHandler(this.getClass());
this.roleId = roleId;
String scriptsDirectory = FileUtil.edexPath(System.getProperty(
RemoteScriptConstants.scriptDirectoryKey,
RemoteScriptConstants.scriptDirectoryDefault));
// Strip tailing separators.
if (scriptsDirectory.endsWith(IPathManager.SEPARATOR)) {
StringBuilder sb = new StringBuilder(scriptsDirectory);
do {
sb.setLength(sb.length() - 1);
} while ((sb.length() > 0)
&& (sb.lastIndexOf(IPathManager.SEPARATOR) == (sb.length() - 1)));
scriptsDirectory = sb.toString();
}
this.scriptsDirectory = scriptsDirectory;
}
/**
* The method a subclass must implement to perform the work for the desired
* request.
*
* @param request
* @return results
*/
abstract protected Object performRequest(RemoteScriptRequest request);
/*
* (non-Javadoc)
*
* @see
* com.raytheon.uf.common.serialization.comm.IRequestHandler#handleRequest
* (com.raytheon.uf.common.serialization.comm.IServerRequest)
*/
@Override
public Object handleRequest(RemoteScriptRequest request) throws Exception {
Object result = null;
if (statusHandler.isPriorityEnabled(Priority.INFO)) {
statusHandler.handle(Priority.INFO, String.format(
"Start for %s, do %s", request.getUserId(), getRoleId()));
}
ITimer timer = TimeUtil.getTimer();
timer.start();
result = performRequest(request);
timer.stop();
if (statusHandler.isPriorityEnabled(Priority.INFO)) {
statusHandler.handle(
Priority.INFO,
String.format("Finish for %s, do %s, took %s",
request.getUserId(), getRoleId(),
TimeUtil.prettyDuration(timer.getElapsedTime())));
}
return result;
}
protected String getRoleId() {
return roleId;
}
/**
* Performs the authorization work for the handlers.
*
* @param user
* @param request
* @return authorizationResponse
* @throws AuthorizationException
*/
public AuthorizationResponse authorized(IUser user,
RemoteScriptRequest request) throws AuthorizationException {
AuthManager manager = AuthManagerFactory.getInstance().getManager();
IRoleStorage roleStorage = manager.getRoleStorage();
String roleId = getRoleId();
boolean authorized = roleStorage.isAuthorized(roleId, user.uniqueId()
.toString(), APPLICATION);
if (authorized) {
return new AuthorizationResponse(authorized);
} else {
String message = "Not Authorized to run " + roleId;
if (statusHandler.isPriorityEnabled(Priority.INFO)) {
statusHandler.handle(Priority.INFO,
String.format("%s, %s", user.uniqueId(), message));
}
return new AuthorizationResponse(message);
}
}
}

View file

@ -0,0 +1,103 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.remote.script;
import com.raytheon.uf.common.localization.IPathManager;
import com.raytheon.uf.common.localization.LocalizationContext;
import com.raytheon.uf.common.localization.LocalizationFile;
import com.raytheon.uf.common.localization.PathManagerFactory;
import com.raytheon.uf.common.remote.script.RemoteScriptListRequest;
import com.raytheon.uf.common.remote.script.RemoteScriptListResponse;
import com.raytheon.uf.common.remote.script.RemoteScriptRequest;
import com.raytheon.uf.common.status.UFStatus.Priority;
/**
* Handler to get the remote script list.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 14, 2014 2742 rferrel Initial creation
* Exclude files with md5 checksum extension.
*
* </pre>
*
* @author rferrel
* @version 1.0
*/
public class RemoteScriptListHandler extends AbstractRemoteScriptHandler {
/** Extension for check sum files to remove from listing. */
private final String MD5_EXT = ".md5";
/**
* Constructor.
*/
public RemoteScriptListHandler() {
// The role id in the common remoteScriptAdminRoles.xml
super("remote.script.list");
}
/*
* (non-Javadoc)
*
* @see
* com.raytheon.uf.edex.remote.script.RemoteScriptHandler#performRequest
* (com.raytheon.uf.common.remote.script.RemoteScriptRequest)
*/
public Object performRequest(RemoteScriptRequest request) {
IPathManager pm = PathManagerFactory.getPathManager();
RemoteScriptListRequest req = (RemoteScriptListRequest) request;
if (statusHandler.isPriorityEnabled(Priority.DEBUG)) {
statusHandler.handle(Priority.DEBUG,
String.format("Request: %s", req));
}
LocalizationContext[] ctxs = req.getContexts();
RemoteScriptListResponse result = new RemoteScriptListResponse();
for (LocalizationContext ctx : ctxs) {
LocalizationFile[] lFiles = pm.listFiles(ctx, scriptsDirectory,
null, false, true);
if ((lFiles != null) && (lFiles.length > 0)) {
for (LocalizationFile lFile : lFiles) {
if (!lFile.getName().trim().endsWith(MD5_EXT)) {
result.add(lFile);
System.out.println(lFile.getFile().getAbsolutePath());
}
}
}
}
if (statusHandler.isPriorityEnabled(Priority.DEBUG)) {
statusHandler.handle(Priority.DEBUG,
String.format("Results: %s", result));
}
return result;
}
}

View file

@ -0,0 +1,303 @@
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.edex.remote.script;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.raytheon.uf.common.comm.HttpClient;
import com.raytheon.uf.common.localization.IPathManager;
import com.raytheon.uf.common.localization.LocalizationContext;
import com.raytheon.uf.common.localization.LocalizationFile;
import com.raytheon.uf.common.localization.PathManagerFactory;
import com.raytheon.uf.common.remote.script.RemoteScriptConstants;
import com.raytheon.uf.common.remote.script.RemoteScriptRequest;
import com.raytheon.uf.common.remote.script.RemoteScriptRunRequest;
import com.raytheon.uf.common.remote.script.RemoteScriptRunResponse;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.common.util.RunProcess;
/**
* Handler to Run a remote script and return the results.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 19, 2014 2743 rferrel Initial creation
*
* </pre>
*
* @author rferrel
* @version 1.0
*/
public class RemoteScriptRunHandler extends AbstractRemoteScriptHandler {
/**
* Time to back off from socket time out to allow completion of a timeout
* script.
*/
private static final int BACKOFF_MSEC = 100;
/**
* Resource timeout.
*/
private final int defaultTimeoutSec;
/**
* Resource flag value.
*/
private final boolean defaultUseStdErrFlag;
/**
* Resource set up exit status.
*/
private final int defaultSetupExit;
/**
* Constructor setup roleId and resource property values.
*/
public RemoteScriptRunHandler() {
// The role id in the common remoteScriptAdminRoles.xml
super("remote.script.run");
// Set up default values.
String defaultTimeoutStr = System.getProperty(
RemoteScriptConstants.scriptTimeoutKey,
RemoteScriptConstants.scriptTimeoutDefault);
int defaultTimeoutSec = -1;
try {
defaultTimeoutSec = Integer.parseInt(defaultTimeoutStr);
} catch (NumberFormatException ex) {
defaultTimeoutSec = -1;
} finally {
if (defaultTimeoutSec <= 0) {
defaultTimeoutSec = Integer
.parseInt(RemoteScriptConstants.scriptTimeoutDefault);
}
this.defaultTimeoutSec = defaultTimeoutSec;
}
String defaultUseStdErr = System.getProperty(
RemoteScriptConstants.scriptUseStdErrKey,
RemoteScriptConstants.scriptUseStdErrDefault);
this.defaultUseStdErrFlag = Boolean.parseBoolean(defaultUseStdErr);
String defaultSetupErrorStr = System.getProperty(
RemoteScriptConstants.scriptSetupErrrorKey,
RemoteScriptConstants.scriptUseStdErrDefault);
int defaultSetupExit = 0;
try {
defaultSetupExit = Integer.parseInt(defaultSetupErrorStr);
} catch (NumberFormatException ex) {
defaultSetupExit = 0;
} finally {
if (defaultSetupExit <= 0) {
defaultSetupExit = Integer
.parseInt(RemoteScriptConstants.scriptSetUpErrorDefault);
}
this.defaultSetupExit = defaultSetupExit;
}
}
/*
* (non-Javadoc)
*
* @see
* com.raytheon.uf.common.serialization.comm.IRequestHandler#handleRequest
* (com.raytheon.uf.common.serialization.comm.IServerRequest)
*/
@Override
public Object handleRequest(RemoteScriptRequest request) throws Exception {
return super.handleRequest(request);
}
/*
* (non-Javadoc)
*
* @see
* com.raytheon.uf.edex.remote.script.RemoteScriptHandler#performRequest
* (com.raytheon.uf.common.remote.script.RemoteScriptRequest)
*/
public Object performRequest(RemoteScriptRequest request) {
RemoteScriptRunRequest req = (RemoteScriptRunRequest) request;
RemoteScriptRunResponse result = new RemoteScriptRunResponse();
Map<String, String> propMap = req.getPropertyMap();
String timeoutValue = propMap
.get(RemoteScriptConstants.scriptTimeoutKey);
int timeoutSec = -1;
if (timeoutValue == null) {
timeoutSec = defaultTimeoutSec;
} else {
try {
timeoutSec = Integer.parseInt(timeoutValue);
if (timeoutSec <= 0) {
timeoutSec = defaultTimeoutSec;
}
} catch (NumberFormatException ex) {
statusHandler.handle(Priority.PROBLEM,
String.format("Bad timeout value %s", timeoutValue));
timeoutSec = defaultTimeoutSec;
} finally {
if (timeoutSec <= 0) {
timeoutSec = defaultTimeoutSec;
}
}
}
long timeout = timeoutSec * TimeUtil.MILLIS_PER_SECOND;
String useStdErrString = propMap
.get(RemoteScriptConstants.scriptUseStdErrKey);
boolean useStdErr = defaultUseStdErrFlag;
if (useStdErrString != null) {
useStdErr = Boolean.parseBoolean(useStdErrString);
}
String setupExitValue = propMap
.get(RemoteScriptConstants.scriptSetupErrrorKey);
int setupExit = -1;
if (setupExitValue == null) {
setupExit = defaultSetupExit;
} else {
try {
setupExit = Integer.parseInt(setupExitValue);
} catch (NumberFormatException ex) {
statusHandler.handle(Priority.PROBLEM, String.format(
"Bad setup Error exit value %s", setupExitValue));
setupExit = defaultSetupExit;
} finally {
if (setupExit <= 0) {
setupExit = defaultSetupExit;
}
}
}
List<String> arguments = req.getScriptArguments();
String script = req.getScript();
LocalizationContext context = req.getContext();
IPathManager pm = PathManagerFactory.getPathManager();
String name = scriptsDirectory + IPathManager.SEPARATOR + script;
LocalizationFile lFile = pm.getLocalizationFile(context, name);
File file = lFile.getFile();
File dir = file.getParentFile();
if (!file.canExecute()) {
String message = String.format("Not an executable script: \"%s\".",
lFile);
return sendMessage(result, message, useStdErr, setupExit);
}
int maxTimeout = HttpClient.getInstance().getSocketTimeout()
- BACKOFF_MSEC;
if (maxTimeout <= 0) {
String message = String
.format("HttpClient's socket timeout of %d msec not enough time to run a remote script.",
HttpClient.getInstance().getSocketTimeout());
return sendMessage(result, message, useStdErr, setupExit);
} else if (timeout > maxTimeout) {
timeout = maxTimeout;
}
List<String> args = new ArrayList<String>();
args.add(file.getAbsolutePath());
if (arguments != null && (arguments.size() > 0)) {
args.addAll(arguments);
}
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectErrorStream(!useStdErr);
pb.directory(dir);
Process p = null;
RunProcess rp = RunProcess.getRunProcess();
String errorMessage = null;
// TODO - The timeout/destroy should be placed in RunProcess along with
// limiting the size of stdout/stderr.
try {
p = pb.start();
rp.setProcess(p);
synchronized (rp) {
rp.wait(timeout);
if (!rp.isExecComplete()) {
p.destroy();
result.setTimedOut(true);
rp.notify();
errorMessage = "Script timed out.";
}
}
} catch (Exception ex) {
errorMessage = "Problem running script: "
+ ex.getLocalizedMessage().trim();
statusHandler.handle(Priority.PROBLEM, errorMessage, ex);
} finally {
if (p != null) {
result.setOutput(rp.getStdout());
result.setError(rp.getStderr());
}
result.setExitStatus(rp.waitFor());
if (errorMessage != null) {
if (useStdErr) {
result.setError(result.getError() + "\n" + errorMessage);
} else {
result.setOutput(result.getOutput() + "\n" + errorMessage);
}
}
}
return result;
}
/**
* Report a problem in running the script.
*
* @param result
* @param message
* @param useStdErr
* @param setupExit
* @return result
*/
private RemoteScriptRunResponse sendMessage(RemoteScriptRunResponse result,
String message, boolean useStdErr, int setupExit) {
statusHandler.handle(Priority.PROBLEM, message);
if (useStdErr) {
result.setError(message);
} else {
result.setOutput(message);
}
result.setExitStatus(setupExit);
return result;
}
}

View file

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<nwsRoleData xmlns:ns2="group">
<application>Remote Script</application>
<!-- Remote Script List permission.-->
<permission id="remote.script.list">
<description>
This permission allows the user to retrive a listing of remote scripts.
</description>
</permission>
<!-- Remote Script Execute permission. -->
<permission id="remote.script.run">
<description>
This permission allows the user to execute a remote script.
</description>
</permission>
<user userId="ALL">
<userPermission>remote.script.list</userPermission>
<userPermission>remote.script.run</userPermission>
</user>
</nwsRoleData>

View file

@ -0,0 +1,32 @@
#!/bin/sh
usage(){
cat <<EOF
This script is used to test the remote script execution in CAVE/NCP.
It sleeps certain number of seconds. The return code is zero if the
script runs successfully.
Usage: test_script numberSeconds
-<numberSeconds>: number of seconds to sleep.
--help print out usage
EOF
exit
}
if [ $# -lt 1 ]; then
usage
fi
if [ "$1" == "--help" ]; then
usage
else
sleep $1
if [ "$?" == 0 ]; then
echo Sleeping...$1 seconds...Done!
exit 0
else
exit -1
fi
fi

View file

@ -35,6 +35,9 @@ Import-Package: com.raytheon.uf.common.serialization.comm,
com.raytheon.uf.viz.d2d.ui.perspectives,
com.raytheon.uf.viz.sounding,
com.vividsolutions.jts.geom,
gov.noaa.nws.ncep.common.dataplugin.gpd,
gov.noaa.nws.ncep.common.dataplugin.gpd.product,
gov.noaa.nws.ncep.common.dataplugin.gpd.query,
gov.noaa.nws.ncep.common.dataplugin.ncuair,
gov.noaa.nws.ncep.edex.common.ncinventory,
gov.noaa.nws.ncep.edex.common.sounding,

View file

@ -1,4 +1,5 @@
package gov.noaa.nws.ncep.ui.nsharp;
/**
*
* gov.noaa.nws.ncep.ui.nsharp.NsharpDataPageProperty
@ -24,128 +25,153 @@ import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.raytheon.uf.common.serialization.ISerializableObject;
@XmlRootElement(name = "NsharpDataPageProperty")
@XmlAccessorType(XmlAccessType.NONE)
public class NsharpDataPageProperty implements ISerializableObject{
@XmlAttribute
private int summary1Page=NsharpConstants.PAGE_SUMMARY1;
@XmlAttribute
private int summary2Page=NsharpConstants.PAGE_SUMMARY2;
public class NsharpDataPageProperty implements ISerializableObject {
@XmlAttribute
private int summary1Page = NsharpConstants.PAGE_SUMMARY1;
@XmlAttribute
private int parcelDataPage=NsharpConstants.PAGE_PARCEL_DATA;
@XmlAttribute
private int thermodynamicDataPage=NsharpConstants.PAGE_THERMODYNAMIC_DATA;
@XmlAttribute
private int opcDataPage=NsharpConstants.PAGE_OPC_DATA;
@XmlAttribute
private int mixingHeightPage=NsharpConstants.PAGE_MIXING_HEIGHT;
@XmlAttribute
private int stormRelativePage=NsharpConstants.PAGE_STORM_RELATIVE;
@XmlAttribute
private int meanWindPage=NsharpConstants.PAGE_MEAN_WIND;
@XmlAttribute
private int convectiveInitiationPage=NsharpConstants.PAGE_CONVECTIVE_INITIATION;
@XmlAttribute
private int severePotentialPage=NsharpConstants.PAGE_SEVERE_POTENTIAL;
@XmlAttribute
private int summary2Page = NsharpConstants.PAGE_SUMMARY2;
@XmlAttribute
private int numberPagePerDisplay = 1;
public int getSummary1Page() {
return summary1Page;
}
@XmlAttribute
private int parcelDataPage = NsharpConstants.PAGE_PARCEL_DATA;
public void setSummary1Page(int summary1Page) {
this.summary1Page = summary1Page;
}
@XmlAttribute
private int thermodynamicDataPage = NsharpConstants.PAGE_THERMODYNAMIC_DATA;
public int getSummary2Page() {
return summary2Page;
}
@XmlAttribute
private int opcDataPage = NsharpConstants.PAGE_OPC_DATA;
public void setSummary2Page(int summary2Page) {
this.summary2Page = summary2Page;
}
@XmlAttribute
private int mixingHeightPage = NsharpConstants.PAGE_MIXING_HEIGHT;
public int getParcelDataPage() {
return parcelDataPage;
}
@XmlAttribute
private int stormRelativePage = NsharpConstants.PAGE_STORM_RELATIVE;
public void setParcelDataPage(int parcelDataPage) {
this.parcelDataPage = parcelDataPage;
}
@XmlAttribute
private int meanWindPage = NsharpConstants.PAGE_MEAN_WIND;
public int getThermodynamicDataPage() {
return thermodynamicDataPage;
}
@XmlAttribute
private int convectiveInitiationPage = NsharpConstants.PAGE_CONVECTIVE_INITIATION;
public void setThermodynamicDataPage(int thermodynamicDataPage) {
this.thermodynamicDataPage = thermodynamicDataPage;
}
@XmlAttribute
private int severePotentialPage = NsharpConstants.PAGE_SEVERE_POTENTIAL;
public int getOpcDataPage() {
return opcDataPage;
}
// d2dlite
@XmlAttribute
private int d2dLitePage = NsharpConstants.PAGE_D2DLITE;
public void setOpcDataPage(int opcDataPage) {
this.opcDataPage = opcDataPage;
}
// d2dlite
@XmlAttribute
private int futurePage = NsharpConstants.PAGE_FUTURE;
public int getMixingHeightPage() {
return mixingHeightPage;
}
@XmlAttribute
private int numberPagePerDisplay = 1;
public void setMixingHeightPage(int mixingHeightPage) {
this.mixingHeightPage = mixingHeightPage;
}
public int getSummary1Page() {
return summary1Page;
}
public int getStormRelativePage() {
return stormRelativePage;
}
public void setSummary1Page(int summary1Page) {
this.summary1Page = summary1Page;
}
public void setStormRelativePage(int stormRelativePage) {
this.stormRelativePage = stormRelativePage;
}
public int getSummary2Page() {
return summary2Page;
}
public int getMeanWindPage() {
return meanWindPage;
}
public void setSummary2Page(int summary2Page) {
this.summary2Page = summary2Page;
}
public void setMeanWindPage(int meanWindPage) {
this.meanWindPage = meanWindPage;
}
public int getParcelDataPage() {
return parcelDataPage;
}
public int getConvectiveInitiationPage() {
return convectiveInitiationPage;
}
public void setParcelDataPage(int parcelDataPage) {
this.parcelDataPage = parcelDataPage;
}
public void setConvectiveInitiationPage(int convectiveInitiationPage) {
this.convectiveInitiationPage = convectiveInitiationPage;
}
public int getThermodynamicDataPage() {
return thermodynamicDataPage;
}
public int getSeverePotentialPage() {
return severePotentialPage;
}
public void setThermodynamicDataPage(int thermodynamicDataPage) {
this.thermodynamicDataPage = thermodynamicDataPage;
}
public void setSeverePotentialPage(int severePotentialPage) {
this.severePotentialPage = severePotentialPage;
}
public int getOpcDataPage() {
return opcDataPage;
}
public int getNumberPagePerDisplay() {
return numberPagePerDisplay;
}
public void setOpcDataPage(int opcDataPage) {
this.opcDataPage = opcDataPage;
}
public void setNumberPagePerDisplay(int numberPagePerDisplay) {
this.numberPagePerDisplay = numberPagePerDisplay;
}
public int getMixingHeightPage() {
return mixingHeightPage;
}
public void setMixingHeightPage(int mixingHeightPage) {
this.mixingHeightPage = mixingHeightPage;
}
public int getStormRelativePage() {
return stormRelativePage;
}
public void setStormRelativePage(int stormRelativePage) {
this.stormRelativePage = stormRelativePage;
}
public int getMeanWindPage() {
return meanWindPage;
}
public void setMeanWindPage(int meanWindPage) {
this.meanWindPage = meanWindPage;
}
public int getConvectiveInitiationPage() {
return convectiveInitiationPage;
}
public void setConvectiveInitiationPage(int convectiveInitiationPage) {
this.convectiveInitiationPage = convectiveInitiationPage;
}
public int getSeverePotentialPage() {
return severePotentialPage;
}
public void setSeverePotentialPage(int severePotentialPage) {
this.severePotentialPage = severePotentialPage;
}
public int getNumberPagePerDisplay() {
return numberPagePerDisplay;
}
public void setNumberPagePerDisplay(int numberPagePerDisplay) {
this.numberPagePerDisplay = numberPagePerDisplay;
}
// d2dlite
public int getD2dLitePage() {
return d2dLitePage;
}
public void setD2dLitePage(int d2dLitePage) {
this.d2dLitePage = d2dLitePage;
}
public int getFuturePage() {
return futurePage;
}
public void setFuturePage(int futurePage) {
this.futurePage = futurePage;
}
}

View file

@ -1,4 +1,5 @@
package gov.noaa.nws.ncep.ui.nsharp;
/**
*
* gov.noaa.nws.ncep.ui.nsharp.NsharpGraphProperty
@ -33,330 +34,342 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.eclipse.swt.graphics.RGB;
import com.raytheon.uf.common.serialization.ISerializableObject;
@XmlRootElement(name = "NsharpGraphProperty")
@XmlAccessorType(XmlAccessType.NONE)
public class NsharpGraphProperty implements ISerializableObject{
@XmlAttribute
private boolean temp=true;
@XmlAttribute
private boolean dewp=true;
@XmlAttribute
private boolean parcelTv=true;
@XmlAttribute
private boolean parcel=true;
@XmlAttribute
private boolean dcape=true;
@XmlAttribute
private boolean VTemp=true;
@XmlAttribute
private boolean wetBulb=true;
@XmlAttribute
private boolean mixratio=false;
@XmlAttribute
private boolean dryAdiabat=true;
@XmlAttribute
private boolean moistAdiabat=false;
@XmlAttribute
private boolean effLayer=true;
@XmlAttribute
private boolean cloud=false;
@XmlAttribute
private boolean hodo=true;
@XmlAttribute
private boolean meanWind=true;
@XmlAttribute
private boolean smv3075=false;
@XmlAttribute
private boolean smv1585=false;
@XmlAttribute
private boolean smvBunkersR=true;
@XmlAttribute
private boolean smvBunkersL=true;
@XmlAttribute
private boolean omega=true;
@XmlAttribute
private boolean corfidiV=false;
@XmlAttribute
private boolean windBarb=true;
@XmlAttribute
private int windBarbDistance=NsharpConstants.WINDBARB_DISTANCE_DEFAULT;
@XmlAttribute
private int tempOffset=0;
@XmlAttribute
private String paneConfigurationName= NsharpConstants.PANE_DEF_CFG_1_STR;
@XmlAttribute
private List<String> gribModelTypeList = new ArrayList<String>();
@XmlAttribute
private float windBarbLineWidth=NsharpConstants.WINDBARB_WIDTH;
@XmlAttribute
private float windBarbSize=NsharpConstants.WINDBARB_SIZE;
@XmlElement
public class NsharpGraphProperty implements ISerializableObject {
@XmlAttribute
private boolean temp = true;
@XmlAttribute
private boolean dewp = true;
@XmlAttribute
private boolean parcelTv = true;
@XmlAttribute
private boolean parcel = true;
@XmlAttribute
private boolean dcape = true;
@XmlAttribute
private boolean VTemp = true;
@XmlAttribute
private boolean wetBulb = true;
@XmlAttribute
private boolean mixratio = false;
@XmlAttribute
private boolean dryAdiabat = true;
@XmlAttribute
private boolean moistAdiabat = false;
@XmlAttribute
private boolean effLayer = true;
@XmlAttribute
private boolean cloud = false;
@XmlAttribute
private boolean hodo = true;
@XmlAttribute
private boolean meanWind = true;
@XmlAttribute
private boolean smv3075 = false;
@XmlAttribute
private boolean smv1585 = false;
@XmlAttribute
private boolean smvBunkersR = true;
@XmlAttribute
private boolean smvBunkersL = true;
@XmlAttribute
private boolean omega = true;
@XmlAttribute
private boolean corfidiV = false;
@XmlAttribute
private boolean windBarb = true;
@XmlAttribute
private int windBarbDistance = NsharpConstants.WINDBARB_DISTANCE_DEFAULT;
@XmlAttribute
private int tempOffset = 0;
@XmlAttribute
private String paneConfigurationName = NsharpConstants.PANE_DEF_CFG_1_STR;
@XmlAttribute
private List<String> gribModelTypeList = new ArrayList<String>();
@XmlAttribute
private float windBarbLineWidth = NsharpConstants.WINDBARB_WIDTH;
@XmlAttribute
private float windBarbSize = NsharpConstants.WINDBARB_SIZE;
@XmlElement
@XmlJavaTypeAdapter(RGBColorAdapter.class)
private RGB windBarbColor= NsharpConstants.color_yellow;
@XmlAttribute
private boolean showFilteredWindInCircle=false;
public boolean isTemp() {
return temp;
}
private RGB windBarbColor = NsharpConstants.color_yellow;
public void setTemp(boolean temp) {
this.temp = temp;
}
@XmlAttribute
private boolean showFilteredWindInCircle = false;
public boolean isDewp() {
return dewp;
}
@XmlAttribute
private int sndCompRadius = 0; // FixMark:nearByStnCompSnd
public void setDewp(boolean dewp) {
this.dewp = dewp;
}
public boolean isTemp() {
return temp;
}
public boolean isParcelTv() {
return parcelTv;
}
public void setTemp(boolean temp) {
this.temp = temp;
}
public void setParcelTv(boolean parcelTv) {
this.parcelTv = parcelTv;
}
public boolean isDewp() {
return dewp;
}
public boolean isParcel() {
return parcel;
}
public void setDewp(boolean dewp) {
this.dewp = dewp;
}
public void setParcel(boolean parcel) {
this.parcel = parcel;
}
public boolean isParcelTv() {
return parcelTv;
}
public boolean isDcape() {
return dcape;
}
public void setParcelTv(boolean parcelTv) {
this.parcelTv = parcelTv;
}
public void setDcape(boolean dcape) {
this.dcape = dcape;
}
public boolean isParcel() {
return parcel;
}
public boolean isVTemp() {
return VTemp;
}
public void setParcel(boolean parcel) {
this.parcel = parcel;
}
public void setVTemp(boolean vTemp) {
VTemp = vTemp;
}
public boolean isDcape() {
return dcape;
}
public boolean isWetBulb() {
return wetBulb;
}
public void setDcape(boolean dcape) {
this.dcape = dcape;
}
public void setWetBulb(boolean wetBulb) {
this.wetBulb = wetBulb;
}
public boolean isVTemp() {
return VTemp;
}
public boolean isMixratio() {
return mixratio;
}
public void setVTemp(boolean vTemp) {
VTemp = vTemp;
}
public void setMixratio(boolean mixratio) {
this.mixratio = mixratio;
}
public boolean isWetBulb() {
return wetBulb;
}
public boolean isDryAdiabat() {
return dryAdiabat;
}
public void setWetBulb(boolean wetBulb) {
this.wetBulb = wetBulb;
}
public void setDryAdiabat(boolean dryAdiabat) {
this.dryAdiabat = dryAdiabat;
}
public boolean isMixratio() {
return mixratio;
}
public boolean isMoistAdiabat() {
return moistAdiabat;
}
public void setMixratio(boolean mixratio) {
this.mixratio = mixratio;
}
public void setMoistAdiabat(boolean moistAdiabat) {
this.moistAdiabat = moistAdiabat;
}
public boolean isDryAdiabat() {
return dryAdiabat;
}
public boolean isEffLayer() {
return effLayer;
}
public void setDryAdiabat(boolean dryAdiabat) {
this.dryAdiabat = dryAdiabat;
}
public void setEffLayer(boolean effLayer) {
this.effLayer = effLayer;
}
public boolean isMoistAdiabat() {
return moistAdiabat;
}
public boolean isCloud() {
return cloud;
}
public void setMoistAdiabat(boolean moistAdiabat) {
this.moistAdiabat = moistAdiabat;
}
public void setCloud(boolean cloud) {
this.cloud = cloud;
}
public boolean isEffLayer() {
return effLayer;
}
public boolean isHodo() {
return hodo;
}
public void setEffLayer(boolean effLayer) {
this.effLayer = effLayer;
}
public void setHodo(boolean hodo) {
this.hodo = hodo;
}
public boolean isCloud() {
return cloud;
}
public boolean isMeanWind() {
return meanWind;
}
public void setCloud(boolean cloud) {
this.cloud = cloud;
}
public void setMeanWind(boolean meanWind) {
this.meanWind = meanWind;
}
public boolean isHodo() {
return hodo;
}
public boolean isSmv3075() {
return smv3075;
}
public void setHodo(boolean hodo) {
this.hodo = hodo;
}
public void setSmv3075(boolean smv3075) {
this.smv3075 = smv3075;
}
public boolean isMeanWind() {
return meanWind;
}
public boolean isSmv1585() {
return smv1585;
}
public void setMeanWind(boolean meanWind) {
this.meanWind = meanWind;
}
public void setSmv1585(boolean smv1585) {
this.smv1585 = smv1585;
}
public boolean isSmv3075() {
return smv3075;
}
public boolean isSmvBunkersR() {
return smvBunkersR;
}
public void setSmv3075(boolean smv3075) {
this.smv3075 = smv3075;
}
public void setSmvBunkersR(boolean smvBunkersR) {
this.smvBunkersR = smvBunkersR;
}
public boolean isSmv1585() {
return smv1585;
}
public boolean isSmvBunkersL() {
return smvBunkersL;
}
public void setSmv1585(boolean smv1585) {
this.smv1585 = smv1585;
}
public void setSmvBunkersL(boolean smvBunkersL) {
this.smvBunkersL = smvBunkersL;
}
public boolean isSmvBunkersR() {
return smvBunkersR;
}
public boolean isOmega() {
return omega;
}
public void setSmvBunkersR(boolean smvBunkersR) {
this.smvBunkersR = smvBunkersR;
}
public void setOmega(boolean omega) {
this.omega = omega;
}
public boolean isSmvBunkersL() {
return smvBunkersL;
}
public void setSmvBunkersL(boolean smvBunkersL) {
this.smvBunkersL = smvBunkersL;
}
public boolean isCorfidiV() {
return corfidiV;
}
public boolean isOmega() {
return omega;
}
public void setCorfidiV(boolean corfidiV) {
this.corfidiV = corfidiV;
}
public void setOmega(boolean omega) {
this.omega = omega;
}
public boolean isWindBarb() {
return windBarb;
}
public boolean isCorfidiV() {
return corfidiV;
}
public void setWindBarb(boolean windBarb) {
this.windBarb = windBarb;
}
public void setCorfidiV(boolean corfidiV) {
this.corfidiV = corfidiV;
}
public int getWindBarbDistance() {
return windBarbDistance;
}
public boolean isWindBarb() {
return windBarb;
}
public void setWindBarbDistance(int windBarbDistance) {
this.windBarbDistance = windBarbDistance;
}
public void setWindBarb(boolean windBarb) {
this.windBarb = windBarb;
}
public int getTempOffset() {
return tempOffset;
}
public int getWindBarbDistance() {
return windBarbDistance;
}
public void setTempOffset(int tempOffset) {
this.tempOffset = tempOffset;
}
public void setWindBarbDistance(int windBarbDistance) {
this.windBarbDistance = windBarbDistance;
}
public String getPaneConfigurationName() {
return paneConfigurationName;
}
public int getTempOffset() {
return tempOffset;
}
public void setPaneConfigurationName(String paneConfigurationName) {
this.paneConfigurationName = paneConfigurationName;
}
public void setTempOffset(int tempOffset) {
this.tempOffset = tempOffset;
}
public List<String> getGribModelTypeList() {
return gribModelTypeList;
}
// FixMark:nearByStnCompSnd
public int getSndCompRadius() {
return sndCompRadius;
}
public void setGribModelTypeList(List<String> gribModelTypeList) {
this.gribModelTypeList = gribModelTypeList;
}
public void setSndCompRadius(int sndCompRadius) {
this.sndCompRadius = sndCompRadius;
}
public float getWindBarbLineWidth() {
return windBarbLineWidth;
}
// end FixMark:nearByStnCompSnd
public void setWindBarbLineWidth(float windBarbLineWidth) {
this.windBarbLineWidth = windBarbLineWidth;
}
public String getPaneConfigurationName() {
return paneConfigurationName;
}
public float getWindBarbSize() {
return windBarbSize;
}
public void setPaneConfigurationName(String paneConfigurationName) {
this.paneConfigurationName = paneConfigurationName;
}
public void setWindBarbSize(float windBarbSize) {
this.windBarbSize = windBarbSize;
}
public List<String> getGribModelTypeList() {
return gribModelTypeList;
}
public RGB getWindBarbColor() {
return windBarbColor;
}
public void setGribModelTypeList(List<String> gribModelTypeList) {
this.gribModelTypeList = gribModelTypeList;
}
public void setWindBarbColor(RGB windBarbColor) {
this.windBarbColor = windBarbColor;
}
public float getWindBarbLineWidth() {
return windBarbLineWidth;
}
public boolean isShowFilteredWindInCircle() {
return showFilteredWindInCircle;
}
public void setWindBarbLineWidth(float windBarbLineWidth) {
this.windBarbLineWidth = windBarbLineWidth;
}
public void setShowFilteredWindInCircle(boolean showFilteredWindInCircle) {
this.showFilteredWindInCircle = showFilteredWindInCircle;
}
public float getWindBarbSize() {
return windBarbSize;
}
public void setWindBarbSize(float windBarbSize) {
this.windBarbSize = windBarbSize;
}
public RGB getWindBarbColor() {
return windBarbColor;
}
public void setWindBarbColor(RGB windBarbColor) {
this.windBarbColor = windBarbColor;
}
public boolean isShowFilteredWindInCircle() {
return showFilteredWindInCircle;
}
public void setShowFilteredWindInCircle(boolean showFilteredWindInCircle) {
this.showFilteredWindInCircle = showFilteredWindInCircle;
}
}

View file

@ -43,347 +43,408 @@ import com.raytheon.viz.core.graphing.WGraphics;
import com.vividsolutions.jts.geom.Coordinate;
public class NsharpIcingPaneBackground extends NsharpGenericPaneBackground {
//private NsharpSkewTPaneDescriptor desc;
private IWireframeShape linesNumbersShape;
private IWireframeShape RHLabelShape;
private IWireframeShape tempLabelShape;
private IWireframeShape EPILabelShape;//Equivalent Potential Instability
private double currentZoomLevel=1;
private final float defaultLabelSpace = 50;
private float labelSpace = defaultLabelSpace;
private int iceXOrig=NsharpConstants.ICING_X_ORIG;
private int iceYOrig=NsharpConstants.ICING_Y_ORIG+(int)labelSpace;
private int iceXEnd=NsharpConstants.ICING_X_END;
private int iceWidth=NsharpConstants.ICING_WIDTH;
private int iceYEnd=iceYOrig+NsharpConstants.ICING_HEIGHT;
private int paneHeight = NsharpConstants.SKEWT_HEIGHT;
private float yMagFactor=1;
private float xMagFactor=1;
private NsharpGraphProperty graphConfigProperty;
public NsharpIcingPaneBackground(NsharpSkewTPaneDescriptor desc) {
// private NsharpSkewTPaneDescriptor desc;
private IWireframeShape linesNumbersShape;
private IWireframeShape RHLabelShape;
private IWireframeShape tempLabelShape;
private IWireframeShape EPILabelShape;// Equivalent Potential Instability
private double currentZoomLevel = 1;
private final float defaultLabelSpace = 50;
private float labelSpace = defaultLabelSpace;
private int iceXOrig = NsharpConstants.ICING_X_ORIG;
private int iceYOrig = NsharpConstants.ICING_Y_ORIG + (int) labelSpace;
private int iceXEnd = NsharpConstants.ICING_X_END;
private int iceWidth = NsharpConstants.ICING_WIDTH;
private int iceYEnd = iceYOrig + NsharpConstants.ICING_HEIGHT;
private int paneHeight = NsharpConstants.SKEWT_HEIGHT;
private float yMagFactor = 1;
private float xMagFactor = 1;
private NsharpGraphProperty graphConfigProperty;
public NsharpIcingPaneBackground(NsharpSkewTPaneDescriptor desc) {
super();
this.rectangle = new Rectangle(iceXOrig, iceYOrig,
iceWidth, NsharpConstants.ICING_HEIGHT);
this.rectangle = new Rectangle(iceXOrig, iceYOrig, iceWidth,
NsharpConstants.ICING_HEIGHT);
pe = new PixelExtent(this.rectangle);
world = new WGraphics(this.rectangle);
NsharpConfigManager configMgr = NsharpConfigManager.getInstance();
graphConfigProperty = configMgr.retrieveNsharpConfigStoreFromFs().getGraphProperty();
//System.out.println("NsharpIcingPaneBackground created");
graphConfigProperty = configMgr.retrieveNsharpConfigStoreFromFs()
.getGraphProperty();
// System.out.println("NsharpIcingPaneBackground created");
this.desc = desc;
}
@Override
protected WGraphics computeWorld() {
// TODO Auto-generated method stub
return null;
}
private void createAllShapes(){
IExtent ext = desc.getRenderableDisplay().getExtent();
double xmin = ext.getMinX(); //Extent's viewable envelope min x and y
double ymax = ext.getMaxY();
@Override
protected WGraphics computeWorld() {
// TODO Auto-generated method stub
return null;
}
private void createAllShapes() {
IExtent ext = desc.getRenderableDisplay().getExtent();
double xmin = ext.getMinX(); // Extent's viewable envelope min x and y
double ymax = ext.getMaxY();
double ymin = ext.getMinY();
double dispX,pX=0;
double dispY, pY=0;
double dispX, pX = 0;
double dispY, pY = 0;
String s = "";
linesNumbersShape = target.createWireframeShape(false,desc );
tempLabelShape = target.createWireframeShape(false,desc );
RHLabelShape = target.createWireframeShape(false,desc );
EPILabelShape = target.createWireframeShape(false,desc );
linesNumbersShape = target.createWireframeShape(false, desc);
tempLabelShape = target.createWireframeShape(false, desc);
RHLabelShape = target.createWireframeShape(false, desc);
EPILabelShape = target.createWireframeShape(false, desc);
linesNumbersShape.allocate(100);
tempLabelShape.allocate(20);
RHLabelShape.allocate(20);
EPILabelShape.allocate(4);
//set world based on pressure/RH
world.setWorldCoordinates(NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT, toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP),
NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT, toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
pX= world.mapX( NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT);
if(pX < xmin)
dispX = xmin + 20 * currentZoomLevel*xMagFactor;
// set world based on pressure/RH
world.setWorldCoordinates(NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT,
toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP),
NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT,
toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
pX = world.mapX(NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT);
if (pX < xmin)
dispX = xmin + 20 * currentZoomLevel * xMagFactor;
else
dispX = pX + 20 * currentZoomLevel*xMagFactor;
//pressure lines and labels
for (double i = NsharpConstants.ICING_PRESSURE_LEVEL_TOP; i <= NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM; i=i+ NsharpConstants.ICING_PRESSURE_LEVEL_INC) {
//Pressure lines
double [][] lines = {{iceXOrig, world.mapY(toLogScale(i))},{iceXEnd, world.mapY(toLogScale(i))}};
linesNumbersShape.addLineSegment(lines);
s = NsharpConstants.pressFormat.format(i);
//pressure labels
dispY = world.mapY(toLogScale(i))+5;
double [] lblXy = {dispX,dispY};
linesNumbersShape.addLabel(s, lblXy);
dispX = pX + 20 * currentZoomLevel * xMagFactor;
// pressure lines and labels
for (double i = NsharpConstants.ICING_PRESSURE_LEVEL_TOP; i <= NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM; i = i
+ NsharpConstants.ICING_PRESSURE_LEVEL_INC) {
// Pressure lines
double[][] lines = { { iceXOrig, world.mapY(toLogScale(i)) },
{ iceXEnd, world.mapY(toLogScale(i)) } };
linesNumbersShape.addLineSegment(lines);
s = NsharpConstants.pressFormat.format(i);
// pressure labels
dispY = world.mapY(toLogScale(i)) + 5;
double[] lblXy = { dispX, dispY };
linesNumbersShape.addLabel(s, lblXy);
}
//RHLabel
//double [] lblRhXy = {iceXOrig+ iceWidth/2, iceYOrig-45};
//RHLabelShape.addLabel("*****ICING Display*****", lblRhXy);
double [] lblRhXy1 = {iceXOrig+iceWidth/2,iceYOrig-35*yMagFactor};
RHLabelShape.addLabel("*****ICING Display***** RELATIVE HUMIDITY", lblRhXy1);
double [][] lineRH = {{0,0},{0,0}};
RHLabelShape.addLineSegment(lineRH);//add dummy line
pY = world.mapY(toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP));
if(ymin < pY)
dispY = pY + 20 * currentZoomLevel*yMagFactor;
else
dispY = ymin + 20 * currentZoomLevel*yMagFactor;
for (double i = NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT; i <= NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT; i= i+NsharpConstants.ICING_RELATIVE_HUMIDITY_INC) {
// temperature/humidity vertical lines
double [][] lines = {{world.mapX(i), iceYOrig},{world.mapX(i), iceYEnd}};
linesNumbersShape.addLineSegment(lines);
//RH label
s = NsharpConstants.pressFormat.format(i);
double [] lblXy = {world.mapX(i), dispY};
RHLabelShape.addLabel(s, lblXy);
// RHLabel
// double [] lblRhXy = {iceXOrig+ iceWidth/2, iceYOrig-45};
// RHLabelShape.addLabel("*****ICING Display*****", lblRhXy);
double[] lblRhXy1 = { iceXOrig + iceWidth / 2,
iceYOrig - 35 * yMagFactor };
RHLabelShape.addLabel("*****ICING Display***** RELATIVE HUMIDITY",
lblRhXy1);
double[][] lineRH = { { 0, 0 }, { 0, 0 } };
RHLabelShape.addLineSegment(lineRH);// add dummy line
pY = world.mapY(toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP));
if (ymin < pY)
dispY = pY + 20 * currentZoomLevel * yMagFactor;
else
dispY = ymin + 20 * currentZoomLevel * yMagFactor;
for (double i = NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT; i <= NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT; i = i
+ NsharpConstants.ICING_RELATIVE_HUMIDITY_INC) {
// temperature/humidity vertical lines
double[][] lines = { { world.mapX(i), iceYOrig },
{ world.mapX(i), iceYEnd } };
linesNumbersShape.addLineSegment(lines);
// RH label
s = NsharpConstants.pressFormat.format(i);
double[] lblXy = { world.mapX(i), dispY };
RHLabelShape.addLabel(s, lblXy);
}
//temperature label
double [] lblTXy = {iceXOrig+ iceWidth/2, iceYEnd+20*yMagFactor};
// temperature label
double[] lblTXy = { iceXOrig + iceWidth / 2, iceYEnd + 20 * yMagFactor };
tempLabelShape.addLabel("TEMPERATURE (C)", lblTXy);
double [][] lineT = {{0,0},{0,0}};
tempLabelShape.addLineSegment(lineT);//add dummy line
//set world based on pressure/twmp
world.setWorldCoordinates(NsharpConstants.ICING_TEMPERATURE_LEFT, toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP),
NsharpConstants.ICING_TEMPERATURE_RIGHT, toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
pY = world.mapY(toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
if(ymax > pY)
dispY = pY - 10 * currentZoomLevel*yMagFactor;
else
dispY = ymax - 10 * currentZoomLevel*yMagFactor;
for (double i = NsharpConstants.ICING_TEMPERATURE_LEFT; i <= NsharpConstants.ICING_TEMPERATURE_RIGHT; i= i+NsharpConstants.ICING_TEMPERATURE_INC) {
// temperature label
s = NsharpConstants.pressFormat.format(i);
double [] lblXy = {world.mapX(i),dispY};// iceYEnd+10};
tempLabelShape.addLabel(s, lblXy);
double[][] lineT = { { 0, 0 }, { 0, 0 } };
tempLabelShape.addLineSegment(lineT);// add dummy line
// set world based on pressure/twmp
world.setWorldCoordinates(NsharpConstants.ICING_TEMPERATURE_LEFT,
toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP),
NsharpConstants.ICING_TEMPERATURE_RIGHT,
toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
pY = world
.mapY(toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
if (ymax > pY)
dispY = pY - 10 * currentZoomLevel * yMagFactor;
else
dispY = ymax - 10 * currentZoomLevel * yMagFactor;
for (double i = NsharpConstants.ICING_TEMPERATURE_LEFT; i <= NsharpConstants.ICING_TEMPERATURE_RIGHT; i = i
+ NsharpConstants.ICING_TEMPERATURE_INC) {
// temperature label
s = NsharpConstants.pressFormat.format(i);
double[] lblXy = { world.mapX(i), dispY };// iceYEnd+10};
tempLabelShape.addLabel(s, lblXy);
}
//EPI label
double [] lblEPIXy = {iceXOrig+ iceWidth/2, iceYEnd+35*yMagFactor};
EPILabelShape.addLabel("EQUIVALENT POTENTIAL INSTABILITY x 1E-3 K/m", lblEPIXy);
double [][] lineE = {{0,0},{0,0}};
EPILabelShape.addLineSegment(lineE);//add dummy line
// EPI label
double[] lblEPIXy = { iceXOrig + iceWidth / 2,
iceYEnd + 35 * yMagFactor };
EPILabelShape.addLabel("EQUIVALENT POTENTIAL INSTABILITY x 1E-3 K/m",
lblEPIXy);
double[][] lineE = { { 0, 0 }, { 0, 0 } };
EPILabelShape.addLineSegment(lineE);// add dummy line
linesNumbersShape.compile();
RHLabelShape.compile();
tempLabelShape.compile();
EPILabelShape.compile();
}
@Override
public synchronized void initInternal(IGraphicsTarget target) {
// TODO Auto-generated method stub
super.initInternal(target);
createAllShapes();
}
}
@Override
protected void paintInternal(IGraphicsTarget target,
PaintProperties paintProps) throws VizException {
// TODO Auto-generated method stub
//super.paintInternal(target, paintProps);
target.setupClippingPlane(pe);
target.drawRect(pe, NsharpConstants.backgroundColor, 1.0f, 1.0f);
target.clearClippingPlane();
double zoomLevel = paintProps.getZoomLevel();
if(zoomLevel > 1.0f)
zoomLevel = 1.0f;
if(zoomLevel != currentZoomLevel)
{
currentZoomLevel = zoomLevel;
if(linesNumbersShape!= null){
linesNumbersShape.dispose();
}
if(RHLabelShape!= null){
RHLabelShape.dispose();
}
if(tempLabelShape!= null){
tempLabelShape.dispose();
}
if(EPILabelShape!= null){
EPILabelShape.dispose();
}
createAllShapes();
}
this.smallFont.setSmoothing(false);
this.smallFont.setScaleFont(false);
target.drawWireframeShape(linesNumbersShape, NsharpConstants.pressureColor, 1, LineStyle.SOLID,smallFont);
HashMap<String, NsharpLineProperty> lpMap = ((NsharpSkewTPaneDescriptor)desc).getSkewtResource().getLinePropertyMap();
if(lpMap!=null){
NsharpLineProperty lp =lpMap.get(NsharpConstants.lineNameArray[NsharpConstants.LINE_ICING_RH]);
target.drawWireframeShape(RHLabelShape, lp.getLineColor(), 1, LineStyle.SOLID,smallFont);
lp =lpMap.get(NsharpConstants.lineNameArray[NsharpConstants.LINE_ICING_TEMP]);
target.drawWireframeShape(tempLabelShape,lp.getLineColor(), 1, LineStyle.SOLID,smallFont);
lp =lpMap.get(NsharpConstants.lineNameArray[NsharpConstants.LINE_ICING_EPI]);
target.drawWireframeShape(EPILabelShape, lp.getLineColor(), 1, LineStyle.SOLID,smallFont);
}
else {
target.drawWireframeShape(RHLabelShape, NsharpConstants.color_green, 1, LineStyle.SOLID,smallFont);
target.drawWireframeShape(tempLabelShape, NsharpConstants.color_red, 1, LineStyle.SOLID,smallFont);
target.drawWireframeShape(EPILabelShape, NsharpConstants.color_violet_red, 1, LineStyle.SOLID,smallFont);
}
}
@Override
public void disposeInternal() {
// TODO Auto-generated method stub
super.disposeInternal();
if(linesNumbersShape!= null){
linesNumbersShape.dispose();
}
if(RHLabelShape!= null){
RHLabelShape.dispose();
}
if(tempLabelShape!= null){
tempLabelShape.dispose();
}
if(EPILabelShape!= null){
EPILabelShape.dispose();
}
}
@Override
public double getViewableMaxPressure(){
IExtent ext = desc.getRenderableDisplay().getExtent();
double ymax = ext.getMaxY();
double xmin = ext.getMinX();
world.setWorldCoordinates(NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT, toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP),
NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT, toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
//Coordinate c = world.unMap(xmin, ymax);
double viewablePmax = reverseLogScale(world.unMap(xmin, ymax).y);
@Override
public synchronized void initInternal(IGraphicsTarget target) {
// TODO Auto-generated method stub
super.initInternal(target);
createAllShapes();
}
@Override
protected void paintInternal(IGraphicsTarget target,
PaintProperties paintProps) throws VizException {
// TODO Auto-generated method stub
// super.paintInternal(target, paintProps);
target.setupClippingPlane(pe);
target.drawRect(pe, NsharpConstants.backgroundColor, 1.0f, 1.0f);
target.clearClippingPlane();
double zoomLevel = paintProps.getZoomLevel();
if (zoomLevel > 1.0f)
zoomLevel = 1.0f;
if (zoomLevel != currentZoomLevel) {
currentZoomLevel = zoomLevel;
if (linesNumbersShape != null) {
linesNumbersShape.dispose();
}
if (RHLabelShape != null) {
RHLabelShape.dispose();
}
if (tempLabelShape != null) {
tempLabelShape.dispose();
}
if (EPILabelShape != null) {
EPILabelShape.dispose();
}
createAllShapes();
}
this.smallFont.setSmoothing(false);
this.smallFont.setScaleFont(false);
target.drawWireframeShape(linesNumbersShape,
NsharpConstants.pressureColor, 1, LineStyle.SOLID, smallFont);
HashMap<String, NsharpLineProperty> lpMap = ((NsharpSkewTPaneDescriptor) desc)
.getSkewtResource().getLinePropertyMap();
if (lpMap != null) {
NsharpLineProperty lp = lpMap
.get(NsharpConstants.lineNameArray[NsharpConstants.LINE_ICING_RH]);
target.drawWireframeShape(RHLabelShape, lp.getLineColor(), 1,
LineStyle.SOLID, smallFont);
lp = lpMap
.get(NsharpConstants.lineNameArray[NsharpConstants.LINE_ICING_TEMP]);
target.drawWireframeShape(tempLabelShape, lp.getLineColor(), 1,
LineStyle.SOLID, smallFont);
lp = lpMap
.get(NsharpConstants.lineNameArray[NsharpConstants.LINE_ICING_EPI]);
target.drawWireframeShape(EPILabelShape, lp.getLineColor(), 1,
LineStyle.SOLID, smallFont);
} else {
target.drawWireframeShape(RHLabelShape,
NsharpConstants.color_green, 1, LineStyle.SOLID, smallFont);
target.drawWireframeShape(tempLabelShape,
NsharpConstants.color_red, 1, LineStyle.SOLID, smallFont);
target.drawWireframeShape(EPILabelShape,
NsharpConstants.color_violet_red, 1, LineStyle.SOLID,
smallFont);
}
}
@Override
public void disposeInternal() {
// TODO Auto-generated method stub
super.disposeInternal();
if (linesNumbersShape != null) {
linesNumbersShape.dispose();
}
if (RHLabelShape != null) {
RHLabelShape.dispose();
}
if (tempLabelShape != null) {
tempLabelShape.dispose();
}
if (EPILabelShape != null) {
EPILabelShape.dispose();
}
}
@Override
public double getViewableMaxPressure() {
IExtent ext = desc.getRenderableDisplay().getExtent();
double ymax = ext.getMaxY();
double xmin = ext.getMinX();
world.setWorldCoordinates(NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT,
toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP),
NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT,
toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
// Coordinate c = world.unMap(xmin, ymax);
double viewablePmax = reverseLogScale(world.unMap(xmin, ymax).y);
return viewablePmax;
}
@Override
public double getViewableMinPressure(){
IExtent ext = desc.getRenderableDisplay().getExtent();
double ymin = ext.getMinY();
double xmin = ext.getMinX();
world.setWorldCoordinates(NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT, toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP),
NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT, toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
public double getViewableMinPressure() {
IExtent ext = desc.getRenderableDisplay().getExtent();
double ymin = ext.getMinY();
double xmin = ext.getMinX();
world.setWorldCoordinates(NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT,
toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP),
NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT,
toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
double viewablePmin = reverseLogScale(world.unMap(xmin, ymin).y);
return viewablePmin;
}
@Override
public double getYPositionRatioByPressure(double pressure){
double pY= world.mapY(toLogScale(pressure));
IExtent ext = desc.getRenderableDisplay().getExtent();
double ymin = ext.getMinY();
double ymax = ext.getMaxY();
double ratio = (pY-ymin) / (ymax-ymin);
//System.out.println("ratio="+ratio+ "rtP="+rtP+" maxP="+maxP+" minP="+minP);
public double getYPositionRatioByPressure(double pressure) {
double pY = world.mapY(toLogScale(pressure));
IExtent ext = desc.getRenderableDisplay().getExtent();
double ymin = ext.getMinY();
double ymax = ext.getMaxY();
double ratio = (pY - ymin) / (ymax - ymin);
// System.out.println("ratio="+ratio+
// "rtP="+rtP+" maxP="+maxP+" minP="+minP);
return ratio;
}
@Override
public ViewablePressureContainer getViewablePressureLinesContainer(){
ViewablePressureContainer vpc = new ViewablePressureContainer();
IExtent ext = desc.getRenderableDisplay().getExtent();
float ymax = (float)ext.getMaxY();
float ymin =(float) ext.getMinY();
double vPmax = getViewableMaxPressure();
double vPmin = getViewableMinPressure();
vpc.maxVIewablePressure = (float)vPmax;
vpc.minVIewablePressure = (float)vPmin;
for (float pressure = 300; pressure <= 1000;pressure= pressure+100) {
if(pressure >= vPmin &&pressure <= vPmax){
double pY= world.mapY(toLogScale(pressure));
float ratio = (float) (pY-ymin) / (ymax-ymin);
vpc.pyMap.put(pressure, ratio);
//System.out.println("Icing press="+pressure+" ratio="+ratio+ " pY="+pY+" maxPy="+ymax+" minPy="+ymin);
}
}
return vpc;
public ViewablePressureContainer getViewablePressureLinesContainer() {
ViewablePressureContainer vpc = new ViewablePressureContainer();
IExtent ext = desc.getRenderableDisplay().getExtent();
float ymax = (float) ext.getMaxY();
float ymin = (float) ext.getMinY();
double vPmax = getViewableMaxPressure();
double vPmin = getViewableMinPressure();
vpc.maxVIewablePressure = (float) vPmax;
vpc.minVIewablePressure = (float) vPmin;
for (float pressure = 300; pressure <= 1000; pressure = pressure + 100) {
if (pressure >= vPmin && pressure <= vPmax) {
double pY = world.mapY(toLogScale(pressure));
float ratio = (float) (pY - ymin) / (ymax - ymin);
vpc.pyMap.put(pressure, ratio);
// System.out.println("Icing press="+pressure+" ratio="+ratio+
// " pY="+pY+" maxPy="+ymax+" minPy="+ymin);
}
}
return vpc;
}
@Override
public ViewablePressureContainer getViewablePressureContainer(List<NcSoundingLayer> soundingLys){
world.setWorldCoordinates(NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT, toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP),
NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT, toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
ViewablePressureContainer vpc = new ViewablePressureContainer();
IExtent ext = desc.getRenderableDisplay().getExtent();
float ymax = (float)ext.getMaxY();
float ymin =(float) ext.getMinY();
double vPmax = getViewableMaxPressure();
double vPmin = getViewableMinPressure();
vpc.maxVIewablePressure = (float)vPmax;
vpc.minVIewablePressure = (float)vPmin;
for(NcSoundingLayer ly: soundingLys){
float pressure = ly.getPressure();
if(pressure >= vPmin &&pressure <= vPmax){
double pY= world.mapY(toLogScale(pressure));
float ratio = (float) (pY-ymin) / (ymax-ymin);
vpc.pyMap.put(pressure, ratio);
//System.out.println("Icing press="+pressure+" ratio="+ratio+ " pY="+pY+" maxPy="+ymax+" minPy="+ymin);
}
}
return vpc;
public ViewablePressureContainer getViewablePressureContainer(
List<NcSoundingLayer> soundingLys) {
world.setWorldCoordinates(NsharpConstants.ICING_RELATIVE_HUMIDITY_LEFT,
toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_TOP),
NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT,
toLogScale(NsharpConstants.ICING_PRESSURE_LEVEL_BOTTOM));
ViewablePressureContainer vpc = new ViewablePressureContainer();
IExtent ext = desc.getRenderableDisplay().getExtent();
float ymax = (float) ext.getMaxY();
float ymin = (float) ext.getMinY();
double vPmax = getViewableMaxPressure();
double vPmin = getViewableMinPressure();
vpc.maxVIewablePressure = (float) vPmax;
vpc.minVIewablePressure = (float) vPmin;
for (NcSoundingLayer ly : soundingLys) {
float pressure = ly.getPressure();
if (pressure >= vPmin && pressure <= vPmax) {
double pY = world.mapY(toLogScale(pressure));
float ratio = (float) (pY - ymin) / (ymax - ymin);
vpc.pyMap.put(pressure, ratio);
// System.out.println("Icing press="+pressure+" ratio="+ratio+
// " pY="+pY+" maxPy="+ymax+" minPy="+ymin);
}
}
return vpc;
}
/*
* Called from handleResize() in skewTPaneResource only
*/
public void handleResize(IExtent ext){
if(target==null)
return;
//IExtent ext = desc.getRenderableDisplay().getExtent();
//ext.reset();
float prevHeight = paneHeight;
float prevWidth = iceWidth;
paneHeight = (int) (ext.getHeight());
yMagFactor = yMagFactor*((float)paneHeight/prevHeight);
labelSpace = defaultLabelSpace * yMagFactor;
iceXOrig=(int) (ext.getMinX());
iceYOrig=(int) (ext.getMinY())+ (int)labelSpace;
iceXEnd=iceXOrig+(int) (ext.getWidth());
iceYEnd=iceYOrig+(int) (ext.getHeight()) - 2*(int)labelSpace;
iceWidth = (int) (ext.getWidth());
xMagFactor = xMagFactor* ((float)iceWidth/prevWidth);
this.rectangle = new Rectangle(iceXOrig, iceYOrig,
iceWidth, (int) ext.getHeight()-2*(int)labelSpace);
public void handleResize(IExtent ext) {
if (target == null)
return;
// IExtent ext = desc.getRenderableDisplay().getExtent();
// ext.reset();
float prevHeight = paneHeight;
float prevWidth = iceWidth;
paneHeight = (int) (ext.getHeight());
yMagFactor = yMagFactor * ((float) paneHeight / prevHeight);
labelSpace = defaultLabelSpace * yMagFactor;
iceXOrig = (int) (ext.getMinX());
iceYOrig = (int) (ext.getMinY()) + (int) labelSpace;
iceXEnd = iceXOrig + (int) (ext.getWidth());
iceYEnd = iceYOrig + (int) (ext.getHeight()) - 2 * (int) labelSpace;
iceWidth = (int) (ext.getWidth());
xMagFactor = xMagFactor * ((float) iceWidth / prevWidth);
this.rectangle = new Rectangle(iceXOrig, iceYOrig, iceWidth,
(int) ext.getHeight() - 2 * (int) labelSpace);
pe = new PixelExtent(this.rectangle);
//desc.setNewPe(pe);
// desc.setNewPe(pe);
world = new WGraphics(this.rectangle);
if(linesNumbersShape!= null){
linesNumbersShape.dispose();
}
if(RHLabelShape!= null){
RHLabelShape.dispose();
}
if(tempLabelShape!= null){
tempLabelShape.dispose();
}
if(EPILabelShape!= null){
EPILabelShape.dispose();
}
if (linesNumbersShape != null) {
linesNumbersShape.dispose();
}
if (RHLabelShape != null) {
RHLabelShape.dispose();
}
if (tempLabelShape != null) {
tempLabelShape.dispose();
}
if (EPILabelShape != null) {
EPILabelShape.dispose();
}
createAllShapes();
}
public void handleZooming(){
if(linesNumbersShape!= null){
linesNumbersShape.dispose();
}
if(RHLabelShape!= null){
RHLabelShape.dispose();
}
if(tempLabelShape!= null){
tempLabelShape.dispose();
}
if(EPILabelShape!= null){
EPILabelShape.dispose();
}
public void handleZooming() {
if (linesNumbersShape != null) {
linesNumbersShape.dispose();
}
if (RHLabelShape != null) {
RHLabelShape.dispose();
}
if (tempLabelShape != null) {
tempLabelShape.dispose();
}
if (EPILabelShape != null) {
EPILabelShape.dispose();
}
createAllShapes();
}
public double getWindBarbXPosition(){
IExtent ext = desc.getRenderableDisplay().getExtent();
double xmax = ext.getMaxX(); //Extent's viewable envelope min x and y
public double getWindBarbXPosition() {
IExtent ext = desc.getRenderableDisplay().getExtent();
double xmax = ext.getMaxX(); // Extent's viewable envelope min x and y
double ymax = ext.getMaxY();
double pX= world.mapX( NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT);
if(pX < xmax)
xmax = pX;
double windBarbSizfactor = graphConfigProperty.getWindBarbSize()/2.2f;
if(windBarbSizfactor < 1)
windBarbSizfactor=1;
double dispX = xmax - 50 * currentZoomLevel * xMagFactor* windBarbSizfactor;
Coordinate cumap = world.unMap(dispX,ymax);
double pX = world.mapX(NsharpConstants.ICING_RELATIVE_HUMIDITY_RIGHT);
if (pX < xmax)
xmax = pX;
double windBarbSizfactor = graphConfigProperty.getWindBarbSize() / 2.2f;
if (windBarbSizfactor < 1)
windBarbSizfactor = 1;
double dispX = xmax - 50 * currentZoomLevel * xMagFactor
* windBarbSizfactor;
Coordinate cumap = world.unMap(dispX, ymax);
return cumap.x;
}
}
}

View file

@ -0,0 +1,158 @@
package gov.noaa.nws.ncep.ui.nsharp.display.map;
import gov.noaa.nws.ncep.common.dataplugin.gpd.GenericPointDataConstants;
import gov.noaa.nws.ncep.common.dataplugin.gpd.product.GenericPointDataLevel;
import gov.noaa.nws.ncep.common.dataplugin.gpd.product.GenericPointDataParameter;
import gov.noaa.nws.ncep.common.dataplugin.gpd.product.GenericPointDataStationProduct;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingLayer;
import gov.noaa.nws.ncep.ui.nsharp.NsharpStationInfo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
// import gov.noaa.nws.ncep.viz.rsc.gpd.query.GpdQuery;
/*
* Chin Note; User only be able to pick one station from Nsharp map at a time, however, the picked station may have several time lines
* associated with it. stnPtDataLineLst contains a list of same stations but with different time lines (if provided)
*/
public class NsharpGpdSoundingQuery {
public static void getGpdPfcSndData(
List<NsharpStationInfo> stnPtDataLineLst,
Map<String, List<NcSoundingLayer>> soundingLysLstMap,
String prodName) {
for (NsharpStationInfo StnPt : stnPtDataLineLst) {
// one StnPt represent one reference time line
// with one reference time, there may be many forecast time / range
// start time
List<Date> rangeTimeList = new ArrayList<Date>();
for (NsharpStationInfo.timeLineSpecific tmlinSpc : StnPt
.getTimeLineSpList()) {
rangeTimeList.add(tmlinSpc.getTiemLine());
}
List<GenericPointDataStationProduct> stnPList = null;
// TBDGPD List<GenericPointDataStationProduct> stnPList =
// GpdQuery.getGpdStationModelSoundingProductList(prodName,GenericPointDataQueryKey.BY_SLAT_SLON,
// null,(float)stnPtDataLineLst.get(0).getLatitude(),(float)stnPtDataLineLst.get(0).getLongitude(),
// rangeTimeList,false,0,StnPt.getReftime());
if (stnPList != null && stnPList.size() > 0) {
for (GenericPointDataStationProduct stnProd : stnPList) {
List<GenericPointDataLevel> levelList = stnProd
.getLevelLst();
List<NcSoundingLayer> sndLayerList = new ArrayList<NcSoundingLayer>();
for (GenericPointDataLevel gpdl : levelList) {
List<GenericPointDataParameter> gpdParmList = gpdl
.getGpdParameters();
NcSoundingLayer sndLyer = new NcSoundingLayer();
for (GenericPointDataParameter gpdParm : gpdParmList) {
if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_PRESSURE)) {
sndLyer.setPressure(gpdParm.getValue());
} else if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_HEIGHT)) {
sndLyer.setGeoHeight(gpdParm.getValue());
} else if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_TEMP)) {
sndLyer.setTemperature(gpdParm.getValue());
} else if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_DEWPT)) {
sndLyer.setDewpoint(gpdParm.getValue());
} else if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_WIND_DIR)) {
sndLyer.setWindDirection(gpdParm.getValue());
} else if (gpdParm
.getName()
.equals(GenericPointDataConstants.GEMPAK_WIND_SPEED)) {
sndLyer.setWindSpeed(gpdParm.getValue());
}
}
sndLayerList.add(sndLyer);
}
String dispInfo = "";
for (NsharpStationInfo.timeLineSpecific tmlinSpc : StnPt
.getTimeLineSpList()) {
if (tmlinSpc.getTiemLine().getTime() == (stnProd
.getForecastTime() * 1000 + stnProd
.getRefTime().getTime())) {
dispInfo = tmlinSpc.getDisplayInfo();
soundingLysLstMap.put(dispInfo, sndLayerList);
break;
}
}
}
}
}
}
public static void getGpdObsSndData(
List<NsharpStationInfo> stnPtDataLineLst,
Map<String, List<NcSoundingLayer>> soundingLysLstMap,
String prodName) {
List<Date> refTimeList = new ArrayList<Date>();
for (NsharpStationInfo StnPt : stnPtDataLineLst) {
// one StnPt represent one data time line
Date refTime = new Date();
refTime.setTime(StnPt.getReftime().getTime());
refTimeList.add(refTime);
}
// System.out.println("stn lat =" +
// stnPtDataLineLst.get(0).getLatitude()
// + " lon=" + stnPtDataLineLst.get(0).getLongitude());
List<GenericPointDataStationProduct> stnPList = null;
// TBDGPD List<GenericPointDataStationProduct> stnPList =
// GpdQuery.getGpdStationProductList(prodName,GenericPointDataQueryKey.BY_SLAT_SLON,
// null,(float)stnPtDataLineLst.get(0).getLatitude(),(float)stnPtDataLineLst.get(0).getLongitude(),
// refTimeList,false,0);
if (stnPList != null && stnPList.size() > 0) {
for (GenericPointDataStationProduct stnProd : stnPList) {
List<GenericPointDataLevel> levelList = stnProd.getLevelLst();
List<NcSoundingLayer> sndLayerList = new ArrayList<NcSoundingLayer>();
for (GenericPointDataLevel gpdl : levelList) {
List<GenericPointDataParameter> gpdParmList = gpdl
.getGpdParameters();
NcSoundingLayer sndLyer = new NcSoundingLayer();
for (GenericPointDataParameter gpdParm : gpdParmList) {
if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_PRESSURE)) {
sndLyer.setPressure(gpdParm.getValue());
} else if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_HEIGHT)) { // NcSoundingProfile
// sndPf=
// PfcSoundingQuery.getPfcSndData(StnPt.getDatauri(),(float)StnPt.getLatitude(),
// (float)StnPt.getLongitude(),
// StnPt.getReftime(),
// StnPt.getRangestarttime(),
// PfcSoundingQuery.PfcSndType.NAMSND);
sndLyer.setGeoHeight(gpdParm.getValue());
} else if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_TEMP)) {
sndLyer.setTemperature(gpdParm.getValue());
} else if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_DEWPT)) {
sndLyer.setDewpoint(gpdParm.getValue());
} else if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_WIND_DIR)) {
sndLyer.setWindDirection(gpdParm.getValue());
} else if (gpdParm.getName().equals(
GenericPointDataConstants.GEMPAK_WIND_SPEED)) {
sndLyer.setWindSpeed(gpdParm.getValue());
}
}
sndLayerList.add(sndLyer);
}
String dispInfo = "";
for (NsharpStationInfo StnPt : stnPtDataLineLst) {
if (StnPt.getReftime().getTime() == stnProd.getRefTime()
.getTime()) {
dispInfo = StnPt.getStnDisplayInfo();
soundingLysLstMap.put(dispInfo, sndLayerList);
break;
}
}
}
}
}
}

View file

@ -25,8 +25,8 @@ import gov.noaa.nws.ncep.ui.nsharp.NsharpStationInfo;
import gov.noaa.nws.ncep.ui.nsharp.SurfaceStationPointData;
import gov.noaa.nws.ncep.ui.nsharp.display.NsharpEditor;
import gov.noaa.nws.ncep.ui.nsharp.display.rsc.NsharpResourceHandler;
import gov.noaa.nws.ncep.ui.nsharp.view.ModelSoundingDialogContents;
import gov.noaa.nws.ncep.ui.nsharp.view.NsharpLoadDialog;
import gov.noaa.nws.ncep.ui.nsharp.view.NsharpModelSoundingDialogContents;
import gov.noaa.nws.ncep.ui.pgen.tools.InputHandlerDefaultImpl;
import gov.noaa.nws.ncep.viz.ui.display.NatlCntrsEditor;
@ -51,44 +51,44 @@ import com.vividsolutions.jts.geom.Coordinate;
//@SuppressWarnings("unchecked")
public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
public NsharpMapMouseHandler() {
instance = this;
}
public NsharpMapMouseHandler() {
instance = this;
}
// private NsharpSkewTDisplay renderableDisplay=null;
private static final double NctextuiPointMinDistance = 45000;
private static final double NctextuiPointMinDistance = 45000;
// private int prevMouseX, prevMouseY;
private static NsharpMapMouseHandler instance;
private double lat, lon;
public double getLat() {
return lat;
}
private static NsharpMapMouseHandler instance;
private double lat, lon;
public double getLat() {
return lat;
}
public double getLon() {
return lon;
}
public double getLon() {
return lon;
}
public static NsharpMapMouseHandler getAccess() {
return instance;
}
return instance;
}
/*
* (non-Javadoc)
*
* @see com.raytheon.viz.ui.input.IInputHandler#handleMouseDown(int, int,
* int)
*/
@Override
public boolean handleMouseDown(int x, int y, int button) {
@Override
public boolean handleMouseDown(int x, int y, int button) {
// System.out.println("nsharp map mouse down");
// prevMouseX = x;
// prevMouseY = y;
return false;
return false;
}
/*
@ -100,21 +100,21 @@ public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
*/
@Override
public boolean handleMouseDownMove(int x, int y, int button) {
return false;
return false;
}
@Override
public boolean handleMouseMove(int x, int y) {
// TODO Auto-generated method stub
return false;
}
public boolean handleMouseMove(int x, int y) {
// TODO Auto-generated method stub
return false;
}
/*
/*
* (non-Javadoc)
*
* @see com.raytheon.viz.ui.input.IInputHandler#handleMouseUp(int, int, int)
* handle right button, so user be able to pick stn and print text report
* handle right button, so user be able to pick stn and print text report
*/
@Override
public boolean handleMouseUp(int x, int y, int button) {
@ -123,26 +123,26 @@ public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
// if ( !NsharpMapResource.getOrCreateNsharpMapResource().isEditable())
// return false;
// System.out.println("NsharpMapMouseHandler handleMouseUp called");
// button 1 is left mouse button
// button 1 is left mouse button
if (button == 1) {
NatlCntrsEditor mapEditor = NsharpMapResource.getMapEditor();
NatlCntrsEditor mapEditor = NsharpMapResource.getMapEditor();
if (mapEditor != null) {
// for(int i=0; i<
// mapEditor.getDescriptor().getResourceList().size(); i++)
// System.out.println(
// "C resourcename="+mapEditor.getDescriptor().getResourceList().get(i).getResource().getName());
// Check if mouse is in geographic extent
Coordinate loc = mapEditor.translateClick(x, y);
// Check if mouse is in geographic extent
Coordinate loc = mapEditor.translateClick(x, y);
if (loc == null)
return false;
NsharpLoadDialog loadDia = NsharpLoadDialog.getAccess();
return false;
NsharpLoadDialog loadDia = NsharpLoadDialog.getAccess();
if (loadDia != null) {
if (loadDia.getActiveLoadSoundingType() == NsharpLoadDialog.MODEL_SND
&& loadDia.getMdlDialog() != null
&& loadDia.getMdlDialog().getLocationText() != null) {
if (loadDia.getMdlDialog().getCurrentLocType() == ModelSoundingDialogContents.LocationType.STATION) {
if (loadDia.getMdlDialog().getCurrentLocType() == NsharpModelSoundingDialogContents.LocationType.STATION) {
// System.out.println("mouse up 1 loc.x "+ loc.x+
// " loc.y="+ loc.y);
String stnName = SurfaceStationPointData
@ -151,7 +151,7 @@ public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
// " loc.y="+ loc.y);
// System.out.println("stn name = "+ stnName);
if (stnName == null)
stnName = "";
stnName = "";
loadDia.getMdlDialog().getLocationText()
.setText(stnName);
} else {
@ -170,10 +170,10 @@ public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
List<NsharpStationInfo> points = NsharpMapResource
.getOrCreateNsharpMapResource().getPoints();// loadDia.getNsharpMapResource().getPoints();
if (points.isEmpty() == false) {
// create an editor NsharpEditor
// create an editor NsharpEditor
// NsharpEditor skewtEdt =
// NsharpEditor.createOrOpenEditor();
// get the stn close to loc "enough" and retrieve
// report for it
// Note::One stn may have more than one dataLine, if
@ -184,27 +184,50 @@ public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
&& stnPtDataLineLst.size() > 0) {
// System.out.println("MapMouseHandler creating NsharpSkewTDisplay");
// hash map, use stn display info as key
Map<String, List<NcSoundingLayer>> soundingLysLstMap = new HashMap<String, List<NcSoundingLayer>>();
Map<String, List<NcSoundingLayer>> soundingLysLstMap = new HashMap<String, List<NcSoundingLayer>>();
long t01 = System.currentTimeMillis();
// String soundingType;
if (activeLoadType == NsharpLoadDialog.OBSER_SND) {
NsharpMapResource.startWaitCursor();
NsharpMapResource.startWaitCursor();
NsharpObservedSoundingQuery
.getObservedSndData(
stnPtDataLineLst, loadDia
.getObsDialog()
.isRawData(),
soundingLysLstMap);
NsharpMapResource.stopWaitCursor();
NsharpMapResource.stopWaitCursor();
} else if (activeLoadType == NsharpLoadDialog.PFC_SND) {
NsharpMapResource.startWaitCursor();
NsharpMapResource.startWaitCursor();
NsharpPfcSoundingQuery
.getPfcSndDataBySndTmRange(
stnPtDataLineLst,
soundingLysLstMap);
NsharpMapResource.stopWaitCursor();
} else
return false;
NsharpMapResource.stopWaitCursor();
}
/*
* TBDGPD else if(activeLoadType ==
* NsharpLoadDialog.GPD_OBS_SND){
* NsharpMapResource.startWaitCursor();
* NsharpGpdSoundingQuery
* .getGpdObsSndData(stnPtDataLineLst,
* soundingLysLstMap,
* loadDia.getActiveGpdProdName());
* NsharpMapResource.stopWaitCursor(); } else
* if(activeLoadType ==
* NsharpLoadDialog.GPD_PFC_SND){
* NsharpMapResource.startWaitCursor();
* NsharpGpdSoundingQuery
* .getGpdPfcSndData(stnPtDataLineLst,
* soundingLysLstMap,
* loadDia.getActiveGpdProdName());
* NsharpMapResource.stopWaitCursor(); }
*/
else
return false;
long t02 = System.currentTimeMillis();
// System.out.println("Nsharp spent " +
// (t02-t01)+ " ms to query data");
// System.out.println("MAP size/"
// +soundingLysLstMap.size());
if (soundingLysLstMap.size() <= 0) {
@ -214,40 +237,40 @@ public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
.getShell();
MessageBox mb = new MessageBox(shell,
SWT.ICON_WARNING | SWT.OK);
mb.setMessage("Invalid sounding data returned from DB for this station!!");
mb.open();
loadDia.closeDiaOnly();
return false;
}
loadDia.closeDiaOnly();
mb.setMessage("Invalid sounding data returned from DB for this station!!");
mb.open();
loadDia.closeDiaOnly();
return false;
}
loadDia.closeDiaOnly();
// NsharpResourceHandler skewRsc =
// skewtEdt.getRscHandler();
// skewRsc.addRsc(soundingLysLstMap,
// stnPtDataLineLst.get(0));
loadDataToNsharpResources(soundingLysLstMap,
stnPtDataLineLst.get(0));
mapEditor = NsharpMapResource.getMapEditor();
if (mapEditor != null) {
mapEditor.refresh();
}
bringSkewTEdToTop();
mapEditor = NsharpMapResource.getMapEditor();
if (mapEditor != null) {
mapEditor.refresh();
}
bringSkewTEdToTop();
} else {
// System.out.println("Mouse point too far from stn");
}
}
} else { // debug
// System.out.println("points is null");
}
}
}
}
}
}
}
}
} else if (button == 3) {
// NsharpEditor.bringSkewTEditorToTop();
bringSkewTEdToTop();
}
return false;
bringSkewTEdToTop();
}
return false;
}
/*
@ -260,18 +283,18 @@ public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
private void bringSkewTEdToTop() {
Job uijob = new UIJob("clear source selection") { //$NON-NLS-1$
public IStatus runInUIThread(IProgressMonitor monitor) {
NsharpEditor.bringEditorToTop();
return Status.OK_STATUS;
}
NsharpEditor.bringEditorToTop();
return Status.OK_STATUS;
}
};
uijob.setSystem(true);
uijob.schedule();
};
uijob.setSystem(true);
uijob.schedule();
}
/*
* Same reason to use UIJob as bringSkewTEdToTop()
*/
/*
* Same reason to use UIJob as bringSkewTEdToTop()
*/
private void loadDataToNsharpResources(
final Map<String, List<NcSoundingLayer>> soundMap,
final NsharpStationInfo stnInfo) {
@ -279,16 +302,16 @@ public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
public IStatus runInUIThread(IProgressMonitor monitor) {
NsharpResourceHandler rscHdr = NsharpEditor
.createOrOpenEditor().getRscHandler();
rscHdr.addRsc(soundMap, stnInfo);
return Status.OK_STATUS;
}
rscHdr.addRsc(soundMap, stnInfo);
return Status.OK_STATUS;
}
};
uijob.setSystem(true);
uijob.schedule();
};
uijob.setSystem(true);
uijob.schedule();
}
/**
/**
* Gets the nearest point of an selected element to the input point
*
* @param el
@ -300,40 +323,40 @@ public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
private List<NsharpStationInfo> getPtWithinMinDist(
List<NsharpStationInfo> points, Coordinate pt) {
NsharpStationInfo thePoint = null;
double minDistance = NctextuiPointMinDistance;
GeodeticCalculator gc;
List<NsharpStationInfo> thePoints = new ArrayList<NsharpStationInfo>();
// TODO : can't assume this is a map Editor/MapDescriptor
NatlCntrsEditor mapEditor = NsharpMapResource.getMapEditor();
NsharpStationInfo thePoint = null;
double minDistance = NctextuiPointMinDistance;
GeodeticCalculator gc;
List<NsharpStationInfo> thePoints = new ArrayList<NsharpStationInfo>();
// TODO : can't assume this is a map Editor/MapDescriptor
NatlCntrsEditor mapEditor = NsharpMapResource.getMapEditor();
if (mapEditor != null) {
IMapDescriptor desc = (IMapDescriptor) mapEditor
.getActiveDisplayPane().getRenderableDisplay()
.getDescriptor();
gc = new GeodeticCalculator(desc.getCRS());
gc.setStartingGeographicPoint(pt.x, pt.y);
gc = new GeodeticCalculator(desc.getCRS());
gc.setStartingGeographicPoint(pt.x, pt.y);
// int textDispIndex = 1;//debug
for (NsharpStationInfo point : points) {
gc.setDestinationGeographicPoint(point.getLongitude(),
point.getLatitude());
double dist;
double dist;
try {
dist = gc.getOrthodromicDistance();
dist = gc.getOrthodromicDistance();
// System.out.println("dist to point " + textDispIndex++ +
// " is " + dist);
if (dist < minDistance) {
minDistance = dist;
thePoint = point;
}
minDistance = dist;
thePoint = point;
}
} catch (Exception e) {
// e.printStackTrace();
// System.out.println("getOrthodromicDistance exception happened!");
}
}
}
}
// Chin, there may be more than one point for a selected stn. As
// user may selected more than one data time,
// For same stn, each data time will have one point to represent it.
@ -342,18 +365,18 @@ public class NsharpMapMouseHandler extends InputHandlerDefaultImpl {
for (NsharpStationInfo point : points) {
if ((thePoint.getLatitude() == point.getLatitude())
&& (thePoint.getLongitude() == point.getLongitude())) {
thePoints.add(point);
}
}
thePoints.add(point);
}
}
// marked X on selected point
NsharpMapResource.getOrCreateNsharpMapResource()
.setPickedPoint(thePoint);
}
}
return thePoints;
}
}
return thePoints;
}

View file

@ -73,11 +73,11 @@ public class NsharpMapResource extends
private static NatlCntrsEditor mapEditor = null;
private static NsharpMapMouseHandler mouseHandler;
private static NsharpMapMouseHandler mouseHandler;
private static Cursor waitCursor = null;
private static Control cursorControl;
private static Control cursorControl;
private static boolean mouseHandlerRegistered = false;
@ -90,110 +90,110 @@ public class NsharpMapResource extends
.getActivePage() != null) {
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().bringToTop(mapEditor);
mapEditor.refresh();
}
mapEditor.refresh();
}
} catch (Exception e) {
}
}
}
public static NatlCntrsEditor getMapEditor() {
return mapEditor;
}
}
public static NsharpMapResource getMapRsc() {
return mapRsc;
}
public static NatlCntrsEditor getMapEditor() {
return mapEditor;
}
private NsharpMapResourceData nsharpMapResourceData;
public static NsharpMapResource getMapRsc() {
return mapRsc;
}
/** The set of symbols with similar attributes across many locations */
private SymbolLocationSet symbolSet = null;
private NsharpMapResourceData nsharpMapResourceData;
private SymbolLocationSet symbolToMark = null;
/** The set of symbols with similar attributes across many locations */
private SymbolLocationSet symbolSet = null;
private List<NsharpStationInfo> points = new ArrayList<NsharpStationInfo>();
private SymbolLocationSet symbolToMark = null;
private List<NsharpStationInfo> pickedPoint = new ArrayList<NsharpStationInfo>();
private List<NsharpStationInfo> points = new ArrayList<NsharpStationInfo>();
public void setPickedPoint(NsharpStationInfo point) {
this.pickedPoint.add(point);
}
public List<NsharpStationInfo> getPoints() {
return points;
}
private List<NsharpStationInfo> pickedPoint = new ArrayList<NsharpStationInfo>();
public void setPoints(List<NsharpStationInfo> points) {
public void setPickedPoint(NsharpStationInfo point) {
this.pickedPoint.add(point);
}
public List<NsharpStationInfo> getPoints() {
return points;
}
public void setPoints(List<NsharpStationInfo> points) {
if (points == null) {
this.pickedPoint.clear();
this.pickedPoint.clear();
symbolToMark = null;
symbolSet = null;
this.points.clear();
this.points.clear();
} else {
this.points = points;
}
}
this.points = points;
}
}
public void addPoint(NsharpStationInfo point) {
points.add(point);
}
public void addPoint(NsharpStationInfo point) {
points.add(point);
}
/**
* Default constructor
*/
protected NsharpMapResource(NsharpMapResourceData resourceData,
LoadProperties loadProperties) {
super(resourceData, loadProperties);
/**
* Default constructor
*/
protected NsharpMapResource(NsharpMapResourceData resourceData,
LoadProperties loadProperties) {
super(resourceData, loadProperties);
// set the editable capability
getCapability(EditableCapability.class).setEditable(true);
this.nsharpMapResourceData = resourceData;
this.nsharpMapResourceData = resourceData;
// System.out.println("NsharpMapResource constructed");
}
}
public static void startWaitCursor() {
waitCursor = new Cursor(Display.getCurrent(), SWT.CURSOR_WAIT);
cursorControl = Display.getCurrent().getCursorControl();
cursorControl = Display.getCurrent().getCursorControl();
if (cursorControl != null && waitCursor != null)
cursorControl.setCursor(waitCursor);
}
cursorControl.setCursor(waitCursor);
}
public static void stopWaitCursor() {
if (cursorControl != null && waitCursor != null) {
cursorControl.setCursor(null);
}
cursorControl.setCursor(null);
}
if (waitCursor != null) {
waitCursor.dispose();
waitCursor.dispose();
waitCursor = null;
}
}
}
}
private static void createMapEditor() {
// create an editor MapEditor
try {
AbstractEditor ed = NcDisplayMngr.getActiveNatlCntrsEditor();
// Is this called in D2D. Should we only check for NcMapEditors.
// create an editor MapEditor
try {
AbstractEditor ed = NcDisplayMngr.getActiveNatlCntrsEditor();
// Is this called in D2D. Should we only check for NcMapEditors.
// If this isn't a NatlCntrsEditor should we look for one or just
// create a new one.
//
//
if (NcEditorUtil.getNcDisplayType(ed) == NcDisplayType.NMAP_DISPLAY) {
mapEditor = (NatlCntrsEditor) ed;
} else {
mapEditor = (NatlCntrsEditor) NcDisplayMngr
.createNatlCntrsEditor(NcDisplayType.NMAP_DISPLAY,
"Select NSharp Source");
}
}
// for(int i=0; i<
// mapEditor.getDescriptor().getResourceList().size(); i++)
// System.out.println(
// "A resourcename="+mapEditor.getDescriptor().getResourceList().get(i).getResource().getName());
ResourceBndlLoader rbdLoader = new ResourceBndlLoader("DefaultMap");
ResourceBndlLoader rbdLoader = new ResourceBndlLoader("DefaultMap");
rbdLoader.addDefaultRBD(NcDisplayType.NMAP_DISPLAY, mapEditor);
VizApp.runSync(rbdLoader);
// System.out.println("NsharpMapResource create editor "+
@ -207,9 +207,9 @@ public class NsharpMapResource extends
System.out
.println("NsharpMapResource Could not load initial editor: "
+ ve.getMessage());
ve.printStackTrace();
}
}
ve.printStackTrace();
}
}
// private static void createMapEditorTest(){
// // create an editor MapEditor
@ -245,26 +245,26 @@ public class NsharpMapResource extends
// }
public static void registerMouseHandler() {
if (mouseHandlerRegistered)
return;
mouseHandler = getMouseHandler();
return;
mouseHandler = getMouseHandler();
if (mapEditor != null && mouseHandler != null) {
mapEditor.registerMouseHandler((IInputHandler) mouseHandler);
mouseHandlerRegistered = true;
}
}
mouseHandlerRegistered = true;
}
}
public static void unregisterMouseHandler() {
if (!mouseHandlerRegistered)
return;
mouseHandler = getMouseHandler();
return;
mouseHandler = getMouseHandler();
if (mapEditor != null && mouseHandler != null) {
mapEditor.unregisterMouseHandler((IInputHandler) mouseHandler);
mouseHandlerRegistered = false;
}
}
}
}
/**
/**
* Create a new MapResource and add it to the current editor.
*
* @return the MapResource
@ -273,54 +273,54 @@ public class NsharpMapResource extends
if (mapRsc == null) {
if (mapEditor == null) {
createMapEditor();// createMapEditor();
}
}
if (mapEditor != null) {
IMapDescriptor desc = (IMapDescriptor) mapEditor
.getActiveDisplayPane().getRenderableDisplay()
.getDescriptor();
try {
try {
if (mapRscData == null)
mapRscData = new NsharpMapResourceData();
mapRsc = mapRscData.construct(new LoadProperties(), desc);
desc.getResourceList().add(mapRsc);
mapRsc.init(mapEditor.getActiveDisplayPane().getTarget());
// register mouse handler
mouseHandler = getMouseHandler();
mouseHandler = getMouseHandler();
mapEditor
.registerMouseHandler((IInputHandler) mouseHandler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return mapRsc;
}
public static void deleteNsharpMapResource() {
// System.out.println("NsharpMapResource:deleteNsharpMapResource ");
if (mapRsc != null) {
mapRsc.dispose();
mapRsc = null;
}
mapRsc.dispose();
mapRsc = null;
}
}
/**
* Called when resource is disposed
/**
* Called when resource is disposed
*
* @see com.raytheon.viz.core.rsc.IVizResource#dispose()
*/
@Override
public void disposeInternal() {
* @see com.raytheon.viz.core.rsc.IVizResource#dispose()
*/
@Override
public void disposeInternal() {
// System.out.println("NsharpMapResource:disposeInternal "+
// this.toString());
if (mapEditor != null) {
mapEditor.unregisterMouseHandler(mouseHandler);
mouseHandler = null;
mouseHandler = null;
// close editor
/*
* if((PlatformUI.getWorkbench()!=
@ -331,65 +331,65 @@ public class NsharpMapResource extends
* PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage
* ().closeEditor(mapEditor, false);
*/
mapEditor = null;
mapEditor = null;
}
pickedPoint = null;
points = null;
symbolSet = null;
symbolToMark = null;
mapRsc = null;
pickedPoint = null;
points = null;
symbolSet = null;
symbolToMark = null;
mapRsc = null;
mapRscData = null;
if (waitCursor != null)
waitCursor.dispose();
waitCursor.dispose();
waitCursor = null;
mouseHandlerRegistered = false;
}
}
/*
* (non-Javadoc)
*
* @see
* com.raytheon.viz.core.rsc.IVizResource#getCoordinateReferenceSystem()
*/
public CoordinateReferenceSystem getCoordinateReferenceSystem() {
*/
public CoordinateReferenceSystem getCoordinateReferenceSystem() {
if (descriptor == null)
return null;
if (descriptor == null)
return null;
return descriptor.getCRS();
return descriptor.getCRS();
}
}
/*
* (non-Javadoc)
*
* @see com.raytheon.viz.core.rsc.IVizResource#getName()
*/
@Override
public String getName() {
* @see com.raytheon.viz.core.rsc.IVizResource#getName()
*/
@Override
public String getName() {
return "NSHARP Resource";
return "NSHARP Resource";
}
}
/*
* (non-Javadoc)
*
* @see com.raytheon.viz.core.rsc.IVizResource#init(com.raytheon.viz.core.
* IGraphicsTarget)
*/
@Override
public void initInternal(IGraphicsTarget target) throws VizException {
*/
@Override
public void initInternal(IGraphicsTarget target) throws VizException {
// System.out.println("NsharpMapResource:initInternal called");
// mapfont = target.initializeFont("Monospace",
// (float) (12 *
// nsharpMapResourceData.getMarkerTextSize().getSoftwareSize()), null);
// make the nsharp map resource editable
EditableManager.makeEditable(this,
getCapability(EditableCapability.class).isEditable());
}
}
/*
* (non-Javadoc)
@ -397,65 +397,65 @@ public class NsharpMapResource extends
* @see
* com.raytheon.viz.core.rsc.IVizResource#isApplicable(com.raytheon.viz.
* core.PixelExtent)
*/
public boolean isApplicable(PixelExtent extent) {
*/
public boolean isApplicable(PixelExtent extent) {
return true;
return true;
}
}
private void generateSymbolForDrawing() {
String type;
float lineWidth = nsharpMapResourceData.getMarkerWidth();
String type;
float lineWidth = nsharpMapResourceData.getMarkerWidth();
Boolean clear = false;
String category = new String("Marker");
double sizeScale = nsharpMapResourceData.getMarkerSize();
String category = new String("Marker");
double sizeScale = nsharpMapResourceData.getMarkerSize();
if (points.isEmpty() == true) {
symbolSet = null;
if (points.isEmpty() == true) {
symbolSet = null;
} else {
// SymbolLocationSet constructor requires a positive-length array of
// Coordinate
Coordinate[] locations = new Coordinate[points.size()];
Coordinate[] locations = new Coordinate[points.size()];
Color[] colors = new Color[] { new Color(
NsharpConstants.color_green.red,
NsharpConstants.color_green.green,
NsharpConstants.color_green.green,
NsharpConstants.color_green.blue) };
// System.out.println( "generateSymbolSet: size ="+ points.size());
int i = 0;
for (NsharpStationInfo p : points) {
double lon, lat;
lon = p.getLongitude();
lat = p.getLatitude();
int i = 0;
for (NsharpStationInfo p : points) {
double lon, lat;
lon = p.getLongitude();
lat = p.getLatitude();
locations[i++] = new Coordinate(lon, lat);
}
type = nsharpMapResourceData.getMarkerType().toString();
}
type = nsharpMapResourceData.getMarkerType().toString();
// System.out.println( "generateSymbolSet done size ="+ i);
symbolSet = new SymbolLocationSet(null, colors, lineWidth,
sizeScale, clear, locations, category, type);
}
}
// generate symbol for picked stn to mark X
if (pickedPoint != null && pickedPoint.size() > 0) {
Coordinate[] locations = new Coordinate[pickedPoint.size()];
int i = 0;
for (NsharpStationInfo p : pickedPoint) {
double lon, lat;
lon = p.getLongitude();
lat = p.getLatitude();
Coordinate[] locations = new Coordinate[pickedPoint.size()];
int i = 0;
for (NsharpStationInfo p : pickedPoint) {
double lon, lat;
lon = p.getLongitude();
lat = p.getLatitude();
locations[i++] = new Coordinate(lon, lat);
}
type = nsharpMapResourceData.getStnMarkerType().toString();
}
type = nsharpMapResourceData.getStnMarkerType().toString();
Color[] colors = new Color[] { new Color(
NsharpConstants.color_red.red,
NsharpConstants.color_red.green,
NsharpConstants.color_red.green,
NsharpConstants.color_red.blue) };
symbolToMark = new SymbolLocationSet(null, colors, lineWidth,
sizeScale * 2, clear, locations, category, type);
} else
symbolToMark = null;
}
}
/*
* (non-Javadoc)
@ -463,46 +463,46 @@ public class NsharpMapResource extends
* @see
* com.raytheon.viz.core.drawables.IRenderable#paint(com.raytheon.viz.core
* .IGraphicsTarget, com.raytheon.viz.core.drawables.PaintProperties)
*/
@Override
public void paintInternal(IGraphicsTarget target, PaintProperties paintProps)
throws VizException {
*/
@Override
public void paintInternal(IGraphicsTarget target, PaintProperties paintProps)
throws VizException {
// System.out.println("paintInternal called!");
// IFont font = target.initializeFont("Monospace",
// (float) (12 *
// nsharpMapResourceData.getMarkerTextSize().getSoftwareSize()), null);
generateSymbolForDrawing();
generateSymbolForDrawing();
DisplayElementFactory df = new DisplayElementFactory(target,
this.descriptor);
if (symbolSet != null) {
ArrayList<IDisplayable> elements = df.createDisplayElements(
symbolSet, paintProps);
for (IDisplayable each : elements) {
try {
each.draw(target, paintProps);
each.dispose();
try {
each.draw(target, paintProps);
each.dispose();
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
// System.out.println("paintInternal caught draw exception!");
}
}
}
}
}
}
if (symbolToMark != null) {
ArrayList<IDisplayable> elements = df.createDisplayElements(
symbolToMark, paintProps);
for (IDisplayable each : elements) {
try {
each.draw(target, paintProps);
each.dispose();
try {
each.draw(target, paintProps);
each.dispose();
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
// System.out.println("paintInternal caught draw exception!");
}
}
}
}
}
}
// font.dispose();
}
}
/*
* (non-Javadoc)
@ -510,12 +510,12 @@ public class NsharpMapResource extends
* @see
* com.raytheon.viz.core.rsc.capabilities.IProjectableResource#isProjectable
* (org.opengis.referencing.crs.CoordinateReferenceSystem)
*/
public boolean isProjectable(CoordinateReferenceSystem mapData) {
*/
public boolean isProjectable(CoordinateReferenceSystem mapData) {
return true;
return true;
}
}
/*
* (non-Javadoc)
@ -523,94 +523,94 @@ public class NsharpMapResource extends
* @see
* com.raytheon.viz.core.rsc.capabilities.IProjectableResource#project(org
* .opengis.referencing.crs.CoordinateReferenceSystem)
*/
@Override
public void project(CoordinateReferenceSystem mapData) throws VizException {
*/
@Override
public void project(CoordinateReferenceSystem mapData) throws VizException {
// System.out.println("NctextuiResource: project ");
}
}
/**
* Returns the current mouse handler.
*
* @return
*/
private static NsharpMapMouseHandler getMouseHandler() {
*/
private static NsharpMapMouseHandler getMouseHandler() {
if (mouseHandler == null) {
mouseHandler = new NsharpMapMouseHandler();
mouseHandler = new NsharpMapMouseHandler();
}
return mouseHandler;
}
@Override
public boolean okToUnload() {
/*
* DisAllow unloading of Resource
*/
return false;
}
public boolean okToUnload() {
/*
* DisAllow unloading of Resource
*/
@Override
public void notifyRemove(ResourcePair rp) throws VizException {
// TODO Auto-generated method stub
}
return false;
@Override
public void propertiesChanged(ResourceProperties updatedProps) {
}
@Override
public void notifyRemove(ResourcePair rp) throws VizException {
// TODO Auto-generated method stub
}
@Override
public void propertiesChanged(ResourceProperties updatedProps) {
if (updatedProps.isVisible()) {
reopenTextView();
} else {
hideTextView();
}
}
}
private void hideTextView() {
IWorkbenchPage wpage = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
IViewPart vpart = wpage.findView("gov.noaa.nws.ncep.ui.nsharp");
if (wpage.isPartVisible(vpart)) {
NsharpPaletteWindow paletteWin = NsharpPaletteWindow.getInstance();
NsharpPaletteWindow paletteWin = NsharpPaletteWindow.getInstance();
if (paletteWin != null) {
paletteWin.setEditorVisible(false);
wpage.hideView(vpart);
}
paletteWin.setEditorVisible(false);
wpage.hideView(vpart);
}
}
}
}
private void reopenTextView() {
IWorkbenchPage wpage = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
IViewPart vpart = wpage.findView("gov.noaa.nws.ncep.ui.nsharp");
if (!wpage.isPartVisible(vpart)) {
NsharpPaletteWindow paletteWin = NsharpPaletteWindow.getInstance();
NsharpPaletteWindow paletteWin = NsharpPaletteWindow.getInstance();
if (paletteWin != null) {
paletteWin.setEditorVisible(true);
try {
paletteWin.setEditorVisible(true);
try {
vpart = wpage.showView("gov.noaa.nws.ncep.ui.nsharp");
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
/**
* Check if the resource is currently editable
*
* @return editable
*/
public boolean isEditable() {
return getCapability(EditableCapability.class).isEditable();
}
/**
* Check if the resource is currently editable
*
* @return editable
*/
public boolean isEditable() {
return getCapability(EditableCapability.class).isEditable();
}
public void setEditable(boolean enable) {
getCapability(EditableCapability.class).setEditable(enable);

View file

@ -30,28 +30,28 @@ import com.raytheon.uf.viz.core.rsc.LoadProperties;
public class NsharpMapResourceData extends AbstractResourceData {
private MarkerState markerState = MarkerState.MARKER_ONLY;
private MarkerState markerState = MarkerState.MARKER_ONLY;
private MarkerType markerType = MarkerType.DIAMOND;
private MarkerType markerType = MarkerType.DIAMOND;
private Float markerSize = 1f;
private Float markerSize = 1f;
private Integer markerWidth = 2;
private Integer markerWidth = 2;
private MarkerTextSize markerTextSize = MarkerTextSize.MEDIUM;
private MarkerTextSize markerTextSize = MarkerTextSize.MEDIUM;
private String mapName = "NSHARP";
private String mapName = "NSHARP";
private MarkerType stnMarkerType = MarkerType.LARGE_X;
public MarkerType getStnMarkerType() {
return stnMarkerType;
}
private MarkerType stnMarkerType = MarkerType.LARGE_X;
public MarkerType getStnMarkerType() {
return stnMarkerType;
}
public NsharpMapResourceData() {
super();
}
public NsharpMapResourceData() {
super();
}
/*
* (non-Javadoc)
*
@ -59,13 +59,13 @@ public class NsharpMapResourceData extends AbstractResourceData {
* com.raytheon.uf.viz.core.rsc.AbstractResourceData#construct(com.raytheon
* .uf.viz.core.comm.LoadProperties,
* com.raytheon.uf.viz.core.drawables.IDescriptor)
*/
@Override
public NsharpMapResource construct(LoadProperties loadProperties,
IDescriptor descriptor) throws VizException {
// TODO Auto-generated method stub
return new NsharpMapResource(this, loadProperties);
}
*/
@Override
public NsharpMapResource construct(LoadProperties loadProperties,
IDescriptor descriptor) throws VizException {
// TODO Auto-generated method stub
return new NsharpMapResource(this, loadProperties);
}
/*
* (non-Javadoc)
@ -73,15 +73,15 @@ public class NsharpMapResourceData extends AbstractResourceData {
* @see
* com.raytheon.uf.viz.core.rsc.AbstractResourceData#update(java.lang.Object
* )
*/
@Override
public void update(Object updateData) {
// TODO Auto-generated method stub
*/
@Override
public void update(Object updateData) {
// TODO Auto-generated method stub
}
}
@Override
public boolean equals(Object obj) {
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof NsharpMapResourceData))
return false;
NsharpMapResourceData rdata = (NsharpMapResourceData) obj;
@ -93,54 +93,54 @@ public class NsharpMapResourceData extends AbstractResourceData {
&& this.stnMarkerType.equals(rdata.getStnMarkerType()))
return true;
return false;
}
public MarkerState getMarkerState() {
return markerState;
}
return false;
}
public void setMarkerState(MarkerState markerState) {
this.markerState = markerState;
}
public MarkerState getMarkerState() {
return markerState;
}
public MarkerType getMarkerType() {
return markerType;
}
public void setMarkerState(MarkerState markerState) {
this.markerState = markerState;
}
public void setMarkerType(MarkerType markerType) {
this.markerType = markerType;
}
public MarkerType getMarkerType() {
return markerType;
}
public Float getMarkerSize() {
return markerSize;
}
public void setMarkerType(MarkerType markerType) {
this.markerType = markerType;
}
public void setMarkerSize(Float markerSize) {
this.markerSize = markerSize;
}
public Float getMarkerSize() {
return markerSize;
}
public Integer getMarkerWidth() {
return markerWidth;
}
public void setMarkerSize(Float markerSize) {
this.markerSize = markerSize;
}
public void setMarkerWidth(Integer markerWidth) {
this.markerWidth = markerWidth;
}
public Integer getMarkerWidth() {
return markerWidth;
}
public MarkerTextSize getMarkerTextSize() {
return markerTextSize;
}
public void setMarkerWidth(Integer markerWidth) {
this.markerWidth = markerWidth;
}
public void setMarkerTextSize(MarkerTextSize markerTextSize) {
this.markerTextSize = markerTextSize;
}
public MarkerTextSize getMarkerTextSize() {
return markerTextSize;
}
public String getMapName() {
return mapName;
}
public void setMarkerTextSize(MarkerTextSize markerTextSize) {
this.markerTextSize = markerTextSize;
}
public void setMapName(String mapName) {
this.mapName = mapName;
}
public String getMapName() {
return mapName;
}
public void setMapName(String mapName) {
this.mapName = mapName;
}
}

View file

@ -1,4 +1,5 @@
package gov.noaa.nws.ncep.ui.nsharp.display.map;
/**
*
* gov.noaa.nws.ncep.ui.nsharp.display.map.NsharpObservedSoundingQuery
@ -30,92 +31,113 @@ import gov.noaa.nws.ncep.viz.common.soundingQuery.NcSoundingQuery;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
//Chin-T import com.raytheon.uf.common.sounding.SoundingLayer;
import com.vividsolutions.jts.geom.Coordinate;
//Chin-T import com.raytheon.uf.common.sounding.SoundingLayer;
public class NsharpObservedSoundingQuery {
//Chin-T public static void getObservedSndData(List<NsharpStationInfo> stnPtDataLineLst, Map<String, List<SoundingLayer>> soundingLysLstMap) {
//Chin: note that Nsharp currently GUI only allow user pick one stn at one time, but could be many refTimes.
public static void getObservedSndData(List<NsharpStationInfo> stnPtDataLineLst, boolean rawData, Map<String, List<NcSoundingLayer>> soundingLysLstMap) {
//String pickedStnInfo = "";
List<Coordinate> coords= new ArrayList<Coordinate>();
List<Long> refTimeLst = new ArrayList<Long>();
//create refTime array and lat/lon array
for(NsharpStationInfo StnPt : stnPtDataLineLst){
//one StnPt represent one data time line
//List<Integer> Ids = StnPt.getDbId();
System.out.println("stn lat ="+StnPt.getLatitude()+ " lon="+StnPt.getLongitude());
boolean exist = false;
for(Coordinate c: coords){
if(c.x == StnPt.getLongitude() && c.y == StnPt.getLatitude()){
exist= true;
break;
}
}
if(exist==false) {
Coordinate coord = new Coordinate(StnPt.getLongitude(),StnPt.getLatitude());
coords.add(coord);
}
exist = false;
for(long t: refTimeLst){
if(t == StnPt.getReftime().getTime()){
exist= true;
break;
}
}
if(exist==false) {
refTimeLst.add(StnPt.getReftime().getTime());
}
}
double[][] latLon = new double[coords.size()][2];
for (int i=0; i< coords.size(); i++){
latLon[i][0]= coords.get(i).y; //lat
latLon[i][1]= coords.get(i).x; //lon
}
NcSoundingCube cube = NcSoundingQuery.uaGenericSoundingQuery(refTimeLst.toArray(new Long[0]), latLon, stnPtDataLineLst.get(0).getSndType(),
NcSoundingLayer.DataType.ALLDATA, !rawData, "-1");
//NcSoundingCube cube = NcSoundingQuery.soundingQueryByLatLon(stnPtDataLineLst.get(0).getReftime().getTime(), coords, stnPtDataLineLst.get(0).getSndType(),
// NcSoundingLayer.DataType.ALLDATA, !rawData, "-1");
if(cube != null && cube.getSoundingProfileList().size()>0 && cube.getRtnStatus()==NcSoundingCube.QueryStatus.OK){
for(NcSoundingProfile sndPf : cube.getSoundingProfileList()){
List<NcSoundingLayer> rtnSndLst = sndPf.getSoundingLyLst();
//if(rtnSndLst != null && rtnSndLst.size() > 0){
//NcSoundingProfile sndPf = cube.getSoundingProfileList().get(0);
//System.out.println("size of profile = "+ cube.getSoundingProfileList().size());
//debug
//for(NcSoundingProfile pf: cube.getSoundingProfileList()){
// System.out.println("sounding profile: lat="+pf.getStationLatitude()+" lon="+pf.getStationLongitude()+ " stnId="+ pf.getStationId() );
//}
//List<NcSoundingLayer> rtnSndLst = sndPf.getSoundingLyLst();
// Chin-T List<SoundingLayer> sndLyList = NsharpSoundingQueryCommon.convertToSoundingLayerList(rtnSndLst);
if(rtnSndLst != null && rtnSndLst.size() > 0){
//update sounding data so they can be used by Skewt Resource and PalletWindow
if(rawData)
rtnSndLst = NsharpDataHandling.sortObsSoundingDataForShow(rtnSndLst, sndPf.getStationElevation());
else
rtnSndLst = NsharpDataHandling.organizeSoundingDataForShow(rtnSndLst, sndPf.getStationElevation());
//minimum rtnSndList size will be 2 (50 & 75 mb layers), but that is not enough
// We need at least 2 regular layers for plotting
if(rtnSndLst != null && rtnSndLst.size() > 4){
String dispInfo="";
for(NsharpStationInfo StnPt : stnPtDataLineLst){
if(StnPt.getReftime().getTime() == sndPf.getFcsTime()){
dispInfo = StnPt.getStnDisplayInfo();
break;
}
}
soundingLysLstMap.put(dispInfo, rtnSndLst);
}
}
}
//}
}
}
// Chin-T public static void getObservedSndData(List<NsharpStationInfo>
// stnPtDataLineLst, Map<String, List<SoundingLayer>> soundingLysLstMap) {
// Chin: note that Nsharp currently GUI only allow user pick one stn at one
// time, but could be many refTimes.
public static void getObservedSndData(
List<NsharpStationInfo> stnPtDataLineLst, boolean rawData,
Map<String, List<NcSoundingLayer>> soundingLysLstMap) {
// String pickedStnInfo = "";
List<Coordinate> coords = new ArrayList<Coordinate>();
List<Long> refTimeLst = new ArrayList<Long>();
// create refTime array and lat/lon array
for (NsharpStationInfo StnPt : stnPtDataLineLst) {
// one StnPt represent one data time line
// List<Integer> Ids = StnPt.getDbId();
// System.out.println("stn lat ="+StnPt.getLatitude()+
// " lon="+StnPt.getLongitude());
boolean exist = false;
for (Coordinate c : coords) {
if (c.x == StnPt.getLongitude() && c.y == StnPt.getLatitude()) {
exist = true;
break;
}
}
if (exist == false) {
Coordinate coord = new Coordinate(StnPt.getLongitude(),
StnPt.getLatitude());
coords.add(coord);
}
exist = false;
for (long t : refTimeLst) {
if (t == StnPt.getReftime().getTime()) {
exist = true;
break;
}
}
if (exist == false) {
refTimeLst.add(StnPt.getReftime().getTime());
}
}
double[][] latLon = new double[coords.size()][2];
for (int i = 0; i < coords.size(); i++) {
latLon[i][0] = coords.get(i).y; // lat
latLon[i][1] = coords.get(i).x; // lon
}
NcSoundingCube cube = NcSoundingQuery
.uaGenericSoundingQuery(refTimeLst.toArray(new Long[0]),
latLon, stnPtDataLineLst.get(0).getSndType(),
NcSoundingLayer.DataType.ALLDATA, !rawData, "-1");
// NcSoundingCube cube =
// NcSoundingQuery.soundingQueryByLatLon(stnPtDataLineLst.get(0).getReftime().getTime(),
// coords, stnPtDataLineLst.get(0).getSndType(),
// NcSoundingLayer.DataType.ALLDATA, !rawData, "-1");
if (cube != null && cube.getSoundingProfileList().size() > 0
&& cube.getRtnStatus() == NcSoundingCube.QueryStatus.OK) {
for (NcSoundingProfile sndPf : cube.getSoundingProfileList()) {
List<NcSoundingLayer> rtnSndLst = sndPf.getSoundingLyLst();
// if(rtnSndLst != null && rtnSndLst.size() > 0){
// NcSoundingProfile sndPf =
// cube.getSoundingProfileList().get(0);
// System.out.println("size of profile = "+
// cube.getSoundingProfileList().size());
// debug
// for(NcSoundingProfile pf: cube.getSoundingProfileList()){
// System.out.println("sounding profile: lat="+pf.getStationLatitude()+" lon="+pf.getStationLongitude()+
// " stnId="+ pf.getStationId() );
// }
// List<NcSoundingLayer> rtnSndLst = sndPf.getSoundingLyLst();
// Chin-T List<SoundingLayer> sndLyList =
// NsharpSoundingQueryCommon.convertToSoundingLayerList(rtnSndLst);
if (rtnSndLst != null && rtnSndLst.size() > 0) {
// update sounding data so they can be used by Skewt
// Resource and PalletWindow
if (rawData)
rtnSndLst = NsharpDataHandling
.sortObsSoundingDataForShow(rtnSndLst,
sndPf.getStationElevation());
else
rtnSndLst = NsharpDataHandling
.organizeSoundingDataForShow(rtnSndLst,
sndPf.getStationElevation());
// minimum rtnSndList size will be 2 (50 & 75 mb layers),
// but that is not enough
// We need at least 2 regular layers for plotting
if (rtnSndLst != null && rtnSndLst.size() > 4) {
String dispInfo = "";
for (NsharpStationInfo StnPt : stnPtDataLineLst) {
if (StnPt.getReftime().getTime() == sndPf
.getFcsTime()) {
dispInfo = StnPt.getStnDisplayInfo();
break;
}
}
soundingLysLstMap.put(dispInfo, rtnSndLst);
}
}
}
// }
}
}
}

View file

@ -1,4 +1,5 @@
package gov.noaa.nws.ncep.ui.nsharp.display.rsc;
/**
*
*
@ -53,273 +54,404 @@ import com.raytheon.viz.core.ColorUtil;
import com.raytheon.viz.core.graphing.WGraphics;
import com.vividsolutions.jts.geom.Coordinate;
public class NsharpAbstractPaneResource extends AbstractVizResource<AbstractResourceData, NsharpAbstractPaneDescriptor>{
NsharpNative nsharpNative=null;
protected IGraphicsTarget target=null;
protected Rectangle rectangle;
protected WGraphics world;
protected PixelExtent pe;
protected static final UnitConverter celciusToFahrenheit = SI.CELSIUS.getConverterTo(NonSI.FAHRENHEIT);
protected static final UnitConverter celciusToKelvin = SI.CELSIUS.getConverterTo(SI.KELVIN);
protected List<NcSoundingLayer> soundingLys = null;
protected List<NcSoundingLayer> previousSoundingLys = null;
protected NsharpResourceHandler rscHandler=null;
protected NsharpGraphProperty graphConfigProperty=null;
protected HashMap<String, NsharpLineProperty> linePropertyMap=null;
protected int currentSoundingLayerIndex =0;
protected IFont font9=null;
protected IFont font10=null;
protected IFont font11=null;
protected IFont font12=null;
protected float currentFont10Size=10;
public class NsharpAbstractPaneResource extends
AbstractVizResource<AbstractResourceData, NsharpAbstractPaneDescriptor> {
NsharpNative nsharpNative = null;
protected IGraphicsTarget target = null;
protected Rectangle rectangle;
protected WGraphics world;
protected PixelExtent pe;
protected static final UnitConverter celciusToFahrenheit = SI.CELSIUS
.getConverterTo(NonSI.FAHRENHEIT);
protected static final UnitConverter celciusToKelvin = SI.CELSIUS
.getConverterTo(SI.KELVIN);
protected List<NcSoundingLayer> soundingLys = null;
protected List<NcSoundingLayer> previousSoundingLys = null;
protected NsharpResourceHandler rscHandler = null;
protected NsharpGraphProperty graphConfigProperty = null;
protected HashMap<String, NsharpLineProperty> linePropertyMap = null;
protected int currentSoundingLayerIndex = 0;
protected IFont font9 = null;
protected IFont font10 = null;
protected IFont font11 = null;
protected IFont font12 = null;
protected IFont font20 = null; // d2dlite
protected float currentFont10Size = 10;
protected int commonLinewidth;
protected LineStyle commonLineStyle;
protected Coordinate interactiveTempPointCoordinate;
protected Float currentZoomLevel=1f;
protected float currentCanvasBoundWidth;//= NsharpConstants.DEFAULT_CANVAS_WIDTH;
protected float currentCanvasBoundHeight; //= NsharpConstants.DEFAULT_CANVAS_HEIGHT;
protected float myDefaultCanvasHeight;// = NsharpConstants.DEFAULT_CANVAS_HEIGHT*4/5;
protected float myDefaultCanvasWidth;//= NsharpConstants.DEFAULT_CANVAS_WIDTH/2;
//protected Float zoomLevel;
protected boolean resize=false;
protected String paneConfigurationName;
protected Float currentZoomLevel = 1f;
protected float currentCanvasBoundWidth;// =
// NsharpConstants.DEFAULT_CANVAS_WIDTH;
protected float currentCanvasBoundHeight; // =
// NsharpConstants.DEFAULT_CANVAS_HEIGHT;
protected float myDefaultCanvasHeight;// =
// NsharpConstants.DEFAULT_CANVAS_HEIGHT*4/5;
protected float myDefaultCanvasWidth;// =
// NsharpConstants.DEFAULT_CANVAS_WIDTH/2;
// protected Float zoomLevel;
protected boolean resize = false;
protected String paneConfigurationName;
public static final float INVALID_DATA = NsharpNativeConstants.NSHARP_NATIVE_INVALID_DATA;
protected Coordinate cursorCor;
protected int charHeight = NsharpConstants.CHAR_HEIGHT_;
protected double charWidth;
protected Coordinate cursorCor;
protected double charHeight = NsharpConstants.CHAR_HEIGHT_; // d2dlite
protected double charWidth;
// d2dlite
protected double lineHeight = charHeight * 1.2;
protected PaintProperties paintProps;
public NsharpAbstractPaneResource(AbstractResourceData resourceData,
LoadProperties loadProperties, NsharpAbstractPaneDescriptor desc) {
super(resourceData, loadProperties);
descriptor = desc;
this.dataTimes = new ArrayList<DataTime>();
}
@Override
protected void disposeInternal() {
if(font9!=null){
font9.dispose();
font9=null;
}
if(font10!=null){
font10.dispose();
font10=null;
}
if(font11!=null){
font11.dispose();
font11=null;
}
if(font12!=null){
font12.dispose();
font12=null;
}
this.target.dispose();
target = null;
}
protected boolean sidePaneMode = false; // FixMark:sidePaneLooping d2dlite
public NsharpAbstractPaneResource(AbstractResourceData resourceData,
LoadProperties loadProperties, NsharpAbstractPaneDescriptor desc) {
super(resourceData, loadProperties);
descriptor = desc;
this.dataTimes = new ArrayList<DataTime>();
@Override
protected void paintInternal(IGraphicsTarget target,
PaintProperties paintProps) throws VizException {
this.paintProps = paintProps;
this.target = target;
if(rscHandler== null || rscHandler.getSoundingLys()==null)
return;
float zoomLevel = paintProps.getZoomLevel();
/*if( currentCanvasBoundWidth!= paintProps.getCanvasBounds().width || currentCanvasBoundHeight!=paintProps.getCanvasBounds().height){
}
currentCanvasBoundWidth= paintProps.getCanvasBounds().width;
currentCanvasBoundHeight=paintProps.getCanvasBounds().height;
adjustFontSize(currentCanvasBoundWidth,currentCanvasBoundHeight);
}
*/
//System.out.println("currentZoomLevel="+currentZoomLevel+" paintProps's zoomLevel="+zoomLevel);
if(zoomLevel > 1.0f)
zoomLevel = 1.0f;
if((zoomLevel != currentZoomLevel) ){
currentZoomLevel = zoomLevel;
handleZooming();
}
if(this.resize==true ){
handleResize();
}
}
@Override
protected void disposeInternal() {
if (font9 != null) {
font9.dispose();
font9 = null;
}
if (font10 != null) {
font10.dispose();
font10 = null;
}
if (font11 != null) {
font11.dispose();
font11 = null;
}
if (font12 != null) {
font12.dispose();
font12 = null;
}
if (font20 != null) { // d2dlite
font20.dispose();
font20 = null;
}
this.target.dispose();
target = null;
}
@Override
protected void initInternal(IGraphicsTarget target) throws VizException {
this.target = target;
this.font9 = target.initializeFont("Monospace", 9, null);
this.font10 = target.initializeFont("Monospace", 10, null);
this.font11 = target.initializeFont("Monospace", 11, null);
IFont.Style[] style = {IFont.Style.BOLD};
this.font12 = target.initializeFont("Monospace", 12, style);
this.font9.setSmoothing(false);
this.font9.setScaleFont(false);
this.font10.setSmoothing(false);
this.font10.setScaleFont(false);
this.font11.setSmoothing(false);
this.font11.setScaleFont(false);
this.font12.setSmoothing(false);
this.font12.setScaleFont(false);
commonLinewidth = getCapability(OutlineCapability.class).getOutlineWidth();
commonLineStyle = getCapability(OutlineCapability.class)
.getLineStyle();
this.resize=true ;
//nsharpNative = new NsharpNative();
//System.out.println("NsharpDefaultPaneResource ::: initInternal with native "+ nsharpNative.toString());
}
@SuppressWarnings("deprecation")
public void resetData(List<NcSoundingLayer> soundingLys, List<NcSoundingLayer> prevsoundingLys){
this.soundingLys = soundingLys;
this.previousSoundingLys = prevsoundingLys;
descriptor.setFrame(0);
}
@Override
protected void paintInternal(IGraphicsTarget target,
PaintProperties paintProps) throws VizException {
this.paintProps = paintProps;
this.target = target;
if (rscHandler == null || rscHandler.getSoundingLys() == null)
return;
float zoomLevel = paintProps.getZoomLevel();
/*
* if( currentCanvasBoundWidth!= paintProps.getCanvasBounds().width ||
* currentCanvasBoundHeight!=paintProps.getCanvasBounds().height){
*
* currentCanvasBoundWidth= paintProps.getCanvasBounds().width;
* currentCanvasBoundHeight=paintProps.getCanvasBounds().height;
* adjustFontSize(currentCanvasBoundWidth,currentCanvasBoundHeight); }
*/
// System.out.println("currentZoomLevel="+currentZoomLevel+" paintProps's zoomLevel="+zoomLevel);
if (zoomLevel > 1.0f)
zoomLevel = 1.0f;
if ((zoomLevel != currentZoomLevel)) {
currentZoomLevel = zoomLevel;
handleZooming();
public WGraphics getWorld() {
return world;
}
protected void adjustFontSize(float canvasW, float canvasH ) {
float font9Size,font10Size,font11Size,font12Size;
float fontAdjusted=0;
float fontBaseH=90f; //Chin: why 70 & 100? After many "try and error" experiments...
float fontBaseW=120f;
if(canvasH < myDefaultCanvasHeight && canvasW< myDefaultCanvasWidth){
//both width and height are smaller than default
float wAdjust = (float)(myDefaultCanvasWidth-canvasW)/fontBaseW;
float hAdjust = (float)(myDefaultCanvasHeight-canvasH)/fontBaseH;
fontAdjusted = Math.max(wAdjust,hAdjust);
}
else if(canvasW< myDefaultCanvasWidth){
// only width smaller than default
fontAdjusted = (float)(myDefaultCanvasWidth-canvasW)/fontBaseW;
}
else if(canvasH < myDefaultCanvasHeight ){
// only height smaller than default
fontAdjusted = (float)(myDefaultCanvasHeight-canvasH)/fontBaseH;
}
//Chin: Can not bigger than 9, otherwise, fint9 size willbe negative.
//Why 8.8 ? After many "try and error" experiments...
if(fontAdjusted > 8.8)
fontAdjusted=8.8f;
font9Size = 9-fontAdjusted;
font10Size = 10-fontAdjusted;
font11Size =11-fontAdjusted;
font12Size = 12-fontAdjusted;
}
if (this.resize == true) {
handleResize();
}
}
if(font9!=null){
font9.dispose();
}
font9 = target.initializeFont("Monospace", font9Size, null);
if(font10!=null){
font10.dispose();
}
font10 = target.initializeFont("Monospace", font10Size, null);
if(font11!=null){
font11.dispose();
}
font11 = target.initializeFont("Monospace", font11Size, null);
if(font12!=null){
font12.dispose();
}
IFont.Style[] style = {IFont.Style.BOLD};
font12 = target.initializeFont("Monospace", font12Size, style);
currentFont10Size = font10Size;
//System.out.println(descriptor.getPaneNumber()+": adjusted font10 size ="+currentFont10Size);
}
protected void magnifyFont(double zoomLevel) {
float magFactor = 1.0f / (float)zoomLevel;
font9.setMagnification(magFactor);
font10.setMagnification(magFactor);
font11.setMagnification(magFactor);
font12.setMagnification(magFactor);
}
@Override
@Override
protected void initInternal(IGraphicsTarget target) throws VizException {
this.target = target;
this.font9 = target.initializeFont("Monospace", 9, null);
this.font10 = target.initializeFont("Monospace", 10, null);
this.font11 = target.initializeFont("Monospace", 11, null);
IFont.Style[] style = { IFont.Style.BOLD };
this.font12 = target.initializeFont("Monospace", 12, style);
this.font20 = target.initializeFont("Monospace", 20, null); // d2dlite
this.font9.setSmoothing(false);
this.font9.setScaleFont(false);
this.font10.setSmoothing(false);
this.font10.setScaleFont(false);
this.font11.setSmoothing(false);
this.font11.setScaleFont(false);
this.font12.setSmoothing(false);
this.font12.setScaleFont(false);
this.font20.setSmoothing(false); // d2dlite
this.font20.setScaleFont(false);
commonLinewidth = getCapability(OutlineCapability.class)
.getOutlineWidth();
commonLineStyle = getCapability(OutlineCapability.class).getLineStyle();
this.resize = true;
// nsharpNative = new NsharpNative();
// System.out.println("NsharpDefaultPaneResource ::: initInternal with native "+
// nsharpNative.toString());
}
@SuppressWarnings("deprecation")
public void resetData(List<NcSoundingLayer> soundingLys,
List<NcSoundingLayer> prevsoundingLys) {
this.soundingLys = soundingLys;
this.previousSoundingLys = prevsoundingLys;
descriptor.setFrame(0);
}
public WGraphics getWorld() {
return world;
}
protected void adjustFontSize(float canvasW, float canvasH) {
float font9Size, font10Size, font11Size, font12Size, font20Size; // d2dlite
float fontAdjusted = 0;
float fontBaseH = 90f; // Chin: why 70 & 100? After many "try and error"
// experiments...
float fontBaseW = 120f;
if (canvasH < myDefaultCanvasHeight && canvasW < myDefaultCanvasWidth) {
// both width and height are smaller than default
float wAdjust = (float) (myDefaultCanvasWidth - canvasW)
/ fontBaseW;
float hAdjust = (float) (myDefaultCanvasHeight - canvasH)
/ fontBaseH;
fontAdjusted = Math.max(wAdjust, hAdjust);
} else if (canvasW < myDefaultCanvasWidth) {
// only width smaller than default
fontAdjusted = (float) (myDefaultCanvasWidth - canvasW) / fontBaseW;
} else if (canvasH < myDefaultCanvasHeight) {
// only height smaller than default
fontAdjusted = (float) (myDefaultCanvasHeight - canvasH)
/ fontBaseH;
}
// Chin: Can not bigger than 9, otherwise, fint9 size willbe negative.
// Why 8.8 ? After many "try and error" experiments...
if (fontAdjusted > 8.8)
fontAdjusted = 8.8f;
font9Size = 9 - fontAdjusted;
font10Size = 10 - fontAdjusted;
font11Size = 11 - fontAdjusted;
font12Size = 12 - fontAdjusted;
font20Size = 20 - fontAdjusted; // d2dlite
if (font9 != null) {
font9.dispose();
}
font9 = target.initializeFont("Monospace", font9Size, null);
if (font10 != null) {
font10.dispose();
}
font10 = target.initializeFont("Monospace", font10Size, null);
if (font11 != null) {
font11.dispose();
}
font11 = target.initializeFont("Monospace", font11Size, null);
if (font12 != null) {
font12.dispose();
}
IFont.Style[] style = { IFont.Style.BOLD };
font12 = target.initializeFont("Monospace", font12Size, style);
// d2dlite
if (font20 != null) {
font20.dispose();
}
font20 = target.initializeFont("Monospace", font20Size, style);
currentFont10Size = font10Size;
// System.out.println(descriptor.getPaneNumber()+": adjusted font10 size ="+currentFont10Size);
}
protected void magnifyFont(double zoomLevel) {
float magFactor = 1.0f / (float) zoomLevel;
font9.setMagnification(magFactor);
font10.setMagnification(magFactor);
font11.setMagnification(magFactor);
font12.setMagnification(magFactor);
font20.setMagnification(magFactor); // d2dlite
}
@Override
public void setDescriptor(NsharpAbstractPaneDescriptor descriptor) {
super.setDescriptor(descriptor);
RGB rgb = ColorUtil.getNewColor(descriptor);
getCapability(ColorableCapability.class).setColor(rgb);
//System.out.println("screwT Rsc setDescriptor called");
// System.out.println("screwT Rsc setDescriptor called");
}
public void setSoundingLys(List<NcSoundingLayer> soundingLys) {
this.soundingLys = soundingLys;
}
public void setSoundingLys(List<NcSoundingLayer> soundingLys) {
this.soundingLys = soundingLys;
}
public HashMap<String, NsharpLineProperty> getLinePropertyMap() {
return linePropertyMap;
}
public HashMap<String, NsharpLineProperty> getLinePropertyMap() {
return linePropertyMap;
}
public void setLinePropertyMap(
HashMap<String, NsharpLineProperty> linePropertyMap) {
this.linePropertyMap = linePropertyMap;
}
public void setLinePropertyMap(
HashMap<String, NsharpLineProperty> linePropertyMap) {
this.linePropertyMap = linePropertyMap;
public NsharpGraphProperty getGraphConfigProperty() {
return graphConfigProperty;
}
}
public void setGraphConfigProperty(NsharpGraphProperty graphConfigProperty) {
this.graphConfigProperty = graphConfigProperty;
paneConfigurationName = this.graphConfigProperty.getPaneConfigurationName();
}
public NsharpGraphProperty getGraphConfigProperty() {
return graphConfigProperty;
}
public NsharpResourceHandler getRscHandler() {
return rscHandler;
}
public void setGraphConfigProperty(NsharpGraphProperty graphConfigProperty) {
this.graphConfigProperty = graphConfigProperty;
paneConfigurationName = this.graphConfigProperty
.getPaneConfigurationName();
public int getCurrentSoundingLayerIndex() {
return currentSoundingLayerIndex;
}
}
public void setRscHandler(NsharpResourceHandler rscHandler) {
this.rscHandler = rscHandler;
if(descriptor != null)
descriptor.setRscHandler(rscHandler);
}
public NsharpResourceHandler getRscHandler() {
return rscHandler;
}
public int getCurrentSoundingLayerIndex() {
return currentSoundingLayerIndex;
}
public void setRscHandler(NsharpResourceHandler rscHandler) {
this.rscHandler = rscHandler;
if (descriptor != null)
descriptor.setRscHandler(rscHandler);
}
public void setNsharpNative(NsharpNative nsharpNative) {
this.nsharpNative = nsharpNative;
}
public void handleResize() {
this.resize = false;
// double vertRatio = paintProps.getView().getExtent().getHeight() /
// paintProps.getCanvasBounds().height;
// double hRatio = paintProps.getView().getExtent().getWidth() /
// paintProps.getCanvasBounds().width;
// System.out.println(descriptor.getPaneNumber()+"viewWidth="+paintProps.getView().getExtent().getWidth()+" viewHeight="+paintProps.getView().getExtent().getHeight()
// );
// System.out.println(descriptor.getPaneNumber()+"canvWidth="+paintProps.getCanvasBounds().width+" canvHeight="+paintProps.getCanvasBounds().height
// );
// System.out.println(descriptor.getPaneNumber()+": vertRatio="+vertRatio
// + " hRatio="+hRatio);
if (paintProps != null
&& (currentCanvasBoundWidth != paintProps.getCanvasBounds().width || currentCanvasBoundHeight != paintProps
.getCanvasBounds().height)) {
currentCanvasBoundWidth = paintProps.getCanvasBounds().width;
currentCanvasBoundHeight = paintProps.getCanvasBounds().height;
adjustFontSize(currentCanvasBoundWidth, currentCanvasBoundHeight);
}
}
public void setResize(boolean resize) {
this.resize = resize;
}
public void handleZooming() {
}
// FixMark:sidePaneLooping
public boolean isSidePaneMode() {
return sidePaneMode;
}
// FixMark:sidePaneLooping
public void setSidePaneMode(boolean sidePaneMode) {
this.sidePaneMode = sidePaneMode;
}
protected void defineCharHeight(IFont font) {
if (paintProps == null)
return;
DrawableString str = new DrawableString("CHINCHEN",
NsharpConstants.color_black);
str.font = font;
double vertRatio = paintProps.getView().getExtent().getHeight()
/ paintProps.getCanvasBounds().height;
double horizRatio = paintProps.getView().getExtent().getWidth()
/ paintProps.getCanvasBounds().width;
charHeight = target.getStringsBounds(str).getHeight() * vertRatio; // d2dlite
lineHeight = charHeight * 1.2; // d2dlite
charWidth = target.getStringsBounds(str).getWidth() * horizRatio / 8;
}
// d2dlite start
protected String timeDescriptionToDisplayStr(String timeDescription) {
/*
* As of 2014 April 9, current time description string is defined as
* "YYMMDD/HH(DOW)" or "YYMMDD/HH(DOW)Vxxx". Convert them to
* "DD.HH(DOW)" or "DD.HHVxxx(DOW)" for GUI display.
*/
String rtnStr = timeDescription.substring(4); // get rid of YYMM
if (rtnStr.contains("V")) {
String[] s1Str = rtnStr.split("V"); // split DD/HH(DOW)Vxxx to
// "DD/HH(DOW)" and "xxx"
String[] s2Str = s1Str[0].split("\\("); // split "DD/HH(DOW)" to
// "DD/HH" and "DOW)"
rtnStr = s2Str[0] + "V" + s1Str[1] + "(" + s2Str[1]; // put together
// to
// "DD/HHVxxx(DOW)"
}
rtnStr = rtnStr.replace("/", "."); // replace "/" with "."
return rtnStr;
}
protected String pickedStnInfoStrToDisplayStr(String pickedStnInfoStr) {
/*
* As of 2014 April 9, current pickedStnInfoStr string is defined as
* "stnId YYMMDD/HH(DOW)Vxxx sndType". This function is to convert it to
* "stnId DD.HHVxxx(DOW) sndType" for GUI display. for example,
* "ATLH 101209/03(Thu)V003 GFS230" converts to
* "ATLH 09.03V003(Thu) GFS230"
*/
String[] s1Str = pickedStnInfoStr.split(" ");
if (s1Str.length == 3) {
String rtnStr = timeDescriptionToDisplayStr(s1Str[1]);
rtnStr = s1Str[0] + " " + rtnStr + " " + s1Str[2];
return rtnStr;
} else
return pickedStnInfoStr; // not a good input, just return it
}
// d2dlite end
public void setNsharpNative(NsharpNative nsharpNative) {
this.nsharpNative = nsharpNative;
}
public void handleResize(){
this.resize=false;
//double vertRatio = paintProps.getView().getExtent().getHeight() / paintProps.getCanvasBounds().height;
//double hRatio = paintProps.getView().getExtent().getWidth() / paintProps.getCanvasBounds().width;
//System.out.println(descriptor.getPaneNumber()+"viewWidth="+paintProps.getView().getExtent().getWidth()+" viewHeight="+paintProps.getView().getExtent().getHeight() );
//System.out.println(descriptor.getPaneNumber()+"canvWidth="+paintProps.getCanvasBounds().width+" canvHeight="+paintProps.getCanvasBounds().height );
//System.out.println(descriptor.getPaneNumber()+": vertRatio="+vertRatio + " hRatio="+hRatio);
if(paintProps!=null && (currentCanvasBoundWidth!= paintProps.getCanvasBounds().width || currentCanvasBoundHeight!=paintProps.getCanvasBounds().height)){
currentCanvasBoundWidth= paintProps.getCanvasBounds().width;
currentCanvasBoundHeight=paintProps.getCanvasBounds().height;
adjustFontSize(currentCanvasBoundWidth,currentCanvasBoundHeight);
}
}
public void setResize(boolean resize) {
this.resize = resize;
}
public void handleZooming(){
}
protected void defineCharHeight(IFont font){
if(paintProps == null)
return;
DrawableString str =new DrawableString("CHINCHEN",NsharpConstants.color_black);
str.font = font;
double vertRatio = paintProps.getView().getExtent().getHeight() / paintProps.getCanvasBounds().height;
double horizRatio = paintProps.getView().getExtent().getWidth() / paintProps.getCanvasBounds().width;
charHeight = (int) (target.getStringsBounds(str).getHeight() * vertRatio);
charWidth = target.getStringsBounds(str).getWidth() * horizRatio /8;
//System.out.println(descriptor.getPaneNumber()+": font10 char height ="+charHeight+ " vertRatio="+vertRatio);
}
}

View file

@ -213,6 +213,20 @@ public class NsharpHodoPaneResource extends NsharpAbstractPaneResource{
}
}
else if(compareSndIsOn && currentStnListIndex >=0 && currentTimeListIndex >=0){
//start FixMark:nearByStnCompSnd
List<NsharpResourceHandler.CompSndSelectedElem> sndCompElementList = rscHandler.getCompSndSelectedElemList();
for(NsharpResourceHandler.CompSndSelectedElem compElem: sndCompElementList){
NsharpSoundingElementStateProperty elemProp = stnTimeSndTable.get(compElem.getStnIndex()).get(compElem.getTimeIndex()).get(compElem.getSndIndex());
if(sndElemList.get(compElem.getSndIndex()).getActionState()== NsharpConstants.ActState.ACTIVE &&
elemProp!=null){
List<NcSoundingLayer> soundingLayeys = elemProp.getSndLyLst();
int colorIndex = elemProp.getCompColorIndex();
RGB color = linePropertyMap.get(NsharpConstants.lineNameArray[colorIndex]).getLineColor();
createRscHodoWindShape(world, soundingLayeys, color);
}
}
/* origonal code
for(NsharpOperationElement elm: sndElemList) {
if(elm.getActionState() == NsharpConstants.ActState.ACTIVE &&
stnTimeSndTable.get(currentStnListIndex).get(currentTimeListIndex).get(sndElemList.indexOf(elm))!=null){
@ -221,7 +235,8 @@ public class NsharpHodoPaneResource extends NsharpAbstractPaneResource{
RGB color = linePropertyMap.get(NsharpConstants.lineNameArray[colorIndex]).getLineColor();
createRscHodoWindShape(world, soundingLayeys, color);
}
}
}*/
//end FixMark:nearByStnCompSnd
}
else if(overlayIsOn == true ){
previousSoundingLys = rscHandler.getPreviousSoundingLys();

View file

@ -20,362 +20,585 @@
*/
package gov.noaa.nws.ncep.ui.nsharp.natives;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingLayer;
import java.util.HashMap;
import java.util.Map;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingLayer;
public class NsharpNativeConstants {
public static final float NSHARP_NATIVE_INVALID_DATA = NcSoundingLayer.MISSING; //-9999f
//Note: legacy NSHARP lib return -999 as invalid data
public static final float NSHARP_LEGACY_LIB_INVALID_DATA = NcSoundingLayer.MISSING; //-9999f
public static final float PI = 3.14159265F;
/*
* PAGE1 CANVAS1 string definitions
*/
public static final String PAGE1TEXT1_SB_STR ="SB PARCEL ";
public static final String PAGE1TEXT1_ML_STR ="ML PARCEL ";
public static final String PAGE1TEXT1_FCST_STR ="FCST PARCEL";
public static final String PAGE1TEXT1_MU_STR ="MU PARCEL ";
public static final String PAGE1TEXT1_USER_STR ="USER PARCEL";
public static final String PAGE1TEXT1_EFF_STR ="EFF PARCEL ";
//PARCELTYPES_STR array: order of array element should follow PARCELTYPE_* definitions below.
//public static final String[] PARCELTYPES_STR = {"", PAGE1TEXT1_SB_STR, PAGE1TEXT1_FCST_STR,PAGE1TEXT1_ML_STR,
// PAGE1TEXT1_MU_STR, PAGE1TEXT1_USER_STR, PAGE1TEXT1_EFF_STR
//};
/*
* PAGE1 Panel2 string definitions
*/
public static final String[] STORM_MOTION_TYPE_STR1 = { "SFC-1km", "SFC_2km",
"SFC_3km", "Eff Inflow Layer"
};
public static final String[] STORM_MOTION_TYPE_STR2 = { "SFC-6km","SFC-8km", "LCL-EL(Cloud Layer)",
"Lower Half Storm Depth"
};
public static final float[][] STORM_MOTION_HEIGHT1 = { {0,1000}, {0,2000}, {0,3000}, {0,0}
};
public static final float[][] STORM_MOTION_HEIGHT2 = { {0,6000},
{0, 8000}, {0,0},{0,0}
};
/*
* PARCEL DATA string definitions
*/
//PARCEL type flags to be used for define_parcel()
public static final short PARCELTYPE_CUIRRENT_SELECTION = -1;
public static final short PARCELTYPE_OBS_SFC = 1;
public static final short PARCELTYPE_FCST_SFC = 2;
public static final short PARCELTYPE_MOST_UNSTABLE = 3;//BigNsharp
public static final short PARCELTYPE_MEAN_MIXING = 4; //BigNsharp
public static final short PARCELTYPE_USER_DEFINED = 5;
public static final short PARCELTYPE_EFF = 6; //BigNsharp
public static final short PARCEL_MAX = PARCELTYPE_EFF;
//default pressure for parcel as defined in BigNsharp
public static final float OBS_LAYER = 0.0f;
public static final float FCST_LAYER = 0.0f;
public static final float MML_LAYER = 100.0f; /* mean-mixed layer */
public static final float MU_LAYER = 400.0f; /* most-unstable layer */
public static final float USER_LAYER = 850.0f; /* default user-defined level */
public static final float EFF_LAYER = MU_LAYER; //Chin, need to check with John
/*1 = Observed sfc parcel */
/* 2 = Fcst sfc parcel */
/* 3 = Most unstable parcel */
/* 4 = Mean mixlyr parcel */
/* 5 = User defined parcel */
/* 6 = Mean Effective Layer parcel
*
*/
//parcel header string
public static final String PARCEL_DATA_STR = "\t\t\t\tPARCEL DATA \r\n";
public static final String PARCEL_OBS_SFC_STR = "\t\t*** SFC PARCEL ***\r\n";
public static final String PARCEL_FORECAST_SFC_STR = "\t\t*** FCST SFC PARCEL ***\r\n";
public static final String PARCEL_MEAN_MIXING_STR = "\t\t*** MEAN MIXING LAYER PARCEL ***\r\n";
public static final String PARCEL_MOST_UNSTABLE_STR = "\t\t*** MOST UNSTABLE PARCEL ***\r\n";
public static final String PARCEL_MEAN_EFF_STR = "\t\t*** MEAN EFFECTIVE PARCEL ***\r\n";
public static final String PARCEL_USR_DEFINED_STR = "\t\t*** %.1f mb PARCEL ***\r\n";
//parcel lines
public static final String PARCEL_LPL_LINE = "LPL:\t%dmb\t%dC/%dC\t%dF/%dF\r\n\r\n";
public static final String PARCEL_LPL_LINE_ = "LPL:_%dmb_%dC/%dC_%dF/%dF";
public static final String PARCEL_CAPE_LINE = "CAPE = %.0f J/Kg";
public static final String PARCEL_CAPE_MISSING = "CAPE = M";
public static final String PARCEL_LI_LINE = "LI(500mb) =%5.0fC\r\n";
public static final String PARCEL_LI_MISSING = "LI(500mb) = M\r\n";
public static final String PARCEL_BFZL_LINE = "BFZL = %.0f J/Kg";
public static final String PARCEL_BFZL_MISSING = "BFZL = M";
public static final String PARCEL_LIMIN_LINE = "LImin = %4.0fC /%4.0fmb\r\n";
public static final String PARCEL_LIMIN_MISSING = "LImin = M / M\r\n";
public static final String PARCEL_CINH_LINE = "CINH = %.0f J/Kg";
public static final String PARCEL_CINH_MISSING = "CINH = M";
public static final String PARCEL_CAP_LINE = "Cap = %4.0fC /%4.0fmb\r\n\r\n";
public static final String PARCEL_CAP_MISSING = "Cap = M / M\r\n\r\n";
public static final String PARCEL_LEVEL_LINE = "LEVEL\t\tPRES\t\tHGT(AGL)\t\tTEMP\r\n____________________________________________________\r\n";
public static final String PARCEL_LEVEL_LINE_ = "LEVEL_PRES_HGT(AGL)_TEMP";
public static final String PARCEL_LCL_LINE = "LCL\t\t%5.0fmb\t\t%7.0fft\r\n";
public static final String PARCEL_LCL_LINE_ = "LCL_%5.0fmb_%7.0fft_ ";
public static final String PARCEL_LCL_MISSING = "LCL\t\tM \t\tM\r\n";
public static final String PARCEL_LCL_MISSING_ = "LCL_M_M_ ";
public static final String PARCEL_LFC_LINE = "LFC\t\t%5.0fmb\t\t%7.0fft\t%6.0fC\r\n";
public static final String PARCEL_LFC_LINE_ = "LFC_%5.0fmb_%7.0fft_%6.0fC";
public static final String PARCEL_LFC_MISSING = "LFC\t\tM \t\tM \t\t\tM\r\n";
public static final String PARCEL_LFC_MISSING_ = "LFC_M_M_M";
public static final String PARCEL_EL_LINE = "EL \t\t%5.0fmb\t\t%7.0fft\t%6.0fC\r\n";
public static final String PARCEL_EL_LINE_ = "EL_%5.0fmb_%7.0fft_%6.0fC";
public static final String PARCEL_EL_MISSING = "EL \t\tM \t\tM \t\t\tM\r\n";
public static final String PARCEL_EL_MISSING_ = "EL_M_M_M";
public static final String PARCEL_MPL_LINE = "MPL\t\t%5.0fmb\t\t%7.0fft\r\n";
public static final String PARCEL_MPL_LINE_ = "MPL_%5.0fmb_%7.0fft_ ";
public static final String PARCEL_MPL_MISSING = "MPL\t\tM \t\tM\r\n";
public static final String PARCEL_MPL_MISSING_ = "MPL_M_M_ ";
/*
* THERMODYNAMIC DATA string definitions
*/
// THERMODYNAMIC HEADER STR
public static final String THERMO_DATA_STR = "\t\t\t\tTHERMODYNAMIC DATA \r\n";
public static final String THERMO_MOISTURE_STR = "\t\t------ AVAILABLE MOISTURE ------\r\n";
public static final String THERMO_INSTABILITY_STR = "\t\t------ CONDITIONAL INSTABILITY ------\r\n";
public static final String THERMO_MISC_PARMS_STR = "\t\t------ MISC PARAMETERS ------\r\n";
// THERMODYNAMIC LINE STRING
public static final String THERMO_PWATER_LINE = "P. Water = %2.2f in\t\t";
public static final String THERMO_PWATER_MISSING = "P. Water = M \t\t";
public static final String THERMO_MEANRH_LINE = "Mean RH = %.0f %c \r\n";
public static final String THERMO_MEANRH_MISSING = "Mean RH = M\r\n";
public static final String THERMO_MEANW_LINE = "Mean W = %.1fg/Kg\t\t";
public static final String THERMO_MEANW_MISSING = "Mean W = M\t\t\t";
public static final String THERMO_MEANLRH_LINE = "Mean LRH = %.0f %c \r\n";
public static final String THERMO_MEANLRH_MISSING = "Mean LRH = M\r\n";
public static final String THERMO_TOP_LINE = "Top of Moist Lyr = %.0f mb / %.0f ft\r\n";
public static final String THERMO_TOP_MISSING = "Top of Moist Lyr = \t\tM / M\r\n\r\n";
public static final String THERMO_700500mb_LINE = "700-500mb Lapse Rate = %.0f C / %.1f C/Km\r\n";
public static final String THERMO_700500mb_MISSING = "700-500mb Lapse Rate = M / M\r\n\r\n";
public static final String THERMO_850500mb_LINE = "850-500mb Lapse Rate = %.0f C / %.1f C/Km\r\n";
public static final String THERMO_850500mb_MISSING = "850-500mb Lapse Rate = M / M\r\n\r\n";
public static final String THERMO_TOTAL_LINE = "Total Totals = %.0f\t\t";
public static final String THERMO_TOTAL_MISSING = "Total Totals = M \t\t";
public static final String THERMO_KINDEX_LINE = "K-Index = %.0f\r\n";
public static final String THERMO_KINDEX_MISSING = "K-Index = M\r\n";
public static final String THERMO_SWEAT_LINE = "SWEAT Index = %.0f\t\t";
public static final String THERMO_SWEAT_MISSING = "SWEAT Index = M\t\t";
public static final String THERMO_MAXT_LINE = "Max Temp = %.0fF\r\n";
public static final String THERMO_MAXT_MISSING = "Max Temp = M\r\n";
public static final String THERMO_THETAE_LINE = "ThetaE Diff = %.0fC\t\t";
public static final String THERMO_THETAE_MISSING = "ThetaE Diff = M \t\t";
public static final String THERMO_CONVT_LINE = "Conv Temp = %.0fF\r\n";
public static final String THERMO_CONVT_MISSING = "Conv Temp = M\r\n";
public static final String THERMO_FGZ_MISSING = "FGZ level = M\r\n";
public static final String THERMO_FGZ_LINE = "FGZ level = %.0fft\r\n";
public static final String THERMO_WBZ_MISSING = "WBZ level = M \t\t";
public static final String THERMO_WBZ_LINE = "WBZ level = %3.0fft\t";
/*
* OPC LOW LEVEL STABILITY data string
*/
public static final String OPC_LOW_LEVEL_STR = "\t\t\t OPC LOW LEVEL STABILITY \r\n";
public static final float NSHARP_NATIVE_INVALID_DATA = NcSoundingLayer.MISSING; // -9999f
// Note: legacy NSHARP lib return -999 as invalid data
public static final float NSHARP_LEGACY_LIB_INVALID_DATA = NcSoundingLayer.MISSING; // -9999f
public static final float PI = 3.14159265F;
/*
* PAGE1 CANVAS1 string definitions
*/
public static final String PAGE1TEXT1_SB_STR = "SB PARCEL ";
public static final String PAGE1TEXT1_ML_STR = "ML PARCEL ";
public static final String PAGE1TEXT1_FCST_STR = "FCST PARCEL";
public static final String PAGE1TEXT1_MU_STR = "MU PARCEL ";
public static final String PAGE1TEXT1_USER_STR = "USER PARCEL";
public static final String PAGE1TEXT1_EFF_STR = "EFF PARCEL ";
// PARCELTYPES_STR array: order of array element should follow PARCELTYPE_*
// definitions below.
// public static final String[] PARCELTYPES_STR = {"", PAGE1TEXT1_SB_STR,
// PAGE1TEXT1_FCST_STR,PAGE1TEXT1_ML_STR,
// PAGE1TEXT1_MU_STR, PAGE1TEXT1_USER_STR, PAGE1TEXT1_EFF_STR
// };
/*
* PAGE1 Panel2 string definitions
*/
public static final String[] STORM_MOTION_TYPE_STR1 = { "SFC-1km",
"SFC-2km", "SFC-3km", "Eff Inflow Layer" };
public static final String[] STORM_MOTION_TYPE_STR2 = { "SFC-6km",
"SFC-8km", "LCL-EL(Cloud Layer)", "Lower Half Storm Depth" };
public static final float[][] STORM_MOTION_HEIGHT1 = { { 0, 1000 },
{ 0, 2000 }, { 0, 3000 }, { 0, 0 } };
public static final float[][] STORM_MOTION_HEIGHT2 = { { 0, 6000 },
{ 0, 8000 }, { 0, 0 }, { 0, 0 } };
/*
* PARCEL DATA string definitions
*/
// PARCEL type flags to be used for define_parcel()
public static final short PARCELTYPE_CUIRRENT_SELECTION = -1;
public static final short PARCELTYPE_OBS_SFC = 1;
public static final short PARCELTYPE_FCST_SFC = 2;
public static final short PARCELTYPE_MOST_UNSTABLE = 3;// BigNsharp
public static final short PARCELTYPE_MEAN_MIXING = 4; // BigNsharp
public static final short PARCELTYPE_USER_DEFINED = 5;
public static final short PARCELTYPE_EFF = 6; // BigNsharp
public static final short PARCEL_MAX = PARCELTYPE_EFF;
public static final short PARCEL_D2DLITE_MAX = PARCELTYPE_MOST_UNSTABLE; // d2dlite
// default pressure for parcel as defined in BigNsharp
public static final float OBS_LAYER = 0.0f;
public static final float FCST_LAYER = 0.0f;
public static final float MML_LAYER = 100.0f; /* mean-mixed layer */
public static final float MU_LAYER = 400.0f; /* most-unstable layer */
public static final float USER_LAYER = 850.0f; /* default user-defined level */
public static final float EFF_LAYER = MU_LAYER; // Chin, need to check with
// John
/* 1 = Observed sfc parcel */
/* 2 = Fcst sfc parcel */
/* 3 = Most unstable parcel */
/* 4 = Mean mixlyr parcel */
/* 5 = User defined parcel */
/*
* 6 = Mean Effective Layer parcel
*/
// parcel header string
public static final String PARCEL_DATA_STR = "\t\t\t\tPARCEL DATA \r\n";
public static final String PARCEL_OBS_SFC_STR = "\t\t*** SFC PARCEL ***\r\n";
public static final String PARCEL_FORECAST_SFC_STR = "\t\t*** FCST SFC PARCEL ***\r\n";
public static final String PARCEL_MEAN_MIXING_STR = "\t\t*** MEAN MIXING LAYER PARCEL ***\r\n";
public static final String PARCEL_MOST_UNSTABLE_STR = "\t\t*** MOST UNSTABLE PARCEL ***\r\n";
public static final String PARCEL_MEAN_EFF_STR = "\t\t*** MEAN EFFECTIVE PARCEL ***\r\n";
public static final String PARCEL_USR_DEFINED_STR = "\t\t*** %.1f mb PARCEL ***\r\n";
// parcel lines
public static final String PARCEL_LPL_LINE = "LPL:\t%dmb\t%dC/%dC\t%dF/%dF\r\n\r\n";
public static final String PARCEL_LPL_LINE_ = "LPL:_%dmb_%dC/%dC_%dF/%dF";
public static final String PARCEL_CAPE_LINE = "CAPE = %.0f J/Kg";
public static final String PARCEL_CAPE_MISSING = "CAPE = M";
public static final String PARCEL_LI_LINE = "LI(500mb) =%5.0fC\r\n";
public static final String PARCEL_LI_MISSING = "LI(500mb) = M\r\n";
public static final String PARCEL_BFZL_LINE = "BFZL = %.0f J/Kg";
public static final String PARCEL_BFZL_MISSING = "BFZL = M";
public static final String PARCEL_LIMIN_LINE = "LImin = %4.0fC /%4.0fmb\r\n";
public static final String PARCEL_LIMIN_MISSING = "LImin = M / M\r\n";
public static final String PARCEL_CINH_LINE = "CINH = %.0f J/Kg";
public static final String PARCEL_CINH_MISSING = "CINH = M";
public static final String PARCEL_CAP_LINE = "Cap = %4.0fC /%4.0fmb\r\n\r\n";
public static final String PARCEL_CAP_MISSING = "Cap = M / M\r\n\r\n";
public static final String PARCEL_LEVEL_LINE = "LEVEL\t\tPRES\t\tHGT(AGL)\t\tTEMP\r\n____________________________________________________\r\n";
public static final String PARCEL_LEVEL_LINE_ = "LEVEL_PRES_HGT(AGL)_TEMP";
public static final String PARCEL_LCL_LINE = "LCL\t\t%5.0fmb\t\t%7.0fft\r\n";
public static final String PARCEL_LCL_LINE_ = "LCL_%5.0fmb_%7.0fft_ ";
public static final String PARCEL_LCL_MISSING = "LCL\t\tM \t\tM\r\n";
public static final String PARCEL_LCL_MISSING_ = "LCL_M_M_ ";
public static final String PARCEL_LFC_LINE = "LFC\t\t%5.0fmb\t\t%7.0fft\t%6.0fC\r\n";
public static final String PARCEL_LFC_LINE_ = "LFC_%5.0fmb_%7.0fft_%6.0fC";
public static final String PARCEL_LFC_MISSING = "LFC\t\tM \t\tM \t\t\tM\r\n";
public static final String PARCEL_LFC_MISSING_ = "LFC_M_M_M";
public static final String PARCEL_EL_LINE = "EL \t\t%5.0fmb\t\t%7.0fft\t%6.0fC\r\n";
public static final String PARCEL_EL_LINE_ = "EL_%5.0fmb_%7.0fft_%6.0fC";
public static final String PARCEL_EL_MISSING = "EL \t\tM \t\tM \t\t\tM\r\n";
public static final String PARCEL_EL_MISSING_ = "EL_M_M_M";
public static final String PARCEL_MPL_LINE = "MPL\t\t%5.0fmb\t\t%7.0fft\r\n";
public static final String PARCEL_MPL_LINE_ = "MPL_%5.0fmb_%7.0fft_ ";
public static final String PARCEL_MPL_MISSING = "MPL\t\tM \t\tM\r\n";
public static final String PARCEL_MPL_MISSING_ = "MPL_M_M_ ";
/*
* THERMODYNAMIC DATA string definitions
*/
// THERMODYNAMIC HEADER STR
public static final String THERMO_DATA_STR = "\t\t\t\tTHERMODYNAMIC DATA \r\n";
public static final String THERMO_MOISTURE_STR = "\t\t------ AVAILABLE MOISTURE ------\r\n";
public static final String THERMO_INSTABILITY_STR = "\t\t------ CONDITIONAL INSTABILITY ------\r\n";
public static final String THERMO_MISC_PARMS_STR = "\t\t------ MISC PARAMETERS ------\r\n";
// THERMODYNAMIC LINE STRING
public static final String THERMO_PWATER_LINE = "P. Water = %2.2f in\t\t";
public static final String THERMO_PWATER_MISSING = "P. Water = M \t\t";
public static final String THERMO_MEANRH_LINE = "Mean RH = %.0f %c \r\n";
public static final String THERMO_MEANRH_MISSING = "Mean RH = M\r\n";
public static final String THERMO_MEANW_LINE = "Mean W = %.1fg/Kg\t\t";
public static final String THERMO_MEANW_MISSING = "Mean W = M\t\t\t";
public static final String THERMO_MEANLRH_LINE = "Mean LRH = %.0f %c \r\n";
public static final String THERMO_MEANLRH_MISSING = "Mean LRH = M\r\n";
public static final String THERMO_TOP_LINE = "Top of Moist Lyr = %.0f mb / %.0f ft\r\n";
public static final String THERMO_TOP_MISSING = "Top of Moist Lyr = \t\tM / M\r\n\r\n";
public static final String THERMO_700500mb_LINE = "700-500mb Lapse Rate = %.0f C / %.1f C/Km\r\n";
public static final String THERMO_700500mb_MISSING = "700-500mb Lapse Rate = M / M\r\n\r\n";
public static final String THERMO_850500mb_LINE = "850-500mb Lapse Rate = %.0f C / %.1f C/Km\r\n";
public static final String THERMO_850500mb_MISSING = "850-500mb Lapse Rate = M / M\r\n\r\n";
public static final String THERMO_TOTAL_LINE = "Total Totals = %.0f\t\t";
public static final String THERMO_TOTAL_MISSING = "Total Totals = M \t\t";
public static final String THERMO_KINDEX_LINE = "K-Index = %.0f\r\n";
public static final String THERMO_KINDEX_MISSING = "K-Index = M\r\n";
public static final String THERMO_SWEAT_LINE = "SWEAT Index = %.0f\t\t";
public static final String THERMO_SWEAT_MISSING = "SWEAT Index = M\t\t";
public static final String THERMO_MAXT_LINE = "Max Temp = %.0fF\r\n";
public static final String THERMO_MAXT_MISSING = "Max Temp = M\r\n";
public static final String THERMO_THETAE_LINE = "ThetaE Diff = %.0fC\t\t";
public static final String THERMO_THETAE_MISSING = "ThetaE Diff = M \t\t";
public static final String THERMO_CONVT_LINE = "Conv Temp = %.0fF\r\n";
public static final String THERMO_CONVT_MISSING = "Conv Temp = M\r\n";
public static final String THERMO_FGZ_MISSING = "FGZ level = M\r\n";
public static final String THERMO_FGZ_LINE = "FGZ level = %.0fft\r\n";
public static final String THERMO_WBZ_MISSING = "WBZ level = M \t\t";
public static final String THERMO_WBZ_LINE = "WBZ level = %3.0fft\t";
/*
* OPC LOW LEVEL STABILITY data string
*/
public static final String OPC_LOW_LEVEL_STR = "\t\t\t OPC LOW LEVEL STABILITY \r\n";
// OPC page header string
public static final String OPC_SURFACE975_STR = " ----- SURFACE-975 hPa TEMP GRADIENT -----\r\n";
public static final String OPC_LOWEST_INV_STR = "\r\n -------- LOWEST INVERSION HEIGHT --------\r\n";
public static final String OPC_MIXING_HGT_STR = " ------------- MIXING HEIGHT -------------\r\n";
// OPC SURFACE975 line strings
public static final String OPC_LEVEL_LINE = "LEVEL\t\tPRES\t\tHEIGHT\t\tTEMP\r\n_______________________________________________\r\n";
public static final String OPC_LEVEL_LINE_ = "LEVEL_PRES_HEIGHT_TEMP";
public static final String OPC_975_LINE = "975 hPa\t\t 975 mb\t\t%4.0f m\t\t%.2f C\r\n";
public static final String OPC_975_LINE_ = "975 hPa_975 mb_%4.0f m_%.2f C";
public static final String OPC_975_LINE_MISSING = "975 hPa\t\t 975 mb\t\tM \t\t\tM \r\n";
public static final String OPC_975_LINE_MISSING_ = "975 hPa_975 mb_M_M";
public static final String OPC_SURFACE_LINE = "Surface\t\t%4.0f mb\t\t%4.0f m\t\t%.2f C\r\n\r\n";
public static final String OPC_SURFACE_LINE_ = "Surface_%4.0f mb_%4.0f m_%.2f C";
public static final String OPC_SURFACE_MISSING = "Surface\t\t M mb\t\t M m\t\t M\r\n";
public static final String OPC_SURFACE_MISSING_ = "Surface_M_M_M";
public static final String OPC_975_SURFACE_LINE = "975-Sfc Gradient = %.2f C\r\n";
public static final String OPC_975_SURFACE_MISSING = "975-Sfc Gradient = M\r\n";
// lowest inversion height line strings
public static final String OPC_BASEHEIGHT_LINE = "Base Height = %.0f m\r\n";
public static final String OPC_BASEHEIGHT_MISSING = "Base Height = M\r\n";
public static final String OPC_BASEPRESSURE_LINE = "Base Pressure = %.0f mb\r\n";
//OPC page header string
public static final String OPC_SURFACE975_STR = " ----- SURFACE-975 hPa TEMP GRADIENT -----\r\n";
public static final String OPC_LOWEST_INV_STR = "\r\n -------- LOWEST INVERSION HEIGHT --------\r\n";
public static final String OPC_MIXING_HGT_STR = " ------------- MIXING HEIGHT -------------\r\n";
//OPC SURFACE975 line strings
public static final String OPC_LEVEL_LINE = "LEVEL\t\tPRES\t\tHEIGHT\t\tTEMP\r\n_______________________________________________\r\n";
public static final String OPC_LEVEL_LINE_ = "LEVEL_PRES_HEIGHT_TEMP";
public static final String OPC_975_LINE = "975 hPa\t\t 975 mb\t\t%4.0f m\t\t%.2f C\r\n";
public static final String OPC_975_LINE_ = "975 hPa_975 mb_%4.0f m_%.2f C";
public static final String OPC_975_LINE_MISSING = "975 hPa\t\t 975 mb\t\tM \t\t\tM \r\n";
public static final String OPC_975_LINE_MISSING_ = "975 hPa_975 mb_M_M";
public static final String OPC_SURFACE_LINE = "Surface\t\t%4.0f mb\t\t%4.0f m\t\t%.2f C\r\n\r\n";
public static final String OPC_SURFACE_LINE_ = "Surface_%4.0f mb_%4.0f m_%.2f C";
public static final String OPC_SURFACE_MISSING = "Surface\t\t M mb\t\t M m\t\t M\r\n";
public static final String OPC_SURFACE_MISSING_ = "Surface_M_M_M";
public static final String OPC_975_SURFACE_LINE = "975-Sfc Gradient = %.2f C\r\n";
public static final String OPC_975_SURFACE_MISSING = "975-Sfc Gradient = M\r\n";
// lowest inversion height line strings
public static final String OPC_BASEHEIGHT_LINE = "Base Height = %.0f m\r\n";
public static final String OPC_BASEHEIGHT_MISSING = "Base Height = M\r\n";
public static final String OPC_BASEPRESSURE_LINE = "Base Pressure = %.0f mb\r\n";
public static final String OPC_BASEPRESSURE_MISSING = "Base Pressure = M\r\n";
public static final String OPC_CHANGE_IN_TEMP_LINE = "Change in Temp = %.2f C\r\n";
public static final String OPC_CHANGE_IN_TEMP_MISSING = "Change in Temp = M\r\n";
// mixing height line strings
public static final String OPC_LAYER_BASED_STR = "\t\t\t\t*** Layer Based ***\r\n";
public static final String OPC_SURFACE_BASED_STR = "\t\t\t\t*** Surface Based ***\r\n";
public static final String OPC_DRY_AD_LINE = "Dry Ad Lapse Rate _= 9.8 C/Km\r\n";
public static final String OPC_THRESH_LAPSE_LINE = "Thresh Lapse Rate _= 8.3 C/Km\r\n";
public static final String OPC_MIXINGHEIGHT_LINE = "Mixing Height _= %.0f m\r\n";
public static final String OPC_MIXINGPRESSURE_LINE ="Mixing Pressure _= %.0f mb\r\n";
public static final String OPC_TOPMIXLAYER_LINE = "Top Mix Layer Wind _= %d%c/%d kt\r\n";
public static final String OPC_MIXLAYERMAX_LINE = "Mix Layer Max Wind _= %d%c/%d kt\r\n";
public static final String OPC_MIXINGHEIGHT_MISSING="Mixing Height _= M\r\n";
public static final String OPC_MIXINGPRESSURE_MISSING = "Mixing Pressure _= M\r\n";
public static final String OPC_TOPMIXLAYER_MISSING ="Top Mix Layer Wind _= M / M\r\n";
public static final String OPC_MIXLAYERMAX_MISSING ="Mix Layer Max Wind _= M / M r\n";
public static final String OPC_LAYER_LAPSE_LINE = "Layer Lapse Rate _= %.2f C/%.1fC/Km\r\n";
public static final String OPC_LAYER_LAPSE_MISSING ="Layer Lapse Rate _= M / M\r\n";
/*
* STORM RELATIVE data string
*/
public static final String STORM_RELATIVE_STR = "\t\t\tSTORM RELATIVE \r\n";
// SR header strings
public static final String STORM_HELICITY_STR = "\t\t------ SR HELICITY ------\r\n";
public static final String STORM_WIND_STR = "\r\n \t\t------ SR WINDS ------\r\n";
//SR Helicity line strings
public static final String STORM_MOTION_LINE = "%3.0f%c / %3.0f kt ( %.0f m/s )\r\n";
public static final String STORM_MOTION_MISSING = "M / M (M)\r\n";
public static final String STORM_LAYER_POS_STR = "LAYER_POS_NEG_TOT\r\n";
public static final String STORM_SFC2KM_LINE = "Sfc - 2 km_%.0f_%4.0f_%.0f m%c/s%c\r\n";
public static final String STORM_SFC3KM_LINE = "Sfc - 3 km_%.0f_%4.0f_%.0f m%c/s%c\r\n";
public static final String STORM_LPL_LFC_LINE = "LPL - LFC_%.0f_%4.0f_%.0f m%c/s%c\r\n";
public static final String STORM_SFC3KM_MISSING = "Sfc - 3 km_M _M _M\r\n";
public static final String STORM_SFC2KM_MISSING = "Sfc - 2 km_M _M _M\r\n";
public static final String STORM_LPL_LFC_MISSING= "LPL - LFC _M _M _M\r\n";
public static final String STORM_LAYER_VECTOR_STR = "LAYER_VECTOR\r\n";
public static final String STORM_SFC2KM_VECT_LINE = "Sfc - 2 km_%3.0f / %3.0f kt (%3.0f m/s)\r\n";
public static final String STORM_SFC2KM_VECT_MISSING = "Sfc - 2 km_ M / M (M)\r\n";
public static final String STORM_4_6KM_VECT_LINE = "4 - 6 km _%3.0f / %3.0f kt (%3.0f m/s)\r\n";
public static final String STORM_4_6KM_VECT_MISSING = "4 - 6 km_ M / M (M)\r\n";
public static final String STORM_9_11KM_VECT_LINE = "9 - 11 km_%3.0f / %3.0f kt (%3.0f m/s)\r\n";
public static final String STORM_9_11KM_VECT_MISSING = "9 - 11 km_ M / M (M)\r\n";
/*
* MEAN WIND data string
*/
public static final String MEAN_WIND_STR = "\t\t\t\tMEAN WIND \r\n";
//Mean Wind line strings
public static final String MEANWIND_SFC6KM_LINE = "Sfc - 6 km_%3.0f /\t%3.0f kt\t(%.0f m/s)\r\n";
public static final String MEANWIND_LFC_EL_LINE = "LFC - EL_%3.0f /\t%3.0f kt\t(%.0f m/s)\r\n";
public static final String MEANWIND_850_200MB_LINE = "850 - 200 mb_%3.0f /\t%3.0f kt\t(%.0f m/s)\r\n";
public static final String MEANWIND_SFC6KM_MISSING = "Sfc - 6 km_M / \tM \t(M)\r\n";
public static final String MEANWIND_LFC_EL_MISSING = "LFC - EL_M / \tM \t(M)\r\n";
public static final String MEANWIND_850_200MB_MISSING = "850 - 200 mb_M / \tM \t(M)\r\n";
/*
* ENVIRONMENTAL SHEAR data string
*/
public static final String ENVIRONMENTAL_SHEAR_STR = "\t\t\tENVIRONMENTAL SHEAR \r\n";
//ENVIRONMENTAL SHEAR line strings
public static final String SHEAR_LAYER_DELTA_STR = "LAYER_DELTA V_TOT SHR\r\n";
public static final String SHEAR_LOW_3KM_LINE = "Low - 3 km_%3.0f kt (%3.0f m/s)_%.0f\r\n";
public static final String SHEAR_LOW_3KM_MISSING = "Low - 3 km_M ( M )_M\r\n";
public static final String SHEAR_SFC_2KM_LINE = "Sfc - 2 km_%3.0f kt (%3.0f m/s)_%.0f\r\n";
public static final String SHEAR_SFC_2KM_MISSING = "Sfc - 2 km_M ( M )_M\r\n";
public static final String SHEAR_SFC_6KM_LINE = "Sfc - 6 km_%3.0f kt (%3.0f m/s)_%.0f\r\n";
public static final String SHEAR_SFC_6KM_MISSING = "Sfc - 6 km_M ( M )_M\r\n";
public static final String SHEAR_SFC_12KM_LINE = "Sfc - 12 km_%3.0f kt (%3.0f m/s)_%.0f\r\n";
public static final String SHEAR_SFC_12KM_MISSING = "Sfc - 12 km_M ( M ) _M\r\n";
/*
* CONVECTIVE INITIATION data strings
*/
public static final String CONVECTIVE_INITIATION_STR = "\t\t\t\tCONVECTIVE INITIATION \r\n";
public static final String CONVECTIVE_CINH_LINE = "CINH_= %6.0f J/Kg";
public static final String CONVECTIVE_KINDEX_LINE = "K-Index_= %6.0f";
public static final String CONVECTIVE_CINH_MISSING = "CINH_= M";
public static final String CONVECTIVE_KINDEX_MISSING = "K-Index_= M";
public static final String CONVECTIVE_CAP_LINE = "Cap_= %.0fC / %.0fmb\n";
public static final String CONVECTIVE_MEANRH_LINE = "Mean RH_= %.0f %c";
public static final String CONVECTIVE_CAP_MISSING = "Cap_= M / M\r\n";
public static final String CONVECTIVE_MEANRH_MISSING = "Mean RH_= M\r\n";
public static final String CONVECTIVE_TOP_LINE = "Top of Moist Lyr = %.0f mb / %.0f ft\r\n";
public static final String CONVECTIVE_TOP_MISSING = "Top of Moist Lyr = M / M\r\n";
public static final String CONVECTIVE_LFC_LINE = "LFC Height = %.0f mb / %.0f ft\r\n";
public static final String CONVECTIVE_LFC_MISSING = "LFC Height = M / M\r\n";
public static final String OPC_CHANGE_IN_TEMP_LINE = "Change in Temp = %.2f C\r\n";
/*
* STORM TYPE data strings
*/
public static final String STORM_TYPE_STR = "\t\t\t\t STORM TYPE \r\n";
public static final String STORM_TYPE_CAPE_LINE = "CAPE _= %6.0f J/Kg\t";
public static final String STORM_TYPE_EHI_LINE = "EHI _= %6.1f \t";
public static final String STORM_TYPE_BRN_LINE = "BRN _= %6.0f \t";
public static final String STORM_TYPE_CAPE_MISSING = "CAPE _= M";
public static final String STORM_TYPE_EHI_MISSING = "EHI _= M";
public static final String STORM_TYPE_BRN_MISSING = "BRN _= M";
public static final String STORM_TYPE_EFF_LINE = "Eff. SREH _= %.0f m%c/s%c\r\n";
public static final String STORM_TYPE_EFF_MISSING = "Eff. SREH _= M\r\n";
public static final String STORM_TYPE_3KM_LINE = "3km Shear _= %.0f m/s\r\n";
public static final String STORM_TYPE_3KM_MISSING = "3km Shear _= M\r\n";
public static final String STORM_TYPE_BRNSHEAR_LINE = "BRN Shear _= %.0f m%c/s%c\r\n";
public static final String STORM_TYPE_BRNSHEAR_MISSING = "BRN Shear _= M\r\n";
/*
* SEVERE POTENTIAL data strings
*/
public static final String SEVERE_POTENTIAL_STR = "\t\t\t\tSEVERE POTENTIAL \r\n";
// SEVERE POTENTIAL HEADER STR
public static final String SEVERE_HAIL_POTENTIAL_STR = "\t\t------ HAIL POTENTIAL ------\r\n";
public static final String SEVERE_TORNADO_POTENTIAL_STR = "\t\t------ TORNADO POTENTIAL ------\r\n";
// SEVERE POTENTIAL LINE STRING
public static final String SEVERE_CAPE_LINE = "CAPE_= %5.0f J/Kg";
public static final String SEVERE_MIDRH_LINE = "Mid Lvl RH_= %5.0f %c";
public static final String SEVERE_CHI1_LINE = "CHI1_= %5.1f ";
public static final String SEVERE_CAPE_MISSING = "CAPE_= M";
public static final String SEVERE_MIDRH_MISSING = "Mid Lvl RH_= M";
public static final String SEVERE_CHI1_MISSING = "CHI1_= M";
public static final String SEVERE_WBZ_LINE = "WBZ level_= %.0fft\r\n";
public static final String SEVERE_FGZ_LINE = "FGZ level_= %.0fft\r\n";
public static final String SEVERE_CHI2_LINE ="CHI2_= %.1f\r\n";
public static final String SEVERE_WBZ_MISSING = "WBZ level_= M\r\n";
public static final String SEVERE_FGZ_MISSING = "FGZ level_= M\r\n";
public static final String SEVERE_CHI2_MISSING ="CHI2_= M\r\n";
public static final String SEVERE_ELSTORM_LINE = "EL Storm Relative Wind Speed = %.0f kt \r\n";
public static final String SEVERE_ELSTORM_MISSING = "EL Storm Relative Wind Speed = M \r\n";
public static final String SEVERE_AVGBL_LINE = "Avg BL Wetbulb Temp = %.1f %cC \r\n";
public static final String SEVERE_AVGBL_MISSING = "Avg BL Wetbulb Temp = M \r\n";
public static final String SEVERE_LOWSRWSFC_LINE = "Low SRW (Sfc - LFC) _= %.0f kt\r\n";
public static final String SEVERE_MIDSRW_LINE = "Mid SRW (LFC - LFC+4km) _= %.0f kt\r\n";
public static final String SEVERE_LOWSRWEL_LINE = "Low SRW (EL-4km - EL) _= %.0f kt\r\n";
public static final String SEVERE_LOWSRWSFC_MISSING = "Low SRW (Sfc - LFC) _= M \r\n";
public static final String SEVERE_MIDSRW_MISSING = "Mid SRW (LFC - LFC+4km) _= M \r\n";
public static final String SEVERE_LOWSRWEL_MISSING = "Low SRW (EL-4km - EL) _= M \r\n";
public static final String OPC_CHANGE_IN_TEMP_MISSING = "Change in Temp = M\r\n";
/*
* PRECIPITATION TYPE data strings
*/
public static final String PRECIPITATION_TYPE_STR = "\t\t\t\t PRECIPITATION TYPE \r\n";
public static final String PRECIPITATION_MELTING_LINE = "Melting Level = %.0f ft / %.0f mb\r\n";
public static final String PRECIPITATION_MELTING_MISSING = "Melting Level = M \r\n";
// mixing height line strings
public static final String OPC_LAYER_BASED_STR = "\t\t\t\t*** Layer Based ***\r\n";
/*
* HEAVY RAINFALL data strings
*/
public static final String HEAVY_RAINFALL_STR = "\t\t\t\t HEAVY RAINFALL \r\n";
// change Rogash QPF to Rainfall Rate (TL)
public static final String HEAVY_ROGASH_LINE = "Rogash Rainfall Rate = %.2f in/hr\r\n";
public static final String HEAVY_ROGASH_MISSING = "Rogash Rainfall Rate = M \r\n";
public static final String OPC_SURFACE_BASED_STR = "\t\t\t\t*** Surface Based ***\r\n";
// use parcel type to retrieve parcel header string for display
public static final Map<Short, String> parcelToHdrStrMap = new HashMap<Short, String>(){
private static final long serialVersionUID = 1L;
public static final String OPC_DRY_AD_LINE = "Dry Ad Lapse Rate _= 9.8 C/Km\r\n";
{
public static final String OPC_THRESH_LAPSE_LINE = "Thresh Lapse Rate _= 8.3 C/Km\r\n";
public static final String OPC_MIXINGHEIGHT_LINE = "Mixing Height _= %.0f m\r\n";
public static final String OPC_MIXINGPRESSURE_LINE = "Mixing Pressure _= %.0f mb\r\n";
public static final String OPC_TOPMIXLAYER_LINE = "Top Mix Layer Wind _= %d%c/%d kt\r\n";
public static final String OPC_MIXLAYERMAX_LINE = "Mix Layer Max Wind _= %d%c/%d kt\r\n";
public static final String OPC_MIXINGHEIGHT_MISSING = "Mixing Height _= M\r\n";
public static final String OPC_MIXINGPRESSURE_MISSING = "Mixing Pressure _= M\r\n";
public static final String OPC_TOPMIXLAYER_MISSING = "Top Mix Layer Wind _= M / M\r\n";
public static final String OPC_MIXLAYERMAX_MISSING = "Mix Layer Max Wind _= M / M r\n";
public static final String OPC_LAYER_LAPSE_LINE = "Layer Lapse Rate _= %.2f C/%.1fC/Km\r\n";
public static final String OPC_LAYER_LAPSE_MISSING = "Layer Lapse Rate _= M / M\r\n";
/*
* STORM RELATIVE data string
*/
public static final String STORM_RELATIVE_STR = "\t\t\tSTORM RELATIVE \r\n";
// SR header strings
public static final String STORM_HELICITY_STR = "\t\t------ SR HELICITY ------\r\n";
public static final String STORM_WIND_STR = "\r\n \t\t------ SR WINDS ------\r\n";
// SR Helicity line strings
public static final String STORM_MOTION_LINE = "%3.0f%c / %3.0f kt ( %.0f m/s )\r\n";
public static final String STORM_MOTION_MISSING = "M / M (M)\r\n";
public static final String STORM_LAYER_POS_STR = "LAYER_POS_NEG_TOT\r\n";
public static final String STORM_SFC2KM_LINE = "Sfc - 2 km_%.0f_%4.0f_%.0f m%c/s%c\r\n";
public static final String STORM_SFC3KM_LINE = "Sfc - 3 km_%.0f_%4.0f_%.0f m%c/s%c\r\n";
public static final String STORM_LPL_LFC_LINE = "LPL - LFC_%.0f_%4.0f_%.0f m%c/s%c\r\n";
public static final String STORM_SFC3KM_MISSING = "Sfc - 3 km_M _M _M\r\n";
public static final String STORM_SFC2KM_MISSING = "Sfc - 2 km_M _M _M\r\n";
public static final String STORM_LPL_LFC_MISSING = "LPL - LFC _M _M _M\r\n";
public static final String STORM_LAYER_VECTOR_STR = "LAYER_VECTOR\r\n";
public static final String STORM_SFC2KM_VECT_LINE = "Sfc - 2 km_%3.0f / %3.0f kt (%3.0f m/s)\r\n";
public static final String STORM_SFC2KM_VECT_MISSING = "Sfc - 2 km_ M / M (M)\r\n";
public static final String STORM_4_6KM_VECT_LINE = "4 - 6 km _%3.0f / %3.0f kt (%3.0f m/s)\r\n";
public static final String STORM_4_6KM_VECT_MISSING = "4 - 6 km_ M / M (M)\r\n";
public static final String STORM_9_11KM_VECT_LINE = "9 - 11 km_%3.0f / %3.0f kt (%3.0f m/s)\r\n";
public static final String STORM_9_11KM_VECT_MISSING = "9 - 11 km_ M / M (M)\r\n";
/*
* MEAN WIND data string
*/
public static final String MEAN_WIND_STR = "\t\t\t\tMEAN WIND \r\n";
// Mean Wind line strings
public static final String MEANWIND_SFC6KM_LINE = "Sfc - 6 km_%3.0f /\t%3.0f kt\t(%.0f m/s)\r\n";
public static final String MEANWIND_LFC_EL_LINE = "LFC - EL_%3.0f /\t%3.0f kt\t(%.0f m/s)\r\n";
public static final String MEANWIND_850_200MB_LINE = "850 - 200 mb_%3.0f /\t%3.0f kt\t(%.0f m/s)\r\n";
public static final String MEANWIND_SFC6KM_MISSING = "Sfc - 6 km_M / \tM \t(M)\r\n";
public static final String MEANWIND_LFC_EL_MISSING = "LFC - EL_M / \tM \t(M)\r\n";
public static final String MEANWIND_850_200MB_MISSING = "850 - 200 mb_M / \tM \t(M)\r\n";
/*
* ENVIRONMENTAL SHEAR data string
*/
public static final String ENVIRONMENTAL_SHEAR_STR = "\t\t\tENVIRONMENTAL SHEAR \r\n";
// ENVIRONMENTAL SHEAR line strings
public static final String SHEAR_LAYER_DELTA_STR = "LAYER_DELTA V_TOT SHR\r\n";
public static final String SHEAR_LOW_3KM_LINE = "Low - 3 km_%3.0f kt (%3.0f m/s)_%.0f\r\n";
public static final String SHEAR_LOW_3KM_MISSING = "Low - 3 km_M ( M )_M\r\n";
public static final String SHEAR_SFC_2KM_LINE = "Sfc - 2 km_%3.0f kt (%3.0f m/s)_%.0f\r\n";
public static final String SHEAR_SFC_2KM_MISSING = "Sfc - 2 km_M ( M )_M\r\n";
public static final String SHEAR_SFC_6KM_LINE = "Sfc - 6 km_%3.0f kt (%3.0f m/s)_%.0f\r\n";
public static final String SHEAR_SFC_6KM_MISSING = "Sfc - 6 km_M ( M )_M\r\n";
public static final String SHEAR_SFC_12KM_LINE = "Sfc - 12 km_%3.0f kt (%3.0f m/s)_%.0f\r\n";
public static final String SHEAR_SFC_12KM_MISSING = "Sfc - 12 km_M ( M ) _M\r\n";
/*
* CONVECTIVE INITIATION data strings
*/
public static final String CONVECTIVE_INITIATION_STR = "\t\t\t\tCONVECTIVE INITIATION \r\n";
public static final String CONVECTIVE_CINH_LINE = "CINH_= %6.0f J/Kg";
public static final String CONVECTIVE_KINDEX_LINE = "K-Index_= %6.0f";
public static final String CONVECTIVE_CINH_MISSING = "CINH_= M";
public static final String CONVECTIVE_KINDEX_MISSING = "K-Index_= M";
public static final String CONVECTIVE_CAP_LINE = "Cap_= %.0fC / %.0fmb\n";
public static final String CONVECTIVE_MEANRH_LINE = "Mean RH_= %.0f %c";
public static final String CONVECTIVE_CAP_MISSING = "Cap_= M / M\r\n";
public static final String CONVECTIVE_MEANRH_MISSING = "Mean RH_= M\r\n";
public static final String CONVECTIVE_TOP_LINE = "Top of Moist Lyr = %.0f mb / %.0f ft\r\n";
public static final String CONVECTIVE_TOP_MISSING = "Top of Moist Lyr = M / M\r\n";
public static final String CONVECTIVE_LFC_LINE = "LFC Height = %.0f mb / %.0f ft\r\n";
public static final String CONVECTIVE_LFC_MISSING = "LFC Height = M / M\r\n";
/*
* STORM TYPE data strings
*/
public static final String STORM_TYPE_STR = "\t\t\t\t STORM TYPE \r\n";
public static final String STORM_TYPE_CAPE_LINE = "CAPE _= %6.0f J/Kg\t";
public static final String STORM_TYPE_EHI_LINE = "EHI _= %6.1f \t";
public static final String STORM_TYPE_BRN_LINE = "BRN _= %6.0f \t";
public static final String STORM_TYPE_CAPE_MISSING = "CAPE _= M";
public static final String STORM_TYPE_EHI_MISSING = "EHI _= M";
public static final String STORM_TYPE_BRN_MISSING = "BRN _= M";
public static final String STORM_TYPE_EFF_LINE = "Eff. SREH _= %.0f m%c/s%c\r\n";
public static final String STORM_TYPE_EFF_MISSING = "Eff. SREH _= M\r\n";
public static final String STORM_TYPE_3KM_LINE = "3km Shear _= %.0f m/s\r\n";
public static final String STORM_TYPE_3KM_MISSING = "3km Shear _= M\r\n";
public static final String STORM_TYPE_BRNSHEAR_LINE = "BRN Shear _= %.0f m%c/s%c\r\n";
public static final String STORM_TYPE_BRNSHEAR_MISSING = "BRN Shear _= M\r\n";
/*
* SEVERE POTENTIAL data strings
*/
public static final String SEVERE_POTENTIAL_STR = "\t\t\t\tSEVERE POTENTIAL \r\n";
// SEVERE POTENTIAL HEADER STR
public static final String SEVERE_HAIL_POTENTIAL_STR = "\t\t------ HAIL POTENTIAL ------\r\n";
public static final String SEVERE_TORNADO_POTENTIAL_STR = "\t\t------ TORNADO POTENTIAL ------\r\n";
// SEVERE POTENTIAL LINE STRING
public static final String SEVERE_CAPE_LINE = "CAPE_= %5.0f J/Kg";
public static final String SEVERE_MIDRH_LINE = "Mid Lvl RH_= %5.0f %c";
public static final String SEVERE_CHI1_LINE = "CHI1_= %5.1f ";
public static final String SEVERE_CAPE_MISSING = "CAPE_= M";
public static final String SEVERE_MIDRH_MISSING = "Mid Lvl RH_= M";
public static final String SEVERE_CHI1_MISSING = "CHI1_= M";
public static final String SEVERE_WBZ_LINE = "WBZ level_= %.0fft\r\n";
public static final String SEVERE_FGZ_LINE = "FGZ level_= %.0fft\r\n";
public static final String SEVERE_CHI2_LINE = "CHI2_= %.1f\r\n";
public static final String SEVERE_WBZ_MISSING = "WBZ level_= M\r\n";
public static final String SEVERE_FGZ_MISSING = "FGZ level_= M\r\n";
public static final String SEVERE_CHI2_MISSING = "CHI2_= M\r\n";
public static final String SEVERE_ELSTORM_LINE = "EL Storm Relative Wind Speed = %.0f kt \r\n";
public static final String SEVERE_ELSTORM_MISSING = "EL Storm Relative Wind Speed = M \r\n";
public static final String SEVERE_AVGBL_LINE = "Avg BL Wetbulb Temp = %.1f %cC \r\n";
public static final String SEVERE_AVGBL_MISSING = "Avg BL Wetbulb Temp = M \r\n";
public static final String SEVERE_LOWSRWSFC_LINE = "Low SRW (Sfc - LFC) _= %.0f kt\r\n";
public static final String SEVERE_MIDSRW_LINE = "Mid SRW (LFC - LFC+4km) _= %.0f kt\r\n";
public static final String SEVERE_LOWSRWEL_LINE = "Low SRW (EL-4km - EL) _= %.0f kt\r\n";
public static final String SEVERE_LOWSRWSFC_MISSING = "Low SRW (Sfc - LFC) _= M \r\n";
public static final String SEVERE_MIDSRW_MISSING = "Mid SRW (LFC - LFC+4km) _= M \r\n";
public static final String SEVERE_LOWSRWEL_MISSING = "Low SRW (EL-4km - EL) _= M \r\n";
/*
* PRECIPITATION TYPE data strings
*/
public static final String PRECIPITATION_TYPE_STR = "\t\t\t\t PRECIPITATION TYPE \r\n";
public static final String PRECIPITATION_MELTING_LINE = "Melting Level = %.0f ft / %.0f mb\r\n";
public static final String PRECIPITATION_MELTING_MISSING = "Melting Level = M \r\n";
/*
* HEAVY RAINFALL data strings
*/
public static final String HEAVY_RAINFALL_STR = "\t\t\t\t HEAVY RAINFALL \r\n";
// change Rogash QPF to Rainfall Rate (TL)
public static final String HEAVY_ROGASH_LINE = "Rogash Rainfall Rate = %.2f in/hr\r\n";
public static final String HEAVY_ROGASH_MISSING = "Rogash Rainfall Rate = M \r\n";
// use parcel type to retrieve parcel header string for display
public static final Map<Short, String> parcelToHdrStrMap = new HashMap<Short, String>() {
private static final long serialVersionUID = 1L;
{
put(NsharpNativeConstants.PARCELTYPE_OBS_SFC, PARCEL_OBS_SFC_STR);
put(NsharpNativeConstants.PARCELTYPE_FCST_SFC, PARCEL_FORECAST_SFC_STR);
put(NsharpNativeConstants.PARCELTYPE_MEAN_MIXING, PARCEL_MEAN_MIXING_STR);
put(NsharpNativeConstants.PARCELTYPE_MOST_UNSTABLE, PARCEL_MOST_UNSTABLE_STR);
put(NsharpNativeConstants.PARCELTYPE_USER_DEFINED, PARCEL_USR_DEFINED_STR);
put(NsharpNativeConstants.PARCELTYPE_FCST_SFC,
PARCEL_FORECAST_SFC_STR);
put(NsharpNativeConstants.PARCELTYPE_MEAN_MIXING,
PARCEL_MEAN_MIXING_STR);
put(NsharpNativeConstants.PARCELTYPE_MOST_UNSTABLE,
PARCEL_MOST_UNSTABLE_STR);
put(NsharpNativeConstants.PARCELTYPE_USER_DEFINED,
PARCEL_USR_DEFINED_STR);
put(NsharpNativeConstants.PARCELTYPE_EFF, PARCEL_MEAN_EFF_STR);
}
};
public static final Map<Short, String> parcelToTypeStrMap = new HashMap<Short, String>(){
private static final long serialVersionUID = 1L;
{
public static final Map<Short, String> parcelToTypeStrMap = new HashMap<Short, String>() {
private static final long serialVersionUID = 1L;
{
put(NsharpNativeConstants.PARCELTYPE_OBS_SFC, PAGE1TEXT1_SB_STR);
put(NsharpNativeConstants.PARCELTYPE_FCST_SFC, PAGE1TEXT1_FCST_STR);
put(NsharpNativeConstants.PARCELTYPE_MEAN_MIXING, PAGE1TEXT1_ML_STR);
put(NsharpNativeConstants.PARCELTYPE_MOST_UNSTABLE, PAGE1TEXT1_MU_STR);
put(NsharpNativeConstants.PARCELTYPE_USER_DEFINED, PAGE1TEXT1_USER_STR);
put(NsharpNativeConstants.PARCELTYPE_EFF,PAGE1TEXT1_EFF_STR );
put(NsharpNativeConstants.PARCELTYPE_MOST_UNSTABLE,
PAGE1TEXT1_MU_STR);
put(NsharpNativeConstants.PARCELTYPE_USER_DEFINED,
PAGE1TEXT1_USER_STR);
put(NsharpNativeConstants.PARCELTYPE_EFF, PAGE1TEXT1_EFF_STR);
}
};
public static final Map<Short, Float> parcelToLayerMap = new HashMap<Short, Float>(){
private static final long serialVersionUID = 1L;
{
public static final Map<Short, Float> parcelToLayerMap = new HashMap<Short, Float>() {
private static final long serialVersionUID = 1L;
{
put(NsharpNativeConstants.PARCELTYPE_OBS_SFC, OBS_LAYER);
put(NsharpNativeConstants.PARCELTYPE_FCST_SFC, FCST_LAYER);
put(NsharpNativeConstants.PARCELTYPE_MEAN_MIXING, MML_LAYER);
@ -384,26 +607,48 @@ public static final String OPC_MIXINGPRESSURE_MISSING = "Mixing Pressure
put(NsharpNativeConstants.PARCELTYPE_EFF, EFF_LAYER);
}
};
public static final String TEMP_TRACE = "Temperature Trace";
public static final String DEWP_TRACE = "Dewpoint Trace";
public static final String PARCEL_VT_TRACE= "Parcel Tv Trace";
public static final String PARCEL_T_TRACE= "Parcel Trace";
public static final String DCAPE_TRACE = "DCAPE Trace";
public static final String VTEMP_TRACE = "Virtual Temperature Trace";
public static final String WETBULB_TRACE= "WetbulbTrace";
public static final String MIXING_RATIO= "Mixing Ratio";
public static final String DRY_ADIABAT= "Dry Adiabat";
public static final String MOIST_ADIABAT= "Moist Adiabat";
public static final String OMEGA = "Omega";
public static final String MEAN_WIND_VECTOR = "Mean Wind Vector";
public static final String STORM_MOTION_VECTOR_3075 = "30/75 Storm Motion Vector";
public static final String STORM_MOTION_VECTOR_1585 = "15/85 Storm Motion Vector";
public static final String STORM_MOTION_VECTOR_BUNKERS_R = "Bunkers R Storm Motion Vector";
public static final String STORM_MOTION_VECTOR_BUNKERS_L = "Bunkers L Storm Motion Vector";
public static final String CORFIDI_VECTORS = "Corfidi Vectors";
public static final String HODOGRAPH = "Hodograph Trace";
public static final String EFFECTIVE_LAYER = "Effective Layer";
public static final String CLOUD = "Cloud";
public static final String WINDBARB="Wind Barb";
public static final float ENTRAIN_DEFAULT = 0.0f;
public static final String TEMP_TRACE = "Temperature Trace";
public static final String DEWP_TRACE = "Dewpoint Trace";
public static final String PARCEL_VT_TRACE = "Parcel Tv Trace";
public static final String PARCEL_T_TRACE = "Parcel Trace";
public static final String DCAPE_TRACE = "DCAPE Trace";
public static final String VTEMP_TRACE = "Virtual Temperature Trace";
public static final String WETBULB_TRACE = "WetbulbTrace";
public static final String MIXING_RATIO = "Mixing Ratio";
public static final String DRY_ADIABAT = "Dry Adiabat";
public static final String MOIST_ADIABAT = "Moist Adiabat";
public static final String OMEGA = "Omega";
public static final String MEAN_WIND_VECTOR = "Mean Wind Vector";
public static final String STORM_MOTION_VECTOR_3075 = "30/75 Storm Motion Vector";
public static final String STORM_MOTION_VECTOR_1585 = "15/85 Storm Motion Vector";
public static final String STORM_MOTION_VECTOR_BUNKERS_R = "Bunkers R Storm Motion Vector";
public static final String STORM_MOTION_VECTOR_BUNKERS_L = "Bunkers L Storm Motion Vector";
public static final String CORFIDI_VECTORS = "Corfidi Vectors";
public static final String HODOGRAPH = "Hodograph Trace";
public static final String EFFECTIVE_LAYER = "Effective Layer";
public static final String CLOUD = "Cloud";
public static final String WINDBARB = "Wind Barb";
public static final float ENTRAIN_DEFAULT = 0.0f;
}

View file

@ -25,308 +25,416 @@ import org.eclipse.swt.widgets.Text;
import com.raytheon.uf.viz.core.exception.VizException;
public class NsharpDataPageConfigDialog extends Dialog {
private MessageBox mb;
private NsharpConfigStore configStore=null;
private NsharpConfigManager mgr;
private NsharpDataPageProperty dpp;
private NsharpDataPageProperty editingDpp;
private static NsharpDataPageConfigDialog instance=null;
//this array is used to store page display "order"
private int[] pageOrderNumberArray = new int[NsharpConstants.PAGE_MAX_NUMBER+1];//element 0 is dummy one
private int[] editingOrderNumberArray = new int[NsharpConstants.PAGE_MAX_NUMBER+1];//element 0 is dummy one
private int lblWidth = 200;
private int lblHeight = 20;
private int textWidth = 80;
private int numberPagePerDisplay = 2;
private Label curLbl;
private Text newText;
private Text[] newOrderTextArray= new Text[NsharpConstants.PAGE_MAX_NUMBER+1];//element 0 is dummy one
private Label[] curOrderLblArray = new Label[NsharpConstants.PAGE_MAX_NUMBER+1];//element 0 is dummy one
private Label[] pageNameLblArray = new Label[NsharpConstants.PAGE_MAX_NUMBER+1];//element 0 is dummy one
public static NsharpDataPageConfigDialog getInstance(Shell parentShell) {
if(instance == null)
instance = new NsharpDataPageConfigDialog(parentShell);
return instance;
}
protected NsharpDataPageConfigDialog(Shell parentShell) {
super(parentShell);
instance = this;
mgr =NsharpConfigManager.getInstance();
configStore = mgr.retrieveNsharpConfigStoreFromFs();
dpp = configStore.getDataPageProperty();
pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY1 ] = dpp.getSummary1Page();
pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY2 ] = dpp.getSummary2Page();
pageOrderNumberArray[NsharpConstants.PAGE_PARCEL_DATA ] = dpp.getParcelDataPage();
pageOrderNumberArray[NsharpConstants.PAGE_THERMODYNAMIC_DATA ] = dpp.getThermodynamicDataPage();
pageOrderNumberArray[NsharpConstants.PAGE_OPC_DATA ] = dpp.getOpcDataPage();
pageOrderNumberArray[NsharpConstants.PAGE_MIXING_HEIGHT] = dpp.getMixingHeightPage();
pageOrderNumberArray[NsharpConstants.PAGE_STORM_RELATIVE ] = dpp.getStormRelativePage();
pageOrderNumberArray[NsharpConstants.PAGE_MEAN_WIND ] = dpp.getMeanWindPage();
pageOrderNumberArray[NsharpConstants.PAGE_CONVECTIVE_INITIATION ] = dpp.getConvectiveInitiationPage();
pageOrderNumberArray[NsharpConstants.PAGE_SEVERE_POTENTIAL ] = dpp.getSeverePotentialPage();
editingOrderNumberArray = pageOrderNumberArray.clone();
numberPagePerDisplay = dpp.getNumberPagePerDisplay();
mb = new MessageBox(parentShell, SWT.ICON_WARNING
| SWT.OK );
}
/*
private MessageBox mb;
private NsharpConfigStore configStore = null;
private NsharpConfigManager mgr;
private NsharpDataPageProperty dpp;
private NsharpDataPageProperty editingDpp;
private String paneConfigurationName; // d2dlite
private Group btnGp;
private static NsharpDataPageConfigDialog instance = null;
// this array is used to store page display "order"
private int[] pageOrderNumberArray = new int[NsharpConstants.PAGE_MAX_NUMBER + 1];// element
// 0
// is
// dummy
// one
private int[] editingOrderNumberArray = new int[NsharpConstants.PAGE_MAX_NUMBER + 1];// element
// 0
// is
// dummy
// one
private int lblWidth = 200;
private int lblHeight = 20;
private int textWidth = 80;
private int numberPagePerDisplay = 2;
private Label curLbl;
private Text newText;
private Text[] newOrderTextArray = new Text[NsharpConstants.PAGE_MAX_NUMBER + 1];// element
// 0
// is
// dummy
// one
private Label[] curOrderLblArray = new Label[NsharpConstants.PAGE_MAX_NUMBER + 1];// element
// 0
// is
// dummy
// one
private Label[] pageNameLblArray = new Label[NsharpConstants.PAGE_MAX_NUMBER + 1];// element
// 0
// is
// dummy
// one
public static NsharpDataPageConfigDialog getInstance(Shell parentShell) {
if (instance == null)
instance = new NsharpDataPageConfigDialog(parentShell);
return instance;
}
protected NsharpDataPageConfigDialog(Shell parentShell) {
super(parentShell);
instance = this;
mgr = NsharpConfigManager.getInstance();
configStore = mgr.retrieveNsharpConfigStoreFromFs();
dpp = configStore.getDataPageProperty();
paneConfigurationName = configStore.getGraphProperty()
.getPaneConfigurationName();
pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY1] = dpp
.getSummary1Page();
pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY2] = dpp
.getSummary2Page();
pageOrderNumberArray[NsharpConstants.PAGE_PARCEL_DATA] = dpp
.getParcelDataPage();
pageOrderNumberArray[NsharpConstants.PAGE_THERMODYNAMIC_DATA] = dpp
.getThermodynamicDataPage();
pageOrderNumberArray[NsharpConstants.PAGE_OPC_DATA] = dpp
.getOpcDataPage();
pageOrderNumberArray[NsharpConstants.PAGE_MIXING_HEIGHT] = dpp
.getMixingHeightPage();
pageOrderNumberArray[NsharpConstants.PAGE_STORM_RELATIVE] = dpp
.getStormRelativePage();
pageOrderNumberArray[NsharpConstants.PAGE_MEAN_WIND] = dpp
.getMeanWindPage();
pageOrderNumberArray[NsharpConstants.PAGE_CONVECTIVE_INITIATION] = dpp
.getConvectiveInitiationPage();
pageOrderNumberArray[NsharpConstants.PAGE_SEVERE_POTENTIAL] = dpp
.getSeverePotentialPage();
pageOrderNumberArray[NsharpConstants.PAGE_D2DLITE] = dpp
.getD2dLitePage(); // d2dlite
pageOrderNumberArray[NsharpConstants.PAGE_FUTURE] = dpp.getFuturePage(); // d2dlite
editingOrderNumberArray = pageOrderNumberArray.clone();
numberPagePerDisplay = dpp.getNumberPagePerDisplay();
mb = new MessageBox(parentShell, SWT.ICON_WARNING | SWT.OK);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell ) {
super.configureShell( shell );
shell.setText( "Data Page Display Configuration" );
}
@Override
public int open( ) {
if ( this.getShell() == null ){
this.create();
}
this.getShell().setLocation(this.getShell().getParent().getLocation().x+1100,
this.getShell().getParent().getLocation().y+200);
return super.open();
}
@Override
public void createButtonsForButtonBar(Composite parent) {
// create OK button but using Apply label for applying user entered data
//Chin note: when "apply" button is selected or Return key is entered,
// okPressed() will be called. So, handle event at one place, ie.e at okPressed().
createButton(parent, IDialogConstants.OK_ID,
"Apply",
true);
Button saveBtn = createButton(parent, IDialogConstants.INTERNAL_ID,
"Save",false);
saveBtn.addListener( SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
//System.out.println("save listener is called, also apply changes");
if(sanityCheck()== false){
System.out.println("sanity check failed");
return;
}
applyChange();
dpp.setSummary1Page(pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY1 ]);
dpp.setSummary2Page(pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY2 ]);
dpp.setParcelDataPage(pageOrderNumberArray[NsharpConstants.PAGE_PARCEL_DATA ]);
dpp.setThermodynamicDataPage(pageOrderNumberArray[NsharpConstants.PAGE_THERMODYNAMIC_DATA ] );
dpp.setOpcDataPage(pageOrderNumberArray[NsharpConstants.PAGE_OPC_DATA ]);
dpp.setMixingHeightPage(pageOrderNumberArray[NsharpConstants.PAGE_MIXING_HEIGHT]);
dpp.setStormRelativePage(pageOrderNumberArray[NsharpConstants.PAGE_STORM_RELATIVE ] );
dpp.setMeanWindPage(pageOrderNumberArray[NsharpConstants.PAGE_MEAN_WIND ] );
dpp.setConvectiveInitiationPage(pageOrderNumberArray[NsharpConstants.PAGE_CONVECTIVE_INITIATION ] );
dpp.setSeverePotentialPage(pageOrderNumberArray[NsharpConstants.PAGE_SEVERE_POTENTIAL ] );
dpp.setNumberPagePerDisplay(numberPagePerDisplay);
try {
//save to xml
mgr.saveConfigStoreToFs(configStore);
} catch (VizException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} );
* @see
* org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets
* .Shell)
*/
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText("Data Page Display Configuration");
Button canBtn = createButton(parent, IDialogConstants.CLOSE_ID,
IDialogConstants.CLOSE_LABEL, false);
canBtn.addListener( SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
//System.out.println("close listener is called");
close();
}
} );
}
/*
* To make sure user does not configure same page order number for different page.
*/
private boolean sanityCheck(){
for(int i=1; i <= NsharpConstants.PAGE_MAX_NUMBER; i++){
String textStr = newOrderTextArray[i ].getText();
if((textStr != null) && !(textStr.isEmpty())){
if(!textStr.contains("-") || textStr.length() > 1){
int pnum = Integer.decode(textStr);
if(pnum >=1 && pnum <= NsharpConstants.PAGE_MAX_NUMBER)
editingOrderNumberArray[i]= pnum;
else{
System.out.println("wrong order ="+pnum);
mb.setMessage( "Wrong Configuration! Order number should be within [1-10]");
mb.open();
return false;
}
}
}
}
for(int i=1; i<= NsharpConstants.PAGE_MAX_NUMBER; i++){
for(int j=1; j< NsharpConstants.PAGE_MAX_NUMBER; j++){
if((i!=j) && editingOrderNumberArray[i]==editingOrderNumberArray[j]){
mb.setMessage( "Wrong Configuration! Multiple pages with same order.");
mb.open();
return false;
}
}
}
return true;
}
private void applyChange(){
pageOrderNumberArray = editingOrderNumberArray.clone();
for(int i=1; i <= NsharpConstants.PAGE_MAX_NUMBER; i++){
curOrderLblArray[i].setText(Integer.toString(pageOrderNumberArray[i]));
}
NsharpEditor editor = NsharpEditor.getActiveNsharpEditor();
if (editor != null) {
NsharpResourceHandler rsc = editor.getRscHandler();
editingDpp = new NsharpDataPageProperty();
editingDpp.setSummary1Page(pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY1 ]);
editingDpp.setSummary2Page(pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY2 ]);
editingDpp.setParcelDataPage(pageOrderNumberArray[NsharpConstants.PAGE_PARCEL_DATA ]);
editingDpp.setThermodynamicDataPage(pageOrderNumberArray[NsharpConstants.PAGE_THERMODYNAMIC_DATA ] );
editingDpp.setOpcDataPage(pageOrderNumberArray[NsharpConstants.PAGE_OPC_DATA ]);
editingDpp.setMixingHeightPage(pageOrderNumberArray[NsharpConstants.PAGE_MIXING_HEIGHT]);
editingDpp.setStormRelativePage(pageOrderNumberArray[NsharpConstants.PAGE_STORM_RELATIVE ] );
editingDpp.setMeanWindPage(pageOrderNumberArray[NsharpConstants.PAGE_MEAN_WIND ] );
editingDpp.setConvectiveInitiationPage(pageOrderNumberArray[NsharpConstants.PAGE_CONVECTIVE_INITIATION ] );
editingDpp.setSeverePotentialPage(pageOrderNumberArray[NsharpConstants.PAGE_SEVERE_POTENTIAL ] );
editingDpp.setNumberPagePerDisplay(numberPagePerDisplay);
rsc.setDataPageProperty(editingDpp);
editor.refresh();
}
@Override
public int open() {
if (this.getShell() == null) {
this.create();
}
}
/*private void setDisplay(){
int pageIndex = 0;
for(int orderNum=1; orderNum <= NsharpConstants.PAGE_MAX_NUMBER; orderNum++){
for(int j=1; j <= NsharpConstants.PAGE_MAX_NUMBER; j++){
//find the page with order number equal to orderNum
if(orderNum == pageOrderNumberArray[j]){
pageIndex = j;
break;
}
}
curOrderLblArray[orderNum].setText(Integer.toString(pageOrderNumberArray[pageIndex]));
newOrderTextArray[orderNum].setText(Integer.toString(pageOrderNumberArray[pageIndex]));
pageNameLblArray[orderNum].setText(NsharpConstants.PAGE_NAME_ARRAY[pageIndex]);
}
}*/
@Override
public void okPressed() {
//"Enter" key is pressed, or "Apply" button is pressed.
//Chin: handle user entered configuration, sanity checking and apply its changes.
//System.out.println("CR is pressed");
setReturnCode(OK);
if(sanityCheck()== false){
System.out.println("sanity check failed");
return;
}
applyChange();
}
@Override
protected Control createDialogArea(Composite parent) {
Composite top;
top = (Composite) super.createDialogArea(parent);
// Create the main layout for the shell.
GridLayout mainLayout = new GridLayout(1, false);
mainLayout.marginHeight = 3;
mainLayout.marginWidth = 3;
top.setLayout(mainLayout);
Group btnGp = new Group(top, SWT.SHADOW_ETCHED_IN);
btnGp.setText("number of page per display");
//.setFont(newFont);
Button oneBtn = new Button(btnGp, SWT.RADIO | SWT.BORDER);
oneBtn.setText("1");
oneBtn.setEnabled( true );
oneBtn.setBounds(btnGp.getBounds().x+ NsharpConstants.btnGapX, btnGp.getBounds().y + NsharpConstants.labelGap, NsharpConstants.btnWidth,NsharpConstants.btnHeight);
//oneBtn.setFont(newFont);
oneBtn.addListener( SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
numberPagePerDisplay=1;
//System.out.println("new obvSnd dialog uair btn");
}
} );
Button twoBtn = new Button(btnGp, SWT.RADIO | SWT.BORDER);
twoBtn.setText("2");
twoBtn.setEnabled( true );
twoBtn.setBounds(btnGp.getBounds().x+ NsharpConstants.btnGapX, oneBtn.getBounds().y + oneBtn.getBounds().height+ NsharpConstants.btnGapY, NsharpConstants.btnWidth,NsharpConstants.btnHeight);
//twoBtn.setFont(newFont);
twoBtn.addListener( SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
numberPagePerDisplay=2;
}
} );
if(numberPagePerDisplay==1)
oneBtn.setSelection(true);
else
twoBtn.setSelection(true);
Group configGp = new Group(top, SWT.SHADOW_ETCHED_IN | SWT.NO_RADIO_GROUP);
Label nameLbl = new Label(configGp, SWT.BORDER );
nameLbl.setText(" Page Name");
nameLbl.setBounds(configGp.getBounds().x, configGp.getBounds().y, lblWidth,lblHeight);
Label curOrderLbl = new Label(configGp, SWT.BORDER );
curOrderLbl.setText("Current");
curOrderLbl.setBounds(nameLbl.getBounds().x+nameLbl.getBounds().width, nameLbl.getBounds().y,textWidth,lblHeight);
Label newOrderLbl =new Label(configGp, SWT.BORDER );
//newOrderLbl.setText(Integer.toString(summary1Page));
newOrderLbl.setBounds(curOrderLbl.getBounds().x+curOrderLbl.getBounds().width, nameLbl.getBounds().y,textWidth,lblHeight);
newOrderLbl.setText("New Order");
Label prevLbl = nameLbl;
Label pageLbl;
for(int i=1; i <= NsharpConstants.PAGE_MAX_NUMBER; i++){
pageLbl = pageNameLblArray[i] = new Label(configGp, SWT.BORDER );
pageLbl.setText(NsharpConstants.PAGE_NAME_ARRAY[i]);
pageLbl.setBounds(configGp.getBounds().x, prevLbl.getBounds().y+lblHeight, lblWidth,lblHeight);
curLbl = curOrderLblArray[i] =new Label(configGp, SWT.BORDER );
curLbl.setText(Integer.toString(pageOrderNumberArray[i]));
curLbl.setBounds(pageLbl.getBounds().x+pageLbl.getBounds().width, pageLbl.getBounds().y,textWidth,lblHeight);
newText = newOrderTextArray[i] = new Text(configGp, SWT.BORDER | SWT.SINGLE);
newText.setBounds(curLbl.getBounds().x+curLbl.getBounds().width, pageLbl.getBounds().y,textWidth,lblHeight);
newText.setEditable(true);
newText.setText(Integer.toString(pageOrderNumberArray[i]));
//to make sure user enter digits only
newText.addListener (SWT.Verify, new EditListener (newText) );
prevLbl = pageLbl;
}
return top;
}
public class EditListener implements Listener {
Text newOrderText;
public void handleEvent (Event e) {
String string = e.text;
char [] chars = new char [string.length ()];
string.getChars (0, chars.length, chars, 0);
//System.out.println("entered s="+ string);
//Chin note: when "Delete", "Backspace" entered, this handler will be called, but
// its chars.length = 0
if(chars.length == 1 && newOrderText!=null){
if(chars [0] == '-' ){
//if "-" is not first char
String textStr = newOrderText.getText();
if((textStr != null) && (textStr.length() >= 1) && (textStr.contains("-"))){
e.doit = false;
return;
}
}else if (!('0' <= chars [0] && chars [0] <= '9')) {
e.doit = false;
return;
}
this.getShell().setLocation(
this.getShell().getParent().getLocation().x + 1100,
this.getShell().getParent().getLocation().y + 200);
mgr = NsharpConfigManager.getInstance();
configStore = mgr.retrieveNsharpConfigStoreFromFs();
dpp = configStore.getDataPageProperty();
paneConfigurationName = configStore.getGraphProperty()
.getPaneConfigurationName();
if (paneConfigurationName.equals(NsharpConstants.PANE_LITE_D2D_CFG_STR)) // d2dlite
btnGp.setVisible(false);
else
btnGp.setVisible(true);
return super.open();
}
}
}
@Override
public void createButtonsForButtonBar(Composite parent) {
// create OK button but using Apply label for applying user entered data
// Chin note: when "apply" button is selected or Return key is entered,
// okPressed() will be called. So, handle event at one place, ie.e at
// okPressed().
createButton(parent, IDialogConstants.OK_ID, "Apply", true);
Button saveBtn = createButton(parent, IDialogConstants.INTERNAL_ID,
"Save", false);
saveBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
// System.out.println("save listener is called, also apply changes");
if (sanityCheck() == false) {
System.out.println("sanity check failed");
return;
}
applyChange();
dpp.setSummary1Page(pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY1]);
dpp.setSummary2Page(pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY2]);
dpp.setParcelDataPage(pageOrderNumberArray[NsharpConstants.PAGE_PARCEL_DATA]);
dpp.setThermodynamicDataPage(pageOrderNumberArray[NsharpConstants.PAGE_THERMODYNAMIC_DATA]);
dpp.setOpcDataPage(pageOrderNumberArray[NsharpConstants.PAGE_OPC_DATA]);
dpp.setMixingHeightPage(pageOrderNumberArray[NsharpConstants.PAGE_MIXING_HEIGHT]);
dpp.setStormRelativePage(pageOrderNumberArray[NsharpConstants.PAGE_STORM_RELATIVE]);
dpp.setMeanWindPage(pageOrderNumberArray[NsharpConstants.PAGE_MEAN_WIND]);
dpp.setConvectiveInitiationPage(pageOrderNumberArray[NsharpConstants.PAGE_CONVECTIVE_INITIATION]);
dpp.setSeverePotentialPage(pageOrderNumberArray[NsharpConstants.PAGE_SEVERE_POTENTIAL]);
dpp.setD2dLitePage(pageOrderNumberArray[NsharpConstants.PAGE_D2DLITE]);// d2dlite
dpp.setFuturePage(pageOrderNumberArray[NsharpConstants.PAGE_FUTURE]);// d2dlite
dpp.setNumberPagePerDisplay(numberPagePerDisplay);
try {
// save to xml
mgr.saveConfigStoreToFs(configStore);
} catch (VizException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Button canBtn = createButton(parent, IDialogConstants.CLOSE_ID,
IDialogConstants.CLOSE_LABEL, false);
canBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
// System.out.println("close listener is called");
close();
}
});
}
/*
* To make sure user does not configure same page order number for different
* page.
*/
private boolean sanityCheck() {
for (int i = 1; i <= NsharpConstants.PAGE_MAX_NUMBER; i++) {
String textStr = newOrderTextArray[i].getText();
if ((textStr != null) && !(textStr.isEmpty())) {
if (!textStr.contains("-") || textStr.length() > 1) {
int pnum = Integer.decode(textStr);
if (pnum >= 1 && pnum <= NsharpConstants.PAGE_MAX_NUMBER)
editingOrderNumberArray[i] = pnum;
else {
System.out.println("wrong order =" + pnum);
mb.setMessage("Wrong Configuration! Order number should be within [1-12]");
mb.open();
return false;
}
}
}
}
for (int i = 1; i <= NsharpConstants.PAGE_MAX_NUMBER; i++) {
for (int j = 1; j < NsharpConstants.PAGE_MAX_NUMBER; j++) {
if ((i != j)
&& editingOrderNumberArray[i] == editingOrderNumberArray[j]) {
mb.setMessage("Wrong Configuration! Multiple pages with same order.");
mb.open();
return false;
}
}
}
return true;
}
private void applyChange() {
pageOrderNumberArray = editingOrderNumberArray.clone();
for (int i = 1; i <= NsharpConstants.PAGE_MAX_NUMBER; i++) {
curOrderLblArray[i].setText(Integer
.toString(pageOrderNumberArray[i]));
}
NsharpEditor editor = NsharpEditor.getActiveNsharpEditor();
if (editor != null) {
NsharpResourceHandler rsc = editor.getRscHandler();
editingDpp = new NsharpDataPageProperty();
editingDpp
.setSummary1Page(pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY1]);
editingDpp
.setSummary2Page(pageOrderNumberArray[NsharpConstants.PAGE_SUMMARY2]);
editingDpp
.setParcelDataPage(pageOrderNumberArray[NsharpConstants.PAGE_PARCEL_DATA]);
editingDpp
.setThermodynamicDataPage(pageOrderNumberArray[NsharpConstants.PAGE_THERMODYNAMIC_DATA]);
editingDpp
.setOpcDataPage(pageOrderNumberArray[NsharpConstants.PAGE_OPC_DATA]);
editingDpp
.setMixingHeightPage(pageOrderNumberArray[NsharpConstants.PAGE_MIXING_HEIGHT]);
editingDpp
.setStormRelativePage(pageOrderNumberArray[NsharpConstants.PAGE_STORM_RELATIVE]);
editingDpp
.setMeanWindPage(pageOrderNumberArray[NsharpConstants.PAGE_MEAN_WIND]);
editingDpp
.setConvectiveInitiationPage(pageOrderNumberArray[NsharpConstants.PAGE_CONVECTIVE_INITIATION]);
editingDpp
.setSeverePotentialPage(pageOrderNumberArray[NsharpConstants.PAGE_SEVERE_POTENTIAL]);
editingDpp
.setD2dLitePage(pageOrderNumberArray[NsharpConstants.PAGE_D2DLITE]); // d2dlite
editingDpp
.setFuturePage(pageOrderNumberArray[NsharpConstants.PAGE_FUTURE]); // d2dlite
editingDpp.setNumberPagePerDisplay(numberPagePerDisplay);
rsc.setDataPageProperty(editingDpp);
editor.refresh();
}
}
/*
* private void setDisplay(){ int pageIndex = 0; for(int orderNum=1;
* orderNum <= NsharpConstants.PAGE_MAX_NUMBER; orderNum++){ for(int j=1; j
* <= NsharpConstants.PAGE_MAX_NUMBER; j++){ //find the page with order
* number equal to orderNum if(orderNum == pageOrderNumberArray[j]){
* pageIndex = j; break; } }
* curOrderLblArray[orderNum].setText(Integer.toString
* (pageOrderNumberArray[pageIndex]));
* newOrderTextArray[orderNum].setText(Integer
* .toString(pageOrderNumberArray[pageIndex]));
* pageNameLblArray[orderNum].setText
* (NsharpConstants.PAGE_NAME_ARRAY[pageIndex]); } }
*/
@Override
public void okPressed() {
// "Enter" key is pressed, or "Apply" button is pressed.
// Chin: handle user entered configuration, sanity checking and apply
// its changes.
// System.out.println("CR is pressed");
setReturnCode(OK);
if (sanityCheck() == false) {
System.out.println("sanity check failed");
return;
}
applyChange();
}
@Override
protected Control createDialogArea(Composite parent) {
Composite top;
top = (Composite) super.createDialogArea(parent);
// Create the main layout for the shell.
GridLayout mainLayout = new GridLayout(1, false);
mainLayout.marginHeight = 3;
mainLayout.marginWidth = 3;
top.setLayout(mainLayout);
btnGp = new Group(top, SWT.SHADOW_ETCHED_IN);
btnGp.setText("number of page per display");
if (paneConfigurationName.equals(NsharpConstants.PANE_LITE_D2D_CFG_STR)) // d2dlite
btnGp.setVisible(false);
Button oneBtn = new Button(btnGp, SWT.RADIO | SWT.BORDER);
oneBtn.setText("1");
oneBtn.setEnabled(true);
oneBtn.setBounds(btnGp.getBounds().x + NsharpConstants.btnGapX,
btnGp.getBounds().y + NsharpConstants.labelGap,
NsharpConstants.btnWidth, NsharpConstants.btnHeight);
// oneBtn.setFont(newFont);
oneBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
numberPagePerDisplay = 1;
// System.out.println("new obvSnd dialog uair btn");
}
});
Button twoBtn = new Button(btnGp, SWT.RADIO | SWT.BORDER);
twoBtn.setText("2");
twoBtn.setEnabled(true);
twoBtn.setBounds(btnGp.getBounds().x + NsharpConstants.btnGapX,
oneBtn.getBounds().y + oneBtn.getBounds().height
+ NsharpConstants.btnGapY, NsharpConstants.btnWidth,
NsharpConstants.btnHeight);
// twoBtn.setFont(newFont);
twoBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
numberPagePerDisplay = 2;
}
});
if (numberPagePerDisplay == 1)
oneBtn.setSelection(true);
else
twoBtn.setSelection(true);
Group configGp = new Group(top, SWT.SHADOW_ETCHED_IN
| SWT.NO_RADIO_GROUP);
Label nameLbl = new Label(configGp, SWT.BORDER);
nameLbl.setText(" Page Name");
nameLbl.setBounds(configGp.getBounds().x, configGp.getBounds().y,
lblWidth, lblHeight);
Label curOrderLbl = new Label(configGp, SWT.BORDER);
curOrderLbl.setText("Current");
curOrderLbl.setBounds(
nameLbl.getBounds().x + nameLbl.getBounds().width,
nameLbl.getBounds().y, textWidth, lblHeight);
Label newOrderLbl = new Label(configGp, SWT.BORDER);
// newOrderLbl.setText(Integer.toString(summary1Page));
newOrderLbl.setBounds(
curOrderLbl.getBounds().x + curOrderLbl.getBounds().width,
nameLbl.getBounds().y, textWidth, lblHeight);
newOrderLbl.setText("New Order");
Label prevLbl = nameLbl;
Label pageLbl;
for (int i = 1; i <= NsharpConstants.PAGE_MAX_NUMBER; i++) {
pageLbl = pageNameLblArray[i] = new Label(configGp, SWT.BORDER);
pageLbl.setText(NsharpConstants.PAGE_NAME_ARRAY[i]);
pageLbl.setBounds(configGp.getBounds().x, prevLbl.getBounds().y
+ lblHeight, lblWidth, lblHeight);
curLbl = curOrderLblArray[i] = new Label(configGp, SWT.BORDER);
curLbl.setText(Integer.toString(pageOrderNumberArray[i]));
curLbl.setBounds(pageLbl.getBounds().x + pageLbl.getBounds().width,
pageLbl.getBounds().y, textWidth, lblHeight);
newText = newOrderTextArray[i] = new Text(configGp, SWT.BORDER
| SWT.SINGLE);
newText.setBounds(curLbl.getBounds().x + curLbl.getBounds().width,
pageLbl.getBounds().y, textWidth, lblHeight);
newText.setEditable(true);
newText.setText(Integer.toString(pageOrderNumberArray[i]));
// to make sure user enter digits only
newText.addListener(SWT.Verify, new EditListener(newText));
prevLbl = pageLbl;
}
return top;
}
public class EditListener implements Listener {
Text newOrderText;
public void handleEvent(Event e) {
String string = e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
// System.out.println("entered s="+ string);
// Chin note: when "Delete", "Backspace" entered, this handler will
// be called, but
// its chars.length = 0
if (chars.length == 1 && newOrderText != null) {
if (chars[0] == '-') {
// if "-" is not first char
String textStr = newOrderText.getText();
if ((textStr != null) && (textStr.length() >= 1)
&& (textStr.contains("-"))) {
e.doit = false;
return;
}
} else if (!('0' <= chars[0] && chars[0] <= '9')) {
e.doit = false;
return;
}
}
}
public EditListener(Text newOrderText) {
super();
this.newOrderText = newOrderText;
}
}
public EditListener(Text newOrderText) {
super();
this.newOrderText = newOrderText;
}
}
}

View file

@ -0,0 +1,420 @@
/**
*
* gov.noaa.nws.ncep.ui.nsharp.view.GpdProductDialogContents
*
* This java class performs the NSHARP NsharpLoadDialog functions.
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------- ------- -------- -----------
* 08/2013 Chin Chen Initial coding
*
* </pre>
*
* @author Chin Chen
* @version 1.0
*/
package gov.noaa.nws.ncep.ui.nsharp.view;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingStnInfo;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingStnInfoCollection;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingTimeLines;
import gov.noaa.nws.ncep.ui.nsharp.NsharpConstants;
import gov.noaa.nws.ncep.ui.nsharp.NsharpStationInfo;
import gov.noaa.nws.ncep.ui.nsharp.display.map.NsharpMapResource;
import gov.noaa.nws.ncep.viz.common.soundingQuery.NcSoundingQuery;
import java.sql.Timestamp;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
// import gov.noaa.nws.ncep.viz.rsc.gpd.query.GpdQuery;
public class NsharpGpdObsSoundingDialogContents {
private Composite parent;
private org.eclipse.swt.widgets.List sndTimeList = null, prodList = null;
// private Text newProdNameText, curProdNameText;
private Group sndTimeListGp, topGp, prodGp;
private boolean timeLimit = false;
// private boolean rawData = false;
private Button timeBtn;
// private String FILE_DROP = "DROP";
private String currentProdName = "";
private NsharpLoadDialog ldDia;
// private Label curProdLbl, newProdLbl;
private ArrayList<String> selectedTimeList = new ArrayList<String>();
private Font newFont;
private String[] sel = new String[1];
public String getCurrentProdName() {
return currentProdName;
}
public void setCurrentProdName(String currentProdName) {
this.currentProdName = currentProdName;
}
public NsharpGpdObsSoundingDialogContents(Composite parent) {
this.parent = parent;
ldDia = NsharpLoadDialog.getAccess();
newFont = ldDia.getNewFont();
}
private void createProdList() {
if (prodList != null)
prodList.removeAll();
if (sndTimeList != null)
sndTimeList.removeAll();
ldDia.startWaitCursor();
List<String> prodStrLst = null;
// TBDGPD List<String> prodStrLst = GpdQuery
// .getGpdAvailProducts(GenericPointDataReqType.GET_GPD_AVAILABLE_OBSERVED_SOUNDING_PRODUCTS);
if (prodList != null) {
for (String prod : prodStrLst)
prodList.add(prod);
}
ldDia.stopWaitCursor();
}
private void createSndList() {
/*
* /testing List<String> prodList =
* GpdQuery.getGpdAvailProducts(GenericPointDataReqType
* .GET_GPD_AVAILABLE_SURFACE_PRODUCTS); if(prodList != null &&
* prodList.size() > 0){ for(String prod: prodList)
* System.out.println("GPD product = "+ prod); } //edn testing
*/
if (currentProdName.equals("") == true)
return;
if (sndTimeList != null)
sndTimeList.removeAll();
// use NcSoundingQuery to query
ldDia.startWaitCursor();
NcSoundingTimeLines timeLines = null;
// TBDGPD NcSoundingTimeLines timeLines =
// GpdQuery.getGpdSoundingTimeLines(currentProdName);
if (timeLines != null && timeLines.getTimeLines() != null) {
DateFormatSymbols dfs = new DateFormatSymbols();
String[] defaultDays = dfs.getShortWeekdays();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
for (Object timeLine : timeLines.getTimeLines()) {
Timestamp synoptictime = (Timestamp) timeLine;
if (synoptictime != null) {
// need to format synoptictime to GMT time string.
// Timestamp.toString produce a local time Not GMT time
cal.setTimeInMillis(synoptictime.getTime());
String dayOfWeek = defaultDays[cal
.get(Calendar.DAY_OF_WEEK)];
// String gmtTimeStr =
// String.format("%1$ty%1$tm%1$td/%1$tH%1$tM %2$s", cal,
// currentSndType.toString());
String gmtTimeStr = String.format(
"%1$ty%1$tm%1$td/%1$tH(%3$s) %2$s", cal,
currentProdName.toString(), dayOfWeek);
if (!timeLimit) {
// System.out.println("not 00z and 12z only");
sndTimeList.add(gmtTimeStr);
} else {
int hour = cal.get(Calendar.HOUR_OF_DAY);
// System.out.println("00z and 12z only hour = "+ hour);
if ((hour == 0) || (hour == 12))
sndTimeList.add(gmtTimeStr);
}
}
}
} else
System.out.println("EDEX timeline query return null");
ldDia.stopWaitCursor();
}
private void queryAndMarkStn(String selectedSndTime) {
String selectTimetr = NcSoundingQuery
.convertSoundTimeDispStringToRangeStartTimeFormat(selectedSndTime);
NsharpMapResource nsharpMapResource = NsharpMapResource
.getOrCreateNsharpMapResource();
double lat, lon;
String stnInfoStr;
// use NcSoundingQuery to query stn info
// TBDGPD NcSoundingStnInfoCollection sndStnInfoCol =
// GpdQuery.getGpdStationInfoCollection(currentProdName, selectTimetr);
NcSoundingStnInfoCollection sndStnInfoCol = null;
if (sndStnInfoCol != null && sndStnInfoCol.getStationInfo() != null) {
NcSoundingStnInfo[] stnInfoAry = sndStnInfoCol.getStationInfo();
// System.out.println("gpdobs station number = " +
// stnInfoAry.length);
// Note: A same station may have many reports
for (int i = 0; i < stnInfoAry.length; i++) {
NcSoundingStnInfo stnInfo = stnInfoAry[i];
Timestamp synoptictime = null;
stnInfoStr = stnInfo.getStnId();
if (stnInfoStr == null || stnInfoStr.length() < 1)
stnInfoStr = "*";
lat = stnInfo.getStationLatitude();
lon = stnInfo.getStationLongitude();
// elv = stnInfo.getStationElevation();
synoptictime = (Timestamp) stnInfo.getSynopTime();
// convert to Nsharp's own station info struct
NsharpStationInfo stn = new NsharpStationInfo();
String packedStnInfoStr = stnInfoStr.replace(" ", "_");
int endIndex = Math.min(
NsharpConstants.MAX_SOUNDING_SOURCE_STR_LENGTH,
currentProdName.length());
stn.setStnDisplayInfo(packedStnInfoStr + " " + selectedSndTime
+ " " + currentProdName.substring(0, endIndex));
stn.setLongitude(lon);
stn.setLatitude(lat);
stn.setStnId(stnInfoStr);
stn.setReftime(synoptictime);
stn.setRangestarttime(synoptictime);
stn.setSndType(currentProdName.toString());
// System.out.println("sndType= "+currentSndType);
// System.out.println("stn lat ="+stn.getLatitude() +
// " lon="+stn.getLongitude());
nsharpMapResource.addPoint(stn);
}
NsharpMapResource.bringMapEditorToTop();
}
}
private void handleSndTimeSelection() {
String selectedSndTime = null;
if (sndTimeList.getSelectionCount() > 0) {
NsharpMapResource nsharpMapResource = NsharpMapResource
.getOrCreateNsharpMapResource();// NsharpLoadDialog.getAccess().getNsharpMapResource();
nsharpMapResource.setPoints(null);
selectedTimeList.clear();
ldDia.startWaitCursor();
for (int i = 0; i < sndTimeList.getSelectionCount(); i++) {
selectedSndTime = sndTimeList.getSelection()[i];
selectedTimeList.add(selectedSndTime);
// System.out.println("selected sounding time is " +
// selectedSndTime);
int endIndex = selectedSndTime.indexOf(" ");
String queryingSndTime = selectedSndTime.substring(0, endIndex);
queryAndMarkStn(queryingSndTime);
}
ldDia.setGpdSelectedTimeList(selectedTimeList);
ldDia.stopWaitCursor();
}
}
public void createGpdObsDialogContents() {
currentProdName = ldDia.getActiveGpdProdName();
// System.out.println("createGpdDialogContents");
// timeLimit =false;
// rawData = false;
topGp = new Group(parent, SWT.SHADOW_ETCHED_IN);
topGp.setLayout(new GridLayout(2, false));
ldDia.createSndTypeList(topGp);
/*
* prodNameGp = new Group(topGp, SWT.SHADOW_ETCHED_IN);
* prodNameGp.setLayout( new GridLayout( 2, true ) );
* prodNameGp.setText("Product Name"); prodNameGp.setFont(newFont);
* curProdLbl = new Label(prodNameGp, SWT.NONE | SWT.BORDER);
* //curProdLbl.setBounds(prodNameGp.getBounds().x,
* prodNameGp.getBounds().y + NsharpConstants.btnGapY,
* prodNameGp.getBounds().width/2,NsharpConstants.btnHeight);
* curProdLbl.setText("Current Product:"); curProdLbl.setFont(newFont);
* curProdNameText = new Text(prodNameGp, SWT.NONE );
* //curProdNameText.setBounds
* (curProdLbl.getBounds().x+curProdLbl.getBounds().width,
* prodNameGp.getBounds().y + NsharpConstants.btnGapY,
* prodNameGp.getBounds().width/2,NsharpConstants.btnHeight);
* curProdNameText.setText(currentProdName);
* curProdNameText.setFont(newFont); curProdNameText.setTextLimit(20);
* curProdNameText.setEditable(false); Color color = new
* Color(Display.getDefault(), NsharpConstants.backgroundColor);
* curProdNameText.setBackground(color); newProdLbl = new
* Label(prodNameGp, SWT.NONE | SWT.BORDER);
* //curProdLbl.setBounds(prodNameGp.getBounds().x,
* prodNameGp.getBounds().y + NsharpConstants.btnGapY,
* prodNameGp.getBounds().width/2,NsharpConstants.btnHeight);
* newProdLbl.setText("New Product:"); newProdLbl.setFont(newFont);
*
* newProdNameText = new Text(prodNameGp, SWT.BORDER | SWT.SINGLE);
* //GridData data1 = new GridData (SWT.FILL,SWT.FILL, true, true);
* //prodNameText.setLayoutData (data1);
* //prodNameText.setBounds(stationBtn.getBounds().x,
* locationLbl.getBounds().y,450,NsharpConstants.btnHeight);
* newProdNameText.setTextLimit(20); newProdNameText.setFont(newFont);
* //prodNameText.addListener (SWT.Verify, new Listener () { //public
* void handleEvent (Event e) { //String userInputStr = e.text; //
* System.out.println(userInputStr); //} //}); Button setBtn = new
* Button(prodNameGp, SWT.PUSH); setBtn.setText("Set Product Name");
* setBtn.setFont(newFont); setBtn.setEnabled( true );
* setBtn.setBounds(prodNameGp.getBounds().x+ NsharpConstants.btnGapX,
* curProdLbl.getBounds().y + curProdLbl.getBounds().height+
* NsharpConstants.btnGapY,
* NsharpConstants.btnWidth,NsharpConstants.btnHeight);
* setBtn.addListener( SWT.MouseUp, new Listener() { public void
* handleEvent(Event event) { String textStr =
* newProdNameText.getText(); if((textStr != null) &&
* !(textStr.isEmpty())){ //textStr = textStr.trim(); currentProdName =
* textStr; currentProdName = currentProdName.trim();
* //System.out.println(currentProdName);
* curProdNameText.setText(currentProdName); curProdNameText.redraw();
* createSndList(); ldDia.setActiveGpdProdName(currentProdName); } } }
* );
*/
prodGp = new Group(topGp, SWT.SHADOW_ETCHED_IN);
prodGp.setText("Gpd Observed Sounding List");
prodGp.setFont(newFont);
prodList = new org.eclipse.swt.widgets.List(prodGp, SWT.BORDER
| SWT.V_SCROLL);
prodList.setBounds(prodGp.getBounds().x, prodGp.getBounds().y
+ NsharpConstants.labelGap, NsharpConstants.filelistWidth,
NsharpConstants.listHeight);
// query to get and add available sounding models from DB
prodList.setFont(newFont);
createProdList();
// create a selection listener to handle user's selection on list
prodList.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
if (prodList.getSelectionCount() > 0) {
currentProdName = prodList.getSelection()[0];
ldDia.setActiveGpdProdName(currentProdName);
createSndList();
}
}
});
timeBtn = new Button(topGp, SWT.CHECK | SWT.BORDER);
timeBtn.setText("00Z and 12Z only");
timeBtn.setEnabled(true);
timeBtn.setFont(newFont);
timeBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
if (timeLimit)
timeLimit = false;
else
timeLimit = true;
// refresh sounding list if file type is selected already
if (sndTimeList != null && currentProdName.equals("") == false) {
createSndList();
}
}
});
// create file widget list
sndTimeListGp = new Group(parent, SWT.SHADOW_ETCHED_IN);
sndTimeListGp.setText("Sounding Times:");
sndTimeListGp.setFont(newFont);
sndTimeList = new org.eclipse.swt.widgets.List(sndTimeListGp,
SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
sndTimeList.setBounds(sndTimeListGp.getBounds().x
+ NsharpConstants.btnGapX, sndTimeListGp.getBounds().y
+ NsharpConstants.labelGap, NsharpConstants.listWidth,
NsharpConstants.listHeight * 7);
sndTimeList.setFont(newFont);
// create a selection listener to handle user's selection on list
sndTimeList.addListener(SWT.Selection, new Listener() {
// private String selectedSndTime=null;
public void handleEvent(Event e) {
handleSndTimeSelection();
}
});
if (currentProdName.equals("") == false) {
sel[0] = currentProdName;
prodList.setSelection(sel);
createSndList();
selectedTimeList = ldDia.getGpdSelectedTimeList();
Object[] selTimeObjectArray = selectedTimeList.toArray();
String[] selTimeStringArray = Arrays.copyOf(selTimeObjectArray,
selTimeObjectArray.length, String[].class);
sndTimeList.setSelection(selTimeStringArray);
handleSndTimeSelection();
}
}
public void cleanup() {
if (sndTimeList != null) {
sndTimeList.removeListener(SWT.Selection,
sndTimeList.getListeners(SWT.Selection)[0]);
sndTimeList.dispose();
sndTimeList = null;
}
if (sndTimeListGp != null) {
sndTimeListGp.dispose();
sndTimeListGp = null;
}
if (prodList != null) {
if (prodList.getListeners(SWT.Selection).length > 0)
prodList.removeListener(SWT.Selection,
prodList.getListeners(SWT.Selection)[0]);
prodList.dispose();
prodList = null;
}
if (prodGp != null) {
prodGp.dispose();
prodGp = null;
}
NsharpLoadDialog ldDia = NsharpLoadDialog.getAccess();
ldDia.cleanSndTypeList();
if (topGp != null) {
topGp.dispose();
topGp = null;
}
}
/*
* public static NcSoundingTimeLines gpdSoundingTimeLineQuery (String
* productName){ NcSoundingTimeLines timeLines = null;
* GenericPointDataReqMsg reqMsg = new GenericPointDataReqMsg();
* reqMsg.setReqType
* (GenericPointDataReqType.GET_GPD_PRODUCT_TIMELINE_OBJECT);
* reqMsg.setProductName(productName); try { Object rslts =
* ThriftClient.sendRequest( reqMsg ); if( (rslts instanceof
* NcSoundingTimeLines) ) { // timeLines = (NcSoundingTimeLines)rslts; }
* else { System.out.println("Request Failed: ");
*
* } } catch (Exception e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*
*
* return timeLines;
*
* }
*/
}

View file

@ -0,0 +1,490 @@
/**
*
* gov.noaa.nws.ncep.ui.nsharp.view.PfcSoundingDialogContents
*
* This java class performs the NSHARP NsharpLoadDialog functions.
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------- ------- -------- -----------
* 01/2011 229 Chin Chen Initial coding
*
* </pre>
*
* @author Chin Chen
* @version 1.0
*/
package gov.noaa.nws.ncep.ui.nsharp.view;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingProfile;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingStnInfo;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingStnInfoCollection;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingTimeLines;
import gov.noaa.nws.ncep.ui.nsharp.NsharpConstants;
import gov.noaa.nws.ncep.ui.nsharp.NsharpStationInfo;
import gov.noaa.nws.ncep.ui.nsharp.display.map.NsharpMapResource;
import gov.noaa.nws.ncep.viz.common.soundingQuery.NcSoundingQuery;
import java.sql.Timestamp;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
//import gov.noaa.nws.ncep.viz.rsc.gpd.query.GpdQuery;
public class NsharpGpdPfcSoundingDialogContents {
private Composite parent;
private org.eclipse.swt.widgets.List prodList, availablefileList,
sndTimeList;
private Group topGp, prodGp, bottomGp, availableFileGp, sndTimeListGp;
private Button namBtn, gfsBtn, timeBtn;
private boolean timeLimit = false;
private List<String> selectedFileList = new ArrayList<String>();
private List<String> selectedTimeList = new ArrayList<String>();
private List<NsharpStationInfo> stnPoints = new ArrayList<NsharpStationInfo>();
private NcSoundingProfile.PfcSndType currentSndType = NcSoundingProfile.PfcSndType.NONE;
private NsharpLoadDialog ldDia;
private Font newFont;
private String currentProdName = "";
private String[] sel = new String[1];
public NcSoundingProfile.PfcSndType getCurrentSndType() {
return currentSndType;
}
public NsharpGpdPfcSoundingDialogContents() {
}
public NsharpGpdPfcSoundingDialogContents(Composite parent) {
this.parent = parent;
ldDia = NsharpLoadDialog.getAccess();
newFont = ldDia.getNewFont();
}
private void createPFCAvailableFileList() {
sndTimeList.removeAll();
;
availablefileList.removeAll();
// query using NcSoundingQuery class to query
NcSoundingTimeLines timeLines = null;
// TBDGPD NcSoundingTimeLines timeLines =
// GpdQuery.getGpdSoundingTimeLines(currentProdName);
if (timeLines != null && timeLines.getTimeLines() != null) {
ldDia.startWaitCursor();
for (Object timeLine : timeLines.getTimeLines()) {
Timestamp reftime = (Timestamp) timeLine;
if (reftime != null) {
// need to format reftime to GMT time string.
// Timestamp.toString produce a local time Not GMT time
Calendar cal = Calendar.getInstance(TimeZone
.getTimeZone("GMT"));
cal.setTimeInMillis(reftime.getTime());
String gmtTimeStr = String.format(
"%1$tY-%1$tm-%1$td %1$tH", cal);
// System.out.println("GMT time " + gmtTimeStr);
availablefileList.add(gmtTimeStr);
}
}
ldDia.stopWaitCursor();
} else
System.out.println("SQL: query return null");
}
private void createPFCSndTimeList(List<String> selectedFlLst) {
if (selectedFlLst.size() <= 0)
return;
sndTimeList.removeAll();
ldDia.startWaitCursor();
String sndStr = currentProdName;
int endIndex = Math.min(3, sndStr.length());
String dispSndStr = sndStr.substring(0, endIndex);
DateFormatSymbols dfs = new DateFormatSymbols();
String[] defaultDays = dfs.getShortWeekdays();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
for (int i = 0; i < selectedFlLst.size(); i++) {
String fl = selectedFlLst.get(i);
long reftimeMs = NcSoundingQuery.convertRefTimeStr(fl);
// System.out.println("reftime="+fl + " in ms="+reftimeMs);
NcSoundingTimeLines timeLines = null;
// TBDGPD NcSoundingTimeLines timeLines =
// GpdQuery.getGpdRangeStartTimes(currentProdName, fl);
if (timeLines != null && timeLines.getTimeLines().length > 0) {
for (Object obj : timeLines.getTimeLines()) {
Timestamp rangestart = (Timestamp) obj;
// need to format rangestart to GMT time string.
// Timestamp.toString produce a local time Not GMT time
cal.setTimeInMillis(rangestart.getTime());
long vHour = (cal.getTimeInMillis() - reftimeMs) / 3600000;
String dayOfWeek = defaultDays[cal
.get(Calendar.DAY_OF_WEEK)];
// String gmtTimeStr =
// String.format("%1$ty%1$tm%1$td/%1$tH%1$tMV%2$03d %3$s",
// cal, vHour,dispSndStr);
String gmtTimeStr = String.format(
"%1$ty%1$tm%1$td/%1$tH(%4$s)V%2$03d %3$s", cal,
vHour, dispSndStr, dayOfWeek);
if (sndTimeList.indexOf(gmtTimeStr) != -1) {
// this indicate that gmtTimeStr is already in the
// sndTimeList, then we dont need to add it to list
// again.
continue;
}
// System.out.println("GMT time " + gmtTimeStr);
if (!timeLimit)
sndTimeList.add(gmtTimeStr);
else {
int hour = cal.get(Calendar.HOUR_OF_DAY);
if ((hour == 0) || (hour == 12))
sndTimeList.add(gmtTimeStr);
}
}
}
}
ldDia.stopWaitCursor();
}
private void handleAvailFileListSelection() {
String selectedFile = null;
if (availablefileList.getSelectionCount() > 0) {
selectedFileList.clear();
for (int i = 0; i < availablefileList.getSelectionCount(); i++) {
selectedFile = availablefileList.getSelection()[i];
// System.out.println("selected sounding file is " +
// selectedFile);
selectedFileList.add(selectedFile);
}
ldDia.setPfcSelectedFileList(selectedFileList);
createPFCSndTimeList(selectedFileList);
}
}
private void handleSndTimeSelection() {
String selectedSndTime = null;
if (sndTimeList.getSelectionCount() > 0) {
NsharpMapResource nsharpMapResource = NsharpMapResource
.getOrCreateNsharpMapResource();
nsharpMapResource.setPoints(null);
selectedTimeList.clear();
ldDia.startWaitCursor();
List<String> queriedTimeList = new ArrayList<String>();
for (int i = 0; i < sndTimeList.getSelectionCount(); i++) {
selectedSndTime = sndTimeList.getSelection()[i];
selectedTimeList.add(selectedSndTime);
int endIndex = selectedSndTime.indexOf(" ");
String querySndTime = selectedSndTime.substring(0, endIndex);
// System.out.println("selected sounding time is " +
// selectedSndTime);
// refTimeStr is same as "PFC file" name in Load dialog display
String refTimeStr = NcSoundingQuery
.convertSoundTimeDispStringToForecastTime(querySndTime);
// while rangeStartStr is same as "sounding Times
String rangeStartStr = NcSoundingQuery
.convertSoundTimeDispStringToRangeStartTimeFormat(querySndTime);
if (queriedTimeList.contains(refTimeStr) == true) {
// for all range start times of one reference time, they
// should have same stations, therefore, only
// query once, the rest will be just marked.
addStnPtWithoutQuery(refTimeStr, rangeStartStr,
querySndTime);
} else {
queriedTimeList.add(refTimeStr);
queryAndMarkStn(refTimeStr, rangeStartStr, querySndTime);
}
}
ldDia.stopWaitCursor();
nsharpMapResource.setPoints(stnPoints);
NsharpMapResource.bringMapEditorToTop();
}
}
private void createProdList() {
if (prodList != null)
prodList.removeAll();
if (sndTimeList != null)
sndTimeList.removeAll();
if (availablefileList != null)
availablefileList.removeAll();
ldDia.startWaitCursor();
List<String> prodStrLst = null;
// TBDGPD List<String> prodStrLst =
// GpdQuery.getGpdAvailProducts(GenericPointDataReqType.GET_GPD_AVAILABLE_MODEL_SOUNDING_PRODUCTS);
for (String prod : prodStrLst)
prodList.add(prod);
ldDia.stopWaitCursor();
}
public void createGpdPfcDialogContents() {
topGp = new Group(parent, SWT.SHADOW_ETCHED_IN);
topGp.setLayout(new GridLayout(2, false));
currentSndType = ldDia.getActivePfcSndType();
ldDia.createSndTypeList(topGp);
prodGp = new Group(topGp, SWT.SHADOW_ETCHED_IN);
prodGp.setText("Gpd Pfc Sounding List");
prodGp.setFont(newFont);
prodList = new org.eclipse.swt.widgets.List(prodGp, SWT.BORDER
| SWT.V_SCROLL);
prodList.setBounds(prodGp.getBounds().x, prodGp.getBounds().y
+ NsharpConstants.labelGap, NsharpConstants.filelistWidth,
NsharpConstants.listHeight);
// query to get and add available sounding models from DB
prodList.setFont(newFont);
createProdList();
// create a selection listener to handle user's selection on list
prodList.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
if (prodList.getSelectionCount() > 0) {
currentProdName = prodList.getSelection()[0];
ldDia.setActiveGpdProdName(currentProdName);
createPFCAvailableFileList();
}
}
});
timeBtn = new Button(parent, SWT.CHECK | SWT.BORDER);
timeBtn.setText("00Z and 12Z only");
timeBtn.setEnabled(true);
// timeBtn.setBounds(fileTypeGp.getBounds().x+ NsharpConstants.btnGapX,
// browseBtn.getBounds().y + browseBtn.getBounds().height+
// NsharpConstants.btnGapY,
// NsharpConstants.btnWidth,NsharpConstants.btnHeight);
timeBtn.setFont(newFont);
timeBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
if (timeLimit)
timeLimit = false;
else
timeLimit = true;
// refresh sounding list if file type is selected already
if (!currentSndType.equals("NA") && selectedFileList.size() > 0) {
createPFCSndTimeList(selectedFileList);
}
}
});
bottomGp = new Group(parent, SWT.SHADOW_ETCHED_IN);
bottomGp.setLayout(new GridLayout(2, false));
availableFileGp = new Group(bottomGp, SWT.SHADOW_ETCHED_IN);
availableFileGp.setText("Available PFC files:");
availableFileGp.setFont(newFont);
availablefileList = new org.eclipse.swt.widgets.List(availableFileGp,
SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
availablefileList.setBounds(availableFileGp.getBounds().x,
availableFileGp.getBounds().y + NsharpConstants.labelGap,
NsharpConstants.filelistWidth,
NsharpConstants.listHeight * 36 / 5);
// create a selection listener to handle user's selection on list
availablefileList.setFont(newFont);
availablefileList.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
handleAvailFileListSelection();
}
});
// create Sounding Times widget list
sndTimeListGp = new Group(bottomGp, SWT.SHADOW_ETCHED_IN);
sndTimeListGp.setText("Sounding Times:");
sndTimeListGp.setFont(newFont);
sndTimeList = new org.eclipse.swt.widgets.List(sndTimeListGp,
SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
sndTimeList.removeAll();
sndTimeList.setFont(newFont);
sndTimeList.setBounds(sndTimeListGp.getBounds().x,
sndTimeListGp.getBounds().y + NsharpConstants.labelGap,
NsharpConstants.listWidth, NsharpConstants.listHeight * 36 / 5);
sndTimeList.addListener(SWT.Selection, new Listener() {
// private String selectedSndTime=null;
public void handleEvent(Event e) {
handleSndTimeSelection();
}
});
if (currentProdName.equals("") == false) {
sel[0] = currentProdName;
prodList.setSelection(sel);
createPFCAvailableFileList();
selectedFileList = ldDia.getPfcSelectedFileList();
Object[] selFileObjectArray = selectedFileList.toArray();
String[] selFileStringArray = Arrays.copyOf(selFileObjectArray,
selFileObjectArray.length, String[].class);
availablefileList.setSelection(selFileStringArray);
handleAvailFileListSelection();
selectedTimeList = ldDia.getPfcSelectedTimeList();
Object[] selTimeObjectArray = selectedTimeList.toArray();
String[] selTimeStringArray = Arrays.copyOf(selTimeObjectArray,
selTimeObjectArray.length, String[].class);
sndTimeList.setSelection(selTimeStringArray);
handleSndTimeSelection();
}
}
private void addStnPtWithoutQuery(String refTimeStr, String rangeStartStr,
String selectedSndTime) {
long reftimeMs = NcSoundingQuery.convertRefTimeStr(refTimeStr);
Timestamp refTime = new Timestamp(reftimeMs);
for (NsharpStationInfo stn : stnPoints) {
if (refTime.equals(stn.getReftime()) == true) {
long rangetimeMs = NcSoundingQuery
.convertRefTimeStr(rangeStartStr);
Timestamp rangeStartTime = new Timestamp(rangetimeMs);
NsharpStationInfo.timeLineSpecific timeLinsSpc = stn.new timeLineSpecific();
String sndTypeStr = currentProdName;
int endIndex = Math.min(
NsharpConstants.MAX_SOUNDING_SOURCE_STR_LENGTH,
sndTypeStr.length());
String dispInfo = stn.getStnId() + " " + selectedSndTime + " "
+ sndTypeStr.substring(0, endIndex);
timeLinsSpc.setDisplayInfo(dispInfo);
timeLinsSpc.setTiemLine(rangeStartTime);
stn.addToTimeLineSpList(timeLinsSpc);
}
}
// System.out.println("addStnPtWithoutQuery stn num ="+
// stnPoints.size()+ " for pfc refTime(file) "+refTimeStr);
}
private void queryAndMarkStn(String refTimeStr, String rangeStartStr,
String selectedSndTime) {
// use NcSoundingQuery to query stn info
String sndTypeStr = currentProdName;
NcSoundingStnInfoCollection sndStnInfoCol = null;
// TBDGPD NcSoundingStnInfoCollection sndStnInfoCol
// =GpdQuery.getGpdStationInfoCollection(currentProdName,refTimeStr,rangeStartStr);
if (sndStnInfoCol != null && sndStnInfoCol.getStationInfo() != null) {
NcSoundingStnInfo[] stnInfoAry = sndStnInfoCol.getStationInfo();
System.out.println("gpdpfc station number = " + stnInfoAry.length);
// System.out.println("queryAndMarkStn stn num ="+
// stnInfoAry.length+ " for pfc refTime(file) "+refTimeStr);
for (int i = 0; i < stnInfoAry.length; i++) {
NcSoundingStnInfo stnInfo = stnInfoAry[i];
NsharpStationInfo stn = new NsharpStationInfo();
NsharpStationInfo.timeLineSpecific timeLinsSpc = stn.new timeLineSpecific();
int endIndex = Math.min(
NsharpConstants.MAX_SOUNDING_SOURCE_STR_LENGTH,
sndTypeStr.length());
String packedStnIdStr = stnInfo.getStnId().replace(" ", "_");
String dispInfo = packedStnIdStr + " " + selectedSndTime + " "
+ sndTypeStr.substring(0, endIndex);
timeLinsSpc.setDisplayInfo(dispInfo);
timeLinsSpc.setTiemLine(stnInfo.getRangeStartTime());
stn.addToTimeLineSpList(timeLinsSpc);
stn.setLongitude(stnInfo.getStationLongitude());
stn.setLatitude(stnInfo.getStationLatitude());
stn.setReftime(stnInfo.getSynopTime());
stn.setStnId(stnInfo.getStnId());
stn.setSndType(sndTypeStr);
// if(i <10)
// System.out.println(
// "disP="+dispInfo+" refT= "+stnInfo.getSynopTime()+
// " rangSt="+stnInfo.getRangeStartTime());
stnPoints.add(stn);
}
}
}
public void cleanup() {
if (namBtn != null && namBtn.isDisposed() == false) {
namBtn.removeListener(SWT.MouseUp,
namBtn.getListeners(SWT.MouseUp)[0]);
namBtn.dispose();
namBtn = null;
}
if (gfsBtn != null) {
gfsBtn.removeListener(SWT.MouseUp,
gfsBtn.getListeners(SWT.MouseUp)[0]);
gfsBtn.dispose();
gfsBtn = null;
}
NsharpLoadDialog ldDia = NsharpLoadDialog.getAccess();
ldDia.cleanSndTypeList();
if (prodList != null) {
if (prodList.getListeners(SWT.Selection).length > 0)
prodList.removeListener(SWT.Selection,
prodList.getListeners(SWT.Selection)[0]);
prodList.dispose();
prodList = null;
}
if (prodGp != null) {
prodGp.dispose();
prodGp = null;
}
if (topGp != null) {
topGp.dispose();
topGp = null;
}
if (timeBtn != null) {
timeBtn.removeListener(SWT.MouseUp,
timeBtn.getListeners(SWT.MouseUp)[0]);
timeBtn.dispose();
timeBtn = null;
}
if (availablefileList != null) {
availablefileList.removeListener(SWT.Selection,
availablefileList.getListeners(SWT.Selection)[0]);
availablefileList.dispose();
availablefileList = null;
}
if (availableFileGp != null) {
availableFileGp.dispose();
availableFileGp = null;
}
if (sndTimeList != null) {
sndTimeList.removeListener(SWT.Selection,
sndTimeList.getListeners(SWT.Selection)[0]);
sndTimeList.dispose();
sndTimeList = null;
}
if (sndTimeListGp != null) {
sndTimeListGp.dispose();
sndTimeListGp = null;
}
if (bottomGp != null) {
bottomGp.dispose();
bottomGp = null;
}
}
}

View file

@ -19,15 +19,14 @@
*/
package gov.noaa.nws.ncep.ui.nsharp.view;
import java.util.ArrayList;
import java.util.List;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingProfile;
import gov.noaa.nws.ncep.ui.nsharp.NsharpConstants;
import gov.noaa.nws.ncep.ui.nsharp.display.NsharpEditor;
import gov.noaa.nws.ncep.ui.nsharp.display.map.NsharpMapResource;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
@ -47,445 +46,551 @@ import org.eclipse.swt.widgets.Text;
import com.raytheon.uf.viz.core.exception.VizException;
public class NsharpLoadDialog extends Dialog {
private final static int DIALOG_WIDTH = 350;
private final static int DIALOG_HEIGHT = 920;
protected Composite top;
private static Composite dialogParent;
private static NsharpLoadDialog INSTANCE = null;
private static Shell shell;
private org.eclipse.swt.widgets.List soundingTypeList;
public static final String[] soundingTypeStringArray = {
"Observed Soundings" , "Model Soundings", "PFC Soundings", "Archive Files","ACARS Soundings"
};
// define index to loadStringArray
public static final int OBSER_SND = 0;
public static final int MODEL_SND = 1;
public static final int PFC_SND = 2;
public static final int ARCHIVE = 3;
public static final int ACARS_SND = 4;
private ObservedSoundingDialogContents obsDialog;
private PfcSoundingDialogContents pfcDialog;
private ModelSoundingDialogContents mdlDialog;
private Group soundingTypeGp, acarsGp;
private int activeLoadSoundingType;
private NcSoundingProfile.ObsSndType activeObsSndType=NcSoundingProfile.ObsSndType.NCUAIR;
private ArrayList<String> obsSelectedTimeList = new ArrayList<String>();
private NcSoundingProfile.PfcSndType activePfcSndType=NcSoundingProfile.PfcSndType.NAMSND;
private List<String> pfcSelectedFileList = new ArrayList<String>();
private List<String> pfcSelectedTimeList = new ArrayList<String>();
private String activeMdlSndMdlType="";
private List<String> mdlSelectedFileList = new ArrayList<String>();
private List<String> mdlSelectedTimeList = new ArrayList<String>();
private Text text1;
private MessageBox mb;
private Cursor waitCursor=null;
private Font newFont;
public Font getNewFont() {
return newFont;
}
public ObservedSoundingDialogContents getObsDialog() {
return obsDialog;
}
public PfcSoundingDialogContents getPfcDialog() {
return pfcDialog;
}
public void setAndOpenMb(String msg) {
if (mb != null) {
mb.setMessage(msg);
try {
mb.open();
}catch (Exception e) {
mb = new MessageBox(shell, SWT.ICON_WARNING
| SWT.OK);
mb.setMessage(msg);
mb.open();
//e.printStackTrace();
}
}
}
public ModelSoundingDialogContents getMdlDialog() {
return mdlDialog;
}
public void createSndTypeList(Group TopLoadGp) {
soundingTypeGp = new Group(TopLoadGp,SWT.SHADOW_ETCHED_IN);
soundingTypeGp.setText("Sounding Type");
soundingTypeGp.setFont(newFont);
soundingTypeList = new org.eclipse.swt.widgets.List(soundingTypeGp, SWT.SINGLE | SWT.V_SCROLL );
soundingTypeList.setBounds(soundingTypeGp.getBounds().x + NsharpConstants.btnGapX, soundingTypeGp.getBounds().y +NsharpConstants.labelGap, NsharpConstants.filelistWidth, NsharpConstants.listHeight);
private final static int DIALOG_WIDTH = 350;
private final static int DIALOG_HEIGHT = 920;
protected Composite top;
private static Composite dialogParent;
private static NsharpLoadDialog INSTANCE = null;
private static Shell shell;
private org.eclipse.swt.widgets.List soundingTypeList;
public static final String[] soundingTypeStringArray = {
"Observed Soundings", "Model Soundings", "PFC Soundings",/*
* TBDGPD
* "GPD Observed"
* ,
* "GPD PFC"
* ,
*/
"Archive Files" };
// define index to loadStringArray
public static final int OBSER_SND = 0;
public static final int MODEL_SND = 1;
public static final int PFC_SND = 2;
// TBDGPD public static final int GPD_OBS_SND = 3;
// TBDGPDpublic static final int GPD_PFC_SND = 4;
public static final int ARCHIVE = 3; // TBDGPD 5;
private NsharpObservedSoundingDialogContents obsDialog;
private NsharpPfcSoundingDialogContents pfcDialog;
// TBDGPD private NsharpGpdPfcSoundingDialogContents gpdPfcDialog;
// TBDGPD private NsharpGpdObsSoundingDialogContents gpdObsDialog;
private NsharpModelSoundingDialogContents mdlDialog;
private Group soundingTypeGp;
private int activeLoadSoundingType;
private NcSoundingProfile.ObsSndType activeObsSndType = NcSoundingProfile.ObsSndType.NCUAIR;
private ArrayList<String> obsSelectedTimeList = new ArrayList<String>();
private String activeGpdProdName = "";
private ArrayList<String> gpdSelectedTimeList = new ArrayList<String>();
private NcSoundingProfile.PfcSndType activePfcSndType = NcSoundingProfile.PfcSndType.NAMSND;
private List<String> pfcSelectedFileList = new ArrayList<String>();
private List<String> pfcSelectedTimeList = new ArrayList<String>();
private String activeMdlSndMdlType = "";
private List<String> mdlSelectedFileList = new ArrayList<String>();
private List<String> mdlSelectedTimeList = new ArrayList<String>();
private Text text1;
private MessageBox mb;
private Cursor waitCursor = null;
private Font newFont;
public Font getNewFont() {
return newFont;
}
public NsharpObservedSoundingDialogContents getObsDialog() {
return obsDialog;
}
public NsharpPfcSoundingDialogContents getPfcDialog() {
return pfcDialog;
}
// TBDGPD
// public NsharpGpdObsSoundingDialogContents getGpdDialog() {
// return gpdObsDialog;
// }
public void setAndOpenMb(String msg) {
if (mb != null) {
mb.setMessage(msg);
try {
mb.open();
} catch (Exception e) {
mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
mb.setMessage(msg);
mb.open();
// e.printStackTrace();
}
}
}
public NsharpModelSoundingDialogContents getMdlDialog() {
return mdlDialog;
}
public void createSndTypeList(Group TopLoadGp) {
soundingTypeGp = new Group(TopLoadGp, SWT.SHADOW_ETCHED_IN);
soundingTypeGp.setText("Sounding Type");
soundingTypeGp.setFont(newFont);
soundingTypeList = new org.eclipse.swt.widgets.List(soundingTypeGp,
SWT.SINGLE | SWT.V_SCROLL);
soundingTypeList.setBounds(soundingTypeGp.getBounds().x
+ NsharpConstants.btnGapX, soundingTypeGp.getBounds().y
+ NsharpConstants.labelGap, NsharpConstants.filelistWidth,
NsharpConstants.filelistHeight);
soundingTypeList.setFont(newFont);
for(String loadStr : soundingTypeStringArray){
soundingTypeList.add( loadStr );
}
//create a selection listener to handle user's selection on list
soundingTypeList.addListener ( SWT.Selection, new Listener () {
private String selectedProduct=null;
public void handleEvent (Event e) {
if (soundingTypeList.getSelectionCount() > 0 ) {
for (String loadStr : soundingTypeStringArray) {
soundingTypeList.add(loadStr);
}
// create a selection listener to handle user's selection on list
soundingTypeList.addListener(SWT.Selection, new Listener() {
private String selectedProduct = null;
selectedProduct = soundingTypeList.getSelection()[0];
NsharpMapResource nsharpMapResource = NsharpMapResource.getOrCreateNsharpMapResource();//NsharpLoadDialog.getAccess().getNsharpMapResource();
nsharpMapResource.setPoints(null);
NsharpEditor editor = NsharpEditor.getActiveNsharpEditor();
if(editor!=null)
editor.refresh();
//shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
public void handleEvent(Event e) {
if (soundingTypeList.getSelectionCount() > 0) {
selectedProduct = soundingTypeList.getSelection()[0];
NsharpMapResource nsharpMapResource = NsharpMapResource
.getOrCreateNsharpMapResource();// NsharpLoadDialog.getAccess().getNsharpMapResource();
nsharpMapResource.setPoints(null);
NsharpMapResource.getMapEditor().refresh();
NsharpEditor editor = NsharpEditor.getActiveNsharpEditor();
if (editor != null)
editor.refresh();
// shell =
// PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
if(selectedProduct.equals(soundingTypeStringArray[OBSER_SND])){
//System.out.println("OBSER_SND enter");
if(activeLoadSoundingType != OBSER_SND){
cleanupDialog(activeLoadSoundingType); //clean up before resetting activeLoadType
activeLoadSoundingType = OBSER_SND;
obsDialog.createObsvdDialogContents();
//shell.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
dialogParent.pack();
dialogParent.layout(true);
dialogParent.redraw();
soundingTypeList.setSelection(OBSER_SND);
}
}
else if(selectedProduct.equals(soundingTypeStringArray[MODEL_SND])){
//System.out.println("MODEL_SND enter");
if(activeLoadSoundingType != MODEL_SND) {
cleanupDialog(activeLoadSoundingType);//clean up before resetting activeLoadType
activeLoadSoundingType = MODEL_SND;
mdlDialog.createMdlDialogContents();
dialogParent.pack();
dialogParent.layout(true);
dialogParent.redraw();
soundingTypeList.setSelection(MODEL_SND);
}
}
else if(selectedProduct.equals(soundingTypeStringArray[PFC_SND])){
//System.out.println("PFC_SND enter");
if(activeLoadSoundingType != PFC_SND){
cleanupDialog(activeLoadSoundingType); //clean up before resetting activeLoadType
activeLoadSoundingType = PFC_SND;
pfcDialog.createPfcDialogContents();
dialogParent.pack();
dialogParent.layout(true);
dialogParent.redraw();
soundingTypeList.setSelection(PFC_SND);
}
if (selectedProduct
.equals(soundingTypeStringArray[OBSER_SND])) {
// System.out.println("OBSER_SND enter");
}
else if(selectedProduct.equals(soundingTypeStringArray[ARCHIVE])){
//System.out.println("ARCHIVE enter");
if(activeLoadSoundingType != ARCHIVE) {
cleanupDialog(activeLoadSoundingType);//clean up before resetting activeLoadType
activeLoadSoundingType = ARCHIVE;
NsharpHandleArchiveFile.openArchiveFile(shell);
close();
}
if (activeLoadSoundingType != OBSER_SND) {
cleanupDialog(activeLoadSoundingType); // clean up
// before
// resetting
// activeLoadType
activeLoadSoundingType = OBSER_SND;
obsDialog.createObsvdDialogContents();
// shell.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
dialogParent.pack();
dialogParent.layout(true);
dialogParent.redraw();
soundingTypeList.setSelection(OBSER_SND);
}
} else if (selectedProduct
.equals(soundingTypeStringArray[MODEL_SND])) {
// System.out.println("MODEL_SND enter");
if (activeLoadSoundingType != MODEL_SND) {
cleanupDialog(activeLoadSoundingType);// clean up
// before
// resetting
// activeLoadType
activeLoadSoundingType = MODEL_SND;
mdlDialog.createMdlDialogContents();
dialogParent.pack();
dialogParent.layout(true);
dialogParent.redraw();
soundingTypeList.setSelection(MODEL_SND);
}
else if(selectedProduct.equals(soundingTypeStringArray[ACARS_SND])){
//System.out.println("ACARS_SND enter");
if(activeLoadSoundingType != ACARS_SND) {
cleanupDialog(activeLoadSoundingType);//clean up before resetting activeLoadType
activeLoadSoundingType = ACARS_SND;
//setShellSize(false);
acarsGp = new Group(dialogParent,SWT.SHADOW_ETCHED_IN);
acarsGp.setLayout( new GridLayout( 1, false ) );
createSndTypeList(acarsGp);
text1 = new Text(acarsGp, SWT.MULTI | SWT.BORDER | SWT.WRAP );
text1.setText("Acars Soundings\nis still under\ndevelopment!");
dialogParent.pack();
dialogParent.layout(true);
dialogParent.redraw();
soundingTypeList.setSelection(ACARS_SND);
}
}
}
}
}
} else if (selectedProduct
.equals(soundingTypeStringArray[PFC_SND])) {
// System.out.println("PFC_SND enter");
if (activeLoadSoundingType != PFC_SND) {
cleanupDialog(activeLoadSoundingType); // clean up
// before
// resetting
// activeLoadType
activeLoadSoundingType = PFC_SND;
pfcDialog.createPfcDialogContents();
dialogParent.pack();
dialogParent.layout(true);
dialogParent.redraw();
soundingTypeList.setSelection(PFC_SND);
}
} else if (selectedProduct
.equals(soundingTypeStringArray[ARCHIVE])) {
// System.out.println("ARCHIVE enter");
if (activeLoadSoundingType != ARCHIVE) {
cleanupDialog(activeLoadSoundingType);// clean up
// before
// resetting
// activeLoadType
activeLoadSoundingType = ARCHIVE;
NsharpHandleArchiveFile.openArchiveFile(shell);
close();
}
}
/*
* TBDGPD else
* if(selectedProduct.equals(soundingTypeStringArray
* [GPD_OBS_SND])){ if(activeLoadSoundingType !=
* GPD_OBS_SND){ cleanupDialog(activeLoadSoundingType);
* //clean up before resetting activeLoadType
* activeLoadSoundingType = GPD_OBS_SND;
* gpdObsDialog.createGpdObsDialogContents();
* //shell.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
* dialogParent.pack(); dialogParent.layout(true);
* dialogParent.redraw();
* soundingTypeList.setSelection(GPD_OBS_SND); } } else
* if(selectedProduct
* .equals(soundingTypeStringArray[GPD_PFC_SND])){
* if(activeLoadSoundingType != GPD_PFC_SND){
* cleanupDialog(activeLoadSoundingType); //clean up before
* resetting activeLoadType activeLoadSoundingType =
* GPD_PFC_SND; gpdPfcDialog.createGpdPfcDialogContents();
* //shell.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
* dialogParent.pack(); dialogParent.layout(true);
* dialogParent.redraw();
* soundingTypeList.setSelection(GPD_PFC_SND); } }
*/
}
}
});
}
public void cleanSndTypeList(){
if(soundingTypeList!= null){
soundingTypeList.removeListener(SWT.Selection, soundingTypeList.getListeners(SWT.Selection)[0]);
soundingTypeList.dispose();
soundingTypeList = null;
}
if(soundingTypeGp!=null){
soundingTypeGp.dispose();
soundingTypeGp=null;
}
}
private void cleanSelf(){
if(text1 != null){
text1.dispose();
text1 = null;
}
}
private void cleanupDialog(int activeLoadType){
switch (activeLoadType) {
case OBSER_SND:
obsDialog.cleanup();
break;
case MODEL_SND:
mdlDialog.cleanup();
break;
case PFC_SND:
pfcDialog.cleanup();
break;
case ACARS_SND:
if(text1 != null){
text1.dispose();
text1 = null;
}
if(acarsGp!= null){
acarsGp.dispose();
acarsGp = null;
}
break;
case ARCHIVE:
break;
default:
break;
}
}
public void setActiveLoadSoundingType(int activeLoadSoundingType) {
this.activeLoadSoundingType = activeLoadSoundingType;
}
public int getActiveLoadSoundingType() {
return activeLoadSoundingType;
}
}
public List<String> getPfcSelectedFileList() {
return pfcSelectedFileList;
}
public void setPfcSelectedFileList(List<String> pfcSelectedFileList) {
this.pfcSelectedFileList = pfcSelectedFileList;
}
public List<String> getPfcSelectedTimeList() {
return pfcSelectedTimeList;
}
public void setPfcSelectedTimeList(List<String> pfcSelectedTimeList) {
this.pfcSelectedTimeList = pfcSelectedTimeList;
}
public ArrayList<String> getObsSelectedTimeList() {
return obsSelectedTimeList;
}
public void setObsSelectedTimeList(ArrayList<String> obsSelectedTimeList) {
this.obsSelectedTimeList = obsSelectedTimeList;
}
public NcSoundingProfile.ObsSndType getActiveObsSndType() {
return activeObsSndType;
}
public void setActiveObsSndType(NcSoundingProfile.ObsSndType activeObsSndType) {
this.activeObsSndType = activeObsSndType;
}
public NcSoundingProfile.PfcSndType getActivePfcSndType() {
return activePfcSndType;
}
public void setActivePfcSndType(NcSoundingProfile.PfcSndType activePfcSndType) {
this.activePfcSndType = activePfcSndType;
}
public String getActiveMdlSndMdlType() {
return activeMdlSndMdlType;
}
public void setActiveMdlSndMdlType(String activeMdlSndMdlType) {
this.activeMdlSndMdlType = activeMdlSndMdlType;
}
public void cleanSndTypeList() {
if (soundingTypeList != null) {
soundingTypeList.removeListener(SWT.Selection,
soundingTypeList.getListeners(SWT.Selection)[0]);
soundingTypeList.dispose();
soundingTypeList = null;
}
if (soundingTypeGp != null) {
soundingTypeGp.dispose();
soundingTypeGp = null;
}
}
public List<String> getMdlSelectedFileList() {
return mdlSelectedFileList;
}
public void setMdlSelectedFileList(List<String> mdlSelectedFileList) {
this.mdlSelectedFileList = mdlSelectedFileList;
}
public List<String> getMdlSelectedTimeList() {
return mdlSelectedTimeList;
}
public void setMdlSelectedTimeList(List<String> mdlSelectedTimeList) {
this.mdlSelectedTimeList = mdlSelectedTimeList;
}
private void cleanSelf() {
static int count = 0;
if (text1 != null) {
text1.dispose();
text1 = null;
}
}
public static NsharpLoadDialog getAccess() {
return INSTANCE;
}
private void cleanupDialog(int activeLoadType) {
switch (activeLoadType) {
case OBSER_SND:
obsDialog.cleanup();
break;
case MODEL_SND:
mdlDialog.cleanup();
break;
case PFC_SND:
pfcDialog.cleanup();
break;
/*
* TBDGPD case GPD_OBS_SND: gpdObsDialog.cleanup(); break; case
* GPD_PFC_SND: gpdPfcDialog.cleanup(); break;
*/
case ARCHIVE:
break;
default:
break;
}
public NsharpLoadDialog(Shell parentShell)throws VizException {
super(parentShell);
// set modeless, so mouse button can be used by others
this.setShellStyle(SWT.TITLE | SWT.MODELESS | SWT.CLOSE |SWT.SHELL_TRIM);
//System.out.println("loadDia constructed");
activeLoadSoundingType = OBSER_SND;
}
}
public void setActiveLoadSoundingType(int activeLoadSoundingType) {
this.activeLoadSoundingType = activeLoadSoundingType;
}
/*
public int getActiveLoadSoundingType() {
return activeLoadSoundingType;
}
public List<String> getPfcSelectedFileList() {
return pfcSelectedFileList;
}
public void setPfcSelectedFileList(List<String> pfcSelectedFileList) {
this.pfcSelectedFileList = pfcSelectedFileList;
}
public List<String> getPfcSelectedTimeList() {
return pfcSelectedTimeList;
}
public void setPfcSelectedTimeList(List<String> pfcSelectedTimeList) {
this.pfcSelectedTimeList = pfcSelectedTimeList;
}
public ArrayList<String> getObsSelectedTimeList() {
return obsSelectedTimeList;
}
public void setObsSelectedTimeList(ArrayList<String> obsSelectedTimeList) {
this.obsSelectedTimeList = obsSelectedTimeList;
}
public ArrayList<String> getGpdSelectedTimeList() {
return gpdSelectedTimeList;
}
public void setGpdSelectedTimeList(ArrayList<String> gpdSelectedTimeList) {
this.gpdSelectedTimeList = gpdSelectedTimeList;
}
public NcSoundingProfile.ObsSndType getActiveObsSndType() {
return activeObsSndType;
}
public void setActiveObsSndType(
NcSoundingProfile.ObsSndType activeObsSndType) {
this.activeObsSndType = activeObsSndType;
}
public NcSoundingProfile.PfcSndType getActivePfcSndType() {
return activePfcSndType;
}
public void setActivePfcSndType(
NcSoundingProfile.PfcSndType activePfcSndType) {
this.activePfcSndType = activePfcSndType;
}
public String getActiveMdlSndMdlType() {
return activeMdlSndMdlType;
}
public void setActiveMdlSndMdlType(String activeMdlSndMdlType) {
this.activeMdlSndMdlType = activeMdlSndMdlType;
}
public String getActiveGpdProdName() {
return activeGpdProdName;
}
public void setActiveGpdProdName(String activeGpdProdName) {
this.activeGpdProdName = activeGpdProdName;
}
public List<String> getMdlSelectedFileList() {
return mdlSelectedFileList;
}
public void setMdlSelectedFileList(List<String> mdlSelectedFileList) {
this.mdlSelectedFileList = mdlSelectedFileList;
}
public List<String> getMdlSelectedTimeList() {
return mdlSelectedTimeList;
}
public void setMdlSelectedTimeList(List<String> mdlSelectedTimeList) {
this.mdlSelectedTimeList = mdlSelectedTimeList;
}
static int count = 0;
public static NsharpLoadDialog getAccess() {
return INSTANCE;
}
public NsharpLoadDialog(Shell parentShell) throws VizException {
super(parentShell);
// set modeless, so mouse button can be used by others
this.setShellStyle(SWT.TITLE | SWT.MODELESS | SWT.CLOSE
| SWT.SHELL_TRIM);
// System.out.println("loadDia constructed");
activeLoadSoundingType = OBSER_SND;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell( Shell shell ) {
super.configureShell( shell );
NsharpLoadDialog.shell = shell;
* @see
* org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets
* .Shell)
*/
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
NsharpLoadDialog.shell = shell;
shell.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
shell.setText( "Load" );
mb = new MessageBox(shell, SWT.ICON_WARNING
| SWT.OK);
shell.setText("Load");
mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
mb.setMessage( "User Input Error!");
Font font = shell.getFont();
FontData[] fontData = font.getFontData();
for (int i = 0; i < fontData.length; i++) {
fontData[i].setHeight(7);
//fontData[i].setName("courier");
}
newFont = new Font(font.getDevice(), fontData);
shell.setFont(newFont);
mb.setMessage("User Input Error!");
Font font = shell.getFont();
FontData[] fontData = font.getFontData();
for (int i = 0; i < fontData.length; i++) {
fontData[i].setHeight(7);
// fontData[i].setName("courier");
}
newFont = new Font(font.getDevice(), fontData);
shell.setFont(newFont);
}
private void createLoadContents(Composite parent) {
/* CHIN 1331
NsharpMapResource nsharpMapResource = NsharpMapResource.getOrCreateNsharpMapResource();//NsharpLoadDialog.getAccess().getNsharpMapResource();
nsharpMapResource.setPoints(null);
NsharpEditor editor = NsharpEditor.getActiveNsharpEditor();
if (editor != null) {
NsharpResourceHandler rsc = editor.getRscHandler();
rsc.cleanUpRsc();
editor.refresh();
}*/
dialogParent = parent;
obsDialog = new ObservedSoundingDialogContents(dialogParent);
pfcDialog = new PfcSoundingDialogContents(dialogParent);
mdlDialog = new ModelSoundingDialogContents(dialogParent);
switch(activeLoadSoundingType){
case MODEL_SND:
mdlDialog.createMdlDialogContents();
break;
case PFC_SND:
pfcDialog.createPfcDialogContents();
break;
default: //OBSER_SND is default for all other cases, also set activeLoadSoundingType to OBSER_SND
obsDialog.createObsvdDialogContents();
activeLoadSoundingType = OBSER_SND;
break;
}
soundingTypeList.setSelection(activeLoadSoundingType);
}
/**
* Creates the dialog area
*/
@Override
public Control createDialogArea(Composite parent) {
top = (Composite) super.createDialogArea(parent);
private void createLoadContents(Composite parent) {
/*
* CHIN 1331 NsharpMapResource nsharpMapResource =
* NsharpMapResource.getOrCreateNsharpMapResource
* ();//NsharpLoadDialog.getAccess().getNsharpMapResource();
* nsharpMapResource.setPoints(null); NsharpEditor editor =
* NsharpEditor.getActiveNsharpEditor(); if (editor != null) {
* NsharpResourceHandler rsc = editor.getRscHandler(); rsc.cleanUpRsc();
* editor.refresh(); }
*/
dialogParent = parent;
obsDialog = new NsharpObservedSoundingDialogContents(dialogParent);
pfcDialog = new NsharpPfcSoundingDialogContents(dialogParent);
mdlDialog = new NsharpModelSoundingDialogContents(dialogParent);
// TBDGPD gpdObsDialog = new
// NsharpGpdObsSoundingDialogContents(dialogParent);
// TBDGPD gpdPfcDialog = new
// NsharpGpdPfcSoundingDialogContents(dialogParent);
switch (activeLoadSoundingType) {
case MODEL_SND:
mdlDialog.createMdlDialogContents();
break;
case PFC_SND:
pfcDialog.createPfcDialogContents();
break;
/*
* TBDGPD case GPD_OBS_SND: gpdObsDialog.createGpdObsDialogContents();
* break; case GPD_PFC_SND: gpdPfcDialog.createGpdPfcDialogContents();
* break;
*/
default: // OBSER_SND is default for all other cases, also set
// activeLoadSoundingType to OBSER_SND
obsDialog.createObsvdDialogContents();
activeLoadSoundingType = OBSER_SND;
break;
}
// Create the main layout for the shell.
GridLayout mainLayout = new GridLayout(1, false);
mainLayout.marginHeight = 3;
mainLayout.marginWidth = 3;
//top.setLayout(mainLayout);
//System.out.println("createDialogArea called");
// Initialize all of the menus, controls, and layouts
createLoadContents(top);
//shell.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
if(waitCursor==null)
waitCursor = new Cursor( top.getDisplay(), SWT.CURSOR_WAIT);
return top;
}
soundingTypeList.setSelection(activeLoadSoundingType);
@Override
public int open( ) {
//System.out.println("loadDia opened");
if ( this.getShell() == null ){
this.create();
}
this.getShell().setLocation(this.getShell().getParent().getLocation().x+1100,
this.getShell().getParent().getLocation().y+200);
NsharpMapResource.bringMapEditorToTop();
return super.open();
}
@Override
public boolean close() {
NsharpMapResource nsharpMapResource = NsharpMapResource.getMapRsc();
if(nsharpMapResource!=null)
nsharpMapResource.setPoints(null);
//System.out.println("loadDia closed");
cleanSelf();
cleanupDialog(activeLoadSoundingType);
//INSTANCE = null;
if(waitCursor!=null)
waitCursor.dispose();
waitCursor=null;
newFont.dispose();
return (super.close());
/**
* Creates the dialog area
*/
@Override
public Control createDialogArea(Composite parent) {
top = (Composite) super.createDialogArea(parent);
// Create the main layout for the shell.
GridLayout mainLayout = new GridLayout(1, false);
mainLayout.marginHeight = 3;
mainLayout.marginWidth = 3;
// top.setLayout(mainLayout);
// System.out.println("createDialogArea called");
// Initialize all of the menus, controls, and layouts
createLoadContents(top);
// shell.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
if (waitCursor == null)
waitCursor = new Cursor(top.getDisplay(), SWT.CURSOR_WAIT);
return top;
}
public boolean closeDiaOnly() {
cleanSelf();
return (super.close());
}
//Only use Cancel button but NOT ok button
@Override
public void createButtonsForButtonBar(Composite parent) {
// create Cancel buttons by default, but use close label
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CLOSE_LABEL, false);
//cancelBtn.setBounds(cancelBtn.getBounds().x, cancelBtn.getBounds().y+DIALOG_HEIGHT, 20, 10);
//System.out.println("createButtonsForButtonBar cancelBtn bound"+cancelBtn.getBounds());
}
@Override
public int open() {
// System.out.println("loadDia opened");
public static NsharpLoadDialog getInstance( Shell parShell){
//System.out.println("getInstance called");
if ( INSTANCE == null ){
try {
INSTANCE = new NsharpLoadDialog( parShell );
//System.out.println("new load dialog INSTANCE created");
} catch (VizException e) {
e.printStackTrace();
}
}
return INSTANCE;
}
if (this.getShell() == null) {
this.create();
}
this.getShell().setLocation(
this.getShell().getParent().getLocation().x + 1100,
this.getShell().getParent().getLocation().y + 200);
NsharpMapResource.bringMapEditorToTop();
return super.open();
//public void setShellSize(boolean big){
// if(big == true) {
// }
// else {
// shell.setSize(DIALOG_WIDTH, DIALOG_HEIGHT-100);
// }
//}
public void startWaitCursor(){
if(waitCursor!=null)
top.setCursor(waitCursor);
}
public void stopWaitCursor(){
top.setCursor(null);
}
}
@Override
public boolean close() {
NsharpMapResource nsharpMapResource = NsharpMapResource.getMapRsc();
if (nsharpMapResource != null)
nsharpMapResource.setPoints(null);
// System.out.println("loadDia closed");
cleanSelf();
cleanupDialog(activeLoadSoundingType);
// INSTANCE = null;
if (waitCursor != null)
waitCursor.dispose();
waitCursor = null;
newFont.dispose();
return (super.close());
}
public boolean closeDiaOnly() {
cleanSelf();
return (super.close());
}
// Only use Cancel button but NOT ok button
@Override
public void createButtonsForButtonBar(Composite parent) {
// create Cancel buttons by default, but use close label
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CLOSE_LABEL, false);
// cancelBtn.setBounds(cancelBtn.getBounds().x,
// cancelBtn.getBounds().y+DIALOG_HEIGHT, 20, 10);
// System.out.println("createButtonsForButtonBar cancelBtn bound"+cancelBtn.getBounds());
}
public static NsharpLoadDialog getInstance(Shell parShell) {
// System.out.println("getInstance called");
if (INSTANCE == null) {
try {
INSTANCE = new NsharpLoadDialog(parShell);
// System.out.println("new load dialog INSTANCE created");
} catch (VizException e) {
e.printStackTrace();
}
}
return INSTANCE;
}
public void startWaitCursor() {
if (waitCursor != null)
top.setCursor(waitCursor);
}
public void stopWaitCursor() {
top.setCursor(null);
}
}

View file

@ -0,0 +1,868 @@
/**
*
* gov.noaa.nws.ncep.ui.nsharp.view.ModelSoundingDialogContents
*
* This java class performs the NSHARP NsharpLoadDialog functions.
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------- ------- -------- -----------
* 01/2011 229 Chin Chen Initial coding
*
* </pre>
*
* @author Chin Chen
* @version 1.0
*/
package gov.noaa.nws.ncep.ui.nsharp.view;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingCube;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingLayer;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingProfile;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingTimeLines;
import gov.noaa.nws.ncep.ui.nsharp.NsharpConfigManager;
import gov.noaa.nws.ncep.ui.nsharp.NsharpConfigStore;
import gov.noaa.nws.ncep.ui.nsharp.NsharpConstants;
import gov.noaa.nws.ncep.ui.nsharp.NsharpGraphProperty;
import gov.noaa.nws.ncep.ui.nsharp.NsharpGridInventory;
import gov.noaa.nws.ncep.ui.nsharp.NsharpStationInfo;
import gov.noaa.nws.ncep.ui.nsharp.SurfaceStationPointData;
import gov.noaa.nws.ncep.ui.nsharp.display.NsharpEditor;
import gov.noaa.nws.ncep.ui.nsharp.display.map.NsharpMapResource;
import gov.noaa.nws.ncep.ui.nsharp.display.rsc.NsharpResourceHandler;
import gov.noaa.nws.ncep.ui.nsharp.natives.NsharpDataHandling;
import gov.noaa.nws.ncep.viz.common.soundingQuery.NcSoundingQuery;
import java.sql.Timestamp;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
import com.vividsolutions.jts.geom.Coordinate;
public class NsharpModelSoundingDialogContents {
private Composite parent;
private org.eclipse.swt.widgets.List modelTypeList = null,
availableFileList = null, sndTimeList = null;
// timeLineToFileMap maps time line (rangeStart time in sndTimeList) to
// available file (reftime in availableFileList)
private Map<String, String> timeLineToFileMap = new HashMap<String, String>();
// soundingLysLstMap maps "lat;lon timeline" string to its queried sounding
// layer list
private Map<String, List<NcSoundingLayer>> soundingLysLstMap = new HashMap<String, List<NcSoundingLayer>>();
private Group modelTypeGp, bottomGp, availableFileGp, sndTimeListGp, topGp,
locationMainGp;
private Button timeBtn, latlonBtn, stationBtn, loadBtn;
private Text locationText;
private Label locationLbl;
private boolean timeLimit = false;
private NsharpLoadDialog ldDia;
private Font newFont;
private List<String> selectedFileList = new ArrayList<String>();
private List<String> selectedTimeList = new ArrayList<String>();
// private NcSoundingProfile.MdlSndType currentSndType =
// NcSoundingProfile.MdlSndType.NONE;
private float lat, lon;
private String stnStr = "";
private final String GOOD_LATLON_STR = " A good input looked like this:\n 38.95;-77.45 or 38.95,-77.45";
private final String GOOD_STN_STR = " A good input looked like this:\n GAI or gai";
String gribDecoderName = "grid";// NcSoundingQuery.NCGRIB_PLUGIN_NAME;
private String selectedModel = "";
// private DBType currentDb = DBType.NCGRIB;
private static final String SND_TIMELINE_NOT_AVAIL_STRING = "No Sounding Time for Nsharp";
public enum LocationType {
LATLON, STATION
}
public enum DBType {
GRIB, NCGRIB
}
private LocationType currentLocType = LocationType.LATLON;
public LocationType getCurrentLocType() {
return currentLocType;
}
public Text getLocationText() {
return locationText;
}
public NsharpModelSoundingDialogContents(Composite parent) {
this.parent = parent;
ldDia = NsharpLoadDialog.getAccess();
newFont = ldDia.getNewFont();
/*
* if( VizPerspectiveListener.getCurrentPerspectiveManager()!= null){
* if(
* VizPerspectiveListener.getCurrentPerspectiveManager().getPerspectiveId
* ().equals(NmapCommon.NatlCntrsPerspectiveID)) gribDecoderName =
* NcSoundingQuery.NCGRIB_PLUGIN_NAME; else gribDecoderName =
* NcSoundingQuery.GRIB_PLUGIN_NAME;
*
*
* //for testing //gribDecoderName = NcSoundingQuery.GRIB_PLUGIN_NAME;
* //System.out.println("perspective id = " +
* VizPerspectiveListener.getCurrentPerspectiveManager
* ().getPerspectiveId()); }
*/
}
private void createMDLAvailableFileList() {
if (sndTimeList != null)
sndTimeList.removeAll();
if (availableFileList != null)
availableFileList.removeAll();
HashMap<String, RequestConstraint> rcMap = new HashMap<String, RequestConstraint>();
rcMap.put("info.datasetId", new RequestConstraint(selectedModel));
ldDia.startWaitCursor();
ArrayList<String> queryRsltsList1 = NsharpGridInventory.getInstance()
.searchInventory(rcMap, "dataTime");// .refTime" );
/*
* Chin Note: with this query, the returned string has this format,
* "grid/ruc13/2012-01-17_16:00:00.0(6)xxxxx" We will have to strip off
* "ncgrib/ruc13/" and ":00:00.0(6)xxxxx", also replace "_" with space,
* to get grid file name like this "2012-01-17 16".
*/
/*
* fixMarkA Chin 12/11/2013: at this moment, the returned string format
* is like this, 2012-01-17_16:00:00.0_(6) We will have to strip off
* ":00:00.0_(6)", also replace first "_" with space, to get grid file
* name like this "2012-01-17 16". fixMarkA
*/
// fixMarkAchar fileSep = File.pathSeparatorChar;
// fixMarkA String header = "grid"+fileSep+ selectedModel +fileSep;
if (queryRsltsList1 != null && !queryRsltsList1.isEmpty()) {
Collections.sort(queryRsltsList1, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(queryRsltsList1);
for (String queryRslt : queryRsltsList1) {
// fixMarkA queryRslt = queryRslt.substring(header.length());
String refTime = queryRslt.substring(0, queryRslt.indexOf('_'));
refTime = refTime
+ " "
+ queryRslt.substring(queryRslt.indexOf('_') + 1,
queryRslt.indexOf(':'));
// System.out.println("ret for disp="+refTime );
// Chin: a same refTime may be returned more than once.
int index = availableFileList.indexOf(refTime);
if (index == -1) // index = -1 means it is not in the list
availableFileList.add(refTime);
}
}
ldDia.stopWaitCursor();
}
/*
* private void createMDLAvailableFileListOld() { if(sndTimeList!=null)
* sndTimeList.removeAll(); if(availableFileList!=null)
* availableFileList.removeAll();
*
* //query using NcSoundingQuery class to query NcSoundingTimeLines
* timeLines = NcSoundingQuery.mdlSoundingTimeLineQuery(selectedModel,
* gribDecoderName); if(timeLines!= null && timeLines.getTimeLines() !=
* null){ ldDia.startWaitCursor(); for(Object timeLine :
* timeLines.getTimeLines()){ Timestamp reftime = (Timestamp)timeLine;
* if(reftime != null){ //need to format reftime to GMT time string.
* Timestamp.toString produce a local time Not GMT time Calendar cal =
* Calendar.getInstance(TimeZone.getTimeZone("GMT"));
* cal.setTimeInMillis(reftime.getTime()); String gmtTimeStr =
* String.format("%1$tY-%1$tm-%1$td %1$tH", cal);
* //System.out.println("GMT time " + gmtTimeStr);
* availableFileList.add(gmtTimeStr);
*
* }
*
* } ldDia.stopWaitCursor(); } else
* System.out.println("SQL: query return null"); }
*/
private void createMDLSndTimeList(List<String> selectedFlLst) {
if (selectedFlLst.size() <= 0)
return;
if (sndTimeList != null)
sndTimeList.removeAll();
if (timeLineToFileMap != null)
timeLineToFileMap.clear();
int nameLen = Math.min(6, selectedModel.length());
String modelName = selectedModel.substring(0, nameLen);
// query using NcSoundingQuery to query
DateFormatSymbols dfs = new DateFormatSymbols();
String[] defaultDays = dfs.getShortWeekdays();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
ldDia.startWaitCursor();
for (int i = 0; i < selectedFlLst.size(); i++) {
String fl = selectedFlLst.get(i);
long reftimeMs = NcSoundingQuery.convertRefTimeStr(fl);
NcSoundingTimeLines timeLines = NcSoundingQuery
.mdlSoundingRangeTimeLineQuery(selectedModel, fl,
gribDecoderName);
if (timeLines != null && timeLines.getTimeLines().length > 0) {
for (Object obj : timeLines.getTimeLines()) {
Timestamp rangestart = (Timestamp) obj;
// need to format rangestart to GMT time string.
// Timestamp.toString produce a local time Not GMT time
cal.setTimeInMillis(rangestart.getTime());
long vHour = (cal.getTimeInMillis() - reftimeMs) / 3600000;
String dayOfWeek = defaultDays[cal
.get(Calendar.DAY_OF_WEEK)];
// String gmtTimeStr =
// String.format("%1$ty%1$tm%1$td/%1$tH%1$tMV%2$03d %3$s",
// cal, vHour,modelName);
String gmtTimeStr = String.format(
"%1$ty%1$tm%1$td/%1$tH(%4$s)V%2$03d %3$s", cal,
vHour, modelName, dayOfWeek);
if (sndTimeList.indexOf(gmtTimeStr) != -1) {
// this indicate that gmtTimeStr is already in the
// sndTimeList, then we dont need to add it to list
// again.
continue;
}
// System.out.println("GMT time " + gmtTimeStr);
if (!timeLimit) {
sndTimeList.add(gmtTimeStr);
timeLineToFileMap.put(gmtTimeStr, fl);
} else {
int hour = cal.get(Calendar.HOUR_OF_DAY);
if ((hour == 0) || (hour == 12)) {
sndTimeList.add(gmtTimeStr);
timeLineToFileMap.put(gmtTimeStr, fl);
}
}
}
}
}
if (sndTimeList != null && sndTimeList.getItemCount() <= 0) {
sndTimeList.add(SND_TIMELINE_NOT_AVAIL_STRING);
}
ldDia.stopWaitCursor();
}
private void queryAndLoadData(boolean stnQuery)
throws java.text.ParseException {
soundingLysLstMap.clear();
ldDia.startWaitCursor();
Timestamp refTime = null;
// Chin Note: Since NcGrib/Grib HDF5 data file is created based on a
// forecast time line, we can not query
// more than one time line at one time as Edex server just could not
// support such query at one shot.
// This is not the case of PFC sounding (modelsounding db). It has all
// time lines of one forecast report
// saved in one file. Therefore, PFC query is much faster.
for (String timeLine : selectedTimeList) {
// avail file, ie. its refTime
String selectedFileStr = timeLineToFileMap.get(timeLine);
// start FixMark:nearByStnCompSnd
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
df.parse(selectedFileStr);
Calendar cal = df.getCalendar();
int offset = cal.get(Calendar.ZONE_OFFSET)
+ cal.get(Calendar.DST_OFFSET) / (60 * 1000);
refTime = new Timestamp(cal.getTimeInMillis() + offset);
// end FixMark:nearByStnCompSnd
String rangeStartStr = NcSoundingQuery
.convertSoundTimeDispStringToRangeStartTimeFormat(timeLine);
float[][] latLon = { { lat, lon } };
NcSoundingCube cube = NcSoundingQuery.mdlSoundingQueryByLatLon(
selectedFileStr + ":00:00", rangeStartStr, latLon,
gribDecoderName, selectedModel, false, "-1");
if (cube != null
&& cube.getRtnStatus() == NcSoundingCube.QueryStatus.OK) {
// System.out.println("mdlSoundingQueryByLatLon returnd ok");
NcSoundingProfile sndPf = cube.getSoundingProfileList().get(0);
List<NcSoundingLayer> rtnSndLst = sndPf.getSoundingLyLst();
if (rtnSndLst != null && rtnSndLst.size() > 1) {
// Remove sounding layers that not used by NSHARP
// System.out.println("numbe of layer returned from query ="+
// rtnSndLst.size());
rtnSndLst = NsharpDataHandling.organizeSoundingDataForShow(
rtnSndLst, sndPf.getStationElevation());
// minimum rtnSndList size will be 2 (50 & 75 mb layers),
// but that is not enough
// We need at least 2 regular layers for plotting
if (rtnSndLst != null && rtnSndLst.size() > 4) { // after
// organized,
// if size
// is still
// good
if (!stnQuery) {
soundingLysLstMap.put(lat + "/" + lon + " "
+ timeLine, rtnSndLst);
// System.out.println(lat+";"+lon+" "+timeLine);
} else {
// replaced space to _ in stnStr.
String stnStrPacked = stnStr.replace(" ", "_");
soundingLysLstMap.put(
stnStrPacked + " " + timeLine, rtnSndLst);
// System.out.println(stnStr+" "+timeLine);
}
continue;
}
}
// code to this point means query result is not good
NsharpLoadDialog ldDia = NsharpLoadDialog.getAccess();
if (!stnQuery) {
ldDia.setAndOpenMb("Sounding query with lat/lon (" + lat
+ "/" + lon + ") at " + timeLine
+ ": Returned\n But without vlaid data");
} else {
ldDia.setAndOpenMb("Sounding query with stn " + stnStr
+ "at lat/lon (" + lat + "/" + lon + ") at "
+ timeLine + ": Returned\n But without vlaid data");
}
// return;
} else {
if (!stnQuery) {
System.out.println("mdlsoundingQueryByLatLon failed");
NsharpLoadDialog ldDia = NsharpLoadDialog.getAccess();
if (cube != null)
ldDia.setAndOpenMb("Sounding query with lat/lon ("
+ lat + "/" + lon + ") at " + timeLine
+ ": failed\nError status:"
+ cube.getRtnStatus().toString());
else
ldDia.setAndOpenMb("Sounding query with lat/lon ("
+ lat + "/" + lon + ") at " + timeLine
+ ": failed\nError status: NULL returned");
} else {
System.out.println("mdlsoundingQueryByStn failed");
NsharpLoadDialog ldDia = NsharpLoadDialog.getAccess();
if (cube != null)
ldDia.setAndOpenMb("Sounding query with stn " + stnStr
+ "at lat/lon (" + lat + "/" + lon + ") at "
+ timeLine + ": failed\nError status:"
+ cube.getRtnStatus().toString());
else
ldDia.setAndOpenMb("Sounding query with stn " + stnStr
+ "at lat/lon (" + lat + "/" + lon + ") at "
+ timeLine
+ ": failed\nError status: NULL returned");
}
// return;
}
}
ldDia.stopWaitCursor();
NsharpEditor skewtEdt = NsharpEditor.createOrOpenEditor();
NsharpResourceHandler skewRsc = skewtEdt.getRscHandler();
// create station info structure
NsharpStationInfo stnInfo = new NsharpStationInfo();
stnInfo.setSndType(selectedModel);
stnInfo.setLatitude(lat);
stnInfo.setLongitude(lon);
stnInfo.setStnId(stnStr);
stnInfo.setReftime(refTime);// FixMark:nearByStnCompSnd
skewRsc.addRsc(soundingLysLstMap, stnInfo);
skewRsc.setSoundingType(selectedModel);
NsharpEditor.bringEditorToTop();
}
private void createModelTypeList() {
if (modelTypeList != null)
modelTypeList.removeAll();
if (sndTimeList != null)
sndTimeList.removeAll();
if (availableFileList != null)
availableFileList.removeAll();
ldDia.startWaitCursor();
List<String> cfgList = null;
NsharpConfigManager configMgr = NsharpConfigManager.getInstance();
NsharpConfigStore configStore = configMgr
.retrieveNsharpConfigStoreFromFs();
NsharpGraphProperty graphConfigProperty = configStore
.getGraphProperty();
cfgList = graphConfigProperty.getGribModelTypeList();
HashMap<String, RequestConstraint> rcMap = new HashMap<String, RequestConstraint>();
rcMap.put("pluginName", new RequestConstraint("grid"));
ArrayList<String> queryRsltsList = NsharpGridInventory.getInstance()
.searchInventory(rcMap, "info.datasetId");
/*
* Chin Note: with this query, the returned string has this format,
* "ncgrib/gfsP5" We will have to strip off "ncgrib/" to get model name
* like this "gfsP5".
*/
/*
* fixMarkB Chin: 12/11/2013 at this moment, the returned string has
* this format, "gfsP5", just he model name. Therefore, we do not have
* to process on it.
*/
if (queryRsltsList != null && !queryRsltsList.isEmpty()) {
Collections.sort(queryRsltsList, String.CASE_INSENSITIVE_ORDER);
for (String queryRslt : queryRsltsList) {
// System.out.println("model name:"+queryRslt );
String modelName = queryRslt;// fixMarkB .substring(
// "grid/".length() );
if (cfgList != null && cfgList.size() > 0) {
if (cfgList.contains(modelName))
modelTypeList.add(modelName);
} else
modelTypeList.add(modelName);
}
}
ldDia.stopWaitCursor();
}
private void handleAvailFileListSelection() {
String selectedFile = null;
if (availableFileList.getSelectionCount() > 0) {
selectedFileList.clear();
for (int i = 0; i < availableFileList.getSelectionCount(); i++) {
selectedFile = availableFileList.getSelection()[i];
// System.out.println("selected sounding file is " +
// selectedFile);
selectedFileList.add(selectedFile);
}
createMDLSndTimeList(selectedFileList);
}
}
private void handleSndTimeSelection() {
String selectedSndTime = null;
if (sndTimeList.getSelectionCount() > 0
&& sndTimeList.getSelection()[0]
.equals(SND_TIMELINE_NOT_AVAIL_STRING) == false) {
selectedTimeList.clear();
for (int i = 0; i < sndTimeList.getSelectionCount(); i++) {
selectedSndTime = sndTimeList.getSelection()[i];
// System.out.println("selected sounding time is " +
// selectedSndTime);
selectedTimeList.add(selectedSndTime);
}
NsharpMapResource.bringMapEditorToTop();
}
}
public void createMdlDialogContents() {
topGp = new Group(parent, SWT.SHADOW_ETCHED_IN);
topGp.setLayout(new GridLayout(2, false));
selectedModel = ldDia.getActiveMdlSndMdlType();
ldDia.createSndTypeList(topGp);
modelTypeGp = new Group(topGp, SWT.SHADOW_ETCHED_IN);
modelTypeGp.setText("Model Type");
modelTypeGp.setFont(newFont);
modelTypeList = new org.eclipse.swt.widgets.List(modelTypeGp,
SWT.BORDER | SWT.V_SCROLL);
modelTypeList.setBounds(modelTypeGp.getBounds().x,
modelTypeGp.getBounds().y + NsharpConstants.labelGap,
NsharpConstants.filelistWidth, NsharpConstants.listHeight);
// query to get and add available sounding models from DB
modelTypeList.setFont(newFont);
createModelTypeList();
// create a selection listener to handle user's selection on list
modelTypeList.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
if (modelTypeList.getSelectionCount() > 0) {
selectedModel = modelTypeList.getSelection()[0];
ldDia.setActiveMdlSndMdlType(selectedModel);
// System.out.println("selected sounding model is " +
// selectedModel);
createMDLAvailableFileList();
}
}
});
availableFileGp = new Group(topGp, SWT.SHADOW_ETCHED_IN);
availableFileGp.setText("Available Grid files:");
availableFileGp.setFont(newFont);
availableFileList = new org.eclipse.swt.widgets.List(availableFileGp,
SWT.BORDER /* FixMark:nearByStnCompSnd| SWT.MULTI */
| SWT.V_SCROLL);
availableFileList.setBounds(availableFileGp.getBounds().x,
availableFileGp.getBounds().y + NsharpConstants.labelGap,
NsharpConstants.filelistWidth, NsharpConstants.listHeight);// *32/5
// );
availableFileList.setFont(newFont);
// create a selection listener to handle user's selection on list
availableFileList.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
handleAvailFileListSelection();
}
});
// create Sounding Times widget list
sndTimeListGp = new Group(topGp, SWT.SHADOW_ETCHED_IN);
sndTimeListGp.setText("Sounding Times:");
sndTimeListGp.setFont(newFont);
sndTimeList = new org.eclipse.swt.widgets.List(sndTimeListGp,
SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
sndTimeList.removeAll();
sndTimeList.setFont(newFont);
sndTimeList.setBounds(sndTimeListGp.getBounds().x,
sndTimeListGp.getBounds().y + NsharpConstants.labelGap,
NsharpConstants.listWidth, NsharpConstants.listHeight);// *32/5);
sndTimeList.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
handleSndTimeSelection();
}
});
timeBtn = new Button(topGp, SWT.CHECK | SWT.BORDER);
timeBtn.setText("00Z and 12Z only");
timeBtn.setEnabled(true);
timeBtn.setFont(newFont);
timeBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
if (timeLimit)
timeLimit = false;
else
timeLimit = true;
// refresh sounding list if file type is selected already
if (selectedModel != null && selectedFileList.size() > 0) {
createMDLSndTimeList(selectedFileList);
}
}
});
locationMainGp = new Group(parent, SWT.SHADOW_ETCHED_IN);
locationMainGp.setLayout(new GridLayout(5, false));
locationMainGp.setText("Location");
locationMainGp.setFont(newFont);
latlonBtn = new Button(locationMainGp, SWT.RADIO | SWT.BORDER);
latlonBtn.setText("Lat/Lon");
latlonBtn.setFont(newFont);
latlonBtn.setEnabled(true);
latlonBtn.setSelection(true);
latlonBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
currentLocType = LocationType.LATLON;
locationText.setText("");
}
});
stationBtn = new Button(locationMainGp, SWT.RADIO | SWT.BORDER);
stationBtn.setText("Station");
stationBtn.setEnabled(true);
stationBtn.setFont(newFont);
stationBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
currentLocType = LocationType.STATION;
locationText.setText("");
}
});
// locationInputGp = new Group(locationMainGp,SWT.SHADOW_ETCHED_IN);
locationLbl = new Label(locationMainGp, SWT.NONE | SWT.BORDER);
// locationLbl.setBounds(latlonBtn.getBounds().x,
// latlonBtn.getBounds().y + latlonBtn.getBounds().height+
// NsharpConstants.btnGapY,
// bottomGp.getBounds().width/2,NsharpConstants.btnHeight);
locationLbl.setText("Location:");
locationLbl.setFont(newFont);
locationText = new Text(locationMainGp, SWT.BORDER | SWT.SINGLE);
GridData data1 = new GridData(SWT.FILL, SWT.FILL, true, true);
locationText.setLayoutData(data1);
// locationText.setBounds(stationBtn.getBounds().x,
// locationLbl.getBounds().y,450,NsharpConstants.btnHeight);
locationText.setTextLimit(15);
locationText.setFont(newFont);
locationText.addListener(SWT.Verify, new Listener() {
public void handleEvent(Event e) {
String userInputStr = e.text;
if (userInputStr.length() > 0) {
if (currentLocType == LocationType.LATLON) {
// to make sure user enter digits and separated by ";"
// or ","only, if lat/lon is used
// System.out.println("user input str" + userInputStr);
if (userInputStr.length() == 1) {
char inputChar = userInputStr.charAt(0);
if (!('0' <= inputChar && inputChar <= '9')
&& inputChar != ';' && inputChar != ','
&& inputChar != '-' && inputChar != '.') {
e.doit = false;
return;
}
}
} else {
// do nothing when station type
}
}
}
});
loadBtn = new Button(locationMainGp, SWT.PUSH);
loadBtn.setText("Load ");
loadBtn.setFont(newFont);
loadBtn.setEnabled(true);
loadBtn.setBounds(locationMainGp.getBounds().x
+ NsharpConstants.btnGapX, locationLbl.getBounds().y
+ locationLbl.getBounds().height + NsharpConstants.btnGapY,
NsharpConstants.btnWidth, NsharpConstants.btnHeight);
loadBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
NsharpLoadDialog ldDia = NsharpLoadDialog.getAccess();
if (selectedTimeList != null && selectedTimeList.size() == 0) {
ldDia.setAndOpenMb("Time line(s) is not selected!\n Can not load data!");
return;
}
String textStr = locationText.getText();
if ((textStr != null) && !(textStr.isEmpty())) {
// textStr = textStr.trim();
if (currentLocType == LocationType.LATLON) {
// to make sure user enter digits and separated by ";"
// or ","only, if lat/lon is used
int dividerIndex = textStr.indexOf(';');
boolean indexFound = false;
if (dividerIndex != -1)
indexFound = true;
if (indexFound == false) {
dividerIndex = textStr.indexOf(',');
if (dividerIndex != -1)
indexFound = true;
}
if (indexFound == true) {
try {
lat = Float.parseFloat(textStr.substring(0,
dividerIndex));
lon = Float.parseFloat(textStr
.substring(dividerIndex + 1));
if (lat > 90 || lat < -90 || lon > 180
|| lon < -180) {
// System.out.println("bad lat/lon entered ="
// + textStr);
ldDia.setAndOpenMb("lat/lon out of range ("
+ textStr + ") entered!\n"
+ GOOD_LATLON_STR);
locationText.setText("");
return;
}
// System.out.println("user enter lat " + lat+
// " lon " + lon);
queryAndLoadData(false);
} catch (Exception e) {
System.out
.println("queryAndLoadData failed at (1)"
+ textStr);
// ldDia.setAndOpenMb("Bad lat/lon ("+textStr+") entered!\n"+GOOD_LATLON_STR);
// locationText.setText("");
return;
}
} else {
// System.out.println("2 bad lat/lon entered =" +
// textStr);
ldDia.setAndOpenMb("Bad lat/lon (" + textStr
+ ") entered!\n" + GOOD_LATLON_STR);
locationText.setText("");
return;
}
} else if (currentLocType == LocationType.STATION) {
// query station lat /lon
try {
textStr = textStr.trim(); // user may start with a
// space before enter a
// station id
stnStr = textStr.toUpperCase(Locale.getDefault());
Coordinate co = SurfaceStationPointData
.getStnCoordinate(stnStr);
lat = (float) co.y;
lon = (float) co.x;
// System.out.println("user enter station ="+
// stnStr+" length="+ stnStr.length()+" lat " + lat+
// " lon " + lon);
if (lat == SurfaceStationPointData.DEFAULT_LATLON) {
// System.out.println("bad stn id entered =" +
// textStr);
ldDia.setAndOpenMb("Bad station id (" + textStr
+ ") entered!\n" + GOOD_STN_STR);
locationText.setText("");
return;
}
queryAndLoadData(true);
} catch (Exception e) {
System.out.println("queryAndLoadData failed at (2)"
+ textStr);
// ldDia.setAndOpenMb("Bad lat/lon ("+textStr+") entered!\n"+GOOD_LATLON_STR);
// locationText.setText("");
return;
}
}
// ldDia.close();
}
}
});
if (selectedModel != null && selectedModel.equals("") == false) {
String[] selectedModelArray = { selectedModel };
modelTypeList.setSelection(selectedModelArray);
createMDLAvailableFileList();
selectedFileList = ldDia.getMdlSelectedFileList();
Object[] selFileObjectArray = selectedFileList.toArray();
String[] selFileStringArray = Arrays.copyOf(selFileObjectArray,
selFileObjectArray.length, String[].class);
availableFileList.setSelection(selFileStringArray);
handleAvailFileListSelection();
selectedTimeList = ldDia.getMdlSelectedTimeList();
Object[] selTimeObjectArray = selectedTimeList.toArray();
String[] selTimeStringArray = Arrays.copyOf(selTimeObjectArray,
selTimeObjectArray.length, String[].class);
sndTimeList.setSelection(selTimeStringArray);
handleSndTimeSelection();
}
}
public void cleanup() {
/*
* if(gfsBtn != null){ gfsBtn.removeListener(SWT.MouseUp,
* gfsBtn.getListeners(SWT.MouseUp)[0]); gfsBtn.dispose(); gfsBtn =
* null; } if(namBtn != null){ namBtn.removeListener(SWT.MouseUp,
* namBtn.getListeners(SWT.MouseUp)[0]); namBtn.dispose(); namBtn =
* null; } if(ngmBtn != null){ ngmBtn.removeListener(SWT.MouseUp,
* ngmBtn.getListeners(SWT.MouseUp)[0]); ngmBtn.dispose(); ngmBtn =
* null; } if(ruc2Btn != null){ ruc2Btn.removeListener(SWT.MouseUp,
* ruc2Btn.getListeners(SWT.MouseUp)[0]); ruc2Btn.dispose(); ruc2Btn =
* null; } if(ukmetBtn != null){ ukmetBtn.removeListener(SWT.MouseUp,
* ukmetBtn.getListeners(SWT.MouseUp)[0]); ukmetBtn.dispose(); ukmetBtn
* = null; }
*/
if (modelTypeList != null) {
if (modelTypeList.getListeners(SWT.Selection).length > 0)
modelTypeList.removeListener(SWT.Selection,
modelTypeList.getListeners(SWT.Selection)[0]);
modelTypeList.dispose();
modelTypeList = null;
}
if (modelTypeGp != null) {
modelTypeGp.dispose();
modelTypeGp = null;
}
if (timeBtn != null) {
timeBtn.removeListener(SWT.MouseUp,
timeBtn.getListeners(SWT.MouseUp)[0]);
timeBtn.dispose();
timeBtn = null;
}
NsharpLoadDialog ldDia = NsharpLoadDialog.getAccess();
ldDia.cleanSndTypeList();
if (availableFileList != null) {
availableFileList.removeListener(SWT.Selection,
availableFileList.getListeners(SWT.Selection)[0]);
availableFileList.dispose();
availableFileList = null;
}
if (availableFileGp != null) {
availableFileGp.dispose();
availableFileGp = null;
}
if (sndTimeList != null) {
sndTimeList.removeListener(SWT.Selection,
sndTimeList.getListeners(SWT.Selection)[0]);
sndTimeList.dispose();
sndTimeList = null;
}
if (sndTimeListGp != null) {
sndTimeListGp.dispose();
sndTimeListGp = null;
}
if (bottomGp != null) {
bottomGp.dispose();
bottomGp = null;
}
if (topGp != null) {
topGp.dispose();
topGp = null;
}
if (loadBtn != null) {
loadBtn.removeListener(SWT.MouseUp,
loadBtn.getListeners(SWT.MouseUp)[0]);
loadBtn.dispose();
loadBtn = null;
}
if (stationBtn != null) {
stationBtn.removeListener(SWT.MouseUp,
stationBtn.getListeners(SWT.MouseUp)[0]);
stationBtn.dispose();
stationBtn = null;
}
if (latlonBtn != null) {
latlonBtn.removeListener(SWT.MouseUp,
latlonBtn.getListeners(SWT.MouseUp)[0]);
latlonBtn.dispose();
latlonBtn = null;
}
if (locationText != null) {
locationText.removeListener(SWT.Verify,
locationText.getListeners(SWT.Verify)[0]);
locationText.dispose();
locationText = null;
}
if (locationLbl != null) {
locationLbl.dispose();
locationLbl = null;
}
if (locationMainGp != null) {
locationMainGp.dispose();
locationMainGp = null;
}
/*
* if(newTabBtn != null){ newTabBtn.removeListener(SWT.MouseUp,
* newTabBtn.getListeners(SWT.MouseUp)[0]); newTabBtn.dispose();
* newTabBtn = null; }
*/
}
}

View file

@ -0,0 +1,391 @@
/**
*
* gov.noaa.nws.ncep.ui.nsharp.view.ObservedSoundingDialogContents
*
* This java class performs the NSHARP NsharpLoadDialog functions.
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------- ------- -------- -----------
* 01/2011 229 Chin Chen Initial coding
* 09/14/2011 457 S. Gurung Renamed H5UAIR to NCUAIR
*
* </pre>
*
* @author Chin Chen
* @version 1.0
*/
package gov.noaa.nws.ncep.ui.nsharp.view;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingProfile;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingStnInfo;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingStnInfoCollection;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingTimeLines;
import gov.noaa.nws.ncep.ui.nsharp.NsharpConstants;
import gov.noaa.nws.ncep.ui.nsharp.NsharpStationInfo;
import gov.noaa.nws.ncep.ui.nsharp.display.map.NsharpMapResource;
import gov.noaa.nws.ncep.viz.common.soundingQuery.NcSoundingQuery;
import java.sql.Timestamp;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.TimeZone;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
public class NsharpObservedSoundingDialogContents {
private Composite parent;
private org.eclipse.swt.widgets.List sndTimeList;
private Group btnGp, sndTimeListGp, topGp, midGp;
private boolean timeLimit = false;
private boolean rawData = false;
private Button timeBtn, bufruaBtn, uairBtn, rawBtn;
private String FILE_UAIR = "UAIR";
private String FILE_BUFRUA = "BUFRUA";
// private String FILE_DROP = "DROP";
private NcSoundingProfile.ObsSndType currentSndType = NcSoundingProfile.ObsSndType.NONE;
private NsharpLoadDialog ldDia;
private ArrayList<String> selectedTimeList = new ArrayList<String>();
private Font newFont;
public boolean isRawData() {
return rawData;
}
public NcSoundingProfile.ObsSndType getCurrentSndType() {
return currentSndType;
}
public NsharpObservedSoundingDialogContents(Composite parent) {
this.parent = parent;
ldDia = NsharpLoadDialog.getAccess();
newFont = ldDia.getNewFont();
}
private void createObsvdSndUairList() {
sndTimeList.removeAll();
// use NcSoundingQuery to query
NcSoundingTimeLines timeLines = NcSoundingQuery
.soundingTimeLineQuery(currentSndType.toString());
if (timeLines != null && timeLines.getTimeLines() != null) {
DateFormatSymbols dfs = new DateFormatSymbols();
String[] defaultDays = dfs.getShortWeekdays();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
ldDia.startWaitCursor();
for (Object timeLine : timeLines.getTimeLines()) {
Timestamp synoptictime = (Timestamp) timeLine;
if (synoptictime != null) {
// need to format synoptictime to GMT time string.
// Timestamp.toString produce a local time Not GMT time
cal.setTimeInMillis(synoptictime.getTime());
String dayOfWeek = defaultDays[cal
.get(Calendar.DAY_OF_WEEK)];
// String gmtTimeStr =
// String.format("%1$ty%1$tm%1$td/%1$tH%1$tM %2$s", cal,
// currentSndType.toString());
String gmtTimeStr = String.format(
"%1$ty%1$tm%1$td/%1$tH(%3$s) %2$s", cal,
currentSndType.toString(), dayOfWeek);
if (!timeLimit) {
// System.out.println("not 00z and 12z only");
sndTimeList.add(gmtTimeStr);
} else {
int hour = cal.get(Calendar.HOUR_OF_DAY);
// System.out.println("00z and 12z only hour = "+ hour);
if ((hour == 0) || (hour == 12))
sndTimeList.add(gmtTimeStr);
}
}
}
ldDia.stopWaitCursor();
} else
System.out.println("EDEX timeline query return null");
}
private void queryAndMarkStn(String selectedSndTime) {
String selectTimetr = NcSoundingQuery
.convertSoundTimeDispStringToRangeStartTimeFormat(selectedSndTime);
NsharpMapResource nsharpMapResource = NsharpMapResource
.getOrCreateNsharpMapResource();
// Chin float lat, lon;
double lat, lon;
String stnInfoStr;
// use NcSoundingQuery to query stn info
NcSoundingStnInfoCollection sndStnInfoCol = NcSoundingQuery
.soundingStnInfoQuery(currentSndType.toString(), selectTimetr);
if (sndStnInfoCol != null && sndStnInfoCol.getStationInfo() != null) {
NcSoundingStnInfo[] stnInfoAry = sndStnInfoCol.getStationInfo();
// System.out.println("obs station number = "+ stnInfoAry.length );
// Note: A same station may have many reports
for (int i = 0; i < stnInfoAry.length; i++) {
NcSoundingStnInfo stnInfo = stnInfoAry[i];
Timestamp synoptictime = null;
stnInfoStr = stnInfo.getStnId();
if (stnInfoStr == null || stnInfoStr.length() < 1)
stnInfoStr = "*";
lat = stnInfo.getStationLatitude();
lon = stnInfo.getStationLongitude();
// elv = stnInfo.getStationElevation();
synoptictime = (Timestamp) stnInfo.getSynopTime();
// convert to Nsharp's own station info struct
NsharpStationInfo stn = new NsharpStationInfo();
String packedStnInfoStr = stnInfoStr.replace(" ", "_");
stn.setStnDisplayInfo(packedStnInfoStr + " " + selectedSndTime
+ " " + currentSndType.toString());
stn.setLongitude(lon);
stn.setLatitude(lat);
stn.setStnId(stnInfoStr);
stn.setReftime(synoptictime);
stn.setRangestarttime(synoptictime);
stn.setSndType(currentSndType.toString());
// System.out.println("sndType= "+currentSndType);
// System.out.println("stn lat ="+stn.getLatitude() +
// " lon="+stn.getLongitude());
nsharpMapResource.addPoint(stn);
}
NsharpMapResource.bringMapEditorToTop();
}
}
private void handleSndTimeSelection() {
String selectedSndTime = null;
if (sndTimeList.getSelectionCount() > 0) {
NsharpMapResource nsharpMapResource = NsharpMapResource
.getOrCreateNsharpMapResource();// NsharpLoadDialog.getAccess().getNsharpMapResource();
nsharpMapResource.setPoints(null);
selectedTimeList.clear();
ldDia.startWaitCursor();
for (int i = 0; i < sndTimeList.getSelectionCount(); i++) {
selectedSndTime = sndTimeList.getSelection()[i];
selectedTimeList.add(selectedSndTime);
// System.out.println("selected sounding time is " +
// selectedSndTime);
int endIndex = selectedSndTime.indexOf(" ");
String queryingSndTime = selectedSndTime.substring(0, endIndex);
queryAndMarkStn(queryingSndTime);
}
ldDia.setObsSelectedTimeList(selectedTimeList);
ldDia.stopWaitCursor();
}
}
public void createObsvdDialogContents() {
currentSndType = ldDia.getActiveObsSndType();
timeLimit = false;
rawData = false;
topGp = new Group(parent, SWT.SHADOW_ETCHED_IN);
topGp.setLayout(new GridLayout(2, false));
// ldDia.setShellSize(false);
ldDia.createSndTypeList(topGp);
btnGp = new Group(topGp, SWT.SHADOW_ETCHED_IN);
btnGp.setText("File Type");
btnGp.setFont(newFont);
uairBtn = new Button(btnGp, SWT.RADIO | SWT.BORDER);
uairBtn.setText(FILE_UAIR);
uairBtn.setEnabled(true);
uairBtn.setBounds(btnGp.getBounds().x + NsharpConstants.btnGapX,
btnGp.getBounds().y + NsharpConstants.labelGap,
NsharpConstants.btnWidth, NsharpConstants.btnHeight);
uairBtn.setFont(newFont);
uairBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
sndTimeList.removeAll();
currentSndType = NcSoundingProfile.ObsSndType.NCUAIR;
ldDia.setActiveObsSndType(currentSndType);
createObsvdSndUairList();
// System.out.println("new obvSnd dialog uair btn");
}
});
bufruaBtn = new Button(btnGp, SWT.RADIO | SWT.BORDER);
bufruaBtn.setText(FILE_BUFRUA);
bufruaBtn.setEnabled(true);
bufruaBtn.setBounds(btnGp.getBounds().x + NsharpConstants.btnGapX,
uairBtn.getBounds().y + uairBtn.getBounds().height
+ NsharpConstants.btnGapY, NsharpConstants.btnWidth,
NsharpConstants.btnHeight);
bufruaBtn.setFont(newFont);
bufruaBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
sndTimeList.removeAll();
currentSndType = NcSoundingProfile.ObsSndType.BUFRUA;
ldDia.setActiveObsSndType(currentSndType);
createObsvdSndUairList();
}
});
midGp = new Group(parent, SWT.SHADOW_ETCHED_IN);
midGp.setLayout(new GridLayout(2, false));
timeBtn = new Button(midGp, SWT.CHECK | SWT.BORDER);
timeBtn.setText("00Z and 12Z only");
timeBtn.setEnabled(true);
// timeBtn.setBounds(btnGp.getBounds().x+ NsharpConstants.btnGapX,
// browseBtn.getBounds().y + browseBtn.getBounds().height+
// NsharpConstants.btnGapY,
// NsharpConstants.btnWidth,NsharpConstants.btnHeight);
timeBtn.setFont(newFont);
timeBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
if (timeBtn.getSelection())
timeLimit = true;
else
timeLimit = false;
// refresh sounding list if file type is selected already
if (currentSndType == NcSoundingProfile.ObsSndType.NCUAIR
|| currentSndType == NcSoundingProfile.ObsSndType.BUFRUA) {
createObsvdSndUairList();
}
}
});
rawBtn = new Button(midGp, SWT.CHECK | SWT.BORDER);
rawBtn.setText("raw data");
rawBtn.setEnabled(true);
rawBtn.setBounds(timeBtn.getBounds().x + timeBtn.getBounds().width,
timeBtn.getBounds().y, timeBtn.getBounds().width,
timeBtn.getBounds().height);
rawBtn.setFont(newFont);
rawBtn.addListener(SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
if (rawBtn.getSelection())
rawData = true;
else
rawData = false;
;
}
});
// create file widget list
sndTimeListGp = new Group(parent, SWT.SHADOW_ETCHED_IN);
sndTimeListGp.setText("Sounding Times:");
sndTimeListGp.setFont(newFont);
sndTimeList = new org.eclipse.swt.widgets.List(sndTimeListGp,
SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
sndTimeList.setBounds(btnGp.getBounds().x + NsharpConstants.btnGapX,
sndTimeListGp.getBounds().y + NsharpConstants.labelGap,
NsharpConstants.listWidth, NsharpConstants.listHeight * 7);
sndTimeList.setFont(newFont);
// create a selection listener to handle user's selection on list
sndTimeList.addListener(SWT.Selection, new Listener() {
// private String selectedSndTime=null;
public void handleEvent(Event e) {
handleSndTimeSelection();
}
});
if (currentSndType == NcSoundingProfile.ObsSndType.NCUAIR
|| currentSndType == NcSoundingProfile.ObsSndType.BUFRUA) {
if (currentSndType == NcSoundingProfile.ObsSndType.NCUAIR)
uairBtn.setSelection(true);
else
bufruaBtn.setSelection(true);
createObsvdSndUairList();
selectedTimeList = ldDia.getObsSelectedTimeList();
Object[] selTimeObjectArray = selectedTimeList.toArray();
String[] selTimeStringArray = Arrays.copyOf(selTimeObjectArray,
selTimeObjectArray.length, String[].class);
sndTimeList.setSelection(selTimeStringArray);
handleSndTimeSelection();
}
}
public void cleanup() {
if (sndTimeList != null) {
sndTimeList.removeListener(SWT.Selection,
sndTimeList.getListeners(SWT.Selection)[0]);
sndTimeList.dispose();
sndTimeList = null;
}
if (sndTimeListGp != null) {
sndTimeListGp.dispose();
sndTimeListGp = null;
}
if (timeBtn != null) {
timeBtn.removeListener(SWT.MouseUp,
timeBtn.getListeners(SWT.MouseUp)[0]);
timeBtn.dispose();
timeBtn = null;
}
if (rawBtn != null) {
rawBtn.removeListener(SWT.MouseUp,
rawBtn.getListeners(SWT.MouseUp)[0]);
rawBtn.dispose();
rawBtn = null;
}
if (midGp != null) {
midGp.dispose();
midGp = null;
}
/*
* if(browseBtn != null){ browseBtn.removeListener(SWT.MouseUp,
* browseBtn.getListeners(SWT.MouseUp)[0]); browseBtn.dispose();
* browseBtn = null; }
*
*
* if(tamBtn != null){ tamBtn.removeListener(SWT.MouseUp,
* tamBtn.getListeners(SWT.MouseUp)[0]); tamBtn.dispose(); tamBtn =
* null; }
*/
if (bufruaBtn != null) {
bufruaBtn.removeListener(SWT.MouseUp,
bufruaBtn.getListeners(SWT.MouseUp)[0]);
bufruaBtn.dispose();
bufruaBtn = null;
}
if (uairBtn != null) {
uairBtn.removeListener(SWT.MouseUp,
uairBtn.getListeners(SWT.MouseUp)[0]);
uairBtn.dispose();
uairBtn = null;
}
if (btnGp != null) {
btnGp.dispose();
btnGp = null;
}
/*
* if(newTabBtn != null){ newTabBtn.removeListener(SWT.MouseUp,
* newTabBtn.getListeners(SWT.MouseUp)[0]); newTabBtn.dispose();
* newTabBtn = null; }
*/
NsharpLoadDialog ldDia = NsharpLoadDialog.getAccess();
ldDia.cleanSndTypeList();
if (topGp != null) {
topGp.dispose();
topGp = null;
}
}
}

View file

@ -212,7 +212,7 @@ public class NsharpPaneConfigDialog extends Dialog {
else {
NsharpPaletteWindow paletteWin = NsharpPaletteWindow.getInstance();
if(paletteWin!=null){
paletteWin.updateSpcGraphBtn(paneConfigurationName);
paletteWin.updateSpecialGraphBtn(paneConfigurationName);
}
}
}

View file

@ -0,0 +1,424 @@
/**
*
* gov.noaa.nws.ncep.ui.nsharp.view.PfcSoundingDialogContents
*
* This java class performs the NSHARP NsharpLoadDialog functions.
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------- ------- -------- -----------
* 01/2011 229 Chin Chen Initial coding
*
* </pre>
*
* @author Chin Chen
* @version 1.0
*/
package gov.noaa.nws.ncep.ui.nsharp.view;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingProfile;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingStnInfo;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingStnInfoCollection;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingTimeLines;
import gov.noaa.nws.ncep.ui.nsharp.NsharpConstants;
import gov.noaa.nws.ncep.ui.nsharp.NsharpStationInfo;
import gov.noaa.nws.ncep.ui.nsharp.display.map.NsharpMapResource;
import gov.noaa.nws.ncep.viz.common.soundingQuery.NcSoundingQuery;
import java.sql.Timestamp;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
public class NsharpPfcSoundingDialogContents {
private Composite parent;
private org.eclipse.swt.widgets.List availablefileList, sndTimeList;
private Group topGp, fileTypeGp, bottomGp, availableFileGp, sndTimeListGp;
private Button namBtn, gfsBtn, timeBtn;
private boolean timeLimit = false;
private List<String> selectedFileList = new ArrayList<String>();
private List<String> selectedTimeList = new ArrayList<String>();
private List<NsharpStationInfo> stnPoints = new ArrayList<NsharpStationInfo>();
private NcSoundingProfile.PfcSndType currentSndType = NcSoundingProfile.PfcSndType.NONE;
private NsharpLoadDialog ldDia;
private Font newFont;
public NcSoundingProfile.PfcSndType getCurrentSndType() {
return currentSndType;
}
public NsharpPfcSoundingDialogContents() {
}
public NsharpPfcSoundingDialogContents (Composite parent) {
this.parent = parent;
ldDia = NsharpLoadDialog.getAccess();
newFont = ldDia.getNewFont();
}
private void createPFCAvailableFileList() {
sndTimeList.removeAll();;
availablefileList.removeAll();
//query using NcSoundingQuery class to query
NcSoundingTimeLines timeLines = NcSoundingQuery.soundingTimeLineQuery(currentSndType.toString());
if(timeLines!= null && timeLines.getTimeLines() != null){
ldDia.startWaitCursor();
for(Object timeLine : timeLines.getTimeLines()){
Timestamp reftime = (Timestamp)timeLine;
if(reftime != null){
//need to format reftime to GMT time string. Timestamp.toString produce a local time Not GMT time
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(reftime.getTime());
String gmtTimeStr = String.format("%1$tY-%1$tm-%1$td %1$tH", cal);
//System.out.println("GMT time " + gmtTimeStr);
availablefileList.add(gmtTimeStr);
}
}
ldDia.stopWaitCursor();
}
else
System.out.println("SQL: query return null");
}
private void createPFCSndTimeList(List<String> selectedFlLst) {
if(selectedFlLst.size() <=0 )
return;
//currentDBTblName = MODELSOUNDING_TBL_NAME;
sndTimeList.removeAll();
//query using NcSoundingQuery to query
ldDia.startWaitCursor();
String sndStr = currentSndType.toString();
int endIndex= Math.min(3, sndStr.length());
String dispSndStr = sndStr.substring(0, endIndex);
DateFormatSymbols dfs= new DateFormatSymbols();
String[] defaultDays = dfs.getShortWeekdays();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
for(int i=0; i< selectedFlLst.size(); i++){
String fl = selectedFlLst.get(i);
long reftimeMs= NcSoundingQuery.convertRefTimeStr(fl);
//System.out.println("reftime="+fl + " in ms="+reftimeMs);
NcSoundingTimeLines timeLines = NcSoundingQuery.soundingRangeTimeLineQuery(sndStr, fl);
if(timeLines != null && timeLines.getTimeLines().length >0) {
for(Object obj : timeLines.getTimeLines()){
Timestamp rangestart = (Timestamp)obj;
//need to format rangestart to GMT time string. Timestamp.toString produce a local time Not GMT time
cal.setTimeInMillis(rangestart.getTime());
long vHour = (cal.getTimeInMillis()- reftimeMs)/3600000;
String dayOfWeek = defaultDays[cal.get(Calendar.DAY_OF_WEEK)];
//String gmtTimeStr = String.format("%1$ty%1$tm%1$td/%1$tH%1$tMV%2$03d %3$s", cal, vHour,dispSndStr);
String gmtTimeStr = String.format("%1$ty%1$tm%1$td/%1$tH(%4$s)V%2$03d %3$s", cal, vHour,dispSndStr,dayOfWeek);
if(sndTimeList.indexOf(gmtTimeStr) != -1){
// this indicate that gmtTimeStr is already in the sndTimeList, then we dont need to add it to list again.
continue;
}
//System.out.println("GMT time " + gmtTimeStr);
if(!timeLimit)
sndTimeList.add(gmtTimeStr);
else {
int hour = cal.get(Calendar.HOUR_OF_DAY);
if((hour == 0) || (hour == 12))
sndTimeList.add(gmtTimeStr);
}
}
}
}
ldDia.stopWaitCursor();
}
private void handleAvailFileListSelection(){
String selectedFile=null;
if (availablefileList.getSelectionCount() > 0 ) {
selectedFileList.clear();
for(int i=0; i < availablefileList.getSelectionCount(); i++) {
selectedFile = availablefileList.getSelection()[i];
//System.out.println("selected sounding file is " + selectedFile);
selectedFileList.add(selectedFile);
}
ldDia.setPfcSelectedFileList(selectedFileList);
createPFCSndTimeList(selectedFileList);
}
}
private void handleSndTimeSelection(){
String selectedSndTime=null;
if (sndTimeList.getSelectionCount() > 0 ) {
NsharpMapResource nsharpMapResource = NsharpMapResource.getOrCreateNsharpMapResource();//NsharpLoadDialog.getAccess().getNsharpMapResource();
nsharpMapResource.setPoints(null);
selectedTimeList.clear();
ldDia.startWaitCursor();
List<String> queriedTimeList = new ArrayList<String>();
for(int i=0; i < sndTimeList.getSelectionCount(); i++) {
selectedSndTime = sndTimeList.getSelection()[i];
selectedTimeList.add(selectedSndTime);
int endIndex = selectedSndTime.indexOf(" ");
String querySndTime = selectedSndTime.substring(0, endIndex);
//System.out.println("selected sounding time is " + selectedSndTime);
//refTimeStr is same as "PFC file" name in Load dialog display
String refTimeStr=NcSoundingQuery.convertSoundTimeDispStringToForecastTime(querySndTime);
//while rangeStartStr is same as "sounding Times
String rangeStartStr = NcSoundingQuery.convertSoundTimeDispStringToRangeStartTimeFormat(querySndTime);
if(queriedTimeList.contains(refTimeStr)== true){
addStnPtWithoutQuery(refTimeStr,rangeStartStr,querySndTime);
}
else {
queriedTimeList.add(refTimeStr);
queryAndMarkStn(refTimeStr,rangeStartStr,querySndTime);
}
}
ldDia.stopWaitCursor();
nsharpMapResource.setPoints(stnPoints);
NsharpMapResource.bringMapEditorToTop();
}
}
public void createPfcDialogContents(){
topGp = new Group(parent,SWT.SHADOW_ETCHED_IN);
topGp.setLayout( new GridLayout( 2, false ) );
currentSndType = ldDia.getActivePfcSndType();
ldDia.createSndTypeList(topGp);
fileTypeGp = new Group(topGp, SWT.SHADOW_ETCHED_IN);
fileTypeGp.setText("File Type");
fileTypeGp.setFont(newFont);
namBtn = new Button(fileTypeGp, SWT.RADIO | SWT.BORDER);
namBtn.setText("NAMSND");
namBtn.setEnabled( true );
namBtn.setBounds(fileTypeGp.getBounds().x+ NsharpConstants.btnGapX, fileTypeGp.getBounds().y + NsharpConstants.labelGap, NsharpConstants.btnWidth,NsharpConstants.btnHeight);
namBtn.setFont(newFont);
namBtn.addListener( SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
currentSndType = NcSoundingProfile.PfcSndType.NAMSND;
createPFCAvailableFileList();
ldDia.setActivePfcSndType(currentSndType);
}
} );
gfsBtn = new Button(fileTypeGp, SWT.RADIO | SWT.BORDER);
gfsBtn.setText("GFSSND");
gfsBtn.setEnabled( true );
gfsBtn.setBounds(fileTypeGp.getBounds().x+ NsharpConstants.btnGapX, namBtn.getBounds().y + namBtn.getBounds().height+ NsharpConstants.btnGapY, NsharpConstants.btnWidth,NsharpConstants.btnHeight);
gfsBtn.setFont(newFont);
gfsBtn.addListener( SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
currentSndType = NcSoundingProfile.PfcSndType.GFSSND;
createPFCAvailableFileList();
ldDia.setActivePfcSndType(currentSndType);
}
} );
timeBtn = new Button(parent, SWT.CHECK | SWT.BORDER);
timeBtn.setText("00Z and 12Z only");
timeBtn.setEnabled( true );
//timeBtn.setBounds(fileTypeGp.getBounds().x+ NsharpConstants.btnGapX, browseBtn.getBounds().y + browseBtn.getBounds().height+ NsharpConstants.btnGapY, NsharpConstants.btnWidth,NsharpConstants.btnHeight);
timeBtn.setFont(newFont);
timeBtn.addListener( SWT.MouseUp, new Listener() {
public void handleEvent(Event event) {
if(timeLimit)
timeLimit = false;
else
timeLimit = true;
//refresh sounding list if file type is selected already
if(!currentSndType.equals("NA") && selectedFileList.size() > 0 ){
createPFCSndTimeList(selectedFileList);
}
}
} );
bottomGp = new Group(parent,SWT.SHADOW_ETCHED_IN);
bottomGp.setLayout( new GridLayout( 2, false ) );
availableFileGp = new Group(bottomGp,SWT.SHADOW_ETCHED_IN);
availableFileGp.setText("Available PFC files:");
availableFileGp.setFont(newFont);
availablefileList = new org.eclipse.swt.widgets.List(availableFileGp, SWT.BORDER | /*// FixMark:nearByStnCompSnd SWT.MULTI| */SWT.V_SCROLL );
availablefileList.setBounds(availableFileGp.getBounds().x, availableFileGp.getBounds().y + NsharpConstants.labelGap , NsharpConstants.filelistWidth, NsharpConstants.listHeight *36/5);
//create a selection listener to handle user's selection on list
availablefileList.setFont(newFont);
availablefileList.addListener ( SWT.Selection, new Listener () {
public void handleEvent (Event e) {
handleAvailFileListSelection();
}
} );
//create Sounding Times widget list
sndTimeListGp = new Group(bottomGp,SWT.SHADOW_ETCHED_IN);
sndTimeListGp.setText("Sounding Times:");
sndTimeListGp.setFont(newFont);
sndTimeList = new org.eclipse.swt.widgets.List(sndTimeListGp, SWT.BORDER | SWT.MULTI| SWT.V_SCROLL );
sndTimeList.removeAll();
sndTimeList.setFont(newFont);
sndTimeList.setBounds(sndTimeListGp.getBounds().x, sndTimeListGp.getBounds().y + NsharpConstants.labelGap, NsharpConstants.listWidth, NsharpConstants.listHeight*36/5 );
sndTimeList.addListener ( SWT.Selection, new Listener () {
// private String selectedSndTime=null;
public void handleEvent (Event e) {
handleSndTimeSelection();
}
});
if(currentSndType==NcSoundingProfile.PfcSndType.GFSSND || currentSndType==NcSoundingProfile.PfcSndType.NAMSND){
if(currentSndType==NcSoundingProfile.PfcSndType.GFSSND)
gfsBtn.setSelection(true);
else
namBtn.setSelection(true);
createPFCAvailableFileList();
selectedFileList = ldDia.getPfcSelectedFileList();
Object[] selFileObjectArray = selectedFileList.toArray();
String[] selFileStringArray = Arrays.copyOf(selFileObjectArray, selFileObjectArray.length, String[].class);
availablefileList.setSelection(selFileStringArray);
handleAvailFileListSelection();
selectedTimeList = ldDia.getPfcSelectedTimeList();
Object[] selTimeObjectArray = selectedTimeList.toArray();
String[] selTimeStringArray = Arrays.copyOf(selTimeObjectArray, selTimeObjectArray.length, String[].class);
sndTimeList.setSelection(selTimeStringArray);
handleSndTimeSelection();
}
}
private void addStnPtWithoutQuery(String refTimeStr,String rangeStartStr, String selectedSndTime) {
long reftimeMs= NcSoundingQuery.convertRefTimeStr(refTimeStr);
Timestamp refTime = new Timestamp(reftimeMs);
for(NsharpStationInfo stn: stnPoints){
if(refTime.equals(stn.getReftime())== true){
long rangetimeMs= NcSoundingQuery.convertRefTimeStr(rangeStartStr);
Timestamp rangeStartTime = new Timestamp(rangetimeMs);
NsharpStationInfo.timeLineSpecific timeLinsSpc = stn.new timeLineSpecific();
String sndTypeStr = currentSndType.toString();
int endIndex= Math.min(4, sndTypeStr.length());
String dispInfo = stn.getStnId()+ " " + selectedSndTime+" "+sndTypeStr.substring(0,endIndex);
timeLinsSpc.setDisplayInfo(dispInfo);
timeLinsSpc.setTiemLine(rangeStartTime);
stn.addToTimeLineSpList(timeLinsSpc);
}
}
//System.out.println("addStnPtWithoutQuery stn num ="+ stnPoints.size()+ " for pfc refTime(file) "+refTimeStr);
}
private void queryAndMarkStn(String refTimeStr,String rangeStartStr, String selectedSndTime) {
//use NcSoundingQuery to query stn info
String sndTypeStr = currentSndType.toString();
NcSoundingStnInfoCollection sndStnInfoCol = NcSoundingQuery.soundingStnInfoQuery(sndTypeStr,rangeStartStr, refTimeStr);
if(sndStnInfoCol != null && sndStnInfoCol.getStationInfo() != null){
NcSoundingStnInfo[] stnInfoAry = sndStnInfoCol.getStationInfo();
//System.out.println("queryAndMarkStn stn num ="+ stnInfoAry.length+ " for pfc refTime(file) "+refTimeStr);
for(int i=0; i < stnInfoAry.length; i++){
NcSoundingStnInfo stnInfo = stnInfoAry[i];
NsharpStationInfo stn = new NsharpStationInfo();
NsharpStationInfo.timeLineSpecific timeLinsSpc = stn.new timeLineSpecific();
int endIndex= Math.min(4, sndTypeStr.length());
String packedStnIdStr= stnInfo.getStnId().replace(" ", "_");
String dispInfo = packedStnIdStr + " " + selectedSndTime+" "+sndTypeStr.substring(0,endIndex);
timeLinsSpc.setDisplayInfo(dispInfo);
timeLinsSpc.setTiemLine(stnInfo.getRangeStartTime());
stn.addToTimeLineSpList(timeLinsSpc);
stn.setLongitude(stnInfo.getStationLongitude());
stn.setLatitude(stnInfo.getStationLatitude());
stn.setReftime(stnInfo.getSynopTime());
stn.setStnId(stnInfo.getStnId());
stn.setSndType(sndTypeStr);
//if(i <10)
// System.out.println( "disP="+dispInfo+" refT= "+stnInfo.getSynopTime()+ " rangSt="+stnInfo.getRangeStartTime());
stnPoints.add(stn);
}
}
}
public void cleanup(){
if(namBtn != null&& namBtn.isDisposed()== false){
namBtn.removeListener(SWT.MouseUp, namBtn.getListeners(SWT.MouseUp)[0]);
namBtn.dispose();
namBtn = null;
}
if(gfsBtn != null){
gfsBtn.removeListener(SWT.MouseUp, gfsBtn.getListeners(SWT.MouseUp)[0]);
gfsBtn.dispose();
gfsBtn = null;
}
/*if(ruc2Btn != null){
ruc2Btn.removeListener(SWT.MouseUp, ruc2Btn.getListeners(SWT.MouseUp)[0]);
ruc2Btn.dispose();
ruc2Btn = null;
}
if(rucpBtn != null){
rucpBtn.removeListener(SWT.MouseUp, rucpBtn.getListeners(SWT.MouseUp)[0]);
rucpBtn.dispose();
rucpBtn = null;
}
if(browseBtn != null){
browseBtn.removeListener(SWT.MouseUp, browseBtn.getListeners(SWT.MouseUp)[0]);
browseBtn.dispose();
browseBtn = null;
} */
NsharpLoadDialog ldDia = NsharpLoadDialog.getAccess();
ldDia.cleanSndTypeList();
if(topGp!= null){
topGp.dispose();
topGp = null;
}
if(timeBtn != null){
timeBtn.removeListener(SWT.MouseUp, timeBtn.getListeners(SWT.MouseUp)[0]);
timeBtn.dispose();
timeBtn = null;
}
if(fileTypeGp!= null){
fileTypeGp.dispose();
fileTypeGp = null;
}
if(availablefileList!= null){
availablefileList.removeListener(SWT.Selection, availablefileList.getListeners(SWT.Selection)[0]);
availablefileList.dispose();
availablefileList = null;
}
if(availableFileGp!= null){
availableFileGp.dispose();
availableFileGp = null;
}
if(sndTimeList!= null){
sndTimeList.removeListener(SWT.Selection, sndTimeList.getListeners(SWT.Selection)[0]);
sndTimeList.dispose();
sndTimeList = null;
}
if(sndTimeListGp!= null){
sndTimeListGp.dispose();
sndTimeListGp = null;
}
if(bottomGp!= null){
bottomGp.dispose();
bottomGp = null;
}
/*if(newTabBtn != null){
newTabBtn.removeListener(SWT.MouseUp, newTabBtn.getListeners(SWT.MouseUp)[0]);
newTabBtn.dispose();
newTabBtn = null;
}*/
}
}

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<NsharpConfigStore xmlns:ns2="group" xmlns:ns3="http://www.example.org/productType">
<graphProperty paneConfigurationName="Default Configuration 1" tempOffset="0" windBarbDistance="400" windBarb="true" corfidiV="false" omega="true" smvBunkersL="true" smvBunkersR="true" smv1585="false" smv3075="false" meanWind="true" hodo="true" cloud="false" effLayer="true" moistAdiabat="false" dryAdiabat="true" mixratio="true" wetBulb="true" vTemp="true" parcelAscent="true" parcel="true" dewp="true" temp="true"/>
<graphProperty paneConfigurationName="D2D Skewt Standard Screen Configuration" tempOffset="0" windBarbDistance="400" windBarb="true" corfidiV="false" omega="true" smvBunkersL="true" smvBunkersR="true" smv1585="false" smv3075="false" meanWind="true" hodo="true" cloud="false" effLayer="true" moistAdiabat="false" dryAdiabat="true" mixratio="true" wetBulb="true" vTemp="true" parcelAscent="true" parcel="true" dewp="true" temp="true" windBarbLineWidth="2.0" windBarbSize="2.5" showFilteredWindInCircle="false" sndCompRadius="0"/>
<linePropertyMap>
<Line lineName="Compare 6">
<lineProperty lineWidth="2" lineStyle="SOLID">
@ -128,5 +128,5 @@
</lineProperty>
</Line>
</linePropertyMap>
<dataPageProperty severePotentialPage="10" convectiveInitiationPage="9" meanWindPage="8" stormRelativePage="7" mixingHeightPage="6" opcDataPage="5" thermodynamicDataPage="4" parcelDataPage="3" summary2Page="2" summary1Page="1"/>
<dataPageProperty severePotentialPage="10" convectiveInitiationPage="9" meanWindPage="8" stormRelativePage="7" mixingHeightPage="6" opcDataPage="5" thermodynamicDataPage="4" parcelDataPage="3" summary2Page="2" summary1Page="1" d2DLitePage="11" futurePage="12" numberPagePerDisplay="2"/>
</NsharpConfigStore>

View file

@ -427,6 +427,12 @@
commandId="gov.noaa.nws.ncep.viz.CustomProjection"
label="Custom Area...">
</command>
<command
commandId="gov.noaa.nws.ncep.viz.ui.remotescript"
label="Run Remote Script"
mnemonic="R"
style="push">
</command>
<!--
<command
commandId="sync.file.tool.command"

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>gov.noaa.nws.ncep.viz.ui.remotescript</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,7 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6

View file

@ -0,0 +1,23 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Remotescript
Bundle-SymbolicName: gov.noaa.nws.ncep.viz.ui.remotescript;singleton:=true
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: gov.noaa.nws.ncep.viz.ui.remotescript.Activator
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
com.raytheon.uf.viz.core,
com.raytheon.uf.common.auth;bundle-version="1.12.1174"
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Export-Package: gov.noaa.nws.ncep.viz.ui.remotescript,
gov.noaa.nws.ncep.viz.ui.remotescript.dialog
Import-Package: com.raytheon.uf.common.auth.user,
com.raytheon.uf.common.localization,
com.raytheon.uf.common.remote.script,
com.raytheon.uf.common.serialization,
com.raytheon.uf.common.serialization.comm,
com.raytheon.uf.viz.core.auth,
com.raytheon.uf.viz.core.requests,
gov.noaa.nws.ncep.viz.localization,
gov.noaa.nws.ncep.viz.ui.display

View file

@ -0,0 +1,4 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.

View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.3"?>
<plugin>
<extension
point="org.eclipse.ui.commands">
<command
id="gov.noaa.nws.ncep.viz.ui.remotescript"
name="Run Remote Script">
</command>
</extension>
<extension
point="org.eclipse.ui.handlers">
<handler
class="gov.noaa.nws.ncep.viz.ui.remotescript.RemoteScriptDialogHandler"
commandId="gov.noaa.nws.ncep.viz.ui.remotescript">
</handler>
</extension>
<extension
point="com.raytheon.uf.viz.localization.localizationpath">
<path
application="NCEP"
localizationType="COMMON_STATIC"
name="remoteScripts"
recursive="false"
value="ncep/remoteScripts"
>
</path>
</extension>
</plugin>

View file

@ -0,0 +1,50 @@
package gov.noaa.nws.ncep.viz.ui.remotescript;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "gov.noaa.nws.ncep.viz.ui.remotescript"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}

View file

@ -0,0 +1,53 @@
/*
* gov.noaa.nws.ncep.viz.ui.remotescript.RemoteScripDialogtHandler
*
* March 2014
*
* This code has been developed by the NCEP/SIB for use in the AWIPS2 system.
*/
package gov.noaa.nws.ncep.viz.ui.remotescript;
import gov.noaa.nws.ncep.viz.ui.display.NcDisplayMngr;
import gov.noaa.nws.ncep.viz.ui.remotescript.dialog.RemoteScriptDialog;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
/**
* Handler to pop up the remote script window in CAVE.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 03/14 #? B. Yin Initial creation.
*
* </pre>
*
* @author byin
* @version 1.0
*
*/
public class RemoteScriptDialogHandler extends AbstractHandler {
/*
* (non-Javadoc)
*
* @see
* org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands
* .ExecutionEvent)
*/
@Override
public Object execute(ExecutionEvent arg0) throws ExecutionException {
RemoteScriptDialog dlg = RemoteScriptDialog.getInstance(NcDisplayMngr
.getCaveShell());
dlg.open();
return null;
}
}

View file

@ -0,0 +1,981 @@
/*
* gov.noaa.nws.ncep.viz.ui.remotescript.dialog.RemoteScriptDialog
*
* 26 March 2014
*
* This code has been developed by the NCEP/SIB for use in the AWIPS2 system.
*/
package gov.noaa.nws.ncep.viz.ui.remotescript.dialog;
import gov.noaa.nws.ncep.viz.localization.NcPathManager;
import gov.noaa.nws.ncep.viz.ui.remotescript.job.IRemoteJobObserver;
import gov.noaa.nws.ncep.viz.ui.remotescript.job.JobsModelProvider;
import gov.noaa.nws.ncep.viz.ui.remotescript.job.RemoteScriptJob;
import gov.noaa.nws.ncep.viz.ui.remotescript.job.RemoteScriptJob.JobStatus;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import com.raytheon.uf.common.auth.user.IUser;
import com.raytheon.uf.common.localization.IPathManager;
import com.raytheon.uf.common.localization.LocalizationContext;
import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel;
import com.raytheon.uf.common.localization.PathManagerFactory;
import com.raytheon.uf.common.remote.script.RemoteScriptListRequest;
import com.raytheon.uf.common.remote.script.RemoteScriptListResponse;
import com.raytheon.uf.common.remote.script.RemoteScriptRunRequest;
import com.raytheon.uf.common.remote.script.RemoteScriptRunResponse;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.viz.core.auth.UserController;
import com.raytheon.uf.viz.core.localization.LocalizationManager;
import com.raytheon.uf.viz.core.requests.ThriftClient;
/**
* Dialog for remote script execution
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 03/14 ? B. Yin Initial Creation.
*
* </pre>
*
* @author byin
*
*/
public class RemoteScriptDialog extends Dialog implements IRemoteJobObserver {
// singleton instance
private static RemoteScriptDialog INSTANCE;
private final IUFStatusHandler statusHandler = UFStatus
.getHandler(RemoteScriptDialog.class);
private final IUser user = UserController.getUserObject();
// last location of the dialog
private Point lastLocation = null;
// last size
private Point lastSize = null;
// List viewer for available scripts
private ListViewer scriptListViewer = null;
// Table viewer for submitted jobs
private TableViewer jobTableViewer;
private Listener scrollBarListener;
// Text field for script selected from the list
private Text scriptSelected;
private Button goBtn;
private Text scriptUsage;
private Text scriptOutput;
// Available scripts and their localization contexts
private Map<String, List<LocalizationContext>> scriptMap;
// private static final String CHECKSUM_FILE_EXTENSION = ".md5";
private static final String SCRIPT_HELP_ARGUMENT = "--help";
public RemoteScriptDialog(Shell parent) {
super(parent);
setShellStyle(SWT.TITLE | SWT.CLOSE | SWT.MAX | SWT.MIN | SWT.RESIZE
| SWT.MODELESS);
JobsModelProvider.INSTANCE.registerJobObserver(this);
}
/**
* Creates the dialog if the dialog does not exist and returns the instance.
* If the dialog exists, return the instance.
*
* @param parShell
* @return
*/
public static RemoteScriptDialog getInstance(Shell parShell) {
if (INSTANCE == null) {
INSTANCE = new RemoteScriptDialog(parShell);
}
return INSTANCE;
}
/**
* Creates the dialog area
*/
@Override
public Control createDialogArea(Composite parent) {
Composite top = (Composite) super.createDialogArea(parent);
// Create the main layout for the shell.
GridLayout mainLayout = new GridLayout(1, true);
mainLayout.marginHeight = 1;
mainLayout.marginWidth = 1;
top.setLayout(mainLayout);
// Initialize all of the controls, and layouts
initializeComponents(top);
return top;
}
/**
* Creates buttons, menus, and other controls in the dialog area
*
*/
private void initializeComponents(Composite parent) {
getShell().setText("Remote Script Execution");
// show scroll bars when needed
scrollBarListener = new Listener() {
@Override
public void handleEvent(Event event) {
Text txt = (Text) event.widget;
Rectangle r1 = txt.getClientArea();
Rectangle r2 = txt.computeTrim(r1.x, r1.y, r1.width, r1.height);
Point p = txt.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
txt.getHorizontalBar().setVisible(r2.width <= p.x);
txt.getVerticalBar().setVisible(r2.height <= p.y);
if (event.type == SWT.Modify) {
txt.getParent().layout(true);
txt.showSelection();
}
}
};
// Create tab folder
TabFolder tabFolder = new TabFolder(parent, SWT.RESIZE);
GridData gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
gd.horizontalAlignment = SWT.FILL;
gd.verticalAlignment = SWT.FILL;
tabFolder.setLayoutData(gd);
// Create submit tab
final TabItem submitTabItem = new TabItem(tabFolder, SWT.RESIZE);
submitTabItem.setText("Submit");
Composite submitComp = new Composite(tabFolder, SWT.TOP | SWT.RESIZE);
submitComp.setLayout(new GridLayout(2, false));
createSubmitTabControls(submitComp);
submitTabItem.setControl(submitComp);
// Create status tab
final TabItem statusTabItem = new TabItem(tabFolder, SWT.NONE);
statusTabItem.setText("Status");
Composite statusComp = new Composite(tabFolder, SWT.TOP | SWT.RESIZE);
statusComp.setLayout(new GridLayout(1, false));
createStatusTabControls(statusComp);
statusTabItem.setControl(statusComp);
tabFolder.pack();
}
@Override
/**
* Do not create Ok/Cancel buttons for this dialog.
*/
public Control createButtonBar(Composite parent) {
return null;
}
/**
* Creates controls in the submit tab
*
* @param parent
*/
private void createSubmitTabControls(Composite parent) {
SashForm sashForm = new SashForm(parent, SWT.HORIZONTAL);
GridData sashGd = new GridData(SWT.FILL, SWT.FILL, true, true);
sashForm.setLayoutData(sashGd);
sashForm.setSashWidth(3);
createLeftSubmitPanel(sashForm);
createRightSubmitPanel(sashForm);
sashForm.setWeights(new int[] { 3, 7 });
}
/**
* Creates Site, Desk, and the script list in the submit tab
*
* @param parent
*/
private void createLeftSubmitPanel(Composite parent) {
Composite leftComp = new Composite(parent, SWT.TOP);
leftComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
leftComp.setLayout(new FormLayout());
// Composite for site and desk
Composite siteDeskComp = new Composite(leftComp, SWT.None);
FormData fd1 = new FormData();
fd1.top = new FormAttachment(0, 0);
fd1.left = new FormAttachment(0, 0);
siteDeskComp.setLayoutData(fd1);
siteDeskComp.setLayout(new GridLayout(2, false));
// Site combo
Label siteLbl = new Label(siteDeskComp, SWT.LEFT);
siteLbl.setText("Site:");
final Combo siteCombo = new Combo(siteDeskComp, SWT.DROP_DOWN
| SWT.READ_ONLY);
String curSite = LocalizationManager.getInstance().getCurrentSite();
int ii = 0;
for (String site : PathManagerFactory.getPathManager().getContextList(
LocalizationLevel.SITE)) {
siteCombo.add(site);
if (site.equals(curSite)) {
siteCombo.select(ii);
}
ii++;
}
// Desk combo
Label deskLbl = new Label(siteDeskComp, SWT.LEFT);
deskLbl.setText("Desk:");
final Combo deskCombo = new Combo(siteDeskComp, SWT.DROP_DOWN
| SWT.READ_ONLY);
String curDesk = NcPathManager.getInstance().getDeskContext()
.getContextName();
int jj = 0;
for (String desk : PathManagerFactory.getPathManager().getContextList(
NcPathManager.getInstance().getDeskLevel())) {
deskCombo.add(desk);
if (desk.equals(curDesk)) {
deskCombo.select(jj);
}
jj++;
}
deskCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
scriptListViewer.setInput(getScriptList(siteCombo.getText(),
deskCombo.getText()));
scriptListViewer.refresh(true);
scriptSelected.setText("");
}
});
siteCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
scriptListViewer.setInput(getScriptList(siteCombo.getText(),
deskCombo.getText()));
scriptListViewer.refresh(true);
scriptSelected.setText("");
}
});
// Available script list group
Group listGrp = new Group(leftComp, SWT.None);
listGrp.setText("Available Scripts");
FormData fd2 = new FormData();
fd2.top = new FormAttachment(siteDeskComp, 5, SWT.BOTTOM);
fd2.bottom = new FormAttachment(100, 0);
fd2.left = new FormAttachment(0, 0);
fd2.right = new FormAttachment(100, 0);
listGrp.setLayoutData(fd2);
listGrp.setLayout(new FormLayout());
scriptListViewer = new ListViewer(listGrp, SWT.SINGLE | SWT.V_SCROLL
| SWT.H_SCROLL);
FormData fd3 = new FormData();
fd3.top = new FormAttachment(0, 10);
fd3.bottom = new FormAttachment(100, 0);
fd3.height = 400;
fd3.left = new FormAttachment(0, 0);
fd3.right = new FormAttachment(100, 0);
scriptListViewer.getList().setLayoutData(fd3);
scriptListViewer.getList().setBackground(listGrp.getBackground());
scriptListViewer.setContentProvider(new IStructuredContentProvider() {
@Override
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
// return getScriptList(siteCombo.getText(),
// deskCombo.getText());
}
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput,
Object newInput) {
}
});
scriptListViewer.setInput(getScriptList(siteCombo.getText(),
deskCombo.getText()));
scriptListViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
String scripteWithContext = scriptListViewer.getList()
.getSelection()[0];
String script = scripteWithContext.substring(0,
scripteWithContext.indexOf(" ("));
scriptSelected.setText(script + " ");
scriptUsage.setText(getScriptUsage(script,
getScriptContext(script, scripteWithContext)));
if (scriptUsage.getText().contains(
"Not an executable script")) {
goBtn.setEnabled(false);
} else {
goBtn.setEnabled(true);
}
}
});
}
/**
* Creates text field for selected script, GO button and usage text field.
*
* @param parent
*/
private void createRightSubmitPanel(Composite parent) {
Composite rightComp = new Composite(parent, SWT.TOP | SWT.RESIZE);
rightComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
rightComp.setLayout(new FormLayout());
// Text for selected script and the GO button
Composite textComp = new Composite(rightComp, SWT.TOP | SWT.RESIZE);
FormData fd1 = new FormData();
fd1.top = new FormAttachment(0, 0);
fd1.left = new FormAttachment(0, 0);
fd1.right = new FormAttachment(100, 0);
textComp.setLayoutData(fd1);
textComp.setLayout(new FormLayout());
scriptSelected = new Text(textComp, SWT.SINGLE | SWT.BORDER
| SWT.RESIZE);
FormData fd2 = new FormData();
fd2.top = new FormAttachment(0, 5);
fd2.bottom = new FormAttachment(100, 0);
fd2.left = new FormAttachment(0, 0);
fd2.right = new FormAttachment(90, 0);
scriptSelected.setLayoutData(fd2);
scriptSelected.setBackground(this.getShell().getDisplay()
.getSystemColor(SWT.COLOR_GRAY));
scriptSelected.addListener(SWT.Verify, new Listener() {
@Override
public void handleEvent(Event event) {
// Make the script name in the text field NOT editable.
if (event.widget instanceof Text) {
if (getSelectedScript().isEmpty() && event.text.isEmpty()) {
event.doit = true;
} else if (event.text.equals(getSelectedScript() + " ")
&& event.start == 0) {
// event sent from the list viewer
event.doit = true;
} else if (event.start <= getSelectedScript().length()) {
event.doit = false;
}
}
}
});
goBtn = new Button(textComp, SWT.PUSH);
goBtn.setText("GO");
FormData fd3 = new FormData();
fd3.top = new FormAttachment(0, 5);
fd3.left = new FormAttachment(scriptSelected, 10, SWT.RIGHT);
goBtn.setLayoutData(fd3);
goBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (scriptListViewer.getList().getSelectionCount() != 0) {
String scriptWithContext = scriptListViewer.getList()
.getSelection()[0];
String script = getSelectedScript();
String arguments = getArguments();
RemoteScriptJob job = new RemoteScriptJob(user, script,
arguments, getScriptContext(script,
scriptWithContext), Calendar.getInstance(),
JobStatus.IN_PROGRESS);
JobsModelProvider.INSTANCE.addRemoteScriptJob(job);
// JobsModelProvider.INSTANCE.runJob(job);
}
}
});
Group usageGrp = new Group(rightComp, SWT.RESIZE);
FormData fd4 = new FormData();
fd4.top = new FormAttachment(textComp, 15, SWT.BOTTOM);
fd4.bottom = new FormAttachment(100, 0);
fd4.left = new FormAttachment(0, 0);
fd4.right = new FormAttachment(100, 0);
usageGrp.setLayoutData(fd4);
usageGrp.setLayout(new FormLayout());
usageGrp.setText("Script Usage");
scriptUsage = new Text(usageGrp, SWT.MULTI | SWT.READ_ONLY | SWT.RESIZE
| SWT.H_SCROLL | SWT.V_SCROLL);
FormData fd5 = new FormData();
fd5.top = new FormAttachment(0, 10);
fd5.bottom = new FormAttachment(100, 0);
fd5.left = new FormAttachment(0, 0);
fd5.right = new FormAttachment(100, 0);
scriptUsage.setLayoutData(fd5);
scriptUsage.setBackground(usageGrp.getBackground());
scriptUsage.addListener(SWT.Resize, scrollBarListener);
scriptUsage.addListener(SWT.Modify, scrollBarListener);
}
/**
* Creates controls in status tab
*
* @param parent
*/
private void createStatusTabControls(Composite parent) {
// Sash form to hold the job table and the job output field.
SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
GridData sashGd = new GridData(SWT.FILL, SWT.FILL, true, true);
sashForm.setLayoutData(sashGd);
sashForm.setSashWidth(3);
// Create the job table viewer
jobTableViewer = new TableViewer(sashForm, SWT.MULTI | SWT.V_SCROLL
| SWT.H_SCROLL | SWT.FULL_SELECTION);
// Sort the job by time submitted
jobTableViewer.setComparator(new ViewerComparator() {
@Override
public int compare(Viewer viewer, Object obj1, Object obj2) {
RemoteScriptJob rsj1 = (RemoteScriptJob) obj1;
RemoteScriptJob rsj2 = (RemoteScriptJob) obj2;
return rsj2.getTmSubmitted().compareTo(rsj1.getTmSubmitted());
}
});
Table jobTable = jobTableViewer.getTable();
// Add a column header named "Job" that's left justified
TableViewerColumn column = createTableViewerColumn(jobTableViewer,
"Job", 200, 0);
column.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
RemoteScriptJob rsj = (RemoteScriptJob) element;
return (rsj.getRemoteScriptName() + " ("
+ getLocalizationName(rsj.getContext()) + ")");
}
});
// Add a column header named "Time Submitted" that's left justified
TableViewerColumn column2 = createTableViewerColumn(jobTableViewer,
"Time Submitted", 200, 1);
column2.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
RemoteScriptJob rsj = (RemoteScriptJob) element;
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return sdf.format(rsj.getTmSubmitted().getTime());
}
});
// Add a column header named "Status/Return" that's left justified
TableViewerColumn column3 = createTableViewerColumn(jobTableViewer,
"Status/Return", 200, 2);
column3.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
RemoteScriptJob rsj = (RemoteScriptJob) element;
return rsj.getStatus().toString();
}
});
jobTableViewer.setContentProvider(new ArrayContentProvider());
jobTableViewer.setInput(JobsModelProvider.INSTANCE
.getRemoteScriptJobs());
setItemBackgroundColor(jobTableViewer);
jobTableViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
scriptOutput.setText(((RemoteScriptJob) jobTableViewer
.getTable().getSelection()[0].getData())
.getOutput());
}
});
// Show the column headers
jobTable.setHeaderVisible(true);
// Create the job output field
Group outputGrp = new Group(sashForm, SWT.RESIZE);
outputGrp.setLayout(new FormLayout());
outputGrp.setText("Job Output");
scriptOutput = new Text(outputGrp, SWT.MULTI | SWT.READ_ONLY
| SWT.RESIZE | SWT.H_SCROLL | SWT.V_SCROLL);
FormData fd = new FormData();
fd.top = new FormAttachment(0, 0);
fd.bottom = new FormAttachment(100, 0);
fd.left = new FormAttachment(0, 0);
fd.right = new FormAttachment(100, 0);
scriptOutput.setLayoutData(fd);
scriptOutput.setBackground(outputGrp.getBackground());
jobTable.setBackground(outputGrp.getBackground());
scriptOutput.addListener(SWT.Resize, scrollBarListener);
scriptOutput.addListener(SWT.Modify, scrollBarListener);
sashForm.setWeights(new int[] { 5, 1 });
}
/**
* Set the location and size of the dialog
*/
@Override
public int open() {
if (this.getShell() == null) {
this.create();
}
Point size = getInitialSize();
getShell().setSize(size);
getShell().setLocation(getInitialLocation(size));
return super.open();
}
/**
* Get the last used size of the dialog.
*
* @return
*/
@Override
protected Point getInitialSize() {
return (lastSize == null) ? super.getInitialSize() : lastSize;
}
/**
* Get the last used location of the dialog.
*
* @param size
* @return
*/
@Override
protected Point getInitialLocation(Point size) {
return (lastLocation == null) ? super.getInitialLocation(size)
: lastLocation;
}
/**
* Save location and size of the dialog.
*/
public boolean close() {
if (getShell() != null && !getShell().isDisposed()) {
Rectangle bounds = getShell().getBounds();
lastLocation = new Point(bounds.x, bounds.y);
lastSize = getShell().getSize();
}
return super.close();
}
/**
* Create a column of a table viewer
*
* @param tv
* - table viewer
* @param title
* - column title
* @param bound
* - column width
* @param colNumber
* - column number
* @return table viewer column
*/
private TableViewerColumn createTableViewerColumn(TableViewer tv,
String title, int bound, final int colNumber) {
final TableViewerColumn viewerColumn = new TableViewerColumn(tv,
SWT.NONE);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
return viewerColumn;
}
/**
* Set color for each row of the table
*
* @param tv
*/
private void setItemBackgroundColor(TableViewer tv) {
Table tbl = tv.getTable();
TableItem items[] = tbl.getItems();
for (int ii = 0; ii < items.length; ii++) {
setItemBackgroundColor((RemoteScriptJob) items[ii].getData());
}
}
/**
* Set the color of the job if it in the table. FAIL or TIME_OUT: red OK :
* green IN_PROGRESS : grey
*
* @param job
*/
private void setItemBackgroundColor(RemoteScriptJob job) {
TableItem item = findTableItem(job);
JobStatus status = job.getStatus();
if (item != null) {
if (status.equals(JobStatus.FAIL)
|| status.equals(JobStatus.TIME_OUT)) {
this.getShell().getDisplay();
item.setBackground(new Color(Display.getCurrent(), 225, 50, 30));
} else if (status.equals(JobStatus.OK)) {
item.setBackground(new Color(Display.getCurrent(), 70, 180, 30));
} else {
item.setBackground(this.getShell().getDisplay()
.getSystemColor(SWT.COLOR_GRAY));
}
}
}
/**
* Create a String array of available scripts with their localization
* levels.
*
* @param site
* @param desk
* @return script name array
*/
@SuppressWarnings("unchecked")
private String[] getScriptList(String site, String desk) {
List<String> ret = new ArrayList<String>();
getScriptMap(site, desk);
if (scriptMap != null) {
Iterator<?> it = scriptMap.entrySet().iterator();
while (it.hasNext()) {
Entry<?, ?> entry = (Entry<?, ?>) it.next();
for (LocalizationContext lc : (List<LocalizationContext>) entry
.getValue()) {
ret.add((String) entry.getKey() + " ("
+ getLocalizationName(lc) + ")");
}
}
Collections.sort(ret);
return ret.toArray(new String[ret.size()]);
} else {
return new String[] {};
}
}
/**
* Query the EDEX server and get the available scripts for the specified
* site and desk.
*
* @param site
* @param desk
*/
private void getScriptMap(String site, String desk) {
if (desk == null || desk.isEmpty()) {
desk = "None";
}
IPathManager manager = PathManagerFactory.getPathManager();
LocalizationContext baseContext = manager.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.BASE);
LocalizationContext siteContext = manager.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.SITE);
siteContext.setContextName(site);
LocalizationContext deskContext = manager.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
NcPathManager.getInstance().getDeskLevel());
deskContext.setContextName(desk);
LocalizationContext userContext = manager.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.USER);
RemoteScriptListRequest request = new RemoteScriptListRequest(user
.uniqueId().toString(), new LocalizationContext[] {
baseContext, siteContext, deskContext, userContext });
request.setUser(user);
try {
RemoteScriptListResponse response = (RemoteScriptListResponse) ThriftClient
.sendPrivilegedRequest(request);
if (response != null) {
scriptMap = response.getScripts();
}
} catch (Exception e) {
statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e);
}
}
/**
* Run the selected script with "--help" argument to get the usage info.
*
* @param script
* @param context
* @return
*/
private String getScriptUsage(String script, LocalizationContext context) {
RemoteScriptRunRequest runRequest = new RemoteScriptRunRequest(user
.uniqueId().toString(), script, context);
runRequest.setUser(user);
runRequest.addScriptArgument(SCRIPT_HELP_ARGUMENT);
String usageInfo = "";
try {
RemoteScriptRunResponse runResponse = (RemoteScriptRunResponse) ThriftClient
.sendPrivilegedRequest(runRequest);
if (runResponse != null) {
usageInfo += runResponse.getOutput();
}
} catch (Exception e) {
statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e);
}
if (usageInfo.isEmpty()) {
usageInfo = "No usage infomation!";
}
return usageInfo;
}
/**
* Get the arguments user types in
*
* @return
*/
private String getArguments() {
String script = getSelectedScript();
return scriptSelected.getText().substring(script.length() + 1);
}
/**
* Get the localization context of the selected script.
*
* @param script
* @param scripteWithContext
* @return - localization context of the script
*/
protected LocalizationContext getScriptContext(String script,
String scriptWithContext) {
String contextName = scriptWithContext.substring(
scriptWithContext.indexOf(" (") + 2,
scriptWithContext.indexOf(")"));
LocalizationContext context = null;
if (contextName.equalsIgnoreCase("BASE")) {
IPathManager manager = PathManagerFactory.getPathManager();
context = manager.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.BASE);
} else {
for (LocalizationContext lc : scriptMap.get(script)) {
if (!lc.getLocalizationLevel().equals(
LocalizationContext.LocalizationLevel.BASE)
&& lc.getContextName().equalsIgnoreCase(contextName)) {
context = lc;
}
}
}
return context;
}
/**
* Get the selected script name (without the localization context string)
* from the script list.
*
* @return script name
*/
private String getSelectedScript() {
if (scriptListViewer.getList().getSelectionCount() == 0) {
return "";
} else {
String scripteWithContext = scriptListViewer.getList()
.getSelection()[0];
return scripteWithContext.substring(0,
scripteWithContext.indexOf(" ("));
}
}
/**
* Update status, color, output of the specified job.
*/
@Override
public void updateRemoteJob(RemoteScriptJob job) {
jobTableViewer.update(job, null);
setItemBackgroundColor(job);
// update output
if (jobTableViewer.getTable().getSelection().length > 0
&& jobTableViewer.getTable().getSelection()[0].getData()
.equals(job)) {
String output = job.getOutput();
if (!job.getError().isEmpty()) {
output += "\nError message:\n" + job.getError();
}
scriptOutput.setText(output);
}
}
/**
* Add a new job to the job status table.
*/
@Override
public void addRemoteJob(RemoteScriptJob job) {
jobTableViewer.add(job);
setItemBackgroundColor(job);
}
/**
* Find the table item of the specified job.
*
* @param job
* @return
*/
private TableItem findTableItem(RemoteScriptJob job) {
Table tbl = jobTableViewer.getTable();
TableItem items[] = tbl.getItems();
for (int ii = 0; ii < items.length; ii++) {
if (items[ii].getData().equals(job)) {
return items[ii];
}
}
return null;
}
/**
* Get the name of the localization context.
*
* @param lc
* @return localization context name
*/
private String getLocalizationName(LocalizationContext lc) {
if (lc.getLocalizationLevel().equals(
LocalizationContext.LocalizationLevel.BASE)) {
return "base";
} else {
return lc.getContextName();
}
}
}

View file

@ -0,0 +1,31 @@
/*
* gov.noaa.nws.ncep.viz.ui.remotescript.job.IRemoteJobObserver
*
* 26 March 2014
*
* This code has been developed by the NCEP/SIB for use in the AWIPS2 system.
*/
package gov.noaa.nws.ncep.viz.ui.remotescript.job;
/**
* Interface for remote job observer
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 03/14 ? B. Yin Initial Creation.
*
* </pre>
*
* @author byin
*
*/
public interface IRemoteJobObserver {
public void updateRemoteJob(RemoteScriptJob job);
public void addRemoteJob(RemoteScriptJob job);
}

View file

@ -0,0 +1,129 @@
/*
* gov.noaa.nws.ncep.viz.ui.remotescript.job.JobsModelProvider
*
* 26 March 2014
*
* This code has been developed by the NCEP/SIB for use in the AWIPS2 system.
*/
package gov.noaa.nws.ncep.viz.ui.remotescript.job;
/**
* Model part of the remote job MVC.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 03/14 ? B. Yin Initial Creation.
*
* </pre>
*
* @author byin
*
*/
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import com.raytheon.uf.viz.core.VizApp;
public enum JobsModelProvider {
INSTANCE;
private List<RemoteScriptJob> jobs;
private List<IRemoteJobObserver> observers;
/**
* Private constructor.
*/
private JobsModelProvider() {
jobs = new ArrayList<RemoteScriptJob>();
observers = new ArrayList<IRemoteJobObserver>();
}
/**
* Get remote jobs submitted.
*
* @return
*/
public List<RemoteScriptJob> getRemoteScriptJobs() {
return jobs;
}
/**
* Add a new job.
*
* @param job
*/
public void addRemoteScriptJob(RemoteScriptJob job) {
notifyObservers(job);
jobs.add(job);
runJob(job);
}
/**
* Update an existing job.
*
* @param job
*/
public void updateRemoteScriptJob(RemoteScriptJob job) {
notifyObservers(job);
}
/**
* Register a job observer.
*
* @param observer
*/
public void registerJobObserver(IRemoteJobObserver observer) {
observers.add(observer);
}
/**
* Notify observers when a new job is added or an existing job is updated.
*
* @param job
*/
private void notifyObservers(RemoteScriptJob job) {
for (IRemoteJobObserver observer : observers) {
if (jobs.contains(job)) {
observer.updateRemoteJob(job);
} else {
observer.addRemoteJob(job);
}
}
}
/**
* Run the specified job and add a job change listener.
*
* @param job
*/
private void runJob(RemoteScriptJob job) {
job.addJobChangeListener((new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
final IJobChangeEvent evt = event;
VizApp.runSync(new Runnable() {
public void run() {
RemoteScriptJob ajob = (RemoteScriptJob) evt.getJob();
updateRemoteScriptJob(ajob);
}
});
}
}));
job.setUser(true);
job.schedule();
}
}

View file

@ -0,0 +1,134 @@
/*
* gov.noaa.nws.ncep.viz.ui.remotescript.job.RemoteScriptJob
*
* 26 March 2014
*
* This code has been developed by the NCEP/SIB for use in the AWIPS2 system.
*/
package gov.noaa.nws.ncep.viz.ui.remotescript.job;
import java.util.Calendar;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import com.raytheon.uf.common.auth.user.IUser;
import com.raytheon.uf.common.localization.LocalizationContext;
import com.raytheon.uf.common.remote.script.RemoteScriptRunRequest;
import com.raytheon.uf.common.remote.script.RemoteScriptRunResponse;
import com.raytheon.uf.viz.core.requests.ThriftClient;
/**
* Remote script job class.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 03/14 ? B. Yin Initial Creation.
*
* </pre>
*
* @author byin
*
*/
public class RemoteScriptJob extends Job {
public enum JobStatus {
IN_PROGRESS, OK, FAIL, TIME_OUT
}
private IUser user;
private String remoteScriptName;
private String arguments;
private LocalizationContext context;
private Calendar timeSubmitted;
private JobStatus status;
private String output = "";
private String error = "";
public RemoteScriptJob(IUser user, String name, String arguments,
LocalizationContext context, Calendar date, JobStatus status) {
super(name + "NCP");
this.user = user;
this.remoteScriptName = name;
this.arguments = arguments;
this.context = context;
this.timeSubmitted = date;
this.status = status;
}
public String getRemoteScriptName() {
return remoteScriptName;
}
public LocalizationContext getContext() {
return context;
}
public String getJobName() {
return remoteScriptName;
}
public String getOutput() {
return output;
}
public Calendar getTmSubmitted() {
return timeSubmitted;
}
public JobStatus getStatus() {
return status;
}
public String getError() {
return error;
}
/**
* Send a request to EDEX to run the job and get the response.
*/
@Override
protected IStatus run(IProgressMonitor monitor) {
RemoteScriptRunRequest runRequest = new RemoteScriptRunRequest(user
.uniqueId().toString(), remoteScriptName, context);
runRequest.setUser(user);
runRequest.parseAndSetScriptArguments(arguments);
try {
RemoteScriptRunResponse runResponse = (RemoteScriptRunResponse) ThriftClient
.sendPrivilegedRequest(runRequest);
if (runResponse != null) {
if (runResponse.isTimedOut()) {
status = JobStatus.TIME_OUT;
} else {
output = runResponse.getOutput();
if (runResponse.getExitStatus() == 0) {
status = JobStatus.OK;
} else {
status = JobStatus.FAIL;
error = runResponse.getError();
}
}
}
} catch (Exception e) {
status = JobStatus.FAIL;
}
return Status.OK_STATUS;
}
}