answer stringlengths 17 10.2M |
|---|
package com.wrapper.spotify.requests;
import com.google.gson.JsonElement;
import com.wrapper.spotify.HttpManager;
import com.wrapper.spotify.UtilProtos.Url;
import java.text.SimpleDateFormat;
public interface Request {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
Url toUrl();
String toString();
String toString(final boolean withQueryParameters);
interface Builder {
AbstractRequest build();
Builder setHttpManager(final HttpManager httpManager);
Builder setScheme(final Url.Scheme scheme);
Builder setHost(final String host);
Builder setPort(final Integer port);
Builder setPath(final String path);
Builder setParameter(final String name, final String value);
Builder setHeaderParameter(final String name, final String value);
Builder setBodyParameter(final String name, final String value);
Builder setPart(final Url.Part part);
Builder setBodyParameter(final JsonElement jsonBody);
}
} |
package org.cactoos.scalar;
import org.cactoos.Func;
import org.cactoos.Scalar;
import org.cactoos.func.FuncOf;
/**
* Ternary operation.
*
* <p>There is no thread-safety guarantee.
*
* <p>This class implements {@link Scalar}, which throws a checked
* {@link Exception}. This may not be convenient in many cases. To make
* it more convenient and get rid of the checked exception you can
* use the {@link Unchecked} decorator. Or you may use
* {@link IoChecked} to wrap it in an IOException.</p>
*
* <pre>{@code
* new Ternary<>(
* scalar,
* value -> value > 3,
* value -> true,
* value -> false
* ).value() // will be equal to true
* }</pre>
*
* @param <T> Type of item.
* @since 0.8
*/
public final class Ternary<T> extends ScalarEnvelope<T> {
/**
* Ctor.
* @param cnd The condition
* @param cons The consequent
* @param alter The alternative
* @since 0.9
*/
public Ternary(final boolean cnd, final T cons, final T alter) {
this(() -> cnd, cons, alter);
}
/**
* Ctor.
* @param cnd The condition
* @param cons The consequent
* @param alter The alternative
*/
public Ternary(final Scalar<Boolean> cnd, final T cons, final T alter) {
this(cnd, () -> cons, () -> alter);
}
/**
* Ctor.
* @param cnd The condition
* @param cons The consequent
* @param alter The alternative
* @since 0.9
*/
public Ternary(
final boolean cnd,
final Scalar<? extends T> cons,
final Scalar<? extends T> alter
) {
this(new Constant<>(cnd), cons, alter);
}
/**
* Ctor.
* @param cnd The condition
* @param cons The consequent
* @param alter The alternative
* @since 0.9
*/
public Ternary(
final Scalar<Boolean> cnd,
final Scalar<? extends T> cons,
final Scalar<? extends T> alter
) {
this(
new Object(),
new FuncOf<>(cnd),
new FuncOf<>(cons),
new FuncOf<>(alter)
);
}
/**
* Ctor.
* @param input The input to pass to all of them
* @param cnd The condition
* @param cons The consequent
* @param alter The alternative
* @param <X> Type of input
* @since 0.9
* @checkstyle ParameterNumberCheck (5 lines)
*/
public <X> Ternary(
final X input,
final Func<? super X, Boolean> cnd,
final Func<? super X, ? extends T> cons,
final Func<? super X, ? extends T> alter
) {
this(new Constant<>(input), cnd, cons, alter);
}
/**
* Ctor.
* @param input The input to pass to all of them
* @param cnd The condition
* @param cons The consequent
* @param alter The alternative
* @param <X> Type of input
* @since 0.9
* @checkstyle ParameterNumberCheck (5 lines)
*/
public <X> Ternary(
final Scalar<? extends X> input,
final Func<? super X, Boolean> cnd,
final Func<? super X, ? extends T> cons,
final Func<? super X, ? extends T> alter
) {
super(() -> {
final X inp = input.value();
final Func<? super X, ? extends T> result;
if (cnd.apply(inp)) {
result = cons;
} else {
result = alter;
}
return result.apply(inp);
});
}
} |
package org.fosstrak.tdt;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.epcglobalinc.tdt.EpcTagDataTranslation;
import org.epcglobalinc.tdt.Field;
import org.epcglobalinc.tdt.GEPC64;
import org.epcglobalinc.tdt.GEPC64Entry;
import org.epcglobalinc.tdt.Level;
import org.epcglobalinc.tdt.LevelTypeList;
import org.epcglobalinc.tdt.ModeList;
import org.epcglobalinc.tdt.Option;
import org.epcglobalinc.tdt.PadDirectionList;
import org.epcglobalinc.tdt.Rule;
import org.epcglobalinc.tdt.Scheme;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
*
* This class provides methods for translating an electronic product code (EPC)
* between various levels of representation including BINARY, TAG_ENCODING,
* PURE_IDENTITY and LEGACY formats. An additional output level ONS_HOSTNAME may
* be defined for some coding schemes.
*
* @author Mark Harrison [University of Cambridge] - mark.harrison@cantab.net
* @author James Brusey
* @author Jochen Mader - jochen@pramari.com
* @author Christian Floerkemeier
*/
public class TDTEngine {
// - Class/Member Variables -/
/**
* prefix_tree_map is a map of levels to prefix trees. Each prefix tree is a
* Trie structure (see wikipedia) that is useful for quickly finding a
* matching prefix.
*/
private Map<LevelTypeList, PrefixTree<PrefixMatch>> prefix_tree_map = new HashMap<LevelTypeList, PrefixTree<PrefixMatch>>();
/**
* HashMap gs1cpi is an associative array providing a lookup between either
* a GS1 Company Prefix and the corresponding integer-based Company Prefix
* Index, where one of these has been registered for use with 64-bit EPCs -
* or the reverse lookup from Company Prefix Index to GS1 Company Prefix.
* Note that this is an optimization to avoid having to do an xpath trawl
* through the CPI table each time.
*/
private HashMap<String, String> gs1cpi = new HashMap<String, String>();
/** The gepc64 table xml. */
private String GEPC64xml;
// - Constructors -/
/**
* Legacy constructor for a new Tag Data Translation engine.
*
* @param confdir
* the string value of the path to a configuration directory
* consisting of two subdirectories, <code>schemes</code> and
* <code>auxiliary</code>.
*
* <p>
* When the class TDTEngine is constructed, the path to a local
* directory must be specified, by passing it as a single string
* parameter to the constructor method (without any trailing
* slash or file separator). e.g.
* <code><pre>TDTEngine engine = new TDTEngine("/opt/TDT");</pre></code>
* </p>
* <p>
* The specified directory must contain two subdirectories named
* auxiliary and schemes. The Tag Data Translation definition
* files for the various coding schemes should be located inside
* the subdirectory called <code>schemes</code>. Any auxiliary
* lookup files (such as <code>ManagerTranslation.xml</code>)
* should be located inside the subdirectory called
* <code>auxiliary</code>.
*
* Files within the schemes directory ending in <code>.xml</code>
* are read in and unmarshalled using JAXB.
*/
@Deprecated
public TDTEngine(String confdir) throws FileNotFoundException,
MarshalException, ValidationException, TDTException {
try {
Unmarshaller unmar = getUnmarshaller();
URL scheme = new URL(confdir + "/schemes/");
URL aux = new URL(confdir + "/auxiliary/ManagerTranslation.xml");
Set<URL> schemes = new HashSet<URL>();
schemes.add(scheme);
URLConnection urlcon = scheme.openConnection();
urlcon.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(urlcon
.getInputStream()));
String line;
for (; (line = in.readLine()) != null;) {
if (line.endsWith(".xml")) {
loadEpcTagDataTranslation(unmar, new URL(scheme.toString()
+ line));
}
}
loadGEPC64Table(unmar, aux);
} catch (MalformedURLException e) {
throw new FileNotFoundException(e.getMessage());
} catch (IOException e) {
throw new FileNotFoundException(e.getMessage());
} catch (JAXBException e) {
throw new MarshalException(e);
}
}
/**
* Constructor for a new Tag Data Translation engine. This constructor uses
* the schemes included on the classpath. All files are unmarshalled using
* JAXB.
*
* @param auxiliary
* URL to the auxiliary file containing a GEPC64Table
* @param schemes
* directory containing the schemes, all files ending in xml are
* read and parsed
* @throws IOException
* thrown if the url is unreachable
* @throws JAXBException
* thrown if the files could not be parsed
*/
public TDTEngine() throws IOException, JAXBException {
Unmarshaller unmar = getUnmarshaller();
URL auxiliary = this.getClass().getClassLoader().getResource(
"auxiliary/ManagerTranslation.xml");
URL schemes = TDTFrontEnd.class.getClassLoader().getResource(
"schemes/schemes.list");
URLConnection urlcon = schemes.openConnection();
urlcon.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(urlcon
.getInputStream()));
String line;
for (; (line = in.readLine()) != null;) {
loadEpcTagDataTranslation(unmar, TDTFrontEnd.class.getClassLoader()
.getResource("schemes/" + line));
}
loadGEPC64Table(unmar, auxiliary);
}
/**
* Constructor for a new Tag Data Translation engine. All files are
* unmarshalled using JAXB.
*
* @param auxiliary
* URL to the auxiliary file containing a GEPC64Table
* @param schemes
* directory containing the schemes, all files ending in xml are
* read and parsed
* @throws IOException
* thrown if the url is unreachable
* @throws JAXBException
* thrown if the files could not be parsed
*/
public TDTEngine(URL auxiliary, URL schemes) throws IOException,
JAXBException {
Unmarshaller unmar = getUnmarshaller();
URLConnection urlcon = schemes.openConnection();
urlcon.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(urlcon
.getInputStream()));
String line;
for (; (line = in.readLine()) != null;) {
if (line.endsWith(".xml")) {
loadEpcTagDataTranslation(unmar, new URL(schemes.toString()
+ line));
}
}
loadGEPC64Table(unmar, auxiliary);
}
/**
* Constructor for a new Tag Data Translation engine. All files are
* unmarshalled using JAXB.
*
* @param auxiliary
* URL to the auxiliary file containing a GEPC64Table
* @param schemes
* set containing several urls pointing to directories containing
* the schemes. All files ending in xml are read and parsed.
* @param absolute
* true if the given URLs are absolute
* @throws IOException
* thrown if the url is unreachable
* @throws JAXBException
* thrown if the files could not be parsed
*/
public TDTEngine(URL auxiliary, Set<URL> schemes, boolean absolute)
throws JAXBException, IOException {
Unmarshaller unmar = getUnmarshaller();
for (URL scheme : schemes) {
if (absolute) {
loadEpcTagDataTranslation(unmar, scheme);
continue;
}
URLConnection urlcon = scheme.openConnection();
urlcon.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(urlcon
.getInputStream()));
String line;
for (; (line = in.readLine()) != null;) {
if (line.endsWith(".xml")) {
loadEpcTagDataTranslation(unmar, new URL(schemes.toString()
+ line));
}
}
}
loadGEPC64Table(unmar, auxiliary);
}
/**
* Creates the unmarshaller.
*
* @return
* @throws JAXBException
*/
private Unmarshaller getUnmarshaller() throws JAXBException {
JAXBContext context = JAXBContext.newInstance(
EpcTagDataTranslation.class, GEPC64.class, GEPC64Entry.class);
return context.createUnmarshaller();
}
/**
* Load an xml file from the given url and unmarshal it into an
* EPCTagDataTranslation.
*
* @param unmar
* @param schemeUrl
* @throws IOException
* @throws JAXBException
*/
private void loadEpcTagDataTranslation(Unmarshaller unmar, URL schemeUrl)
throws IOException, JAXBException {
URLConnection urlcon = schemeUrl.openConnection();
urlcon.connect();
// xml doesn't have enough info for jaxb to figure out
// the
// classname, so we are doing explicit loading
JAXBElement<EpcTagDataTranslation> el = unmar.unmarshal(
new StreamSource(urlcon.getInputStream()),
EpcTagDataTranslation.class);
EpcTagDataTranslation tdt = el.getValue();
initFromTDT(tdt);
}
/**
* Load an xml file from the given url and unmarshal it into a GEPC64Table.
*
* @param unmar
* @param auxiliary
* @throws IOException
* @throws JAXBException
*/
private void loadGEPC64Table(Unmarshaller unmar, URL auxiliary)
throws IOException, JAXBException {
URLConnection urlcon = auxiliary.openConnection();
urlcon.connect();
// load the GEPC64Table
JAXBElement<GEPC64> el = unmar.unmarshal(new StreamSource(urlcon
.getInputStream()), GEPC64.class);
GEPC64 cpilookup = el.getValue();
for (GEPC64Entry entry : cpilookup.getEntry()) {
String comp = entry.getCompanyPrefix();
String indx = entry.getIndex().toString();
gs1cpi.put(indx, comp);
gs1cpi.put(comp, indx);
}
}
// - Methods -/
private class PrefixMatch {
private Scheme s;
private Level level;
public PrefixMatch(Scheme s, Level level) {
this.s = s;
this.level = level;
}
public Scheme getScheme() {
return s;
}
public Level getLevel() {
return level;
}
}
/** initialise various indices */
private void initFromTDT(EpcTagDataTranslation tdt) {
for (Scheme ss : tdt.getScheme()) {
// create an index so that we can find a scheme based on tag length
for (Level level : ss.getLevel()) {
String s = level.getPrefixMatch();
if (s != null) {
// insert into prefix tree according to level type.
PrefixTree<PrefixMatch> prefix_tree = prefix_tree_map
.get(level.getType());
if (prefix_tree == null) {
prefix_tree = new PrefixTree<PrefixMatch>();
prefix_tree_map.put(level.getType(), prefix_tree);
}
prefix_tree.insert(s, new PrefixMatch(ss, level));
}
}
}
}
/**
* Given an input string, and optionally a tag length, find a scheme / level
* with a matching prefix and tag length.
*/
private PrefixMatch findPrefixMatch(String input, String tagLength) {
List<PrefixMatch> match_list = new ArrayList<PrefixMatch>();
for (PrefixTree<PrefixMatch> tree : prefix_tree_map.values()) {
List<PrefixMatch> list = tree.search(input);
if (!list.isEmpty()) {
if (tagLength == null)
match_list.addAll(list);
else {
for (PrefixMatch match : list) {
if (match.getScheme().getTagLength().equals(tagLength))
match_list.add(match);
}
}
}
}
if (match_list.isEmpty())
throw new TDTException(
"No schemes or levels matched the input value");
else if (match_list.size() > 1)
throw new TDTException(
"More than one scheme/level matched the input value");
else
return match_list.get(0);
}
/**
* Given an input string, level, and optionally a tag length, find a
* matching prefix.
*/
private PrefixMatch findPrefixMatch(String input, String tagLength,
LevelTypeList level_type) {
List<PrefixMatch> match_list = new ArrayList<PrefixMatch>();
PrefixTree<PrefixMatch> tree = prefix_tree_map.get(level_type);
assert tree != null;
List<PrefixMatch> list = tree.search(input);
if (!list.isEmpty()) {
if (tagLength == null)
match_list.addAll(list);
else {
for (PrefixMatch match : list)
if (match.getScheme().getTagLength() == tagLength)
match_list.add(match);
}
}
if (match_list.isEmpty())
throw new TDTException(
"No schemes or levels matched the input value");
else if (match_list.size() > 1)
throw new TDTException(
"More than one scheme/level matched the input value");
else
return match_list.get(0);
}
/**
* Translates the input string of a specified input level to a specified
* outbound level of the same coding scheme. For example, the input string
* value may be a tag-encoding URI and the outbound level specified by
* string outboundlevel may be BINARY, in which case the return value is a
* binary representation expressed as a string.
*
* <p>
* Note that this version of the method requires that the user specify the
* input level, rather than searching for it. However it still automatically
* finds the scheme used.
* </p>
*
* @param input
* input tag coding
* @param inputLevel
* level such as BINARY, or TAG_ENCODING.
* @param tagLength
* tag length such as VALUE_64 or VALUE_96.
* @param inputParameters
* a map with any additional properties.
* @param outputLevel
* required output level.
* @return output tag coding
*/
public String convert(String input, LevelTypeList inputLevel,
String tagLength, Map<String, String> inputParameters,
LevelTypeList outputLevel) {
PrefixMatch match = findPrefixMatch(input, tagLength, inputLevel);
return convertLevel(match.getScheme(), match.getLevel(), input,
inputParameters, outputLevel);
}
/**
* The convert method translates a String input to a specified outbound
* level of the same coding scheme. For example, the input string value may
* be a tag-encoding URI and the outbound level specified by string
* outboundlevel may be BINARY, in which case the return value is a binary
* representation expressed as a string.
*
* @param input
* the identifier to be converted.
* @param inputParameters
* additional parameters which need to be provided because they
* cannot always be determined from the input value alone.
* Examples include the taglength, companyprefixlength and filter
* values.
* @param outputLevel
* the outbound level required for the ouput. Permitted values
* include BINARY, TAG_ENCODING, PURE_IDENTITY, LEGACY and
* ONS_HOSTNAME.
* @return the identifier converted to the output level.
*/
public String convert(String input, Map<String, String> inputParameters,
LevelTypeList outputLevel) {
String tagLength = null;
if (inputParameters.containsKey("taglength")) {
// in principle, the user should provide a
// TagLengthList object in the parameter list.
String s = inputParameters.get("taglength");
tagLength = s;
}
PrefixMatch match = findPrefixMatch(input, tagLength);
return convertLevel(match.getScheme(), match.getLevel(), input,
inputParameters, outputLevel);
}
/**
* convert from a particular scheme / level
*/
private String convertLevel(Scheme tdtscheme, Level tdtlevel, String input,
Map<String, String> inputParameters, LevelTypeList outboundlevel) {
String outboundstring;
Map<String, String> extraparams =
// new NoisyMap
(new HashMap<String, String>(inputParameters));
// get the scheme's option key, which is the name of a
// parameter whose value is matched to the option key of the
// level.
String optionkey = tdtscheme.getOptionKey();
String optionValue = extraparams.get(optionkey);
// the name of a parameter which allows the appropriate option
// to be selected
// now consider the various options within the scheme and
// level for each option element inside the level, check
// whether the pattern attribute matches as a regular
// expression
String matchingOptionKey = null;
Option matchingOption = null;
Matcher prefixMatcher = null;
for (Option opt : tdtlevel.getOption()) {
if (optionValue == null || optionValue.equals(opt.getOptionKey())) {
// possible match
Matcher matcher = Pattern.compile(opt.getPattern()).matcher(
input);
if (matcher.matches()) {
if (prefixMatcher != null)
throw new TDTException("Multiple patterns matched");
prefixMatcher = matcher;
matchingOptionKey = opt.getOptionKey();
matchingOption = opt;
}
}
}
if (prefixMatcher == null)
throw new TDTException("No patterns matched");
optionValue = matchingOptionKey;
for (Field field : matchingOption.getField()) {
BigInteger seq = field.getSeq();
String strfieldname = field.getName();
String strfieldvalue = prefixMatcher.group(seq.intValue());
// System.out.println(" processing field " + strfieldname + " = '"
// + strfieldvalue + "'");
if (field.getCompaction() == null) {
// if compaction is null, treat field as an integer
if (field.getCharacterSet() != null) { // if the character set
// is specified
Matcher charsetmatcher = Pattern.compile(
"^" + field.getCharacterSet() + "$").matcher(
strfieldvalue);
if (!charsetmatcher.matches()) {
throw new TDTException(
"field "
+ strfieldname
+ " ("
+ strfieldvalue
+ ") does not conform to the allowed character set ("
+ field.getCharacterSet() + ") ");
}
}
BigInteger bigvalue = null;
if (tdtlevel.getType() == LevelTypeList.BINARY) { // if the
// input was
// BINARY
bigvalue = new BigInteger(strfieldvalue, 2);
extraparams.put(strfieldname, bigvalue.toString());
} else {
if (field.getDecimalMinimum() != null
|| field.getDecimalMaximum() != null)
bigvalue = new BigInteger(strfieldvalue);
extraparams.put(strfieldname, strfieldvalue);
}
if (field.getDecimalMinimum() != null) { // if the decimal
// minimum is
// specified
BigInteger bigmin = new BigInteger(field
.getDecimalMinimum());
if (bigvalue.compareTo(bigmin) == -1) { // throw an
// exception if the
// field value is
// less than the
// decimal minimum
throw new TDTException("field " + strfieldname + " ("
+ bigvalue + ") is less than DecimalMinimum ("
+ field.getDecimalMinimum() + ") allowed");
}
}
if (field.getDecimalMaximum() != null) { // if the decimal
// maximum is
// specified
BigInteger bigmax = new BigInteger(field
.getDecimalMaximum());
if (bigvalue.compareTo(bigmax) == 1) { // throw an excpetion
// if the field
// value is greater
// than the decimal
// maximum
throw new TDTException("field " + strfieldname + " ("
+ bigvalue
+ ") is greater than DecimalMaximum ("
+ field.getDecimalMaximum() + ") allowed");
}
}
// after extracting the field, it may be necessary to pad it.
padField(extraparams, field);
} else {
// compaction is specified - interpret binary as a string value
// using a truncated byte per character
String compaction = field.getCompaction();
PadDirectionList padDir = field.getPadDir();
String padchar = field.getPadChar();
String s;
if ("5-bit".equals(compaction))
// "5-bit"
s = bin2uppercasefive(strfieldvalue);
else if ("6-bit".equals(compaction))
// 6-bit
s = bin2alphanumsix(strfieldvalue);
else if ("7-bit".equals(compaction))
// 7-bit
s = bin2asciiseven(strfieldvalue);
else if ("8-bit".equals(compaction))
// 8-bit
s = bin2bytestring(strfieldvalue);
else
throw new Error("unsupported compaction method "
+ compaction);
extraparams.put(strfieldname, stripPadChar(s, padDir, padchar));
}
} // for each field;
/**
* the EXTRACT rules are performed after parsing the input, in order to
* determine additional fields that are to be derived from the fields
* obtained by the pattern match process
*/
int seq = 0;
for (Rule tdtrule : tdtlevel.getRule()) {
if (tdtrule.getType() == ModeList.EXTRACT) {
assert seq < tdtrule.getSeq().intValue() : "Rule out of sequence order";
seq = tdtrule.getSeq().intValue();
processRules(extraparams, tdtrule);
}
}
/**
* Now we need to consider the corresponding output level and output
* option. The scheme must remain the same, as must the value of
* optionkey (to select the corresponding option element nested within
* the required outbound level)
*/
Level tdtoutlevel = findLevel(tdtscheme, outboundlevel);
Option tdtoutoption = findOption(tdtoutlevel, optionValue);
/**
* the FORMAT rules are performed before formatting the output, in order
* to determine additional fields that are required for preparation of
* the outbound format
*/
seq = 0;
for (Rule tdtrule : tdtoutlevel.getRule()) {
if (tdtrule.getType() == ModeList.FORMAT) {
assert seq < tdtrule.getSeq().intValue() : "Rule out of sequence order";
seq = tdtrule.getSeq().intValue();
processRules(extraparams, tdtrule);
}
}
/**
* Now we need to ensure that all fields required for the outbound
* grammar are suitably padded etc. processPadding takes care of firstly
* padding the non-binary fields if padChar and padDir, length are
* specified then (if necessary) converting to binary and padding the
* binary representation to the left with zeros if the bit string is has
* fewer bits than the bitLength attribute specifies. N.B. TDTv1.1 will
* be more specific about bit-level padding rather than assuming that it
* is always to the left with the zero bit.
*/
// System.out.println(" prior to processPadding, " + extraparams);
for (Field field : tdtoutoption.getField()) {
// processPadding(extraparams, field, outboundlevel, tdtoutoption);
padField(extraparams, field);
if (outboundlevel == LevelTypeList.BINARY)
binaryPadding(extraparams, field);
}
/**
* Construct the output from the specified grammar (in ABNF format)
* together with the field values stored in inputparams
*/
outboundstring = buildGrammar(tdtoutoption.getGrammar(), extraparams);
// System.out.println("final extraparams = " + extraparams);
// System.out.println("returned " + outboundstring);
return outboundstring;
}
/**
*
* Converts a binary string into a large integer (numeric string)
*/
private String bin2dec(String binary) {
BigInteger dec = new BigInteger(binary, 2);
return dec.toString();
}
/**
*
* Converts a large integer (numeric string) to a binary string
*/
private String dec2bin(String decimal) {
// TODO: required?
if (decimal == null) {
decimal = "1";
}
BigInteger bin = new BigInteger(decimal);
return bin.toString(2);
}
/**
*
* Converts a hexadecimal string to a binary string
*/
private String hex2bin(String hex) {
BigInteger bin = new BigInteger(hex.toLowerCase(), 16);
return bin.toString(2);
}
/**
*
* Converts a binary string to a hexadecimal string
*/
private String bin2hex(String binary) {
BigInteger hex = new BigInteger(binary, 2);
return hex.toString(16).toUpperCase();
}
/**
* Returns a string built using a particular grammar. Single-quotes strings
* are counted as literal strings, whereas all other strings appearing in
* the grammar require substitution with the corresponding value from the
* extraparams hashmap.
*/
private String buildGrammar(String grammar, Map<String, String> extraparams) {
StringBuilder outboundstring = new StringBuilder();
String[] fields = Pattern.compile("\\s+").split(grammar);
for (int i = 0; i < fields.length; i++) {
if (fields[i].substring(0, 1).equals("'")) {
outboundstring.append(fields[i].substring(1,
fields[i].length() - 1));
} else {
outboundstring.append(extraparams.get(fields[i]));
}
}
return outboundstring.toString();
}
/**
*
* Converts the value of a specified fieldname from the extraparams map into
* binary, either handling it as a large integer or taking into account the
* compaction of each ASCII byte that is specified in the TDT definition
* file for that particular field
*/
private String fieldToBinary(Field field, Map<String, String> extraparams) {
// really need an index to find field number given fieldname;
String fieldname = field.getName();
String value = extraparams.get(fieldname);
String compaction = field.getCompaction();
if (compaction == null) {
value = dec2bin(value);
} else {
if ("5-bit".equals(compaction)) {
value = uppercasefive2bin(value);
} else if ("6-bit".equals(compaction)) {
value = alphanumsix2bin(value);
} else if ("7-bit".equals(compaction)) {
value = asciiseven2bin(value);
} else if ("8-bit".equals(compaction)) {
value = bytestring2bin(value);
} else
throw new Error("Unsupported compaction " + compaction);
}
return value;
}
/**
* pad a value according the field definition.
*/
private void padField(Map<String, String> extraparams, Field field) {
String name = field.getName();
String value = extraparams.get(name);
PadDirectionList padDir = field.getPadDir();
int requiredLength = 0;
if (field.getLength() != null) {
requiredLength = field.getLength().intValue();
}
// assert value != null;
if (value == null)
return;
String padCharString = field.getPadChar();
// if no pad char specified, don't attempt padding
if (padCharString == null)
return;
assert padCharString.length() > 0;
char padChar = padCharString.charAt(0);
StringBuilder buf = new StringBuilder(requiredLength);
if (padDir == PadDirectionList.LEFT) {
for (int i = 0; i < requiredLength - value.length(); i++)
buf.append(padChar);
buf.append(value);
} else if (padDir == PadDirectionList.RIGHT) {
buf.append(value);
for (int i = 0; i < requiredLength - value.length(); i++)
buf.append(padChar);
}
assert buf.length() == requiredLength;
if (requiredLength != value.length()) {
// System.out.println(" updated " + name + " to '" + buf + "'");
extraparams.put(name, buf.toString());
}
/*
* else { StringBuilder mybuf = new StringBuilder(); for (int i = 0; i <
* value.length(); i++) { if (i > 0) mybuf.append(',');
* mybuf.append('\''); mybuf.append(value.charAt(i));
* mybuf.append('\''); }
*
*
* System.out.println(" field " + name + " not padded as " +
* mybuf.toString() + " is already " + requiredLength +
* " characters long"); }
*/
}
/**
* If the outbound level is BINARY, convert the string field to binary, then
* pad to the left with the appropriate number of zero bits to reach a
* number of bits specified by the bitLength attribute of the TDT definition
* file.
*/
private void binaryPadding(Map<String, String> extraparams, Field tdtfield) {
String fieldname = tdtfield.getName();
int reqbitlength = tdtfield.getBitLength().intValue();
String value;
String binaryValue = fieldToBinary(tdtfield, extraparams);
if (binaryValue.length() < reqbitlength) {
int extraBitLength = reqbitlength - binaryValue.length();
StringBuilder zeroPaddedBinaryValue = new StringBuilder("");
for (int i = 0; i < extraBitLength; i++) {
zeroPaddedBinaryValue.append("0");
}
zeroPaddedBinaryValue.append(binaryValue);
value = zeroPaddedBinaryValue.toString();
} else {
if (binaryValue.length() > reqbitlength)
throw new TDTException("Binary value [" + binaryValue
+ "] for field " + fieldname
+ " exceeds maximum allowed " + reqbitlength
+ " bits. Decimal value was "
+ extraparams.get(fieldname));
value = binaryValue;
}
extraparams.put(fieldname, value);
}
/**
* Removes leading or trailing characters equal to padchar from the
* start/end of the string specified as the first parameter. The second
* parameter specified the stripping direction as "LEFT" or "RIGHT" and the
* third parameter specifies the character to be stripped.
*/
private String stripPadChar(String field, PadDirectionList paddir,
String padchar) {
String rv;
if (paddir == null || padchar == null)
rv = field;
else {
String pattern;
if (paddir == PadDirectionList.RIGHT)
pattern = "[" + padchar + "]+$";
else
// if (paddir == PadDirectionList.LEFT)
pattern = "^[" + padchar + "]+";
rv = field.replaceAll(pattern, "");
}
return rv;
}
/**
*
* Adds additional entries to the extraparams hashmap by processing various
* rules defined in the TDT definition files. Typically used for string
* processing functions, lookup in tables, calculation of check digits etc.
*/
private void processRules(Map<String, String> extraparams, Rule tdtrule) {
String tdtfunction = tdtrule.getFunction();
int openbracket = tdtfunction.indexOf("(");
assert openbracket != -1;
String params = tdtfunction.substring(openbracket + 1, tdtfunction
.length() - 1);
String rulename = tdtfunction.substring(0, openbracket);
String[] parameter = params.split(",");
String newfieldname = tdtrule.getNewFieldName();
// System.out.println(tdtfunction + " " + parameter[0] + " " +
// extraparams.get(parameter[0]));
/**
* Stores in the hashmap extraparams the value obtained from a lookup in
* a specified XML table.
*
* The first parameter is the given value already known. This is denoted
* as $1 in the corresponding XPath expression
*
* The second parameter is the string filename of the table which must
* be present in the auxiliary subdirectory
*
* The third parameter is the column in which the supplied input value
* should be sought
*
* The fourth parameter is the column whose value should be read for the
* corresponding row, in order to obtain the result of the lookup.
*
* The rule in the definition file may contain an XPath expression and a
* URL where the table may be obtained.
*/
if (rulename.equals("TABLELOOKUP")) {
// parameter[0] is given value
// parameter[1] is table
// parameter[2] is input column supplied
// parameter[3] is output column required
assert parameter.length == 4 : "incorrect number of parameters to tablelookup "
+ params;
if (parameter[1].equals("tdt64bitcpi")) {
String s = extraparams.get(parameter[0]);
assert s != null : tdtfunction + " when " + parameter[0]
+ " is null";
String t = gs1cpi.get(s);
assert t != null : "gs1cpi[" + s + "] is null";
assert newfieldname != null;
extraparams.put(newfieldname, t);
// extraparams.put(newfieldname,
// gs1cpi.get(extraparams.get(parameter[0])));
} else { // JPB! the following is untested
String tdtxpath = tdtrule.getTableXPath();
String tdttableurl = tdtrule.getTableURL();
String tdtxpathsub = tdtxpath.replaceAll("\\$1", extraparams
.get(parameter[0]));
extraparams.put(newfieldname, xpathlookup(
"ManagerTranslation.xml", tdtxpathsub));
}
}
/**
* Stores the length of the specified string under the new fieldname
* specified by the corresponding rule of the definition file.
*/
if (rulename.equals("LENGTH")) {
assert extraparams.get(parameter[0]) != null : tdtfunction
+ " when " + parameter[0] + " is null";
if (extraparams.get(parameter[0]) != null) {
extraparams.put(newfieldname, Integer.toString(extraparams.get(
parameter[0]).length()));
}
}
/**
* Stores a GS1 check digit in the extraparams hashmap, keyed under the
* new fieldname specified by the corresponding rule of the definition
* file.
*/
if (rulename.equals("GS1CHECKSUM")) {
assert extraparams.get(parameter[0]) != null : tdtfunction
+ " when " + parameter[0] + " is null";
if (extraparams.get(parameter[0]) != null) {
extraparams.put(newfieldname, gs1checksum(extraparams
.get(parameter[0])));
}
}
/**
* Obtains a substring of the string provided as the first parameter. If
* only a single second parameter is specified, then this is considered
* as the start index and all characters from the start index onwards
* are stored in the extraparams hashmap under the key named
* 'newfieldname' in the corresponding rule of the definition file. If a
* second and third parameter are specified, then the second parameter
* is the start index and the third is the length of characters
* required. A substring consisting characters from the start index up
* to the required length of characters is stored in the extraparams
* hashmap, keyed under the new fieldname specified by the corresponding
* rule of the defintion file.
*/
if (rulename.equals("SUBSTR")) {
assert extraparams.get(parameter[0]) != null : tdtfunction
+ " when " + parameter[0] + " is null";
if (parameter.length == 2) {
if (extraparams.get(parameter[0]) != null) {
int start = getIntValue(parameter[1], extraparams);
if (start >= 0) {
extraparams.put(newfieldname, extraparams.get(
parameter[0]).substring(start));
}
}
}
if (parameter.length == 3) { // need to check that this variation is
// correct - c.f. Perl substr
assert extraparams.get(parameter[0]) != null : tdtfunction
+ " when " + parameter[0] + " is null";
if (extraparams.get(parameter[0]) != null) {
int start = getIntValue(parameter[1], extraparams);
int end = getIntValue(parameter[2], extraparams);
if ((start >= 0) && (end >= 0)) {
extraparams.put(newfieldname, extraparams.get(
parameter[0]).substring(start, start + end));
}
}
}
}
/**
* Concatenates specified string parameters together. Literal values
* must be enclosed within single or double quotes or consist of
* unquoted digits. Other unquoted strings are considered as fieldnames
* and the corresponding value from the extraparams hashmap are
* inserted. The result of the concatenation (and substitution) of the
* strings is stored as a new entry in the extraparams hashmap, keyed
* under the new fieldname specified by the rule.
*/
if (rulename.equals("CONCAT")) {
StringBuilder buffer = new StringBuilder();
for (int p1 = 0; p1 < parameter.length; p1++) {
Matcher matcher = Pattern.compile("\"(.*?)\"|'(.*?)'|[0-9]")
.matcher(parameter[p1]);
if (matcher.matches()) {
buffer.append(parameter[p1]);
} else {
assert extraparams.get(parameter[p1]) != null : tdtfunction
+ " when " + parameter[p1] + " is null";
if (extraparams.get(parameter[p1]) != null) {
buffer.append(extraparams.get(parameter[p1]));
}
}
}
extraparams.put(newfieldname, buffer.toString());
}
}
/**
*
* Returns the value of a specified fieldname from the specified hashmap and
* returns an integer value or throws an exception if the value is not an
* integer
*/
private int getIntValue(String fieldname, Map<String, String> extraparams) {
Matcher checkint = Pattern.compile("^\\d+$").matcher(fieldname);
int rv;
if (checkint.matches()) {
rv = Integer.parseInt(fieldname);
} else {
if (extraparams.containsKey(fieldname)) {
rv = Integer.parseInt(extraparams.get(fieldname));
} else {
rv = -1;
throw new TDTException("No integer value for " + fieldname
+ " can be found - check extraparams");
}
}
return rv;
}
/**
*
* Performs an XPATH lookup in an xml document. The document has been loaded
* into a private member. The XPATH expression is supplied as the second
* string parameter The return value is of type string e.g. this is
* currently used primarily for looking up the Company Prefix Index for
* encoding a GS1 Company Prefix into a 64-bit EPC tag
*
*/
private String xpathlookup(String xml, String expression) {
try {
// Parse the XML as a W3C document.
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = builder.parse(GEPC64xml);
XPath xpath = XPathFactory.newInstance().newXPath();
String rv = (String) xpath.evaluate(expression, document,
XPathConstants.STRING);
return rv;
} catch (ParserConfigurationException e) {
System.err.println("ParserConfigurationException caught...");
e.printStackTrace();
return null;
} catch (XPathExpressionException e) {
System.err.println("XPathExpressionException caught...");
e.printStackTrace();
return null;
} catch (SAXException e) {
System.err.println("SAXException caught...");
e.printStackTrace();
return null;
} catch (IOException e) {
System.err.println("IOException caught...");
e.printStackTrace();
return null;
}
}
// auxiliary functions
/**
*
* Converts a binary string input into a byte string, using 8-bits per
* character byte
*/
private String bytestring2bin(String bytestring) {
String binary;
StringBuilder buffer = new StringBuilder("");
int len = bytestring.length();
byte[] bytes = bytestring.getBytes();
for (int i = 0; i < len; i++) {
buffer.append(padBinary(dec2bin(Integer.toString(bytes[i])), 8));
}
binary = buffer.toString();
return binary;
}
/**
*
* Converts a byte string input into a binary string, using 8-bits per
* character byte
*/
private String bin2bytestring(String binary) {
String bytestring;
StringBuilder buffer = new StringBuilder("");
int len = binary.length();
for (int i = 0; i < len; i += 8) {
int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i,
i + 8), 8)));
buffer.append((char) j);
}
bytestring = buffer.toString();
return bytestring;
}
/**
*
* Converts an ASCII string input into a binary string, using 7-bit
* compaction of each ASCII byte
*/
private String asciiseven2bin(String asciiseven) {
String binary;
StringBuilder buffer = new StringBuilder("");
int len = asciiseven.length();
byte[] bytes = asciiseven.getBytes();
for (int i = 0; i < len; i++) {
buffer.append(padBinary(dec2bin(Integer.toString(bytes[i] % 128)),
8).substring(1, 8));
}
binary = buffer.toString();
return binary;
}
/**
*
* Converts a binary string input into an ASCII string output, assuming that
* 7-bit compaction was used
*/
private String bin2asciiseven(String binary) {
String asciiseven;
StringBuilder buffer = new StringBuilder("");
int len = binary.length();
for (int i = 0; i < len; i += 7) {
int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i,
i + 7), 8)));
buffer.append((char) j);
}
asciiseven = buffer.toString();
return asciiseven;
}
/**
* Converts an alphanumeric string input into a binary string, using 6-bit
* compaction of each ASCII byte
*/
private String alphanumsix2bin(String alphanumsix) {
String binary;
StringBuilder buffer = new StringBuilder("");
int len = alphanumsix.length();
byte[] bytes = alphanumsix.getBytes();
for (int i = 0; i < len; i++) {
buffer
.append(padBinary(dec2bin(Integer.toString(bytes[i] % 64)),
8).substring(2, 8));
}
binary = buffer.toString();
return binary;
}
/**
*
* Converts a binary string input into a character string output, assuming
* that 6-bit compaction was used
*/
private String bin2alphanumsix(String binary) {
String alphanumsix;
StringBuilder buffer = new StringBuilder("");
int len = binary.length();
for (int i = 0; i < len; i += 6) {
int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i,
i + 6), 8)));
if (j < 32) {
j += 64;
}
buffer.append((char) j);
}
alphanumsix = buffer.toString();
return alphanumsix;
}
/**
* Converts an upper case character string input into a binary string, using
* 5-bit compaction of each ASCII byte
*/
private String uppercasefive2bin(String uppercasefive) {
String binary;
StringBuilder buffer = new StringBuilder("");
int len = uppercasefive.length();
byte[] bytes = uppercasefive.getBytes();
for (int i = 0; i < len; i++) {
buffer
.append(padBinary(dec2bin(Integer.toString(bytes[i] % 32)),
8).substring(3, 8));
}
binary = buffer.toString();
return binary;
}
/**
*
* Converts a binary string input into a character string output, assuming
* that 5-bit compaction was used
*/
private String bin2uppercasefive(String binary) {
String uppercasefive;
StringBuilder buffer = new StringBuilder("");
int len = binary.length();
for (int i = 0; i < len; i += 5) {
int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i,
i + 5), 8)));
buffer.append((char) (j + 64));
}
uppercasefive = buffer.toString();
return uppercasefive;
}
/**
* Pads a binary value supplied as a string first parameter to the left with
* leading zeros in order to reach a required number of bits, as expressed
* by the second parameter, reqlen. Returns a string value corresponding to
* the binary value left padded to the required number of bits.
*/
private String padBinary(String binary, int reqlen) {
String rv;
int l = binary.length();
int pad = (reqlen - (l % reqlen)) % reqlen;
StringBuilder buffer = new StringBuilder("");
for (int i = 0; i < pad; i++) {
buffer.append("0");
}
buffer.append(binary);
rv = buffer.toString();
return rv;
}
/**
* Calculates the check digit for a supplied input string (assuming that the
* check digit will be the digit immediately following the supplied input
* string). GS1 (formerly EAN.UCC) check digit calculation methods are used.
*/
private String gs1checksum(String input) {
int checksum;
int weight;
int total = 0;
int len = input.length();
int d;
for (int i = 0; i < len; i++) {
if (i % 2 == 0) {
weight = -3;
} else {
weight = -1;
}
d = Integer.parseInt(input.substring(len - 1 - i, len - i));
total += weight * d;
}
checksum = (10 + total % 10) % 10;
return Integer.toString(checksum);
}
/**
* find a level by its type in a scheme. This involves iterating through the
* list of levels. The main reason for doing it this way is to avoid being
* dependent on the order in which the levels are coded in the xml, which is
* not explicitly constrained.
*/
private Level findLevel(Scheme scheme, LevelTypeList levelType) {
Level level = null;
for (Level lev : scheme.getLevel()) {
if (lev.getType() == levelType) {
level = lev;
break;
}
}
if (level == null)
throw new Error("Couldn't find type " + levelType + " in scheme "
+ scheme);
return level;
}
/**
* find a option by its type in a scheme. This involves iterating through
* the list of options. The main reason for doing it this way is to avoid
* being dependent on the order in which the options are coded in the xml,
* which is not explicitly constrained.
*/
private Option findOption(Level level, String optionKey) {
Option option = null;
for (Option opt : level.getOption()) {
if (opt.getOptionKey().equals(optionKey)) {
option = opt;
break;
}
}
if (option == null)
throw new Error("Couldn't find option for " + optionKey
+ " in level " + level);
return option;
}
} |
package am.app.mappingEngine;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import am.app.Core;
import am.app.mappingEngine.AbstractMatcher.alignType;
import am.app.mappingEngine.Mapping.MappingRelation;
import am.app.ontology.Node;
import am.app.ontology.Ontology;
/**
* This interface represents a Similarity Matrix.
*
* The idea is to separate the definition of a Similarity Matrix from the
* implementation.
*
* We can have similarity matrices
* (1) in a memory array (ArraySimilarityMatrix)
* (2) in a sparse matrix representation
* (3) in a database
*/
public abstract class SimilarityMatrix
{
/* Fields */
protected int sourceOntologyID, targetOntologyID;
//not used at the moment. At the moment indetermined similarity are set with 0.
//if we want to start using it is important to keep it similar to 0, to allow compatibility with non-updated methods.
final static double INDETERMINED = Double.MIN_NORMAL;
protected MappingRelation relation = MappingRelation.EQUIVALENCE; //this is a default relation used when no relation is specified for this matrix
protected alignType typeOfMatrix;
public MappingRelation getRelation() { return relation; }; // relation of the matrix? is this required?
public abstract alignType getAlignType();
/* Getters and Setters */
public int getSourceOntologyID() { return sourceOntologyID; }
public void setSourceOntologyID(int sourceOntologyID) { this.sourceOntologyID = sourceOntologyID; }
public int getTargetOntologyID() { return targetOntologyID; }
public void setTargetOntologyID(int targetOntologyID) { this.targetOntologyID = targetOntologyID; }
public abstract int getRows();
public abstract int getColumns();
public abstract Mapping get(int i, int j);
public abstract void set(int i, int j, Mapping d);
@Deprecated
public abstract void setSimilarity(int i, int j, double d); // deprecated because it cannot deal with null values.
public abstract double getSimilarity( int i, int j);
/* Methods that calculate */
public abstract List<Mapping> chooseBestN();
public abstract List<Mapping> chooseBestN(List<Integer> rowsIncludedList, List<Integer> colsIncludedList, boolean considerThreshold, double threshold);
public abstract List<Mapping> chooseBestN(boolean considerThreshold, double threshold);
public abstract List<Mapping> chooseBestN(List<Integer> rowsIncludedList, List<Integer> colsIncludedList);
public abstract SimilarityMatrix clone(); // TODO: Should not be abstract? Investigate.
public abstract void initFromNodeList(List<Node> sourceList, List<Node> targetList);
public abstract Mapping[] getColMaxValues(int col, int numMaxValues);
public abstract Mapping[] getRowMaxValues(int row, int numMaxValues);
public abstract double[][] getCopiedSimilarityMatrix();
public abstract double getRowSum(int row);
public abstract double getColSum(int col);
public abstract void fillMatrix(double d, List<Node> sourceList, List<Node> targetList);
/* Mapping retrieval methods */
/**
* This method should return an descending ordered list of mappings that have
* a similarity equal to or above the given threshold.
*
* If you do not want a threshold, set th = 0.0.
*
* Complexity: O( n^2 + n log n );
*
* @param th A threshold. Mappings with similarity equal to or above this threshold will be returned.
* @return Descending list of Mappings with similarity >= th.
*/
public List<Mapping> getOrderedMappingsAboveThreshold( double th ) {
Vector<Mapping> mappingArray = new Vector<Mapping>();
for(int i = 0; i < getRows(); i++){
for(int j = 0; j < getColumns(); j++){
Mapping currentMapping = get(i,j);
if(currentMapping != null && currentMapping.getSimilarity() >= th ){
mappingArray.add(this.get(i, j));
}
}
}
Collections.sort(mappingArray, new MappingSimilarityComparator() );
return mappingArray;
}
public List<Mapping> getOrderedMappingsWithNull() {
Vector<Mapping> mappingArray = new Vector<Mapping>();
for(int i = 0; i < getRows(); i++){
for(int j = 0; j < getColumns(); j++){
Mapping currentMapping = get(i,j);
if( currentMapping == null ) mappingArray.add( new Mapping(null, null, 0.0d) );
else {mappingArray.add(this.get(i, j)); }
}
}
Collections.sort(mappingArray, new MappingSimilarityComparator() );
return mappingArray;
}
/**
* This method returns all the mappings in the matrix.
* Null entries are allocated new Mapping object with similarity = 0.0.
* @return
* @throws Exception
*/
public List<Mapping> toList() throws Exception {
List<Mapping> list = new ArrayList<Mapping>();
for( int row = 0; row < getRows(); row++ ) {
for( int col = 0; col < getColumns(); col++ ) {
Mapping m = get(row, col);
if( m == null ) {
Ontology sourceOntology = Core.getInstance().getOntologyByID(sourceOntologyID);
Ontology targetOntology = Core.getInstance().getOntologyByID(targetOntologyID);
if( typeOfMatrix == alignType.aligningClasses ) {
Node sN = sourceOntology.getClassesList().get(row);
Node tN = targetOntology.getClassesList().get(col);
list.add( new Mapping(sN, tN, 0.0d) );
} else if( typeOfMatrix == alignType.aligningProperties ) {
Node sN = sourceOntology.getPropertiesList().get(row);
Node tN = targetOntology.getPropertiesList().get(col);
list.add( new Mapping(sN, tN, 0.0d) );
} else {
throw new Exception("Similarity Matrix in invalid state.");
}
}
else list.add(m);
}
}
return list;
}
/* Ranking methods */
public abstract double getMaxValue(); // TODO: Should not be abstract.
public abstract Mapping[] getTopK(int k); // TODO: Should not be abstract.
public abstract Mapping[] getTopK(int k, boolean[][] filteredCells); // TODO: Should not be abstract.
//public abstract int countNonNullValues(); // TODO: What is this used for? Investigate.
public abstract List<Mapping> toMappingArray();
public abstract List<Mapping> toMappingArray(FileWriter fw, int round);
public abstract List<Double> toSimilarityArray(List<Mapping> mapsArray);
public abstract SimilarityMatrix toArraySimilarityMatrix(); // TODO: Is this necessary? Investigate.
} |
package cz.xtf.jolokia;
import io.fabric8.kubernetes.api.model.Pod;
/**
* "%s/api/v1/namespaces/%s/pods/https:%s:8778/proxy/
* jolokia/exec/org.apache.activemq:type=Broker,brokerName=%3$s,destinationType=Queue,destinationName=%s/browse%28%29",
*
* @author David Simansky | dsimansk@redhat.com
*/
public class JolokiaRequestBuilder {
private String masterUrl;
private String namespace;
private Pod pod;
private String beanName;
private AmqJolokiaRequest amqReq;
public static JolokiaRequestBuilder newRequest() {
return new JolokiaRequestBuilder();
}
public JolokiaRequestBuilder withMasterUrl(String masterUrl) {
this.masterUrl = masterUrl;
return this;
}
public JolokiaRequestBuilder withNamespace(String namespace) {
this.namespace = namespace;
return this;
}
public JolokiaRequestBuilder withPod(Pod pod) {
this.pod = pod;
return this;
}
public AmqJolokiaRequest withAmq() {
this.beanName = "org.apache.activemq:type=Broker";
this.amqReq = new AmqJolokiaRequest(this);
return this.amqReq;
}
public JolokiaRequestBuilder endRequest() {
return this;
}
public String build() {
StringBuilder sb = new StringBuilder(masterUrl)
.append("/api/v1/namespaces/").append(namespace).append("/pods")
.append("/https:").append(pod.getMetadata().getName()).append(":8778/proxy")
.append("/jolokia")
.append(this.amqReq.execMethod != null ? "/exec/" : "/read/")
.append(beanName);
if (amqReq != null) {
sb.append(",brokerName=").append(pod.getMetadata().getName())
.append(",destinationType=").append(this.amqReq.destinationType)
.append(",destinationName=").append(this.amqReq.destinationName)
.append("/");
if (this.amqReq.execMethod != null) {
sb.append(this.amqReq.execMethod).append("%28%29");
} else {
sb.append(this.amqReq.attribute);
}
}
return sb.toString();
}
public class AmqJolokiaRequest {
String destinationName;
String destinationType;
String execMethod;
String attribute;
JolokiaRequestBuilder parent;
AmqJolokiaRequest(JolokiaRequestBuilder parent) {
this.parent = parent;
}
public AmqJolokiaRequest withQueue(String name) {
destinationType = "Queue";
destinationName = name;
return this;
}
public AmqJolokiaRequest withExecMethod(String execMethod) {
this.execMethod = execMethod;
return this;
}
public AmqJolokiaRequest withAttribute(String attribute){
this.attribute = attribute;
return this;
}
public JolokiaRequestBuilder endAmq() {
return parent;
}
}
} |
package org.fosstrak.tdt;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.epcglobalinc.tdt.EpcTagDataTranslation;
import org.epcglobalinc.tdt.Field;
import org.epcglobalinc.tdt.GEPC64;
import org.epcglobalinc.tdt.GEPC64Entry;
import org.epcglobalinc.tdt.Level;
import org.epcglobalinc.tdt.LevelTypeList;
import org.epcglobalinc.tdt.ModeList;
import org.epcglobalinc.tdt.Option;
import org.epcglobalinc.tdt.PadDirectionList;
import org.epcglobalinc.tdt.Rule;
import org.epcglobalinc.tdt.Scheme;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
*
* This class provides methods for translating an electronic product code (EPC)
* between various levels of representation including BINARY, TAG_ENCODING,
* PURE_IDENTITY and LEGACY formats. An additional output level ONS_HOSTNAME may
* be defined for some coding schemes.
*
* @author Mark Harrison [University of Cambridge] - mark.harrison@cantab.net
* @author James Brusey
* @author Jochen Mader - jochen@pramari.com
* @author Christian Floerkemeier
*/
public class TDTEngine {
// - Class/Member Variables -/
final Boolean showdebug=true; // if true, print any debug messages;
/**
* prefix_tree_map is a map of levels to prefix trees. Each prefix tree is a
* Trie structure (see wikipedia) that is useful for quickly finding a
* matching prefix.
*/
private Map<LevelTypeList, PrefixTree<PrefixMatch>> prefix_tree_map = new HashMap<LevelTypeList, PrefixTree<PrefixMatch>>();
/**
* HashMap gs1cpi is an associative array providing a lookup between either
* a GS1 Company Prefix and the corresponding integer-based Company Prefix
* Index, where one of these has been registered for use with 64-bit EPCs -
* or the reverse lookup from Company Prefix Index to GS1 Company Prefix.
* Note that this is an optimization to avoid having to do an xpath trawl
* through the CPI table each time.
*/
private HashMap<String, String> gs1cpi = new HashMap<String, String>();
/** The gepc64 table xml. */
private String GEPC64xml;
// - Constructors -/
/**
* Legacy constructor for a new Tag Data Translation engine.
*
* @param confdir
* the string value of the path to a configuration directory
* consisting of two subdirectories, <code>schemes</code> and
* <code>auxiliary</code>.
*
* <p>
* When the class TDTEngine is constructed, the path to a local
* directory must be specified, by passing it as a single string
* parameter to the constructor method (without any trailing
* slash or file separator). e.g.
* <code><pre>TDTEngine engine = new TDTEngine("/opt/TDT");</pre></code>
* </p>
* <p>
* The specified directory must contain two subdirectories named
* auxiliary and schemes. The Tag Data Translation definition
* files for the various coding schemes should be located inside
* the subdirectory called <code>schemes</code>. Any auxiliary
* lookup files (such as <code>ManagerTranslation.xml</code>)
* should be located inside the subdirectory called
* <code>auxiliary</code>.
*
* Files within the schemes directory ending in <code>.xml</code>
* are read in and unmarshalled using JAXB.
*/
@Deprecated
public TDTEngine(String confdir) throws FileNotFoundException,
MarshalException, ValidationException, TDTException {
try {
Unmarshaller unmar = getUnmarshaller();
URL confdirurl;
if (confdir.endsWith("/")) {
confdirurl = new URL("file","localhost",confdir);
} else {
confdirurl = new URL("file","localhost",confdir+"/");
}
URL scheme = new URL(confdirurl,"schemes/");
URL auxGEPC64table = new URL(confdirurl,"auxiliary/ManagerTranslation.xml");
Set<String> schemes = new HashSet<String>();
URLConnection urlcon = scheme.openConnection();
urlcon.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
String line;
for (; (line = in.readLine()) != null;) {
if (line.endsWith(".xml")) {
URL defurl = new URL(scheme,line);
loadEpcTagDataTranslation(unmar, defurl);
schemes.add(line);
}
}
loadGEPC64Table(unmar, auxGEPC64table);
} catch (MalformedURLException e) {
throw new FileNotFoundException(e.getMessage());
} catch (IOException e) {
throw new FileNotFoundException(e.getMessage());
} catch (JAXBException e) {
throw new MarshalException(e);
}
}
/**
* Constructor for a new Tag Data Translation engine. This constructor uses
* the schemes included on the classpath in a directory called schemes
* (or from within the jar). The ManagerTranslation.xml file is loaded from a directory
* called auxiliary on the classpath. All schemes must have filenames ending in .xml
* Note that previously this constructor required all schemes to be listed within a file schemes.list
* The constructor has now been rewritten to remove this constraint.
* Instead, the engine will attempt to load all .xml files within the schemes/ directory.
*
* @throws IOException
* thrown if the url is unreachable
* @throws JAXBException
* thrown if the schemes could not be parsed
*/
public TDTEngine() throws IOException, JAXBException {
Unmarshaller unmar = getUnmarshaller();
URL auxiliary = this.getClass().getClassLoader().getResource("auxiliary/ManagerTranslation.xml");
URL schemesdir = this.getClass().getClassLoader().getResource("schemes/");
String inputSchemeLine;
try {
URL parent = new URL(schemesdir,".");
URLConnection urlcon = schemesdir.openConnection();
BufferedReader dis = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
while ((inputSchemeLine = dis.readLine()) != null) {
if (inputSchemeLine.endsWith(".xml")) {
URL schemeURL = new URL(schemesdir, inputSchemeLine);
loadEpcTagDataTranslation(unmar, schemeURL);
}
}
dis.close();
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
loadGEPC64Table(unmar, auxiliary);
}
/**
* Constructor for a new Tag Data Translation engine. All files are
* unmarshalled using JAXB.
*
* @param auxiliary
* URL to the auxiliary file containing a GEPC64Table
* @param schemes
* directory containing the schemes, all files ending in xml are
* read and parsed
* @throws IOException
* thrown if the url is unreachable
* @throws JAXBException
* thrown if the files could not be parsed
*/
public TDTEngine(URL auxiliary, URL schemes) throws IOException,
JAXBException {
Unmarshaller unmar = getUnmarshaller();
URLConnection urlcon = schemes.openConnection();
urlcon.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(urlcon
.getInputStream()));
String line;
for (; (line = in.readLine()) != null;) {
if (line.endsWith(".xml")) {
loadEpcTagDataTranslation(unmar, new URL(schemes.toString()
+ line));
}
}
loadGEPC64Table(unmar, auxiliary);
}
/**
* Constructor for a new Tag Data Translation engine. All files are
* unmarshalled using JAXB.
*
* @param auxiliary
* URL to the auxiliary file containing a GEPC64Table
* @param schemes
* set containing several urls pointing to directories containing
* the schemes. All files ending in xml are read and parsed.
* @param absolute
* true if the given URLs are absolute
* @throws IOException
* thrown if the url is unreachable
* @throws JAXBException
* thrown if the files could not be parsed
*/
public TDTEngine(URL auxiliary, Set<URL> schemes, boolean absolute)
throws JAXBException, IOException {
Unmarshaller unmar = getUnmarshaller();
for (URL scheme : schemes) {
if (absolute) {
loadEpcTagDataTranslation(unmar, scheme);
continue;
}
URLConnection urlcon = scheme.openConnection();
urlcon.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(urlcon
.getInputStream()));
String line;
for (; (line = in.readLine()) != null;) {
if (line.endsWith(".xml")) {
loadEpcTagDataTranslation(unmar, new URL(schemes.toString()
+ line));
}
}
}
loadGEPC64Table(unmar, auxiliary);
}
/**
* Creates the unmarshaller.
*
* @return
* @throws JAXBException
*/
private Unmarshaller getUnmarshaller() throws JAXBException {
JAXBContext context = JAXBContext.newInstance(
EpcTagDataTranslation.class, GEPC64.class, GEPC64Entry.class);
return context.createUnmarshaller();
}
/**
* Load an xml file from the given url and unmarshal it into an
* EPCTagDataTranslation.
*
* @param unmar
* @param schemeUrl
* @throws IOException
* @throws JAXBException
*/
private void loadEpcTagDataTranslation(Unmarshaller unmar, URL schemeUrl)
throws IOException, JAXBException {
URLConnection urlcon = schemeUrl.openConnection();
urlcon.connect();
// xml doesn't have enough info for jaxb to figure out
// the
// classname, so we are doing explicit loading
JAXBElement<EpcTagDataTranslation> el = unmar.unmarshal(
new StreamSource(urlcon.getInputStream()),
EpcTagDataTranslation.class);
EpcTagDataTranslation tdt = el.getValue();
initFromTDT(tdt);
}
/**
* Load an xml file from the given url and unmarshal it into a GEPC64Table.
*
* @param unmar
* @param auxiliary
* @throws IOException
* @throws JAXBException
*/
private void loadGEPC64Table(Unmarshaller unmar, URL auxiliary)
throws IOException, JAXBException {
URLConnection urlcon = auxiliary.openConnection();
urlcon.connect();
// load the GEPC64Table
JAXBElement<GEPC64> el = unmar.unmarshal(new StreamSource(urlcon
.getInputStream()), GEPC64.class);
GEPC64 cpilookup = el.getValue();
for (GEPC64Entry entry : cpilookup.getEntry()) {
String comp = entry.getCompanyPrefix();
String indx = entry.getIndex().toString();
gs1cpi.put(indx, comp);
gs1cpi.put(comp, indx);
}
}
/**
* Private method for obtaining a hashmap of URLs for named auxiliary files, whether in a file directory, web directory or web page
*
* @param auxdirURL
* URL to the directory containing auxiliary files or web page linking to auxiliary files
* @param requiredauxfiles
* Set of individual auxiliary files to be retrieved
* @return a hash map relating the name of the filename and its URL
*
* @throws IOException
* thrown if the url is unreachable
*/
private static HashMap<String,URL> getauxiliaryURLs(URL auxdirURL, Set<String> requiredauxfiles) {
HashMap<String, URL> foundauxfiles = new HashMap<String, URL>();
String inputAuxLine;
try {
URL parent = new URL(auxdirURL,".");
String relauxiliary=auxdirURL.getFile();
URLConnection urlconauxiliary = auxdirURL.openConnection();
BufferedReader dis2 = new BufferedReader(new InputStreamReader(urlconauxiliary.getInputStream()));
while ((inputAuxLine = dis2.readLine()) != null) {
for (String requestedfile: requiredauxfiles) {
if (requestedfile.endsWith(".xml")) {
String pattern = requestedfile.replaceAll("\\.","\\\\.").replaceAll("^","(").replaceAll("$",")").toString();
Pattern regex = Pattern.compile(pattern);
String pattern2 = requestedfile.replaceAll("\\.","\\\\.").replaceAll("^","href=['\"]([^ ]+?").replaceAll("$",")['\"]").toString();
Pattern regex2 = Pattern.compile(pattern2);
// check if line includes filename.xml - if so, extract auxiliaryfile
Matcher matcher2 = regex.matcher(inputAuxLine);
if (matcher2.find()) {
URL relURL = new URL(parent, matcher2.group(1));
foundauxfiles.put(requestedfile, relURL);
}
// check if line includes href="filename.xml - if so, extract auxiliaryfile
Matcher matcher3 = regex2.matcher(inputAuxLine);
if (matcher3.find()) {
URL relURL = new URL(parent, matcher3.group(1));
foundauxfiles.put(requestedfile, relURL);
}
}
}
}
dis2.close();
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
return foundauxfiles;
}
/**
* Private method for obtaining a set of URLs for TDT definition files, whether in a file directory, web directory or web page
*
* @param schemesdirURL
* URL to the directory containing TDT definition files files or web page linking to TDT definition files
* @return a list of URLs of TDT definition files contained within the directory or web page pointed to by the URL
*
* @throws IOException
* thrown if the url is unreachable
*/
private static Set<URL> getschemeURLs(URL schemesdirURL, Set<String> schemes) {
String inputSchemeLine;
Set<URL> schemeURLs = new HashSet<URL>();
try {
URL parent = new URL(schemesdirURL,".");
String relschemes=schemesdirURL.getFile();
URLConnection urlconschemes = schemesdirURL.openConnection();
BufferedReader dis = new BufferedReader(new InputStreamReader(urlconschemes.getInputStream()));
while ((inputSchemeLine = dis.readLine()) != null) {
// check if line includes filename.xml - if so, add to Set
Matcher matcher = Pattern.compile("([A-Za-z0-9-_]+-[0-9*]+\\.xml)").matcher(inputSchemeLine);
if (matcher.find()) {
URL relURL = new URL(parent, matcher.group(0));
if (!matcher.group(0).contains("test")) {
schemeURLs.add(relURL);
schemes.add(matcher.group(0));
}
}
}
dis.close();
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
return schemeURLs;
}
// - Methods -/
private class PrefixMatch {
private Scheme s;
private Level level;
public PrefixMatch(Scheme s, Level level) {
this.s = s;
this.level = level;
}
public Scheme getScheme() {
return s;
}
public Level getLevel() {
return level;
}
}
private class PrefixMatch2 {
private Scheme s;
private Level level;
private String taglength;
public PrefixMatch2(Scheme s, Level level, String taglength) {
this.s = s;
this.level = level;
this.taglength=taglength;
}
public Scheme getScheme() {
return s;
}
public Level getLevel() {
return level;
}
public String getTaglength() {
return taglength;
}
}
/** initialise various indices */
private void initFromTDT(EpcTagDataTranslation tdt) {
for (Scheme ss : tdt.getScheme()) {
// create an index so that we can find a scheme based on tag length
for (Level level : ss.getLevel()) {
String s = level.getPrefixMatch();
if (s != null) {
// insert into prefix tree according to level type.
PrefixTree<PrefixMatch> prefix_tree = prefix_tree_map
.get(level.getType());
if (prefix_tree == null) {
prefix_tree = new PrefixTree<PrefixMatch>();
prefix_tree_map.put(level.getType(), prefix_tree);
}
prefix_tree.insert(s, new PrefixMatch(ss, level));
debugprintln("Insert into prefix_tree Prefix: "+s+" : Scheme="+ss.getName()+" ; TagLength="+level.getType());
}
}
}
}
/**
* Given an input string, and optionally a tag length, find a scheme / level
* with a matching prefix and tag length.
*/
private PrefixMatch2 findPrefixMatch(String input, String strTagLength) {
debugprintln("PrefixMatch with 2 parameters: specified strTagLength = "+strTagLength);
debugprintln("input was: "+input);
int realTagLength=Integer.parseInt(strTagLength);
List<PrefixMatch> match_list = new ArrayList<PrefixMatch>();
List<PrefixMatch> alt_match_list = new ArrayList<PrefixMatch>();
for (PrefixTree<PrefixMatch> tree : prefix_tree_map.values()) {
List<PrefixMatch> list = tree.search(input);
if (!list.isEmpty()) {
debugprintln("list is not empty (line 566)");
if (strTagLength == null)
match_list.addAll(list);
else {
for (PrefixMatch match : list) {
BigInteger tagLength = new BigInteger(strTagLength);
BigInteger schemeTagLength = match.getScheme().getTagLength();
if (tagLength.compareTo(schemeTagLength) == 0) {
match_list.add(match);
debugprintln("Added to match_list");
debugprintln("Matched scheme :"+match.getScheme().getName().toString());
debugprintln("scheme taglength = "+ schemeTagLength);
debugprintln("tagLength = "+tagLength);
realTagLength=Integer.parseInt(schemeTagLength.toString());
} else {
// need TO DO the same for findPrefixMatch with 3 parameters (method below)
alt_match_list.add(match);
realTagLength=Integer.parseInt(schemeTagLength.toString());
debugprintln("Added to alt_match_list");
debugprintln("Matched scheme :"+match.getScheme().getName().toString());
debugprintln("scheme taglength = "+ schemeTagLength);
debugprintln("tagLength = "+tagLength);
debugprintln("realTagLength = "+realTagLength);
}
}
}
}
}
if (match_list.isEmpty()) {
debugprintln("match_list was empty");
if (alt_match_list.size() == 1) {
debugprintln("but alt_match_list has one element: "+alt_match_list.get(0).getScheme().getName());
match_list.add(alt_match_list.get(0));
}
}
if (match_list.isEmpty()) {
debugprintln("***EXCEPTION: No schemes or levels matched the input value (line 608)");
throw new TDTException("No schemes or levels matched the input value");
} else if (match_list.size() > 1) {
debugprintln("***EXCEPTION: More than one scheme/level matched the input value (line 611)");
int patternmatchcount=0;
int matchingindex=-1;
int currentindex=0;
for (PrefixMatch cand : match_list) {
boolean patternmatch=false;
for (Option candopt : cand.getLevel().getOption()) {
Matcher matcher = Pattern.compile("^"+candopt.getPattern()+"$").matcher(input);
if (matcher.lookingAt()) {
patternmatch=true;
}
}
if (patternmatch) {
matchingindex=currentindex;
patternmatchcount++;
}
currentindex++;
}
if ((patternmatchcount == 1) && (matchingindex > -1)) {
debugprintln("Returning "+match_list.get(matchingindex).getScheme().getName()+" with level "+match_list.get(matchingindex).getLevel().getType()+" and setting tagLength to "+realTagLength);
return new PrefixMatch2(match_list.get(matchingindex).getScheme(),match_list.get(matchingindex).getLevel(),Integer.toString(realTagLength));
} else {
throw new TDTException("More than one scheme/level matched the input value even at pattern level");
}
} else {
debugprintln("Returning "+match_list.get(0).getScheme().getName()+" with level "+match_list.get(0).getLevel().getType()+" and setting tagLength to "+realTagLength);
return new PrefixMatch2(match_list.get(0).getScheme(),match_list.get(0).getLevel(),Integer.toString(realTagLength));
}
}
/**
* Given an input string, level, and optionally a tag length, find a
* matching prefix.
*/
private PrefixMatch2 findPrefixMatch(String input, String strTagLength,
LevelTypeList level_type) {
debugprintln("PrefixMatch with 3 parameters: specified strTagLength = "+strTagLength);
int realTagLength=Integer.parseInt(strTagLength);
List<PrefixMatch> match_list = new ArrayList<PrefixMatch>();
List<PrefixMatch> alt_match_list = new ArrayList<PrefixMatch>();
PrefixTree<PrefixMatch> tree = prefix_tree_map.get(level_type);
assert tree != null;
List<PrefixMatch> list = tree.search(input);
if (!list.isEmpty()) {
if (strTagLength == null)
match_list.addAll(list);
else {
BigInteger tagLength = new BigInteger(strTagLength);
for (PrefixMatch match : list)
if (match.getScheme().getTagLength().compareTo(tagLength) == 0) {
match_list.add(match);
} else {
alt_match_list.add(match);
realTagLength = Integer.parseInt(match.getScheme().getTagLength().toString());
}
}
}
if (match_list.isEmpty()) {
if (alt_match_list.size() == 1) {
match_list.add(alt_match_list.get(0));
}
}
if (match_list.isEmpty()) {
debugprintln("***EXCPETION: No schemes or levels matched the input value (line 679)");
throw new TDTException("No schemes or levels matched the input value");
} else if (match_list.size() > 1) {
debugprintln("***EXCEPTION: More than one scheme/level matched the input value (line 682)");
int patternmatchcount=0;
int matchingindex=-1;
int currentindex=0;
for (PrefixMatch cand : match_list) {
boolean patternmatch=false;
for (Option candopt : cand.getLevel().getOption()) {
Matcher matcher = Pattern.compile("^"+candopt.getPattern()+"$").matcher(input);
if (matcher.lookingAt()) {
patternmatch=true;
}
}
if (patternmatch) {
matchingindex=currentindex;
patternmatchcount++;
}
currentindex++;
}
if ((patternmatchcount == 1) && (matchingindex > -1)) {
debugprintln("Returning "+match_list.get(matchingindex).getScheme().getName()+" with level "+match_list.get(matchingindex).getLevel().getType()+" and setting tagLength to "+realTagLength);
return new PrefixMatch2(match_list.get(matchingindex).getScheme(),match_list.get(matchingindex).getLevel(),Integer.toString(realTagLength));
} else {
throw new TDTException("More than one scheme/level matched the input value even at pattern level");
}
} else {
return new PrefixMatch2(match_list.get(0).getScheme(),match_list.get(0).getLevel(),Integer.toString(realTagLength));
}
}
/**
* Translates the input string of a specified input level to a specified
* outbound level of the same coding scheme. For example, the input string
* value may be a tag-encoding URI and the outbound level specified by
* string outboundlevel may be BINARY, in which case the return value is a
* binary representation expressed as a string.
*
* <p>
* Note that this version of the method requires that the user specify the
* input level, rather than searching for it. However it still automatically
* finds the scheme used.
* </p>
*
* @param input
* input tag coding
* @param inputLevel
* level such as BINARY, or TAG_ENCODING.
* @param tagLength
* tag length such as VALUE_64 or VALUE_96.
* @param inputParameters
* a map with any additional properties.
* @param outputLevel
* required output level.
* @return output tag coding
*/
public String convert(String input, LevelTypeList inputLevel,
String tagLength, Map<String, String> suppliedInputParameters,
LevelTypeList outputLevel) {
debugprintln("convert (line 699)");
Map<String, String> inputParameters=suppliedInputParameters;
debugprintln("inputParameters were");
Iterator i=inputParameters.keySet().iterator();
while (i.hasNext()) {
String key = i.next().toString();
debugprintln(key + "=" + inputParameters.get(key));
}
debugprintln("End of inputParameters");
if (input.startsWith("urn:epc:")) {
input = uriunescape(input);
}
PrefixMatch2 matchtemp = findPrefixMatch(input, tagLength, inputLevel);
PrefixMatch match = new PrefixMatch(matchtemp.getScheme(),matchtemp.getLevel());
inputParameters.put("taglength",matchtemp.getTaglength());
// if the input is binary or URI, ignore any value of optionKey that is specified in the input parameters (since its value may contradict the value obtained from pattern matching the input)
debugprintln("[line 718] matchtemp.getLevel().getType() = "+matchtemp.getLevel().getType().toString());
return convertLevel(match.getScheme(), match.getLevel(), input, inputParameters, outputLevel);
}
/**
* The convert method translates a String input to a specified outbound
* level of the same coding scheme. For example, the input string value may
* be a tag-encoding URI and the outbound level specified by string
* outboundlevel may be BINARY, in which case the return value is a binary
* representation expressed as a string.
*
* @param input
* the identifier to be converted.
* @param inputParameters
* additional parameters which need to be provided because they
* cannot always be determined from the input value alone.
* Examples include the taglength, companyprefixlength and filter
* values.
* @param outputLevel
* the outbound level required for the ouput. Permitted values
* include BINARY, TAG_ENCODING, PURE_IDENTITY, LEGACY and
* ONS_HOSTNAME.
* @return the identifier converted to the output level.
*/
public String convert(String input, Map<String, String> suppliedInputParameters,
LevelTypeList outputLevel) {
debugprintln("convert (line 748)");
debugprintln("===============================================");
debugprintln("CONVERT "+input+" to "+outputLevel.toString());
Map<String, String> inputParameters=suppliedInputParameters;
debugprintln("GS1 CP length = "+inputParameters.get("gs1companyprefixlength"));
debugprintln("inputParameters were");
Iterator i=inputParameters.keySet().iterator();
while (i.hasNext()) {
String key = i.next().toString();
debugprintln(key + "=" + inputParameters.get(key));
}
debugprintln("End of inputParameters");
String tagLength = null;
String decodedinput;
String encoded;
if (inputParameters.containsKey("taglength")) {
// in principle, the user should provide a
// TagLengthList object in the parameter list.
String s = inputParameters.get("taglength");
tagLength = s;
debugprintln("taglength was provided. tagLength = "+s);
}
if (input.startsWith("urn:epc:")) {
input = uriunescape(input);
}
PrefixMatch2 matchtemp = findPrefixMatch(input, tagLength);
PrefixMatch match = new PrefixMatch(matchtemp.getScheme(),matchtemp.getLevel());
inputParameters.put("taglength",matchtemp.getTaglength());
debugprintln("Tag length has been set to "+matchtemp.getTaglength());
// if the input is binary or URI, ignore any value of optionKey that is specified in the input parameters (since its value may contradict the value obtained from pattern matching the input)
debugprintln("[line 786] matchtemp.getLevel().getType() = "+matchtemp.getLevel().getType().toString());
debugprintln("reached line 788");
// if a URI is supplied, remember to perform URL decoding on it before passing it to the convertLevel() method
// if a URI is returned, remember to perform URL encoding on it before returning it as output
return convertLevel(match.getScheme(), match.getLevel(), input, inputParameters, outputLevel);
}
/**
* convert from a particular scheme / level
*/
private String convertLevel(Scheme tdtscheme, Level tdtlevel, String input,
Map<String, String> inputParameters, LevelTypeList outboundlevel) {
debugprintln("convertLevel (line 820) - 19:12 21st October 2010");
debugprintln("===============================================");
debugprintln("CONVERT "+input+" to "+outboundlevel.toString());
String outboundstring;
Map<String, String> extraparams =
// new NoisyMap
(new HashMap<String, String>(inputParameters));
// get the scheme's option key, which is the name of a
// parameter whose value is matched to the option key of the
// level.
String optionValue;
String optionkey = tdtscheme.getOptionKey();
debugprintln("optionkey for scheme = "+optionkey);
debugprintln("tdtlevel.getType() = "+tdtlevel.getType().toString());
if (!((tdtlevel.getType() == LevelTypeList.TAG_ENCODING) || (tdtlevel.getType() == LevelTypeList.PURE_IDENTITY) || (tdtlevel.getType() == LevelTypeList.BINARY) )) {
optionValue = inputParameters.get(optionkey);
} else {
optionValue=null;
}
debugprintln("optionValue = "+optionValue);
// the name of a parameter which allows the appropriate option
// to be selected
// now consider the various options within the scheme and
// level for each option element inside the level, check
// whether the pattern attribute matches as a regular
// expression
String matchingOptionKey = null;
Option matchingOption = null;
Matcher prefixMatcher = null;
Map<String,Option> pattern_map = new HashMap<String,Option>();
Map<String,Matcher> matcher_map = new HashMap<String,Matcher>();
debugprintln("line 858 input = "+input);
for (Option opt : tdtlevel.getOption()) {
if (optionValue == null || optionValue.equals(opt.getOptionKey())) {
// possible match
debugprintln("optionValue = "+optionValue);
debugprintln("opt.getOptionKey() = "+opt.getOptionKey());
debugprintln("Pattern = "+opt.getPattern());
Matcher matcher = Pattern.compile("^"+opt.getPattern()).matcher(input);
debugprintln("lookingAt ^"+opt.getPattern());
if (matcher.lookingAt()) {
debugprintln("MATCHED!");
pattern_map.put(opt.getOptionKey(),opt);
matcher_map.put(opt.getOptionKey(),matcher);
}
}
}
debugprintln("Size of pattern_map is "+pattern_map.size());
if (pattern_map.isEmpty()) {
debugprintln("***EXCEPTION: No patterns matched (line 879)");
throw new TDTException("No patterns matched (line 880)");
}
if (pattern_map.size() > 1) {
debugprintln("optionkey = "+optionkey);
debugprintln("extraparams.get("+optionkey+") = "+extraparams.get(optionkey));
debugprintln("optionValue = "+optionValue);
if (pattern_map.containsKey(optionValue)) {
debugprintln("matchingOptionKey = "+optionValue);
debugprintln("matchingOption has pattern = "+pattern_map.get(optionValue).getPattern());
matchingOptionKey = optionValue;
matchingOption=pattern_map.get(optionValue);
prefixMatcher=matcher_map.get(optionValue);
}
}
if (pattern_map.size() == 1) {
debugprintln("matchingOptionKey = "+pattern_map.keySet().iterator().next());
matchingOptionKey = pattern_map.keySet().iterator().next().toString();
debugprintln("matchingOption has pattern = "+pattern_map.get(matchingOptionKey).getPattern());
matchingOption=pattern_map.get(matchingOptionKey);
prefixMatcher=matcher_map.get(matchingOptionKey);
}
optionValue = matchingOptionKey;
debugprintln("optionValue = "+optionValue);
Level tdtoutlevel = findLevel(tdtscheme, outboundlevel);
debugprint("tdtoutlevel prefixMatch = ");
if (tdtoutlevel.getPrefixMatch() != null) {
debugprintln(tdtoutlevel.getPrefixMatch().toString());
} else {
debugprintln("null");
}
Level tdttagurilevel = findLevel(tdtscheme, LevelTypeList.TAG_ENCODING);
Level tdtbinarylevel = findLevel(tdtscheme, LevelTypeList.BINARY);
debugprint("tdttagurilevel prefixMatch = ");
debugprintln(tdttagurilevel.getPrefixMatch().toString());
Option tdtoutoption = findOption(tdtoutlevel, optionValue);
debugprint("tdtoutoption pattern = ");
if (tdtoutoption.getPattern() != null) {
debugprintln(tdtoutoption.getPattern().toString());
} else {
debugprintln("null");
}
Option tdttagurioption = findOption(tdttagurilevel, optionValue);
Option tdtbinaryoption = findOption(tdtbinarylevel, optionValue);
debugprint("tdttagurioption pattern = ");
debugprintln(tdttagurioption.getPattern().toString());
// EXTRACTION of values or each of the fields.
// consider all fields within the matching option
for (Field field : matchingOption.getField()) {
BigInteger seq = field.getSeq();
String strfieldname = field.getName();
PadDirectionList padDir = field.getPadDir();
PadDirectionList taguriPadDir;
PadDirectionList bitPadDir = field.getBitPadDir();
String padChar = field.getPadChar();
String taguriPadChar;
String outPadChar;
int requiredLength = -1; // -1 indicates that no length is specified
if (field.getLength() != null) {
requiredLength = field.getLength().intValue();
}
debugprintln("
debugprintln("fieldname = "+strfieldname);
String strfieldvaluematched = prefixMatcher.group(seq.intValue());
debugprintln("strfieldvaluematched = "+strfieldvaluematched);
debugprintln("
Field outputfield = findField(tdtoutoption, strfieldname, tdtoutlevel);
// debugprintln("outputfield characterset = "+outputfield.getCharacterSet().toString());
Field tagurifield = findField(tdttagurioption, strfieldname, tdttagurilevel);
Field binaryfield = findField(tdtbinaryoption, strfieldname, tdtbinarylevel);
if (tdtlevel.getType() == LevelTypeList.BINARY ) {
debugprintln("Converting from BINARY to NON-BINARY - see Figure 9b");
String result9blayer1;
String result9blayer2;
String result9blayer3;
if (binaryfield.getCompaction() != null) {
if (binaryfield.getBitPadDir() != null) {
// strip leading/trailing bits at the bitPadDir edge until a multiple of compaction bits is obtained
int intcompaction = -1;
String strCompaction = binaryfield.getCompaction();
if (strCompaction.equals("5-bit")) { intcompaction = 5; }
if (strCompaction.equals("6-bit")) { intcompaction = 6; }
if (strCompaction.equals("7-bit")) { intcompaction = 7; }
if (strCompaction.equals("8-bit")) { intcompaction = 8; }
if (intcompaction > -1) {
result9blayer1 = stripbinarypadding(strfieldvaluematched, binaryfield.getBitPadDir(), intcompaction);
} else {
result9blayer1 = strfieldvaluematched;
debugprintln("Invalid value for compaction");
}
} else {
// do nothing
result9blayer1 = strfieldvaluematched;
}
// convert the sequence of bits into characters, considering that each byte may have been compacted, as indicated by the compaction attribute
result9blayer2 = binaryToString(result9blayer1,binaryfield.getCompaction());
// check that the string value only contains characters from the permitted character set
debugprintln("9b: Checking that result "+result9blayer2+" is within character set "+tagurifield.getCharacterSet());
checkWithinCharacterSet(strfieldname, result9blayer2, tagurifield.getCharacterSet());
} else {
if (binaryfield.getBitPadDir() != null) {
// strip leading/trailing bits at the bitPadDir edge until the first non-zero bit is encountered
result9blayer1 = stripbinarypadding(strfieldvaluematched, binaryfield.getBitPadDir(), 0);
} else {
// do nothing
result9blayer1 = strfieldvaluematched;
}
// consider the sequence of bits as an unsigned integer and convert this integer into a numeric string
result9blayer2 = bin2dec(result9blayer1);
debugprintln("9b: Intermediate results at layer 2="+result9blayer2);
// check that the numeric value is not less than the specified minimum nor greater than the specified maximum
/**
* the EXTRACT rules are performed after parsing the input, in order to
* determine additional fields that are to be derived from the fields
* obtained by the pattern match process
*/
debugprintln("Processing RULE elements of type 'EXTRACT'");
int seq = 0;
for (Rule tdtrule : tdtlevel.getRule()) {
if (tdtrule.getType() == ModeList.EXTRACT) {
debugprintln("Rule #"+tdtrule.getSeq().intValue()+": "+tdtrule.getNewFieldName());
assert seq < tdtrule.getSeq().intValue() : "Rule out of sequence order";
seq = tdtrule.getSeq().intValue();
processRules(extraparams, tdtrule);
}
}
debugprintln("Finished processing 'EXTRACT' rules");
/**
* Now we need to consider the corresponding output level and output
* option. The scheme must remain the same, as must the value of
* optionkey (to select the corresponding option element nested within
* the required outbound level)
*/
// Level tdtoutlevel = findLevel(tdtscheme, outboundlevel);
// Option tdtoutoption = findOption(tdtoutlevel, optionValue);
/**
* the FORMAT rules are performed before formatting the output, in order
* to determine additional fields that are required for preparation of
* the outbound format
*/
debugprintln("Processing RULE elements of type 'FORMAT'");
seq = 0;
for (Rule tdtrule : tdtoutlevel.getRule()) {
if (tdtrule.getType() == ModeList.FORMAT) {
debugprintln("Rule #"+tdtrule.getSeq().intValue()+": "+tdtrule.getNewFieldName());
assert seq < tdtrule.getSeq().intValue() : "Rule out of sequence order";
seq = tdtrule.getSeq().intValue();
processRules(extraparams, tdtrule);
}
}
/**
* Now we need to ensure that all fields required for the outbound
* grammar are suitably padded etc. processPadding takes care of firstly
* padding the non-binary fields if padChar and padDir, length are
* specified then (if necessary) converting to binary and padding the
* binary representation to the left with zeros if the bit string is has
* fewer bits than the bitLength attribute specifies. N.B. TDTv1.1 will
* be more specific about bit-level padding rather than assuming that it
* is always to the left with the zero bit.
*/
debugprintln("Finished processing 'FORMAT' rules");
if (tdtoutlevel.getType() == LevelTypeList.BINARY ) {
debugprintln("Converting output fields from NON-BINARY to BINARY - see Figure 9a");
for (Field field : tdtoutoption.getField()) {
String strfieldname = field.getName();
Field tagurifield = findField(tdttagurioption, strfieldname, tdttagurilevel);
Field binaryfield = findField(tdtbinaryoption, strfieldname, tdtbinarylevel);
String strfieldvaluematched = extraparams.get(strfieldname);
debugprintln("Output field: "+strfieldname+" had value "+strfieldvaluematched);
String result9alayer1;
if (tagurifield !=null) {
if (tagurifield.getPadChar() != null) {
if (binaryfield.getPadChar() != null) {
debugprintln("9a Invalid TDT definition file");
result9alayer1="";
} else {
// Strip non-binary field of any successive pad characters tagurifield.getPadChar() at edge tagurifield.getPadDir()
result9alayer1 = stripPadChar(strfieldvaluematched,tagurifield.getPadDir(),tagurifield.getPadChar());
}
} else {
if (binaryfield.getPadChar() != null) {
// Pad the non-binary field with pad characters binaryfield.getPadChar() at the edge binaryfield.getPadDir() to reach a total length of binaryfield.getLength() characters
result9alayer1 = applyPadChar(strfieldvaluematched, binaryfield.getPadDir(), binaryfield.getPadChar(), binaryfield.getLength().intValue());
} else {
// do not pad this field at the non-binary level
result9alayer1 = strfieldvaluematched;
}
}
debugprintln("\tIntermediate Result for Fig 9a at layer 1="+result9alayer1);
String result9alayer2;
if (binaryfield.getCompaction() != null) {
// treat the field as an alphanumeric field
// check that all of its characters are within the allowed character set
checkWithinCharacterSet(strfieldname, result9alayer1, tagurifield.getCharacterSet());
// convert to binary using the compaction method specified for that field at binary level
result9alayer2 = stringToBinary(result9alayer1,binaryfield.getCompaction().toString());
} else {
// check that the non-binary value is not less than the minimum nor greater than the maximum value permitted
if (result9alayer1.length() > 0) {
checkMinimum(strfieldname, new BigInteger(result9alayer1), tagurifield.getDecimalMinimum());
checkMaximum(strfieldname, new BigInteger(result9alayer1), tagurifield.getDecimalMaximum());
}
// treat the numeric field as as an unsigned integer and convert this integer into a sequence of bits
result9alayer2 = dec2bin(result9alayer1);
}
debugprintln("\tIntermediate Result for Fig 9a at layer 2="+result9alayer2);
String result9alayer3;
if (binaryfield.getBitPadDir() != null) {
debugprintln("9a Pad with leading/trailing bits at the "+binaryfield.getBitPadDir()+" edge to reach a total of "+binaryfield.getBitLength()+" bits");
result9alayer3 = applyPadChar(result9alayer2, binaryfield.getBitPadDir(), "0", binaryfield.getBitLength().intValue());
} else {
debugprintln("9a Don't pad at binary level");
result9alayer3 = result9alayer2;
}
debugprintln("\tFinal Result for Fig 9a at layer 3="+result9alayer3);
debugprintln("Need to put this value into extraparams as the value for key "+strfieldname);
debugprintln("binaryfield.getBitLength() = "+binaryfield.getBitLength());
if ((binaryfield.getBitLength() != null) && (binaryfield.getBitLength().intValue() == 0)) {
extraparams.put(strfieldname,"");
} else {
extraparams.put(strfieldname,result9alayer3);
}
} else {
String result9alayer3;
if (binaryfield.getBitPadDir() != null) {
debugprintln("9a Pad with leading/trailing bits at the "+binaryfield.getBitPadDir()+" edge to reach a total of "+binaryfield.getBitLength()+" bits");
result9alayer3 = applyPadChar(dec2bin(strfieldvaluematched), binaryfield.getBitPadDir(), "0", binaryfield.getBitLength().intValue());
} else {
debugprintln("9a Don't pad at binary level");
result9alayer3 = dec2bin(strfieldvaluematched);
}
debugprintln("binaryfield.getBitLength() = "+binaryfield.getBitLength());
if ((binaryfield.getBitLength() != null) && (binaryfield.getBitLength().intValue() == 0)) {
extraparams.put(strfieldname,"");
} else {
extraparams.put(strfieldname,result9alayer3);
}
}
}
}
/**
* Construct the output from the specified grammar (in ABNF format)
* together with the field values stored in inputparams
*/
debugprintln("Building final grammar");
for (Field testfield : tdtoutoption.getField()) {
String testfieldname = testfield.getName();
debugprintln("Field to be checked: "+testfieldname+" = "+extraparams.get(testfieldname));
if (outboundlevel == LevelTypeList.BINARY) {
Field tagurifield = findField(tdttagurioption, testfieldname, tdttagurilevel);
if (tagurifield.getDecimalMinimum() != null) {
debugprintln("Decimal minimum = "+tagurifield.getDecimalMinimum());
checkMinimum(testfieldname, new BigInteger(bin2dec(extraparams.get(testfieldname))), testfield.getDecimalMinimum());
}
if (tagurifield.getDecimalMaximum() != null) {
debugprintln("Decimal maximum = "+tagurifield.getDecimalMaximum());
checkMaximum(testfieldname, new BigInteger(bin2dec(extraparams.get(testfieldname))), testfield.getDecimalMaximum());
}
} else {
if (testfield.getDecimalMinimum() != null) {
debugprintln("Decimal minimum = "+testfield.getDecimalMinimum());
checkMinimum(testfieldname, new BigInteger(extraparams.get(testfieldname)), testfield.getDecimalMinimum());
}
if (testfield.getDecimalMaximum() != null) {
debugprintln("Decimal maximum = "+testfield.getDecimalMaximum());
checkMaximum(testfieldname, new BigInteger(extraparams.get(testfieldname)), testfield.getDecimalMaximum());
}
if (testfield.getCharacterSet() != null) {
debugprintln("Character set = "+testfield.getCharacterSet());
checkWithinCharacterSet(testfieldname, extraparams.get(testfieldname), testfield.getCharacterSet());
}
}
}
// need to get fields for tdtoutoption
// then check each one for min/max, charSet
outboundstring = buildGrammar(tdtoutoption.getGrammar(), extraparams, outboundlevel);
// debugprintln("final extraparams = " + extraparams);
debugprintln("RESULT after building grammar = " + outboundstring);
debugprintln("===============================================================================");
debugprintln("");
return outboundstring;
}
/**
*
* Converts a binary string into a large integer (numeric string)
*/
public String bin2dec(String binary) {
debugprintln("(line 1285) binary = "+binary);
if (binary.length() == 0) {
return "0";
} else {
debugprintln("Converting binary to decimal");
BigInteger dec = new BigInteger(binary, 2);
debugprintln("Decimal value = "+dec.toString());
return dec.toString();
}
}
/**
*
* Converts a large integer (numeric string) to a binary string
*/
public String dec2bin(String decimal) {
// TODO: required?
if (decimal == null) {
decimal = "1";
}
debugprintln("(line 1301) decimal = "+decimal);
if (decimal.length() == 0) {
return "0";
} else {
BigInteger bin = new BigInteger(decimal);
return bin.toString(2);
}
}
private StringBuffer replaceStringBuffer(StringBuffer buffer, String value) {
buffer.replace(0,buffer.length(),value);
return buffer;
}
private void checkWithinCharacterSet(String fieldname, String value, String characterset) {
if (characterset != null) {
// if the character set is specified
// check that the entire strfieldvalue consists only of characters
// permitted within the permitted character set for that field
// according to the characterSet attribute
String appendedCharacterSet;
if (characterset.endsWith("*")) {
appendedCharacterSet=characterset;
} else {
appendedCharacterSet=characterset+"*";
}
Matcher charsetmatcher = Pattern.compile("^" + appendedCharacterSet + "$").matcher(value);
// if any invalid characters are found, throw a new TDT Exception
if (!charsetmatcher.matches()) {
debugprintln("***EXCEPTION: field "+ fieldname+ " ("+ value+ ") does not conform to the allowed character set ("+ characterset + ") ");
//throw new TDTException("field "+ fieldname+ " ("+ value+ ") does not conform to the allowed character set ("+ characterset + ") ");
}
}
}
private void checkMinimum(String fieldname, BigInteger bigvalue, String decimalminimum) {
// if decimalMinimum is specified, check that the field is not less than the minimum value permitted by decimalMinimum
if (decimalminimum != null) {
BigInteger bigmin = new BigInteger(decimalminimum);
if (bigvalue.compareTo(bigmin) == -1) {
// throw an exception if the field value is less than the decimal minimum
debugprintln("***EXCEPTION: field " + fieldname + " (" + bigvalue + ") is less than DecimalMinimum (" + decimalminimum + ") allowed");
//throw new TDTException("field " + fieldname + " (" + bigvalue + ") is less than DecimalMinimum (" + decimalminimum + ") allowed");
}
}
}
private void checkMaximum(String fieldname, BigInteger bigvalue, String decimalmaximum) {
// if decimalMaximum is specified, check that the field is not greater than the maximum value permitted by decimalMaximum
if (decimalmaximum != null) {
BigInteger bigmax = new BigInteger(decimalmaximum);
if (bigvalue.compareTo(bigmax) == 1) {
// throw an exception if the field value is greater than the decimal maximum
debugprintln("***EXCEPTION: field " + fieldname + " (" + bigvalue + ") is greater than DecimalMaximum (" + decimalmaximum + ") allowed");
// throw new TDTException("field " + fieldname + " (" + bigvalue + ") is greater than DecimalMaximum (" + decimalmaximum + ") allowed");
}
}
}
/**
*
* Converts a binary string to a character string according to the specified compaction
*
*/
private String binaryToString(String value, String compaction) {
String s;
if ("5-bit".equals(compaction)) {
// "5-bit"
s = bin2uppercasefive(value);
} else if ("6-bit".equals(compaction)) {
// 6-bit
s = bin2alphanumsix(value);
} else if ("7-bit".equals(compaction)) {
// 7-bit
s = bin2asciiseven(value);
} else if ("8-bit".equals(compaction)) {
// 8-bit
s = bin2bytestring(value);
} else {
debugprintln("***ERROR: unsupported compaction method " + compaction);
throw new Error("unsupported compaction method " + compaction);
}
return s;
}
/**
*
* Converts a hexadecimal string to a binary string
* Note that this method ensures that the binary string has leading zeros
* in order to reach a length corresponding to 4 times the length of the hex string
* Note that the actual binary string to be provided to the convert() method may need between 1 and 3 leading zeros to be truncated
* An example is SGLN-195, where the hex representation would be padded to 49 hex characters, resulting in 196 bits after hex2bin
* so we would need to try firstly converting 196 bits (i.e. offset 0), then 195 bits (offset = 1), then 194 bits (offset=2), then 193 bits (offset=3)
* until we find one of these which successfully converts.
*/
public String hex2bin(String hex) {
int lenhex = hex.length();
debugprintln("(line 1407) hex = "+hex);
if (hex.length() == 0) {
return "";
} else {
BigInteger bin = new BigInteger(hex.toLowerCase(), 16);
StringBuffer stringbin = new StringBuffer(bin.toString(2));
int padlength = lenhex*4 - stringbin.length();
if (padlength > 0) {
stringbin.insert(0,"00000000000000000000000000000000000000000000000000000000000000".substring(0,padlength));
}
return stringbin.toString();
}
}
/**
*
* Converts a binary string to a hexadecimal string
* Note that this method ensures that the hex string has leading zeros
* in order to reach a length corresponding to 1/4 of the length of the binary string, rounded up to the nearest integer.
*/
public String bin2hex(String binary) {
int lenbin = binary.length();
int lenhex = ((lenbin + 3)/4);
debugprintln("(line 1428) binary = "+binary);
if (binary.length() == 0) {
return "";
} else {
BigInteger hex = new BigInteger(binary, 2);
StringBuffer rawhex= new StringBuffer(hex.toString(16).toUpperCase());
int padlength = lenhex-rawhex.length();
if (padlength > 0) {
rawhex.insert(0,"0000".substring(0,padlength));
}
return rawhex.toString();
}
}
/**
* Returns a string built using a particular grammar. Single-quotes strings
* are counted as literal strings, whereas all other strings appearing in
* the grammar require substitution with the corresponding value from the
* extraparams hashmap.
*/
private String buildGrammar(String grammar, Map<String, String> extraparams, LevelTypeList outboundlevel) {
StringBuilder outboundstring = new StringBuilder();
String[] fields = Pattern.compile("\\s+").split(grammar);
for (int i = 0; i < fields.length; i++) {
String formattedparam;
if (fields[i].substring(0, 1).equals("'")) {
formattedparam=fields[i].substring(1,fields[i].length() - 1);
} else {
if ((outboundlevel == LevelTypeList.TAG_ENCODING) || (outboundlevel == LevelTypeList.PURE_IDENTITY)) {
formattedparam = uriescape(extraparams.get(fields[i]));
debugprintln("(line 1484) param = "+extraparams.get(fields[i]));
debugprintln("(line 1485) formattedparam = "+formattedparam);
} else {
formattedparam = extraparams.get(fields[i]);
}
}
outboundstring.append(formattedparam);
debugprintln("buildGrammar appending outboundstring with "+formattedparam);
}
debugprintln("buildGrammar outboundstring = "+outboundstring.toString());
return outboundstring.toString();
}
/**
*
* Converts the value of a specified fieldname from the extraparams map into
* binary, either handling it as a large integer or taking into account the
* compaction of each ASCII byte that is specified in the TDT definition
* file for that particular field
*/
private String fieldToBinary(Field field, Map<String, String> extraparams) {
// really need an index to find field number given fieldname;
String fieldname = field.getName();
String value = extraparams.get(fieldname);
String compaction = field.getCompaction();
if (compaction == null) {
value = dec2bin(value);
} else {
value = stringToBinary(value, compaction);
}
return value;
}
/**
*
* Converts a character string to a binary string according to the specified compaction
*
*/
private String stringToBinary(String value, String compaction) {
String s;
if ("5-bit".equals(compaction)) {
// "5-bit"
s = uppercasefive2bin(value);
} else if ("6-bit".equals(compaction)) {
// 6-bit
s = alphanumsix2bin(value);
} else if ("7-bit".equals(compaction)) {
// 7-bit
s = asciiseven2bin(value);
} else if ("8-bit".equals(compaction)) {
// 8-bit
s = bytestring2bin(value);
} else {
debugprintln("***ERROR: unsupported compaction method " + compaction);
throw new Error("unsupported compaction method " + compaction);
}
return s;
}
/**
* pad a value according the field definition.
*/
private void padField(Map<String, String> extraparams, Field field) {
String name = field.getName();
String value = extraparams.get(name);
PadDirectionList padDir = field.getPadDir();
PadDirectionList bitPadDir = field.getBitPadDir();
debugprintln("Line 1560 (padField), outputfield ["+name+"] = "+value);
if (bitPadDir != null) {
if (bitPadDir == PadDirectionList.RIGHT) {
debugprintln("Line 1563 (padField), bitPadDir = RIGHT");
} else {
debugprintln("Line 1565 (padField), bitPadDir = LEFT");
}
}
if (padDir != null) {
if (padDir == PadDirectionList.RIGHT) {
debugprintln("Line 1571 (padField), padDir = RIGHT");
} else {
debugprintln("Line 1573 (padField), padDir = LEFT");
}
}
int requiredLength = -1; // -1 indicates that the length is unspecified
if (field.getLength() != null) {
requiredLength = field.getLength().intValue();
}
debugprintln("Line 1583 (padField), requiredLength ["+name+"] = "+requiredLength);
// assert value != null;
if (value == null)
return;
String padCharString = field.getPadChar();
// if no pad char specified, don't attempt padding
if (padCharString == null)
return;
assert padCharString.length() > 0;
char padChar = padCharString.charAt(0);
String paddedvalue;
if ((value != null) && (value.toString().length() < requiredLength) && (padCharString !=null) && (requiredLength >=0)) {
paddedvalue = applyPadChar(value, padDir, padCharString, requiredLength);
debugprintln("Line 1600 (padField), paddedvalue = "+paddedvalue);
} else {
paddedvalue = value;
debugprintln("Line 1603 (padField), No need for padding");
}
if (requiredLength != value.length()) {
extraparams.put(name,paddedvalue);
}
if (requiredLength == 0) {
extraparams.put(name,"");
}
}
/**
* If the outbound level is BINARY, convert the string field to binary, then
* pad to the left with the appropriate number of zero bits to reach a
* number of bits specified by the bitLength attribute of the TDT definition
* file.
*/
private void binaryPadding(Map<String, String> extraparams, Field tdtfield) {
String fieldname = tdtfield.getName();
int reqbitlength = tdtfield.getBitLength().intValue();
PadDirectionList bitPadDir = tdtfield.getBitPadDir();
String binarypaddedvalue;
String binaryValue = fieldToBinary(tdtfield, extraparams);
debugprintln("binarypadding: binaryValue = "+binaryValue);
if (binaryValue.length() < reqbitlength) {
if (bitPadDir != null) {
binarypaddedvalue = applyPadChar(binaryValue, bitPadDir, "0", reqbitlength);
} else {
// Default to binary padding at the left if bitPadDir is unspecified.
// This is for backwards compatibility with TDT 1.0 definition files that lack bitPadDir
binarypaddedvalue = applyPadChar(binaryValue, PadDirectionList.LEFT, "0", reqbitlength);
}
} else {
if (binaryValue.length() > reqbitlength) {
debugprintln("***EXCEPTION: Binary value [" + binaryValue + "] for field " + fieldname + " exceeds maximum allowed " + reqbitlength + " bits. Decimal value was " + extraparams.get(fieldname));
throw new TDTException("Binary value [" + binaryValue + "] for field " + fieldname + " exceeds maximum allowed " + reqbitlength + " bits. Decimal value was " + extraparams.get(fieldname));
}
binarypaddedvalue = binaryValue;
}
if (reqbitlength==0) {
binarypaddedvalue="";
}
debugprintln("binarypadding: binarypaddedalue = "+binarypaddedvalue);
extraparams.put(fieldname, binarypaddedvalue);
}
/**
* Removes leading or trailing characters equal to padchar from the
* start/end of the string specified as the first parameter. The second
* parameter specified the stripping direction as "LEFT" or "RIGHT" and the
* third parameter specifies the character to be stripped.
*/
private String stripPadChar(String padded, PadDirectionList dir, String padchar) {
String rv;
String onlypadcharpattern="^["+padchar+"]+$";
Pattern testregex = Pattern.compile(onlypadcharpattern);
// check if line includes filename.xml - if so, extract auxiliaryfile
Matcher testmatcher2 = testregex.matcher(padded);
if (testmatcher2.find()) {
rv=padchar;
} else {
if (dir == null || padchar == null)
rv = padded;
else {
String pattern;
if (dir == PadDirectionList.RIGHT)
pattern = "[" + padchar + "]+$";
else
// if (dir == PadDirectionList.LEFT)
pattern = "^[" + padchar + "]+";
rv = padded.replaceAll(pattern, "");
}
}
return rv;
}
/**
* Applies leading or trailing characters equal to padchar from the
* start/end of the string specified as the first parameter.
* The second parameter specified the stripping direction as "LEFT" or "RIGHT".
* The third parameter specifies the character to be used for padding.
* The fourth parameter specifies the required length for the string.
*/
private String applyPadChar(String bare, PadDirectionList dir, String padchar, int requiredLength) {
String rv;
if (dir == null || padchar == null || requiredLength == -1)
rv = bare;
else {
StringBuilder buf = new StringBuilder(requiredLength);
for (int i=0; i < requiredLength - bare.length(); i++)
buf.append(padchar);
if (dir == PadDirectionList.RIGHT)
rv = bare+buf.toString();
else
// if (dir == PadDirectionList.LEFT)
rv = buf.toString()+bare;
}
return rv;
}
private String stripbinarypadding(String input, PadDirectionList bitPadDir, int compaction) {
String stripped;
Pattern testregex = Pattern.compile("^0+$");
// check if line includes filename.xml - if so, extract auxiliaryfile
Matcher testmatcher2 = testregex.matcher(input);
if (testmatcher2.find()) {
stripped="0";
} else {
if (compaction >=4) {
if (bitPadDir == PadDirectionList.RIGHT) {
int lastnonzerobit = input.lastIndexOf("1");
int bitsforstripped = compaction * (1 + lastnonzerobit/compaction);
stripped = input.substring(0,bitsforstripped);
} else {
int firstnonzerobit = input.indexOf("1");
int length = input.length();
int bitsforstripped = compaction * (1+ (length - firstnonzerobit)/compaction);
stripped = input.substring(length-bitsforstripped);
}
} else {
if (bitPadDir == PadDirectionList.RIGHT) {
int lastnonzerobit = input.lastIndexOf("1");
stripped = input.substring(0,lastnonzerobit);
} else {
int firstnonzerobit = input.indexOf("1");
stripped = input.substring(firstnonzerobit);
}
}
}
return stripped;
}
/**
*
* Adds additional entries to the extraparams hashmap by processing various
* rules defined in the TDT definition files. Typically used for string
* processing functions, lookup in tables, calculation of check digits etc.
*/
private void processRules(Map<String, String> extraparams, Rule tdtrule) {
String tdtfunction = tdtrule.getFunction();
int openbracket = tdtfunction.indexOf("(");
assert openbracket != -1;
String params = tdtfunction.substring(openbracket + 1, tdtfunction
.length() - 1);
String rulename = tdtfunction.substring(0, openbracket);
String[] parameter = params.split(",");
String newfieldname = tdtrule.getNewFieldName();
debugprintln("Rule: newfieldname = "+newfieldname);
debugprintln(tdtfunction + " " + parameter[0] + " " + extraparams.get(parameter[0]));
/**
* Stores in the hashmap extraparams the value obtained from a lookup in
* a specified XML table.
*
* The first parameter is the given value already known. This is denoted
* as $1 in the corresponding XPath expression
*
* The second parameter is the string filename of the table which must
* be present in the auxiliary subdirectory
*
* The third parameter is the column in which the supplied input value
* should be sought
*
* The fourth parameter is the column whose value should be read for the
* corresponding row, in order to obtain the result of the lookup.
*
* The rule in the definition file may contain an XPath expression and a
* URL where the table may be obtained.
*/
if (rulename.equals("TABLELOOKUP")) {
// parameter[0] is given value
// parameter[1] is table
// parameter[2] is input column supplied
// parameter[3] is output column required
assert parameter.length == 4 : "incorrect number of parameters to tablelookup "
+ params;
if (parameter[1].equals("tdt64bitcpi")) {
String s = extraparams.get(parameter[0]);
assert s != null : tdtfunction + " when " + parameter[0]
+ " is null";
String t = gs1cpi.get(s);
assert t != null : "gs1cpi[" + s + "] is null";
assert newfieldname != null;
extraparams.put(newfieldname, t);
debugprintln("Rule result: "+newfieldname+" = "+t);
// extraparams.put(newfieldname,
// gs1cpi.get(extraparams.get(parameter[0])));
} else { // JPB! the following is untested
String tdtxpath = tdtrule.getTableXPath();
String tdttableurl = tdtrule.getTableURL();
String tdtxpathsub = tdtxpath.replaceAll("\\$1", extraparams.get(parameter[0]));
extraparams.put(newfieldname, xpathlookup("ManagerTranslation.xml", tdtxpathsub));
debugprintln("TABLELOOKUP Rule result: "+newfieldname+" = "+xpathlookup("ManagerTranslation.xml", tdtxpathsub));
}
}
/**
* Stores the length of the specified string under the new fieldname
* specified by the corresponding rule of the definition file.
*/
if (rulename.equals("LENGTH")) {
assert extraparams.get(parameter[0]) != null : tdtfunction
+ " when " + parameter[0] + " is null";
if (extraparams.get(parameter[0]) != null) {
extraparams.put(newfieldname, Integer.toString(extraparams.get(parameter[0]).length()));
debugprintln("LENGTH Rule result: "+newfieldname+" = "+Integer.toString(extraparams.get(parameter[0]).length()));
}
}
/**
* Stores a GS1 check digit in the extraparams hashmap, keyed under the
* new fieldname specified by the corresponding rule of the definition
* file.
*/
if (rulename.equals("GS1CHECKSUM")) {
assert extraparams.get(parameter[0]) != null : tdtfunction
+ " when " + parameter[0] + " is null";
if (extraparams.get(parameter[0]) != null) {
extraparams.put(newfieldname, gs1checksum(extraparams.get(parameter[0])));
debugprintln("GS1CHECKSUM Rule result: "+newfieldname+" = "+gs1checksum(extraparams.get(parameter[0])));
}
}
/**
* Obtains a substring of the string provided as the first parameter. If
* only a single second parameter is specified, then this is considered
* as the start index and all characters from the start index onwards
* are stored in the extraparams hashmap under the key named
* 'newfieldname' in the corresponding rule of the definition file. If a
* second and third parameter are specified, then the second parameter
* is the start index and the third is the length of characters
* required. A substring consisting characters from the start index up
* to the required length of characters is stored in the extraparams
* hashmap, keyed under the new fieldname specified by the corresponding
* rule of the defintion file.
*/
if (rulename.equals("SUBSTR")) {
assert extraparams.get(parameter[0]) != null : tdtfunction
+ " when " + parameter[0] + " is null";
if (parameter.length == 2) {
if (extraparams.get(parameter[0]) != null) {
int start = getIntValue(parameter[1], extraparams);
if (start >= 0) {
extraparams.put(newfieldname, extraparams.get(parameter[0]).substring(start));
debugprintln("SUBSTR Rule result: "+newfieldname+" = "+extraparams.get(parameter[0]).substring(start));
}
}
}
if (parameter.length == 3) { // need to check that this variation is
// correct - c.f. Perl substr
assert extraparams.get(parameter[0]) != null : tdtfunction
+ " when " + parameter[0] + " is null";
if (extraparams.get(parameter[0]) != null) {
int start = getIntValue(parameter[1], extraparams);
int end = getIntValue(parameter[2], extraparams);
if ((start >= 0) && (end >= 0)) {
extraparams.put(newfieldname, extraparams.get(parameter[0]).substring(start, start + end));
debugprintln("SUBSTR Rule result: "+newfieldname+" = "+extraparams.get(parameter[0]).substring(start, start + end));
}
}
}
}
/**
* Concatenates specified string parameters together. Literal values
* must be enclosed within single or double quotes or consist of
* unquoted digits. Other unquoted strings are considered as fieldnames
* and the corresponding value from the extraparams hashmap are
* inserted. The result of the concatenation (and substitution) of the
* strings is stored as a new entry in the extraparams hashmap, keyed
* under the new fieldname specified by the rule.
*/
if (rulename.equals("CONCAT")) {
StringBuilder buffer = new StringBuilder();
for (int p1 = 0; p1 < parameter.length; p1++) {
Matcher matcher = Pattern.compile("\"(.*?)\"|'(.*?)'|[0-9]")
.matcher(parameter[p1]);
if (matcher.matches()) {
buffer.append(parameter[p1]);
} else {
assert extraparams.get(parameter[p1]) != null : tdtfunction
+ " when " + parameter[p1] + " is null";
if (extraparams.get(parameter[p1]) != null) {
buffer.append(extraparams.get(parameter[p1]));
}
}
}
extraparams.put(newfieldname, buffer.toString());
debugprintln("CONCAT Rule result: "+newfieldname+" = "+buffer.toString());
}
/**
* Adds specified parameters together. Unqouted strings are considered
* as fieldnames and the corresponding value from the extraparams hashmap
* are used in the calculation.
* The result of the addition is stored as a new entry in the extraparams
* hashmap, keyed under the new fieldname specified by the rule.
*/
if (rulename.equalsIgnoreCase("add")) {
assert extraparams.get(parameter[0]) != null : tdtfunction + " when " + parameter[0] + " is null";
if ((extraparams.get(parameter[0]) != null) && (parameter[1] != null) && (parameter.length == 2)) {
int initialvalue = getIntValue(parameter[0], extraparams);
int increment = Integer.parseInt(parameter[1]);
extraparams.put(newfieldname, Integer.toString(initialvalue+increment));
}
}
/**
* Multiplies the specified parameters together.
* Unquoted strings are considered as fieldnames and the corresponding
* value from the extraparams hashmap are used in the calculation.
* The result of the multiplication is stored as a new entry in the
* extraparams hashmap, keyed under the new fieldname specified by the rule.
*/
if (rulename.equalsIgnoreCase("multiply")) {
assert extraparams.get(parameter[0]) != null : tdtfunction + " when " + parameter[0] + " is null";
if ((extraparams.get(parameter[0]) != null) && (parameter[1] != null) && (parameter.length == 2)) {
int initialvalue = getIntValue(parameter[0], extraparams);
int factor = Integer.parseInt(parameter[1]);
extraparams.put(newfieldname, Integer.toString(initialvalue*factor));
}
}
/**
* Divides the first parameter by the second parameter.
* Unquoted strings are considered as fieldnames and the corresponding
* value from the extraparams hashmap are used in the calculation.
* The result of the division is stored as a new entry in the
* extraparams hashmap, keyed under the new fieldname specified by the rule.
*/
if (rulename.equalsIgnoreCase("divide")) {
assert extraparams.get(parameter[0]) != null : tdtfunction + " when " + parameter[0] + " is null";
if ((extraparams.get(parameter[0]) != null) && (parameter[1] != null) && (parameter.length == 2)) {
int initialvalue = getIntValue(parameter[0], extraparams);
int divisor = Integer.parseInt(parameter[1]);
extraparams.put(newfieldname, Integer.toString(initialvalue*divisor));
}
}
/**
* Subtracts the second parameter from the first parameter.
* Unquoted strings are considered as fieldnames and the corresponding
* value from the extraparams hashmap are used in the calculation.
* The result of the subtraction is stored as a new entry
* in the extraparams hashmap, keyed under the new fieldname specified
* by the rule.
*/
if (rulename.equalsIgnoreCase("subtract")) {
assert extraparams.get(parameter[0]) != null : tdtfunction + " when " + parameter[0] + " is null";
if ((extraparams.get(parameter[0]) != null) && (parameter[1] != null) && (parameter.length == 2)) {
int initialvalue = getIntValue(parameter[0], extraparams);
int decrement = Integer.parseInt(parameter[1]);
extraparams.put(newfieldname, Integer.toString(initialvalue-decrement));
}
}
/**
* Returns the remainder after integer division of the first parameter
* divided by the second parameter.
* Unquoted strings are considered as fieldnames and the corresponding
* value from the extraparams hashmap are used in the calculation.
* The remainder after integer division is stored as a new entry
* in the extraparams hashmap, keyed under the new fieldname specified
* by the rule.
*/
if (rulename.equalsIgnoreCase("mod")) {
assert extraparams.get(parameter[0]) != null : tdtfunction + " when " + parameter[0] + " is null";
if ((extraparams.get(parameter[0]) != null) && (parameter[1] != null) && (parameter.length == 2)) {
int initialvalue = getIntValue(parameter[0], extraparams);
int divisor = Integer.parseInt(parameter[1]);
extraparams.put(newfieldname, Integer.toString(initialvalue % divisor));
}
}
}
/**
*
* Returns the value of a specified fieldname from the specified hashmap and
* returns an integer value or throws an exception if the value is not an
* integer
*/
private int getIntValue(String fieldname, Map<String, String> extraparams) {
Matcher checkint = Pattern.compile("^\\d+$").matcher(fieldname);
int rv;
if (checkint.matches()) {
rv = Integer.parseInt(fieldname);
} else {
if (extraparams.containsKey(fieldname)) {
rv = Integer.parseInt(extraparams.get(fieldname));
} else {
rv = -1;
debugprintln("***EXCEPTION: No integer value for " + fieldname + " can be found - check extraparams;");
throw new TDTException("No integer value for " + fieldname + " can be found - check extraparams;");
}
}
return rv;
}
/**
*
* Performs an XPATH lookup in an xml document. The document has been loaded
* into a private member. The XPATH expression is supplied as the second
* string parameter The return value is of type string e.g. this is
* currently used primarily for looking up the Company Prefix Index for
* encoding a GS1 Company Prefix into a 64-bit EPC tag
*
*/
private String xpathlookup(String xml, String expression) {
try {
// Parse the XML as a W3C document.
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = builder.parse(GEPC64xml);
XPath xpath = XPathFactory.newInstance().newXPath();
String rv = (String) xpath.evaluate(expression, document,
XPathConstants.STRING);
return rv;
} catch (ParserConfigurationException e) {
System.err.println("ParserConfigurationException caught...");
e.printStackTrace();
return null;
} catch (XPathExpressionException e) {
System.err.println("XPathExpressionException caught...");
e.printStackTrace();
return null;
} catch (SAXException e) {
System.err.println("SAXException caught...");
e.printStackTrace();
return null;
} catch (IOException e) {
System.err.println("IOException caught...");
e.printStackTrace();
return null;
}
}
// auxiliary functions
/**
*
* Converts original characters into URI escape sequences where required
*/
private static String uriescape(String in) {
in = in.replaceAll("%","%25");
in = in.replaceAll("\\?","%3F");
in = in.replaceAll("\"","%22");
in = in.replaceAll("&","%26");
in = in.replaceAll("/","%2F");
in = in.replaceAll("<","%3C");
in = in.replaceAll(">","%3E");
in = in.replaceAll("
return in;
}
/**
*
* Converts URI escaped characters back into original characters
*/
private static String uriunescape(String in) {
in = in.replaceAll("%25","%");
in = in.replaceAll("%3[Ff]","?");
in = in.replaceAll("%22","\\");
in = in.replaceAll("%26","&");
in = in.replaceAll("%2[Ff]","/");
in = in.replaceAll("%3[Cc]","<");
in = in.replaceAll("%3[Ee]",">");
in = in.replaceAll("%23","
return in;
}
/**
*
* Converts a binary string input into a byte string, using 8-bits per
* character byte
*/
private String bytestring2bin(String bytestring) {
String binary;
StringBuilder buffer = new StringBuilder("");
int len = bytestring.length();
byte[] bytes = bytestring.getBytes();
for (int i = 0; i < len; i++) {
buffer.append(padBinary(dec2bin(Integer.toString(bytes[i])), 8));
}
binary = buffer.toString();
return binary;
}
/**
*
* Converts a byte string input into a binary string, using 8-bits per
* character byte
*/
private String bin2bytestring(String binary) {
String bytestring;
StringBuilder buffer = new StringBuilder("");
int len = binary.length();
for (int i = 0; i < len; i += 8) {
int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i,
i + 8), 8)));
buffer.append((char) j);
}
bytestring = buffer.toString();
return bytestring;
}
/**
*
* Converts an ASCII string input into a binary string, using 7-bit
* compaction of each ASCII byte
*/
private String asciiseven2bin(String asciiseven) {
String binary;
StringBuilder buffer = new StringBuilder("");
int len = asciiseven.length();
byte[] bytes = asciiseven.getBytes();
for (int i = 0; i < len; i++) {
buffer.append(padBinary(dec2bin(Integer.toString(bytes[i] % 128)),
8).substring(1, 8));
}
binary = buffer.toString();
return binary;
}
/**
*
* Converts a binary string input into an ASCII string output, assuming that
* 7-bit compaction was used
*/
private String bin2asciiseven(String binary) {
String asciiseven;
StringBuilder buffer = new StringBuilder("");
int len = binary.length();
for (int i = 0; i < len; i += 7) {
int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i,
i + 7), 8)));
buffer.append((char) j);
}
asciiseven = buffer.toString();
return asciiseven;
}
/**
* Converts an alphanumeric string input into a binary string, using 6-bit
* compaction of each ASCII byte
*/
private String alphanumsix2bin(String alphanumsix) {
String binary;
StringBuilder buffer = new StringBuilder("");
int len = alphanumsix.length();
byte[] bytes = alphanumsix.getBytes();
for (int i = 0; i < len; i++) {
buffer
.append(padBinary(dec2bin(Integer.toString(bytes[i] % 64)),
8).substring(2, 8));
}
binary = buffer.toString();
return binary;
}
/**
*
* Converts a binary string input into a character string output, assuming
* that 6-bit compaction was used
*/
private String bin2alphanumsix(String binary) {
String alphanumsix;
StringBuilder buffer = new StringBuilder("");
int len = binary.length();
for (int i = 0; i < len; i += 6) {
int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i,
i + 6), 8)));
if (j < 32) {
j += 64;
}
buffer.append((char) j);
}
alphanumsix = buffer.toString();
return alphanumsix;
}
/**
* Converts an upper case character string input into a binary string, using
* 5-bit compaction of each ASCII byte
*/
private String uppercasefive2bin(String uppercasefive) {
String binary;
StringBuilder buffer = new StringBuilder("");
int len = uppercasefive.length();
byte[] bytes = uppercasefive.getBytes();
for (int i = 0; i < len; i++) {
buffer
.append(padBinary(dec2bin(Integer.toString(bytes[i] % 32)),
8).substring(3, 8));
}
binary = buffer.toString();
return binary;
}
/**
*
* Converts a binary string input into a character string output, assuming
* that 5-bit compaction was used
*/
private String bin2uppercasefive(String binary) {
String uppercasefive;
StringBuilder buffer = new StringBuilder("");
int len = binary.length();
for (int i = 0; i < len; i += 5) {
int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i,
i + 5), 8)));
buffer.append((char) (j + 64));
}
uppercasefive = buffer.toString();
return uppercasefive;
}
/**
* Pads a binary value supplied as a string first parameter to the left with
* leading zeros in order to reach a required number of bits, as expressed
* by the second parameter, reqlen. Returns a string value corresponding to
* the binary value left padded to the required number of bits.
*/
private String padBinary(String binary, int reqlen) {
String rv;
int l = binary.length();
int pad = (reqlen - (l % reqlen)) % reqlen;
StringBuilder buffer = new StringBuilder("");
for (int i = 0; i < pad; i++) {
buffer.append("0");
}
buffer.append(binary);
rv = buffer.toString();
return rv;
}
/**
* Calculates the check digit for a supplied input string (assuming that the
* check digit will be the digit immediately following the supplied input
* string). GS1 (formerly EAN.UCC) check digit calculation methods are used.
*/
private String gs1checksum(String input) {
int checksum;
int weight;
int total = 0;
int len = input.length();
int d;
for (int i = 0; i < len; i++) {
if (i % 2 == 0) {
weight = -3;
} else {
weight = -1;
}
d = Integer.parseInt(input.substring(len - 1 - i, len - i));
total += weight * d;
}
checksum = (10 + total % 10) % 10;
return Integer.toString(checksum);
}
/**
* find a level by its type in a scheme. This involves iterating through the
* list of levels. The main reason for doing it this way is to avoid being
* dependent on the order in which the levels are coded in the xml, which is
* not explicitly constrained.
*/
private Level findLevel(Scheme scheme, LevelTypeList levelType) {
Level level = null;
for (Level lev : scheme.getLevel()) {
if (lev.getType() == levelType) {
level = lev;
// break;
}
}
if (level == null) {
debugprintln("***ERROR: Couldn't find type for " + levelType + " in level " + scheme);
throw new Error("Couldn't find type " + levelType + " in scheme "
+ scheme);
}
return level;
}
/**
* find a option by its type in a scheme. This involves iterating through
* the list of options. The main reason for doing it this way is to avoid
* being dependent on the order in which the options are coded in the xml,
* which is not explicitly constrained.
*/
private Option findOption(Level level, String optionKey) {
Option option = null;
for (Option opt : level.getOption()) {
if (opt.getOptionKey().equals(optionKey)) {
option = opt;
break;
}
}
if (option == null) {
debugprintln("***ERROR: Couldn't find option for " + optionKey + " in level " + level);
throw new Error("Couldn't find option for " + optionKey + " in level " + level);
}
return option;
}
/**
* find a field by its name in an option. This involves iterating through
* the list of fields. The main reason for doing it this way is to avoid
* being dependent on the order in which the fields are coded in the xml,
* which is not explicitly constrained.
*/
private Field findField(Option option, String fieldname, Level tdtoutlevel) {
Field field=null;
for (Field fld : option.getField()) {
if (fld.getName().equals(fieldname)) {
field = fld;
break;
}
}
return field;
}
private void debugprint(String message) {
if (showdebug) {
System.out.print(message);
}
}
private void debugprintln(String message) {
if (showdebug) {
System.out.println(message);
}
}
/**
* adds a list of global company prefixes (GCPs) to the current list of GCPs.
* The list of GCPs is used to convert a GTIN and serial or an SSCC to an
* EPC number when the user does not provide length of the GCP.
*
* The method expects the individual GCPs to be on a new line each. It is up
* to the user to determine wher the GCPs are read from (normal file, network,
* onsepc.com)
*
* @param inputstream
* a reference to a source of GCPs
* @throws IOException
*/
public void addListOfGCPs(InputStream source) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(
source, "US-ASCII"));
try {
String line;
while ((line = br.readLine()) != null) {
//debugprintln(line);
}
} finally {
br.close();
}
}
/**
* converts a GTIN and serial number to the pure identity representation of an EPC.
* The method looks up the length of the global company prefix from a list that can
* loaded into the TDT engine.
*
* @params gtin
* @params serial
* @returns pure identity EPC
*
*/
public String convertGTINandSerialToPureIdentityEPC(String gtin, String serial) {
return " ";
}
/**
* converts a GTIN and serial number to the pure identity representation of an EPC.
* The length of the global company prefix is provided as a method parameter.
*
* @params gtin
* @params serial
* @params length of global company prefix
* @returns pure identity EPC
*
*/
public String convertGTINandSerialToPureIdentityEPC(String gtin, String serial, int gcpLength) {
return " ";
}
/**
* converts a pure identity EPC to gtin and serial.
*
* @params epc in pure identity format
* @returns List with gtin and serial
*
*/
public List<String> convertPureIdentityEPCToGTINandSerial(String EPC) {
return new ArrayList<String>();
}
/**
* converts a SSCC to the pure identity representation of an EPC. The method looks up
* the length of the global company prefix from a list that can loaded into the TDT
* engine via the addGCPs
*
* @params gtin
* @params serial
* @returns pure identity EPC
*
*/
public String convertSSCCToPureIdentityEPC(String sscc) {
return " ";
}
/**
* converts a SSCC to the pure identity representation of an EPC.
* The length of the global company prefix is provided as a method parameter.
* @params gtin
* @params serial
* @params length of global company prefix
* @returns pure identity EPC
*
*/
public String convertSSCCToPureIdentityEPC(String sscc, int gcpLength) {
return " ";
}
/**
* converts a pure identity EPC to gtin and serial.
*
* @params epc in pure identity format
* @returns List with gtin and serial
*
*/
public String convertPureIdentityEPCToSSCC(String EPC) {
return " ";
}
/**
* converts a GLN and serial to the pure identity representation of an EPC. The method looks up
* the length of the global company prefix from a list that can loaded into the TDT
* engine.
*
* @params gtin
* @params serial
* @returns pure identity EPC
*
*/
public String convertGLNandSerialToPureIdentityEPC(String gln, String serial) {
return " ";
}
/**
* converts a GLN and serial to the pure identity representation of an EPC.
* The length of the global company prefix is provided as a method parameter.
* @params gtin
* @params serial
* @params length of global company prefix
* @returns pure identity EPC
*
*/
public String convertGLNandSerialToPureIdentityEPC(String gln, String serial, int gcpLength) {
return " ";
}
/**
* converts a binary EPC to a pure identity representation.
* @params binary EPC
* @returns pure identity EPC
*
*/
public String convertBinaryEPCToPureIdentityEPC(String binary) {
return " ";
}
/**
* converts a binary EPC in hex notation to a pure identity representation.
* @params hexadecimal EPC
* @returns pure identity EPC
*
*/
public String convertHexEPCToPureIdentityEPC(String binary) {
return " ";
}
public String getVersion() {
return "Fosstrak TDT 1.4.0 for TDT v1.4; 2010-110-13 22:29";
}
} |
package de.hapm.swu;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;
import java.util.TimeZone;
import javax.persistence.PersistenceException;
import org.bukkit.Chunk;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.plugin.java.JavaPlugin;
/**
* This little plugin tracks when chunks where generated, and with what version of
*
* @author Markus Andree
*/
public class SmoothWorldUpdaterPlugin extends JavaPlugin implements Listener {
@Override
public void onEnable() {
super.onEnable();
setupDatabase();
getServer().getPluginManager().registerEvents(this, this);
}
public void setupDatabase() {
try {
getDatabase().find(ChunkInfo.class).findRowCount();
}
catch (PersistenceException ex) {
getLogger().info("Installing database for " + getDescription().getName() + " due to first time usage");
installDDL();
}
}
@Override
public void onDisable() {
super.onDisable();
}
@EventHandler
public void chunkLoad(final ChunkLoadEvent args) {
final Chunk chunk = args.getChunk();
final boolean newChunk = args.isNewChunk();
getDatabase().getBackgroundExecutor().execute(new Runnable() {
public void run() {
ChunkInfo info = getChunkInfo(chunk, newChunk);
getDatabase().save(info);
getLogger().info("New " + info.toString());
}
});
}
@EventHandler(priority=EventPriority.MONITOR)
public void blockPlaced(final BlockPlaceEvent args) {
final Chunk chunk = args.getBlock().getChunk();
final int typeId = args.getBlockPlaced().getTypeId();
getDatabase().getBackgroundExecutor().execute(new Runnable() {
public void run() {
ChunkInfo info = getChunkInfo(chunk);
info.setPlaced(typeId);
getDatabase().save(info);
}
});
}
@EventHandler(priority=EventPriority.MONITOR)
public void blockBreak(final BlockBreakEvent args) {
final Chunk chunk = args.getBlock().getChunk();
final int typeId = args.getBlock().getTypeId();
getDatabase().getBackgroundExecutor().execute(new Runnable() {
public void run() {
ChunkInfo info = getChunkInfo(chunk);
info.setBreaked(typeId);
getDatabase().save(info);
}
});
}
public ChunkInfo getChunkInfo(final Chunk chunk) {
return getChunkInfo(chunk, false);
}
public ChunkInfo getChunkInfo(final Chunk chunk, final boolean isNew) {
Hashtable<String, Object> id = new Hashtable<String, Object>();
id.put("world", chunk.getWorld().getName());
id.put("key", ChunkInfo.getKey(chunk.getX(), chunk.getZ()));
ChunkInfo info = getDatabase().find(ChunkInfo.class, id);
if (info == null) {
info = new ChunkInfo(chunk.getWorld().getName(), chunk.getX(), chunk.getZ(), isNew ? getActiveVersion() : ChunkInfo.UNKOWN_GENERATOR_VERSION, Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis());
}
return info;
}
@Override
public List<Class<?>> getDatabaseClasses() {
List<Class<?>> classes = super.getDatabaseClasses();
classes.add(ChunkInfo.class);
classes.add(BlockTypeId.class);
return classes;
}
private int getActiveVersion() {
return 1;
}
} |
package org.jboss.virtual;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.jboss.logging.Logger;
import org.jboss.util.StringPropertyReplacer;
import org.jboss.virtual.spi.LinkInfo;
/**
* VFS Utilities
*
* @author <a href="adrian@jboss.com">Adrian Brock</a>
* @version $Revision: 1.1 $
*/
public class VFSUtils
{
/** The log */
private static final Logger log = Logger.getLogger(VFSUtils.class);
public static final String VFS_LINK_PREFIX = ".vfslink";
public static final String VFS_LINK_NAME = "vfs.link.name";
public static final String VFS_LINK_TARGET = "vfs.link.target";
public static String getPathsString(Collection<VirtualFile> paths)
{
StringBuilder buffer = new StringBuilder();
boolean first = true;
for (VirtualFile path : paths)
{
if (path == null)
throw new IllegalArgumentException("Null path in " + paths);
if (first == false)
buffer.append(':');
else
first = false;
buffer.append(path.getPathName());
}
if (first == true)
buffer.append("<empty>");
return buffer.toString();
}
public static void addManifestLocations(VirtualFile file, List<VirtualFile> paths) throws IOException
{
if (file == null)
throw new IllegalArgumentException("Null file");
if (paths == null)
throw new IllegalArgumentException("Null paths");
Manifest manifest = getManifest(file);
if (manifest == null)
return;
Attributes mainAttributes = manifest.getMainAttributes();
String classPath = mainAttributes.getValue(Attributes.Name.CLASS_PATH);
if (classPath == null)
{
if (log.isTraceEnabled())
log.trace("Manifest has no Class-Path for " + file.getPathName());
return;
}
VirtualFile parent = file.getParent();
if (parent == null)
throw new IllegalStateException(file + " has no parent.");
URL parentURL = null;
URL vfsRootURL = null;
int rootPathLength = 0;
try
{
parentURL = parent.toURL();
vfsRootURL = file.getVFS().getRoot().toURL();
rootPathLength = vfsRootURL.getPath().length();
}
catch(URISyntaxException e)
{
IOException ioe = new IOException("Failed to get parent URL for " + file);
ioe.initCause(e);
throw ioe;
}
StringTokenizer tokenizer = new StringTokenizer(classPath);
while (tokenizer.hasMoreTokens())
{
String path = tokenizer.nextToken();
try
{
URL libURL = new URL(parentURL, path);
String libPath = libURL.getPath();
// TODO, this occurs for inner jars. Doubtful that such a mf cp is valid
if( rootPathLength > libPath.length() )
throw new IOException("Invalid rootPath: "+vfsRootURL+", libPath: "+libPath);
String vfsLibPath = libPath.substring(rootPathLength);
VirtualFile vf = file.getVFS().findChild(vfsLibPath);
paths.add(vf);
}
catch (IOException e)
{
log.debug("Manifest Class-Path entry " + path + " ignored for " + file.getPathName() + " reason=" + e);
}
}
}
public static Manifest getManifest(VirtualFile archive) throws IOException
{
if (archive == null)
throw new IllegalArgumentException("Null archive");
VirtualFile manifest;
try
{
manifest = archive.findChild(JarFile.MANIFEST_NAME);
}
catch (IOException ignored)
{
log.debug("Can't find manifest for " + archive.getPathName());
return null;
}
return readManifest(manifest);
}
/**
* Read the manifest from given manifest VirtualFile.
*
* @param manifest the VF to read from
* @return JAR's manifest
* @throws IOException if problems while opening VF stream occur
*/
public static Manifest readManifest(VirtualFile manifest) throws IOException
{
InputStream stream = manifest.openStream();
try
{
return new Manifest(stream);
}
finally
{
try
{
stream.close();
}
catch (IOException ignored)
{
}
}
}
public static Manifest getManifest(VFS archive) throws IOException
{
VirtualFile root = archive.getRoot();
return getManifest(root);
}
public static String fixName(String name)
{
if (name == null)
throw new IllegalArgumentException("Null name");
int length = name.length();
if (length <= 1)
return name;
if (name.charAt(length-1) == '/')
return name.substring(0, length-1);
return name;
}
/**
*
* @param uri
* @return name from uri's path
*/
public static String getName(URI uri)
{
String name = uri.getPath();
if( name != null )
{
// TODO: Not correct for certain uris like jar:...!/
int lastSlash = name.lastIndexOf('/');
if( lastSlash > 0 )
name = name.substring(lastSlash+1);
}
return name;
}
/**
* Take a URL.getQuery string and parse it into name=value pairs
*
* @param query Possibly empty/null url query string
* @return String[] for the name/value pairs in the query. May be empty but never null.
*/
public static Map<String, String> parseURLQuery(String query)
{
HashMap<String, String> pairsMap = new HashMap<String, String>();
if( query != null )
{
StringTokenizer tokenizer = new StringTokenizer(query, "=&");
while( tokenizer.hasMoreTokens() )
{
String name = tokenizer.nextToken();
String value = tokenizer.nextToken();
pairsMap.put(name, value);
}
}
return pairsMap;
}
/**
* Does a vf name contain the VFS link prefix
* @param name - the name portion of a virtual file
* @return true if the name starts with VFS_LINK_PREFIX, false otherwise
*/
public static boolean isLink(String name)
{
return name.indexOf(VFS_LINK_PREFIX) >= 0;
}
/**
* Read the link information from the stream based on the type as determined
* from the name suffix.
*
* @param is - input stream to the link file contents
* @param name - the name of the virtual file representing the link
* @param props the propertes
* @return a list of the links read from the stream
* @throws IOException on failure to read/parse the stream
* @throws URISyntaxException for an error parsing a URI
*/
public static List<LinkInfo> readLinkInfo(InputStream is, String name, Properties props)
throws IOException, URISyntaxException
{
ArrayList<LinkInfo> info = new ArrayList<LinkInfo>();
if( name.endsWith(".properties") )
parseLinkProperties(is, info, props);
else
throw new UnsupportedEncodingException("Unknown link format: "+name);
return info;
}
/**
* Parse a properties link file
*
* @param is - input stream to the link file contents
* @param info the link infos
* @param props the propertes
* @throws IOException on failure to read/parse the stream
* @throws URISyntaxException for an error parsing a URI
*/
public static void parseLinkProperties(InputStream is, List<LinkInfo> info, Properties props)
throws IOException, URISyntaxException
{
props.load(is);
// Iterate over the property tuples
for(int n = 0; ; n ++)
{
String nameKey = VFS_LINK_NAME + "." + n;
String name = props.getProperty(nameKey);
String uriKey = VFS_LINK_TARGET + "." + n;
String uri = props.getProperty(uriKey);
// End when the value is null since a link may not have a name
if (uri == null)
{
break;
}
// Replace any system property references
uri = StringPropertyReplacer.replaceProperties(uri);
LinkInfo link = new LinkInfo(name, new URI(uri));
info.add(link);
}
}
/**
* Deal with urls that may include spaces.
*
* @param url the url
* @return uri the uri
* @throws URISyntaxException for any error
*/
public static URI toURI(URL url) throws URISyntaxException
{
String urispec = url.toExternalForm();
// Escape any spaces
urispec = urispec.replaceAll(" ", "%20");
return new URI(urispec);
}
} |
package edu.vu.isis.ammo.core.network;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.util.LinkedList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.vu.isis.ammo.core.distributor.DistributorDataStore.ChannelDisposal;
import edu.vu.isis.ammo.core.pb.AmmoMessages;
public class SerialChannel extends NetChannel
{
// Move these to the interface class later.
public static final int SERIAL_DISABLED = 1;
public static final int SERIAL_WAITING_FOR_TTY = 2;
public static final int SERIAL_CONNECTED = 3;
public static final int SERIAL_ERROR = 4;
static {
System.loadLibrary("ethrmon");
}
public SerialChannel( String theName, IChannelManager iChannelManager )
{
super( theName );
logger.info( "SerialChannel::SerialChannel()" );
mChannelManager = iChannelManager;
// The channel is created in the disabled state, so it will
// not have a Connector thread.
}
public synchronized void enable()
{
logger.info( "SerialChannel::enable()" );
if ( mConnector == null ) {
mConnector = new Connector();
mConnector.start();
}
else {
logger.error( "enable() called on an already enabled channel" );
}
}
public synchronized void disable()
{
logger.info( "SerialChannel::disable()" );
if ( mConnector != null ) {
mConnector.terminate();
mConnector = null;
}
disconnect();
setState( SERIAL_DISABLED );
}
/**
* Do we even need this? Does it need to be public? Couldn't the
* NS just call enable/disable in sequence? Ah, reset() might be
* more explicit about what is going on.
*/
public synchronized void reset()
{
disable();
enable();
}
/**
* Rename this to send() once the merge is done.
*/
public ChannelDisposal sendRequest( AmmoGatewayMessage message )
{
return mSenderQueue.putFromDistributor( message );
}
public boolean isConnected() { return getState() == SERIAL_CONNECTED; }
// The following methods will require a disconnect and reconnect,
// because the variables can't changed while running. They probably aren't
// that important in the short-term.
// NOTE: The following two function are probably not working atm. We need
// to make sure that they're synchronized, and deal with disconnecting the
// channel (to force a reconnect). This functionality isn't presently
// needed, but fix this at some point.
/**
* FIXME
*/
public void setDevice( String device )
{
logger.info( "Device set to {}", device );
mDevice = device;
}
/**
* FIXME
*/
public void setBaudRate( int baudRate )
{
logger.info( "Baud rate set to {}", baudRate );
mBaudRate = baudRate;
}
// The following methods can be changed while connected. Modify the
// threads to get the values from synchronized members.
public void setSlotNumber( int slotNumber )
{
logger.info( "Slot set to {}", slotNumber );
mSlotNumber.set( slotNumber );
}
public void setRadiosInGroup( int radiosInGroup )
{
logger.error( "Radios in group set to {}", radiosInGroup );
mRadiosInGroup.set( radiosInGroup );
}
public void setSlotDuration( int slotDuration )
{
logger.error( "Slot duration set to {}", slotDuration );
mSlotDuration.set( slotDuration );
}
public void setTransmitDuration( int transmitDuration )
{
logger.error( "Transmit duration set to {}", transmitDuration );
mTransmitDuration.set( transmitDuration );
}
public void setSenderEnabled( boolean enabled )
{
logger.error( "Sender enabled set to {}", enabled );
mSenderEnabled.set( enabled );
}
public void setReceiverEnabled( boolean enabled )
{
logger.error( "Receiver enabled set to {}", enabled );
mReceiverEnabled.set( enabled );
}
// Private classes, methods, and members
private class Connector extends Thread
{
private final Logger logger = LoggerFactory.getLogger( "net.serial.connector" );
public Connector()
{
logger.info( "SerialChannel.Connector::Connector()" );
setState( SERIAL_WAITING_FOR_TTY );
}
@Override
public void run()
{
logger.info( "SerialChannel.Connector::run()",
Thread.currentThread().getId() );
// We might have been disabled before the thread even gets
// a chance to run, so check that before doing anything.
if ( isInterrupted() )
return;
try {
setState( SERIAL_WAITING_FOR_TTY );
synchronized ( SerialChannel.this ) {
while ( !connect() ) {
logger.debug( "Connect failed. Waiting to retry..." );
wait( WAIT_TIME );
}
setState( SERIAL_CONNECTED );
mConnector = null;
}
} catch ( InterruptedException e ) {
// Do nothing here. If we were interrupted, we need
// to catch the exception and exit cleanly.
}
// FIXME: Do we need this? Is it the right thing to do?
//catch ( Exception e ) {
// logger.warn("Connector threw exception {}", e.getStackTrace() );
}
public void terminate()
{
logger.info( "SerialChannel.Connector::terminate()" );
interrupt();
}
private boolean connect()
{
logger.info( "SerialChannel.Connector::connect()" );
// Create the SerialPort.
if ( mPort != null )
logger.error( "Tried to create mPort when we already had one." );
try {
mPort = new SerialPort( new File(mDevice), mBaudRate );
} catch ( Exception e ) {
logger.info( "Connection to serial port failed" );
mPort = null;
return false;
}
logger.info( "Connection to serial port established " );
mIsConnected.set( true );
// Create the security object. This must be done before
// the ReceiverThread is created in case we receive a
// message before the SecurityObject is ready to have it
// delivered.
if ( getSecurityObject() != null )
logger.error( "Tried to create SecurityObject when we already had one." );
setSecurityObject( new SerialSecurityObject( SerialChannel.this ));
// Create the sending thread.
if ( mSender != null )
logger.error( "Tried to create Sender when we already had one." );
mSender = new SenderThread();
setIsAuthorized( true );
mSender.start();
// Create the receiving thread.
if ( mReceiver != null )
logger.error( "Tried to create Receiver when we already had one." );
mReceiver = new ReceiverThread();
mReceiver.start();
// FIXME: don't pass in the result of buildAuthenticationRequest(). This is
// just a temporary hack.
//parent.getSecurityObject().authorize( mChannelManager.buildAuthenticationRequest());
// HACK: We are currently not using authentication or
// encryption with the 152s, so just force the
// authorization so the senderqueue will start sending
// packets out.
mSenderQueue.markAsAuthorized();
return true;
}
}
private void disconnect()
{
logger.info( "SerialChannel::disconnect()" );
try {
mIsConnected.set( false );
if ( mConnector != null )
mConnector.terminate();
if ( mSender != null )
mSender.interrupt();
if ( mReceiver != null )
mReceiver.interrupt();
mSenderQueue.reset();
if ( mPort != null ) {
logger.debug( "Closing SerialPort..." );
// Closing the port doesn't interrupt blocked read()s,
// so we close the streams first.
mPort.getInputStream().getChannel().close();
mPort.getOutputStream().getChannel().close();
mPort.close();
logger.debug( "Done" );
mPort = null;
}
setIsAuthorized( false );
setSecurityObject( null );
mConnector = null;
mSender = null;
mReceiver = null;
} catch ( Exception e ) {
logger.error( "Caught exception while closing serial port." );
// Do this here, too, since if we exited early because
// of an exception, we want to make sure that we're in
// an unauthorized state.
setIsAuthorized( false );
return;
}
logger.debug( "Disconnected successfully." );
}
// Called by the sender and receiver when they have an exception on the
// port. We only want to call reset() once, so we use an
// AtomicBoolean to keep track of whether we need to call it.
public void ioOperationFailed()
{
if ( mIsConnected.compareAndSet( true, false )) {
logger.error( "I/O operation failed. Resetting channel." );
reset();
}
}
private class SenderQueue
{
public SenderQueue()
{
setIsAuthorized( false );
mDistQueue = new LinkedBlockingQueue<AmmoGatewayMessage>( 20 );
mAuthQueue = new LinkedList<AmmoGatewayMessage>();
}
// In the new design, aren't we supposed to let the
// NetworkService know if the outgoing queue is full or not?
public ChannelDisposal putFromDistributor( AmmoGatewayMessage iMessage )
{
try
{
logger.info( "putFromDistributor()" );
mDistQueue.put( iMessage );
}
catch ( InterruptedException e )
{
return ChannelDisposal.FAILED;
}
return ChannelDisposal.QUEUED;
}
public synchronized void putFromSecurityObject( AmmoGatewayMessage iMessage )
{
logger.info( "putFromSecurityObject()" );
mAuthQueue.offer( iMessage );
}
public synchronized void finishedPuttingFromSecurityObject()
{
logger.info( "finishedPuttingFromSecurityObject()" );
notifyAll();
}
// This is called when the SecurityObject has successfully
// authorized the channel.
public synchronized void markAsAuthorized()
{
logger.info( "Marking channel as authorized" );
notifyAll();
}
public synchronized boolean messageIsAvailable()
{
return mDistQueue.peek() != null;
}
public synchronized AmmoGatewayMessage take() throws InterruptedException
{
logger.info( "taking from SenderQueue" );
if ( getIsAuthorized() ) {
// This is where the authorized SenderThread blocks.
return mDistQueue.take();
} else {
if ( mAuthQueue.size() > 0 ) {
// return the first item in mAuthqueue and remove
// it from the queue.
return mAuthQueue.remove();
} else {
logger.info( "wait()ing in SenderQueue" );
wait(); // This is where the SenderThread blocks.
if ( getIsAuthorized() ) {
return mDistQueue.take();
} else {
// We are not yet authorized, so return the
// first item in mAuthqueue and remove
// it from the queue.
return mAuthQueue.remove();
}
}
}
}
// Somehow synchronize this here.
public synchronized void reset()
{
logger.info( "reset()ing the SenderQueue" );
// Tell the distributor that we couldn't send these
// packets.
AmmoGatewayMessage msg = mDistQueue.poll();
while ( msg != null )
{
if ( msg.handler != null )
ackToHandler( msg.handler, ChannelDisposal.PENDING );
msg = mDistQueue.poll();
}
setIsAuthorized( false );
}
private BlockingQueue<AmmoGatewayMessage> mDistQueue;
private LinkedList<AmmoGatewayMessage> mAuthQueue;
}
private class SenderThread extends Thread
{
public SenderThread()
{
logger.info( "SenderThread::SenderThread", Thread.currentThread().getId() );
}
@Override
public void run()
{
logger.info( "SenderThread <{}>::run()", Thread.currentThread().getId() );
// Sleep until our slot in the round. If, upon waking, we find that
// we are in the right slot, check to see if a packet is available
// to be sent and, if so, send it. Upon getting a serial port error,
// notify our parent and go into an error state.
while ( mSenderState.get() != INetChannel.INTERRUPTED ) {
AmmoGatewayMessage msg = null;
try {
setSenderState( INetChannel.TAKING );
// Try to sleep until our next take time.
long currentTime = System.currentTimeMillis();
int slotDuration = mSlotDuration.get();
int offset = mSlotNumber.get() * slotDuration;
int cycleDuration = slotDuration * mRadiosInGroup.get();
long thisCycleStartTime = (long) (currentTime / cycleDuration) * cycleDuration;
long thisCycleTakeTime = thisCycleStartTime + offset;
long goalTakeTime;
if ( thisCycleTakeTime > currentTime ) {
// We haven't yet reached our take time for this cycle,
// so that's our goal.
goalTakeTime = thisCycleTakeTime;
} else {
// We've already missed our turn this cycle, so add
// cycleDuration and wait until the next round.
goalTakeTime = thisCycleTakeTime + cycleDuration;
}
Thread.sleep( goalTakeTime - currentTime );
// Once we wake up, we need to see if we are in our slot.
// Sometimes the sleep() will not wake up on time, and we
// have missed our slot. If so, don't do a take() and just
// wait until our next slot.
currentTime = System.currentTimeMillis();
logger.debug( "Woke up: slotNumber={}, (time, mu-s)={}, jitter={}",
new Object[] {
mSlotNumber.get(),
currentTime,
currentTime - goalTakeTime } );
if ( currentTime - goalTakeTime > WINDOW_DURATION ) {
logger.debug( "Missed slot: attempted={}, current={}, jitter={}",
new Object[] {
goalTakeTime,
currentTime,
currentTime - goalTakeTime } );
continue;
}
// At this point, we've woken up near the start of our window
// and should send a message if one is available.
if ( !mSenderQueue.messageIsAvailable() ) {
continue;
}
msg = mSenderQueue.take(); // Will not block
logger.debug( "Took a message from the send queue" );
} catch ( InterruptedException ex ) {
logger.debug( "interrupted taking messages from send queue: {}",
ex.getLocalizedMessage() );
setSenderState( INetChannel.INTERRUPTED );
break;
}
try {
ByteBuffer buf = msg.serialize( endian,
AmmoGatewayMessage.VERSION_1_TERSE,
(byte) mSlotNumber.get() );
setSenderState( INetChannel.SENDING );
if ( mSenderEnabled.get() ) {
FileOutputStream outputStream = mPort.getOutputStream();
outputStream.write( buf.array() );
outputStream.flush();
logger.info( "sent message size={}, checksum={}, data:{}",
new Object[] {
msg.size,
Long.toHexString(msg.payload_checksum),
msg.payload } );
}
// legitimately sent to gateway.
if ( msg.handler != null )
ackToHandler( msg.handler, ChannelDisposal.SENT );
} catch ( Exception e ) {
logger.warn("sender threw exception {}", e.getStackTrace() );
if ( msg.handler != null )
ackToHandler( msg.handler, ChannelDisposal.FAILED );
setSenderState( INetChannel.INTERRUPTED );
ioOperationFailed();
}
}
logger.info( "SenderThread <{}>::run() exiting.", Thread.currentThread().getId() );
}
private void setSenderState( int state )
{
mSenderState.set( state );
statusChange();
}
public int getSenderState() { return mSenderState.get(); }
// If we miss our window's start time by more than this amount, we
// give up until our turn in the next cycle.
private static final int WINDOW_DURATION = 25;
private AtomicInteger mSenderState = new AtomicInteger( INetChannel.TAKING );
private final Logger logger = LoggerFactory.getLogger( "net.serial.sender" );
}
private class ReceiverThread extends Thread
{
public ReceiverThread()
{
logger.info( "ReceiverThread::ReceiverThread()", Thread.currentThread().getId() );
mInputStream = mPort.getInputStream();
}
@Override
public void run()
{
logger.info( "ReceiverThread <{}>::run()", Thread.currentThread().getId() );
// Block on reading from the SerialPort until we get some data.
// If we get an error, notify our parent and go into an error state.
// NOTE: We found that our reads were less reliable when reading more than
// one byte at a time using the standard stream and ByteBuffer patterns.
// Reading one byte at a time in the code below is intentional.
try {
final byte first = (byte) 0xef;
final byte second = (byte) 0xbe;
final byte third = (byte) 0xed;
// See note about length=16 below.
byte[] buf_header = new byte[ 32 ];// AmmoGatewayMessage.HEADER_DATA_LENGTH_TERSE ];
ByteBuffer header = ByteBuffer.wrap( buf_header );
header.order( endian );
int state = 0;
byte c = 0;
AmmoGatewayMessage.Builder agmb = null;
while ( mReceiverState.get() != INetChannel.INTERRUPTED ) {
setReceiverState( INetChannel.START );
switch ( state ) {
case 0:
logger.debug( "Waiting for magic sequence." );
c = readAByte();
if ( c == first )
state = c;
break;
case first:
c = readAByte();
if ( c == second || c == first )
state = c;
else
state = 0;
break;
case second:
c = readAByte();
if ( c == third )
state = 1;
else if ( c == 0xef )
state = c;
else
state = 0;
break;
case 1:
{
long currentTime = System.currentTimeMillis();
int slotDuration = mSlotDuration.get();
int cycleDuration = slotDuration * mRadiosInGroup.get();
long thisCycleStartTime = (long) (currentTime / cycleDuration) * cycleDuration;
long currentSlot = (currentTime - thisCycleStartTime) / slotDuration;
logger.debug( "Read magic sequence in slot {} at {}",
currentSlot,
currentTime );
// Set these in buf_header, since extractHeader() expects them.
buf_header[0] = first;
buf_header[1] = second;
buf_header[2] = third;
// For some unknown reason, this was writing past the end of the
// array when length=16. It may have been ant not recompiling things
// properly. Look into it when I have time.
for ( int i = 0; i < 13; ++i ) {
c = readAByte();
buf_header[i+3] = c;
}
logger.debug( " Received terse header, reading payload " );
agmb = AmmoGatewayMessage.extractHeader( header );
if ( agmb == null ) {
logger.error( "Deserialization failure." );
state = 0;
} else {
state = 2;
}
}
break;
case 2:
{
int payload_size = agmb.size();
byte[] buf_payload = new byte[ payload_size ];
for ( int i = 0; i < payload_size; ++i ) {
c = readAByte();
buf_payload[i] = c;
}
AmmoGatewayMessage agm = agmb.payload( buf_payload ).build();
long currentTime = System.currentTimeMillis();
int slotDuration = mSlotDuration.get();
int cycleDuration = slotDuration * mRadiosInGroup.get();
long thisCycleStartTime = (long) (currentTime / cycleDuration) * cycleDuration;
long currentSlot = (currentTime - thisCycleStartTime) / slotDuration;
logger.debug( "Finished reading payload in slot {} at {}",
currentSlot,
currentTime );
logger.info( "received message size={}, checksum={}, data:{}",
new Object[] {
agm.size,
Long.toHexString(agm.payload_checksum),
agm.payload } );
if ( mReceiverEnabled.get() ) {
setReceiverState( INetChannel.DELIVER );
deliverMessage( agm );
} else {
logger.info( "Receiving disabled, discarding message." );
}
header.clear();
setReceiverState( INetChannel.START );
state = 0;
}
break;
default:
logger.debug( "Unknown value for state variable" );
}
}
} catch ( IOException ex ) {
logger.warn( "receiver threw an IOException {}", ex.getStackTrace() );
setReceiverState( INetChannel.INTERRUPTED );
ioOperationFailed();
} catch ( Exception ex ) {
logger.warn( "receiver threw an exception {}", ex.getStackTrace() );
setReceiverState( INetChannel.INTERRUPTED );
ioOperationFailed();
}
logger.info( "ReceiverThread <{}>::run() exiting.", Thread.currentThread().getId() );
}
private byte readAByte() throws IOException
{
//logger.debug( "Calling read() on the SerialPort's InputStream." );
int val = mInputStream.read();
if ( val == -1 ) {
logger.warn( "The serial port returned -1 from read()." );
throw new IOException();
}
// I was trying to make this interruptable, but it didn't
// work. Why not?
// FileChannel fc = mInputStream.getChannel();
// byte[] buf = new byte[1];
// ByteBuffer bb = ByteBuffer.wrap( buf );
// int bytesRead = 0;
// while ( bytesRead == 0 ) {
// logger.debug( "before read()" );
// try {
// bytesRead = fc.read( bb );
// } catch ( Exception e ) {
// logger.warn( "Caught an exception from the read" );
// logger.debug( "after read()" );
// if ( bytesRead == -1 ) {
// logger.warn( "The serial port returned -1 from read()." );
// throw new IOException();
// int val = buf[0];
//logger.debug( "Read: {}", Integer.toHexString(val) );
return (byte) val;
}
private void setReceiverState( int state )
{
mReceiverState.set( state );
statusChange();
}
public int getReceiverState() { return mReceiverState.get(); }
private AtomicInteger mReceiverState = new AtomicInteger( INetChannel.TAKING ); // FIXME: better states
private FileInputStream mInputStream;
private final Logger logger
= LoggerFactory.getLogger( "net.serial.receiver" );
}
// Called by ReceiverThread to send an incoming message to the
// appropriate destination.
private boolean deliverMessage( AmmoGatewayMessage agm )
{
logger.error( "In deliverMessage()" );
boolean result;
if ( mIsAuthorized.get() ) {
logger.info( " delivering to channel manager" );
result = mChannelManager.deliver( agm );
} else {
logger.info( " delivering to security object" );
result = getSecurityObject().deliverMessage( agm );
}
return result;
}
// Called by the SenderThread.
private boolean ackToHandler( INetworkService.OnSendMessageHandler handler,
ChannelDisposal status )
{
return handler.ack( name, status );
}
private synchronized void setSecurityObject( ISecurityObject iSecurityObject )
{
mSecurityObject = iSecurityObject;
}
private synchronized ISecurityObject getSecurityObject()
{
return mSecurityObject;
}
private void setIsAuthorized( boolean iValue )
{
logger.info( "In setIsAuthorized(). value={}", iValue );
mIsAuthorized.set( iValue );
}
public boolean getIsAuthorized()
{
return mIsAuthorized.get();
}
public void authorizationSucceeded( AmmoGatewayMessage agm )
{
setIsAuthorized( true );
mSenderQueue.markAsAuthorized();
// Tell the NetworkService that we're authorized and have it
// notify the apps.
mChannelManager.authorizationSucceeded( this, agm );
}
public void authorizationFailed()
{
// Disconnect the channel.
reset();
}
private void statusChange()
{
// FIXME: make a better state than PENDING. At this point
// they have *no* state since they don't exist.
int senderState = (mSender != null) ? mSender.getSenderState() : PENDING;
int receiverState = (mReceiver != null) ? mReceiver.getReceiverState() : PENDING;
mChannelManager.statusChange( this,
getState(),
senderState,
receiverState );
}
// I made this public to support the hack to get authentication
// working before Nilabja's code is ready. Make it private again
// once his stuff is in.
public IChannelManager mChannelManager;
private ISecurityObject mSecurityObject;
private static final int WAIT_TIME = 5 * 1000; // 5 s
private ByteOrder endian = ByteOrder.LITTLE_ENDIAN;
private String mDevice;
private int mBaudRate;
private AtomicInteger mSlotNumber = new AtomicInteger();
private AtomicInteger mRadiosInGroup = new AtomicInteger();
private AtomicInteger mSlotDuration = new AtomicInteger();
private AtomicInteger mTransmitDuration = new AtomicInteger();
private AtomicBoolean mSenderEnabled = new AtomicBoolean();
private AtomicBoolean mReceiverEnabled = new AtomicBoolean();
private AtomicInteger mState = new AtomicInteger( SERIAL_DISABLED );
private int getState() { return mState.get(); }
private void setState( int state )
{
// Create a method is NetChannel to convert the numbers to strings.
logger.info( "changing state from {} to {}",
mState,
state );
mState.set( state );
}
private Connector mConnector;
private SerialPort mPort;
private AtomicBoolean mIsConnected = new AtomicBoolean( false );
private AtomicBoolean mIsAuthorized = new AtomicBoolean( false );
private SenderThread mSender;
private ReceiverThread mReceiver;
private SenderQueue mSenderQueue = new SenderQueue();
;
private static final Logger logger = LoggerFactory.getLogger( "net.serial" );
} |
package de.htwg.se.minesweeper.aview.tui;
import de.htwg.se.minesweeper.controller.IController;
import de.htwg.se.minesweeper.model.Cell;
import observer.Event;
import observer.IObserver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static de.htwg.se.minesweeper.controller.IController.State.*;
import static de.htwg.se.minesweeper.controller.IController.State.GAME_WON;
public class TUI implements IObserver {
private static final Logger LOGGER = LogManager.getRootLogger(); //LogManager.getLogger();
private static final String HELP_COMMAND = "h";
private static final String NEW_GAME_COMMAND = "n";
private static final String CHANGE_SETTINGS_COMMAND = "c";
private static final String QUIT_COMMAND = "q";
private String lastUserInput = "";
private IController controller;
public TUI(IController controller) {
this.controller = controller;
controller.addObserver(this);
}
public boolean processInput(String input) {
lastUserInput = input;
List<String> inputParts = Arrays.asList(input.split(","));
switch (inputParts.get(0)) {
case QUIT_COMMAND:
controller.quit();
return false; // quit loop in main program
case NEW_GAME_COMMAND:
newGameAction();
break;
case HELP_COMMAND:
showHelpAction();
break;
case CHANGE_SETTINGS_COMMAND:
runSettingsAction(inputParts);
break;
default:
playRoundAction(inputParts);
break;
}
return true;
}
private void showHelpAction() {
LOGGER.info(controller.getHelpText());
}
private void newGameAction() {
controller.startNewGame();
}
private void playRoundAction(List<String> inputParts) {
controller.setState(INFO_TEXT);
if (inputParts.size() == 2) {
revealCell(inputParts);
} else if (inputParts.size() == 3) {
setFlag(inputParts);
} else {
throw new IllegalArgumentException();
}
}
private void setFlag(List<String> answerAsList) {
try {
int row = Integer.parseInt(answerAsList.get(1));
int col = Integer.parseInt(answerAsList.get(2));
controller.toggleFlag(row, col);
} catch (Exception e) {
controller.setState(ERROR);
LOGGER.error(e);
}
}
private void revealCell(List<String> answerAsList) {
int row = Integer.parseInt(answerAsList.get(0));
int col = Integer.parseInt(answerAsList.get(1));
controller.revealCell(row, col);
}
private void runSettingsAction(List<String> list) {
try {
int numRowsAndColumns = Integer.parseInt(list.get(1));
int numberOfMines = Integer.parseInt(list.get(2));
controller.commitNewSettingsAndRestart(numRowsAndColumns, numberOfMines);
} catch (Exception e) {
LOGGER.error(e);
}
}
@Override
public void update(Event e) {
printTUI();
}
public String getGridAsString() {
StringBuilder result = new StringBuilder();
final List<Cell> allCells = controller.getGrid().getCells();
final int numberOfRows = controller.getGrid().getNumberOfRows();
for (int row = 0; row < numberOfRows; row++) {
final int currentRow = row; // to use it in Lambda expression
final List<Cell> justForDebug = allCells.stream()
.filter(cell -> cell.getPosition().getRow() == currentRow)
.collect(Collectors.toList());
allCells.stream()
.filter(cell -> cell.getPosition().getRow() == currentRow)
.forEach(cell -> result.append(cell.toString()).append(" "));
result.append("\n");
}
return result.toString();
}
public void printTUI() {
final IController.State state = controller.getState();
if (state.equals(ERROR)) {
LOGGER.error("NOT A NUMBER!");
return;
}
LOGGER.info(getGridAsString());
if ("".equals(lastUserInput)) {
LOGGER.info("You typed: " + lastUserInput + "\n");
}
switch (state) {
case GAME_LOST:
LOGGER.info("You Lost!");
break;
case GAME_WON:
LOGGER.info("You Won! " + controller.getElapsedTimeSeconds() + " Points!");
break;
case HELP_TEXT:
LOGGER.info(controller.getHelpText());
break;
case CHANGE_SETTINGS_ACTIVATED:
LOGGER.info("Set number of column/row and mines:");
break;
case CHANGE_SETTINGS_SUCCESS:
LOGGER.info("You set row/column to: " + controller.getGrid().getNumberOfRows() + " and mines to: " + controller.getGrid().getNumberOfMines());
break;
case INFO_TEXT: // or status == 0, running? default?
default:
LOGGER.info("Type:\n\tx,x | x is a number between 0 and 9 (row, column) to reveal field.\n" +
"\tf,x,x | Same as above, but only put / remove a flag at this position.\n" +
"\tOr press " + HELP_COMMAND + " to get more help.");
}
if (state == GAME_LOST || state == GAME_WON) {
LOGGER.info("New Game? Type: n");
}
}
public String printTUIAsString() {
final IController.State state = controller.getState();
if (state.equals(ERROR)) {
return "NOT A NUMBER!";
}
final StringBuilder result = new StringBuilder(getGridAsString());
if ("".equals(lastUserInput)) {
result.append("You typed: " + lastUserInput + "\n");
}
switch (state) {
case GAME_LOST:
result.append("You Lost!");
break;
case GAME_WON:
result.append("You Won! " + controller.getElapsedTimeSeconds() + " Points!");
break;
case HELP_TEXT:
result.append(controller.getHelpText());
break;
case CHANGE_SETTINGS_ACTIVATED:
result.append("Set number of column/row and mines:");
break;
case CHANGE_SETTINGS_SUCCESS:
result.append("You set row/column to: " + controller.getGrid().getNumberOfRows() + " and mines to: " + controller.getGrid().getNumberOfMines());
break;
case INFO_TEXT: // or status == 0, running? default?
default:
result.append("Type:\n\tx,x | x is a number between 0 and 9 (row, column) to reveal field.\n" +
"\tf,x,x | Same as above, but only put / remove a flag at this position.\n" +
"\tOr press " + HELP_COMMAND + " to get more help.");
}
if (state == GAME_LOST || state == GAME_WON) {
result.append("New Game? Type: n");
}
return result.toString();
}
} |
package Examples;
// This file is part of Aspose.Words. The source code in this file
// is only intended as a supplement to the documentation, and is provided
import com.aspose.words.*;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test
public class ExTxtSaveOptions extends ApiExampleBase {
@Test(dataProvider = "pageBreaksDataProvider")
public void pageBreaks(boolean forcePageBreaks) throws Exception {
//ExStart
//ExFor:TxtSaveOptionsBase.ForcePageBreaks
//ExSummary:Shows how to specify whether to preserve page breaks when exporting a document to plaintext.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Page 1");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.writeln("Page 2");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.writeln("Page 3");
// Create a "TxtSaveOptions" object, which we can pass to the document's "Save"
// method to modify how we save the document to plaintext.
TxtSaveOptions saveOptions = new TxtSaveOptions();
// The Aspose.Words "Document" objects have page breaks, just like Microsoft Word documents.
// Save formats such as ".txt" are one continuous body of text without page breaks.
// Set the "ForcePageBreaks" property to "true" to preserve all page breaks in the form of '\f' characters.
// Set the "ForcePageBreaks" property to "false" to discard all page breaks.
saveOptions.setForcePageBreaks(forcePageBreaks);
doc.save(getArtifactsDir() + "TxtSaveOptions.PageBreaks.txt", saveOptions);
// If we load a plaintext document with page breaks,
// the "Document" object will use them to split the body into pages.
doc = new Document(getArtifactsDir() + "TxtSaveOptions.PageBreaks.txt");
Assert.assertEquals(forcePageBreaks ? 3 : 1, doc.getPageCount());
//ExEnd
}
@DataProvider(name = "pageBreaksDataProvider")
public static Object[][] pageBreaksDataProvider() {
return new Object[][]
{
{false},
{true},
};
}
@Test(dataProvider = "exportHeadersFootersDataProvider")
public void exportHeadersFooters(int txtExportHeadersFootersMode) throws Exception {
//ExStart
//ExFor:TxtSaveOptionsBase.ExportHeadersFootersMode
//ExFor:TxtExportHeadersFootersMode
//ExSummary:Shows how to specify how to export headers and footers to plain text format.
Document doc = new Document();
// Insert even and primary headers/footers into the document.
// The primary header/footers will override the even headers/footers.
doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.HEADER_EVEN));
doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_EVEN).appendParagraph("Even header");
doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.FOOTER_EVEN));
doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_EVEN).appendParagraph("Even footer");
doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.HEADER_PRIMARY));
doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY).appendParagraph("Primary header");
doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY));
doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY).appendParagraph("Primary footer");
// Insert pages to display these headers and footers.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Page 1");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.writeln("Page 2");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.write("Page 3");
// Create a "TxtSaveOptions" object, which we can pass to the document's "Save" method
// to modify how we save the document to plaintext.
TxtSaveOptions saveOptions = new TxtSaveOptions();
// Set the "ExportHeadersFootersMode" property to "TxtExportHeadersFootersMode.None"
// to not export any headers/footers.
// Set the "ExportHeadersFootersMode" property to "TxtExportHeadersFootersMode.PrimaryOnly"
// to only export primary headers/footers.
// Set the "ExportHeadersFootersMode" property to "TxtExportHeadersFootersMode.AllAtEnd"
// to place all headers and footers for all section bodies at the end of the document.
saveOptions.setExportHeadersFootersMode(txtExportHeadersFootersMode);
doc.save(getArtifactsDir() + "TxtSaveOptions.ExportHeadersFooters.txt", saveOptions);
String docText = new Document(getArtifactsDir() + "TxtSaveOptions.ExportHeadersFooters.txt").getText().trim();
switch (txtExportHeadersFootersMode) {
case TxtExportHeadersFootersMode.ALL_AT_END:
Assert.assertEquals("Page 1\r" +
"Page 2\r" +
"Page 3\r" +
"Even header\r\r" +
"Primary header\r\r" +
"Even footer\r\r" +
"Primary footer", docText);
break;
case TxtExportHeadersFootersMode.PRIMARY_ONLY:
Assert.assertEquals("Primary header\r" +
"Page 1\r" +
"Page 2\r" +
"Page 3\r" +
"Primary footer", docText);
break;
case TxtExportHeadersFootersMode.NONE:
Assert.assertEquals("Page 1\r" +
"Page 2\r" +
"Page 3", docText);
break;
}
//ExEnd
}
@DataProvider(name = "exportHeadersFootersDataProvider")
public static Object[][] exportHeadersFootersDataProvider() {
return new Object[][]
{
{TxtExportHeadersFootersMode.ALL_AT_END},
{TxtExportHeadersFootersMode.PRIMARY_ONLY},
{TxtExportHeadersFootersMode.NONE},
};
}
@Test(enabled = false)
public void txtListIndentation() throws Exception {
//ExStart
//ExFor:TxtListIndentation
//ExFor:TxtListIndentation.Count
//ExFor:TxtListIndentation.Character
//ExFor:TxtSaveOptions.ListIndentation
//ExSummary:Shows how to configure list indenting when saving a document to plaintext.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Create a list with three levels of indentation.
builder.getListFormat().applyNumberDefault();
builder.writeln("Item 1");
builder.getListFormat().listIndent();
builder.writeln("Item 2");
builder.getListFormat().listIndent();
builder.write("Item 3");
// Create a "TxtSaveOptions" object, which we can pass to the document's "Save" method
// to modify how we save the document to plaintext.
TxtSaveOptions txtSaveOptions = new TxtSaveOptions();
// Set the "Character" property to assign a character to use
// for padding that simulates list indentation in plaintext.
txtSaveOptions.getListIndentation().setCharacter(' ');
// Set the "Count" property to specify the number of times
// to place the padding character for each list indent level.
txtSaveOptions.getListIndentation().setCount(3);
doc.save(getArtifactsDir() + "TxtSaveOptions.TxtListIndentation.txt", txtSaveOptions);
String docText = new Document(getArtifactsDir() + "TxtSaveOptions.TxtListIndentation.txt").getText().trim();
Assert.assertEquals("1. Item 1\r" +
" a. Item 2\r" +
" i. Item 3", docText);
//ExEnd
}
@Test(dataProvider = "simplifyListLabelsDataProvider", enabled = false)
public void simplifyListLabels(boolean simplifyListLabels) throws Exception {
//ExStart
//ExFor:TxtSaveOptions.SimplifyListLabels
//ExSummary:Shows how to change the appearance of lists when saving a document to plaintext.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Create a bulleted list with five levels of indentation.
builder.getListFormat().applyBulletDefault();
builder.writeln("Item 1");
builder.getListFormat().listIndent();
builder.writeln("Item 2");
builder.getListFormat().listIndent();
builder.writeln("Item 3");
builder.getListFormat().listIndent();
builder.writeln("Item 4");
builder.getListFormat().listIndent();
builder.write("Item 5");
// Create a "TxtSaveOptions" object, which we can pass to the document's "Save" method
// to modify how we save the document to plaintext.
TxtSaveOptions txtSaveOptions = new TxtSaveOptions();
// Set the "SimplifyListLabels" property to "true" to convert some list
// symbols into simpler ASCII characters, such as '*', 'o', '+', '>', etc.
// Set the "SimplifyListLabels" property to "false" to preserve as many original list symbols as possible.
txtSaveOptions.setSimplifyListLabels(simplifyListLabels);
doc.save(getArtifactsDir() + "TxtSaveOptions.SimplifyListLabels.txt", txtSaveOptions);
String docText = new Document(getArtifactsDir() + "TxtSaveOptions.SimplifyListLabels.txt").getText().trim();
if (simplifyListLabels)
Assert.assertEquals("* Item 1\r" +
" > Item 2\r" +
" + Item 3\r" +
" - Item 4\r" +
" o Item 5", docText);
else
Assert.assertEquals("· Item 1\r" +
"o Item 2\r" +
"§ Item 3\r" +
"· Item 4\r" +
"o Item 5", docText);
//ExEnd
}
@DataProvider(name = "simplifyListLabelsDataProvider")
public static Object[][] simplifyListLabelsDataProvider() {
return new Object[][]
{
{false},
{true},
};
}
@Test
public void paragraphBreak() throws Exception {
//ExStart
//ExFor:TxtSaveOptions
//ExFor:TxtSaveOptions.SaveFormat
//ExFor:TxtSaveOptionsBase
//ExFor:TxtSaveOptionsBase.ParagraphBreak
//ExSummary:Shows how to save a .txt document with a custom paragraph break.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Paragraph 1.");
builder.writeln("Paragraph 2.");
builder.write("Paragraph 3.");
// Create a "TxtSaveOptions" object, which we can pass to the document's "Save" method
// to modify how we save the document to plaintext.
TxtSaveOptions txtSaveOptions = new TxtSaveOptions();
Assert.assertEquals(SaveFormat.TEXT, txtSaveOptions.getSaveFormat());
// Set the "ParagraphBreak" to a custom value that we wish to put at the end of every paragraph.
txtSaveOptions.setParagraphBreak(" End of paragraph.\r\r\t");
doc.save(getArtifactsDir() + "TxtSaveOptions.ParagraphBreak.txt", txtSaveOptions);
String docText = new Document(getArtifactsDir() + "TxtSaveOptions.ParagraphBreak.txt").getText().trim();
Assert.assertEquals("Paragraph 1. End of paragraph.\r\r\t" +
"Paragraph 2. End of paragraph.\r\r\t" +
"Paragraph 3. End of paragraph.", docText);
//ExEnd
}
@Test(dataProvider = "preserveTableLayoutDataProvider")
public void preserveTableLayout(boolean preserveTableLayout) throws Exception {
//ExStart
//ExFor:TxtSaveOptions.PreserveTableLayout
//ExSummary:Shows how to preserve the layout of tables when converting to plaintext.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.startTable();
builder.insertCell();
builder.write("Row 1, cell 1");
builder.insertCell();
builder.write("Row 1, cell 2");
builder.endRow();
builder.insertCell();
builder.write("Row 2, cell 1");
builder.insertCell();
builder.write("Row 2, cell 2");
builder.endTable();
// Create a "TxtSaveOptions" object, which we can pass to the document's "Save" method
// to modify how we save the document to plaintext.
TxtSaveOptions txtSaveOptions = new TxtSaveOptions();
// Set the "PreserveTableLayout" property to "true" to apply whitespace padding to the contents
// of the output plaintext document to preserve as much of the table's layout as possible.
// Set the "PreserveTableLayout" property to "false" to save all tables' contents
// as a continuous body of text, with just a new line for each row.
txtSaveOptions.setPreserveTableLayout(preserveTableLayout);
doc.save(getArtifactsDir() + "TxtSaveOptions.PreserveTableLayout.txt", txtSaveOptions);
String docText = new Document(getArtifactsDir() + "TxtSaveOptions.PreserveTableLayout.txt").getText().trim();
if (preserveTableLayout)
Assert.assertEquals("Row 1, cell 1 Row 1, cell 2\r" +
"Row 2, cell 1 Row 2, cell 2", docText);
else
Assert.assertEquals("Row 1, cell 1\r" +
"Row 1, cell 2\r" +
"Row 2, cell 1\r" +
"Row 2, cell 2", docText);
//ExEnd
}
@DataProvider(name = "preserveTableLayoutDataProvider")
public static Object[][] preserveTableLayoutDataProvider() {
return new Object[][]
{
{false},
{true},
};
}
} |
package org.jfree.chart;
import java.awt.AWTEvent;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.datatransfer.Clipboard;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.EventListener;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.event.EventListenerList;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.jfree.chart.editor.ChartEditor;
import org.jfree.chart.editor.ChartEditorManager;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.ChartChangeEvent;
import org.jfree.chart.event.ChartChangeListener;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.panel.Overlay;
import org.jfree.chart.event.OverlayChangeEvent;
import org.jfree.chart.event.OverlayChangeListener;
import org.jfree.chart.plot.Pannable;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.Zoomable;
import org.jfree.chart.util.Args;
import org.jfree.chart.util.ResourceBundleWrapper;
import org.jfree.chart.util.SerialUtils;
/**
* A Swing GUI component for displaying a {@link JFreeChart} object.
* <P>
* The panel registers with the chart to receive notification of changes to any
* component of the chart. The chart is redrawn automatically whenever this
* notification is received.
*/
public class ChartPanel extends JPanel implements ChartChangeListener,
ChartProgressListener, ActionListener, MouseListener,
MouseMotionListener, OverlayChangeListener, Printable, Serializable {
/** For serialization. */
protected static final long serialVersionUID = 6046366297214274674L;
/**
* Default setting for buffer usage. The default has been changed to
* {@code true} from version 1.0.13 onwards, because of a severe
* performance problem with drawing the zoom rectangle using XOR (which
* now happens only when the buffer is NOT used).
*/
public static final boolean DEFAULT_BUFFER_USED = true;
/** The default panel width. */
public static final int DEFAULT_WIDTH = 1024;
/** The default panel height. */
public static final int DEFAULT_HEIGHT = 768;
/** The default limit below which chart scaling kicks in. */
public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300;
/** The default limit below which chart scaling kicks in. */
public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200;
/** The default limit above which chart scaling kicks in. */
public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 1024;
/** The default limit above which chart scaling kicks in. */
public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 768;
/** The minimum size required to perform a zoom on a rectangle */
public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10;
/** Properties action command. */
public static final String PROPERTIES_COMMAND = "PROPERTIES";
/**
* Copy action command.
*
* @since 1.0.13
*/
public static final String COPY_COMMAND = "COPY";
/** Save action command. */
public static final String SAVE_COMMAND = "SAVE";
/** Action command to save as PNG. */
protected static final String SAVE_AS_PNG_COMMAND = "SAVE_AS_PNG";
/** Action command to save as PNG - use screen size */
protected static final String SAVE_AS_PNG_SIZE_COMMAND = "SAVE_AS_PNG_SIZE";
/** Action command to save as SVG. */
protected static final String SAVE_AS_SVG_COMMAND = "SAVE_AS_SVG";
/** Action command to save as PDF. */
protected static final String SAVE_AS_PDF_COMMAND = "SAVE_AS_PDF";
/** Print action command. */
public static final String PRINT_COMMAND = "PRINT";
/** Zoom in (both axes) action command. */
public static final String ZOOM_IN_BOTH_COMMAND = "ZOOM_IN_BOTH";
/** Zoom in (domain axis only) action command. */
public static final String ZOOM_IN_DOMAIN_COMMAND = "ZOOM_IN_DOMAIN";
/** Zoom in (range axis only) action command. */
public static final String ZOOM_IN_RANGE_COMMAND = "ZOOM_IN_RANGE";
/** Zoom out (both axes) action command. */
public static final String ZOOM_OUT_BOTH_COMMAND = "ZOOM_OUT_BOTH";
/** Zoom out (domain axis only) action command. */
public static final String ZOOM_OUT_DOMAIN_COMMAND = "ZOOM_DOMAIN_BOTH";
/** Zoom out (range axis only) action command. */
public static final String ZOOM_OUT_RANGE_COMMAND = "ZOOM_RANGE_BOTH";
/** Zoom reset (both axes) action command. */
public static final String ZOOM_RESET_BOTH_COMMAND = "ZOOM_RESET_BOTH";
/** Zoom reset (domain axis only) action command. */
public static final String ZOOM_RESET_DOMAIN_COMMAND = "ZOOM_RESET_DOMAIN";
/** Zoom reset (range axis only) action command. */
public static final String ZOOM_RESET_RANGE_COMMAND = "ZOOM_RESET_RANGE";
/** The chart that is displayed in the panel. */
protected JFreeChart chart;
/** Storage for registered (chart) mouse listeners. */
protected transient EventListenerList chartMouseListeners;
/** A flag that controls whether or not the off-screen buffer is used. */
protected boolean useBuffer;
/** A flag that indicates that the buffer should be refreshed. */
protected boolean refreshBuffer;
/** A buffer for the rendered chart. */
protected transient Image chartBuffer;
/** The height of the chart buffer. */
protected int chartBufferHeight;
/** The width of the chart buffer. */
protected int chartBufferWidth;
/**
* The minimum width for drawing a chart (uses scaling for smaller widths).
*/
protected int minimumDrawWidth;
/**
* The minimum height for drawing a chart (uses scaling for smaller
* heights).
*/
protected int minimumDrawHeight;
/**
* The maximum width for drawing a chart (uses scaling for bigger
* widths).
*/
protected int maximumDrawWidth;
/**
* The maximum height for drawing a chart (uses scaling for bigger
* heights).
*/
protected int maximumDrawHeight;
/** The popup menu for the frame. */
protected JPopupMenu popup;
/** The drawing info collected the last time the chart was drawn. */
protected ChartRenderingInfo info;
/** The chart anchor point. */
protected Point2D anchor;
/** The scale factor used to draw the chart. */
protected double scaleX;
/** The scale factor used to draw the chart. */
protected double scaleY;
/** The plot orientation. */
protected PlotOrientation orientation = PlotOrientation.VERTICAL;
/** A flag that controls whether or not domain zooming is enabled. */
protected boolean domainZoomable = false;
/** A flag that controls whether or not range zooming is enabled. */
protected boolean rangeZoomable = false;
/**
* The zoom rectangle starting point (selected by the user with a mouse
* click). This is a point on the screen, not the chart (which may have
* been scaled up or down to fit the panel).
*/
protected Point2D zoomPoint = null;
/** The zoom rectangle (selected by the user with the mouse). */
protected transient Rectangle2D zoomRectangle = null;
/** Controls if the zoom rectangle is drawn as an outline or filled. */
protected boolean fillZoomRectangle = true;
/** The minimum distance required to drag the mouse to trigger a zoom. */
protected int zoomTriggerDistance;
/** Menu item for zooming in on a chart (both axes). */
protected JMenuItem zoomInBothMenuItem;
/** Menu item for zooming in on a chart (domain axis). */
protected JMenuItem zoomInDomainMenuItem;
/** Menu item for zooming in on a chart (range axis). */
protected JMenuItem zoomInRangeMenuItem;
/** Menu item for zooming out on a chart. */
protected JMenuItem zoomOutBothMenuItem;
/** Menu item for zooming out on a chart (domain axis). */
protected JMenuItem zoomOutDomainMenuItem;
/** Menu item for zooming out on a chart (range axis). */
protected JMenuItem zoomOutRangeMenuItem;
/** Menu item for resetting the zoom (both axes). */
protected JMenuItem zoomResetBothMenuItem;
/** Menu item for resetting the zoom (domain axis only). */
protected JMenuItem zoomResetDomainMenuItem;
/** Menu item for resetting the zoom (range axis only). */
protected JMenuItem zoomResetRangeMenuItem;
/**
* The default directory for saving charts to file.
*
* @since 1.0.7
*/
protected File defaultDirectoryForSaveAs;
/** A flag that controls whether or not file extensions are enforced. */
protected boolean enforceFileExtensions;
/** A flag that indicates if original tooltip delays are changed. */
protected boolean ownToolTipDelaysActive;
/** Original initial tooltip delay of ToolTipManager.sharedInstance(). */
protected int originalToolTipInitialDelay;
/** Original reshow tooltip delay of ToolTipManager.sharedInstance(). */
protected int originalToolTipReshowDelay;
/** Original dismiss tooltip delay of ToolTipManager.sharedInstance(). */
protected int originalToolTipDismissDelay;
/** Own initial tooltip delay to be used in this chart panel. */
protected int ownToolTipInitialDelay;
/** Own reshow tooltip delay to be used in this chart panel. */
protected int ownToolTipReshowDelay;
/** Own dismiss tooltip delay to be used in this chart panel. */
protected int ownToolTipDismissDelay;
/** The factor used to zoom in on an axis range. */
protected double zoomInFactor = 0.5;
/** The factor used to zoom out on an axis range. */
protected double zoomOutFactor = 2.0;
/**
* A flag that controls whether zoom operations are centred on the
* current anchor point, or the centre point of the relevant axis.
*
* @since 1.0.7
*/
protected boolean zoomAroundAnchor;
/**
* The paint used to draw the zoom rectangle outline.
*
* @since 1.0.13
*/
protected transient Paint zoomOutlinePaint;
/**
* The zoom fill paint (should use transparency).
*
* @since 1.0.13
*/
protected transient Paint zoomFillPaint;
/** The resourceBundle for the localization. */
protected static ResourceBundle localizationResources
= ResourceBundleWrapper.getBundle(
"org.jfree.chart.LocalizationBundle");
/**
* Temporary storage for the width and height of the chart
* drawing area during panning.
*/
protected double panW, panH;
/** The last mouse position during panning. */
protected Point panLast;
/**
* The mask for mouse events to trigger panning.
*
* @since 1.0.13
*/
protected int panMask = InputEvent.CTRL_MASK;
/**
* A list of overlays for the panel.
*
* @since 1.0.13
*/
protected List<Overlay> overlays;
/**
* Constructs a panel that displays the specified chart.
*
* @param chart the chart.
*/
public ChartPanel(JFreeChart chart) {
this(chart, DEFAULT_WIDTH, DEFAULT_HEIGHT,
DEFAULT_MINIMUM_DRAW_WIDTH, DEFAULT_MINIMUM_DRAW_HEIGHT,
DEFAULT_MAXIMUM_DRAW_WIDTH, DEFAULT_MAXIMUM_DRAW_HEIGHT,
DEFAULT_BUFFER_USED,
true, // properties
true, // save
true, // print
true, // zoom
true // tooltips
);
}
/**
* Constructs a panel containing a chart. The {@code useBuffer} flag
* controls whether or not an offscreen {@code BufferedImage} is
* maintained for the chart. If the buffer is used, more memory is
* consumed, but panel repaints will be a lot quicker in cases where the
* chart itself hasn't changed (for example, when another frame is moved
* to reveal the panel). WARNING: If you set the {@code useBuffer}
* flag to false, note that the mouse zooming rectangle will (in that case)
* be drawn using XOR, and there is a SEVERE performance problem with that
* on JRE6 on Windows.
*
* @param chart the chart.
* @param useBuffer a flag controlling whether or not an off-screen buffer
* is used (read the warning above before setting this
* to {@code false}).
*/
public ChartPanel(JFreeChart chart, boolean useBuffer) {
this(chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH,
DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH,
DEFAULT_MAXIMUM_DRAW_HEIGHT, useBuffer,
true, // properties
true, // save
true, // print
true, // zoom
true // tooltips
);
}
/**
* Constructs a JFreeChart panel.
*
* @param chart the chart.
* @param properties a flag indicating whether or not the chart property
* editor should be available via the popup menu.
* @param save a flag indicating whether or not save options should be
* available via the popup menu.
* @param print a flag indicating whether or not the print option
* should be available via the popup menu.
* @param zoom a flag indicating whether or not zoom options should
* be added to the popup menu.
* @param tooltips a flag indicating whether or not tooltips should be
* enabled for the chart.
*/
public ChartPanel(JFreeChart chart, boolean properties, boolean save,
boolean print, boolean zoom, boolean tooltips) {
this(chart, DEFAULT_WIDTH, DEFAULT_HEIGHT,
DEFAULT_MINIMUM_DRAW_WIDTH, DEFAULT_MINIMUM_DRAW_HEIGHT,
DEFAULT_MAXIMUM_DRAW_WIDTH, DEFAULT_MAXIMUM_DRAW_HEIGHT,
DEFAULT_BUFFER_USED, properties, save, print, zoom, tooltips);
}
/**
* Constructs a JFreeChart panel.
*
* @param chart the chart.
* @param width the preferred width of the panel.
* @param height the preferred height of the panel.
* @param minimumDrawWidth the minimum drawing width.
* @param minimumDrawHeight the minimum drawing height.
* @param maximumDrawWidth the maximum drawing width.
* @param maximumDrawHeight the maximum drawing height.
* @param useBuffer a flag that indicates whether to use the off-screen
* buffer to improve performance (at the expense of
* memory).
* @param properties a flag indicating whether or not the chart property
* editor should be available via the popup menu.
* @param save a flag indicating whether or not save options should be
* available via the popup menu.
* @param print a flag indicating whether or not the print option
* should be available via the popup menu.
* @param zoom a flag indicating whether or not zoom options should be
* added to the popup menu.
* @param tooltips a flag indicating whether or not tooltips should be
* enabled for the chart.
*/
public ChartPanel(JFreeChart chart, int width, int height,
int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth,
int maximumDrawHeight, boolean useBuffer, boolean properties,
boolean save, boolean print, boolean zoom, boolean tooltips) {
this(chart, width, height, minimumDrawWidth, minimumDrawHeight,
maximumDrawWidth, maximumDrawHeight, useBuffer, properties,
true, save, print, zoom, tooltips);
}
/**
* Constructs a JFreeChart panel.
*
* @param chart the chart.
* @param width the preferred width of the panel.
* @param height the preferred height of the panel.
* @param minimumDrawWidth the minimum drawing width.
* @param minimumDrawHeight the minimum drawing height.
* @param maximumDrawWidth the maximum drawing width.
* @param maximumDrawHeight the maximum drawing height.
* @param useBuffer a flag that indicates whether to use the off-screen
* buffer to improve performance (at the expense of
* memory).
* @param properties a flag indicating whether or not the chart property
* editor should be available via the popup menu.
* @param copy a flag indicating whether or not a copy option should be
* available via the popup menu.
* @param save a flag indicating whether or not save options should be
* available via the popup menu.
* @param print a flag indicating whether or not the print option
* should be available via the popup menu.
* @param zoom a flag indicating whether or not zoom options should be
* added to the popup menu.
* @param tooltips a flag indicating whether or not tooltips should be
* enabled for the chart.
*
* @since 1.0.13
*/
public ChartPanel(JFreeChart chart, int width, int height,
int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth,
int maximumDrawHeight, boolean useBuffer, boolean properties,
boolean copy, boolean save, boolean print, boolean zoom,
boolean tooltips) {
setChart(chart);
this.chartMouseListeners = new EventListenerList();
this.info = new ChartRenderingInfo();
setPreferredSize(new Dimension(width, height));
this.useBuffer = useBuffer;
this.refreshBuffer = false;
this.minimumDrawWidth = minimumDrawWidth;
this.minimumDrawHeight = minimumDrawHeight;
this.maximumDrawWidth = maximumDrawWidth;
this.maximumDrawHeight = maximumDrawHeight;
this.zoomTriggerDistance = DEFAULT_ZOOM_TRIGGER_DISTANCE;
// set up popup menu...
this.popup = null;
if (properties || copy || save || print || zoom) {
this.popup = createPopupMenu(properties, copy, save, print, zoom);
}
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
setDisplayToolTips(tooltips);
addMouseListener(this);
addMouseMotionListener(this);
this.defaultDirectoryForSaveAs = null;
this.enforceFileExtensions = true;
// initialize ChartPanel-specific tool tip delays with
// values the from ToolTipManager.sharedInstance()
ToolTipManager ttm = ToolTipManager.sharedInstance();
this.ownToolTipInitialDelay = ttm.getInitialDelay();
this.ownToolTipDismissDelay = ttm.getDismissDelay();
this.ownToolTipReshowDelay = ttm.getReshowDelay();
this.zoomAroundAnchor = false;
this.zoomOutlinePaint = Color.BLUE;
this.zoomFillPaint = new Color(0, 0, 255, 63);
this.panMask = InputEvent.CTRL_MASK;
// for MacOSX we can't use the CTRL key for mouse drags, see:
String osName = System.getProperty("os.name").toLowerCase();
if (osName.startsWith("mac os x")) {
this.panMask = InputEvent.ALT_MASK;
}
this.overlays = new java.util.ArrayList<Overlay>();
}
/**
* Returns the chart contained in the panel.
*
* @return The chart (possibly {@code null}).
*/
public JFreeChart getChart() {
return this.chart;
}
/**
* Sets the chart that is displayed in the panel.
*
* @param chart the chart ({@code null} permitted).
*/
public void setChart(JFreeChart chart) {
// stop listening for changes to the existing chart
if (this.chart != null) {
this.chart.removeChangeListener(this);
this.chart.removeProgressListener(this);
}
// add the new chart
this.chart = chart;
if (chart != null) {
this.chart.addChangeListener(this);
this.chart.addProgressListener(this);
Plot plot = chart.getPlot();
this.domainZoomable = false;
this.rangeZoomable = false;
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.domainZoomable = z.isDomainZoomable();
this.rangeZoomable = z.isRangeZoomable();
this.orientation = z.getOrientation();
}
}
else {
this.domainZoomable = false;
this.rangeZoomable = false;
}
if (this.useBuffer) {
this.refreshBuffer = true;
}
repaint();
}
/**
* Returns the minimum drawing width for charts.
* <P>
* If the width available on the panel is less than this, then the chart is
* drawn at the minimum width then scaled down to fit.
*
* @return The minimum drawing width.
*/
public int getMinimumDrawWidth() {
return this.minimumDrawWidth;
}
/**
* Sets the minimum drawing width for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available width is
* less than this amount, the chart will be drawn using the minimum width
* then scaled down to fit the available space.
*
* @param width The width.
*/
public void setMinimumDrawWidth(int width) {
this.minimumDrawWidth = width;
}
/**
* Returns the maximum drawing width for charts.
* <P>
* If the width available on the panel is greater than this, then the chart
* is drawn at the maximum width then scaled up to fit.
*
* @return The maximum drawing width.
*/
public int getMaximumDrawWidth() {
return this.maximumDrawWidth;
}
/**
* Sets the maximum drawing width for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available width is
* greater than this amount, the chart will be drawn using the maximum
* width then scaled up to fit the available space.
*
* @param width The width.
*/
public void setMaximumDrawWidth(int width) {
this.maximumDrawWidth = width;
}
/**
* Returns the minimum drawing height for charts.
* <P>
* If the height available on the panel is less than this, then the chart
* is drawn at the minimum height then scaled down to fit.
*
* @return The minimum drawing height.
*/
public int getMinimumDrawHeight() {
return this.minimumDrawHeight;
}
/**
* Sets the minimum drawing height for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available height is
* less than this amount, the chart will be drawn using the minimum height
* then scaled down to fit the available space.
*
* @param height The height.
*/
public void setMinimumDrawHeight(int height) {
this.minimumDrawHeight = height;
}
/**
* Returns the maximum drawing height for charts.
* <P>
* If the height available on the panel is greater than this, then the
* chart is drawn at the maximum height then scaled up to fit.
*
* @return The maximum drawing height.
*/
public int getMaximumDrawHeight() {
return this.maximumDrawHeight;
}
/**
* Sets the maximum drawing height for the chart on this panel.
* <P>
* At the time the chart is drawn on the panel, if the available height is
* greater than this amount, the chart will be drawn using the maximum
* height then scaled up to fit the available space.
*
* @param height The height.
*/
public void setMaximumDrawHeight(int height) {
this.maximumDrawHeight = height;
}
/**
* Returns the X scale factor for the chart. This will be 1.0 if no
* scaling has been used.
*
* @return The scale factor.
*/
public double getScaleX() {
return this.scaleX;
}
/**
* Returns the Y scale factory for the chart. This will be 1.0 if no
* scaling has been used.
*
* @return The scale factor.
*/
public double getScaleY() {
return this.scaleY;
}
/**
* Returns the anchor point.
*
* @return The anchor point (possibly {@code null}).
*/
public Point2D getAnchor() {
return this.anchor;
}
/**
* Sets the anchor point. This method is provided for the use of
* subclasses, not end users.
*
* @param anchor the anchor point ({@code null} permitted).
*/
protected void setAnchor(Point2D anchor) {
this.anchor = anchor;
}
/**
* Returns the popup menu.
*
* @return The popup menu.
*/
public JPopupMenu getPopupMenu() {
return this.popup;
}
/**
* Sets the popup menu for the panel.
*
* @param popup the popup menu ({@code null} permitted).
*/
public void setPopupMenu(JPopupMenu popup) {
this.popup = popup;
}
/**
* Returns the chart rendering info from the most recent chart redraw.
*
* @return The chart rendering info.
*/
public ChartRenderingInfo getChartRenderingInfo() {
return this.info;
}
/**
* A convenience method that switches on mouse-based zooming.
*
* @param flag {@code true} enables zooming and rectangle fill on
* zoom.
*/
public void setMouseZoomable(boolean flag) {
setMouseZoomable(flag, true);
}
/**
* A convenience method that switches on mouse-based zooming.
*
* @param flag {@code true} if zooming enabled
* @param fillRectangle {@code true} if zoom rectangle is filled,
* false if rectangle is shown as outline only.
*/
public void setMouseZoomable(boolean flag, boolean fillRectangle) {
setDomainZoomable(flag);
setRangeZoomable(flag);
setFillZoomRectangle(fillRectangle);
}
/**
* Returns the flag that determines whether or not zooming is enabled for
* the domain axis.
*
* @return A boolean.
*/
public boolean isDomainZoomable() {
return this.domainZoomable;
}
/**
* Sets the flag that controls whether or not zooming is enabled for the
* domain axis. A check is made to ensure that the current plot supports
* zooming for the domain values.
*
* @param flag {@code true} enables zooming if possible.
*/
public void setDomainZoomable(boolean flag) {
if (flag) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.domainZoomable = flag && (z.isDomainZoomable());
}
}
else {
this.domainZoomable = false;
}
}
/**
* Returns the flag that determines whether or not zooming is enabled for
* the range axis.
*
* @return A boolean.
*/
public boolean isRangeZoomable() {
return this.rangeZoomable;
}
/**
* A flag that controls mouse-based zooming on the vertical axis.
*
* @param flag {@code true} enables zooming.
*/
public void setRangeZoomable(boolean flag) {
if (flag) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.rangeZoomable = flag && (z.isRangeZoomable());
}
}
else {
this.rangeZoomable = false;
}
}
/**
* Returns the flag that controls whether or not the zoom rectangle is
* filled when drawn.
*
* @return A boolean.
*/
public boolean getFillZoomRectangle() {
return this.fillZoomRectangle;
}
/**
* A flag that controls how the zoom rectangle is drawn.
*
* @param flag {@code true} instructs to fill the rectangle on
* zoom, otherwise it will be outlined.
*/
public void setFillZoomRectangle(boolean flag) {
this.fillZoomRectangle = flag;
}
/**
* Returns the zoom trigger distance. This controls how far the mouse must
* move before a zoom action is triggered.
*
* @return The distance (in Java2D units).
*/
public int getZoomTriggerDistance() {
return this.zoomTriggerDistance;
}
/**
* Sets the zoom trigger distance. This controls how far the mouse must
* move before a zoom action is triggered.
*
* @param distance the distance (in Java2D units).
*/
public void setZoomTriggerDistance(int distance) {
this.zoomTriggerDistance = distance;
}
/**
* Returns the default directory for the "save as" option.
*
* @return The default directory (possibly {@code null}).
*
* @since 1.0.7
*/
public File getDefaultDirectoryForSaveAs() {
return this.defaultDirectoryForSaveAs;
}
/**
* Sets the default directory for the "save as" option. If you set this
* to {@code null}, the user's default directory will be used.
*
* @param directory the directory ({@code null} permitted).
*
* @since 1.0.7
*/
public void setDefaultDirectoryForSaveAs(File directory) {
if (directory != null) {
if (!directory.isDirectory()) {
throw new IllegalArgumentException(
"The 'directory' argument is not a directory.");
}
}
this.defaultDirectoryForSaveAs = directory;
}
/**
* Returns {@code true} if file extensions should be enforced, and
* {@code false} otherwise.
*
* @return The flag.
*
* @see #setEnforceFileExtensions(boolean)
*/
public boolean isEnforceFileExtensions() {
return this.enforceFileExtensions;
}
/**
* Sets a flag that controls whether or not file extensions are enforced.
*
* @param enforce the new flag value.
*
* @see #isEnforceFileExtensions()
*/
public void setEnforceFileExtensions(boolean enforce) {
this.enforceFileExtensions = enforce;
}
/**
* Returns the flag that controls whether or not zoom operations are
* centered around the current anchor point.
*
* @return A boolean.
*
* @since 1.0.7
*
* @see #setZoomAroundAnchor(boolean)
*/
public boolean getZoomAroundAnchor() {
return this.zoomAroundAnchor;
}
/**
* Sets the flag that controls whether or not zoom operations are
* centered around the current anchor point.
*
* @param zoomAroundAnchor the new flag value.
*
* @since 1.0.7
*
* @see #getZoomAroundAnchor()
*/
public void setZoomAroundAnchor(boolean zoomAroundAnchor) {
this.zoomAroundAnchor = zoomAroundAnchor;
}
/**
* Returns the zoom rectangle fill paint.
*
* @return The zoom rectangle fill paint (never {@code null}).
*
* @see #setZoomFillPaint(java.awt.Paint)
* @see #setFillZoomRectangle(boolean)
*
* @since 1.0.13
*/
public Paint getZoomFillPaint() {
return this.zoomFillPaint;
}
/**
* Sets the zoom rectangle fill paint.
*
* @param paint the paint ({@code null} not permitted).
*
* @see #getZoomFillPaint()
* @see #getFillZoomRectangle()
*
* @since 1.0.13
*/
public void setZoomFillPaint(Paint paint) {
Args.nullNotPermitted(paint, "paint");
this.zoomFillPaint = paint;
}
/**
* Returns the zoom rectangle outline paint.
*
* @return The zoom rectangle outline paint (never {@code null}).
*
* @see #setZoomOutlinePaint(java.awt.Paint)
* @see #setFillZoomRectangle(boolean)
*
* @since 1.0.13
*/
public Paint getZoomOutlinePaint() {
return this.zoomOutlinePaint;
}
/**
* Sets the zoom rectangle outline paint.
*
* @param paint the paint ({@code null} not permitted).
*
* @see #getZoomOutlinePaint()
* @see #getFillZoomRectangle()
*
* @since 1.0.13
*/
public void setZoomOutlinePaint(Paint paint) {
this.zoomOutlinePaint = paint;
}
/**
* The mouse wheel handler.
*/
protected MouseWheelHandler mouseWheelHandler;
/**
* Returns {@code true} if the mouse wheel handler is enabled, and
* {@code false} otherwise.
*
* @return A boolean.
*
* @since 1.0.13
*/
public boolean isMouseWheelEnabled() {
return this.mouseWheelHandler != null;
}
/**
* Enables or disables mouse wheel support for the panel.
*
* @param flag a boolean.
*
* @since 1.0.13
*/
public void setMouseWheelEnabled(boolean flag) {
if (flag && this.mouseWheelHandler == null) {
this.mouseWheelHandler = new MouseWheelHandler(this);
}
else if (!flag && this.mouseWheelHandler != null) {
this.removeMouseWheelListener(this.mouseWheelHandler);
this.mouseWheelHandler = null;
}
}
/**
* Add an overlay to the panel.
*
* @param overlay the overlay ({@code null} not permitted).
*
* @since 1.0.13
*/
public void addOverlay(Overlay overlay) {
Args.nullNotPermitted(overlay, "overlay");
this.overlays.add(overlay);
overlay.addChangeListener(this);
repaint();
}
/**
* Removes an overlay from the panel.
*
* @param overlay the overlay to remove ({@code null} not permitted).
*
* @since 1.0.13
*/
public void removeOverlay(Overlay overlay) {
Args.nullNotPermitted(overlay, "overlay");
boolean removed = this.overlays.remove(overlay);
if (removed) {
overlay.removeChangeListener(this);
repaint();
}
}
/**
* Handles a change to an overlay by repainting the panel.
*
* @param event the event.
*
* @since 1.0.13
*/
@Override
public void overlayChanged(OverlayChangeEvent event) {
repaint();
}
/**
* Switches the display of tooltips for the panel on or off. Note that
* tooltips can only be displayed if the chart has been configured to
* generate tooltip items.
*
* @param flag {@code true} to enable tooltips, {@code false} to
* disable tooltips.
*/
public void setDisplayToolTips(boolean flag) {
if (flag) {
ToolTipManager.sharedInstance().registerComponent(this);
}
else {
ToolTipManager.sharedInstance().unregisterComponent(this);
}
}
/**
* Returns a string for the tooltip.
*
* @param e the mouse event.
*
* @return A tool tip or {@code null} if no tooltip is available.
*/
@Override
public String getToolTipText(MouseEvent e) {
String result = null;
if (this.info != null) {
EntityCollection entities = this.info.getEntityCollection();
if (entities != null) {
Insets insets = getInsets();
ChartEntity entity = entities.getEntity(
(int) ((e.getX() - insets.left) / this.scaleX),
(int) ((e.getY() - insets.top) / this.scaleY));
if (entity != null) {
result = entity.getToolTipText();
}
}
}
return result;
}
/**
* Translates a Java2D point on the chart to a screen location.
*
* @param java2DPoint the Java2D point.
*
* @return The screen location.
*/
public Point translateJava2DToScreen(Point2D java2DPoint) {
Insets insets = getInsets();
int x = (int) (java2DPoint.getX() * this.scaleX + insets.left);
int y = (int) (java2DPoint.getY() * this.scaleY + insets.top);
return new Point(x, y);
}
/**
* Translates a panel (component) location to a Java2D point.
*
* @param screenPoint the screen location ({@code null} not
* permitted).
*
* @return The Java2D coordinates.
*/
public Point2D translateScreenToJava2D(Point screenPoint) {
Insets insets = getInsets();
double x = (screenPoint.getX() - insets.left) / this.scaleX;
double y = (screenPoint.getY() - insets.top) / this.scaleY;
return new Point2D.Double(x, y);
}
/**
* Applies any scaling that is in effect for the chart drawing to the
* given rectangle.
*
* @param rect the rectangle ({@code null} not permitted).
*
* @return A new scaled rectangle.
*/
public Rectangle2D scale(Rectangle2D rect) {
Insets insets = getInsets();
double x = rect.getX() * getScaleX() + insets.left;
double y = rect.getY() * getScaleY() + insets.top;
double w = rect.getWidth() * getScaleX();
double h = rect.getHeight() * getScaleY();
return new Rectangle2D.Double(x, y, w, h);
}
/**
* Returns the chart entity at a given point.
* <P>
* This method will return null if there is (a) no entity at the given
* point, or (b) no entity collection has been generated.
*
* @param viewX the x-coordinate.
* @param viewY the y-coordinate.
*
* @return The chart entity (possibly {@code null}).
*/
public ChartEntity getEntityForPoint(int viewX, int viewY) {
ChartEntity result = null;
if (this.info != null) {
Insets insets = getInsets();
double x = (viewX - insets.left) / this.scaleX;
double y = (viewY - insets.top) / this.scaleY;
EntityCollection entities = this.info.getEntityCollection();
result = entities != null ? entities.getEntity(x, y) : null;
}
return result;
}
/**
* Returns the flag that controls whether or not the offscreen buffer
* needs to be refreshed.
*
* @return A boolean.
*/
public boolean getRefreshBuffer() {
return this.refreshBuffer;
}
/**
* Sets the refresh buffer flag. This flag is used to avoid unnecessary
* redrawing of the chart when the offscreen image buffer is used.
*
* @param flag {@code true} indicates that the buffer should be
* refreshed.
*/
public void setRefreshBuffer(boolean flag) {
this.refreshBuffer = flag;
}
/**
* Paints the component by drawing the chart to fill the entire component,
* but allowing for the insets (which will be non-zero if a border has been
* set for this component). To increase performance (at the expense of
* memory), an off-screen buffer image can be used.
*
* @param g the graphics device for drawing on.
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.chart == null) {
return;
}
Graphics2D g2 = (Graphics2D) g.create();
// first determine the size of the chart rendering area...
Dimension size = getSize();
Insets insets = getInsets();
Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top,
size.getWidth() - insets.left - insets.right,
size.getHeight() - insets.top - insets.bottom);
// work out if scaling is required...
boolean scale = false;
double drawWidth = available.getWidth();
double drawHeight = available.getHeight();
this.scaleX = 1.0;
this.scaleY = 1.0;
if (drawWidth < this.minimumDrawWidth) {
this.scaleX = drawWidth / this.minimumDrawWidth;
drawWidth = this.minimumDrawWidth;
scale = true;
}
else if (drawWidth > this.maximumDrawWidth) {
this.scaleX = drawWidth / this.maximumDrawWidth;
drawWidth = this.maximumDrawWidth;
scale = true;
}
if (drawHeight < this.minimumDrawHeight) {
this.scaleY = drawHeight / this.minimumDrawHeight;
drawHeight = this.minimumDrawHeight;
scale = true;
}
else if (drawHeight > this.maximumDrawHeight) {
this.scaleY = drawHeight / this.maximumDrawHeight;
drawHeight = this.maximumDrawHeight;
scale = true;
}
Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth,
drawHeight);
// are we using the chart buffer?
if (this.useBuffer) {
// do we need to resize the buffer?
if ((this.chartBuffer == null)
|| (this.chartBufferWidth != available.getWidth())
|| (this.chartBufferHeight != available.getHeight())) {
this.chartBufferWidth = (int) available.getWidth();
this.chartBufferHeight = (int) available.getHeight();
GraphicsConfiguration gc = g2.getDeviceConfiguration();
this.chartBuffer = gc.createCompatibleImage(
this.chartBufferWidth, this.chartBufferHeight,
Transparency.TRANSLUCENT);
this.refreshBuffer = true;
}
// do we need to redraw the buffer?
if (this.refreshBuffer) {
this.refreshBuffer = false; // clear the flag
Rectangle2D bufferArea = new Rectangle2D.Double(
0, 0, this.chartBufferWidth, this.chartBufferHeight);
// make the background of the buffer clear and transparent
Graphics2D bufferG2 = (Graphics2D)
this.chartBuffer.getGraphics();
Composite savedComposite = bufferG2.getComposite();
bufferG2.setComposite(AlphaComposite.getInstance(
AlphaComposite.CLEAR, 0.0f));
Rectangle r = new Rectangle(0, 0, this.chartBufferWidth,
this.chartBufferHeight);
bufferG2.fill(r);
bufferG2.setComposite(savedComposite);
if (scale) {
AffineTransform saved = bufferG2.getTransform();
AffineTransform st = AffineTransform.getScaleInstance(
this.scaleX, this.scaleY);
bufferG2.transform(st);
this.chart.draw(bufferG2, chartArea, this.anchor,
this.info);
bufferG2.setTransform(saved);
} else {
this.chart.draw(bufferG2, bufferArea, this.anchor,
this.info);
}
bufferG2.dispose();
}
// zap the buffer onto the panel...
g2.drawImage(this.chartBuffer, insets.left, insets.top, this);
} else { // redrawing the chart every time...
AffineTransform saved = g2.getTransform();
g2.translate(insets.left, insets.top);
if (scale) {
AffineTransform st = AffineTransform.getScaleInstance(
this.scaleX, this.scaleY);
g2.transform(st);
}
this.chart.draw(g2, chartArea, this.anchor, this.info);
g2.setTransform(saved);
}
for (Overlay overlay : this.overlays) {
overlay.paintOverlay(g2, this);
}
// redraw the zoom rectangle (if present) - if useBuffer is false,
// we use XOR so we can XOR the rectangle away again without redrawing
// the chart
drawZoomRectangle(g2, !this.useBuffer);
g2.dispose();
this.anchor = null;
}
/**
* Receives notification of changes to the chart, and redraws the chart.
*
* @param event details of the chart change event.
*/
@Override
public void chartChanged(ChartChangeEvent event) {
this.refreshBuffer = true;
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
this.orientation = z.getOrientation();
}
repaint();
}
/**
* Receives notification of a chart progress event.
*
* @param event the event.
*/
@Override
public void chartProgress(ChartProgressEvent event) {
// does nothing - override if necessary
}
/**
* Handles action events generated by the popup menu.
*
* @param event the event.
*/
@Override
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
// many of the zoom methods need a screen location - all we have is
// the zoomPoint, but it might be null. Here we grab the x and y
// coordinates, or use defaults...
double screenX = -1.0;
double screenY = -1.0;
if (this.zoomPoint != null) {
screenX = this.zoomPoint.getX();
screenY = this.zoomPoint.getY();
}
if (command.equals(PROPERTIES_COMMAND)) {
doEditChartProperties();
}
else if (command.equals(COPY_COMMAND)) {
doCopy();
}
else if (command.equals(SAVE_AS_PNG_COMMAND)) {
try {
doSaveAs();
}
catch (IOException e) {
JOptionPane.showMessageDialog(this, "I/O error occurred.",
localizationResources.getString("Save_as_PNG"),
JOptionPane.WARNING_MESSAGE);
}
}
else if (command.equals(SAVE_AS_PNG_SIZE_COMMAND)) {
try{
final Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
doSaveAs(ss.width, ss.height);
}
catch (IOException e){
JOptionPane.showMessageDialog(ChartPanel.this, "I/O error occurred.",
localizationResources.getString("Save_as_PNG"),
JOptionPane.WARNING_MESSAGE);
}
}
else if (command.equals(SAVE_AS_SVG_COMMAND)) {
try {
saveAsSVG(null);
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "I/O error occurred.",
localizationResources.getString("Save_as_SVG"),
JOptionPane.WARNING_MESSAGE);
}
}
else if (command.equals(SAVE_AS_PDF_COMMAND)) {
saveAsPDF(null);
}
else if (command.equals(PRINT_COMMAND)) {
createChartPrintJob();
}
else if (command.equals(ZOOM_IN_BOTH_COMMAND)) {
zoomInBoth(screenX, screenY);
}
else if (command.equals(ZOOM_IN_DOMAIN_COMMAND)) {
zoomInDomain(screenX, screenY);
}
else if (command.equals(ZOOM_IN_RANGE_COMMAND)) {
zoomInRange(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_BOTH_COMMAND)) {
zoomOutBoth(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_DOMAIN_COMMAND)) {
zoomOutDomain(screenX, screenY);
}
else if (command.equals(ZOOM_OUT_RANGE_COMMAND)) {
zoomOutRange(screenX, screenY);
}
else if (command.equals(ZOOM_RESET_BOTH_COMMAND)) {
restoreAutoBounds();
}
else if (command.equals(ZOOM_RESET_DOMAIN_COMMAND)) {
restoreAutoDomainBounds();
}
else if (command.equals(ZOOM_RESET_RANGE_COMMAND)) {
restoreAutoRangeBounds();
}
}
/**
* Handles a 'mouse entered' event. This method changes the tooltip delays
* of ToolTipManager.sharedInstance() to the possibly different values set
* for this chart panel.
*
* @param e the mouse event.
*/
@Override
public void mouseEntered(MouseEvent e) {
if (!this.ownToolTipDelaysActive) {
ToolTipManager ttm = ToolTipManager.sharedInstance();
this.originalToolTipInitialDelay = ttm.getInitialDelay();
ttm.setInitialDelay(this.ownToolTipInitialDelay);
this.originalToolTipReshowDelay = ttm.getReshowDelay();
ttm.setReshowDelay(this.ownToolTipReshowDelay);
this.originalToolTipDismissDelay = ttm.getDismissDelay();
ttm.setDismissDelay(this.ownToolTipDismissDelay);
this.ownToolTipDelaysActive = true;
}
}
/**
* Handles a 'mouse exited' event. This method resets the tooltip delays of
* ToolTipManager.sharedInstance() to their
* original values in effect before mouseEntered()
*
* @param e the mouse event.
*/
@Override
public void mouseExited(MouseEvent e) {
if (this.ownToolTipDelaysActive) {
// restore original tooltip dealys
ToolTipManager ttm = ToolTipManager.sharedInstance();
ttm.setInitialDelay(this.originalToolTipInitialDelay);
ttm.setReshowDelay(this.originalToolTipReshowDelay);
ttm.setDismissDelay(this.originalToolTipDismissDelay);
this.ownToolTipDelaysActive = false;
}
}
/**
* Handles a 'mouse pressed' event.
* <P>
* This event is the popup trigger on Unix/Linux. For Windows, the popup
* trigger is the 'mouse released' event.
*
* @param e The mouse event.
*/
@Override
public void mousePressed(MouseEvent e) {
if (this.chart == null) {
return;
}
Plot plot = this.chart.getPlot();
int mods = e.getModifiers();
if ((mods & this.panMask) == this.panMask) {
// can we pan this plot?
if (plot instanceof Pannable) {
Pannable pannable = (Pannable) plot;
if (pannable.isDomainPannable() || pannable.isRangePannable()) {
Rectangle2D screenDataArea = getScreenDataArea(e.getX(),
e.getY());
if (screenDataArea != null && screenDataArea.contains(
e.getPoint())) {
this.panW = screenDataArea.getWidth();
this.panH = screenDataArea.getHeight();
this.panLast = e.getPoint();
setCursor(Cursor.getPredefinedCursor(
Cursor.MOVE_CURSOR));
}
}
// the actual panning occurs later in the mouseDragged()
// method
}
}
else if (this.zoomRectangle == null) {
Rectangle2D screenDataArea = getScreenDataArea(e.getX(), e.getY());
if (screenDataArea != null) {
this.zoomPoint = getPointInRectangle(e.getX(), e.getY(),
screenDataArea);
}
else {
this.zoomPoint = null;
}
if (e.isPopupTrigger()) {
if (this.popup != null) {
displayPopupMenu(e.getX(), e.getY());
}
}
}
}
/**
* Returns a point based on (x, y) but constrained to be within the bounds
* of the given rectangle. This method could be moved to JCommon.
*
* @param x the x-coordinate.
* @param y the y-coordinate.
* @param area the rectangle ({@code null} not permitted).
*
* @return A point within the rectangle.
*/
protected Point2D getPointInRectangle(int x, int y, Rectangle2D area) {
double xx = Math.max(area.getMinX(), Math.min(x, area.getMaxX()));
double yy = Math.max(area.getMinY(), Math.min(y, area.getMaxY()));
return new Point2D.Double(xx, yy);
}
/**
* Handles a 'mouse dragged' event.
*
* @param e the mouse event.
*/
@Override
public void mouseDragged(MouseEvent e) {
// if the popup menu has already been triggered, then ignore dragging...
if (this.popup != null && this.popup.isShowing()) {
return;
}
// handle panning if we have a start point
if (this.panLast != null) {
double dx = e.getX() - this.panLast.getX();
double dy = e.getY() - this.panLast.getY();
if (dx == 0.0 && dy == 0.0) {
return;
}
double wPercent = -dx / this.panW;
double hPercent = dy / this.panH;
boolean old = this.chart.getPlot().isNotify();
this.chart.getPlot().setNotify(false);
Pannable p = (Pannable) this.chart.getPlot();
if (p.getOrientation() == PlotOrientation.VERTICAL) {
p.panDomainAxes(wPercent, this.info.getPlotInfo(),
this.panLast);
p.panRangeAxes(hPercent, this.info.getPlotInfo(),
this.panLast);
}
else {
p.panDomainAxes(hPercent, this.info.getPlotInfo(),
this.panLast);
p.panRangeAxes(wPercent, this.info.getPlotInfo(),
this.panLast);
}
this.panLast = e.getPoint();
this.chart.getPlot().setNotify(old);
return;
}
// if no initial zoom point was set, ignore dragging...
if (this.zoomPoint == null) {
return;
}
Graphics2D g2 = (Graphics2D) getGraphics();
// erase the previous zoom rectangle (if any). We only need to do
// this is we are using XOR mode, which we do when we're not using
// the buffer (if there is a buffer, then at the end of this method we
// just trigger a repaint)
if (!this.useBuffer) {
drawZoomRectangle(g2, true);
}
boolean hZoom, vZoom;
if (this.orientation == PlotOrientation.HORIZONTAL) {
hZoom = this.rangeZoomable;
vZoom = this.domainZoomable;
}
else {
hZoom = this.domainZoomable;
vZoom = this.rangeZoomable;
}
Rectangle2D scaledDataArea = getScreenDataArea(
(int) this.zoomPoint.getX(), (int) this.zoomPoint.getY());
if (hZoom && vZoom) {
// selected rectangle shouldn't extend outside the data area...
double xmax = Math.min(e.getX(), scaledDataArea.getMaxX());
double ymax = Math.min(e.getY(), scaledDataArea.getMaxY());
this.zoomRectangle = new Rectangle2D.Double(
this.zoomPoint.getX(), this.zoomPoint.getY(),
xmax - this.zoomPoint.getX(), ymax - this.zoomPoint.getY());
}
else if (hZoom) {
double xmax = Math.min(e.getX(), scaledDataArea.getMaxX());
this.zoomRectangle = new Rectangle2D.Double(
this.zoomPoint.getX(), scaledDataArea.getMinY(),
xmax - this.zoomPoint.getX(), scaledDataArea.getHeight());
}
else if (vZoom) {
double ymax = Math.min(e.getY(), scaledDataArea.getMaxY());
this.zoomRectangle = new Rectangle2D.Double(
scaledDataArea.getMinX(), this.zoomPoint.getY(),
scaledDataArea.getWidth(), ymax - this.zoomPoint.getY());
}
// Draw the new zoom rectangle...
if (this.useBuffer) {
repaint();
}
else {
// with no buffer, we use XOR to draw the rectangle "over" the
// chart...
drawZoomRectangle(g2, true);
}
g2.dispose();
}
/**
* Handles a 'mouse released' event. On Windows, we need to check if this
* is a popup trigger, but only if we haven't already been tracking a zoom
* rectangle.
*
* @param e information about the event.
*/
@Override
public void mouseReleased(MouseEvent e) {
// if we've been panning, we need to reset now that the mouse is
// released...
if (this.panLast != null) {
this.panLast = null;
setCursor(Cursor.getDefaultCursor());
}
else if (this.zoomRectangle != null) {
boolean hZoom, vZoom;
if (this.orientation == PlotOrientation.HORIZONTAL) {
hZoom = this.rangeZoomable;
vZoom = this.domainZoomable;
}
else {
hZoom = this.domainZoomable;
vZoom = this.rangeZoomable;
}
boolean zoomTrigger1 = hZoom && Math.abs(e.getX()
- this.zoomPoint.getX()) >= this.zoomTriggerDistance;
boolean zoomTrigger2 = vZoom && Math.abs(e.getY()
- this.zoomPoint.getY()) >= this.zoomTriggerDistance;
if (zoomTrigger1 || zoomTrigger2) {
if ((hZoom && (e.getX() < this.zoomPoint.getX()))
|| (vZoom && (e.getY() < this.zoomPoint.getY()))) {
restoreAutoBounds();
}
else {
double x, y, w, h;
Rectangle2D screenDataArea = getScreenDataArea(
(int) this.zoomPoint.getX(),
(int) this.zoomPoint.getY());
double maxX = screenDataArea.getMaxX();
double maxY = screenDataArea.getMaxY();
// for mouseReleased event, (horizontalZoom || verticalZoom)
// will be true, so we can just test for either being false;
// otherwise both are true
if (!vZoom) {
x = this.zoomPoint.getX();
y = screenDataArea.getMinY();
w = Math.min(this.zoomRectangle.getWidth(),
maxX - this.zoomPoint.getX());
h = screenDataArea.getHeight();
}
else if (!hZoom) {
x = screenDataArea.getMinX();
y = this.zoomPoint.getY();
w = screenDataArea.getWidth();
h = Math.min(this.zoomRectangle.getHeight(),
maxY - this.zoomPoint.getY());
}
else {
x = this.zoomPoint.getX();
y = this.zoomPoint.getY();
w = Math.min(this.zoomRectangle.getWidth(),
maxX - this.zoomPoint.getX());
h = Math.min(this.zoomRectangle.getHeight(),
maxY - this.zoomPoint.getY());
}
Rectangle2D zoomArea = new Rectangle2D.Double(x, y, w, h);
zoom(zoomArea);
}
this.zoomPoint = null;
this.zoomRectangle = null;
}
else {
// erase the zoom rectangle
Graphics2D g2 = (Graphics2D) getGraphics();
if (this.useBuffer) {
repaint();
}
else {
drawZoomRectangle(g2, true);
}
g2.dispose();
this.zoomPoint = null;
this.zoomRectangle = null;
}
}
else if (e.isPopupTrigger()) {
if (this.popup != null) {
displayPopupMenu(e.getX(), e.getY());
}
}
}
/**
* Receives notification of mouse clicks on the panel. These are
* translated and passed on to any registered {@link ChartMouseListener}s.
*
* @param event Information about the mouse event.
*/
@Override
public void mouseClicked(MouseEvent event) {
Insets insets = getInsets();
int x = (int) ((event.getX() - insets.left) / this.scaleX);
int y = (int) ((event.getY() - insets.top) / this.scaleY);
this.anchor = new Point2D.Double(x, y);
if (this.chart == null) {
return;
}
this.chart.setNotify(true); // force a redraw
// new entity code...
Object[] listeners = this.chartMouseListeners.getListeners(
ChartMouseListener.class);
if (listeners.length == 0) {
return;
}
ChartEntity entity = null;
if (this.info != null) {
EntityCollection entities = this.info.getEntityCollection();
if (entities != null) {
entity = entities.getEntity(x, y);
}
}
ChartMouseEvent chartEvent = new ChartMouseEvent(getChart(), event,
entity);
for (int i = listeners.length - 1; i >= 0; i -= 1) {
((ChartMouseListener) listeners[i]).chartMouseClicked(chartEvent);
}
}
/**
* Implementation of the MouseMotionListener's method.
*
* @param e the event.
*/
@Override
public void mouseMoved(MouseEvent e) {
Graphics2D g2 = (Graphics2D) getGraphics();
g2.dispose();
Object[] listeners = this.chartMouseListeners.getListeners(
ChartMouseListener.class);
if (listeners.length == 0) {
return;
}
Insets insets = getInsets();
int x = (int) ((e.getX() - insets.left) / this.scaleX);
int y = (int) ((e.getY() - insets.top) / this.scaleY);
ChartEntity entity = null;
if (this.info != null) {
EntityCollection entities = this.info.getEntityCollection();
if (entities != null) {
entity = entities.getEntity(x, y);
}
}
// we can only generate events if the panel's chart is not null
// (see bug report 1556951)
if (this.chart != null) {
ChartMouseEvent event = new ChartMouseEvent(getChart(), e, entity);
for (int i = listeners.length - 1; i >= 0; i -= 1) {
((ChartMouseListener) listeners[i]).chartMouseMoved(event);
}
}
}
/**
* Zooms in on an anchor point (specified in screen coordinate space).
*
* @param x the x value (in screen coordinates).
* @param y the y value (in screen coordinates).
*/
public void zoomInBoth(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot == null) {
return;
}
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
zoomInDomain(x, y);
zoomInRange(x, y);
plot.setNotify(savedNotify);
}
/**
* Decreases the length of the domain axis, centered about the given
* coordinate on the screen. The length of the domain axis is reduced
* by the value of {@link #getZoomInFactor()}.
*
* @param x the x coordinate (in screen coordinates).
* @param y the y-coordinate (in screen coordinates).
*/
public void zoomInDomain(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomDomainAxes(this.zoomInFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Decreases the length of the range axis, centered about the given
* coordinate on the screen. The length of the range axis is reduced by
* the value of {@link #getZoomInFactor()}.
*
* @param x the x-coordinate (in screen coordinates).
* @param y the y coordinate (in screen coordinates).
*/
public void zoomInRange(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomRangeAxes(this.zoomInFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Zooms out on an anchor point (specified in screen coordinate space).
*
* @param x the x value (in screen coordinates).
* @param y the y value (in screen coordinates).
*/
public void zoomOutBoth(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot == null) {
return;
}
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
zoomOutDomain(x, y);
zoomOutRange(x, y);
plot.setNotify(savedNotify);
}
/**
* Increases the length of the domain axis, centered about the given
* coordinate on the screen. The length of the domain axis is increased
* by the value of {@link #getZoomOutFactor()}.
*
* @param x the x coordinate (in screen coordinates).
* @param y the y-coordinate (in screen coordinates).
*/
public void zoomOutDomain(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomDomainAxes(this.zoomOutFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Increases the length the range axis, centered about the given
* coordinate on the screen. The length of the range axis is increased
* by the value of {@link #getZoomOutFactor()}.
*
* @param x the x coordinate (in screen coordinates).
* @param y the y-coordinate (in screen coordinates).
*/
public void zoomOutRange(double x, double y) {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
Zoomable z = (Zoomable) plot;
z.zoomRangeAxes(this.zoomOutFactor, this.info.getPlotInfo(),
translateScreenToJava2D(new Point((int) x, (int) y)),
this.zoomAroundAnchor);
plot.setNotify(savedNotify);
}
}
/**
* Zooms in on a selected region.
*
* @param selection the selected region.
*/
public void zoom(Rectangle2D selection) {
// get the origin of the zoom selection in the Java2D space used for
// drawing the chart (that is, before any scaling to fit the panel)
Point2D selectOrigin = translateScreenToJava2D(new Point(
(int) Math.ceil(selection.getX()),
(int) Math.ceil(selection.getY())));
PlotRenderingInfo plotInfo = this.info.getPlotInfo();
Rectangle2D scaledDataArea = getScreenDataArea(
(int) selection.getCenterX(), (int) selection.getCenterY());
if ((selection.getHeight() > 0) && (selection.getWidth() > 0)) {
double hLower = (selection.getMinX() - scaledDataArea.getMinX())
/ scaledDataArea.getWidth();
double hUpper = (selection.getMaxX() - scaledDataArea.getMinX())
/ scaledDataArea.getWidth();
double vLower = (scaledDataArea.getMaxY() - selection.getMaxY())
/ scaledDataArea.getHeight();
double vUpper = (scaledDataArea.getMaxY() - selection.getMinY())
/ scaledDataArea.getHeight();
Plot p = this.chart.getPlot();
if (p instanceof Zoomable) {
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = p.isNotify();
p.setNotify(false);
Zoomable z = (Zoomable) p;
if (z.getOrientation() == PlotOrientation.HORIZONTAL) {
z.zoomDomainAxes(vLower, vUpper, plotInfo, selectOrigin);
z.zoomRangeAxes(hLower, hUpper, plotInfo, selectOrigin);
}
else {
z.zoomDomainAxes(hLower, hUpper, plotInfo, selectOrigin);
z.zoomRangeAxes(vLower, vUpper, plotInfo, selectOrigin);
}
p.setNotify(savedNotify);
}
}
}
/**
* Restores the auto-range calculation on both axes.
*/
public void restoreAutoBounds() {
Plot plot = this.chart.getPlot();
if (plot == null) {
return;
}
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
restoreAutoDomainBounds();
restoreAutoRangeBounds();
plot.setNotify(savedNotify);
}
/**
* Restores the auto-range calculation on the domain axis.
*/
public void restoreAutoDomainBounds() {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
// we need to guard against this.zoomPoint being null
Point2D zp = (this.zoomPoint != null
? this.zoomPoint : new Point());
z.zoomDomainAxes(0.0, this.info.getPlotInfo(), zp);
plot.setNotify(savedNotify);
}
}
/**
* Restores the auto-range calculation on the range axis.
*/
public void restoreAutoRangeBounds() {
Plot plot = this.chart.getPlot();
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
// here we tweak the notify flag on the plot so that only
// one notification happens even though we update multiple
// axes...
boolean savedNotify = plot.isNotify();
plot.setNotify(false);
// we need to guard against this.zoomPoint being null
Point2D zp = (this.zoomPoint != null
? this.zoomPoint : new Point());
z.zoomRangeAxes(0.0, this.info.getPlotInfo(), zp);
plot.setNotify(savedNotify);
}
}
/**
* Returns the data area for the chart (the area inside the axes) with the
* current scaling applied (that is, the area as it appears on screen).
*
* @return The scaled data area.
*/
public Rectangle2D getScreenDataArea() {
Rectangle2D dataArea = this.info.getPlotInfo().getDataArea();
Insets insets = getInsets();
double x = dataArea.getX() * this.scaleX + insets.left;
double y = dataArea.getY() * this.scaleY + insets.top;
double w = dataArea.getWidth() * this.scaleX;
double h = dataArea.getHeight() * this.scaleY;
return new Rectangle2D.Double(x, y, w, h);
}
/**
* Returns the data area (the area inside the axes) for the plot or subplot,
* with the current scaling applied.
*
* @param x the x-coordinate (for subplot selection).
* @param y the y-coordinate (for subplot selection).
*
* @return The scaled data area.
*/
public Rectangle2D getScreenDataArea(int x, int y) {
PlotRenderingInfo plotInfo = this.info.getPlotInfo();
Rectangle2D result;
if (plotInfo.getSubplotCount() == 0) {
result = getScreenDataArea();
}
else {
// get the origin of the zoom selection in the Java2D space used for
// drawing the chart (that is, before any scaling to fit the panel)
Point2D selectOrigin = translateScreenToJava2D(new Point(x, y));
int subplotIndex = plotInfo.getSubplotIndex(selectOrigin);
if (subplotIndex == -1) {
return null;
}
result = scale(plotInfo.getSubplotInfo(subplotIndex).getDataArea());
}
return result;
}
/**
* Returns the initial tooltip delay value used inside this chart panel.
*
* @return An integer representing the initial delay value, in milliseconds.
*
* @see javax.swing.ToolTipManager#getInitialDelay()
*/
public int getInitialDelay() {
return this.ownToolTipInitialDelay;
}
/**
* Returns the reshow tooltip delay value used inside this chart panel.
*
* @return An integer representing the reshow delay value, in milliseconds.
*
* @see javax.swing.ToolTipManager#getReshowDelay()
*/
public int getReshowDelay() {
return this.ownToolTipReshowDelay;
}
/**
* Returns the dismissal tooltip delay value used inside this chart panel.
*
* @return An integer representing the dismissal delay value, in
* milliseconds.
*
* @see javax.swing.ToolTipManager#getDismissDelay()
*/
public int getDismissDelay() {
return this.ownToolTipDismissDelay;
}
/**
* Specifies the initial delay value for this chart panel.
*
* @param delay the number of milliseconds to delay (after the cursor has
* paused) before displaying.
*
* @see javax.swing.ToolTipManager#setInitialDelay(int)
*/
public void setInitialDelay(int delay) {
this.ownToolTipInitialDelay = delay;
}
/**
* Specifies the amount of time before the user has to wait initialDelay
* milliseconds before a tooltip will be shown.
*
* @param delay time in milliseconds
*
* @see javax.swing.ToolTipManager#setReshowDelay(int)
*/
public void setReshowDelay(int delay) {
this.ownToolTipReshowDelay = delay;
}
/**
* Specifies the dismissal delay value for this chart panel.
*
* @param delay the number of milliseconds to delay before taking away the
* tooltip
*
* @see javax.swing.ToolTipManager#setDismissDelay(int)
*/
public void setDismissDelay(int delay) {
this.ownToolTipDismissDelay = delay;
}
/**
* Returns the zoom in factor.
*
* @return The zoom in factor.
*
* @see #setZoomInFactor(double)
*/
public double getZoomInFactor() {
return this.zoomInFactor;
}
/**
* Sets the zoom in factor.
*
* @param factor the factor.
*
* @see #getZoomInFactor()
*/
public void setZoomInFactor(double factor) {
this.zoomInFactor = factor;
}
/**
* Returns the zoom out factor.
*
* @return The zoom out factor.
*
* @see #setZoomOutFactor(double)
*/
public double getZoomOutFactor() {
return this.zoomOutFactor;
}
/**
* Sets the zoom out factor.
*
* @param factor the factor.
*
* @see #getZoomOutFactor()
*/
public void setZoomOutFactor(double factor) {
this.zoomOutFactor = factor;
}
/**
* Draws zoom rectangle (if present).
* The drawing is performed in XOR mode, therefore
* when this method is called twice in a row,
* the second call will completely restore the state
* of the canvas.
*
* @param g2 the graphics device.
* @param xor use XOR for drawing?
*/
protected void drawZoomRectangle(Graphics2D g2, boolean xor) {
if (this.zoomRectangle != null) {
if (xor) {
// Set XOR mode to draw the zoom rectangle
g2.setXORMode(Color.GRAY);
}
if (this.fillZoomRectangle) {
g2.setPaint(this.zoomFillPaint);
g2.fill(this.zoomRectangle);
}
else {
g2.setPaint(this.zoomOutlinePaint);
g2.draw(this.zoomRectangle);
}
if (xor) {
// Reset to the default 'overwrite' mode
g2.setPaintMode();
}
}
}
/**
* Displays a dialog that allows the user to edit the properties for the
* current chart.
*
* @since 1.0.3
*/
public void doEditChartProperties() {
ChartEditor editor = ChartEditorManager.getChartEditor(this.chart);
int result = JOptionPane.showConfirmDialog(this, editor,
localizationResources.getString("Chart_Properties"),
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
editor.updateChart(this.chart);
}
}
/**
* Copies the current chart to the system clipboard.
*
* @since 1.0.13
*/
public void doCopy() {
Clipboard systemClipboard
= Toolkit.getDefaultToolkit().getSystemClipboard();
Insets insets = getInsets();
int w = getWidth() - insets.left - insets.right;
int h = getHeight() - insets.top - insets.bottom;
ChartTransferable selection = new ChartTransferable(this.chart, w, h,
getMinimumDrawWidth(), getMinimumDrawHeight(),
getMaximumDrawWidth(), getMaximumDrawHeight(), true);
systemClipboard.setContents(selection, null);
}
/**
* Opens a file chooser and gives the user an opportunity to save the chart
* in PNG format.
*
* @throws IOException if there is an I/O error.
*/
public void doSaveAs() throws IOException {
doSaveAs(-1, -1);
}
/**
* Opens a file chooser and gives the user an opportunity to save the chart
* in PNG format.
*
* @param w the width for the saved image (if less than or equal to zero,
* the panel width will be used);
* @param h the height for the PNG image (if less than or equal to zero,
* the panel height will be used);
*
* @throws IOException if there is an I/O error.
*/
public void doSaveAs(int w, int h) throws IOException {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
localizationResources.getString("PNG_Image_Files"), "png");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".png")) {
filename = filename + ".png";
}
}
if (w <= 0) {
w = getWidth();
}
if (h <= 0) {
h = getHeight();
}
ChartUtils.saveChartAsPNG(new File(filename), this.chart, w, h);
}
}
/**
* Saves the chart in SVG format (a filechooser will be displayed so that
* the user can specify the filename). Note that this method only works
* if the JFreeSVG library is on the classpath...if this library is not
* present, the method will fail.
*/
protected void saveAsSVG(File f) throws IOException {
File file = f;
if (file == null) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
localizationResources.getString("SVG_Files"), "svg");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".svg")) {
filename = filename + ".svg";
}
}
file = new File(filename);
if (file.exists()) {
String fileExists = localizationResources.getString(
"FILE_EXISTS_CONFIRM_OVERWRITE");
int response = JOptionPane.showConfirmDialog(this,
fileExists,
localizationResources.getString("Save_as_SVG"),
JOptionPane.OK_CANCEL_OPTION);
if (response == JOptionPane.CANCEL_OPTION) {
file = null;
}
}
}
}
if (file != null) {
// use reflection to get the SVG string
String svg = generateSVG(getWidth(), getHeight());
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write("<!DOCTYPE svg PUBLIC \"-
writer.write(svg + "\n");
writer.flush();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}
/**
* Generates a string containing a rendering of the chart in SVG format.
* This feature is only supported if the JFreeSVG library is included on
* the classpath.
*
* @return A string containing an SVG element for the current chart, or
* {@code null} if there is a problem with the method invocation
* by reflection.
*/
protected String generateSVG(int width, int height) {
Graphics2D g2 = createSVGGraphics2D(width, height);
if (g2 == null) {
throw new IllegalStateException("JFreeSVG library is not present.");
}
// we suppress shadow generation, because SVG is a vector format and
// the shadow effect is applied via bitmap effects...
g2.setRenderingHint(JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION, true);
String svg = null;
Rectangle2D drawArea = new Rectangle2D.Double(0, 0, width, height);
this.chart.draw(g2, drawArea);
try {
Method m = g2.getClass().getMethod("getSVGElement");
svg = (String) m.invoke(g2);
} catch (NoSuchMethodException e) {
// null will be returned
} catch (SecurityException e) {
// null will be returned
} catch (IllegalAccessException e) {
// null will be returned
} catch (IllegalArgumentException e) {
// null will be returned
} catch (InvocationTargetException e) {
// null will be returned
}
return svg;
}
protected Graphics2D createSVGGraphics2D(int w, int h) {
try {
Class svgGraphics2d = Class.forName("org.jfree.graphics2d.svg.SVGGraphics2D");
Constructor ctor = svgGraphics2d.getConstructor(int.class, int.class);
return (Graphics2D) ctor.newInstance(w, h);
} catch (ClassNotFoundException ex) {
return null;
} catch (NoSuchMethodException ex) {
return null;
} catch (SecurityException ex) {
return null;
} catch (InstantiationException ex) {
return null;
} catch (IllegalAccessException ex) {
return null;
} catch (IllegalArgumentException ex) {
return null;
} catch (InvocationTargetException ex) {
return null;
}
}
/**
* Saves the chart in PDF format (a filechooser will be displayed so that
* the user can specify the filename). Note that this method only works
* if the OrsonPDF library is on the classpath...if this library is not
* present, the method will fail.
*/
protected void saveAsPDF(File f) {
File file = f;
if (file == null) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
localizationResources.getString("PDF_Files"), "pdf");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setFileFilter(filter);
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fileChooser.getSelectedFile().getPath();
if (isEnforceFileExtensions()) {
if (!filename.endsWith(".pdf")) {
filename = filename + ".pdf";
}
}
file = new File(filename);
if (file.exists()) {
String fileExists = localizationResources.getString(
"FILE_EXISTS_CONFIRM_OVERWRITE");
int response = JOptionPane.showConfirmDialog(this,
fileExists,
localizationResources.getString("Save_as_PDF"),
JOptionPane.OK_CANCEL_OPTION);
if (response == JOptionPane.CANCEL_OPTION) {
file = null;
}
}
}
}
if (file != null) {
writeAsPDF(file, getWidth(), getHeight());
}
}
/**
* Writes the current chart to the specified file in PDF format. This
* will only work when the OrsonPDF library is found on the classpath.
* Reflection is used to ensure there is no compile-time dependency on
* OrsonPDF (which is non-free software).
*
* @param file the output file ({@code null} not permitted).
* @param w the chart width.
* @param h the chart height.
*/
private void writeAsPDF(File file, int w, int h) {
if (!ChartUtils.isOrsonPDFAvailable()) {
throw new IllegalStateException(
"OrsonPDF is not present on the classpath.");
}
Args.nullNotPermitted(file, "file");
try {
Class pdfDocClass = Class.forName("com.orsonpdf.PDFDocument");
Object pdfDoc = pdfDocClass.newInstance();
Method m = pdfDocClass.getMethod("createPage", Rectangle2D.class);
Rectangle2D rect = new Rectangle(w, h);
Object page = m.invoke(pdfDoc, rect);
Method m2 = page.getClass().getMethod("getGraphics2D");
Graphics2D g2 = (Graphics2D) m2.invoke(page);
// we suppress shadow generation, because PDF is a vector format and
// the shadow effect is applied via bitmap effects...
g2.setRenderingHint(JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION, true);
Rectangle2D drawArea = new Rectangle2D.Double(0, 0, w, h);
this.chart.draw(g2, drawArea);
Method m3 = pdfDocClass.getMethod("writeToFile", File.class);
m3.invoke(pdfDoc, file);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
} catch (SecurityException ex) {
throw new RuntimeException(ex);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
/**
* Creates a print job for the chart.
*/
public void createChartPrintJob() {
PrinterJob job = PrinterJob.getPrinterJob();
PageFormat pf = job.defaultPage();
PageFormat pf2 = job.pageDialog(pf);
if (pf2 != pf) {
job.setPrintable(this, pf2);
if (job.printDialog()) {
try {
job.print();
}
catch (PrinterException e) {
JOptionPane.showMessageDialog(this, e);
}
}
}
}
/**
* Prints the chart on a single page.
*
* @param g the graphics context.
* @param pf the page format to use.
* @param pageIndex the index of the page. If not {@code 0}, nothing
* gets printed.
*
* @return The result of printing.
*/
@Override
public int print(Graphics g, PageFormat pf, int pageIndex) {
if (pageIndex != 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) g;
double x = pf.getImageableX();
double y = pf.getImageableY();
double w = pf.getImageableWidth();
double h = pf.getImageableHeight();
this.chart.draw(g2, new Rectangle2D.Double(x, y, w, h), this.anchor,
null);
return PAGE_EXISTS;
}
/**
* Adds a listener to the list of objects listening for chart mouse events.
*
* @param listener the listener ({@code null} not permitted).
*/
public void addChartMouseListener(ChartMouseListener listener) {
Args.nullNotPermitted(listener, "listener");
this.chartMouseListeners.add(ChartMouseListener.class, listener);
}
/**
* Removes a listener from the list of objects listening for chart mouse
* events.
*
* @param listener the listener.
*/
public void removeChartMouseListener(ChartMouseListener listener) {
this.chartMouseListeners.remove(ChartMouseListener.class, listener);
}
/**
* Returns an array of the listeners of the given type registered with the
* panel.
*
* @param listenerType the listener type.
*
* @return An array of listeners.
*/
@Override
public EventListener[] getListeners(Class listenerType) {
if (listenerType == ChartMouseListener.class) {
// fetch listeners from local storage
return this.chartMouseListeners.getListeners(listenerType);
}
else {
return super.getListeners(listenerType);
}
}
/**
* Creates a popup menu for the panel.
*
* @param properties include a menu item for the chart property editor.
* @param save include a menu item for saving the chart.
* @param print include a menu item for printing the chart.
* @param zoom include menu items for zooming.
*
* @return The popup menu.
*
* @deprecated Use #createPopupMenu(boolean, boolean, boolean, boolean, boolean)
* as this includes an explicit flag for the {@code copy} menu item.
*/
protected JPopupMenu createPopupMenu(boolean properties, boolean save,
boolean print, boolean zoom) {
return createPopupMenu(properties, false, save, print, zoom);
}
/**
* Creates a popup menu for the panel. This method includes code that
* auto-detects JFreeSVG and OrsonPDF (via reflection) and, if they are
* present (and the {@code save} argument is {@code true}, adds a menu item
* for each.
*
* @param properties include a menu item for the chart property editor.
* @param copy include a menu item for copying to the clipboard.
* @param save include one or more menu items for saving the chart to
* supported image formats.
* @param print include a menu item for printing the chart.
* @param zoom include menu items for zooming.
*
* @return The popup menu.
*
* @since 1.0.13
*/
protected JPopupMenu createPopupMenu(boolean properties,
boolean copy, boolean save, boolean print, boolean zoom) {
JPopupMenu result = new JPopupMenu(localizationResources.getString("Chart") + ":");
boolean separator = false;
if (properties) {
JMenuItem propertiesItem = new JMenuItem(
localizationResources.getString("Properties..."));
propertiesItem.setActionCommand(PROPERTIES_COMMAND);
propertiesItem.addActionListener(this);
result.add(propertiesItem);
separator = true;
}
if (copy) {
if (separator) {
result.addSeparator();
}
JMenuItem copyItem = new JMenuItem(
localizationResources.getString("Copy"));
copyItem.setActionCommand(COPY_COMMAND);
copyItem.addActionListener(this);
result.add(copyItem);
separator = !save;
}
if (save) {
if (separator) {
result.addSeparator();
}
JMenu saveSubMenu = new JMenu(localizationResources.getString("Save_as"));
// PNG - current res
{
JMenuItem pngItem = new JMenuItem(localizationResources.getString(
"PNG..."));
pngItem.setActionCommand(SAVE_AS_PNG_COMMAND);
pngItem.addActionListener(this);
saveSubMenu.add(pngItem);
}
// PNG - screen res
{
final Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
final String pngName = "PNG ("+ss.width+"x"+ss.height+") ...";
JMenuItem pngItem = new JMenuItem(pngName);
pngItem.setActionCommand(SAVE_AS_PNG_SIZE_COMMAND);
pngItem.addActionListener(this);
saveSubMenu.add(pngItem);
}
if (ChartUtils.isJFreeSVGAvailable()) {
JMenuItem svgItem = new JMenuItem(localizationResources.getString(
"SVG..."));
svgItem.setActionCommand(SAVE_AS_SVG_COMMAND);
svgItem.addActionListener(this);
saveSubMenu.add(svgItem);
}
if (ChartUtils.isOrsonPDFAvailable()) {
JMenuItem pdfItem = new JMenuItem(
localizationResources.getString("PDF..."));
pdfItem.setActionCommand(SAVE_AS_PDF_COMMAND);
pdfItem.addActionListener(this);
saveSubMenu.add(pdfItem);
}
result.add(saveSubMenu);
separator = true;
}
if (print) {
if (separator) {
result.addSeparator();
}
JMenuItem printItem = new JMenuItem(
localizationResources.getString("Print..."));
printItem.setActionCommand(PRINT_COMMAND);
printItem.addActionListener(this);
result.add(printItem);
separator = true;
}
if (zoom) {
if (separator) {
result.addSeparator();
}
JMenu zoomInMenu = new JMenu(
localizationResources.getString("Zoom_In"));
this.zoomInBothMenuItem = new JMenuItem(
localizationResources.getString("All_Axes"));
this.zoomInBothMenuItem.setActionCommand(ZOOM_IN_BOTH_COMMAND);
this.zoomInBothMenuItem.addActionListener(this);
zoomInMenu.add(this.zoomInBothMenuItem);
zoomInMenu.addSeparator();
this.zoomInDomainMenuItem = new JMenuItem(
localizationResources.getString("Domain_Axis"));
this.zoomInDomainMenuItem.setActionCommand(ZOOM_IN_DOMAIN_COMMAND);
this.zoomInDomainMenuItem.addActionListener(this);
zoomInMenu.add(this.zoomInDomainMenuItem);
this.zoomInRangeMenuItem = new JMenuItem(
localizationResources.getString("Range_Axis"));
this.zoomInRangeMenuItem.setActionCommand(ZOOM_IN_RANGE_COMMAND);
this.zoomInRangeMenuItem.addActionListener(this);
zoomInMenu.add(this.zoomInRangeMenuItem);
result.add(zoomInMenu);
JMenu zoomOutMenu = new JMenu(
localizationResources.getString("Zoom_Out"));
this.zoomOutBothMenuItem = new JMenuItem(
localizationResources.getString("All_Axes"));
this.zoomOutBothMenuItem.setActionCommand(ZOOM_OUT_BOTH_COMMAND);
this.zoomOutBothMenuItem.addActionListener(this);
zoomOutMenu.add(this.zoomOutBothMenuItem);
zoomOutMenu.addSeparator();
this.zoomOutDomainMenuItem = new JMenuItem(
localizationResources.getString("Domain_Axis"));
this.zoomOutDomainMenuItem.setActionCommand(
ZOOM_OUT_DOMAIN_COMMAND);
this.zoomOutDomainMenuItem.addActionListener(this);
zoomOutMenu.add(this.zoomOutDomainMenuItem);
this.zoomOutRangeMenuItem = new JMenuItem(
localizationResources.getString("Range_Axis"));
this.zoomOutRangeMenuItem.setActionCommand(ZOOM_OUT_RANGE_COMMAND);
this.zoomOutRangeMenuItem.addActionListener(this);
zoomOutMenu.add(this.zoomOutRangeMenuItem);
result.add(zoomOutMenu);
JMenu autoRangeMenu = new JMenu(
localizationResources.getString("Auto_Range"));
this.zoomResetBothMenuItem = new JMenuItem(
localizationResources.getString("All_Axes"));
this.zoomResetBothMenuItem.setActionCommand(
ZOOM_RESET_BOTH_COMMAND);
this.zoomResetBothMenuItem.addActionListener(this);
autoRangeMenu.add(this.zoomResetBothMenuItem);
autoRangeMenu.addSeparator();
this.zoomResetDomainMenuItem = new JMenuItem(
localizationResources.getString("Domain_Axis"));
this.zoomResetDomainMenuItem.setActionCommand(
ZOOM_RESET_DOMAIN_COMMAND);
this.zoomResetDomainMenuItem.addActionListener(this);
autoRangeMenu.add(this.zoomResetDomainMenuItem);
this.zoomResetRangeMenuItem = new JMenuItem(
localizationResources.getString("Range_Axis"));
this.zoomResetRangeMenuItem.setActionCommand(
ZOOM_RESET_RANGE_COMMAND);
this.zoomResetRangeMenuItem.addActionListener(this);
autoRangeMenu.add(this.zoomResetRangeMenuItem);
result.addSeparator();
result.add(autoRangeMenu);
}
return result;
}
/**
* The idea is to modify the zooming options depending on the type of chart
* being displayed by the panel.
*
* @param x horizontal position of the popup.
* @param y vertical position of the popup.
*/
protected void displayPopupMenu(int x, int y) {
if (this.popup == null) {
return;
}
// go through each zoom menu item and decide whether or not to
// enable it...
boolean isDomainZoomable = false;
boolean isRangeZoomable = false;
Plot plot = (this.chart != null ? this.chart.getPlot() : null);
if (plot instanceof Zoomable) {
Zoomable z = (Zoomable) plot;
isDomainZoomable = z.isDomainZoomable();
isRangeZoomable = z.isRangeZoomable();
}
if (this.zoomInDomainMenuItem != null) {
this.zoomInDomainMenuItem.setEnabled(isDomainZoomable);
}
if (this.zoomOutDomainMenuItem != null) {
this.zoomOutDomainMenuItem.setEnabled(isDomainZoomable);
}
if (this.zoomResetDomainMenuItem != null) {
this.zoomResetDomainMenuItem.setEnabled(isDomainZoomable);
}
if (this.zoomInRangeMenuItem != null) {
this.zoomInRangeMenuItem.setEnabled(isRangeZoomable);
}
if (this.zoomOutRangeMenuItem != null) {
this.zoomOutRangeMenuItem.setEnabled(isRangeZoomable);
}
if (this.zoomResetRangeMenuItem != null) {
this.zoomResetRangeMenuItem.setEnabled(isRangeZoomable);
}
if (this.zoomInBothMenuItem != null) {
this.zoomInBothMenuItem.setEnabled(isDomainZoomable
&& isRangeZoomable);
}
if (this.zoomOutBothMenuItem != null) {
this.zoomOutBothMenuItem.setEnabled(isDomainZoomable
&& isRangeZoomable);
}
if (this.zoomResetBothMenuItem != null) {
this.zoomResetBothMenuItem.setEnabled(isDomainZoomable
&& isRangeZoomable);
}
this.popup.show(this, x, y);
}
/**
* Updates the UI for a LookAndFeel change.
*/
@Override
public void updateUI() {
// here we need to update the UI for the popup menu, if the panel
// has one...
if (this.popup != null) {
SwingUtilities.updateComponentTreeUI(this.popup);
}
super.updateUI();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
protected void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtils.writePaint(this.zoomFillPaint, stream);
SerialUtils.writePaint(this.zoomOutlinePaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
protected void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.zoomFillPaint = SerialUtils.readPaint(stream);
this.zoomOutlinePaint = SerialUtils.readPaint(stream);
// we create a new but empty chartMouseListeners list
this.chartMouseListeners = new EventListenerList();
// register as a listener with sub-components...
if (this.chart != null) {
this.chart.addChangeListener(this);
}
}
} |
package de.tblsoft.search.query;
import java.util.ArrayList;
import java.util.List;
public class SearchFilter<T> {
private Operator operator = Operator.OR;
private boolean exclude = true;
private String id;
private String name;
private List<T> values = new ArrayList<T>();
public List<T> getValues() {
return values;
}
public void setValues(List<T> values) {
this.values = values;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Operator getOperator() {
return operator;
}
public void setOperator(Operator operator) {
this.operator = operator;
}
public boolean isExclude() {
return exclude;
}
public void setExclude(boolean exclude) {
this.exclude = exclude;
}
@Override
public String toString() {
return "SearchFilter{" +
"operator=" + operator +
", exclude=" + exclude +
", id='" + id + '\'' +
", name='" + name + '\'' +
", values=" + values +
'}';
}
} |
package org.jtrfp.trcl.core;
import java.awt.Component;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;
import org.jtrfp.trcl.beh.FacingObject;
import org.jtrfp.trcl.beh.MatchDirection;
import org.jtrfp.trcl.beh.MatchPosition;
import org.jtrfp.trcl.beh.RotateAroundObject;
import org.jtrfp.trcl.beh.TriggersVisCalcWithMovement;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.obj.VisibleEverywhere;
import org.jtrfp.trcl.obj.WorldObject;
public class Camera extends WorldObject implements VisibleEverywhere{
private volatile RealMatrix cameraMatrix;
private volatile double viewDepth;
private volatile RealMatrix projectionMatrix;
private final GPU gpu;
private volatile int updateDebugStateCounter;
public Camera(GPU gpu) {
super(gpu.getTr());
this.gpu = gpu;
addBehavior(new MatchPosition().setEnable(true));
addBehavior(new MatchDirection()).setEnable(true);
addBehavior(new FacingObject().setEnable(false));
addBehavior(new RotateAroundObject().setEnable(false));
addBehavior(new TriggersVisCalcWithMovement().setEnable(true));
}//end constructor
private void updateProjectionMatrix(){
final Component component = gpu.getTr().getRootWindow();
final float fov = 70f;// In degrees
final float aspect = (float) component.getWidth()
/ (float) component.getHeight();
final float zF = (float) (viewDepth * 1.5);
final float zN = (float) (TR.mapSquareSize / 10);
final float f = (float) (1. / Math.tan(fov * Math.PI / 360.));
projectionMatrix = new Array2DRowRealMatrix(new double[][]
{ new double[]
{ f / aspect, 0, 0, 0 }, new double[]
{ 0, f, 0, 0 }, new double[]
{ 0, 0, (zF + zN) / (zN - zF), -1f }, new double[]
{ 0, 0, (2f * zF * zN) / (zN - zF), 0 } }).transpose();
}
/**
* @return the lookAtVector
*/
public Vector3D getLookAtVector()
{return getLookAt();}
/**
* @param lookAtVector the lookAtVector to set
*/
public synchronized void setLookAtVector(Vector3D lookAtVector){
double [] heading = super.getHeadingArray();
heading[0] = lookAtVector.getX();
heading[1] = lookAtVector.getY();
heading[2] = lookAtVector.getZ();
cameraMatrix=null;
}
/**
* @return the upVector
*/
public Vector3D getUpVector()
{return super.getTop();}
/**
* @param upVector the upVector to set
*/
public synchronized void setUpVector(Vector3D upVector){
super.setTop(upVector);
cameraMatrix=null;
}
/**
* @return the cameraPosition
*/
public Vector3D getCameraPosition()
{return new Vector3D(super.getPosition());}
/**
* @param cameraPosition
* the cameraPosition to set
*/
public void setPosition(Vector3D cameraPosition) {
this.setPosition(cameraPosition.getX(), cameraPosition.getY(),
cameraPosition.getZ());
}
@Override
public synchronized void setPosition(double x, double y, double z) {
super.setPosition(x, y, z);
//cameraMatrix = null;
}
@Override
public Camera notifyPositionChange(){
cameraMatrix= null;
super.notifyPositionChange();
return this;
}
private void applyMatrix(){
Vector3D eyeLoc = getCameraPosition();
Vector3D aZ = getLookAtVector().negate();
Vector3D aX = getUpVector().crossProduct(aZ).normalize();
Vector3D aY = /*aZ.crossProduct(aX)*/getUpVector();
RealMatrix rM = new Array2DRowRealMatrix(new double[][]
{ new double[]
{ aX.getX(), aX.getY(), aX.getZ(), 0 }, new double[]
{ aY.getX(), aY.getY(), aY.getZ(), 0 }, new double[]
{ aZ.getX(), aZ.getY(), aZ.getZ(), 0 }, new double[]
{ 0, 0, 0, 1 } });
RealMatrix tM = new Array2DRowRealMatrix(new double[][]
{ new double[]
{ 1, 0, 0, -eyeLoc.getX() }, new double[]
{ 0, 1, 0, -eyeLoc.getY() }, new double[]
{ 0, 0, 1, -eyeLoc.getZ() }, new double[]
{ 0, 0, 0, 1 } });
cameraMatrix = getProjectionMatrix().multiply(rM.multiply(tM));
}//end applyMatrix()
public synchronized void setViewDepth(double cameraViewDepth){
this.viewDepth=cameraViewDepth;
cameraMatrix=null;
projectionMatrix=null;
}
private RealMatrix getProjectionMatrix(){
if(projectionMatrix==null)updateProjectionMatrix();
return projectionMatrix;
}
public double getViewDepth()
{return viewDepth;}
private synchronized RealMatrix getMatrix()
{if(cameraMatrix==null){
applyMatrix();
if(updateDebugStateCounter++ % 30 ==0){
gpu.getTr().getReporter().report("org.jtrfp.trcl.core.Camera.position", getPosition());
gpu.getTr().getReporter().report("org.jtrfp.trcl.core.Camera.lookAt", getLookAt());
gpu.getTr().getReporter().report("org.jtrfp.trcl.core.Camera.up", getTop());
}}
return cameraMatrix;
}
public float [] getMatrixAsFlatArray(){
final float [] result = new float[16];
final RealMatrix mat = getMatrix();
for(int i=0; i<16; i++){
result[i]=(float)mat.getEntry(i/4, i%4);
}//end for(16)
return result;
}
}//end Camera |
package edu.neu.ccs.pyramid.experiment;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.neu.ccs.pyramid.configuration.Config;
import edu.neu.ccs.pyramid.dataset.*;
import edu.neu.ccs.pyramid.eval.Accuracy;
import edu.neu.ccs.pyramid.eval.Overlap;
import edu.neu.ccs.pyramid.feature.TopFeatures;
import edu.neu.ccs.pyramid.multilabel_classification.MultiLabelPredictionAnalysis;
import edu.neu.ccs.pyramid.multilabel_classification.multi_label_logistic_regression.MLLogisticLoss;
import edu.neu.ccs.pyramid.multilabel_classification.multi_label_logistic_regression.MLLogisticRegression;
import edu.neu.ccs.pyramid.multilabel_classification.multi_label_logistic_regression.MLLogisticRegressionInspector;
import edu.neu.ccs.pyramid.optimization.LBFGS;
import org.apache.commons.lang3.time.StopWatch;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Exp41 {
public static void main(String[] args) throws Exception{
if (args.length !=1){
throw new IllegalArgumentException("Please specify a properties file.");
}
Config config = new Config(args[0]);
System.out.println(config);
if (config.getBoolean("train")){
train(config);
}
if (config.getBoolean("test")){
test(config);
}
if (config.getBoolean("verify")){
verify(config);
}
}
static MultiLabelClfDataSet loadTrainData(Config config) throws Exception{
String trainFile = new File(config.getString("input.folder"),
config.getString("input.trainData")).getAbsolutePath();
MultiLabelClfDataSet dataSet;
dataSet= TRECFormat.loadMultiLabelClfDataSet(new File(trainFile), DataSetType.ML_CLF_SPARSE,
true);
return dataSet;
}
static MultiLabelClfDataSet loadTestData(Config config) throws Exception{
String trainFile = new File(config.getString("input.folder"),
config.getString("input.testData")).getAbsolutePath();
MultiLabelClfDataSet dataSet;
dataSet= TRECFormat.loadMultiLabelClfDataSet(new File(trainFile), DataSetType.ML_CLF_SPARSE,
true);
return dataSet;
}
static void train(Config config) throws Exception{
String archive = config.getString("output.folder");
String modelName = config.getString("output.model");
StopWatch stopWatch = new StopWatch();
stopWatch.start();
MultiLabelClfDataSet dataSet = loadTrainData(config);
System.out.println("training data set loaded");
MultiLabelClfDataSet testSet = loadTestData(config);
System.out.println("test data set loaded");
System.out.println(dataSet.getMetaInfo());
System.out.println("gathering assignments ");
List<MultiLabel> assignments = DataSetUtil.gatherMultiLabels(dataSet).stream()
.collect(Collectors.toList());
System.out.println("there are "+assignments.size()+ " assignments");
System.out.println("initializing logistic regression");
MLLogisticRegression mlLogisticRegression = new MLLogisticRegression(dataSet.getNumClasses(),dataSet.getNumFeatures(),
assignments);
mlLogisticRegression.setFeatureList(dataSet.getFeatureList());
mlLogisticRegression.setLabelTranslator(dataSet.getLabelTranslator());
mlLogisticRegression.setFeatureExtraction(false);
System.out.println("done");
System.out.println("initializing objective function");
MLLogisticLoss function = new MLLogisticLoss(mlLogisticRegression,dataSet,config.getDouble("train.gaussianPriorVariance"));
System.out.println("done");
System.out.println("initializing lbfgs");
LBFGS lbfgs = new LBFGS(function);
// lbfgs.getTerminator().setRelativeEpsilon(config.getDouble("train.epsilon"));
// lbfgs.setHistory(5);
// LinkedList<Double> valueQueue = new LinkedList<>();
// valueQueue.add(function.getValue());
System.out.println("done");
// int iteration=0;
// System.out.println("iteration = "+iteration);
// lbfgs.iterate();
// valueQueue.add(function.getValue());
// iteration+=1;
for (int iteration =0;iteration<config.getInt("numIterations");iteration++){
lbfgs.iterate();
System.out.println("iteration =" + iteration);
System.out.println("objective = "+lbfgs.getTerminator().getLastValue());
System.out.println("training accuracy = "+Accuracy.accuracy(mlLogisticRegression, dataSet));
System.out.println("training overlap +"+Overlap.overlap(mlLogisticRegression,dataSet));
System.out.println("test accuracy = "+Accuracy.accuracy(mlLogisticRegression,testSet));
System.out.println("test overlap +"+Overlap.overlap(mlLogisticRegression,testSet));
System.out.println("=========================");
}
// MLLogisticRegression mlLogisticRegression = trainer.train(dataSet,assignments);
File serializedModel = new File(archive,modelName);
mlLogisticRegression.serialize(serializedModel);
System.out.println("time spent = " + stopWatch);
System.out.println("accuracy on training set = " +Accuracy.accuracy(mlLogisticRegression,dataSet));
System.out.println("overlap on training set = "+ Overlap.overlap(mlLogisticRegression,dataSet));
}
static void test(Config config) throws Exception{
String archive = config.getString("output.folder");
String modelName = config.getString("output.model");
MLLogisticRegression mlLogisticRegression = MLLogisticRegression.deserialize(new File(archive,modelName));
System.out.println("test data set loaded");
MultiLabelClfDataSet dataSet = loadTestData(config);
System.out.println(dataSet.getMetaInfo());
System.out.println("accuracy on test set = "+Accuracy.accuracy(mlLogisticRegression,dataSet));
System.out.println("overlap on test set = "+ Overlap.overlap(mlLogisticRegression,dataSet));
if (config.getBoolean("test.analyze")){
int limit = config.getInt("test.analyze.rule.limit");
List<MultiLabelPredictionAnalysis> analysisList = IntStream.range(0,dataSet.getNumDataPoints()).parallel().filter(
i -> {
MultiLabel multiLabel = dataSet.getMultiLabels()[i];
MultiLabel prediction = mlLogisticRegression.predict(dataSet.getRow(i));
boolean accept = false;
if (config.getBoolean("test.analyze.doc.withRightPrediction")) {
accept = accept || multiLabel.equals(prediction);
}
if (config.getBoolean("test.analyze.doc.withWrongPrediction")) {
accept = accept || !multiLabel.equals(prediction);
}
return accept;
}
).mapToObj(i -> {
MultiLabel multiLabel = dataSet.getMultiLabels()[i];
MultiLabel prediction = mlLogisticRegression.predict(dataSet.getRow(i));
List<Integer> classes = new ArrayList<Integer>();
for (int k = 0; k < dataSet.getNumClasses(); k++) {
boolean condition1 = multiLabel.matchClass(k) && prediction.matchClass(k) && config.getBoolean("test.analyze.class.truePositive");
boolean condition2 = !multiLabel.matchClass(k) && !prediction.matchClass(k) && config.getBoolean("test.analyze.class.trueNegative");
boolean condition3 = !multiLabel.matchClass(k) && prediction.matchClass(k) && config.getBoolean("test.analyze.class.falsePositive");
boolean condition4 = multiLabel.matchClass(k) && !prediction.matchClass(k) && config.getBoolean("test.analyze.class.falseNegative");
boolean condition5 = k<mlLogisticRegression.getNumClasses();
boolean accept = (condition1 || condition2 || condition3 || condition4) && condition5;
if (accept) {
classes.add(k);
}
}
return MLLogisticRegressionInspector.analyzePrediction(mlLogisticRegression, dataSet, i, classes, limit);
}
)
.collect(Collectors.toList());
int numDocsPerFile = config.getInt("test.analyze.numDocsPerFile");
int numFiles = (int)Math.ceil((double)analysisList.size()/numDocsPerFile);
for (int i=0;i<numFiles;i++){
int start = i;
int end = i+numDocsPerFile;
List<MultiLabelPredictionAnalysis> partition = new ArrayList<>();
for (int a=start;a<end && a<analysisList.size();a++){
partition.add(analysisList.get(a));
}
ObjectMapper mapper = new ObjectMapper();
String fileName = config.getString("test.analyze.file");
int suffixIndex = fileName.lastIndexOf(".json");
if (suffixIndex==-1){
suffixIndex=fileName.length();
}
String file = fileName.substring(0, suffixIndex)+"_"+(i+1)+".json";
mapper.writeValue(new File(config.getString("output.folder"),file), partition);
}
}
}
private static void verify(Config config) throws Exception{
String input = config.getString("input.folder");
MultiLabelClfDataSet dataSet = TRECFormat.loadMultiLabelClfDataSet(new File(input,"train.trec"),
DataSetType.ML_CLF_SPARSE, true);
File modelFile = new File(config.getString("output.folder"),config.getString("output.model"));
MLLogisticRegression mlLogisticRegression = MLLogisticRegression.deserialize(modelFile);
if (config.getBoolean("verify.topFeatures")){
int limit = config.getInt("verify.topFeatures.limit");
List<TopFeatures> topFeaturesList = IntStream.range(0, dataSet.getNumClasses())
.mapToObj(k -> MLLogisticRegressionInspector.topFeatures(mlLogisticRegression, k, limit))
.collect(Collectors.toList());
ObjectMapper mapper = new ObjectMapper();
String file = config.getString("verify.topFeatures.file");
mapper.writeValue(new File(config.getString("output.folder"),file), topFeaturesList);
}
if (config.getBoolean("verify.analyze")){
int limit = config.getInt("verify.analyze.rule.limit");
List<MultiLabelPredictionAnalysis> analysisList = IntStream.range(0,dataSet.getNumDataPoints()).parallel().filter(
i -> {
MultiLabel multiLabel = dataSet.getMultiLabels()[i];
MultiLabel prediction = mlLogisticRegression.predict(dataSet.getRow(i));
boolean accept = false;
if (config.getBoolean("verify.analyze.doc.withRightPrediction")) {
accept = accept || multiLabel.equals(prediction);
}
if (config.getBoolean("verify.analyze.doc.withWrongPrediction")) {
accept = accept || !multiLabel.equals(prediction);
}
return accept;
}
).mapToObj(i -> {
MultiLabel multiLabel = dataSet.getMultiLabels()[i];
MultiLabel prediction = mlLogisticRegression.predict(dataSet.getRow(i));
List<Integer> classes = new ArrayList<Integer>();
for (int k = 0; k < dataSet.getNumClasses(); k++) {
boolean condition1 = multiLabel.matchClass(k) && prediction.matchClass(k) && config.getBoolean("verify.analyze.class.truePositive");
boolean condition2 = !multiLabel.matchClass(k) && !prediction.matchClass(k) && config.getBoolean("verify.analyze.class.trueNegative");
boolean condition3 = !multiLabel.matchClass(k) && prediction.matchClass(k) && config.getBoolean("verify.analyze.class.falsePositive");
boolean condition4 = multiLabel.matchClass(k) && !prediction.matchClass(k) && config.getBoolean("verify.analyze.class.falseNegative");
boolean accept = condition1 || condition2 || condition3 || condition4;
if (accept) {
classes.add(k);
}
}
return MLLogisticRegressionInspector.analyzePrediction(mlLogisticRegression, dataSet, i, classes, limit);
}
)
.collect(Collectors.toList());
int numDocsPerFile = config.getInt("verify.analyze.numDocsPerFile");
int numFiles = (int)Math.ceil((double)analysisList.size()/numDocsPerFile);
for (int i=0;i<numFiles;i++){
int start = i;
int end = i+numDocsPerFile;
List<MultiLabelPredictionAnalysis> partition = new ArrayList<>();
for (int a=start;a<end && a<analysisList.size();a++){
partition.add(analysisList.get(a));
}
ObjectMapper mapper = new ObjectMapper();
String fileName = config.getString("verify.analyze.file");
int suffixIndex = fileName.lastIndexOf(".json");
if (suffixIndex==-1){
suffixIndex=fileName.length();
}
String file = fileName.substring(0,suffixIndex)+"_"+(i+1)+".json";
mapper.writeValue(new File(config.getString("output.folder"),file), partition);
}
}
}
} |
package org.kairosdb.loadtest;
import org.kairosdb.client.Client;
import org.kairosdb.client.HttpClient;
import org.kairosdb.client.TelnetClient;
import org.kairosdb.client.builder.*;
import org.kairosdb.client.response.*;
import org.kairosdb.client.response.grouping.DefaultGroupResult;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URISyntaxException;
import java.util.List;
public class Main
{
public static final String DATASTORE_QUERY_TIME = "kairosdb.datastore.query_time";
public static final String KEY_QUERY_TIME = "kairosdb.datastore.cassandra.key_query_time";
public static final String HTTP_QUERY_TIME = "kairosdb.http.query_time";
public static final String HTTP_REQUEST_TIME = "kairosdb.http.request_time";
//private static final long LOAD_TEST_SIZE = 1000000L;
private static final long LOAD_TEST_SIZE = 10000;
private final HttpClient m_httpClient;
private TelnetClient m_telnetClient;
public static void main(String[] args) throws IOException, URISyntaxException, DataFormatException, InterruptedException
{
PrintStream printStream;
if (args.length == 1)
printStream = new PrintStream(new File(args[0]));
else
printStream = System.out;
printStream.println(RunData.printHeader());
//Main main = new Main("kairos-mini", 4242);
Main main = new Main("localhost", 4242);
//Start 1 million load test
for (int rowCount = 1; rowCount < 16; rowCount ++)
{
RunData rd = new RunData(rowCount);
String metricName = "load_1million_"+rowCount+"_rows";
rd.setLoadTime(main.loadTelnet(metricName, rowCount, (LOAD_TEST_SIZE / rowCount)));
Thread.sleep(2000);
main.queryMetric(metricName, rd);
printStream.println(rd.toString());
}
for (int rowCount = 16; rowCount <= 1024; rowCount *= 2)
{
RunData rd = new RunData(rowCount);
String metricName = "load_1million_"+rowCount+"_rows";
rd.setLoadTime(main.loadTelnet(metricName, rowCount, (LOAD_TEST_SIZE / rowCount)));
Thread.sleep(2000);
main.queryMetric(metricName, rd);
printStream.println(rd.toString());
}
//main.loadTelnet("query_test_60k_big_tags", 60000, 10);
main.close();
}
public Main(String host, int port) throws IOException
{
m_telnetClient = new TelnetClient(host, port);
m_httpClient = new HttpClient("http://"+host+":8080");
}
public void close() throws IOException
{
m_telnetClient.shutdown();
}
private long getDataPoint(Query query) throws DataFormatException
{
Result firstResultByGroup = query.getFirstResultByGroup(new DefaultGroupResult("type", "number"));
if (firstResultByGroup != null)
{
List<DataPoint> dataPoints = firstResultByGroup.getDataPoints();
if (dataPoints.size() != 0)
return (dataPoints.get(0).longValue());
}
return -1;
}
public void queryMetric(String metricName, RunData runData) throws IOException, URISyntaxException, DataFormatException, InterruptedException
{
QueryBuilder qb = QueryBuilder.getInstance();
qb.setStart(1, TimeUnit.MINUTES);
qb.addMetric(metricName);
long start = System.currentTimeMillis();
QueryResponse queryResponse = m_httpClient.query(qb);
long end = System.currentTimeMillis();
if (queryResponse.getStatusCode() != 200)
return;
runData.setSampleSize(queryResponse.getQueries().get(0).getSampleSize());
runData.setClientQueryTime(end - start);
Thread.sleep(1000);
//get stats of above query
qb = QueryBuilder.getInstance();
qb.setStart(1, TimeUnit.MINUTES);
QueryMetric queryMetric = qb.addMetric(DATASTORE_QUERY_TIME);
queryMetric.setOrder(QueryMetric.Order.DESCENDING);
queryMetric.setLimit(1);
queryMetric = qb.addMetric(KEY_QUERY_TIME);
queryMetric.setOrder(QueryMetric.Order.DESCENDING);
queryMetric.setLimit(1);
queryMetric = qb.addMetric(HTTP_QUERY_TIME);
queryMetric.setOrder(QueryMetric.Order.DESCENDING);
queryMetric.setLimit(1);
queryMetric = qb.addMetric(HTTP_REQUEST_TIME);
queryMetric.setOrder(QueryMetric.Order.DESCENDING);
queryMetric.setLimit(1);
QueryResponse response = m_httpClient.query(qb);
//System.out.println(response.getStatusCode());
runData.setKairosDatastoreQueryTime(getDataPoint(response.getQueryResponse(DATASTORE_QUERY_TIME)));
runData.setKairosKeyQueryTime(getDataPoint(response.getQueryResponse(KEY_QUERY_TIME)));
runData.setKairosQueryTime(getDataPoint(response.getQueryResponse(HTTP_QUERY_TIME)));
runData.setKairosRequestTime(getDataPoint(response.getQueryResponse(HTTP_REQUEST_TIME)));
}
public long loadTelnet(String metricName, long rows, long width) throws IOException
{
long start = System.currentTimeMillis();
loadTelnetInternal(metricName, rows, width);
long end = System.currentTimeMillis();
return (end - start);
}
private void loadTelnetInternal(String metricName, long rows, long width) throws IOException
{
//Start time is the current time minus the width of each row.
//So if the width is 10 then the data will be inserted in the last 10 milliseconds.
long start = System.currentTimeMillis() - width;
//PrintWriter os = new PrintWriter(sock.getOutputStream());
long i = 0;
for (; i < width; i++)
{
for (long rowCount = 0L; rowCount < rows; rowCount++)
{
//We add extra tags to make the data larger
MetricBuilder mb = MetricBuilder.getInstance();
mb.addMetric(metricName).addDataPoint(i+start, 42).addTag("row", String.valueOf(rowCount)).addTag("host", "abc.123.ethernet.com").addTag("customer_id", "thompsonrouters");
m_telnetClient.pushMetrics(mb);
//os.println("put " + testName + " " + String.valueOf(i + start) + " 42 row=" + rowCount + " host=abc.123.ethernet.com customer_id=thompsonrouters");
}
//if (i % 10 == 0)
}
}
} |
package org.mvel;
import static org.mvel.DataConversion.canConvert;
import static org.mvel.Operator.*;
import static org.mvel.PropertyAccessor.get;
import org.mvel.integration.VariableResolverFactory;
import org.mvel.util.ExecutionStack;
import static org.mvel.util.ParseTools.containsCheck;
import static org.mvel.util.PropertyTools.*;
import org.mvel.util.Stack;
import org.mvel.util.StringAppender;
import static java.lang.Class.forName;
import static java.lang.String.valueOf;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static java.util.regex.Pattern.compile;
public class AcceleratedParser extends AbstractParser {
private final int roundingMode = BigDecimal.ROUND_HALF_DOWN;
private final TokenIterator tokens;
private final Stack stk = new ExecutionStack();
public AcceleratedParser(FastTokenIterator tokens) {
this.tokens = new FastTokenIterator(tokens);
}
public Object execute(Object ctx, VariableResolverFactory variableFactory) {
Token tk;
Integer operator;
while ((tk = tokens.nextToken()) != null) {
// assert debug("\nSTART_FRAME <<" + tk + ">> STK_SIZE=" + stk.size() + "; STK_PEEK=" + stk.peek() + "; TOKEN#=" + tokens.index());
if (stk.isEmpty()) {
stk.push(tk.getReducedValueAccelerated(ctx, ctx, variableFactory));
}
if (!tk.isOperator()) {
continue;
}
switch (reduceBinary(operator = tk.getOperator())) {
case-1:
// assert debug("FRAME_KILL_PROC");
return stk.pop();
case 0:
// assert debug("FRAME_CONTINUE");
break;
case 1:
// assert debug("FRAME_NEXT");
continue;
}
if (!tokens.hasMoreTokens()) return stk.pop();
stk.push(tokens.nextToken().getReducedValueAccelerated(ctx, ctx, variableFactory), operator);
reduceTrinary();
}
return stk.peek();
}
/**
* This method is called to subEval a binary statement (or junction). The difference between a binary and
* trinary statement, as far as the parser is concerned is that a binary statement has an entrant state,
* where-as a trinary statement does not. Consider: (x && y): in this case, x will be reduced first, and
* therefore will have a value on the stack, so the parser will then process the next statement as a binary,
* which is (&& y).
* <p/>
* You can also think of a binary statement in terms of: ({stackvalue} op value)
*
* @param o - operator
* @return int - behaviour code
*/
private int reduceBinary(int o) {
// assert debug("BINARY_OP " + o + " PEEK=<<" + stk.peek() + ">>");
switch (o) {
case AND:
if (stk.peek() instanceof Boolean && !((Boolean) stk.peek())) {
// assert debug("STMT_UNWIND");
if (unwindStatement()) {
return -1;
}
else {
stk.clear();
return 1;
}
}
else {
stk.discard();
return 1;
}
case OR:
if (stk.peek() instanceof Boolean && ((Boolean) stk.peek())) {
// assert debug("STMT_UNWIND");
if (unwindStatement()) {
return -1;
}
else {
stk.clear();
return 1;
}
}
else {
stk.discard();
return 1;
}
case TERNARY:
if (!(Boolean) stk.pop()) {
skipToOperator(Operator.TERNARY_ELSE);
}
stk.clear();
return 1;
case TERNARY_ELSE:
return -1;
case END_OF_STMT:
/**
* Assignments are a special scenario for dealing with the stack. Assignments are basically like
* held-over failures that basically kickstart the parser when an assignment operator is is
* encountered. The originating token is captured, and the the parser is told to march on. The
* resultant value on the stack is then used to populate the target variable.
*
* The other scenario in which we don't want to wipe the stack, is when we hit the end of the
* statement, because that top stack value is the value we want back from the parser.
*/
if ((fields & Token.ASSIGN) != 0) {
return -1;
}
else if (!hasNoMore()) {
stk.clear();
}
return 1;
}
return 0;
}
/**
* This method is called when we reach the point where we must subEval a trinary operation in the expression.
* (ie. val1 op val2). This is not the same as a binary operation, although binary operations would appear
* to have 3 structures as well. A binary structure (or also a junction in the expression) compares the
* current state against 2 downrange structures (usually an op and a val).
*/
private void reduceTrinary() {
Object v1 = null, v2;
Integer operator;
try {
while (stk.size() > 1) {
operator = (Integer) stk.pop();
v1 = processToken(stk.pop());
v2 = processToken(stk.pop());
// assert debug("DO_TRINARY <<OPCODE_" + operator + ">> register1=" + v1 + "; register2=" + v2);
switch (operator) {
case ADD:
if (v1 instanceof BigDecimal && v2 instanceof BigDecimal) {
stk.push(((BigDecimal) v1).add((BigDecimal) v2));
}
else {
stk.push(valueOf(v2) + valueOf(v1));
}
break;
case SUB:
stk.push(((BigDecimal) v2).subtract(((BigDecimal) v1)));
break;
case DIV:
stk.push(((BigDecimal) v2).divide(((BigDecimal) v1), 20, roundingMode));
break;
case MULT:
stk.push(((BigDecimal) v2).multiply((BigDecimal) v1));
break;
case MOD:
stk.push(((BigDecimal) v2).remainder((BigDecimal) v1));
break;
case EQUAL:
if (v1 instanceof BigDecimal && v2 instanceof BigDecimal) {
stk.push(((BigDecimal) v2).compareTo((BigDecimal) v1) == 0);
}
else if (v1 != null)
stk.push(v1.equals(v2));
else if (v2 != null)
stk.push(v2.equals(v1));
else
stk.push(v1 == v2);
break;
case NEQUAL:
if (v1 instanceof BigDecimal && v2 instanceof BigDecimal) {
stk.push(((BigDecimal) v2).compareTo((BigDecimal) v1) != 0);
}
else if (v1 != null)
stk.push(!v1.equals(v2));
else if (v2 != null)
stk.push(!v2.equals(v1));
else
stk.push(v1 != v2);
break;
case GTHAN:
stk.push(((BigDecimal) v2).compareTo((BigDecimal) v1) == 1);
break;
case LTHAN:
stk.push(((BigDecimal) v2).compareTo((BigDecimal) v1) == -1);
break;
case GETHAN:
stk.push(((BigDecimal) v2).compareTo((BigDecimal) v1) >= 0);
break;
case LETHAN:
stk.push(((BigDecimal) v2).compareTo((BigDecimal) v1) <= 0);
break;
case AND:
if (v2 instanceof Boolean && v1 instanceof Boolean) {
stk.push(((Boolean) v2) && ((Boolean) v1));
break;
}
else if (((Boolean) v2)) {
stk.push(v2, Operator.AND, v1);
}
return;
case OR:
if (v2 instanceof Boolean && v1 instanceof Boolean) {
stk.push(((Boolean) v2) || ((Boolean) v1));
break;
}
else {
stk.push(v2, Operator.OR, v1);
return;
}
case CHOR:
if (!isEmpty(v2) || !isEmpty(v1)) {
stk.clear();
stk.push(!isEmpty(v2) ? v2 : v1);
return;
}
else stk.push(null);
break;
case REGEX:
stk.push(compile(valueOf(v1)).matcher(valueOf(v2)).matches());
break;
case INSTANCEOF:
if (v1 instanceof Class)
stk.push(((Class) v1).isInstance(v2));
else
stk.push(forName(valueOf(v1)).isInstance(v2));
break;
case CONVERTABLE_TO:
if (v1 instanceof Class)
stk.push(canConvert(v2.getClass(), (Class) v1));
else
stk.push(canConvert(v2.getClass(), forName(valueOf(v1))));
break;
case CONTAINS:
stk.push(containsCheck(v2, v1));
break;
case BW_AND:
stk.push(asInt(v2) & asInt(v1));
break;
case BW_OR:
stk.push(asInt(v2) | asInt(v1));
break;
case BW_XOR:
stk.push(asInt(v2) ^ asInt(v1));
break;
case BW_SHIFT_LEFT:
stk.push(asInt(v2) << asInt(v1));
break;
case BW_USHIFT_LEFT:
int iv2 = asInt(v2);
if (iv2 < 0) iv2 *= -1;
stk.push(iv2 << asInt(v1));
break;
case BW_SHIFT_RIGHT:
stk.push(asInt(v2) >> asInt(v1));
break;
case BW_USHIFT_RIGHT:
stk.push(asInt(v2) >>> asInt(v1));
break;
case STR_APPEND:
stk.push(new StringAppender(valueOf(v2)).append(valueOf(v1)).toString());
break;
case PROJECTION:
try {
List<Object> list = new ArrayList<Object>(((Collection) v1).size());
for (Object o : (Collection) v1) {
list.add(get(valueOf(v2), o));
}
stk.push(list);
}
catch (ClassCastException e) {
throw new ParseException("projections can only be peformed on collections");
}
break;
case SOUNDEX:
stk.push(Soundex.soundex(valueOf(v1)).equals(Soundex.soundex(valueOf(v2))));
break;
case SIMILARITY:
stk.push(similarity(valueOf(v1), valueOf(v2)));
break;
}
}
}
catch (ClassCastException e) {
if ((fields & Token.LOOKAHEAD) == 0) {
/**
* This will allow for some developers who like messy expressions to compileAccessor
* away with some messy constructs like: a + b < c && e + f > g + q instead
* of using brackets like (a + b < c) && (e + f > g + q)
*/
fields |= Token.LOOKAHEAD;
Token tk = nextToken();
if (tk != null) {
stk.push(v1, nextToken(), tk.getOperator());
reduceTrinary();
return;
}
}
throw new CompileException("syntax error or incomptable types", expr, cursor, e);
}
catch (Exception e) {
throw new CompileException("failed to subEval expression", e);
}
}
private static int asInt(final Object o) {
return ((BigDecimal) o).intValue();
}
private Object processToken(Object operand) {
setFieldFalse(Token.EVAL_RIGHT);
if (operand instanceof BigDecimal) {
return operand;
}
else if (isNumber(operand)) {
return new BigDecimal(valueOf(operand));
}
else {
return operand;
}
}
private boolean hasNoMore() {
return !tokens.hasMoreTokens();
}
private boolean unwindStatement() {
//noinspection StatementWithEmptyBody
while (tokens.hasMoreTokens() && !tokens.nextToken().isOperator(Operator.END_OF_STMT)) ;
return !tokens.hasMoreTokens();
}
@SuppressWarnings({"StatementWithEmptyBody"})
private void skipToOperator(int operator) {
while (tokens.hasMoreTokens() && !tokens.nextToken().isOperator(operator)) ;
}
} |
package org.mvel.ast;
import org.mvel.ASTNode;
import static org.mvel.AbstractParser.getCurrentThreadParserContext;
import org.mvel.Accessor;
import org.mvel.CompileException;
import org.mvel.ParserContext;
import org.mvel.integration.VariableResolverFactory;
import org.mvel.optimizers.AccessorOptimizer;
import static org.mvel.optimizers.OptimizerFactory.getThreadAccessorOptimizer;
import org.mvel.util.ArrayTools;
import static org.mvel.util.ArrayTools.findFirst;
import static java.lang.System.arraycopy;
/**
* @author Christopher Brock
*/
public class NewObjectNode extends ASTNode {
private transient Accessor newObjectOptimizer;
private String className;
public NewObjectNode(char[] expr, int fields) {
super(expr, fields);
updateClassName();
if ((fields & COMPILE_IMMEDIATE) != 0) {
ParserContext pCtx = getCurrentThreadParserContext();
if (pCtx != null && pCtx.hasImport(className)) {
egressType = pCtx.getImport(className);
}
else {
try {
egressType = Thread.currentThread().getContextClassLoader().loadClass(className);
// egressType = Class.forName(className);
}
catch (ClassNotFoundException e) {
// throw new CompileException("class not found: " + name, e);
}
}
if (egressType != null) {
rewriteClassReferenceToFQCN();
}
}
}
private void rewriteClassReferenceToFQCN() {
String FQCN = egressType.getName();
if (className.indexOf('.') == -1) {
int idx = ArrayTools.findFirst('(', name);
if (idx == -1) {
arraycopy(FQCN.toCharArray(), 0, this.name = new char[idx = FQCN.length()], 0, idx);
}
else {
char[] newName = new char[FQCN.length() + (name.length - idx)];
arraycopy(FQCN.toCharArray(), 0, newName, 0, FQCN.length());
arraycopy(name, idx, newName, FQCN.length(), (name.length - idx));
this.name = newName;
}
updateClassName();
}
}
private void updateClassName() {
int endRange = findFirst('(', name);
if (endRange == -1) {
className = new String(name);
}
else {
className = new String(name, 0, findFirst('(', name));
}
}
public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) {
if (newObjectOptimizer == null) {
if (egressType == null) {
/**
* This means we couldn't resolve the type at the time this AST node was created, which means
* we have to attempt runtime resolution.
*/
if (factory != null && factory.isResolveable(className)) {
try {
egressType = (Class) factory.getVariableResolver(className).getValue();
rewriteClassReferenceToFQCN();
}
catch (ClassCastException e) {
throw new CompileException("cannot construct object: " + className + " is not a class reference", e);
}
}
}
AccessorOptimizer optimizer = getThreadAccessorOptimizer();
newObjectOptimizer = optimizer.optimizeObjectCreation(name, ctx, thisValue, factory);
/**
* Check to see if the optimizer actually produced the object during optimization. If so,
* we return that value now.
*/
if (optimizer.getResultOptPass() != null) {
egressType = optimizer.getEgressType();
return optimizer.getResultOptPass();
}
}
return newObjectOptimizer.getValue(ctx, thisValue, factory);
}
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
return getReducedValueAccelerated(ctx, thisValue, factory);
}
public Accessor getNewObjectOptimizer() {
return newObjectOptimizer;
}
} |
package edu.ufl.cise.cnt5106c.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
public class MergeFile {
private static String FILE_NAME = "ImageFile.jpg";
public static void main(String[] args) {
File ofile = new File("ImageFile2.jpg");
FileOutputStream fos;
FileInputStream fis;
byte[] fileBytes;
int bytesRead = 0;
List<File> list = new ArrayList<>();
for (int i = 0; i < 211; i++) {
list.add(new File("parts/" + FILE_NAME + ".part" + i));
}
try {
fos = new FileOutputStream(ofile, true);
for (File file : list) {
fis = new FileInputStream(file);
fileBytes = new byte[(int) file.length()];
bytesRead = fis.read(fileBytes, 0, (int) file.length());
assert (bytesRead == fileBytes.length);
assert (bytesRead == (int) file.length());
fos.write(fileBytes);
fos.flush();
fileBytes = null;
fis.close();
fis = null;
}
fos.close();
fos = null;
} catch (Exception exception) {
exception.printStackTrace();
}
}
} |
package extracells.gridblock;
import appeng.api.networking.*;
import appeng.api.networking.storage.IStorageGrid;
import appeng.api.parts.PartItemStack;
import appeng.api.storage.IMEMonitor;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.util.AEColor;
import appeng.api.util.DimensionalCoord;
import extracells.part.PartECBase;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.EnumSet;
public class ECBaseGridBlock implements IGridBlock {
protected AEColor color;
protected IGrid grid;
protected int usedChannels;
protected PartECBase host;
public ECBaseGridBlock(PartECBase _host) {
host = _host;
}
@Override
public double getIdlePowerUsage() {
return host.getPowerUsage();
}
@Override
public EnumSet<GridFlags> getFlags() {
return EnumSet.of(GridFlags.REQUIRE_CHANNEL);
}
@Override
public final boolean isWorldAccessible() {
return false;
}
@Override
public final DimensionalCoord getLocation() {
return host.getLocation();
}
@Override
public final AEColor getGridColor() {
return color == null ? AEColor.Transparent : color;
}
@Override
public void onGridNotification(GridNotification notification) {
}
@Override
public final void setNetworkStatus(IGrid _grid, int _usedChannels) {
grid = _grid;
usedChannels = _usedChannels;
}
@Override
public final EnumSet<ForgeDirection> getConnectableSides() {
return EnumSet.noneOf(ForgeDirection.class);
}
@Override
public IGridHost getMachine() {
return host;
}
@Override
public void gridChanged() {
}
@Override
public ItemStack getMachineRepresentation() {
return host.getItemStack(PartItemStack.Network);
}
public IMEMonitor<IAEFluidStack> getFluidMonitor() {
IGridNode node = host.getGridNode();
if (node == null)
return null;
IGrid grid = node.getGrid();
if (grid == null)
return null;
IStorageGrid storageGrid = grid.getCache(IStorageGrid.class);
if (storageGrid == null)
return null;
return storageGrid.getFluidInventory();
}
} |
package io.cfp.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.cfp.dto.TalkUser;
import io.cfp.dto.user.Schedule;
import io.cfp.dto.user.UserProfil;
import io.cfp.entity.Event;
import io.cfp.entity.Role;
import io.cfp.entity.Talk;
import io.cfp.repository.TalkRepo;
import io.cfp.service.TalkUserService;
import io.cfp.service.email.EmailingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
@RestController
@RequestMapping(value = { "/v0/schedule", "/api/schedule" }, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ScheduleController {
private static final Logger LOG = LoggerFactory.getLogger(ScheduleController.class);
private final TalkUserService talkUserService;
private final TalkRepo talks;
private final EmailingService emailingService;
@Autowired
public ScheduleController(TalkUserService talkUserService, TalkRepo talks, EmailingService emailingService) {
super();
this.talkUserService = talkUserService;
this.talks = talks;
this.emailingService = emailingService;
}
@RequestMapping(method = RequestMethod.GET)
public List<Schedule> getSchedule() {
final List<Talk> all = talks.findByEventIdAndStatesFetch(Event.current(), Collections.singleton(Talk.State.ACCEPTED));
return all.stream().map(t -> {
Schedule schedule = new Schedule(t.getId(), t.getName(), t.getDescription());
// speakers
String spreakers = t.getUser().getFirstname() + " " + t.getUser().getLastname();
if (t.getCospeakers() != null) {
spreakers += ", " + t.getCospeakers().stream().map(c -> c.getFirstname() + " " + c.getLastname()).collect(Collectors.joining(", "));
}
schedule.setSpeakers(spreakers);
// event_type
schedule.setEventType(t.getTrack().getLibelle());
schedule.setEventStart(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(t.getDate().toInstant()));
schedule.setEventEnd(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(t.getDate().toInstant().plus(t.getDuree(), ChronoUnit.MINUTES)));
schedule.setVenue(t.getRoom() != null ? t.getRoom().getName() : "TBD");
return schedule;
}).collect(toList());
}
/**
* Get all All talks.
*
* @return Confirmed talks in "LikeBox" format.
*/
@RequestMapping(value = "/confirmed", method = RequestMethod.GET)
@Secured(Role.ADMIN)
public List<Schedule> getConfirmedScheduleList() {
List<TalkUser> talkUserList = talkUserService.findAll(Talk.State.CONFIRMED);
return getSchedules(talkUserList);
}
/**
* Get all ACCEPTED talks'speakers .
*
* @return Speakers Set
*/
@RequestMapping(value = "/accepted/speakers", method = RequestMethod.GET)
@Secured(Role.ADMIN)
public Set<UserProfil> getSpeakerList() {
List<TalkUser> talkUserList = talkUserService.findAll(Talk.State.ACCEPTED);
return talkUserList.stream().map(t -> t.getSpeaker()).collect(toSet());
}
/**
* Get all ACCEPTED talks.
*
* @return Accepted talks in "LikeBox" format.
*/
@RequestMapping(value = "/accepted", method = RequestMethod.GET)
@Secured(Role.ADMIN)
public List<Schedule> getScheduleList() {
List<TalkUser> talkUserList = talkUserService.findAll(Talk.State.ACCEPTED);
return getSchedules(talkUserList);
}
private List<Schedule> getSchedules(List<TalkUser> talkUserList) {
return talkUserList.stream().map(t -> {
Schedule schedule = new Schedule(t.getId(), t.getName(), t.getDescription());
// speakers
String spreakers = t.getSpeaker().getFirstname() + " " + t.getSpeaker().getLastname();
if (t.getCospeakers() != null) {
spreakers += ", " + t.getCospeakers().stream().map(c -> c.getFirstname() + " " + c.getLastname()).collect(Collectors.joining(", "));
}
schedule.setSpeakers(spreakers);
// event_type
schedule.setEventType(t.getTrackLabel());
return schedule;
}).collect(toList());
}
@RequestMapping(value = "", method = RequestMethod.POST, consumes = {"multipart/form-data", "multipart/mixed"})
@Secured(Role.ADMIN)
public ResponseEntity uploadSchedule(@RequestParam("file") MultipartFile file) throws IOException {
final Schedule[] schedules = new ObjectMapper().readValue(file.getBytes(), Schedule[].class);
for (Schedule talk : schedules) {
talkUserService.updateConfirmedTalk(talk.getId(), LocalDateTime.parse(talk.getEventStart(), DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}
return new ResponseEntity<>(HttpStatus.OK);
}
/**
* Notify by mails scheduling result.
*/
@RequestMapping(value = "/notification", method = RequestMethod.POST)
@Secured(Role.ADMIN)
public void notifyScheduling() {
List<Talk> refused = talks.findByEventIdAndStatesFetch(Event.current(), Collections.singleton(Talk.State.REFUSED));
List<Talk> accepted = talks.findByEventIdAndStatesFetch(Event.current(), Collections.singleton(Talk.State.ACCEPTED));
sendMailsWithTempo(accepted, refused);
}
/**
* To help Google Compute Engine we wait 2 s between 2 mails.
* @param accepted
* @param refused
*/
private void sendMailsWithTempo(List<Talk> accepted, List<Talk> refused) {
accepted.forEach(t -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
LOG.warn("Thread Interrupted Exception", e);
}
emailingService.sendSelectionned(t, Locale.FRENCH);
}
);
refused.forEach(t -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
LOG.warn("Thread Interrupted Exception", e);
}
emailingService.sendNotSelectionned(t, Locale.FRENCH);
});
}
} |
package org.rr.mobi4java;
import static org.rr.mobi4java.ByteUtils.getInt;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.rr.mobi4java.EXTHRecord.RECORD_TYPE;
import org.rr.mobi4java.exth.DateRecordDelegate;
import org.rr.mobi4java.exth.StringRecordDelegate;
class MobiUtils {
/**
* Remove the replacement character which is used by utf-8 to display an unknown character (often a black diamond with a white question
* mark or an empty square box).
*
* @param str The input string which should be cleaned.
* @return The cleaned input string.
*/
static String removeUtfReplacementCharacter(String str) {
return StringUtils.remove(str, "\uFFFD");
}
/**
* Remove those bytes which are sometimes found in mobi html markup but did not fit into a string.
*
* @param bytes The bytes which should be searched for bytes which did not belong to a string.
* @return A new byte array which was cleaned from non string fitting bytes.
*/
static byte[] removeRandomBytes(byte[] bytes) {
byte[] searchBytes = new byte[] { 0x00, 0x14, 0x15, 0x19, 0x1c, 0x1d, 0x12, 0x13, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
ByteArrayOutputStream out = new ByteArrayOutputStream(searchBytes.length);
for (byte b : bytes) {
if(Arrays.binarySearch(searchBytes, b) < 0) {
out.write(b);
}
}
return out.toByteArray();
}
/**
* Tries to guess what the image type (if any) of a file based on the file's "magic numbers," the first bytes of the file.
*
* @param data byte array to be tested for image data.
* @return <code>true</code> if an image was detected and <code>false</code> otherwise.
*/
static boolean isImage(byte[] data) {
if(data.length > 4) {
int b1 = getInt(data, 0, 1);
int b2 = getInt(data, 1, 1);
int b3 = getInt(data, 2, 1);
int b4 = getInt(data, 3, 1);
if (b1 == 0x47 && b2 == 0x49) {
return true; // image/gif
} else if (b1 == 0x89 && b2 == 0x50) {
return true; // image/png
} else if (b1 == 0xFF && b2 == 0xD8) {
return true; // image/jpeg
} else if (b1 == 0xFF && b2 == 0xD9) {
return true; // image/jpeg
} else if (b1 == 0x42 && b2 == 0x4D) {
return true; // image/bmp
} else if (b1 == 0x4D && b2 == 0x4D) {
return true; // Motorola byte order TIFF
} else if (b1 == 0x49 && b2 == 0x49) {
return true; // Intel byte order TIFF
} else if (b1 == 0x38 && b2 == 0x42) {
return true; // image/psd
} else if (b1 == 0x50 && b2 == 0x31) {
return true; // image/pbm
} else if (b1 == 0x50 && b2 == 0x34) {
return true; // image/pbm
} else if (b1 == 0x50 && b2 == 0x32) {
return true; // image/pgm
} else if (b1 == 0x50 && b2 == 0x35) {
return true; // image/pgm
} else if (b1 == 0x50 && b2 == 0x33) {
return true; // image/pgm
} else if (b1 == 0x50 && b2 == 0x36) {
return true; // image/pgm
} else if (b1 == 0x97 && b2 == 0x4A && b3 == 0x42 && b4 == 0x32) {
return true; // image/x-jbig2
}
}
return false;
}
private static int getLastContentIndex(MobiHeader mobiHeader, PDBHeader pdbHeader) {
int lastContentIndex = mobiHeader.getLastContentRecordNumber();
if(lastContentIndex <= 0) {
lastContentIndex = pdbHeader.getRecordCount();
}
return lastContentIndex;
}
static int getTextContentStartIndex(MobiHeader mobiHeader) {
int firstContentIndex = mobiHeader.getFirstContentRecordNumber();
if(firstContentIndex <= 0) {
firstContentIndex = 1; // text starts usually with at index 1
}
return firstContentIndex;
}
static int getTextContentEndIndex(MobiHeader mobiHeader, PDBHeader pdbHeader) {
int end = MobiUtils.getLastContentIndex(mobiHeader, pdbHeader);
if(mobiHeader.getFirstImageIndex() - 1 > 0) {
end = Math.min(end, mobiHeader.getFirstImageIndex() - 1);
}
if(mobiHeader.getFirstNonBookIndex() -1 > 0 && mobiHeader.getFirstNonBookIndex() -1 < end) {
end = mobiHeader.getFirstNonBookIndex() - 1;
}
return end;
}
static List<EXTHRecord> findRecordsByType(List<EXTHRecord> records, RECORD_TYPE type) {
List<EXTHRecord> found = new ArrayList<>();
for (EXTHRecord exthRecord : records) {
if(exthRecord.getRecordType() == type) {
found.add(exthRecord);
}
}
return found;
}
static List<StringRecordDelegate> createStringRecords(List<EXTHRecord> records, RECORD_TYPE type) {
List<EXTHRecord> stringRecords = MobiUtils.findRecordsByType(records, type);
List<StringRecordDelegate> stringRecordDelegates = new ArrayList<>(stringRecords.size());
for (EXTHRecord exthRecord : stringRecords) {
stringRecordDelegates.add(new StringRecordDelegate(exthRecord));
}
return stringRecordDelegates;
}
static List<DateRecordDelegate> createDateRecords(List<EXTHRecord> records, RECORD_TYPE type) {
List<EXTHRecord> stringRecords = MobiUtils.findRecordsByType(records, type);
List<DateRecordDelegate> dateRecordDelegates = new ArrayList<>(stringRecords.size());
for (EXTHRecord exthRecord : stringRecords) {
dateRecordDelegates.add(new DateRecordDelegate(exthRecord));
}
return dateRecordDelegates;
}
} |
package io.openshift.booster;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.StaticHandler;
import static io.vertx.core.http.HttpHeaders.CONTENT_TYPE;
public class HttpApplication extends AbstractVerticle {
protected static final String template = "Hello, %s!, is it me you're looking for";
@Override
public void start(Future<Void> future) {
// Create a router object.
Router router = Router.router(vertx);
router.get("/api/greeting").handler(this::greeting); |
package javax.time.format;
import static javax.time.calendrical.LocalDateTimeField.DAY_OF_MONTH;
import static javax.time.calendrical.LocalDateTimeField.DAY_OF_WEEK;
import static javax.time.calendrical.LocalDateTimeField.DAY_OF_YEAR;
import static javax.time.calendrical.LocalDateTimeField.HOUR_OF_DAY;
import static javax.time.calendrical.LocalDateTimeField.MINUTE_OF_HOUR;
import static javax.time.calendrical.LocalDateTimeField.MONTH_OF_YEAR;
import static javax.time.calendrical.LocalDateTimeField.NANO_OF_SECOND;
import static javax.time.calendrical.LocalDateTimeField.SECOND_OF_MINUTE;
import static javax.time.calendrical.LocalDateTimeField.WEEK_BASED_YEAR;
import static javax.time.calendrical.LocalDateTimeField.WEEK_OF_WEEK_BASED_YEAR;
import static javax.time.calendrical.LocalDateTimeField.YEAR;
import java.util.Locale;
import javax.time.DateTimes;
import javax.time.calendrical.DateTimeField;
/**
* Provides common implementations of {@code DateTimeFormatter}.
* <p>
* This utility class provides three different ways to obtain a formatter.
* <ul>
* <li>Using pattern letters, such as {@code yyyy-MMM-dd}
* <li>Using localized styles, such as {@code long} or {@code medium}
* <li>Using predefined constants, such as {@code isoLocalDate()}
* </ul>
*
* <h4>Implementation notes</h4>
* This is a thread-safe utility class.
* All returned formatters are immutable and thread-safe.
*/
public final class DateTimeFormatters {
/**
* Private constructor since this is a utility class.
*/
private DateTimeFormatters() {
}
public static DateTimeFormatter pattern(String pattern) {
return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter();
}
public static DateTimeFormatter pattern(String pattern, Locale locale) {
return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(locale);
}
/**
* Returns a locale specific date format.
* <p>
* This returns a formatter that will print/parse a date.
* The exact format pattern used varies by locale.
* <p>
* The locale is determined from the formatter. The formatter returned directly by
* this method will use the {@link Locale#getDefault() default locale}.
* The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
* on the result of this method.
* <p>
* Note that the localized pattern is looked up lazily.
* This {@code DateTimeFormatter} holds the style required and the locale,
* looking up the pattern required on demand.
*
* @param dateStyle the formatter style to obtain, not null
* @return the date formatter, not null
*/
public static DateTimeFormatter localizedDate(FormatStyle dateStyle) {
DateTimes.checkNotNull(dateStyle, "Date style must not be null");
return new DateTimeFormatterBuilder().appendLocalized(dateStyle, null).toFormatter();
}
/**
* Returns a locale specific time format.
* <p>
* This returns a formatter that will print/parse a time.
* The exact format pattern used varies by locale.
* <p>
* The locale is determined from the formatter. The formatter returned directly by
* this method will use the {@link Locale#getDefault() default locale}.
* The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
* on the result of this method.
* <p>
* Note that the localized pattern is looked up lazily.
* This {@code DateTimeFormatter} holds the style required and the locale,
* looking up the pattern required on demand.
*
* @param timeStyle the formatter style to obtain, not null
* @return the time formatter, not null
*/
public static DateTimeFormatter localizedTime(FormatStyle timeStyle) {
DateTimes.checkNotNull(timeStyle, "Time style must not be null");
return new DateTimeFormatterBuilder().appendLocalized(null, timeStyle).toFormatter();
}
/**
* Returns a locale specific date-time format, which is typically of short length.
* <p>
* This returns a formatter that will print/parse a date-time.
* The exact format pattern used varies by locale.
* <p>
* The locale is determined from the formatter. The formatter returned directly by
* this method will use the {@link Locale#getDefault() default locale}.
* The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
* on the result of this method.
* <p>
* Note that the localized pattern is looked up lazily.
* This {@code DateTimeFormatter} holds the style required and the locale,
* looking up the pattern required on demand.
*
* @param dateTimeStyle the formatter style to obtain, not null
* @return the date-time formatter, not null
*/
public static DateTimeFormatter localizedDateTime(FormatStyle dateTimeStyle) {
DateTimes.checkNotNull(dateTimeStyle, "Date-time style must not be null");
return new DateTimeFormatterBuilder().appendLocalized(dateTimeStyle, dateTimeStyle).toFormatter();
}
/**
* Returns a locale specific date and time format.
* <p>
* This returns a formatter that will print/parse a date-time.
* The exact format pattern used varies by locale.
* <p>
* The locale is determined from the formatter. The formatter returned directly by
* this method will use the {@link Locale#getDefault() default locale}.
* The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)}
* on the result of this method.
* <p>
* Note that the localized pattern is looked up lazily.
* This {@code DateTimeFormatter} holds the style required and the locale,
* looking up the pattern required on demand.
*
* @param dateStyle the date formatter style to obtain, not null
* @param timeStyle the time formatter style to obtain, not null
* @return the date, time or date-time formatter, not null
*/
public static DateTimeFormatter localizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle) {
DateTimes.checkNotNull(dateStyle, "Date style must not be null");
DateTimes.checkNotNull(timeStyle, "Time style must not be null");
return new DateTimeFormatterBuilder().appendLocalized(dateStyle, timeStyle).toFormatter();
}
/**
* Returns the ISO date formatter that prints/parses a local date without
* an offset, such as '2011-12-03'.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyy-MM-dd}
* <p>
* The year will print 4 digits, unless this is insufficient, in which
* case the full year will be printed together with a positive/negative sign.
*
* @return the ISO date formatter, not null
*/
public static DateTimeFormatter isoLocalDate() {
return ISO_LOCAL_DATE;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_LOCAL_DATE;
static {
ISO_LOCAL_DATE = new DateTimeFormatterBuilder()
.appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.appendLiteral('-')
.appendValue(MONTH_OF_YEAR, 2)
.appendLiteral('-')
.appendValue(DAY_OF_MONTH, 2)
.toFormatter();
}
/**
* Returns the ISO date formatter that prints/parses an offset date with
* an offset, such as '2011-12-03+01:00'.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyy-MM-ddZZZ}
* <p>
* The year will print 4 digits, unless this is insufficient, in which
* case the full year will be printed together with a positive/negative sign.
* <p>
* The offset will print and parse an offset with seconds even though that
* is not part of the ISO-8601 standard.
*
* @return the ISO date formatter, not null
*/
public static DateTimeFormatter isoOffsetDate() {
return ISO_OFFSET_DATE;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_OFFSET_DATE;
static {
ISO_OFFSET_DATE = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(ISO_LOCAL_DATE)
.appendOffsetId()
.toFormatter();
}
/**
* Returns the ISO date formatter that prints/parses a date, with the
* offset and zone if available, such as '2011-12-03', '2011-12-03+01:00'
* or '2011-12-03+01:00[Europe/Paris]'.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyy-MM-dd[ZZZ['['I']']]}
* <p>
* The year will print 4 digits, unless this is insufficient, in which
* case the full year will be printed together with a positive/negative sign.
* <p>
* The offset and time-zone identifier will be printed or parsed if present.
* The offset will print and parse an offset with seconds even though that
* is not part of the ISO-8601 standard.
*
* @return the ISO date formatter, not null
*/
public static DateTimeFormatter isoDate() {
return ISO_DATE;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_DATE;
static {
ISO_DATE = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(ISO_LOCAL_DATE)
.optionalStart()
.appendOffsetId()
.optionalStart()
.appendLiteral('[')
.appendZoneId()
.appendLiteral(']')
.toFormatter();
}
/**
* Returns the ISO time formatter that prints/parses a local time, without
* an offset such as '10:15:30'.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code HH:mm[:ss[.S]]}
* <p>
* The seconds will be printed if present in the input, thus a {@code LocalTime}
* will always print the seconds.
* The nanoseconds will be printed if non-zero.
* If non-zero, the minimum number of fractional second digits will printed.
*
* @return the ISO time formatter, not null
*/
public static DateTimeFormatter isoLocalTime() {
return ISO_LOCAL_TIME;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_LOCAL_TIME;
static {
ISO_LOCAL_TIME = new DateTimeFormatterBuilder()
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.optionalStart()
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.optionalStart()
.appendFraction(NANO_OF_SECOND, 0, 9)
.toFormatter();
}
/**
* Returns the ISO time formatter that prints/parses a local time, with
* an offset such as '10:15:30+01:00'.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code HH:mm[:ss[.S]]ZZZ}
* <p>
* The seconds will be printed if present in the input, thus an {@code OffsetTime}
* will always print the seconds.
* The nanoseconds will be printed if non-zero.
* If non-zero, the minimum number of fractional second digits will printed.
* <p>
* The offset will print and parse an offset with seconds even though that
* is not part of the ISO-8601 standard.
*
* @return the ISO time formatter, not null
*/
public static DateTimeFormatter isoOffsetTime() {
return ISO_OFFSET_TIME;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_OFFSET_TIME;
static {
ISO_OFFSET_TIME = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(ISO_LOCAL_TIME)
.appendOffsetId()
.toFormatter();
}
/**
* Returns the ISO time formatter that prints/parses a time, with the
* offset and zone if available, such as '10:15:30', '10:15:30+01:00'
* or '10:15:30+01:00[Europe/Paris]'.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code HH:mm[:ss[.S]][ZZZ['['I']']]}
* <p>
* The seconds will be printed if present in the input, thus a {@code LocalTime}
* will always print the seconds.
* The nanoseconds will be printed if non-zero.
* If non-zero, the minimum number of fractional second digits will printed.
* <p>
* The offset and time-zone identifier will be printed or parsed if present.
* The offset will print and parse an offset with seconds even though that
* is not part of the ISO-8601 standard.
*
* @return the ISO date formatter, not null
*/
public static DateTimeFormatter isoTime() {
return ISO_TIME;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_TIME;
static {
ISO_TIME = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(ISO_LOCAL_TIME)
.optionalStart()
.appendOffsetId()
.optionalStart()
.appendLiteral('[')
.appendZoneId()
.appendLiteral(']')
.toFormatter();
}
/**
* Returns the ISO date formatter that prints/parses a local date without
* an offset, such as '2011-12-03T10:15:30'.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyy-MM-dd'T'HH:mm[:ss[.S]]}
* <p>
* The year will print 4 digits, unless this is insufficient, in which
* case the full year will be printed together with a positive/negative sign.
* <p>
* The seconds will be printed if present in the input, thus a {@code LocalDateTime}
* will always print the seconds.
* The nanoseconds will be printed if non-zero.
* If non-zero, the minimum number of fractional second digits will printed.
*
* @return the ISO date formatter, not null
*/
public static DateTimeFormatter isoLocalDateTime() {
return ISO_LOCAL_DATE_TIME;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_LOCAL_DATE_TIME;
static {
ISO_LOCAL_DATE_TIME = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(ISO_LOCAL_DATE)
.appendLiteral('T')
.append(ISO_LOCAL_TIME)
.toFormatter();
}
/**
* Returns the ISO date formatter that prints/parses an offset date with
* an offset, such as '2011-12-03T10:15:30+01:00'.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyy-MM-dd'T'HH:mm[:ss[.S]]ZZZ}
* <p>
* The year will print 4 digits, unless this is insufficient, in which
* case the full year will be printed together with a positive/negative sign.
* <p>
* The seconds will be printed if present in the input, thus a {@code OffsetDateTime}
* will always print the seconds.
* The nanoseconds will be printed if non-zero.
* If non-zero, the minimum number of fractional second digits will printed.
* <p>
* The offset will print and parse an offset with seconds even though that
* is not part of the ISO-8601 standard.
*
* @return the ISO date formatter, not null
*/
public static DateTimeFormatter isoOffsetDateTime() {
return ISO_OFFSET_DATE_TIME;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_OFFSET_DATE_TIME;
static {
ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder()
.append(ISO_LOCAL_DATE_TIME)
.appendOffsetId()
.toFormatter();
}
/**
* Returns the ISO date formatter that prints/parses an offset date with
* a zone, such as '2011-12-03T10:15:30+01:00[Europe/Paris]'.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyy-MM-dd'T'HH:mm[:ss[.S]]ZZZ'['I']'}
* <p>
* The year will print 4 digits, unless this is insufficient, in which
* case the full year will be printed together with a positive/negative sign.
* <p>
* The seconds will be printed if present in the input, thus a {@code ZonedDateTime}
* will always print the seconds.
* The nanoseconds will be printed if non-zero.
* If non-zero, the minimum number of fractional second digits will printed.
* <p>
* The offset will print and parse an offset with seconds even though that
* is not part of the ISO-8601 standard.
*
* @return the ISO date formatter, not null
*/
public static DateTimeFormatter isoZonedDateTime() {
return ISO_ZONED_DATE_TIME;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_ZONED_DATE_TIME;
static {
ISO_ZONED_DATE_TIME = new DateTimeFormatterBuilder()
.append(ISO_LOCAL_DATE_TIME)
.appendOffsetId()
.appendLiteral('[')
.appendZoneId()
.appendLiteral(']')
.toFormatter();
}
/**
* Returns the ISO date formatter that prints/parses a date, with the
* offset and zone if available, such as '2011-12-03T10:15:30',
* '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyy-MM-dd'T'HH:mm[:ss[.S]][ZZZ['['I']']]}
* <p>
* The year will print 4 digits, unless this is insufficient, in which
* case the full year will be printed together with a positive/negative sign.
* <p>
* The seconds will be printed if present in the input, thus a {@code ZonedDateTime}
* will always print the seconds.
* The nanoseconds will be printed if non-zero.
* If non-zero, the minimum number of fractional second digits will printed.
* <p>
* The offset and time-zone identifier will be printed or parsed if present.
* The offset will print and parse an offset with seconds even though that
* is not part of the ISO-8601 standard.
*
* @return the ISO date formatter, not null
*/
public static DateTimeFormatter isoDateTime() {
return ISO_DATE_TIME;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_DATE_TIME;
static {
ISO_DATE_TIME = new DateTimeFormatterBuilder()
.append(ISO_LOCAL_DATE_TIME)
.optionalStart()
.appendOffsetId()
.optionalStart()
.appendLiteral('[')
.appendZoneId()
.appendLiteral(']')
.toFormatter();
}
/**
* Returns the ISO date formatter that prints/parses a date without an offset.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyy-DDD[ZZZ['['I']']]}
* <p>
* The year will print 4 digits, unless this is insufficient, in which
* case the full year will be printed together with a positive/negative sign.
* <p>
* The offset and time-zone identifier will be printed or parsed if present.
* The offset will print and parse an offset with seconds even though that
* is not part of the ISO-8601 standard.
*
* @return the ISO ordinal date formatter, not null
*/
public static DateTimeFormatter isoOrdinalDate() {
return ISO_ORDINAL_DATE;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_ORDINAL_DATE;
static {
ISO_ORDINAL_DATE = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.appendLiteral('-')
.appendValue(DAY_OF_YEAR, 3)
.optionalStart()
.appendOffsetId()
.optionalStart()
.appendLiteral('[')
.appendZoneId()
.appendLiteral(']')
.toFormatter();
}
/**
* Returns the ISO date formatter that prints/parses a date without an offset.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyy-Www-D[ZZZ['['I']']]}
* <p>
* The year will print 4 digits, unless this is insufficient, in which
* case the full year will be printed together with a positive/negative sign.
* <p>
* The offset and time-zone identifier will be printed or parsed if present.
* The offset will print and parse an offset with seconds even though that
* is not part of the ISO-8601 standard.
*
* @return the ISO week date formatter, not null
*/
public static DateTimeFormatter isoWeekDate() {
return ISO_WEEK_DATE;
}
/** Singleton date formatter. */
private static final DateTimeFormatter ISO_WEEK_DATE;
static {
ISO_WEEK_DATE = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(WEEK_BASED_YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.appendLiteral("-W")
.appendValue(WEEK_OF_WEEK_BASED_YEAR, 2)
.appendLiteral('-')
.appendValue(DAY_OF_WEEK, 1)
.optionalStart()
.appendOffsetId()
.optionalStart()
.appendLiteral('[')
.appendZoneId()
.appendLiteral(']')
.toFormatter();
}
/**
* Returns the ISO instant formatter that prints/parses an instant in UTC.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyy-MM-dd'T'HH:mm:ss.SZZZ}
* <p>
* The year will print 4 digits, unless this is insufficient, in which
* case the full year will be printed together with a positive/negative sign.
* <p>
* The offset will print and parse an offset with seconds even though that
* is not part of the ISO-8601 standard.
*
* @return the ISO instant formatter, not null
*/
public static DateTimeFormatter isoInstant() {
return ISO_INSTANT;
}
/** Singleton formatter. */
private static final DateTimeFormatter ISO_INSTANT;
static {
ISO_INSTANT = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendInstant()
.toFormatter();
}
/**
* Returns the ISO date formatter that prints/parses a date without an offset.
* <p>
* This is the ISO-8601 extended format:<br />
* {@code yyyyMMdd}
* <p>
* The year is limited to printing and parsing 4 digits, as the lack of
* separators makes it impossible to parse more than 4 digits.
*
* @return the ISO date formatter, not null
*/
public static DateTimeFormatter basicIsoDate() {
return BASIC_ISO_DATE;
}
/** Singleton date formatter. */
private static final DateTimeFormatter BASIC_ISO_DATE;
static {
BASIC_ISO_DATE = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(YEAR, 4)
.appendValue(MONTH_OF_YEAR, 2)
.appendValue(DAY_OF_MONTH, 2)
.optionalStart()
.appendOffset("Z", "+HHMM")
.optionalStart()
.appendLiteral('[')
.appendZoneId()
.appendLiteral(']')
.toFormatter();
}
/**
* Returns the RFC-1123 date-time formatter.
* <p>
* This is the RFC-1123 format: EEE, dd MMM yyyy HH:mm:ss Z.
* This is the updated replacement for RFC-822 which had a two digit year.
* <p>
* The year will print 4 digits, and only the range 0000 to 9999 is supported.
*
* @return the ISO date formatter, not null
*/
public static DateTimeFormatter rfc1123() {
return RFC_1123_DATE_TIME;
}
/** Singleton date formatter. */
private static final DateTimeFormatter RFC_1123_DATE_TIME;
static {
RFC_1123_DATE_TIME = new DateTimeFormatterBuilder()
.appendText(DAY_OF_WEEK, TextStyle.SHORT)
.appendLiteral(", ")
.appendValue(DAY_OF_MONTH, 2)
.appendLiteral(' ')
.appendText(MONTH_OF_YEAR, TextStyle.SHORT)
.appendLiteral(' ')
.appendValue(YEAR, 4, 4, SignStyle.NOT_NEGATIVE)
.appendLiteral(' ')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.appendLiteral(' ')
.appendOffset("Z", "+HHMM")
.toFormatter()
.withLocale(Locale.ENGLISH);
}
/**
* Gets the provider of text.
*
* @return the provider, not null
*/
public static DateTimeTextProvider getTextProvider() {
// TODO: obtain provider properly
return new SimpleDateTimeTextProvider();
}
/**
* Gets the provider of format styles.
*
* @return the provider, not null
*/
public static DateTimeFormatStyleProvider getFormatStyleProvider() {
// TODO: obtain provider properly
return new SimpleDateTimeFormatStyleProvider();
}
} |
package seedu.todo.ui;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map;
import seedu.todo.MainApp;
import seedu.todo.commons.exceptions.ParseException;
import seedu.todo.commons.util.StringUtil;
import seedu.todo.controllers.*;
public class InputHandler {
private static InputHandler instance;
private static final int MAX_HISTORY_SIZE = 20;
private static LinkedList<String> commandHistory = new LinkedList<String>();
private static ListIterator<String> commandHistoryIterator = commandHistory.listIterator();
private Controller handlingController = null;
protected InputHandler() {
// Prevent instantiation.
}
/**
* Gets the current input handler instance.
* @@author A0139812A
*/
public static InputHandler getInstance() {
if (instance == null) {
instance = new InputHandler();
}
return instance;
}
/**
* Pushes a command to the end of a LinkedList.
* Commands are stored like a queue, where the oldest items
* are at the start of the List and will be popped off first.
*
* @param command Command string
* @@author A0139812A
*/
private void pushCommand(String command) {
// Adds to the end of the LinkedList.
commandHistory.addLast(command);
// Truncates the list when it gets too big.
if (commandHistory.size() > MAX_HISTORY_SIZE) {
commandHistory.removeFirst();
}
// Create a new iterator, initialize position to point right at the end.
commandHistoryIterator = commandHistory.listIterator(commandHistory.size());
}
/**
* Gets the previous command from the command history. Successive calls will return commands earlier in history.
*
* @return The input command earlier than what was previously retrieved
* @@author A0139812A
*/
public String getPreviousCommandFromHistory() {
if (!commandHistoryIterator.hasPrevious()) {
return "";
}
return commandHistoryIterator.previous();
}
/**
* Gets the next command from the command history. Successive calls will return commands later in history.
*
* @return The input command later than what was previously retrieved
* @@author A0139812A
*/
public String getNextCommandFromHistory() {
if (!commandHistoryIterator.hasNext()) {
return "";
}
return commandHistoryIterator.next();
}
/**
* @@author A0093907W
*
* Processes the command. Returns true if the command was intercepted by a controller, false if otherwise.
* If the command was not intercepted by a controller, it means that the command was not recognized.
*/
public boolean processInput(String input) {
Map<String, String> aliases = MainApp.getConfig().getAliases();
String aliasedInput = StringUtil.replaceAliases(input, aliases);
Controller selectedController = null;
if (this.handlingController != null) {
selectedController = handlingController;
} else {
Controller[] controllers = instantiateAllControllers();
// Get controller which has the maximum confidence.
Controller maxController = getMaxController(aliasedInput, controllers);
// No controller exists with confidence > 0.
if (maxController == null) {
return false;
}
// Select best-matched controller.
selectedController = maxController;
}
// Process using best-matched controller.
try {
// Alias and unalias should not receive an aliasedInput for proper functioning.
if (selectedController.getClass() == AliasController.class ||
selectedController.getClass() == UnaliasController.class) {
selectedController.process(input);
} else {
selectedController.process(aliasedInput);
}
} catch (ParseException e) {
return false;
}
// Since command is not invalid, we push it to history
pushCommand(aliasedInput);
return true;
}
/**
* Get controller which has the maximum confidence.
*
* @param aliasedInput Input with aliases replaced appropriately
* @param controllers Array of instantiated controllers to test
* @return Controller with maximum confidence, null if all non-positive.
*/
private Controller getMaxController(String aliasedInput, Controller[] controllers) {
// Define the controller which returns the maximum confidence.
Controller maxController = null;
float maxConfidence = Integer.MIN_VALUE;
for (int i = 0; i < controllers.length; i++) {
float confidence = controllers[i].inputConfidence(aliasedInput);
// Don't consider controllers with non-positive confidence.
if (confidence <= 0) {
continue;
}
if (confidence > maxConfidence) {
maxConfidence = confidence;
maxController = controllers[i];
}
}
return maxController;
}
private Controller[] instantiateAllControllers() {
return new Controller[] { new AliasController(),
new UnaliasController(),
new HelpController(),
new AddController(),
new ListController(),
new DestroyController(),
new CompleteTaskController(),
new UncompleteTaskController(),
new UpdateController(),
new UndoController(),
new RedoController(),
new ConfigController(),
new ClearController(),
new FindController(),
new TagController(),
new UntagController(),
new ExitController() };
}
} |
package me.coley.recaf.config;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import me.coley.recaf.control.gui.GuiController;
import me.coley.recaf.plugin.PluginKeybinds;
import me.coley.recaf.util.Log;
import me.coley.recaf.util.OSUtil;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Keybind configuration.
*
* @author Matt
*/
public class ConfKeybinding extends Config {
/**
* Save current application to file.
*/
@Conf("binding.saveapp")
public Binding saveApp = KeybindingCreator.from(
Binding.from(KeyCode.CONTROL, KeyCode.E),
KeybindingCreator.OSBinding.from(OSUtil.MAC, Binding.from(KeyCode.META, KeyCode.E))
).buildKeyBindingForCurrentOS();
/**
* Save current work.
*/
@Conf("binding.save")
public Binding save = KeybindingCreator.from(
Binding.from(KeyCode.CONTROL, KeyCode.S),
KeybindingCreator.OSBinding.from(OSUtil.MAC, Binding.from(KeyCode.META, KeyCode.S))
).buildKeyBindingForCurrentOS();
/**
* Undo last change.
*/
@Conf("binding.undo")
public Binding undo = KeybindingCreator.from(
Binding.from(KeyCode.CONTROL, KeyCode.U),
KeybindingCreator.OSBinding.from(OSUtil.MAC, Binding.from(KeyCode.META, KeyCode.U))
).buildKeyBindingForCurrentOS();
/**
* Open find search.
*/
@Conf("binding.find")
public Binding find = KeybindingCreator.from(
Binding.from(KeyCode.CONTROL, KeyCode.F),
KeybindingCreator.OSBinding.from(OSUtil.MAC, Binding.from(KeyCode.META, KeyCode.F))
).buildKeyBindingForCurrentOS();
/**
* Close top-most window <i>(Except the main window)</i>
*/
@Conf("binding.close.window")
public Binding closeWindow = KeybindingCreator.from(
Binding.from(KeyCode.CONTROL, KeyCode.ESCAPE),
KeybindingCreator.OSBinding.from(OSUtil.MAC, Binding.from(KeyCode.META, KeyCode.ESCAPE))
).buildKeyBindingForCurrentOS();
/**
* Close current file/class tab.
*/
@Conf("binding.close.tab")
public Binding closeTab = KeybindingCreator.from(
Binding.from(KeyCode.CONTROL, KeyCode.W),
KeybindingCreator.OSBinding.from(OSUtil.MAC, Binding.from(KeyCode.META, KeyCode.W))
).buildKeyBindingForCurrentOS();
/**
* Goto the selected item's definition.
*/
@Conf("binding.gotodef")
public Binding gotoDef = Binding.from(KeyCode.F3);
/**
* Goto the selected item's definition.
*/
@Conf("binding.rename")
public Binding rename = KeybindingCreator.from(
Binding.from(KeyCode.CONTROL, KeyCode.R),
KeybindingCreator.OSBinding.from(OSUtil.MAC, Binding.from(KeyCode.META, KeyCode.R))
).buildKeyBindingForCurrentOS();
ConfKeybinding() {
super("keybinding");
}
@Override
public boolean supported(Class<?> type) {
return type.equals(Binding.class);
}
/**
* Register window-level keybinds.
*
* @param controller
* Controller to call actions on.
* @param stage
* Window to register keys on.
* @param scene
* Scene in the window.
*/
public void registerWindowKeys(GuiController controller, Stage stage, Scene scene) {
scene.setOnKeyReleased(e -> handleWindowKeyEvents(e, controller, stage, false));
}
/**
* Register window-level keybinds.
*
* @param controller
* Controller to call actions on.
* @param stage
* Window to register keys on.
* @param scene
* Scene in the window.
*/
public void registerMainWindowKeys(GuiController controller, Stage stage, Scene scene) {
scene.setOnKeyReleased(e -> handleWindowKeyEvents(e, controller, stage, true));
}
private void handleWindowKeyEvents(KeyEvent e, GuiController controller, Stage stage, boolean main) {
if(!main && closeWindow.match(e))
stage.close();
if(saveApp.match(e))
controller.windows().getMainWindow().saveApplication();
else {
// Custom bind support
PluginKeybinds.getInstance().getGlobalBinds().forEach((bind, action) -> {
try {
if (bind.match(e))
action.run();
} catch(Throwable t) {
Log.error(t, "Failed executing global keybind action");
}
});
}
}
/**
* Wrapper to act as bind utility.
*
* @author Matt
*/
public static class Binding extends ArrayList<String> {
/**
* @param string
* Series of keys for a keybind, split by '+'.
* @param mask
* Optional mask to include.
*
* @return Binding from keys + mask.
*/
public static Binding from(String string, KeyCode mask) {
String[] codes = string.split("\\+");
Stream<String> stream = Arrays.stream(codes);
if (mask != null)
stream = Stream.concat(Stream.of(mask.getName()), stream);
return stream.map(String::toLowerCase).collect(Collectors.toCollection(Binding::new));
}
/**
* @param event
* Key event.
*
* @return Binding from keys of the event.
*/
public static Binding from(KeyEvent event) {
return from(namesOf(event));
}
/**
* @param codes
* Series of JFX KeyCodes for a keybind. Unlike {@link #from(String, KeyCode)}
* it is implied that the mask is given in this series, if one is intended.
*
* @return Binding from keys.
*/
public static Binding from(KeyCode... codes) {
return Arrays.stream(codes).map(KeyCode::getName)
.map(String::toLowerCase)
.collect(Collectors.toCollection(Binding::new));
}
/**
* @param codes
* Series of keys for a keybind.
*
* @return Binding from keys.
*/
public static Binding from(Collection<String> codes) {
return codes.stream()
.map(String::toLowerCase)
.sorted((a, b) -> (a.length() > b.length()) ? -1 : a.compareTo(b))
.collect(Collectors.toCollection(Binding::new));
}
@Override
public String toString() {
return String.join("+", this);
}
/**
* @param event
* JFX key event.
*
* @return {@code true} if the event matches the current bind.
*/
public boolean match(KeyEvent event) {
if (size() == 1)
// Simple 1-key check
return event.getCode().getName().equalsIgnoreCase(get(0));
else if (size() > 1) {
// Checking binds with masks
Set<String> bindSet = new HashSet<>(this);
Set<String> eventSet = namesOf(event);
return bindSet.equals(eventSet);
} else
throw new IllegalStateException("Keybind must have have at least 1 key!");
}
private static Set<String> namesOf(KeyEvent event) {
Set<String> eventSet = new HashSet<>();
eventSet.add(event.getCode().getName().toLowerCase());
if (event.isControlDown())
eventSet.add("ctrl");
else if (event.isAltDown())
eventSet.add("alt");
else if (event.isShiftDown())
eventSet.add("shift");
else if (event.isMetaDown())
eventSet.add("meta");
return eventSet;
}
}
/**
* Keybinding creator for creating different binding in different OS's.
*
* @author TimmyOVO
*/
public static final class KeybindingCreator {
private final Binding defaultBinding;
private final Map<OSUtil, Binding> bindings;
private KeybindingCreator(Binding defaultBinding, OSBinding... osBindings) {
this.defaultBinding = defaultBinding;
this.bindings = Arrays.stream(OSUtil.values())
.collect(Collectors.toMap(os -> os, os -> defaultBinding));
this.bindings.putAll(
Arrays.stream(osBindings)
.collect(Collectors.toMap(
osBinding -> osBinding.os,
osBinding -> osBinding.binding
))
);
}
/**
* Build a KeybindingCreator to include all os specified keybinding.
*
* @param defaultBinding defaultBinding
* If osBindings is empty, all os's keybinding will be the same.
* @param osBindings os specified keybinding.
* @return A KeybindingCreator instance.
*/
public static KeybindingCreator from(Binding defaultBinding, OSBinding... osBindings) {
return new KeybindingCreator(defaultBinding, osBindings);
}
/**
* Match keybinding for current using os.
*
* @return A Binding instance.
*/
public Binding buildKeyBindingForCurrentOS() {
return bindings.getOrDefault(OSUtil.getOSType(), defaultBinding);
}
/**
* OS specified keybinding wrapper.
*/
public static class OSBinding {
public OSUtil os;
public Binding binding;
private OSBinding(OSUtil os, Binding binding) {
this.os = os;
this.binding = binding;
}
/**
* Build a key binding instance for specified os.
*
* @param os the os to be specified
* @param binding key binding
* @return the instance of OSBinding.
*/
public static OSBinding from(OSUtil os, Binding binding) {
return new OSBinding(os, binding);
}
}
}
} |
package net.imagej.legacy;
import ij.ImagePlus;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.swing.KeyStroke;
import net.imagej.display.ImageDisplay;
import net.imagej.legacy.plugin.LegacyAppConfiguration;
import net.imagej.legacy.plugin.LegacyEditor;
import net.imagej.legacy.plugin.LegacyOpener;
import net.imagej.legacy.plugin.LegacyPostRefreshMenus;
import net.imagej.patcher.LegacyHooks;
import org.scijava.Context;
import org.scijava.log.LogService;
import org.scijava.log.StderrLogService;
import org.scijava.plugin.PluginInfo;
import org.scijava.plugin.PluginService;
import org.scijava.plugin.SciJavaPlugin;
import org.scijava.thread.ThreadService;
import org.scijava.ui.CloseConfirmable;
import org.scijava.util.ListUtils;
/**
* The {@link LegacyHooks} encapsulating an active {@link LegacyService} for use
* within the patched ImageJ 1.x.
*
* @author Johannes Schindelin
*/
public class DefaultLegacyHooks extends LegacyHooks {
private final LegacyService legacyService;
private final IJ1Helper helper;
private LogService log;
private LegacyEditor editor;
private LegacyAppConfiguration appConfig;
private List<LegacyPostRefreshMenus> afterRefreshMenus;
private List<LegacyOpener> legacyOpeners;
/** If the ij.log.file property is set, logs every message to this file. */
private BufferedWriter logFileWriter;
public DefaultLegacyHooks(final LegacyService legacyService) {
this(legacyService, legacyService.getIJ1Helper());
}
public DefaultLegacyHooks(final LegacyService legacyService,
final IJ1Helper helper)
{
this.legacyService = legacyService;
this.helper = helper;
}
@Override
public boolean isLegacyMode() {
return legacyService.isLegacyMode();
}
@Override
public Object getContext() {
return legacyService.getContext();
}
@Override
public synchronized void installed() {
final Context context = legacyService.getContext();
IJ1Helper.subscribeEvents(context);
log = context.getService(LogService.class);
if (log == null) log = new StderrLogService();
editor = createInstanceOfType(LegacyEditor.class);
appConfig = createInstanceOfType(LegacyAppConfiguration.class);
final PluginService pluginService = pluginService();
afterRefreshMenus =
pluginService.createInstancesOfType(LegacyPostRefreshMenus.class);
legacyOpeners = pluginService.createInstancesOfType(LegacyOpener.class);
}
@Override
public void dispose() {
IJ1Helper.subscribeEvents(null);
// TODO: if there are still things open, we should object.
}
@Override
public Object interceptRunPlugIn(final String className, final String arg) {
if (LegacyService.class.getName().equals(className)) return legacyService;
if (Context.class.getName().equals(className)) {
return legacyService == null ? null : legacyService.getContext();
}
// Intercept IJ1 commands
if (helper != null) {
// intercept ij.plugins.Commands
if (helper.commandsName().equals(className)) {
if (arg.equals("open")) {
final Object o = interceptFileOpen(null);
if (o != null) {
if (o instanceof String) {
legacyService.getIJ1Helper().openPathDirectly((String) o);
}
return o;
}
}
}
}
final Object legacyCompatibleCommand =
legacyService.runLegacyCompatibleCommand(className);
if (legacyCompatibleCommand != null) return legacyCompatibleCommand;
return null;
}
@Override
public void registerImage(final Object o) {
if (!legacyService.isSyncEnabled()) return;
final ImagePlus image = (ImagePlus) o;
if (image == null) return;
if (!image.isProcessor()) return;
if (image.getWindow() == null) return;
legacyService.log().debug("register legacy image: " + image);
try {
legacyService.getImageMap().registerLegacyImage(image);
}
catch (final UnsupportedOperationException e) {
// ignore: the dummy legacy service does not have an image map
}
}
@Override
public void unregisterImage(final Object o) {
final ImagePlus image = (ImagePlus) o;
if (image == null) return;
LegacyOutputTracker.removeOutput(image);
legacyService.log().debug("unregister legacy image: " + image);
try {
final ImageDisplay disp =
legacyService.getImageMap().lookupDisplay(image);
if (disp == null) {
legacyService.getImageMap().unregisterLegacyImage(image, true);
}
else {
disp.close();
}
}
catch (final UnsupportedOperationException e) {
// ignore: the dummy legacy service does not have an image map
}
// end alternate
}
@Override
public void debug(final String string) {
legacyService.log().debug(string);
}
@Override
public void error(final Throwable t) {
legacyService.log().error(t);
}
@Override
public void log(final String message) {
if (message != null) {
final String logFilePath = System.getProperty("ij.log.file");
if (logFilePath != null) {
try {
if (logFileWriter == null) {
final OutputStream out = new FileOutputStream(logFilePath, true);
final Writer writer = new OutputStreamWriter(out, "UTF-8");
logFileWriter = new java.io.BufferedWriter(writer);
logFileWriter.write("Started new log on " + new Date() + "\n");
}
logFileWriter.write(message);
if (!message.endsWith("\n")) logFileWriter.newLine();
logFileWriter.flush();
}
catch (final Throwable t) {
t.printStackTrace();
System.getProperties().remove("ij.log.file");
logFileWriter = null;
}
}
}
}
/**
* Returns the application name for use with ImageJ 1.x.
*
* @return the application name
*/
@Override
public String getAppName() {
return appConfig == null ? "ImageJ" : appConfig.getAppName();
}
/**
* Returns the application version to display in the ImageJ 1.x status bar.
*
* @return the application version
*/
@Override
public String getAppVersion() {
return legacyService.getCombinedVersion();
}
/**
* Returns the icon for use with ImageJ 1.x.
*
* @return the application name
*/
@Override
public URL getIconURL() {
return appConfig == null ? getClass().getResource("/icons/imagej-256.png")
: appConfig.getIconURL();
}
@Override
public void runAfterRefreshMenus() {
if (afterRefreshMenus != null) {
for (final Runnable run : afterRefreshMenus) {
run.run();
}
}
}
/**
* Opens the given path in the registered legacy editor, if any.
*
* @param path the path of the file to open
* @return whether the file was opened successfully
*/
@Override
public boolean openInEditor(final String path) {
if (editor == null) return false;
if (path.indexOf("://") > 0) return false;
// if it has no extension, do not open it in the legacy editor
if (!path.matches(".*\\.[0-9A-Za-z]{1,4}")) return false;
if (stackTraceContains(getClass().getName() + ".openInEditor(")) return false;
final File file = new File(path);
if (!file.exists()) return false;
if (isBinaryFile(file)) return false;
return editor.open(file);
}
/**
* Creates the given file in the registered legacy editor, if any.
*
* @param title the title of the file to create
* @param content the text of the file to be created
* @return whether the fule was opened successfully
*/
@Override
public boolean createInEditor(final String title, final String content) {
if (editor == null) return false;
return editor.create(title, content);
}
@Override
public Object interceptOpen(final String path, final int planeIndex,
final boolean display)
{
for (final LegacyOpener opener : legacyOpeners) {
final Object result = opener.open(path, planeIndex, display);
if (result != null) return result;
}
return null;
}
@Override
public Object interceptFileOpen(final String path) {
for (final LegacyOpener opener : legacyOpeners) {
final Object result = opener.open(path, -1, true);
if (result != null) return result;
}
return super.interceptFileOpen(path);
}
@Override
public Object interceptOpenImage(final String path, final int planeIndex) {
for (final LegacyOpener opener : legacyOpeners) {
final Object result = opener.open(path, planeIndex, false);
if (result != null) return result;
}
return super.interceptFileOpen(path);
}
@Override
public Object interceptOpenRecent(final String path) {
for (final LegacyOpener opener : legacyOpeners) {
final Object result = opener.open(path, -1, true);
if (result != null) return result;
}
return super.interceptFileOpen(path);
}
@Override
public Object interceptDragAndDropFile(final File f) {
if (f.getName().endsWith(".lut")) return null;
String path;
try {
path = f.getCanonicalPath();
for (final LegacyOpener opener : legacyOpeners) {
final Object result = opener.open(path, -1, true);
if (result != null) return result;
}
}
catch (final IOException e) {
log.error(e);
}
return super.interceptDragAndDropFile(f);
}
@Override
public boolean interceptKeyPressed(final KeyEvent e) {
String accelerator = KeyStroke.getKeyStrokeForEvent(e).toString();
if (accelerator.startsWith("pressed ")) {
accelerator = accelerator.substring("pressed ".length());
}
return legacyService.handleShortcut(accelerator) ||
(!e.isControlDown() && legacyService.handleShortcut("control " +
accelerator));
}
@Override
public Iterable<Thread> getThreadAncestors() {
final ThreadService threadService = threadService();
if (threadService == null) return null;
final Thread current = Thread.currentThread();
final Set<Thread> seen = new HashSet<Thread>();
seen.add(current);
return new Iterable<Thread>() {
@Override
public Iterator<Thread> iterator() {
return new Iterator<Thread>() {
private Thread thread = threadService.getParent(current);
@Override
public boolean hasNext() {
return thread != null;
}
@Override
public Thread next() {
final Thread next = thread;
thread = threadService.getParent(thread);
if (seen.contains(thread)) {
thread = null;
}
else {
seen.add(thread);
}
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
@Override
public boolean interceptCloseAllWindows() {
final Window[] windows = Window.getWindows();
boolean continueClose = true;
final List<Window> confirmableWindows = new ArrayList<Window>();
final List<Window> unconfirmableWindows = new ArrayList<Window>();
// For each Window, we split them into confirmable or unconfirmable based
// on whether or not they implement CloseConfirmable. As CloseAllWindows
// is synchronized on the WindowManager and disposal typically calls
// WindowManager.removeWindow (also synchronized), disposal is expected
// to block the EDT while we're still executing CloseAllWindows. As the
// EDT is necessary to display confirmation dialogs we can not request
// close confirmation while disposal is in progress without deadlocking.
// Thus we process and temporarily hide CloseConfirmable windows, then
// queue up a mass disposal when user input is no longer required.
// NB: this likely creates a race condition of disposal with System.exit
// being called by ImageJ 1.x's quitting routine. Thus disposal should
// never be required to execute before shutting down the JVM. When such
// behavior is required, the appropriate window should just implement
// CloseConfirmable.
for (int w = windows.length - 1; w >= 0 && continueClose; w
final Window win = windows[w];
// Skip the ImageJ 1.x main window
if (win == legacyService.getIJ1Helper().getIJ()) {
continue;
}
if (CloseConfirmable.class.isAssignableFrom(win.getClass())) {
// Any CloseConfirmable window will have its confirmClose method
// called.
// If this operation was not canceled, we hide the window until it can
// be disposed safely later.
continueClose = ((CloseConfirmable) win).confirmClose();
if (continueClose) {
confirmableWindows.add(win);
win.setVisible(false);
}
}
else if (win.getClass().getPackage().getName().startsWith("ij.")) {
// Whitelist any classes from ij.* to be disposed. This should get
// around any offenders in core ImageJ that leave windows open when
// closing.
// External classes should just implement CloseConfirmable!
unconfirmableWindows.add(win);
}
}
// We always want to dispose any CloseConfirmable windows that were
// successfully added to this list (and thus were not canceled) as
// these windows were expected to be closed.
disposeWindows(confirmableWindows);
// If the close process was canceled, we do not queue disposal for the
// unconfirmable windows.
if (!continueClose) return false;
// Dispose remaining windows and return true to indicate the close
// operation should continue.
disposeWindows(unconfirmableWindows);
return true;
}
@Override
public void interceptImageWindowClose(final Object window) {
final IJ1Helper ij1Helper = legacyService.getIJ1Helper();
final Frame w = (Frame)window;
// When quitting, IJ1 doesn't dispose closing ImageWindows.
// If the quit is later canceled this would leave orphaned windows.
// Thus we queue any closed windows for disposal.
if (ij1Helper.isWindowClosed(w) && ij1Helper.quitting()) {
threadService().queue(new Runnable() {
@Override
public void run() {
w.dispose();
}
});
}
}
@Override
public boolean disposing() {
// NB: At this point, ImageJ1 is in the process of shutting down from
// within its ij.ImageJ#run() method, which is typically, but not always,
// called on a separate thread by ij.ImageJ#quit(). The question is: did
// the shutdown originate from an IJ1 code path, or a SciJava one?
if (legacyService.getIJ1Helper().isDisposing()) {
// NB: ImageJ1 is in the process of a hard shutdown via an API call on
// the SciJava level. It was probably either LegacyService#dispose() or
// LegacyUI#dispose(), either of which triggers IJ1Helper#dispose().
// In that case, we need do nothing else.
}
else {
// NB: ImageJ1 is in the process of a soft shutdown via an API call to
// ij.ImageJ#quit().
// In this case, we must dispose the SciJava context too.
legacyService.getContext().dispose();
}
return true;
}
// -- Helper methods --
/**
* Determines whether a file is binary or text.
* <p>
* This just checks for a NUL in the first 1024 bytes. Not the best test, but
* a pragmatic one.
* </p>
*
* @param file the file to test
* @return whether it is binary
*/
private static boolean isBinaryFile(final File file) {
try {
final InputStream in = new FileInputStream(file);
final byte[] buffer = new byte[1024];
int offset = 0;
while (offset < buffer.length) {
final int count = in.read(buffer, offset, buffer.length - offset);
if (count < 0) break;
offset += count;
}
in.close();
while (offset > 0) {
if (buffer[--offset] == 0) {
return true;
}
}
}
catch (final IOException e) {}
return false;
}
/**
* Determines whether the current stack trace contains the specified string.
*
* @param needle the text to find
* @return whether the stack trace contains the text
*/
private static boolean stackTraceContains(final String needle) {
final StackTraceElement[] trace = Thread.currentThread().getStackTrace();
// exclude elements up to, and including, the caller
for (int i = 3; i < trace.length; i++) {
if (trace[i].toString().contains(needle)) return true;
}
return false;
}
// TODO: move to scijava-common?
private <PT extends SciJavaPlugin> PT createInstanceOfType(
final Class<PT> type)
{
final PluginService pluginService = pluginService();
if (pluginService == null) return null;
final PluginInfo<PT> info =
ListUtils.first(pluginService.getPluginsOfType(type));
return info == null ? null : pluginService.createInstance(info);
}
/**
* Helper method to {@link Window#dispose()} all {@code Windows} in a given
* list.
*/
private void disposeWindows(final List<Window> toDispose) {
// Queue the disposal to avoid deadlocks
threadService().queue(new Runnable() {
@Override
public void run() {
for (final Window win : toDispose) {
win.dispose();
}
}
});
}
private ThreadService threadService() {
return legacyService.getContext().getService(ThreadService.class);
}
private PluginService pluginService() {
return legacyService.getContext().getService(PluginService.class);
}
} |
package tonius.zoom;
import java.util.List;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import tonius.zoom.client.KeyHandler;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemBinoculars extends Item {
public ItemBinoculars() {
this.setMaxStackSize(1);
this.setUnlocalizedName(Zoom.PREFIX + "binoculars");
this.setTextureName(Zoom.RESOURCE_PREFIX + "binoculars");
this.setCreativeTab(CreativeTabs.tabTools);
GameRegistry.registerItem(this, "binoculars");
}
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) {
player.setItemInUse(itemStack, this.getMaxItemUseDuration(itemStack));
return itemStack;
}
@Override
public int getMaxItemUseDuration(ItemStack itemStack) {
return Integer.MAX_VALUE;
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean bool) {
list.add(StatCollector.translateToLocal("item.zoom.binoculars.desc.1"));
if (KeyHandler.keyZoom.getKeyCode() != 0) {
list.add(StatCollector.translateToLocalFormatted("item.zoom.binoculars.desc.2", EnumChatFormatting.AQUA + GameSettings.getKeyDisplayString(KeyHandler.keyZoom.getKeyCode()) + EnumChatFormatting.GRAY));
}
}
} |
package ts.service;
import ts.iot.MqttNode;
import java.util.Properties;
import org.slf4j.LoggerFactory;
import ts.utility.SystemUtility;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;
import org.bson.Document;
import org.eclipse.paho.client.mqttv3.MqttMessage;
/**
*
* @author loki.chuang
*/
public class MongoDBUploader extends MqttNode
{
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(MongoDBUploader.class);
private Properties m_properties = null;
private final String filePath = "/config/IoT.config";
private final String dbName = "IoTRepublic";
private final String colName = "dailydata";
String userUploadId;
//private MqttClient mqttClient;
private MongoCollection<Document> collection;
public MongoDBUploader()
{
super.setNodeName("MongoDB Uploader");
this.m_properties = SystemUtility.readConfigFile(this.filePath);
}
@Override //MqttNode
public void messageArrived(String topicId, MqttMessage mm) throws Exception
{
LOG.info("Data arrived");
TimeZone tz = TimeZone.getDefault();
Date gmtTime = new Date(new Date().getTime() + tz.getRawOffset());
//Date gmtTime = new Date(new Date().getTime());
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
String payload=new String(mm.getPayload());
Document doc = new Document().append("deviceId", topicId).
append("userId", this.userUploadId).
append("value", Double.valueOf(payload)).
append("date", gmtTime);
this.collection.insertOne(doc);
}
@Override //MqttNode
public void Start()
{
String brokerIp = this.m_properties.getProperty("brokerIp");
String brokerPort = this.m_properties.getProperty("brokerPort");
String userId = this.m_properties.getProperty("userId");
String userPassword = this.m_properties.getProperty("userPassword");
this.initMongoDB();
super.connectToBroker(brokerIp, brokerPort, userId, userPassword);
this.initSubscribe();
}
@Override //MqttNode
public void Stop()
{
super.disconnectFromBroker();
//this.disconnectFromBroker();
}
private void initMongoDB()
{
String hostIp = this.m_properties.getProperty("MongoDBAddress");
String port = this.m_properties.getProperty("MongoDBPort");
this.userUploadId = this.m_properties.getProperty("MongoDBuserId");
String userUploadPw = this.m_properties.getProperty("MongoDBuserPw");
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(this.userUploadId, "admin", userUploadPw.toCharArray());
//String mechanism= mongoCredential.getMechanism();
MongoClient mongoClient = new MongoClient(new ServerAddress(hostIp, Integer.parseInt(port)), Arrays.asList(mongoCredential));
MongoDatabase mongoDatabase = mongoClient.getDatabase(this.dbName);
this.collection = mongoDatabase.getCollection(this.colName);
}
private void initSubscribe()
{
String topics = this.m_properties.getProperty("MongoDBsubscribeTopic");
if (topics.equals("ALL"))
{
super.subscribe("
} else
{
LOG.error("subscribe specific topic not implement yet");
}
}
} |
package nl.martijndwars.webpush;
import org.bouncycastle.jce.interfaces.ECPublicKey;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import static java.nio.charset.StandardCharsets.UTF_8;
public class Notification {
/**
* The endpoint associated with the push subscription
*/
private final String endpoint;
/**
* The client's public key
*/
private final ECPublicKey userPublicKey;
/**
* The client's auth
*/
private final byte[] userAuth;
/**
* An arbitrary payload
*/
private final byte[] payload;
private Urgency urgency;
/**
* Time in seconds that the push message is retained by the push service
*/
private final int ttl;
public Notification(String endpoint, ECPublicKey userPublicKey, byte[] userAuth, byte[] payload, int ttl, Urgency urgency) {
this.endpoint = endpoint;
this.userPublicKey = userPublicKey;
this.userAuth = userAuth;
this.payload = payload;
this.ttl = ttl;
this.urgency = urgency;
}
public Notification(String endpoint, PublicKey userPublicKey, byte[] userAuth, byte[] payload, int ttl) {
this(endpoint, (ECPublicKey) userPublicKey, userAuth, payload, ttl, null);
}
public Notification(String endpoint, PublicKey userPublicKey, byte[] userAuth, byte[] payload) {
this(endpoint, userPublicKey, userAuth, payload, 2419200);
}
public Notification(String endpoint, String userPublicKey, String userAuth, byte[] payload) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
this(endpoint, Utils.loadPublicKey(userPublicKey), Base64Encoder.decode(userAuth), payload);
}
public Notification(String endpoint, String userPublicKey, String userAuth, String payload) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
this(endpoint, Utils.loadPublicKey(userPublicKey), Base64Encoder.decode(userAuth), payload.getBytes(UTF_8));
}
public Notification(String endpoint, String userPublicKey, String userAuth, String payload, Urgency urgency) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
this(endpoint, Utils.loadPublicKey(userPublicKey), Base64Encoder.decode(userAuth), payload.getBytes(UTF_8));
this.urgency = urgency;
}
public Notification(Subscription subscription, String payload) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
this(subscription.endpoint, subscription.keys.p256dh, subscription.keys.auth, payload);
}
public Notification(Subscription subscription, String payload, Urgency urgency) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
this(subscription.endpoint, subscription.keys.p256dh, subscription.keys.auth, payload);
this.urgency = urgency;
}
public String getEndpoint() {
return endpoint;
}
public ECPublicKey getUserPublicKey() {
return userPublicKey;
}
public byte[] getUserAuth() {
return userAuth;
}
public byte[] getPayload() {
return payload;
}
public boolean hasPayload() {
return getPayload().length > 0;
}
public boolean hasUrgency() {
return urgency != null;
}
/**
* Detect if the notification is for a GCM-based subscription
*
* @return
*/
public boolean isGcm() {
return getEndpoint().indexOf("https://android.googleapis.com/gcm/send") == 0;
}
public boolean isFcm() {
return getEndpoint().indexOf("https://fcm.googleapis.com/fcm/send") == 0;
}
public int getTTL() {
return ttl;
}
public Urgency getUrgency() {
return urgency;
}
public String getOrigin() throws MalformedURLException {
URL url = new URL(getEndpoint());
return url.getProtocol() + "://" + url.getHost();
}
} |
package no.geonorge.nedlasting.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.access.DataDomain;
import org.apache.cayenne.access.DataNode;
import org.apache.cayenne.configuration.DataNodeDescriptor;
import org.apache.cayenne.configuration.server.DataSourceFactory;
import org.apache.cayenne.configuration.server.ServerRuntime;
import org.apache.cayenne.dba.DbAdapter;
import org.apache.cayenne.map.DataMap;
import org.apache.cayenne.merge.AbstractToDbToken;
import org.apache.cayenne.merge.DbMerger;
import org.apache.cayenne.merge.DropColumnToDb;
import org.apache.cayenne.merge.DropTableToDb;
import org.apache.cayenne.merge.ExecutingMergerContext;
import org.apache.cayenne.merge.MergerToken;
import org.apache.commons.dbcp2.BasicDataSource;
import no.geonorge.nedlasting.data.upgrade.DbUpgrade;
import no.geonorge.nedlasting.utils.IOUtils;
public class Config implements DataSourceFactory {
private static final String KEY_SERVER_PORT = "server.port";
private static final String KEY_JETTY_PORT = "jetty.port";
private static final String KEY_DATABASE_DRIVER = "database.driver";
private static final String KEY_DATABASE_URL = "database.url";
private static final String KEY_DATABASE_USERNAME = "database.username";
private static final String KEY_DATABASE_PASSWORD = "database.password";
private static final String KEY_ALLOWED_FILETYPES = "allowed_filetypes";
private static final String KEY_ALLOWED_HOSTS = "allowed_hosts";
private static final String KEY_CORS = "cors";
private static ServerRuntime runtime;
private static boolean inited = false;
private static int serverPort = 10000;
private static DataSource dataSource;
private static String cors;
private static boolean enableFileProxy = true; // default true. Override in property-file: fileproxy.enable=false
private static List<String> allowedHosts = new ArrayList<>();
private static List<String> allowedFiletypes = new ArrayList<>();
private static final Logger log = Logger.getLogger(Config.class.getName());
public static List<String> getAllowedFiletypes;
static {
log.info("setting up cayenne ServerRuntime");
runtime = new ServerRuntime("cayenne-domain.xml");
}
public static void readConfiguration() throws IOException {
Properties prop = new Properties();
for (String file : Arrays.asList("/etc/geonorge.properties", "geonorge.properties")) {
File configFile = new File(file);
if (!configFile.canRead()) {
continue;
}
InputStream input = null;
try {
input = new FileInputStream(configFile);
prop.load(input);
log.info("read configuration from " + configFile);
} finally {
IOUtils.close(input);
}
}
// look for two different variables for port number. This is to both
// be compatible with geonorge.properties and
Config.serverPort = getProperty(prop, KEY_SERVER_PORT, Config.serverPort);
Config.serverPort = getProperty(prop, KEY_JETTY_PORT, Config.serverPort);
String _enableFileproxy = getProperty(prop,"fileproxy.enable","true");
if (_enableFileproxy.equalsIgnoreCase("true")) {
Config.enableFileProxy = true;
}
if (_enableFileproxy.equalsIgnoreCase("false")) {
Config.enableFileProxy = false;
}
Config.cors = getProperty(prop, KEY_CORS, "*");
String _allowedHosts = getProperty(prop,KEY_ALLOWED_HOSTS,null);
if (_allowedHosts != null) {
String[] _hosts = _allowedHosts.split(",");
for (String _host:_hosts) {
getAllowedHosts().add(_host);
}
}
String _allowedFiletypes = getProperty(prop,KEY_ALLOWED_FILETYPES,null);
if (_allowedFiletypes != null) {
String[] _filetypes = _allowedFiletypes.split(",");
for (String _filetype:_filetypes) {
getAllowedFiletypes().add(_filetype);
}
} else {
Collections.addAll(getAllowedFiletypes(), new String[]{"zip", "sos", "fgdb", "gz", "tar.gz", "tgz"});
}
BasicDataSource nds = new BasicDataSource();
nds.setUrl(getRequiredProperty(prop, KEY_DATABASE_URL));
nds.setDriverClassName(getRequiredProperty(prop, KEY_DATABASE_DRIVER));
nds.setUsername(getProperty(prop, KEY_DATABASE_USERNAME));
nds.setPassword(getProperty(prop, KEY_DATABASE_PASSWORD));
setDataSource(nds);
}
public static boolean isEnableFileProxy() {
return enableFileProxy;
}
public static List<String> getAllowedFiletypes() {
return allowedFiletypes;
}
public static List<String> getAllowedHosts() {
return allowedHosts;
}
public static int getServerPort() {
return serverPort;
}
public static void setDataSource(DataSource ds) {
Config.dataSource = ds;
init();
}
public static DataSource getDataSource() {
if (Config.dataSource == null) {
throw new IllegalStateException("A jdbc data source not configured");
}
return Config.dataSource;
}
public static ObjectContext getObjectContext() {
return runtime.getContext();
}
private static void init() {
if (inited) {
return;
}
inited = true;
log.info("init geonorge download..");
if (dataSource == null) {
log.info("missing data source. not good.");
}
DataDomain domain = runtime.getDataDomain();
DataMap dataMap = domain.getDataMap("datamap");
DataNode dataNode = domain.getDataNode("datanode");
DbAdapter adapter = dataNode.getAdapter();
DbMerger merger = new DbMerger();
List<MergerToken> tokens = merger.createMergeTokens(dataNode, dataMap);
List<AbstractToDbToken> toDbTokens = new ArrayList<AbstractToDbToken>();
for (MergerToken token : tokens) {
if (token.getDirection().isToModel()) {
token = token.createReverse(adapter.mergerFactory());
}
if (token instanceof DropTableToDb) {
continue;
}
if (token instanceof DropColumnToDb) {
continue;
}
if (token instanceof AbstractToDbToken) {
AbstractToDbToken dbToken = (AbstractToDbToken) token;
toDbTokens.add(dbToken);
}
}
ExecutingMergerContext mc = new ExecutingMergerContext(dataMap, dataNode);
for (AbstractToDbToken token : toDbTokens) {
token.execute(mc);
}
DbUpgrade.upgrade();
log.info("inited geonorge download..");
}
private static String getProperty(Properties prop, String key) {
String v = prop.getProperty(key);
if (v == null) {
v = System.getProperty(key);
}
if (v == null) {
v = System.getenv(key);
}
return v;
}
private static String getRequiredProperty(Properties prop, String key) {
String v = getProperty(prop, key);
if (v == null) {
throw new IllegalStateException("missing required configuration parameter: " + key);
}
return v;
}
private static int getProperty(Properties prop, String key, int defaultValue) {
String v = getProperty(prop, key);
return v == null ? defaultValue : Integer.parseInt(v);
}
private static String getProperty(Properties prop, String key, String defaultValue) {
String v = getProperty(prop, key);
return v == null ? defaultValue : v;
}
public DataSource getDataSource(DataNodeDescriptor desc) throws Exception {
return dataSource;
}
public static String getCors() {
return cors;
}
} |
package com.equalinformation.car.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtil {
private static int CONNCOUNT = 0;
Connection connection = null;
public Connection getConnection() {
if (CONNCOUNT == 0) {
createConnection();
++CONNCOUNT;
}
return connection;
}
private Connection createConnection() {
String url = "jdbc:mysql://localhost:3306/"; // Your DB details
String dbName = "tesla";
String driver = "com.mysql.jdbc.Driver";
String userName = "****";
String password = "******";
try {
Class.forName(driver);
connection = DriverManager.getConnection(url+dbName,userName,password);
} catch(Exception e) {
e.printStackTrace();
}
return connection;
}
} |
// P i c t u r e L o a d e r //
// <editor-fold defaultstate="collapsed" desc="hdr"> //
// </editor-fold>
package omr.sheet.picture;
import omr.constant.Constant;
import omr.constant.ConstantSet;
import omr.log.Logger;
import omr.util.FileUtil;
import omr.WellKnowns;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.media.jai.JAI;
public class PictureLoader
{
/** Specific application parameters */
private static final Constants constants = new Constants();
/** Usual logger utility */
private static final Logger logger = Logger.getLogger(PictureLoader.class);
/**
* To disallow instantiation.
*/
private PictureLoader ()
{
}
// loadFile //
public static SortedMap<Integer, RenderedImage> loadImages (File imgFile,
Integer id)
{
if (!imgFile.exists()) {
throw new IllegalArgumentException(imgFile + " does not exist");
}
logger.info("Loading {0} ...", imgFile);
logger.fine("Trying ImageIO");
SortedMap<Integer, RenderedImage> images = loadImageIO(imgFile, id, null);
if (images == null) {
String extension = FileUtil.getExtension(imgFile);
if (extension.equalsIgnoreCase(".pdf")) {
images = loadPDF(imgFile, id);
} else {
logger.fine("Using JAI");
images = loadJAI(imgFile);
}
}
if (images == null) {
logger.warning("Unable to load any image from {0}", imgFile);
}
return images;
}
// loadImageIO //
/**
* Try to load a sequence of images, using ImageIO.
*
* @param imgFile the input image file
* @param id if not null, specifies (counted from 1) which single
* image is desired
* @param idUser if not null, identity used in the returned map
* @return a map of images, or null if failed to load
*/
private static SortedMap<Integer, RenderedImage> loadImageIO (File imgFile,
Integer id,
Integer idUser)
{
logger.fine("loadImageIO {0} id:{1}", imgFile, id);
// Input stream
ImageInputStream stream;
try {
stream = ImageIO.createImageInputStream(imgFile);
} catch (IOException ex) {
logger.warning("Unable to make ImageIO stream", ex);
return null;
}
if (stream == null) {
logger.fine("No ImageIO input stream provider");
return null;
}
try {
Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
if (!readers.hasNext()) {
logger.fine("No ImageIO reader");
return null;
}
ImageReader reader = readers.next();
try {
reader.setInput(stream, false);
int imageCount = reader.getNumImages(true);
if (imageCount > 1) {
logger.info("{0} contains {1} images",
imgFile.getName(), imageCount);
}
SortedMap<Integer, RenderedImage> images = new TreeMap<>();
for (int i = 1; i <= imageCount; i++) {
if ((id == null) || (id == i)) {
BufferedImage img = reader.read(i - 1);
int identity = idUser != null ? idUser : i;
images.put(identity, img);
logger.info("Loaded image #{0} ({1} x {2})",
identity, img.getWidth(), img.getHeight());
}
}
return images;
} catch (Exception ex) {
logger.warning("ImageIO failed", ex);
return null;
} finally {
reader.dispose();
}
} finally {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
// loadJAI //
/**
* Try to load an image, using JAI.
* This seems limited to a single image, thus no id parameter is to be
* provided.
*
* @param imgFile the input file
* @return a map of one image, or null if failed to load
*/
private static SortedMap<Integer, RenderedImage> loadJAI (File imgFile)
{
RenderedImage image = JAI.create("fileload", imgFile.getPath());
try {
if ((image.getWidth() > 0) && (image.getHeight() > 0)) {
SortedMap<Integer, RenderedImage> images = new TreeMap<>();
images.put(1, image);
return images;
}
} catch (Exception ex) {
logger.fine(ex.getMessage());
}
return null;
}
// loadPDF //
/**
* Load a sequence of images out of a PDF file.
* We spawn a Ghostscript subprocess to convert PDF to TIFF and then
* load the temporary TIFF file via loadImageIO().
*
* @param imgFile the input PDF file
* @param id if not null, specifies (counted from 1) which single image
* is desired
* @return a map of images, or null if failed to load
*/
private static SortedMap<Integer, RenderedImage> loadPDF (File imgFile,
Integer id)
{
logger.fine("loadPDF {0} id:{1}", imgFile, id);
// Create a temporary tiff file from the PDF input
Path temp = null;
try {
temp = Files.createTempFile("pic-", ".tif");
} catch (IOException ex) {
logger.warning("Cannot create temporary file " + temp, ex);
return null;
}
// Arguments for Ghostscript
List<String> gsArgs = new ArrayList<>();
gsArgs.add(getGhostscriptExec());
gsArgs.add("-dQUIET");
gsArgs.add("-dNOPAUSE");
gsArgs.add("-dBATCH");
gsArgs.add("-dSAFER");
gsArgs.add("-sDEVICE=" + constants.pdfDevice.getValue());
gsArgs.add("-r" + constants.pdfResolution.getValue());
gsArgs.add("-sOutputFile=" + temp);
if (id != null) {
gsArgs.add("-dFirstPage=" + id);
gsArgs.add("-dLastPage=" + id);
}
gsArgs.add(imgFile.toString());
logger.fine("gsArgs:{0}", gsArgs);
try {
// Spawn Ghostscript process and wait for its completion
new ProcessBuilder(gsArgs).start().waitFor();
// Now load the temporary tiff file
if (id != null) {
return loadImageIO(temp.toFile(), 1, id);
} else {
return loadImageIO(temp.toFile(), null, null);
}
} catch (IOException | InterruptedException ex) {
logger.warning("Error running Ghostscript " + gsArgs, ex);
return null;
} finally {
try {
Files.delete(temp);
} catch (IOException ex) {
logger.warning("Error deleting file " + temp, ex);
}
}
}
// getGhostscriptExec //
/**
* Report the path to proper Ghostscript executable
* on this machine / environment.
*
* @return the path to Ghostscript executable
*/
private static String getGhostscriptExec ()
{
File f;
if (WellKnowns.LINUX || WellKnowns.MAC_OS_X) {
// TODO: certainly modify this line
return "gs";
} else if (WellKnowns.WINDOWS) {
if (WellKnowns.WINDOWS_64) {
f = new File(WellKnowns.GS_FOLDER, "windows/x64/gswin64c.exe");
} else {
f = new File(WellKnowns.GS_FOLDER, "windows/x86/gswin32c.exe");
}
return f.toString();
}
return null;
}
// Constants //
private static final class Constants
extends ConstantSet
{
Constant.Integer pdfResolution = new Constant.Integer(
"DPI",
300,
"DPI resolution for PDF images");
Constant.String pdfDevice = new Constant.String(
"tiff24nc",
"Ghostscript output device (tiff24nc or tiffscaled8)");
}
} |
package org.apdplat.word.analysis;
import org.apdplat.word.segmentation.Word;
import java.util.List;
/**
*
* @author
*/
public interface Similarity {
/**
* 12
* @param object1 1
* @param object2 2
* @return
*/
boolean isSimilar(String object1, String object2);
/**
* 12
* @param object1 1
* @param object2 2
* @return
*/
double similarScore(String object1, String object2);
/**
* 12
* @param words1 1
* @param words2 2
* @return
*/
boolean isSimilar(List<Word> words1, List<Word> words2);
/**
* 12
* @param words1 1
* @param words2 2
* @return
*/
double similarScore(List<Word> words1, List<Word> words2);
} |
package interfaces;
import gui.Building.ResidenceBuildingPanel;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import Person.PersonAgent;
import Person.PersonAgent.Friend;
import Person.Role.Role;
import bank.BankClientRole;
import bank.BankTellerRole;
import bank.LoanTellerRole;
import building.Building;
import util.DateListener;
import util.MasterTime;
import java.util.Calendar;
public interface Person extends DateListener{
//Transportation functions
public abstract void msgWeHaveArrived(String currentDestination);
public abstract void msgImHungry();
public abstract void msgINeedMoney(double moneyNeeded);
public abstract void msgYouHaveALoan(double loan);
public abstract void msgReportForWork(String role);
public abstract void msgGoToMarket(String item);
public abstract void msgReceiveSalary(double salary);
public abstract void msgPayBackLoanUrgently();
public abstract void msgPayBackRentUrgently();
public abstract void msgAddObjectToBackpack(String object, int quantity);
public abstract void msgPartyInvitation(Person p, Calendar rsvpDeadline, Calendar partyTime);
public abstract void msgIAmComing(Person p);
public abstract void msgIAmNotComing(Person p);
public abstract String getName();
public abstract void startThread();
public abstract void setMoney(double d);
public abstract void setMoneyNeeded(double d);
public abstract double getMoney();
public abstract void stateChanged();
public abstract int getAge();
public abstract double getMoneyNeeded();
public abstract Calendar getRealTime();
public abstract List<PersonAgent> getFriends();
public abstract ResidenceBuildingPanel getHome();
public abstract void setInitialRole(Role roleFromString, String string);
public abstract void dateAction(int month, int day, int hour, int minute);
} |
package org.basex.gui.view.editor;
import static org.basex.core.Text.*;
import static org.basex.gui.GUIConstants.*;
import static org.basex.util.Token.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.event.*;
import org.basex.core.*;
import org.basex.data.*;
import org.basex.gui.*;
import org.basex.gui.GUIConstants.Fill;
import org.basex.gui.GUIConstants.Msg;
import org.basex.gui.dialog.*;
import org.basex.gui.editor.Editor.Action;
import org.basex.gui.editor.*;
import org.basex.gui.layout.*;
import org.basex.gui.layout.BaseXFileChooser.Mode;
import org.basex.gui.layout.BaseXLayout.DropHandler;
import org.basex.gui.view.*;
import org.basex.io.*;
import org.basex.util.*;
import org.basex.util.list.*;
public final class EditorView extends View {
/** Error string. */
private static final String ERRSTRING = STOPPED_AT + ' ' +
(LINE_X + ", " + COLUMN_X).replaceAll("%", "([0-9]+)");
/** XQuery error pattern. */
private static final Pattern XQERROR =
Pattern.compile(ERRSTRING + ' ' + IN_FILE_X.replaceAll("%", "(.*?)") + COL);
/** XML error pattern. */
private static final Pattern XMLERROR =
Pattern.compile(LINE_X.replaceAll("%", "(.*?)") + COL + ".*");
/** History Button. */
final BaseXButton hist;
/** Execute Button. */
final BaseXButton stop;
/** Info label. */
final BaseXLabel info;
/** Position label. */
final BaseXLabel pos;
/** Query area. */
final BaseXTabs tabs;
/** Execute button. */
final BaseXButton go;
/** Thread counter. */
int threadID;
/** File in which the most recent error occurred. */
String errFile;
/** Most recent error position; used for clicking on error message. */
int errPos;
/** Header string. */
private final BaseXLabel header;
/** Filter button. */
private final BaseXButton filter;
/** Search panel. */
public final SearchPanel search;
/**
* Default constructor.
* @param man view manager
*/
public EditorView(final ViewNotifier man) {
super(EDITORVIEW, man);
border(6, 6, 6, 6).layout(new BorderLayout(0, 2)).setFocusable(false);
header = new BaseXLabel(EDITOR, true, false);
final BaseXButton srch = new BaseXButton(gui, "search", H_REPLACE);
final BaseXButton openB = BaseXButton.command(GUICommands.C_EDITOPEN, gui);
final BaseXButton saveB = new BaseXButton(gui, "save", H_SAVE);
hist = new BaseXButton(gui, "hist", H_RECENTLY_OPEN);
final BaseXBack buttons = new BaseXBack(Fill.NONE);
buttons.layout(new TableLayout(1, 4, 1, 0));
buttons.add(srch);
buttons.add(openB);
buttons.add(saveB);
buttons.add(hist);
final BaseXBack b = new BaseXBack(Fill.NONE).layout(new BorderLayout(8, 0));
b.add(header, BorderLayout.CENTER);
b.add(buttons, BorderLayout.EAST);
add(b, BorderLayout.NORTH);
tabs = new BaseXTabs(gui);
tabs.setFocusable(false);
final SearchEditor se = new SearchEditor(gui, tabs, null).button(srch);
search = se.panel();
addCreateTab();
add(se, BorderLayout.CENTER);
// status and query pane
search.editor(addTab(), false);
info = new BaseXLabel().setText(OK, Msg.SUCCESS);
pos = new BaseXLabel(" ");
posCode.invokeLater();
stop = new BaseXButton(gui, "stop", H_STOP_PROCESS);
stop.addKeyListener(this);
stop.setEnabled(false);
go = new BaseXButton(gui, "go", H_EXECUTE_QUERY);
go.addKeyListener(this);
filter = BaseXButton.command(GUICommands.C_FILTER, gui);
filter.addKeyListener(this);
filter.setEnabled(false);
final BaseXBack status = new BaseXBack(Fill.NONE).layout(new BorderLayout(4, 0));
status.add(info, BorderLayout.CENTER);
status.add(pos, BorderLayout.EAST);
final BaseXBack query = new BaseXBack(Fill.NONE).layout(new TableLayout(1, 3, 1, 0));
query.add(stop);
query.add(go);
query.add(filter);
final BaseXBack south = new BaseXBack(Fill.NONE).border(4, 0, 0, 0);
south.layout(new BorderLayout(8, 0));
south.add(status, BorderLayout.CENTER);
south.add(query, BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
refreshLayout();
// add listeners
saveB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pop = new JPopupMenu();
final StringBuilder mnem = new StringBuilder();
final JMenuItem sa = GUIMenu.newItem(GUICommands.C_EDITSAVE, gui, mnem);
final JMenuItem sas = GUIMenu.newItem(GUICommands.C_EDITSAVEAS, gui, mnem);
GUICommands.C_EDITSAVE.refresh(gui, sa);
GUICommands.C_EDITSAVEAS.refresh(gui, sas);
pop.add(sa);
pop.add(sas);
pop.show(saveB, 0, saveB.getHeight());
}
});
hist.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JPopupMenu pm = new JPopupMenu();
final ActionListener al = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent ac) {
open(new IOFile(ac.getActionCommand()));
}
};
final StringList sl = new StringList();
for(final EditorArea ea : editors()) sl.add(ea.file.path());
for(final String en : new StringList().add(
gui.gprop.strings(GUIProp.EDITOR)).sort(!Prop.WIN, true)) {
final JMenuItem it = new JMenuItem(en);
it.setEnabled(!sl.contains(en));
pm.add(it).addActionListener(al);
}
pm.show(hist, 0, hist.getHeight());
}
});
refreshHistory(null);
info.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
EditorArea ea = getEditor();
if(errFile != null) {
ea = find(IO.get(errFile), false);
if(ea == null) ea = open(new IOFile(errFile));
tabs.setSelectedComponent(ea);
}
if(errPos == -1) return;
ea.jumpError(errPos);
posCode.invokeLater();
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
stop.setEnabled(false);
go.setEnabled(false);
gui.stop();
}
});
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
getEditor().release(Action.EXECUTE);
}
});
tabs.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
final EditorArea ea = getEditor();
if(ea == null) return;
search.editor(ea, true);
gui.refreshControls();
posCode.invokeLater();
}
});
BaseXLayout.addDrop(this, new DropHandler() {
@Override
public void drop(final Object file) {
if(file instanceof File) open(new IOFile((File) file));
}
});
}
@Override
public void refreshInit() { }
@Override
public void refreshFocus() { }
@Override
public void refreshMark() {
final EditorArea edit = getEditor();
go.setEnabled(edit.script || edit.xquery && !gui.gprop.is(GUIProp.EXECRT));
final Nodes mrk = gui.context.marked;
filter.setEnabled(!gui.gprop.is(GUIProp.FILTERRT) && mrk != null && mrk.size() != 0);
}
@Override
public void refreshContext(final boolean more, final boolean quick) { }
@Override
public void refreshLayout() {
header.setFont(GUIConstants.lfont);
for(final EditorArea edit : editors()) edit.setFont(GUIConstants.mfont);
search.refreshLayout();
}
@Override
public void refreshUpdate() { }
@Override
public boolean visible() {
return gui.gprop.is(GUIProp.SHOWEDITOR);
}
@Override
public void visible(final boolean v) {
gui.gprop.set(GUIProp.SHOWEDITOR, v);
}
@Override
protected boolean db() {
return false;
}
/**
* Opens a new file.
*/
public void open() {
// open file chooser for XML creation
final BaseXFileChooser fc = new BaseXFileChooser(OPEN,
gui.gprop.get(GUIProp.WORKPATH), gui);
fc.filter(BXS_FILES, IO.BXSSUFFIX);
fc.filter(XQUERY_FILES, IO.XQSUFFIXES);
fc.filter(XML_DOCUMENTS, IO.XMLSUFFIXES);
final IOFile[] files = fc.multi().selectAll(Mode.FOPEN);
for(final IOFile f : files) open(f);
}
/**
* Reverts the contents of the currently opened editor.
*/
public void reopen() {
getEditor().reopen(true);
}
/**
* Saves the contents of the currently opened editor.
* @return {@code false} if operation was canceled
*/
public boolean save() {
final EditorArea edit = getEditor();
return edit.opened() ? save(edit.file) : saveAs();
}
/**
* Saves the contents of the currently opened editor under a new name.
* @return {@code false} if operation was canceled
*/
public boolean saveAs() {
// open file chooser for XML creation
final EditorArea edit = getEditor();
final BaseXFileChooser fc = new BaseXFileChooser(
SAVE_AS, edit.file.path(), gui).filter(XQUERY_FILES, IO.XQSUFFIXES);
final IOFile file = fc.select(Mode.FSAVE);
return file != null && save(file);
}
/**
* Creates a new file.
*/
public void newFile() {
addTab();
refreshControls(true);
}
/**
* Opens the specified query file.
* @param file query file
* @return opened editor
*/
public EditorArea open(final IOFile file) {
if(!visible()) GUICommands.C_SHOWEDITOR.execute(gui);
EditorArea edit = find(file, true);
try {
if(edit != null) {
// display open file
tabs.setSelectedComponent(edit);
edit.reopen(true);
} else {
// get current editor
edit = getEditor();
// create new tab if current text is stored on disk or has been modified
if(edit.opened() || edit.modified) edit = addTab();
edit.initText(file.read());
edit.file(file);
}
} catch(final IOException ex) {
BaseXDialog.error(gui, FILE_NOT_OPENED);
}
return edit;
}
/**
* Refreshes the list of recent query files and updates the query path.
* @param file new file
*/
void refreshHistory(final IOFile file) {
final StringList sl = new StringList();
String path = null;
if(file != null) {
path = file.path();
gui.gprop.set(GUIProp.WORKPATH, file.dirPath());
sl.add(path);
tabs.setToolTipTextAt(tabs.getSelectedIndex(), path);
}
final String[] qu = gui.gprop.strings(GUIProp.EDITOR);
for(int q = 0; q < qu.length && q < 19; q++) {
final String f = qu[q];
if(!f.equalsIgnoreCase(path) && IO.get(f).exists()) sl.add(f);
}
// store sorted history
gui.gprop.set(GUIProp.EDITOR, sl.toArray());
hist.setEnabled(!sl.isEmpty());
}
/**
* Closes an editor.
* @param edit editor to be closed. {@code null} closes the currently
* opened editor.
* opened editor is to be closed
*/
public void close(final EditorArea edit) {
final EditorArea ea = edit != null ? edit : getEditor();
if(!confirm(ea)) return;
tabs.remove(ea);
final int t = tabs.getTabCount();
final int i = tabs.getSelectedIndex();
if(t == 1) {
// reopen single tab
addTab();
} else if(i + 1 == t) {
// if necessary, activate last editor tab
tabs.setSelectedIndex(i - 1);
}
}
/**
* Jumps to a specific line.
*/
public void gotoLine() {
final DialogLine dl = new DialogLine(gui);
if(!dl.ok()) return;
final EditorArea edit = getEditor();
final int el = dl.line();
final int ll = edit.last.length;
int p = 0;
for(int l = 1, e = 0; e < ll && l < el; e += cl(edit.last, e)) {
if(edit.last[e] != '\n') continue;
p = e + 1;
++l;
}
edit.setCursor(p);
posCode.invokeLater();
}
/**
* Starts a thread, which shows a waiting info after a short timeout.
*/
public void start() {
final int thread = threadID;
new Thread() {
@Override
public void run() {
Performance.sleep(200);
if(thread == threadID) {
info.setText(PLEASE_WAIT_D, Msg.SUCCESS).setToolTipText(null);
stop.setEnabled(true);
}
}
}.start();
}
/**
* Evaluates the info message resulting from a parsed or executed query.
* @param msg info message
* @param ok {@code true} if evaluation was successful
* @param up update
*/
public void info(final String msg, final boolean ok, final boolean up) {
++threadID;
errPos = -1;
errFile = null;
getEditor().resetError();
final String m = msg.replaceAll("^.*\r?\n\\[.*?\\]", "").
replaceAll(".*" + LINE_X.replaceAll("%", ".*?") + COL, "");
if(ok) {
info.setCursor(GUIConstants.CURSORARROW);
info.setText(m, Msg.SUCCESS).setToolTipText(null);
} else {
info.setCursor(error(msg) ? GUIConstants.CURSORHAND : GUIConstants.CURSORARROW);
info.setText(m, Msg.ERROR).setToolTipText(msg);
}
if(up) {
stop.setEnabled(false);
refreshMark();
}
}
/**
* Handles info messages resulting from a query execution.
* @param msg info message
* @return true if error was found
*/
private boolean error(final String msg) {
final String line = msg.replaceAll("[\\r\\n].*", "");
Matcher m = XQERROR.matcher(line);
int el = 0, ec = 2;
if(!m.matches()) {
m = XMLERROR.matcher(line);
if(!m.matches()) return true;
el = Integer.parseInt(m.group(1));
errFile = getEditor().file.path();
} else {
el = Integer.parseInt(m.group(1));
ec = Integer.parseInt(m.group(2));
errFile = m.group(3);
}
final EditorArea edit = find(IO.get(errFile), false);
if(edit == null) return true;
// find approximate error position
final int ll = edit.last.length;
int ep = ll;
for(int e = 1, l = 1, c = 1; e < ll; ++c, e += cl(edit.last, e)) {
if(l > el || l == el && c == ec) {
ep = e;
break;
}
if(edit.last[e] == '\n') {
++l;
c = 0;
}
}
if(ep < ll && Character.isLetterOrDigit(cp(edit.last, ep))) {
while(ep > 0 && Character.isLetterOrDigit(cp(edit.last, ep - 1))) ep
}
edit.error(ep);
errPos = ep;
return true;
}
/**
* Shows a quit dialog for all modified query files.
* @return {@code false} if confirmation was canceled
*/
public boolean confirm() {
for(final EditorArea edit : editors()) if(!confirm(edit)) return false;
return true;
}
/**
* Checks if the current text can be saved or reverted.
* @param rev revert flag
* @return result of check
*/
public boolean modified(final boolean rev) {
final EditorArea edit = getEditor();
return edit.modified || !rev && !edit.opened();
}
/**
* Returns the current editor.
* @return editor
*/
public EditorArea getEditor() {
final Component c = tabs.getSelectedComponent();
return c instanceof EditorArea ? (EditorArea) c : null;
}
/**
* Refreshes the query modification flag.
* @param force action
*/
void refreshControls(final boolean force) {
// update modification flag
final EditorArea edit = getEditor();
final boolean oe = edit.modified;
edit.modified = edit.hist != null && edit.hist.modified();
if(edit.modified == oe && !force) return;
// update tab title
String title = edit.file.name();
if(edit.modified) title += '*';
edit.label.setText(title);
// update components
gui.refreshControls();
posCode.invokeLater();
}
/** Code for setting cursor position. */
final GUICode posCode = new GUICode() {
@Override
public void eval(final Object arg) {
final int[] lc = getEditor().pos();
pos.setText(lc[0] + " : " + lc[1]);
}
};
/**
* Finds the editor that contains the specified file.
* @param file file to be found
* @param opened considers only opened files
* @return editor
*/
EditorArea find(final IO file, final boolean opened) {
for(final EditorArea edit : editors()) {
if(edit.file.eq(file) && (!opened || edit.opened())) return edit;
}
return null;
}
/**
* Saves the specified editor contents.
* @param file file to write
* @return {@code false} if confirmation was canceled
*/
private boolean save(final IOFile file) {
try {
final EditorArea edit = getEditor();
file.write(edit.getText());
edit.file(file);
return true;
} catch(final IOException ex) {
BaseXDialog.error(gui, FILE_NOT_SAVED);
return false;
}
}
/**
* Choose a unique tab file.
* @return io reference
*/
private IOFile newTabFile() {
// collect numbers of existing files
final BoolList bl = new BoolList();
for(final EditorArea edit : editors()) {
if(edit.opened()) continue;
final String n = edit.file.name().substring(FILE.length());
bl.set(n.isEmpty() ? 1 : Integer.parseInt(n), true);
}
// find first free file number
int c = 0;
while(++c < bl.size() && bl.get(c));
// create io reference
return new IOFile(gui.gprop.get(GUIProp.WORKPATH), FILE + (c == 1 ? "" : c));
}
/**
* Adds a new editor tab.
* @return editor reference
*/
EditorArea addTab() {
final EditorArea edit = new EditorArea(this, newTabFile());
edit.setFont(GUIConstants.mfont);
final BaseXBack tab = new BaseXBack(new BorderLayout(10, 0)).mode(Fill.NONE);
tab.add(edit.label, BorderLayout.CENTER);
final BaseXButton close = tabButton("e_close");
close.setRolloverIcon(BaseXLayout.icon("e_close2"));
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
close(edit);
}
});
tab.add(close, BorderLayout.EAST);
tabs.add(edit, tab, tabs.getComponentCount() - 2);
return edit;
}
/**
* Adds a tab for creating new tabs.
*/
private void addCreateTab() {
final BaseXButton add = tabButton("e_new");
add.setRolloverIcon(BaseXLayout.icon("e_new2"));
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
addTab();
refreshControls(true);
}
});
tabs.add(new BaseXBack(), add, 0);
tabs.setEnabledAt(0, false);
}
/**
* Adds a new tab button.
* @param icon button icon
* @return button
*/
private BaseXButton tabButton(final String icon) {
final BaseXButton b = new BaseXButton(gui, icon, null);
b.border(2, 2, 2, 2).setContentAreaFilled(false);
b.setFocusable(false);
return b;
}
/**
* Shows a quit dialog for the specified editor.
* @param edit editor to be saved
* @return {@code false} if confirmation was canceled
*/
private boolean confirm(final EditorArea edit) {
if(edit.modified && (edit.opened() || edit.getText().length != 0)) {
final Boolean ok = BaseXDialog.yesNoCancel(gui,
Util.info(CLOSE_FILE_X, edit.file.name()));
if(ok == null || ok && !save()) return false;
}
return true;
}
/**
* Returns all editors.
* @return editors
*/
EditorArea[] editors() {
final ArrayList<EditorArea> edits = new ArrayList<EditorArea>();
for(final Component c : tabs.getComponents()) {
if(c instanceof EditorArea) edits.add((EditorArea) c);
}
return edits.toArray(new EditorArea[edits.size()]);
}
} |
package ireader.home;
import ireader.adapter.AppListAdapter;
import ireader.adapter.AppSelectListAdapter;
import ireader.provider.UidDetailDbProvider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import base.util.StringComparator;
import base.util.TaskHelper;
import base.util.Util;
import com.android.settings.net.UidDetail;
import com.android.settings.net.UidDetailProvider;
import com.github.promeg.pinyinhelper.Pinyin;
import com.way.plistview.BladeView;
import com.way.plistview.PinnedHeaderListView;
import com.way.plistview.BladeView.OnItemClickListener;
import de.greenrobot.event.EventBus;
import fi.iki.asb.android.logo.TextViewUndoRedo;
import floating.lib.Dragger;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
public class Home extends Activity implements TextWatcher {
private List<UidDetail> mAllApps, mSystemApps, mUserApps, mCurrentApps;
private PinnedHeaderListView mAppListView;
private ListView mSearchListView;
private View mAppContainer, mSearchContainer;
private View mShadowView;
private AnimatorSet mStartSearchAnimatorSet, mStopSearchAnimatorSet;
private BladeView mLetter;
private AppListAdapter mAppListAdapter;
private AppSelectListAdapter mAppSelectListAdapter;
private UidDetailProvider mUidDetailProvider;
// collection of first character of apps
private List<String> mSections = new ArrayList<String>();
// position of each first-character
private List<Integer> mPositions = new ArrayList<Integer>();
// collection of positions
private Map<String, Integer> mIndexer = new HashMap<String, Integer>();
private EditText mSearchEditText;
private TextViewUndoRedo mUndoRedo;
private InputMethodManager mInputManager;
private static final int APP_ALL = 0;
private static final int APP_SYSTEM = 1;
private static final int APP_USER = 2;
//private static final int APP_GRIDVIEW = 3;
private int mAppGroup = APP_ALL;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAppListView = (PinnedHeaderListView) findViewById(R.id.apps);
mAppListView.setEmptyView(findViewById(R.id.app_list_empty));
AsyncTask<Void, Void, Void> firstTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
getAllApp();
mUidDetailProvider = new UidDetailProvider(Home.this);
mAppListAdapter = new AppListAdapter(Home.this, mUidDetailProvider, mAllApps, mSections, mPositions);
mHandler.sendEmptyMessage(GET_ALL_OK);
return null;
}
};
TaskHelper.execute(firstTask);
mAppListView.setPinnedHeaderView(
LayoutInflater.from(this).inflate(R.layout.biz_plugin_weather_list_group_item, mAppListView,
false));
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
mLetter = (BladeView) findViewById(R.id.app_bladeview);
mLetter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(String s) {
if (!s.matches(FORMAT)) {
s = "
}
if (mIndexer.get(s) != null) {
mAppListView.setSelection(mIndexer.get(s));
}
}
});
mLetter.setCharHeight(dm.density);
mSearchEditText = (EditText) findViewById(R.id.search_edit);
mSearchEditText.addTextChangedListener(this);
mSearchEditText.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
startSearchBarAnimation();
return false;
}
});
mUndoRedo = new TextViewUndoRedo(mSearchEditText);
mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mAppContainer = findViewById(R.id.app_content_container);
mSearchContainer = findViewById(R.id.search_content_container);
mSearchListView = (ListView) findViewById(R.id.search_list);
mSearchListView.setEmptyView(findViewById(R.id.search_empty));
mShadowView = findViewById(R.id.shadow_view);
mShadowView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopSearchBarAnimation();
}
});
// for package add/remove
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
registerReceiver(packageReceiver, filter);
EventBus.getDefault().register(this);
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
unregisterReceiver(packageReceiver);
super.onDestroy();
}
@Override
public void onResume() {
super.onResume();
stopService(new Intent(this, Dragger.class));
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getRepeatCount() == 0) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mAppContainer.getVisibility() == View.VISIBLE) {
if (mIntent != null) {
try {
startActivity(mIntent);
startService(new Intent(Home.this, Dragger.class));
} catch(ActivityNotFoundException e) {}
}
} else {
if (mUndoRedo.getCanUndo()) {
mUndoRedo.undo();
} else if (mUndoRedo.getCanRedo()) {
mUndoRedo.redo();
}
}
return true;
}
}
return false;
}
Intent mIntent;
public void onEventMainThread(Intent intent) {
mIntent = intent;
}
private static final String FORMAT = "^[A-Z]+$";
private UidDetail prepareInfo(ResolveInfo info, boolean block) {
UidDetail detail = new UidDetail();
detail.info = info;
String label = (String) info.loadLabel(mPm);
if (TextUtils.isEmpty(label)) {
label = info.activityInfo.name;
}
detail.label = label;
detail.className = info.activityInfo.name;
detail.hashCode = info.activityInfo.packageName.hashCode();
detail.isSystem = (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM;
detail.packageName = info.activityInfo.packageName;
detail.sourceDir = info.activityInfo.applicationInfo.sourceDir;
if (block) {
Util.extractDetail(detail, mPm);
Util.update(detail, getContentResolver());
} else {
detail.pinyin = Pinyin.toPinyin(label.charAt(0)).toUpperCase();
}
return detail;
}
private void preparePosition() {
mSections.clear();
mPositions.clear();
mIndexer.clear();
switch (mAppGroup) {
case APP_ALL:
mCurrentApps = mAllApps;
break;
case APP_SYSTEM:
mCurrentApps = mSystemApps;
break;
case APP_USER:
mCurrentApps = mUserApps;
break;
}
Collections.sort(mCurrentApps, new StringComparator());// sort by name
for (int i = 0; i < mCurrentApps.size(); i++) {
String firstName = mCurrentApps.get(i).pinyin.substring(0, 1);
if (firstName.matches(FORMAT)) {
if (!mSections.contains(firstName)) {
mSections.add(firstName);
mPositions.add(i);
mIndexer.put(firstName, i);
}
} else {
if (!mSections.contains("
mSections.add("
mPositions.add(i);
mIndexer.put("
}
}
}
if (mAppListAdapter != null) {
mAppListAdapter.setApps(mCurrentApps);
}
}
PackageManager mPm;
private void getAllApp() {
mAllApps = new ArrayList<UidDetail>();
mSystemApps = new ArrayList<UidDetail>();
mUserApps = new ArrayList<UidDetail>();
mPm = getPackageManager();
Cursor cursor = getContentResolver().query(UidDetailDbProvider.CONTENT_URI_APP_DETAIL, null, null, null, UidDetailDbProvider.PINYIN);
if (cursor != null && cursor.moveToFirst()) {
while (cursor.moveToNext()) {
UidDetail detail = new UidDetail();
Util.query(detail, cursor);
if (detail.label != null) {
mAllApps.add(detail);
if (detail.isSystem) {
mSystemApps.add(detail);
} else {
mUserApps.add(detail);
}
}
}
cursor.close();
if (mAllApps.size() == 0) {
// sth wrong when read db. still read from package manager
queryMain(false);
} else {
syncDB();
}
} else {
queryMain(false);
}
preparePosition();
}
private void syncDB() {
for (int i = 0; i < mAllApps.size(); i++) {
if (mAllApps.get(i).icon == null) {
Util.queryIcon(mAllApps.get(i), getContentResolver());
}
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> apps = mPm.queryIntentActivities(mainIntent, 0);
for (int i = 0; i < apps.size(); i++) {
ResolveInfo info = apps.get(i);
String packageName = info.activityInfo.packageName;
String versionName;
try {
versionName = mPm.getPackageInfo(packageName, 0).versionName;
if ((versionName == null) || (versionName.trim().equals("")))
versionName = String.valueOf(mPm.getPackageInfo(packageName, 0).versionCode);
} catch (NameNotFoundException e) {
versionName = e.toString();
}
boolean found = false;
for (int j = 0; j < mAllApps.size(); j++) {
if (mAllApps.get(j).packageName.equals(info.activityInfo.packageName)) {
found = true;
if (mAllApps.get(j).versionName.equals(versionName)) {
mAllApps.get(j).found = true;
break;
} else {
mAllApps.remove(j);
mAllApps.add(j, prepareInfo(info, true));
mAllApps.get(j).found = true;
break;
}
}
}
if (!found) {
UidDetail detail = prepareInfo(info, true);
detail.found = true;
mAllApps.add(detail);
if (detail.isSystem) {
mSystemApps.add(detail);
} else {
mUserApps.add(detail);
}
}
}
int i = 0;
while (i < mAllApps.size()) {
UidDetail detail = mAllApps.get(i);
if (!detail.found) {
mAllApps.remove(i);
if (detail.isSystem) {
mSystemApps.remove(detail);
} else {
mUserApps.remove(detail);
}
getContentResolver().delete(UidDetailDbProvider.CONTENT_URI_APP_DETAIL, UidDetailDbProvider.HASH_CODE + "=" + detail.hashCode, null);
} else {
i += 1;
}
}
}
private void queryMain(boolean block) {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> apps = mPm.queryIntentActivities(mainIntent, 0);
for (int i = 0; i < apps.size(); i++) {
ResolveInfo info = apps.get(i);
UidDetail detail = prepareInfo(info, block);
mAllApps.add(detail);
if (detail.isSystem) {
mSystemApps.add(detail);
} else {
mUserApps.add(detail);
}
}
if (!block) {
AsyncTask<Void, Void, Void> queryIconTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... arg0) {
for (int i = 0; i < mAllApps.size(); i++) {
UidDetail detail = mAllApps.get(i);
Util.extractDetail(detail, mPm);
Util.update(detail, getContentResolver());
// release reference for info, so that it can release memory by gc
detail.info = null;
}
mHandler.sendEmptyMessage(QUERY_ICON_OK);
return null;
}
};
TaskHelper.execute(queryIconTask);
}
}
private static final int GET_ALL_OK = 0;
private static final int SYNC_DB_OK = 1;
private static final int QUERY_ICON_OK = 2;
private class AppHandler extends Handler {
public void handleMessage(Message msg) {
switch(msg.what) {
case GET_ALL_OK:
mAppListView.setAdapter(mAppListAdapter);
mAppListView.setOnScrollListener(mAppListAdapter);
break;
case SYNC_DB_OK:
prepareAll();
break;
case QUERY_ICON_OK:
mAppListAdapter.notifyDataSetChanged();
}
}
}
AppHandler mHandler = new AppHandler();
private void prepareAll() {
preparePosition();
mAppListAdapter.setSections(mSections);
mAppListAdapter.setPositions(mPositions);
mAppListAdapter.notifyDataSetChanged();
}
private void removeInfo(String packageName) {
for (int i = 0; i < mAllApps.size(); i++) {
UidDetail detail = mAllApps.get(i);
if (detail.packageName.equals(packageName)) {
mAllApps.remove(i);
mSystemApps.remove(detail);
mUserApps.remove(detail);
getContentResolver().delete(UidDetailDbProvider.CONTENT_URI_APP_DETAIL, UidDetailDbProvider.HASH_CODE + "=" + detail.hashCode, null);
break;
}
}
}
BroadcastReceiver packageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String packageName = intent.getDataString().split(":")[1];
if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
removeInfo(packageName);
prepareAll();
} else if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mainIntent.setPackage(packageName);
List<ResolveInfo> targetApps = mPm.queryIntentActivities(mainIntent, 0);
// the new package may not support launcher. so filter it at first
for (int i = 0; i < targetApps.size(); i++) {
ResolveInfo info = targetApps.get(i);
if (info.activityInfo.packageName.equals(packageName)) {
UidDetail detail = prepareInfo(info, true);
mAllApps.add(detail);
if (detail.isSystem) {
mSystemApps.add(detail);
} else {
mUserApps.add(detail);
}
prepareAll();
break;
}
}
}
}
};
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mShadowView.setVisibility(View.GONE);
if (TextUtils.isEmpty(s)) {
mAppContainer.setVisibility(View.VISIBLE);
mSearchContainer.setVisibility(View.GONE);
} else {
mAppContainer.setVisibility(View.GONE);
mSearchContainer.setVisibility(View.VISIBLE);
mAppSelectListAdapter = new AppSelectListAdapter(Home.this, mUidDetailProvider, mCurrentApps, mSections, mPositions);
mSearchListView.setTextFilterEnabled(true);
mSearchListView.setAdapter(mAppSelectListAdapter);
mAppSelectListAdapter.getFilter().filter(s);
}
}
@Override
public void afterTextChanged(Editable s) {
}
private void startSearchBarAnimation() {
if (android.os.Build.VERSION.SDK_INT < 11 || mShadowView.getVisibility() == View.VISIBLE) {
return;
}
mShadowView.setAlpha(0);
mShadowView.setVisibility(View.VISIBLE);
if (mStartSearchAnimatorSet != null && !mStartSearchAnimatorSet.isRunning()) {
mStartSearchAnimatorSet.start();
return;
}
PropertyValuesHolder holderAlpha = PropertyValuesHolder.ofFloat("alpha", 0, 1);
Animator animatorAlpha = ObjectAnimator.ofPropertyValuesHolder(mShadowView, holderAlpha);
mStartSearchAnimatorSet = new AnimatorSet();
mStartSearchAnimatorSet.setStartDelay(10);
mStartSearchAnimatorSet.setDuration(200);
mStartSearchAnimatorSet.playTogether(animatorAlpha);
mStartSearchAnimatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator arg0) {
}
});
mStartSearchAnimatorSet.start();
}
private void stopSearchBarAnimation() {
if (android.os.Build.VERSION.SDK_INT < 11 || mShadowView.getVisibility() == View.GONE) {
return;
}
if (mStopSearchAnimatorSet != null && !mStopSearchAnimatorSet.isRunning()) {
mStopSearchAnimatorSet.start();
return;
}
PropertyValuesHolder holderAlpha = PropertyValuesHolder.ofFloat("alpha", 1, 0);
Animator animatorAlpha = ObjectAnimator.ofPropertyValuesHolder(mShadowView, holderAlpha);
mStopSearchAnimatorSet = new AnimatorSet();
mStopSearchAnimatorSet.setDuration(200);
mStopSearchAnimatorSet.playTogether(animatorAlpha);
mStopSearchAnimatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator arg0) {
searchAnimationEnd();
}
@Override
public void onAnimationCancel(Animator arg0) {
searchAnimationEnd();
}
});
mStopSearchAnimatorSet.start();
}
private void searchAnimationEnd() {
mShadowView.setVisibility(View.GONE);
mSearchEditText.clearFocus();
mInputManager.hideSoftInputFromWindow(mSearchEditText.getWindowToken(), 0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, APP_ALL, 0, "all");
menu.add(0, APP_SYSTEM, 0, "system");
menu.add(0, APP_USER, 0, "user");
//menu.add(0, APP_GRIDVIEW, 0, "GridView");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mAppGroup != item.getItemId()) {
mAppGroup = item.getItemId();
prepareAll();
}
return super.onOptionsItemSelected(item);
}
} |
package org.bitvector.microservice2;
import akka.actor.ActorContext;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.undertow.Handlers;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.RoutingHandler;
import io.undertow.server.handlers.Cookie;
import io.undertow.util.Cookies;
import io.undertow.util.Headers;
import io.undertow.util.Methods;
import io.undertow.util.StatusCodes;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.Date;
import java.util.Objects;
public class BaseCtrl {
protected RoutingHandler routingHandler;
protected LoggingAdapter log;
protected SettingsImpl settings;
public BaseCtrl(ActorContext context) {
log = Logging.getLogger(context.system(), this);
settings = Settings.get(context.system());
routingHandler = Handlers.routing()
.add(Methods.GET, "/logout", exchange -> exchange.dispatch(this::doLogout))
.add(Methods.GET, "/login", exchange -> exchange.dispatch(this::doLogin));
}
public RoutingHandler getRoutingHandler() {
return routingHandler;
}
private void doLogin(HttpServerExchange exchange) {
try {
// Assert SSL was used on frontend
String xForwardedProtoHeader = exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_PROTO);
if (xForwardedProtoHeader == null) {
throw new BadBasicAuth("No x-forwarded-proto header");
}
if (!Objects.equals(xForwardedProtoHeader.toLowerCase().trim(), "https")) {
throw new BadBasicAuth("No https encryption");
}
// Collect the subject's username and password via HTTP xBasic scheme.
String authorizationHeader = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION);
if (authorizationHeader == null) {
throw new BadBasicAuth("No HTTP authorization header");
}
String[] schemeAndValue = authorizationHeader.split(" ");
if (schemeAndValue.length != 2) {
throw new BadBasicAuth("Bad HTTP authorization header");
}
if (!Objects.equals(schemeAndValue[0].toLowerCase().trim(), "x" + Headers.BASIC.toString().toLowerCase())) {
throw new BadBasicAuth("Bad authentication scheme");
}
byte[] buffer = Base64.getDecoder().decode(schemeAndValue[1]);
String[] usernameAndPassword = new String(buffer, Charset.forName("utf-8")).split(":");
if (usernameAndPassword.length != 2) {
throw new BadBasicAuth("Bad authentication parameter");
}
// Verify the subject's username and password with Shiro
Subject currentSubject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(usernameAndPassword[0].trim(), usernameAndPassword[1].trim());
token.setRememberMe(true);
currentSubject.login(token);
// Create a server side session to remember the subject
Session currentSession = currentSubject.getSession(true);
currentSession.setTimeout(3600 * 1000); // 1 hour in-activity timeout
// Build a cookie with a JWT value both having 24 hr lifespan.
Date jwtExpireAt = new Date(System.currentTimeMillis() + (24 * 3600 * 1000));
Date cookieExpireAt = new Date(System.currentTimeMillis() + (24 * 3600 * 1000));
String jwt = Jwts.builder()
.setId(currentSession.getId().toString())
.setSubject(currentSubject.getPrincipal().toString())
.setExpiration(jwtExpireAt)
.setIssuer(this.getClass().getPackage().getName())
.signWith(SignatureAlgorithm.HS512, Base64.getDecoder().decode(settings.SECRET_KEY()))
.compact();
Cookie accessTokenCookie = Cookies.parseSetCookieHeader("access_token" + "=" + jwt + ";")
.setExpires(cookieExpireAt)
.setSecure(true)
.setHttpOnly(true);
// Respond to subject with cookie
exchange.getResponseCookies().put("0", accessTokenCookie);
exchange.setStatusCode(StatusCodes.OK);
exchange.getResponseSender().close();
} catch (Exception e) {
// FIXME - need to break out and handle specific exceptions accordingly - maybe
log.error("Caught exception: " + e.getMessage());
exchange.setStatusCode(StatusCodes.UNAUTHORIZED);
exchange.getResponseHeaders().put(Headers.WWW_AUTHENTICATE, "x" + Headers.BASIC.toString() + " " + Headers.REALM + "=" + "Login");
exchange.getResponseSender().close();
}
}
private void doLogout(HttpServerExchange exchange) {
try {
Subject currentSubject = verifySubject(exchange);
currentSubject.logout();
Date cookieExpireAt = new Date(System.currentTimeMillis() + (24 * 3600 * 1000));
Cookie accessTokenCookie = Cookies.parseSetCookieHeader("access_token" + "=" + "null" + ";")
.setExpires(cookieExpireAt)
.setSecure(true)
.setHttpOnly(true);
// Respond to subject with nullified cookie
// exchange.getResponseCookies().put("0", accessTokenCookie);
exchange.setStatusCode(StatusCodes.OK);
exchange.getResponseSender().close();
} catch (Exception e) {
rejectSubject(exchange, e);
}
}
protected Subject verifySubject(HttpServerExchange exchange) throws Exception {
// Assert SSL was used on frontend
String xForwardedProtoHeader = exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_PROTO);
if (xForwardedProtoHeader == null) {
throw new BadTokenAuth("No x-forwarded-proto header");
}
if (!Objects.equals(xForwardedProtoHeader.toLowerCase().trim(), "https")) {
throw new BadTokenAuth("No https encryption");
}
// Verify Authorization header not set
String authorizationHeader = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION);
if (authorizationHeader != null) {
throw new BadTokenAuth("Authorization header present");
}
// Get the cookie back from subject
Cookie accessTokenCookie = exchange.getRequestCookies().get("access_token");
if (accessTokenCookie == null) {
throw new BadTokenAuth("No access_token cookie");
}
// Get the claims back from JWT
Claims claims = Jwts.parser()
.setSigningKey(Base64.getDecoder().decode(settings.SECRET_KEY()))
.parseClaimsJws(accessTokenCookie.getValue())
.getBody();
// Load subject from server side session
Subject currentSubject = new Subject.Builder()
.sessionId(claims.getId())
.buildSubject();
if (!Objects.equals(currentSubject.getPrincipal(), claims.getSubject())) {
throw new BadTokenAuth("No matching subject found");
}
return currentSubject;
}
protected void rejectSubject(HttpServerExchange exchange, Exception e) {
// FIXME - need to break out and handle specific exceptions accordingly - maybe
log.error("Caught exception: " + e.getMessage());
exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
exchange.getResponseHeaders().put(Headers.LOCATION, "/login");
exchange.getResponseSender().close();
}
public static class BadBasicAuth extends Exception {
public BadBasicAuth(String message) {
super(message);
}
}
public static class BadTokenAuth extends Exception {
public BadTokenAuth(String message) {
super(message);
}
}
} |
package nxt;
import nxt.db.DbClause;
import nxt.db.DbIterator;
import nxt.db.DbKey;
import nxt.db.VersionedEntityDbTable;
import nxt.util.Convert;
import nxt.util.Listener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
public final class Currency {
private static final DbKey.LongKeyFactory<Currency> currencyDbKeyFactory = new DbKey.LongKeyFactory<Currency>("id") {
@Override
public DbKey newKey(Currency currency) {
return currency.dbKey;
}
};
private static final VersionedEntityDbTable<Currency> currencyTable = new VersionedEntityDbTable<Currency>("currency", currencyDbKeyFactory) {
@Override
protected Currency load(Connection con, ResultSet rs) throws SQLException {
return new Currency(rs);
}
@Override
protected void save(Connection con, Currency currency) throws SQLException {
currency.save(con);
}
};
public static DbIterator<Currency> getAllCurrencies(int from, int to) {
return currencyTable.getAll(from, to);
}
public static int getCount() {
return currencyTable.getCount();
}
public static Currency getCurrency(long id) {
return currencyTable.get(currencyDbKeyFactory.newKey(id));
}
public static Currency getCurrencyByName(String name) {
return currencyTable.getBy(new DbClause.StringClause("name_lower", name.toLowerCase()));
}
public static Currency getCurrencyByCode(String code) {
return currencyTable.getBy(new DbClause.StringClause("code", code));
}
public static DbIterator<Currency> getCurrencyIssuedBy(long accountId, int from, int to) {
return currencyTable.getManyBy(new DbClause.LongClause("account_id", accountId), from, to);
}
static void addCurrency(Transaction transaction, Attachment.MonetarySystemCurrencyIssuance attachment) {
Currency oldCurrency;
if ((oldCurrency = Currency.getCurrencyByCode(attachment.getCode())) != null) {
oldCurrency.delete(transaction.getSenderId());
}
if ((oldCurrency = Currency.getCurrencyByCode(attachment.getName().toUpperCase())) != null) {
oldCurrency.delete(transaction.getSenderId());
}
if ((oldCurrency = Currency.getCurrencyByName(attachment.getName())) != null) {
oldCurrency.delete(transaction.getSenderId());
}
if ((oldCurrency = Currency.getCurrencyByName(attachment.getCode())) != null) {
oldCurrency.delete(transaction.getSenderId());
}
currencyTable.insert(new Currency(transaction, attachment));
}
static {
Nxt.getBlockchainProcessor().addListener(new CrowdFundingListener(), BlockchainProcessor.Event.AFTER_BLOCK_APPLY);
}
static void init() {}
private final long currencyId;
private final DbKey dbKey;
private final long accountId;
private final String name;
private final String code;
private final String description;
private final int type;
private long totalSupply;
private final int issuanceHeight;
private final long minReservePerUnitNQT;
private final byte minDifficulty;
private final byte maxDifficulty;
private final byte ruleset;
private final byte algorithm;
private final byte decimals;
private long currentSupply;
private long currentReservePerUnitNQT;
private Currency(Transaction transaction, Attachment.MonetarySystemCurrencyIssuance attachment) {
this.currencyId = transaction.getId();
this.dbKey = currencyDbKeyFactory.newKey(this.currencyId);
this.accountId = transaction.getSenderId();
this.name = attachment.getName();
this.code = attachment.getCode();
this.description = attachment.getDescription();
this.type = attachment.getType();
this.totalSupply = attachment.getTotalSupply();
this.issuanceHeight = attachment.getIssuanceHeight();
this.minReservePerUnitNQT = attachment.getMinReservePerUnitNQT();
this.minDifficulty = attachment.getMinDifficulty();
this.maxDifficulty = attachment.getMaxDifficulty();
this.ruleset = attachment.getRuleset();
this.algorithm = attachment.getAlgorithm();
this.decimals = attachment.getDecimals();
this.currentSupply = attachment.getCurrentSupply();
this.currentReservePerUnitNQT = 0;
}
private Currency(ResultSet rs) throws SQLException {
this.currencyId = rs.getLong("id");
this.dbKey = currencyDbKeyFactory.newKey(this.currencyId);
this.accountId = rs.getLong("account_id");
this.name = rs.getString("name");
this.code = rs.getString("code");
this.description = rs.getString("description");
this.type = rs.getInt("type");
this.totalSupply = rs.getLong("total_supply");
this.issuanceHeight = rs.getInt("issuance_height");
this.minReservePerUnitNQT = rs.getLong("min_reserve_per_unit_nqt");
this.minDifficulty = rs.getByte("min_difficulty");
this.maxDifficulty = rs.getByte("max_difficulty");
this.ruleset = rs.getByte("ruleset");
this.algorithm = rs.getByte("algorithm");
this.decimals = rs.getByte("decimals");
this.currentSupply = rs.getLong("current_supply");
this.currentReservePerUnitNQT = rs.getLong("current_reserve_per_unit_nqt");
}
private void save(Connection con) throws SQLException {
try (PreparedStatement pstmt = con.prepareStatement("MERGE INTO currency (id, account_id, name, code, "
+ "description, type, total_supply, issuance_height, min_reserve_per_unit_nqt, "
+ "min_difficulty, max_difficulty, ruleset, algorithm, decimals, current_supply, current_reserve_per_unit_nqt, height, latest) "
+ "KEY (id, height) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, TRUE)")) {
int i = 0;
pstmt.setLong(++i, this.getId());
pstmt.setLong(++i, this.getAccountId());
pstmt.setString(++i, this.getName());
pstmt.setString(++i, this.getCode());
pstmt.setString(++i, this.getDescription());
pstmt.setInt(++i, this.getType());
pstmt.setLong(++i, this.getTotalSupply());
pstmt.setInt(++i, this.getIssuanceHeight());
pstmt.setLong(++i, this.getMinReservePerUnitNQT());
pstmt.setByte(++i, this.getMinDifficulty());
pstmt.setByte(++i, this.getMaxDifficulty());
pstmt.setByte(++i, this.getRuleset());
pstmt.setByte(++i, this.getAlgorithm());
pstmt.setByte(++i, this.getDecimals());
pstmt.setLong(++i, this.getCurrentSupply());
pstmt.setLong(++i, this.getCurrentReservePerUnitNQT());
pstmt.setInt(++i, Nxt.getBlockchain().getHeight());
pstmt.executeUpdate();
}
}
public long getId() {
return currencyId;
}
public long getAccountId() {
return accountId;
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
public int getType() {
return type;
}
public long getTotalSupply() {
return totalSupply;
}
public int getIssuanceHeight() {
return issuanceHeight;
}
public long getMinReservePerUnitNQT() {
return minReservePerUnitNQT;
}
public byte getMinDifficulty() {
return minDifficulty;
}
public byte getMaxDifficulty() {
return maxDifficulty;
}
public byte getRuleset() {
return ruleset;
}
public byte getAlgorithm() {
return algorithm;
}
public byte getDecimals() {
return decimals;
}
public long getCurrentSupply() {
return currentSupply;
}
public long getCurrentReservePerUnitNQT() {
return currentReservePerUnitNQT;
}
public boolean isActive() {
return issuanceHeight <= BlockchainImpl.getInstance().getHeight();
}
static void increaseReserve(Account account, long currencyId, long amountNQT) {
Currency currency = Currency.getCurrency(currencyId);
account.addToBalanceNQT(-Convert.safeMultiply(currency.getTotalSupply(), amountNQT));
currency.currentReservePerUnitNQT += amountNQT;
currencyTable.insert(currency);
CurrencyFounder.addOrUpdateFounder(currencyId, account.getId(), Convert.safeMultiply(currency.getTotalSupply(), amountNQT));
}
static void claimReserve(Account account, long currencyId, long units) {
account.addToCurrencyUnits(currencyId, -units);
Currency currency = Currency.getCurrency(currencyId);
currency.totalSupply -= units;
currencyTable.insert(currency);
account.addToBalanceAndUnconfirmedBalanceNQT(Convert.safeMultiply(units, currency.getCurrentReservePerUnitNQT()));
}
static void transferCurrency(Account senderAccount, Account recipientAccount, long currencyId, long units) {
senderAccount.addToCurrencyUnits(currencyId, -units);
recipientAccount.addToCurrencyAndUnconfirmedCurrencyUnits(currencyId, units);
}
void increaseSupply(long units) {
currentSupply += units;
currencyTable.insert(this);
}
public DbIterator<Account.AccountCurrency> getAccounts(int from, int to) {
return Account.getCurrencyAccounts(this.currencyId, from, to);
}
public DbIterator<Account.AccountCurrency> getAccounts(int height, int from, int to) {
if (height < 0) {
return getAccounts(from, to);
}
return Account.getCurrencyAccounts(this.currencyId, height, from, to);
}
public DbIterator<Exchange> getExchanges(int from, int to) {
return Exchange.getCurrencyExchanges(this.currencyId, from, to);
}
public DbIterator<CurrencyTransfer> getTransfers(int from, int to) {
return CurrencyTransfer.getCurrencyTransfers(this.currencyId, from, to);
}
public boolean is(CurrencyType type) {
return (this.type & type.getCode()) != 0;
}
boolean canBeDeletedBy(long ownerAccountId) {
if (!isActive()) {
return false;
}
if (is(CurrencyType.MINTABLE) && currentSupply < totalSupply && ownerAccountId != accountId) {
return false;
}
try (DbIterator<Account.AccountCurrency> accountCurrencies = Account.getCurrencyAccounts(this.currencyId, 0, -1)) {
return ! accountCurrencies.hasNext() || accountCurrencies.next().getAccountId() == ownerAccountId && ! accountCurrencies.hasNext();
}
}
void delete(long ownerAccountId) {
if (!canBeDeletedBy(ownerAccountId)) {
// shouldn't happen as ownership has already been checked in validate, but as a safety check
throw new IllegalStateException("Currency " + Convert.toUnsignedLong(currencyId) + " not entirely owned by " + Convert.toUnsignedLong(ownerAccountId));
}
Account ownerAccount = Account.getAccount(ownerAccountId);
if (is(CurrencyType.RESERVABLE)) {
Currency.claimReserve(ownerAccount, currencyId, ownerAccount.getCurrencyUnits(currencyId));
CurrencyFounder.remove(currencyId);
}
if (is(CurrencyType.EXCHANGEABLE)) {
List<CurrencyBuyOffer> buyOffers = new ArrayList<>();
try (DbIterator<CurrencyBuyOffer> offers = CurrencyBuyOffer.getOffers(this, 0, -1)) {
while (offers.hasNext()) {
buyOffers.add(offers.next());
}
}
for (CurrencyBuyOffer offer : buyOffers) {
CurrencyExchangeOffer.removeOffer(offer);
}
}
if (is(CurrencyType.MINTABLE)) {
CurrencyMint.deleteCurrency(this);
}
ownerAccount.addToCurrencyUnits(currencyId, -ownerAccount.getCurrencyUnits(currencyId));
ownerAccount.addToUnconfirmedCurrencyUnits(currencyId, -ownerAccount.getUnconfirmedCurrencyUnits(currencyId));
//TODO: anything else to clean up when deleting a currency?
currencyTable.delete(this);
}
private static final class CrowdFundingListener implements Listener<Block> {
@Override
public void notify(Block block) {
try (DbIterator<Currency> issuedCurrencies = currencyTable.getManyBy(new DbClause.IntClause("issuance_height", block.getHeight()), 0, -1)) {
for (Currency currency : issuedCurrencies) {
if (currency.getCurrentReservePerUnitNQT() < currency.getMinReservePerUnitNQT()) {
undoCrowdFunding(currency);
} else {
distributeCurrency(currency);
}
}
}
}
private void undoCrowdFunding(Currency currency) {
try (DbIterator<CurrencyFounder> founders = CurrencyFounder.getCurrencyFounders(currency.getId(), 0, Integer.MAX_VALUE)) {
for (CurrencyFounder founder : founders) {
Account.getAccount(founder.getAccountId()).addToBalanceAndUnconfirmedBalanceNQT(founder.getValue());
}
}
currencyTable.delete(currency);
CurrencyFounder.remove(currency.getId());
}
private void distributeCurrency(Currency currency) {
long totalValue = 0;
List<CurrencyFounder> currencyFounders = new ArrayList<>();
try (DbIterator<CurrencyFounder> founders = CurrencyFounder.getCurrencyFounders(currency.getId(), 0, Integer.MAX_VALUE)) {
for (CurrencyFounder founder : founders) {
totalValue += founder.getValue();
currencyFounders.add(founder);
}
}
for (CurrencyFounder founder : currencyFounders) {
long units = Convert.safeDivide(Convert.safeMultiply(currency.getTotalSupply(), founder.getValue()), totalValue);
Account.getAccount(founder.getAccountId()).addToCurrencyAndUnconfirmedCurrencyUnits(currency.getId(), units);
}
}
}
} |
package com.aspose.imaging.examples;
import java.io.File;
public class Utils {
public static String getDataDir(Class c) {
File dir = new File(System.getProperty("user.dir"));
dir = new File(dir, "src");
dir = new File(dir, "main");
dir = new File(dir, "resources");
for (String s : c.getName().split("\\.")) {
dir = new File(dir, s);
}
if (dir.exists()) {
System.out.println("Using data directory: " + dir.toString());
} else {
dir.mkdirs();
System.out.println("Creating data directory: " + dir.toString());
}
return dir.toString() + File.separator;
}
} |
package org.blockjam.core;
import com.google.inject.Inject;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.blockjam.core.config.ConfigKeys;
import org.blockjam.core.config.ConfigManager;
import org.spongepowered.api.config.DefaultConfig;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameInitializationEvent;
import org.spongepowered.api.plugin.Plugin;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
@Plugin(id = "blockjamcore", name = "BlockJamCore")
public final class BlockJamCorePlugin {
public static BlockJamCorePlugin instance;
@Inject @DefaultConfig(sharedRoot = false) private File configFile;
@Inject @DefaultConfig(sharedRoot = false) private ConfigurationLoader<CommentedConfigurationNode> configLoader;
private ConfigManager configManager;
//TODO: make this extendable?
@Listener
public void onPreInitlization(GameInitializationEvent event) {
instance = this;
try {
configManager = new ConfigManager(configFile, configLoader);
configManager.loadDefaults();
} catch (IOException ex) {
throw new RuntimeException("Failed to load config");
}
}
public static BlockJamCorePlugin instance() {
return instance;
}
public static ConfigManager config() {
return instance().configManager;
}
public static byte[] getFromAuthority(String key) throws IOException {
String url = config().get(ConfigKeys.AUTHORITY_URL);
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
byte[] params = ("key=" + key).getBytes(StandardCharsets.UTF_8);
connection.setFixedLengthStreamingMode(params.length);
OutputStream os = connection.getOutputStream();
os.write(params);
// connection.connect() can be omitted because getResponseCode() calls it automatically
if (connection.getResponseCode() / 100 != 2) {
// this just gets caught down below
throw new IOException("Received bad response code from authority server ("
+ connection.getResponseCode() + " " + connection.getResponseMessage() + ")");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int i;
while ((i = connection.getInputStream().read(buffer)) != -1) {
baos.write(buffer, 0, i);
}
return baos.toByteArray();
} catch (MalformedURLException ex) {
throw new RuntimeException("Invalid config value for `authority-url`", ex);
} catch (IOException ex) {
throw new RuntimeException("Encountered connection error while contacting authority server", ex);
}
}
} |
package com.filemanager.occupancy;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.text.format.Formatter;
import android.util.Log;
import java.io.File;
import java.util.*;
public class StorageScanner extends Thread {
/**
* List of contents is ready.
*/
public static final int MESSAGE_SHOW_STORAGE_ANALYSIS = 526;
private static final String TAG = "StorageScanner";
private File currentDirectory;
private boolean running = false;
boolean cancelled;
private Handler handler;
private FileTreeNode<String> mRoot;
private File mDirectory;
private Context mContext;
private long mBlockSize = 512;
private LinkedList<FileTreeNode<String>> mDir;
private int mResult = 0;
public StorageScanner(File directory, Context context, Handler handler) {
super("Storage analysis Scanner");
currentDirectory = directory;
this.handler = handler;
this.mRoot = new FileTreeNode<>(directory);
this.mDirectory = directory;
this.mContext = context.getApplicationContext();
this.mDir = new LinkedList<>();
StatFs fs = new StatFs(mDirectory.getPath());
mBlockSize = fs.getBlockSize();
}
private void init() {
Log.v(TAG, "Scanning directory " + currentDirectory);
if (cancelled) {
Log.v(TAG, "Scan aborted");
return;
}
}
public void run() {
running = true;
init();
// Scan files
long time = System.currentTimeMillis();
try {
mDir.addFirst(mRoot);
createTreeNodes(mRoot);
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
}
// Return lists
if (!cancelled) {
Iterator iterator = mDir.iterator();
while (iterator.hasNext()) {
FileTreeNode<String> node = (FileTreeNode<String>) iterator.next();
node.refresh();
}
Log.e(TAG, "Sending data back to main thread cost time ==>>" + (System.currentTimeMillis() - time) + " size==>>" + Formatter.formatFileSize(mContext, mRoot.size));
Message msg = handler.obtainMessage(MESSAGE_SHOW_STORAGE_ANALYSIS);
msg.obj = mRoot;
msg.sendToTarget();
}
running = false;
}
public void cancel() {
cancelled = true;
}
public boolean isRunning() {
return running;
}
public static class ComparatorBySize implements Comparator<FileTreeNode<String>> {
public int compare(FileTreeNode<String> f1, FileTreeNode<String> f2) {
long diff = f1.size - f2.size;
if (diff > 0)
return -1;
else if (diff == 0)
return 0;
else
return 1;
}
public boolean equals(Object obj) {
return true;
}
}
private void createTreeNodes(FileTreeNode<String> node) {
Stack<FileTreeNode<String>> dirList = new Stack<FileTreeNode<String>>();
dirList.push(node);
while (!dirList.isEmpty()) {
if (cancelled) {
return;
}
FileTreeNode<String> dirCurrent = dirList.pop();
File[] fileList = dirCurrent.data.listFiles();
if(fileList == null){
continue;
}
for (File f : fileList) {
if (cancelled) {
return;
}
if (f == null) {
continue;
}
mResult++;
FileTreeNode<String> tmp = dirCurrent.addChild(f);
if (f.isDirectory()) {
if (cancelled) {
return;
}
mDir.addFirst(tmp);
dirList.push(tmp);
}
}
}
}
public int getResultCount() {
return mResult;
}
} |
package org.cru.godtools.api.v2;
import org.ccci.util.time.Clock;
import org.cru.godtools.api.meta.MetaResults;
import org.cru.godtools.api.meta.MetaService;
import org.cru.godtools.domain.authentication.AuthorizationService;
import org.cru.godtools.s3.AmazonS3GodToolsConfig;
import org.jboss.logging.Logger;
import org.xml.sax.SAXException;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.net.MalformedURLException;
@Path("v2/meta")
public class MetaResource
{
@Inject
AuthorizationService authService;
@Inject
MetaService metaService;
@Inject
Clock clock;
private Logger log = Logger.getLogger(this.getClass());
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getAllMetaInfo(@QueryParam("Authorization") String authCodeParam,
@HeaderParam("Authorization") String authCodeHeader,
@HeaderParam("Accept") MediaType requestedContentType) throws ParserConfigurationException, SAXException, IOException
{
log.info("Getting all meta info");
boolean hasDraftAccess = authService.hasDraftAccess(authCodeParam, authCodeHeader);
boolean hasAdminAccess = authService.hasAdminAccess(authCodeParam, authCodeHeader);
if(hasAdminAccess || hasDraftAccess)
{
// draft meta file is built from the database
MetaResults metaResults = metaService.getAllMetaResults(hasDraftAccess, hasAdminAccess);
return Response
.ok(metaResults)
.type(requestedContentType)
.build();
}
else
{
return Response
.status(Response.Status.MOVED_PERMANENTLY)
.header("Location", AmazonS3GodToolsConfig.getMetaRedirectUrl(requestedContentType))
.build();
}
}
@GET
@Path("/{language}")
@Produces(MediaType.APPLICATION_XML)
public Response getLanguageMetaInfo(@PathParam("language") String languageCode,
@QueryParam("interpreter") Integer minimumInterpreterVersionParam,
@HeaderParam("interpreter") Integer minimumInterpreterVersionHeader,
@QueryParam("Authorization") String authCodeParam,
@HeaderParam("Authorization") String authCodeHeader,
@HeaderParam("Accept") MediaType requestedContentType) throws MalformedURLException
{
log.info("Getting all meta info for language: " + languageCode);
boolean hasDraftAccess = authService.hasDraftAccess(authCodeParam, authCodeHeader);
boolean hasAdminAccess = authService.hasAdminAccess(authCodeParam, authCodeHeader);
if(hasDraftAccess || hasAdminAccess)
{
MetaResults metaResults = metaService.getLanguageMetaResults(languageCode,
hasDraftAccess,
hasAdminAccess);
return Response
.ok(metaResults)
.type(requestedContentType)
.build();
}
else
{
return Response
.status(Response.Status.MOVED_PERMANENTLY)
.header("Location", AmazonS3GodToolsConfig.getMetaRedirectUrl(requestedContentType))
.build();
}
}
@GET
@Path("/{language}/{package}")
@Produces(MediaType.APPLICATION_XML)
public Response getLanguageAndPackageMetaInfo(@PathParam("language") String languageCode,
@PathParam("package") String packageCode,
@QueryParam("interpreter") Integer minimumInterpreterVersionParam,
@HeaderParam("interpreter") Integer minimumInterpreterVersionHeader,
@QueryParam("Authorization") String authCodeParam,
@HeaderParam("Authorization") String authCodeHeader,
@HeaderParam("Accept") MediaType requestedContentType) throws ParserConfigurationException, SAXException, IOException
{
log.info("Getting all meta info for package: " + packageCode + " language: " + languageCode);
boolean hasDraftAccess = authService.hasDraftAccess(authCodeParam, authCodeHeader);
boolean hasAdminAccess = authService.hasAdminAccess(authCodeParam, authCodeHeader);
if(hasDraftAccess || hasAdminAccess)
{
MetaResults metaResults = metaService.getPackageMetaResults(languageCode,
packageCode,
hasDraftAccess,
hasAdminAccess);
return Response
.ok(metaResults)
.type(requestedContentType)
.build();
}
else
{
return Response
.status(Response.Status.MOVED_PERMANENTLY)
.header("Location", AmazonS3GodToolsConfig.getMetaRedirectUrl(requestedContentType))
.build();
}
}
} |
package sulfur;
import com.google.common.base.Function;
import org.apache.log4j.Logger;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import sulfur.configs.SEnvConfig;
import sulfur.configs.SPageConfig;
import sulfur.factories.SWebDriverFactory;
import sulfur.factories.exceptions.SFailedToCreatePageComponentException;
import sulfur.factories.exceptions.SFailedToCreatePageException;
import sulfur.factories.exceptions.SUnavailableComponentException;
import sulfur.factories.exceptions.SUnavailableDriverException;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author Ivan De Marino
*
* Sulfur Page.
* This class is the central "piece of the puzzle".
*
* Sulfur Pages are collection of Sulfur Components, and contain a basic set of methods
* to test the different parts of a page, looking at it as a composition of "widgets".
*
* The page contains also methods to control the loading flux of a page: to make sure HTML/JS has
* been fully loaded, the internal status of all the composing Components can be considered while
* "waiting for load".
*
* Also, the creation of a Page is based on the following input parameters:
* <ul>
* <li>an Environment Configuration</li>
* <li>a Page Configuration</li>
* <li>a WebDriver name</li>
* <li>a map of URL Path Parameters</li>
* <li>a map of URL Query Parameters</li>
* </ul>
*
* Those together contribute to the setting up of the Page, letting the client code focus on the testing aspects,
* abstracting away "environmental parameters".
*/
public class SPage {
private static final Logger LOG = Logger.getLogger(SPage.class);
/** Default Polling time for SPage#waitForLoad */
private static final long PAGELOAD_WAIT_DEFAULT_POLLING_TIME = 100;
/** Default Polling time unit for SPage#waitForLoad */
private static final TimeUnit PAGELOAD_WAIT_DEFAULT_POLLING_UNIT = TimeUnit.MILLISECONDS;
/** Default Timout time unit for SPage#waitForLoad */
private static final TimeUnit PAGELOAD_WAIT_DEFAULT_TIMEOUT_UNIT = TimeUnit.SECONDS;
private boolean mOpened;
private WebDriver mDriver = null;
private final String mInitialUrl;
private final Map<String, SPageComponent> mPageComponents;
private final SPageConfig mPageConfig;
/**
* Copy-constructor.
*
* @param page SPage to copy from. It will also copy the "opened" status.
*/
public SPage(SPage page) {
// Straight copy
mDriver = page.getDriver();
mPageComponents = page.mPageComponents;
mPageConfig = page.mPageConfig;
// If the page is already open, grab the "currentUrl" as "initialUrl" for this new page
if (page.isOpen()) {
mInitialUrl = page.getCurrentUrl();
mOpened = true;
} else {
mInitialUrl = page.getInitialUrl();
mOpened = false;
}
}
/**
* Construct a Page Object, already opened.
* This is used when a Page interaction causes navigation to another page.
*
* NOTE: Calls to {@link SPage#open()} will have no effect.
*
* @param driver WebDriver intance, initialised and with the page already loaded.
* @param config SPageConfig to use for this new SPage
*/
public SPage(WebDriver driver, SPageConfig config) {
mDriver = driver;
mOpened = true;
mInitialUrl = mDriver.getCurrentUrl();
mPageConfig = config;
mPageComponents = createPageComponentInstances(mPageConfig.getComponentClassnames(), this);
}
/**
* Construct a Page Object, using a pre-existing one as "blueprint".
* This is used when a Page interaction causes navigation to another page.
* The original page will become "stale", as it will be deprived of it's original driver, to pass it to
* the new page.
*
* NOTE: Calls to {@link SPage#open()} will have no effect.
*
* @param oldPage Page Object to start from
* @param newConfig SPageConfig to use for this new Page
*/
public SPage(SPage oldPage, SPageConfig newConfig) {
mDriver = oldPage.getDriver();
mOpened = oldPage.isOpen();
mInitialUrl = oldPage.getCurrentUrl();
mPageConfig = newConfig;
mPageComponents = createPageComponentInstances(mPageConfig.getComponentClassnames(), this);
oldPage.mDriver = null; //< NOTE: Takes ownership of the Driver from the "old page"
}
/**
* Construct a Page Object, not yet opened.
* It validates the input parameters, checking if the requested driver exists, if the page exists and the
* mandatory path and query parameters are all provided.
*
* NOTE: The returned SPage hasn't loaded yet, so the User can still operate on it before the initial HTTP GET.
*
* @param envConfig Sulfur Environment Configuration
* @param driverName Desired WebDriver Name
* @param pageConfig Sulfur Page Configuration
* @param pathParams Map of parameters that will be set in the SPage URL Path (@see SPageConfig)
* @param queryParams Map of parameters that will be set in the SPage URL Query (@see SPageConfig)
*/
public SPage(SEnvConfig envConfig,
String driverName,
SPageConfig pageConfig,
Map<String, String> pathParams,
Map<String, String> queryParams) {
// A bit of input validation
if (null == envConfig) {
throw new RuntimeException("Missing/NULL parameter 'envConfig'");
}
if (null == pageConfig) {
throw new RuntimeException("Missing/NULL parameter 'pageConfig'");
}
// New Page, not yet "opened"
mOpened = false;
// Validate Driver Name
if (!envConfig.getDrivers().contains(driverName)) {
LOG.fatal(String.format("FAILED to find WedDriver '%s'", driverName));
throw new SUnavailableDriverException(driverName);
}
// Compose URL Path & Query to the SPage
String urlPath = pageConfig.composeUrlPath(pathParams);
String urlQuery = pageConfig.composeUrlQuery(queryParams);
// Create the destination URL
try {
mInitialUrl = new URL(
envConfig.getProtocol(), //< protocol
envConfig.getHost(), //< host
envConfig.getPort(), //< port
urlPath + urlQuery).toString(); //< path + query
} catch (MalformedURLException mue) {
LOG.fatal(String.format("FAILED to compose the URL to the Page '%s'", pageConfig.getName()), mue);
throw new SFailedToCreatePageException(mue);
}
// Store the Page Configuration
mPageConfig = pageConfig;
// Create the requested driver
mDriver = new SWebDriverFactory(envConfig).createDriver(driverName);
try {
// Create Page Components based on the configuration
mPageComponents = createPageComponentInstances(pageConfig.getComponentClassnames(), this);
} catch(Exception e) {
// Case something goes wrong, we must make sure the WebDriver is quit
LOG.fatal(String.format("FAILED to Create Components for the Page '%s'", pageConfig.getName()), e);
mDriver.quit();
throw e;
}
}
/**
* Adds a Cookie to a Page.
* Usually this will be used when {@link sulfur.SPage#isOpen()} is still false.
*
* @param cookie Cookie to set on the Page
*/
public void addCookie(Cookie cookie) {
mDriver.manage().addCookie(cookie);
}
/**
* Open the Page.
* It emulates the action of the User.
* NOTE: An Opened page can't be reopened.
*
* @return The same SPage object: useful for call chains
*/
public SPage open() {
if (!mOpened) {
LOG.debug("SPage opening: " + mInitialUrl);
mDriver.get(mInitialUrl);
}
mOpened = true;
return this;
}
/**
* Disposes of a Page.
* After this, the Page object and the internal Driver become unusable (i.e. WebDriver is quitted).
*
* IMPORTANT: If multiple SPage objects use the same WebDriver (i.e. created using
* {@link sulfur.SPage(WebDriver, SPageConfig)}), quitting it will cause unpredictable failures.
*/
public void dispose() {
if (null != mDriver) {
mDriver.quit();
mDriver = null;
}
}
/**
* @return Returns "false" before the SPage#open() method has been invoked.
*/
public boolean isOpen() {
return mOpened;
}
/**
* Returns "true" if the SPage has loaded, "false" otherwise.
* To check for loaded status, it queries all the SPageComponent inside: if all have loaded, the page has loaded.
*
* @return "true" if/when all SPageComponent inside the SPage have loaded.
*/
public boolean hasLoaded() {
for (Map.Entry<String, SPageComponent> component : mPageComponents.entrySet()) {
if (!component.getValue().isLoaded()) {
LOG.warn(String.format("SPageComponent '%s' in SPage '%s' has not loaded (yet?)",
component.getValue().getName(),
getName()));
return false;
}
}
LOG.debug(String.format("SPage '%s' has loaded", getName()));
return true;
}
/**
* Refer to {@link SPage#waitForLoad(long, java.util.concurrent.TimeUnit, long, java.util.concurrent.TimeUnit)}
* @param timeout Time before giving up
*/
public void waitForLoad(long timeout) {
waitForLoad(timeout,
PAGELOAD_WAIT_DEFAULT_TIMEOUT_UNIT,
PAGELOAD_WAIT_DEFAULT_POLLING_TIME,
PAGELOAD_WAIT_DEFAULT_TIMEOUT_UNIT);
}
/**
* Refer to {@link SPage#waitForLoad(long, java.util.concurrent.TimeUnit, long, java.util.concurrent.TimeUnit)}
* @param timeout Time before giving up
* @param unit Time Unit
*/
public void waitForLoad(long timeout, TimeUnit unit) {
waitForLoad(timeout, unit,
PAGELOAD_WAIT_DEFAULT_POLLING_TIME,
PAGELOAD_WAIT_DEFAULT_POLLING_UNIT);
}
/**
* Wait for SPage to Load.
* It will wait for all the internal SPageComponent to finish loading
*
* @param timeout Time before giving up the waiting
* @param timeoutUnit Time Unit used by timeout parameter
* @param polling Time interval between checking if SPage has loaded
* @param pollingUnit Time Unit used by polling parameter
*/
public void waitForLoad(long timeout, TimeUnit timeoutUnit, long polling, TimeUnit pollingUnit) {
Wait<SPage> waiter = new FluentWait<SPage>(this)
.pollingEvery(polling, pollingUnit)
.withTimeout(timeout, timeoutUnit);
waiter.until(new Function<SPage, Boolean>() {
public Boolean apply(SPage page) {
LOG.debug(String.format("Waiting for SPage '%s' to load", getName()));
return page.hasLoaded();
}
});
}
/**
* @return Name of the Page, based on the SPageConfig
*/
public String getName() {
return mPageConfig.getName();
}
/**
* @return Current Page title.
*/
public String getTitle() {
return getDriver().getTitle();
}
/**
* URL used at time the SPage object was constructed.
* @return URL used at time the SPage object was constructed.
*/
public String getInitialUrl() {
return mInitialUrl;
}
/**
* URL the SPage's internal Driver is at.
* @return URL the SPage's internal Driver is at.
*/
public String getCurrentUrl() {
return isOpen() ? getDriver().getCurrentUrl() : getInitialUrl();
}
/**
* @return Current Page source code (i.e. the HTML)
*/
public String getSource() {
return getDriver().getPageSource();
}
/**
* Get SPageComponent from the SPage
*
* @param componentName Name of the Component we are interested in
* @return The SPageComponent we are after
*/
public SPageComponent getComponent(String componentName) {
SPageComponent component = mPageComponents.get(componentName);
if (null == component) {
throw new SUnavailableComponentException(componentName);
}
return mPageComponents.get(componentName);
}
/**
* @return A Map<String, SPageComponent> of all the Components that compose the Page (note: based on the Page Configuration).
*/
public Map<String, SPageComponent> getComponents() {
return mPageComponents;
}
/**
* Create a map of SPageComponents
*
* @param componentClassnames Classnames to use when creating a SPageComponent instance
* @param containingPage The SPage object that will contain those Components once created
*/
private static Map<String, SPageComponent> createPageComponentInstances(String[] componentClassnames, SPage containingPage) {
Map<String, SPageComponent> pageComponents = new HashMap<String, SPageComponent>(componentClassnames.length);
for (String componentClassname : componentClassnames) {
SPageComponent newPageComponent = createPageComponentInstance(componentClassname, containingPage);
pageComponents.put(newPageComponent.getName(), newPageComponent);
}
return pageComponents;
}
/**
* Create instance of given SPageComponent.
*
* NOTE: This delegates the Selenium very own {@link org.openqa.selenium.support.PageFactory}
* to actually populate the WebElement declared in a SPageComponent.
*
* @param componentClassname Classname of the SPageComponent to create
* @param containingPage SPage that will contain the Component
* @return Instance of the SPageComponent
* @throws sulfur.factories.exceptions.SFailedToCreatePageComponentException
*/
private static SPageComponent createPageComponentInstance(String componentClassname, SPage containingPage) {
try {
// Grab class and constructor
Class<?> componentClass = Class.forName(componentClassname);
Constructor<?> componentConstructor = componentClass.getConstructor(SPage.class);
// Create instance of the SPageComponent
SPageComponent componentObj = (SPageComponent) componentConstructor.newInstance(containingPage);
// Initialise the decorated WebElement in the Component, delegating the job to the Selenium {@link PageFactory}
PageFactory.initElements(containingPage.getDriver(), componentObj);
return componentObj;
} catch (Exception e) {
throw new SFailedToCreatePageComponentException(e);
}
}
/**
* Returns the Driver used by this SPage.
* The assumption is that you know what a WebDriver is an the effect that you will have manipulating
* it directly.
*
* It's advisable you use SPageComponent(s) instead.
* @return The WebDriver in use to this SPage Object
*/
public WebDriver getDriver() {
return mDriver;
}
public Object executeScript(String script, Object... args) {
return ((JavascriptExecutor) mDriver).executeScript(script, args);
}
public Object executeAsyncScript(String script, Object... args) {
return ((JavascriptExecutor) mDriver).executeAsyncScript(script, args);
}
@Override
public void finalize() {
dispose();
}
} |
package org.deepsymmetry.beatlink;
import java.io.IOException;
import java.net.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.deepsymmetry.beatlink.data.MetadataFinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides the ability to create a virtual CDJ device that can lurk on a DJ Link network and receive packets sent to
* players, monitoring the detailed state of the other devices. This detailed information is helpful for augmenting
* what {@link BeatFinder} reports, allowing you to keep track of which player is the tempo master, how many beats of
* a track have been played, how close a player is getting to its next cue point, and more. It is also the foundation
* for finding out the rekordbox ID of the loaded track, which supports all the features associated with the
* {@link MetadataFinder}.
*
* @author James Elliott
*/
@SuppressWarnings("WeakerAccess")
public class VirtualCdj extends LifecycleParticipant {
private static final Logger logger = LoggerFactory.getLogger(VirtualCdj.class);
/**
* The port to which other devices will send status update messages.
*/
@SuppressWarnings("WeakerAccess")
public static final int UPDATE_PORT = 50002;
/**
* The socket used to receive device status packets while we are active.
*/
private final AtomicReference<DatagramSocket> socket = new AtomicReference<DatagramSocket>();
/**
* Check whether we are presently posing as a virtual CDJ and receiving device status updates.
*
* @return true if our socket is open, sending presence announcements, and receiving status packets
*/
public boolean isRunning() {
return socket.get() != null;
}
public InetAddress getLocalAddress() {
ensureRunning();
return socket.get().getLocalAddress();
}
/**
* The broadcast address on which we can reach the DJ Link devices. Determined when we start
* up by finding the network interface address on which we are receiving the other devices'
* announcement broadcasts.
*/
private final AtomicReference<InetAddress> broadcastAddress = new AtomicReference<InetAddress>();
public InetAddress getBroadcastAddress() {
ensureRunning();
return broadcastAddress.get();
}
/**
* Keep track of the most recent updates we have seen, indexed by the address they came from.
*/
private final Map<InetAddress, DeviceUpdate> updates = new ConcurrentHashMap<InetAddress, DeviceUpdate>();
/**
* Should we try to use a device number in the range 1 to 4 if we find one is available?
*/
private final AtomicBoolean useStandardPlayerNumber = new AtomicBoolean(false);
public void setUseStandardPlayerNumber(boolean attempt) {
useStandardPlayerNumber.set(attempt);
}
public boolean getUseStandardPlayerNumber() {
return useStandardPlayerNumber.get();
}
/**
* Get the device number that is used when sending presence announcements on the network to pose as a virtual CDJ.
* This starts out being zero unless you explicitly assign another value, which means that the <code>VirtualCdj</code>
* should assign itself an unused device number by watching the network when you call
* {@link #start()}. If {@link #getUseStandardPlayerNumber()} returns {@code true}, self-assignment will try to
* find a value in the range 1 to 4. Otherwise (or if those values are all used by other players), it will try to
* find a value in the range 5 to 15.
*
* @return the virtual player number
*/
public synchronized byte getDeviceNumber() {
return announcementBytes[36];
}
/**
* <p>Set the device number to be used when sending presence announcements on the network to pose as a virtual CDJ.
* If this is set to zero before {@link #start()} is called, the {@code VirtualCdj} will watch the network to
* look for an unused device number, and assign itself that number during startup. If you
* explicitly assign a non-zero value, it will use that device number instead. Setting the value to zero while
* already up and running reassigns it to an unused value immediately. If {@link #getUseStandardPlayerNumber()}
* returns {@code true}, self-assignment will try to find a value in the range 1 to 4. Otherwise (or if those
* values are all used by other players), it will try to find a value in the range 5 to 15.</p>
*
* <p>The device number defaults to 0, enabling self-assignment, and will be reset to that each time the
* {@code VirtualCdj} is stopped.</p>
*
* @param number the virtual player number
*/
@SuppressWarnings("WeakerAccess")
public synchronized void setDeviceNumber(byte number) {
if (number == 0 && isRunning()) {
selfAssignDeviceNumber();
} else {
announcementBytes[36] = number;
}
}
/**
* The interval, in milliseconds, at which we post presence announcements on the network.
*/
private final AtomicInteger announceInterval = new AtomicInteger(1500);
/**
* Get the interval, in milliseconds, at which we broadcast presence announcements on the network to pose as
* a virtual CDJ.
*
* @return the announcement interval
*/
public int getAnnounceInterval() {
return announceInterval.get();
}
public void setAnnounceInterval(int interval) {
if (interval < 200 || interval > 2000) {
throw new IllegalArgumentException("Interval must be between 200 and 2000");
}
announceInterval.set(interval);
}
private static final byte[] announcementBytes = {
0x51, 0x73, 0x70, 0x74, 0x31, 0x57, 0x6d, 0x4a, 0x4f, 0x4c, 0x06, 0x00, 0x62, 0x65, 0x61, 0x74,
0x2d, 0x6c, 0x69, 0x6e, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x02, 0x00, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x01, 0x00
};
/**
* Get the name to be used in announcing our presence on the network.
*
* @return the device name reported in our presence announcement packets
*/
public static String getDeviceName() {
return new String(announcementBytes, 12, 20).trim();
}
/**
* Set the name to be used in announcing our presence on the network. The name can be no longer than twenty
* bytes, and should be normal ASCII, no Unicode.
*
* @param name the device name to report in our presence announcement packets.
*/
public synchronized void setDeviceName(String name) {
if (name.getBytes().length > 20) {
throw new IllegalArgumentException("name cannot be more than 20 bytes long");
}
Arrays.fill(announcementBytes, 12, 32, (byte)0);
System.arraycopy(name.getBytes(), 0, announcementBytes, 12, name.getBytes().length);
}
/**
* Keep track of which device has reported itself as the current tempo master.
*/
private final AtomicReference<DeviceUpdate> tempoMaster = new AtomicReference<DeviceUpdate>();
public DeviceUpdate getTempoMaster() {
ensureRunning();
return tempoMaster.get();
}
/**
* Establish a new tempo master, and if it is a change from the existing one, report it to the listeners.
*
* @param newMaster the packet which caused the change of masters, or {@code null} if there is now no master.
*/
private void setTempoMaster(DeviceUpdate newMaster) {
DeviceUpdate oldMaster = tempoMaster.getAndSet(newMaster);
if ((newMaster == null && oldMaster != null) ||
(newMaster != null && ((oldMaster == null) || !newMaster.getAddress().equals(oldMaster.getAddress())))) {
// This is a change in master, so report it to any registered listeners
deliverMasterChangedAnnouncement(newMaster);
}
}
/**
* How large a tempo change is required before we consider it to be a real difference.
*/
private final AtomicLong tempoEpsilon = new AtomicLong(Double.doubleToLongBits(0.0001));
/**
* Find out how large a tempo change is required before we consider it to be a real difference.
*
* @return the BPM fraction that will trigger a tempo change update
*/
public double getTempoEpsilon() {
return Double.longBitsToDouble(tempoEpsilon.get());
}
/**
* Set how large a tempo change is required before we consider it to be a real difference.
*
* @param epsilon the BPM fraction that will trigger a tempo change update
*/
public void setTempoEpsilon(double epsilon) {
tempoEpsilon.set(Double.doubleToLongBits(epsilon));
}
/**
* Track the most recently reported master tempo.
*/
private final AtomicLong masterTempo = new AtomicLong();
public double getMasterTempo() {
ensureRunning();
return Double.longBitsToDouble(masterTempo.get());
}
/**
* Establish a new master tempo, and if it is a change from the existing one, report it to the listeners.
*
* @param newTempo the newly reported master tempo.
*/
private void setMasterTempo(double newTempo) {
double oldTempo = Double.longBitsToDouble(masterTempo.getAndSet(Double.doubleToLongBits(newTempo)));
if ((getTempoMaster() != null) && (Math.abs(newTempo - oldTempo) > getTempoEpsilon())) {
// This is a change in tempo, so report it to any registered listeners
deliverTempoChangedAnnouncement(newTempo);
}
}
/**
* Given an update packet sent to us, create the appropriate object to describe it.
*
* @param packet the packet received on our update port
* @return the corresponding {@link DeviceUpdate} subclass, or {@code nil} if the packet was not recognizable
*/
private DeviceUpdate buildUpdate(DatagramPacket packet) {
int length = packet.getLength();
int kind = packet.getData()[10];
if (length == 56 && kind == 0x29 && Util.validateHeader(packet, 0x29, "Mixer Status")) {
return new MixerStatus(packet);
} else if ((length == 212 || length == 208 || length == 284 || length == 292) &&
kind == 0x0a && Util.validateHeader(packet, 0x0a, "CDJ Status")) {
return new CdjStatus(packet);
}
logger.warn("Unrecognized device update packet with length " + length + " and kind " + kind);
return null;
}
/**
* Process a device update once it has been received. Track it as the most recent update from its address,
* and notify any registered listeners, including master listeners if it results in changes to tracked state,
* such as the current master player and tempo.
*/
private void processUpdate(DeviceUpdate update) {
updates.put(update.getAddress(), update);
if (update.isTempoMaster()) {
setTempoMaster(update);
setMasterTempo(update.getEffectiveTempo());
} else {
DeviceUpdate oldMaster = getTempoMaster();
if (oldMaster != null && oldMaster.getAddress().equals(update.getAddress())) {
// This device has resigned master status, and nobody else has claimed it so far
setTempoMaster(null);
}
}
deliverDeviceUpdate(update);
}
/**
* Process a beat packet, potentially updating the master tempo and sending our listeners a master
* beat notification. Does nothing if we are not active.
*/
void processBeat(Beat beat) {
if (isRunning() && beat.isTempoMaster()) {
setMasterTempo(beat.getEffectiveTempo());
deliverBeatAnnouncement(beat);
}
}
/**
* Scan a network interface to find if it has an address space which matches the device we are trying to reach.
* If so, return the address specification.
*
* @param aDevice the DJ Link device we are trying to communicate with
* @param networkInterface the network interface we are testing
* @return the address which can be used to communicate with the device on the interface, or null
*/
private InterfaceAddress findMatchingAddress(DeviceAnnouncement aDevice, NetworkInterface networkInterface) {
for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
if ((address.getBroadcast() != null) &&
Util.sameNetwork(address.getNetworkPrefixLength(), aDevice.getAddress(), address.getAddress())) {
return address;
}
}
return null;
}
/**
* The number of milliseconds for which the {@link DeviceFinder} needs to have been watching the network in order
* for us to be confident we can choose a device number that will not conflict.
*/
private static final long SELF_ASSIGNMENT_WATCH_PERIOD = 4000;
/**
* Try to choose a device number, which we have not seen on the network. Start by making sure
* we have been watching long enough to have seen the other devices. Then, if {@link #useStandardPlayerNumber} is
* {@code true}, try to use a standard player number in the range 1-4 if possible. Otherwise (or if all those
* numbers are already in use), pick a number from 5 to 15.
*/
private boolean selfAssignDeviceNumber() {
final long now = System.currentTimeMillis();
final long started = DeviceFinder.getInstance().getFirstDeviceTime();
if (now - started < SELF_ASSIGNMENT_WATCH_PERIOD) {
try {
Thread.sleep(SELF_ASSIGNMENT_WATCH_PERIOD - (now - started)); // Sleep until we hit the right time
} catch (InterruptedException e) {
logger.warn("Interrupted waiting to self-assign device number, giving up.");
return false;
}
}
Set<Integer> numbersUsed = new HashSet<Integer>();
for (DeviceAnnouncement device : DeviceFinder.getInstance().getCurrentDevices()) {
numbersUsed.add(device.getNumber());
}
// Try all player numbers less than mixers use, only including the real player range if we are configured to.
final int startingNumber = (getUseStandardPlayerNumber() ? 1 : 5);
for (int result = startingNumber; result < 16; result++) {
if (!numbersUsed.contains(result)) { // We found one that is not used, so we can use it
setDeviceNumber((byte) result);
if (getUseStandardPlayerNumber() && (result > 4)) {
logger.warn("Unable to self-assign a standard player number, all are in use. Using number " +
result + ".");
}
return true;
}
}
logger.warn("Found no unused device numbers between " + startingNumber + " and 15, giving up.");
return false;
}
/**
* Once we have seen some DJ Link devices on the network, we can proceed to create a virtual player on that
* same network.
*
* @return true if we found DJ Link devices and were able to create the {@code VirtualCdj}.
* @throws SocketException if there is a problem opening a socket on the right network
*/
private boolean createVirtualCdj() throws SocketException {
// Find the network interface and address to use to communicate with the first device we found.
NetworkInterface matchedInterface = null;
InterfaceAddress matchedAddress = null;
DeviceAnnouncement aDevice = DeviceFinder.getInstance().getCurrentDevices().iterator().next();
for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
matchedAddress = findMatchingAddress(aDevice, networkInterface);
if (matchedAddress != null) {
matchedInterface = networkInterface;
break;
}
}
if (matchedAddress == null) {
logger.warn("Unable to find network interface to communicate with " + aDevice +
", giving up.");
return false;
}
if (getDeviceNumber() == 0) {
if (!selfAssignDeviceNumber()) {
return false;
}
}
// Copy the chosen interface's hardware and IP addresses into the announcement packet template
System.arraycopy(matchedInterface.getHardwareAddress(), 0, announcementBytes, 38, 6);
System.arraycopy(matchedAddress.getAddress().getAddress(), 0, announcementBytes, 44, 4);
broadcastAddress.set(matchedAddress.getBroadcast());
// Looking good. Open our communication socket and set up our threads.
socket.set(new DatagramSocket(UPDATE_PORT, matchedAddress.getAddress()));
// Inform the DeviceFinder to ignore our own device announcement packets.
DeviceFinder.getInstance().addIgnoredAddress(socket.get().getLocalAddress());
final byte[] buffer = new byte[512];
final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// Create the update reception thread
Thread receiver = new Thread(null, new Runnable() {
@Override
public void run() {
boolean received;
while (isRunning()) {
try {
socket.get().receive(packet);
received = true;
} catch (IOException e) {
// Don't log a warning if the exception was due to the socket closing at shutdown.
if (isRunning()) {
// We did not expect to have a problem; log a warning and shut down.
logger.warn("Problem reading from DeviceStatus socket, stopping", e);
stop();
}
received = false;
}
try {
if (received && (packet.getAddress() != socket.get().getLocalAddress())) {
DeviceUpdate update = buildUpdate(packet);
if (update != null) {
processUpdate(update);
}
}
} catch (Exception e) {
logger.warn("Problem processing device update packet", e);
}
}
}
}, "beat-link VirtualCdj status receiver");
receiver.setDaemon(true);
receiver.setPriority(Thread.MAX_PRIORITY);
receiver.start();
// Create the thread which announces our participation in the DJ Link network, to request update packets
Thread announcer = new Thread(null, new Runnable() {
@Override
public void run() {
while (isRunning()) {
sendAnnouncement(broadcastAddress.get());
}
}
}, "beat-link VirtualCdj announcement sender");
announcer.setDaemon(true);
announcer.start();
deliverLifecycleAnnouncement(logger, true);
return true;
}
private final LifecycleListener deviceFinderLifecycleListener = new LifecycleListener() {
@Override
public void started(LifecycleParticipant sender) {
logger.debug("VirtualCDJ doesn't have anything to do when the DeviceFinder starts");
}
@Override
public void stopped(LifecycleParticipant sender) {
if (isRunning()) {
logger.info("VirtualCDJ stopping because DeviceFinder has stopped.");
stop();
}
}
};
/**
* Start announcing ourselves and listening for status packets. If already active, has no effect. Requires the
* {@link DeviceFinder} to be active in order to find out how to communicate with other devices, so will start
* that if it is not already.
*
* @return true if we found DJ Link devices and were able to create the {@code VirtualCdj}, or it was already running.
* @throws SocketException if the socket to listen on port 50002 cannot be created
*/
@SuppressWarnings("UnusedReturnValue")
public synchronized boolean start() throws SocketException {
if (!isRunning()) {
// Set up so we know we have to shut down if the DeviceFinder shuts down.
DeviceFinder.getInstance().addLifecycleListener(deviceFinderLifecycleListener);
// Find some DJ Link devices so we can figure out the interface and address to use to talk to them
DeviceFinder.getInstance().start();
for (int i = 0; DeviceFinder.getInstance().getCurrentDevices().isEmpty() && i < 20; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
logger.warn("Interrupted waiting for devices, giving up", e);
return false;
}
}
if (DeviceFinder.getInstance().getCurrentDevices().isEmpty()) {
logger.warn("No DJ Link devices found, giving up");
return false;
}
return createVirtualCdj();
}
return true; // We were already active
}
/**
* Stop announcing ourselves and listening for status updates.
*/
@SuppressWarnings("WeakerAccess")
public synchronized void stop() {
if (isRunning()) {
DeviceFinder.getInstance().removeIgnoredAddress(socket.get().getLocalAddress());
socket.get().close();
socket.set(null);
broadcastAddress.set(null);
updates.clear();
setTempoMaster(null);
setDeviceNumber((byte)0); // Set up for self-assignment if restarted.
deliverLifecycleAnnouncement(logger, false);
}
}
/**
* Send an announcement packet so the other devices see us as being part of the DJ Link network and send us
* updates.
*/
private void sendAnnouncement(InetAddress broadcastAddress) {
try {
DatagramPacket announcement = new DatagramPacket(announcementBytes, announcementBytes.length,
broadcastAddress, DeviceFinder.ANNOUNCEMENT_PORT);
socket.get().send(announcement);
Thread.sleep(getAnnounceInterval());
} catch (Exception e) {
logger.warn("Unable to send announcement packet, shutting down", e);
stop();
}
}
public Set<DeviceUpdate> getLatestStatus() {
ensureRunning();
Set<DeviceUpdate> result = new HashSet<DeviceUpdate>();
long now = System.currentTimeMillis();
for (DeviceUpdate update : updates.values()) {
if (now - update.getTimestamp() <= DeviceFinder.MAXIMUM_AGE) {
result.add(update);
}
}
return Collections.unmodifiableSet(result);
}
public DeviceUpdate getLatestStatusFor(DeviceUpdate device) {
ensureRunning();
return updates.get(device.getAddress());
}
public DeviceUpdate getLatestStatusFor(DeviceAnnouncement device) {
ensureRunning();
return updates.get(device.getAddress());
}
public DeviceUpdate getLatestStatusFor(int deviceNumber) {
ensureRunning();
for (DeviceUpdate update : updates.values()) {
if (update.getDeviceNumber() == deviceNumber) {
return update;
}
}
return null;
}
/**
* Keeps track of the registered master listeners.
*/
private final Set<MasterListener> masterListeners =
Collections.newSetFromMap(new ConcurrentHashMap<MasterListener, Boolean>());
public void addMasterListener(MasterListener listener) {
if (listener != null) {
masterListeners.add(listener);
}
}
/**
* Removes the specified master listener so that it no longer receives device updates when
* there are changes related to the tempo master. If {@code listener} is {@code null} or not present
* in the set of registered listeners, no exception is thrown and no action is performed.
*
* @param listener the master listener to remove
*/
public void removeMasterListener(MasterListener listener) {
if (listener != null) {
masterListeners.remove(listener);
}
}
/**
* Get the set of master listeners that are currently registered.
*
* @return the currently registered tempo master listeners
*/
@SuppressWarnings("WeakerAccess")
public Set<MasterListener> getMasterListeners() {
// Make a copy so callers get an immutable snapshot of the current state.
return Collections.unmodifiableSet(new HashSet<MasterListener>(masterListeners));
}
/**
* Send a master changed announcement to all registered master listeners.
*
* @param update the message announcing the new tempo master
*/
private void deliverMasterChangedAnnouncement(final DeviceUpdate update) {
for (final MasterListener listener : getMasterListeners()) {
try {
listener.masterChanged(update);
} catch (Exception e) {
logger.warn("Problem delivering master changed announcement to listener", e);
}
}
}
/**
* Send a tempo changed announcement to all registered master listeners.
*
* @param tempo the new master tempo
*/
private void deliverTempoChangedAnnouncement(final double tempo) {
for (final MasterListener listener : getMasterListeners()) {
try {
listener.tempoChanged(tempo);
} catch (Exception e) {
logger.warn("Problem delivering tempo changed announcement to listener", e);
}
}
}
/**
* Send a beat announcement to all registered master listeners.
*
* @param beat the beat sent by the tempo master
*/
private void deliverBeatAnnouncement(final Beat beat) {
for (final MasterListener listener : getMasterListeners()) {
try {
listener.newBeat(beat);
} catch (Exception e) {
logger.warn("Problem delivering master beat announcement to listener", e);
}
}
}
/**
* Keeps track of the registered device update listeners.
*/
private final Set<DeviceUpdateListener> updateListeners =
Collections.newSetFromMap(new ConcurrentHashMap<DeviceUpdateListener, Boolean>());
@SuppressWarnings("SameParameterValue")
public void addUpdateListener(DeviceUpdateListener listener) {
if (listener != null) {
updateListeners.add(listener);
}
}
/**
* Removes the specified device update listener so it no longer receives device updates when they come in.
* If {@code listener} is {@code null} or not present
* in the list of registered listeners, no exception is thrown and no action is performed.
*
* @param listener the device update listener to remove
*/
@SuppressWarnings("SameParameterValue")
public void removeUpdateListener(DeviceUpdateListener listener) {
if (listener != null) {
updateListeners.remove(listener);
}
}
/**
* Get the set of device update listeners that are currently registered.
*
* @return the currently registered update listeners
*/
@SuppressWarnings("WeakerAccess")
public Set<DeviceUpdateListener> getUpdateListeners() {
// Make a copy so callers get an immutable snapshot of the current state.
return Collections.unmodifiableSet(new HashSet<DeviceUpdateListener>(updateListeners));
}
/**
* Send a device update to all registered update listeners.
*
* @param update the device update that has just arrived
*/
private void deliverDeviceUpdate(final DeviceUpdate update) {
for (DeviceUpdateListener listener : getUpdateListeners()) {
try {
listener.received(update);
} catch (Exception e) {
logger.warn("Problem delivering device update to listener", e);
}
}
}
/**
* Holds the singleton instance of this class.
*/
private static final VirtualCdj ourInstance = new VirtualCdj();
/**
* Get the singleton instance of this class.
*
* @return the only instance of this class which exists.
*/
public static VirtualCdj getInstance() {
return ourInstance;
}
/**
* Prevent instantiation.
*/
private VirtualCdj() {
// Nothing to do.
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("VirtualCdj[number:").append(getDeviceNumber()).append(", name:").append(getDeviceName());
sb.append(", announceInterval:").append(getAnnounceInterval());
sb.append(", useStandardPlayerNumber:").append(getUseStandardPlayerNumber());
sb.append(", tempoEpsilon:").append(getTempoEpsilon()).append(", active:").append(isRunning());
if (isRunning()) {
sb.append(", localAddress:").append(getLocalAddress().getHostAddress());
sb.append(", broadcastAddress:").append(getBroadcastAddress().getHostAddress());
sb.append(", latestStatus:").append(getLatestStatus()).append(", masterTempo:").append(getMasterTempo());
sb.append(", tempoMaster:").append(getTempoMaster());
}
return sb.append("]").toString();
}
} |
package org.hcjf.properties;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.hcjf.layers.locale.DefaultLocaleLayer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
/**
* This class overrides the system properties default implementation adding
* some default values and properties definitions for the service-oriented platforms
* works.
* @author javaito
*/
public final class SystemProperties extends Properties {
public static final String HCJF_DEFAULT_DATE_FORMAT = "hcjf.default.date.format";
public static final String HCJF_DEFAULT_NUMBER_FORMAT = "hcjf.default.number.format";
public static final String HCJF_DEFAULT_DECIMAL_SEPARATOR = "hcjf.default.decimal.separator";
public static final String HCJF_DEFAULT_GROUPING_SEPARATOR = "hcjf.default.grouping.separator";
public static final String HCJF_DEFAULT_LOCALE = "hcjf.default.locale";
public static final String HCJF_DEFAULT_LOCALE_LAYER_IMPLEMENTATION = "hcjf.default.locale.layer.implementation";
public static final String HCJF_DEFAULT_LOCALE_LAYER_IMPLEMENTATION_NAME = "hcjf.default.locale.layer.implementation.name";
public static final String HCJF_DEFAULT_PROPERTIES_FILE_PATH = "hcjf.default.properties.file.path";
public static final String HCJF_DEFAULT_PROPERTIES_FILE_XML = "hcjf.default.properties.file.xml";
public static final String HCJF_UUID_REGEX = "hcjf.uuid.regex";
public static final String HCJF_INTEGER_NUMBER_REGEX = "hcjf.integer.number.regex";
public static final String HCJF_DECIMAL_NUMBER_REGEX = "hcjf.decimal.number.regex";
public static final String HCJF_SCIENTIFIC_NUMBER_REGEX = "hcjf.scientific.number.regex";
public static final class Layer {
public static final String LOG_TAG = "hcjf.layers.log.tag";
public static final class Deployment {
public static final String SERVICE_NAME = "hcjf.layers.deployment.service.name";
public static final String SERVICE_PRIORITY = "hcjf.layers.deployment.service.priority";
public static final String CLOUD_DEPLOYMENT_ENABLED = "hcjf.layers.plugin.cloud.deployment.enabled";
public static final String CLOUD_DEPLOYMENT_MAP_NAME = "hcjf.layers.plugin.cloud.deployment.map.name";
public static final String CLOUD_DEPLOYMENT_LOCK_NAME = "hcjf.layers.plugin.cloud.deployment.lock.name";
public static final String CLOUD_DEPLOYMENT_LOCK_CONDITION_NAME = "hcjf.layers.plugin.cloud.deployment.lock.condition.name";
public static final String CLOUD_DEPLOYMENT_FILTER = "hcjf.layers.plugin.cloud.deployment.filter";
}
}
public static final class Service {
public static final String STATIC_THREAD_NAME = "hcjf.service.static.thread.name";
public static final String STATIC_THREAD_POOL_CORE_SIZE = "hcjf.service.static.thread.pool.core.size";
public static final String STATIC_THREAD_POOL_MAX_SIZE = "hcfj.service.static.thread.pool.max.size";
public static final String STATIC_THREAD_POOL_KEEP_ALIVE_TIME = "hcfj.service.static.thread.pool.keep.alive.time";
public static final String THREAD_POOL_CORE_SIZE = "hcjf.service.thread.pool.core.size";
public static final String THREAD_POOL_MAX_SIZE = "hcfj.service.thread.pool.max.size";
public static final String THREAD_POOL_KEEP_ALIVE_TIME = "hcfj.service.thread.pool.keep.alive.time";
public static final String GUEST_SESSION_NAME = "hcjf.service.guest.session.name";
public static final String SYSTEM_SESSION_NAME = "hcjf.service.system.session.name";
public static final String SHUTDOWN_TIME_OUT = "hcjf.service.shutdown.time.out";
}
public static final class Event {
public static final String SERVICE_NAME = "hcjf.event.service.name";
public static final String SERVICE_PRIORITY = "hcjf.event.service.priority";
}
public static final class Log {
public static final String SERVICE_NAME = "hcjf.log.service.name";
public static final String SERVICE_PRIORITY = "hcjf.log.service.priority";
public static final String FILE_PREFIX = "hcfj.log.file.prefix";
public static final String ERROR_FILE = "hcfj.log.error.file";
public static final String WARNING_FILE = "hcfj.log.warning.file";
public static final String INFO_FILE = "hcfj.log.info.file";
public static final String DEBUG_FILE = "hcfj.log.debug.file";
public static final String LEVEL = "hcfj.log.level";
public static final String DATE_FORMAT = "hcfj.log.date.format";
public static final String CONSUMERS = "hcjf.log.consumers";
public static final String SYSTEM_OUT_ENABLED = "hcjf.log.system.out.enabled";
public static final String JAVA_STANDARD_LOGGER_ENABLED = "hcjf.log.java.standard.logger.enabled";
public static final String QUEUE_INITIAL_SIZE = "hcjf.log.queue.initial.size";
public static final String TRUNCATE_TAG = "hcjf.log.truncate.tag";
public static final String TRUNCATE_TAG_SIZE = "hcjf.log.truncate.tag.size";
public static final String LOG_CONSUMERS_SIZE = "hcjf.log.consumers.size";
}
public static final class Encoding {
public static final String SERVICE_NAME = "hcjf.encoding.service.name";
public static final String SERVICE_PRIORITY = "hcjf.encoding.service.priority";
}
public static final class FileSystem {
public static final String SERVICE_NAME = "hcjf.file.system.service.name";
public static final String SERVICE_PRIORITY = "hcjf.file.system.service.priority";
public static final String LOG_TAG = "hcjf.file.system.log.tag";
}
public static final class Net {
public static final String SERVICE_NAME = "hcjf.net.service.name";
public static final String LOG_TAG = "hcjf.net.log.tag";
public static final String INPUT_BUFFER_SIZE = "hcfj.net.input.buffer.size";
public static final String OUTPUT_BUFFER_SIZE = "hcfj.net.output.buffer.size";
public static final String DISCONNECT_AND_REMOVE = "hcfj.net.disconnect.and.remove";
public static final String CONNECTION_TIMEOUT_AVAILABLE = "hcfj.net.connection.timeout.available";
public static final String CONNECTION_TIMEOUT = "hcfj.net.connection.timeout";
public static final String WRITE_TIMEOUT = "hcjf.net.write.timeout";
public static final String IO_THREAD_POOL_KEEP_ALIVE_TIME = "hcjf.net.io.thread.pool.keep.alive.time";
public static final String IO_THREAD_POOL_MAX_SIZE = "hcjf.net.io.thread.pool.max.size";
public static final String IO_THREAD_POOL_CORE_SIZE = "hcjf.net.io.thread.pool.core.size";
public static final String DEFAULT_INPUT_BUFFER_SIZE = "hcjf.net.default.input.buffer.size";
public static final String DEFAULT_OUTPUT_BUFFER_SIZE = "hcjf.net.default.output.buffer.size";
public static final String IO_THREAD_DIRECT_ALLOCATE_MEMORY = "hcjf.net.io.thread.direct.allocate.memory";
public static final String SSL_MAX_IO_THREAD_POOL_SIZE = "hcjf.net.ssl.max.io.thread.pool.size";
public static final String PORT_PROVIDER_TIME_WINDOWS_SIZE = "hcjf.net.port.provider.time.windows.size";
public static final String PORT_PROBE_CONNECTION_TIMEOUT = "hcjf.net.port.probe.connection.timeout";
public static final class Broadcast {
public static final String SERVICE_NAME = "hcjf.net.broadcast.service.name";
public static final String LOG_TAG = "hcjf.net.broadcast.log.tag";
public static final String INTERFACE_NAME = "hcjf.net.broadcast.interface.name";
public static final String IP_VERSION = "hcjf.net.broadcast.ip.version";
public static final String SENDER_DELAY = "hcjf.net.broadcast.sender.delay";
public static final String SIGNATURE_ALGORITHM = "hcjf.net.broadcast.signature.algorithm";
public static final String RECEIVER_BUFFER_SIZE = "hcjf.net.broadcast.receiver.buffer.size";
}
public static final class Ssl {
public static final String DEFAULT_PROTOCOL = "hcjf.net.ssl.default.protocol";
public static final String IO_THREAD_NAME = "hcjf.net.ssl.io.thread.name";
public static final String ENGINE_THREAD_NAME = "hcjf.net.ssl.engine.thread.name";
public static final String DEFAULT_KEYSTORE_PASSWORD = "hcjf.net.ssl.default.keystore.password";
public static final String DEFAULT_KEY_PASSWORD = "hcjf.net.ssl.default.key.password";
public static final String DEFAULT_KEYSTORE_FILE_PATH = "hcjf.net.ssl.default.keystore.file.path";
public static final String DEFAULT_TRUSTED_CERTS_FILE_PATH = "hcjf.net.ssl.default.trusted.certs.file.path";
public static final String DEFAULT_KEY_TYPE = "hcjf.net.ssl.default.key.type";
}
public static final class Http {
public static final String LOG_TAG = "hcjf.net.http.server.log.tag";
public static final String SERVER_NAME = "hcjf.net.http.server.name";
public static final String RESPONSE_DATE_HEADER_FORMAT_VALUE = "hcjf.net.http.response.date.header.format.value";
public static final String INPUT_LOG_BODY_MAX_LENGTH = "hcjf.net.http.input.log.body.max.length";
public static final String OUTPUT_LOG_BODY_MAX_LENGTH = "hcjf.net.http.output.log.body.max.length";
public static final String DEFAULT_SERVER_PORT = "hcjf.net.http.default.server.port";
public static final String DEFAULT_CLIENT_PORT = "hcjf.net.http.default.client.port";
public static final String STREAMING_LIMIT_FILE_SIZE = "hcjf.net.http.streaming.limit.file.size";
public static final String DEFAULT_ERROR_FORMAT_SHOW_STACK = "hcjf.net.http.default.error.format.show.stack";
public static final String DEFAULT_CLIENT_CONNECT_TIMEOUT = "hcjf.net.http.default.client.connect.timeout";
public static final String DEFAULT_CLIENT_READ_TIMEOUT = "hcjf.net.http.default.client.read.timeout";
public static final String DEFAULT_CLIENT_WRITE_TIMEOUT = "hcjf.net.http.default.client.write.timeout";
public static final String DEFAULT_GUEST_SESSION_NAME = "hcjf.net.http.default.guest.session.name";
public static final String DEFAULT_FILE_CHECKSUM_ALGORITHM = "hcjf.net.http.default.file.checksum.algorithm";
public static final String ENABLE_AUTOMATIC_RESPONSE_CONTENT_LENGTH = "hcjf.net.http.enable.automatic.response.content.length";
public static final class Folder {
public static final String LOG_TAG = "hcjf.net.http.folder.log.tag";
public static final String FORBIDDEN_CHARACTERS = "hcjf.net.http.folder.forbidden.characters";
public static final String FILE_EXTENSION_REGEX = "hcjf.net.http.folder.file.extension.regex";
public static final String DEFAULT_HTML_DOCUMENT = "hcjf.net.http.folder.default.html.document";
public static final String DEFAULT_HTML_BODY = "hcjf.net.http.folder.default.html.body";
public static final String DEFAULT_HTML_ROW = "hcjf.net.http.folder.default.html.row";
public static final String ZIP_CONTAINER = "hcjf.net.http.folder.zip.container";
public static final String ZIP_TEMP_PREFIX = "hcjf.net.http.folder.zip.temp.prefix";
public static final String JAR_CONTAINER = "hcjf.net.http.folder.jar.container";
public static final String JAR_TEMP_PREFIX = "hcjf.net.http.folder.jar.temp.prefix";
}
}
public static final class Https {
public static final String DEFAULT_SERVER_PORT = "hcjf.net.https.default.server.port";
public static final String DEFAULT_CLIENT_PORT = "hcjf.net.https.default.server.port";
}
public static final class Rest {
public static final String DEFAULT_MIME_TYPE = "hcjf.rest.default.mime.type";
public static final String DEFAULT_ENCODING_IMPL = "hcjf.rest.default.encoding.impl";
public static final String QUERY_PATH = "hcjf.rest.query.path";
public static final String QUERY_PARAMETER_PATH = "hcjf.rest.query.parameter.path";
}
}
public static final class Query {
public static final String LOG_TAG = "hcjf.query.log.tag";
public static final String DEFAULT_LIMIT = "hcjf.query.default.limit";
public static final String DEFAULT_DESC_ORDER = "hcjf.query.default.desc.order";
public static final String SELECT_REGULAR_EXPRESSION = "hcjf.query.select.regular.expression";
public static final String CONDITIONAL_REGULAR_EXPRESSION = "hcjf.query.conditional.regular.expression";
public static final String EVALUATOR_COLLECTION_REGULAR_EXPRESSION = "hcjf.query.evaluator.collection.regular.expression";
public static final String OPERATION_REGULAR_EXPRESSION = "hcjf.query.operation.regular.expression";
public static final String JOIN_REGULAR_EXPRESSION = "hcjf.query.join.regular.expression";
public static final String AS_REGULAR_EXPRESSION = "hcjf.query.as.regular.expression";
public static final String DESC_REGULAR_EXPRESSION = "hcjf.query.desc.regular.expression";
public static final String SELECT_GROUP_INDEX = "hcjf.query.select.group.index";
public static final String FROM_GROUP_INDEX = "hcjf.query.from.group.index";
public static final String CONDITIONAL_GROUP_INDEX = "hcjf.query.conditional.group.index";
public static final String JOIN_RESOURCE_NAME_INDEX = "hcjf.query.join.resource.name.index";
public static final String JOIN_EVALUATORS_INDEX = "hcjf.query.join.evaluators.index";
public static final String DATE_FORMAT = "hcjf.query.date.format";
public static final String DECIMAL_SEPARATOR = "hcjf.query.decimal.separator";
public static final String DECIMAL_FORMAT = "hcjf.query.decimal.format";
public static final String SCIENTIFIC_NOTATION = "hcjf.query.scientific.notation";
public static final String SCIENTIFIC_NOTATION_FORMAT = "hcjf.query.scientific.notation.format";
public static final String EVALUATORS_CACHE_NAME = "hcjf.query.evaluators.cache";
public static final class ReservedWord {
public static final String SELECT = "hcjf.query.select.reserved.word";
public static final String FROM = "hcjf.query.from.reserved.word";
public static final String JOIN = "hcjf.query.join.reserved.word";
public static final String INNER = "hcjf.query.inner.join.reserved.word";
public static final String LEFT = "hcjf.query.left.join.reserved.word";
public static final String RIGHT = "hcjf.query.right.join.reserved.word";
public static final String ON = "hcjf.query.on.reserved.word";
public static final String WHERE = "hcjf.query.where.reserved.word";
public static final String ORDER_BY = "hcjf.query.order.by.reserved.word";
public static final String DESC = "hcjf.query.desc.reserved.word";
public static final String LIMIT = "hcjf.query.limit.reserved.word";
public static final String START = "hcjf.query.start.reserved.word";
public static final String RETURN_ALL = "hcjf.query.return.all.reserved.word";
public static final String ARGUMENT_SEPARATOR = "hcjf.query.argument.separator";
public static final String EQUALS = "hcjf.query.equals.reserved.word";
public static final String DISTINCT = "hcjf.query.distinct.reserved.word";
public static final String DISTINCT_2 = "hcjf.query.distinct.2.reserved.word";
public static final String GREATER_THAN = "hcjf.query.greater.than.reserved.word";
public static final String GREATER_THAN_OR_EQUALS = "hcjf.query.greater.than.or.equals.reserved.word";
public static final String SMALLER_THAN = "hcjf.query.smaller.than.reserved.word";
public static final String SMALLER_THAN_OR_EQUALS = "hcjf.query.smaller.than.or.equals.reserved.word";
public static final String IN = "hcjf.query.in.reserved.word";
public static final String NOT_IN = "hcjf.query.not.in.reserved.word";
public static final String NOT = "hcjf.query.not.reserved.word";
public static final String NOT_2 = "hcjf.query.not.2.reserved.word";
public static final String LIKE = "hcjf.query.like.reserved.word";
public static final String AND = "hcjf.query.and.reserved.word";
public static final String OR = "hcjf.query.or.reserved.word";
public static final String STATEMENT_END = "hcjf.query.statement.end.reserved.word";
public static final String REPLACEABLE_VALUE = "hcjf.query.replaceable.value.reserved.word";
public static final String STRING_DELIMITER = "hcjf.query.string.delimiter.reserved.word";
public static final String NULL = "hcjf.query.null.reserved.word";
public static final String TRUE = "hcjf.query.true.reserved.word";
public static final String FALSE = "hcjf.query.false.reserved.word";
public static final String AS = "hcjf.query.as.reserved.word";
public static final String GROUP_BY = "hcjf.query.group.by.reserved.word";
}
}
public static class Cloud {
public static final String SERVICE_NAME = "hcjf.cloud.name";
public static final String SERVICE_PRIORITY = "hcjf.cloud.priority";
public static final String IMPL = "hcjf.cloud.impl";
public static final String LOG_TAG = "hcjf.cloud.log.tag";
public static class TimerTask {
public static final String MIN_VALUE_OF_DELAY = "hcjf.cloud.timer.task.min.value.of.delay";
public static final String MAP_NAME = "hcjf.cloud.timer.task.map.name";
public static final String MAP_SUFFIX_NAME = "hcjf.cloud.timer.task.map.suffix.name";
public static final String LOCK_SUFFIX_NAME = "hcjf.cloud.timer.task.lock.suffix.name";
public static final String CONDITION_SUFFIX_NAME = "hcjf.cloud.timer.task.condition.suffix.name";
}
public static class Cache {
public static final String MAP_SUFFIX_NAME = "hcjf.cloud.cache.map.suffix.name";
public static final String LOCK_SUFFIX_NAME = "hcjf.cloud.cache.lock.suffix.name";
public static final String CONDITION_SUFFIX_NAME = "hcjf.cloud.cache.condition.suffix.name";
public static final String SIZE_STRATEGY_MAP_SUFFIX_NAME = "hcjf.cloud.cache.size.strategy.map.suffix.name";
}
}
public static class Grant {
public static final String LOG_TAG = "hcjf.grant.log.tag";
public static final String CLOUD_DEPLOYMENT = "hcjf.grant.cloud.deployment";
public static final String CLOUD_MAP_NAME = "hcjf.grant.cloud.map.name";
}
//Java property names
public static final String FILE_ENCODING = "file.encoding";
private static final SystemProperties instance;
static {
instance = new SystemProperties();
}
private final Map<String, Object> instancesCache;
private final JsonParser jsonParser;
private SystemProperties() {
super(new Properties());
instancesCache = new HashMap<>();
jsonParser = new JsonParser();
defaults.put(HCJF_DEFAULT_DATE_FORMAT, "yyyy-MM-dd HH:mm:ss");
defaults.put(HCJF_DEFAULT_NUMBER_FORMAT, "0.000");
defaults.put(HCJF_DEFAULT_DECIMAL_SEPARATOR, ".");
defaults.put(HCJF_DEFAULT_GROUPING_SEPARATOR, ",");
defaults.put(HCJF_DEFAULT_LOCALE, Locale.getDefault().toLanguageTag());
defaults.put(HCJF_DEFAULT_LOCALE_LAYER_IMPLEMENTATION, DefaultLocaleLayer.class.getName());
defaults.put(HCJF_DEFAULT_LOCALE_LAYER_IMPLEMENTATION_NAME, "default.locale.layer");
defaults.put(HCJF_DEFAULT_PROPERTIES_FILE_XML, "false");
defaults.put(HCJF_UUID_REGEX, "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
defaults.put(HCJF_INTEGER_NUMBER_REGEX, "^[-]?[0-9]{1,}$");
defaults.put(HCJF_DECIMAL_NUMBER_REGEX, "^[-]?[0-9,\\.]{0,}[0-9]{1,}$");
defaults.put(HCJF_SCIENTIFIC_NUMBER_REGEX, "^[-]?[0-9,\\.]{0,}[0-9]{1,}E[-]?[0-9]{1,}$");
defaults.put(Layer.LOG_TAG, "LAYER");
defaults.put(Layer.Deployment.SERVICE_NAME, "DeploymentService");
defaults.put(Layer.Deployment.SERVICE_PRIORITY, "0");
defaults.put(Layer.Deployment.CLOUD_DEPLOYMENT_ENABLED, "true");
defaults.put(Layer.Deployment.CLOUD_DEPLOYMENT_MAP_NAME, "hcjf.layers.plugin.cloud.deployment.map");
defaults.put(Layer.Deployment.CLOUD_DEPLOYMENT_LOCK_NAME, "hcjf.layers.plugin.cloud.deployment.lock");
defaults.put(Layer.Deployment.CLOUD_DEPLOYMENT_LOCK_CONDITION_NAME, "hcjf.layers.plugin.cloud.deployment.lock.condition.name");
defaults.put(Service.STATIC_THREAD_NAME, "StaticServiceThread");
defaults.put(Service.STATIC_THREAD_POOL_CORE_SIZE, "1");
defaults.put(Service.STATIC_THREAD_POOL_MAX_SIZE, "5");
defaults.put(Service.STATIC_THREAD_POOL_KEEP_ALIVE_TIME, "10");
defaults.put(Service.THREAD_POOL_CORE_SIZE, "100");
defaults.put(Service.THREAD_POOL_MAX_SIZE, Integer.toString(Integer.MAX_VALUE));
defaults.put(Service.THREAD_POOL_KEEP_ALIVE_TIME, "10");
defaults.put(Service.GUEST_SESSION_NAME, "Guest");
defaults.put(Service.SYSTEM_SESSION_NAME, "System");
defaults.put(Service.SHUTDOWN_TIME_OUT, "200");
defaults.put(Event.SERVICE_NAME, "Events");
defaults.put(Event.SERVICE_PRIORITY, "0");
defaults.put(Encoding.SERVICE_NAME, "EncodingService");
defaults.put(Encoding.SERVICE_PRIORITY, "1");
defaults.put(FileSystem.SERVICE_NAME, "FileSystemWatcherService");
defaults.put(FileSystem.SERVICE_PRIORITY, "1");
defaults.put(FileSystem.LOG_TAG, "FILE_SYSTEM_WATCHER_SERVICE");
defaults.put(Log.SERVICE_NAME, "LogService");
defaults.put(Log.SERVICE_PRIORITY, "0");
defaults.put(Log.FILE_PREFIX, "hcfj");
defaults.put(Log.ERROR_FILE, "false");
defaults.put(Log.WARNING_FILE, "false");
defaults.put(Log.INFO_FILE, "false");
defaults.put(Log.DEBUG_FILE, "false");
defaults.put(Log.LEVEL, "1");
defaults.put(Log.DATE_FORMAT, "yyyy-MM-dd HH:mm:ss,SSS");
defaults.put(Log.CONSUMERS, "[]");
defaults.put(Log.SYSTEM_OUT_ENABLED, "false");
defaults.put(Log.JAVA_STANDARD_LOGGER_ENABLED, "false");
defaults.put(Log.QUEUE_INITIAL_SIZE, "10000");
defaults.put(Log.TRUNCATE_TAG, "false");
defaults.put(Log.TRUNCATE_TAG_SIZE, "35");
defaults.put(Log.LOG_CONSUMERS_SIZE, "50");
defaults.put(Net.SERVICE_NAME, "Net service");
defaults.put(Net.LOG_TAG, "NET_SERVICE");
defaults.put(Net.INPUT_BUFFER_SIZE, "102400");
defaults.put(Net.OUTPUT_BUFFER_SIZE, "102400");
defaults.put(Net.CONNECTION_TIMEOUT_AVAILABLE, "true");
defaults.put(Net.CONNECTION_TIMEOUT, "30000");
defaults.put(Net.DISCONNECT_AND_REMOVE, "true");
defaults.put(Net.WRITE_TIMEOUT, "100");
defaults.put(Net.IO_THREAD_POOL_KEEP_ALIVE_TIME, "120");
defaults.put(Net.IO_THREAD_POOL_MAX_SIZE, "10000");
defaults.put(Net.IO_THREAD_POOL_CORE_SIZE, "100");
defaults.put(Net.DEFAULT_INPUT_BUFFER_SIZE, "102400");
defaults.put(Net.DEFAULT_OUTPUT_BUFFER_SIZE, "102400");
defaults.put(Net.IO_THREAD_DIRECT_ALLOCATE_MEMORY, "false");
defaults.put(Net.SSL_MAX_IO_THREAD_POOL_SIZE, "2");
defaults.put(Net.PORT_PROVIDER_TIME_WINDOWS_SIZE, "15000");
defaults.put(Net.PORT_PROBE_CONNECTION_TIMEOUT, "1000");
defaults.put(Net.Broadcast.SERVICE_NAME, "Broadcast service");
defaults.put(Net.Broadcast.LOG_TAG, "BROADCAST");
defaults.put(Net.Broadcast.INTERFACE_NAME, "eth0");
defaults.put(Net.Broadcast.IP_VERSION, "4");
defaults.put(Net.Broadcast.SENDER_DELAY, "30000");
defaults.put(Net.Broadcast.SIGNATURE_ALGORITHM, "SHA-1");
defaults.put(Net.Broadcast.RECEIVER_BUFFER_SIZE, "1024");
defaults.put(Net.Ssl.DEFAULT_KEY_PASSWORD, "hcjfkeypassword");
defaults.put(Net.Ssl.DEFAULT_KEY_TYPE, "JKS");
defaults.put(Net.Ssl.DEFAULT_KEYSTORE_PASSWORD, "hcjfkeystorepassword");
defaults.put(Net.Ssl.DEFAULT_KEYSTORE_FILE_PATH, "./src/resources/org/hcjf/io/net/https/keystore.jks");
defaults.put(Net.Ssl.DEFAULT_TRUSTED_CERTS_FILE_PATH, "./src/resources/org/hcjf/io/net/https/cacerts.jks");
defaults.put(Net.Ssl.DEFAULT_PROTOCOL, "TLSv1.2");
defaults.put(Net.Ssl.IO_THREAD_NAME, "SslIoThread");
defaults.put(Net.Ssl.ENGINE_THREAD_NAME, "SslEngineThread");
defaults.put(Net.Http.LOG_TAG, "HTTP_SERVER");
defaults.put(Net.Http.SERVER_NAME, "HCJF Web Server");
defaults.put(Net.Http.RESPONSE_DATE_HEADER_FORMAT_VALUE, "EEE, dd MMM yyyy HH:mm:ss z");
defaults.put(Net.Http.INPUT_LOG_BODY_MAX_LENGTH, "128");
defaults.put(Net.Http.OUTPUT_LOG_BODY_MAX_LENGTH, "128");
defaults.put(Net.Http.DEFAULT_SERVER_PORT, "80");
defaults.put(Net.Http.DEFAULT_CLIENT_PORT, "80");
defaults.put(Net.Http.STREAMING_LIMIT_FILE_SIZE, "10240");
defaults.put(Net.Http.DEFAULT_ERROR_FORMAT_SHOW_STACK, "true");
defaults.put(Net.Http.DEFAULT_CLIENT_CONNECT_TIMEOUT, "10000");
defaults.put(Net.Http.DEFAULT_CLIENT_READ_TIMEOUT, "10000");
defaults.put(Net.Http.DEFAULT_CLIENT_WRITE_TIMEOUT, "10000");
defaults.put(Net.Http.DEFAULT_GUEST_SESSION_NAME, "Http guest session");
defaults.put(Net.Http.DEFAULT_FILE_CHECKSUM_ALGORITHM, "MD5");
defaults.put(Net.Http.ENABLE_AUTOMATIC_RESPONSE_CONTENT_LENGTH, "true");
defaults.put(Net.Http.Folder.LOG_TAG, "FOLDER_CONTEXT");
defaults.put(Net.Http.Folder.FORBIDDEN_CHARACTERS, "[]");
defaults.put(Net.Http.Folder.FILE_EXTENSION_REGEX, "\\.(?=[^\\.]+$)");
defaults.put(Net.Http.Folder.DEFAULT_HTML_DOCUMENT, "<!DOCTYPE html><html><head><title>%s</title><body>%s</body></html></head>");
defaults.put(Net.Http.Folder.DEFAULT_HTML_BODY, "<table>%s</table>");
defaults.put(Net.Http.Folder.DEFAULT_HTML_ROW, "<tr><th><a href=\"%s\">%s</a></th></tr>");
defaults.put(Net.Http.Folder.ZIP_CONTAINER, System.getProperty("user.home"));
defaults.put(Net.Http.Folder.ZIP_TEMP_PREFIX, "hcjf_zip_temp");
defaults.put(Net.Http.Folder.JAR_CONTAINER, System.getProperty("user.home"));
defaults.put(Net.Http.Folder.JAR_TEMP_PREFIX, "hcjf_jar_temp");
defaults.put(Net.Https.DEFAULT_SERVER_PORT, "443");
defaults.put(Net.Https.DEFAULT_CLIENT_PORT, "443");
defaults.put(Net.Rest.DEFAULT_MIME_TYPE, "application/json");
defaults.put(Net.Rest.DEFAULT_ENCODING_IMPL, "hcjf");
defaults.put(Net.Rest.QUERY_PATH, "query");
defaults.put(Net.Rest.QUERY_PARAMETER_PATH, "q");
defaults.put(Query.LOG_TAG, "QUERY");
defaults.put(Query.DEFAULT_LIMIT, "1000");
defaults.put(Query.DEFAULT_DESC_ORDER, "false");
defaults.put(Query.SELECT_REGULAR_EXPRESSION, "(?i)^(select[ ]{1,}[a-zA-Z_0-9,.*\\$ ]{1,})([ ]?from[ ]{1,}[a-zA-Z_0-9.]{1,}[ ]?)([a-zA-Z_0-9'=,.~* ?%\\$<>!\\:\\-()\\[\\]]{1,})?[$;]?");
defaults.put(Query.CONDITIONAL_REGULAR_EXPRESSION, "(?i)((?<=(^((inner |left |right )?join )|^where |^limit |^start |^order by |^group by |(( inner | left | right )? join )| where | limit | start | order by | group by )))|(?=(^((inner |left |right )?join )|^where |^limit |^start |^order by |^group by |(( inner | left | right )? join )| where | limit | start | order by | group by ))");
defaults.put(Query.EVALUATOR_COLLECTION_REGULAR_EXPRESSION, "(?i)((?<=( and | or ))|(?=( and | or )))");
defaults.put(Query.OPERATION_REGULAR_EXPRESSION, "(?i)(?<=(=|<>|!=|>|<|>=|<=| in | not in | like ))|(?=(=|<>|!=|>|<|>=|<=| in | not in | like ))");
defaults.put(Query.JOIN_REGULAR_EXPRESSION, "(?i)( on )");
defaults.put(Query.AS_REGULAR_EXPRESSION, "(?i)((?<=( as ))|(?=( as )))");
defaults.put(Query.DESC_REGULAR_EXPRESSION, "(?i)( desc )");
defaults.put(Query.SELECT_GROUP_INDEX, "1");
defaults.put(Query.FROM_GROUP_INDEX, "2");
defaults.put(Query.CONDITIONAL_GROUP_INDEX, "3");
defaults.put(Query.JOIN_RESOURCE_NAME_INDEX, "0");
defaults.put(Query.JOIN_EVALUATORS_INDEX, "1");
defaults.put(Query.DATE_FORMAT, "yyyy-MM-dd HH:mm:ss");
defaults.put(Query.DECIMAL_SEPARATOR, ".");
defaults.put(Query.DECIMAL_FORMAT, "0.000");
defaults.put(Query.SCIENTIFIC_NOTATION, "E");
defaults.put(Query.SCIENTIFIC_NOTATION_FORMAT, "0.0E0");
defaults.put(Query.EVALUATORS_CACHE_NAME, "__evaluators__cache__");
defaults.put(Query.ReservedWord.SELECT, "SELECT");
defaults.put(Query.ReservedWord.FROM, "FROM");
defaults.put(Query.ReservedWord.JOIN, "JOIN");
defaults.put(Query.ReservedWord.INNER, "INNER");
defaults.put(Query.ReservedWord.LEFT, "LEFT");
defaults.put(Query.ReservedWord.RIGHT, "RIGHT");
defaults.put(Query.ReservedWord.ON, "ON");
defaults.put(Query.ReservedWord.WHERE, "WHERE");
defaults.put(Query.ReservedWord.ORDER_BY, "ORDER BY");
defaults.put(Query.ReservedWord.DESC, "DESC");
defaults.put(Query.ReservedWord.LIMIT, "LIMIT");
defaults.put(Query.ReservedWord.START, "START");
defaults.put(Query.ReservedWord.RETURN_ALL, "*");
defaults.put(Query.ReservedWord.ARGUMENT_SEPARATOR, ",");
defaults.put(Query.ReservedWord.EQUALS, "=");
defaults.put(Query.ReservedWord.DISTINCT, "<>");
defaults.put(Query.ReservedWord.DISTINCT_2, "!=");
defaults.put(Query.ReservedWord.GREATER_THAN, ">");
defaults.put(Query.ReservedWord.GREATER_THAN_OR_EQUALS, ">=");
defaults.put(Query.ReservedWord.SMALLER_THAN, "<");
defaults.put(Query.ReservedWord.SMALLER_THAN_OR_EQUALS, "<=");
defaults.put(Query.ReservedWord.IN, "IN");
defaults.put(Query.ReservedWord.NOT_IN, "NOT IN");
defaults.put(Query.ReservedWord.NOT, "NOT");
defaults.put(Query.ReservedWord.NOT_2, "!");
defaults.put(Query.ReservedWord.LIKE, "LIKE");
defaults.put(Query.ReservedWord.AND, "AND");
defaults.put(Query.ReservedWord.OR, "OR");
defaults.put(Query.ReservedWord.STATEMENT_END, ";");
defaults.put(Query.ReservedWord.REPLACEABLE_VALUE, "?");
defaults.put(Query.ReservedWord.STRING_DELIMITER, "'");
defaults.put(Query.ReservedWord.NULL, "NULL");
defaults.put(Query.ReservedWord.TRUE, "TRUE");
defaults.put(Query.ReservedWord.FALSE, "FALSE");
defaults.put(Query.ReservedWord.AS, "AS");
defaults.put(Query.ReservedWord.GROUP_BY, "GROUP BY");
defaults.put(Cloud.SERVICE_NAME, "CloudService");
defaults.put(Cloud.SERVICE_PRIORITY, "0");
defaults.put(Cloud.IMPL, "");
defaults.put(Cloud.LOG_TAG, "CLOUD");
defaults.put(Cloud.TimerTask.MIN_VALUE_OF_DELAY, "30000");
defaults.put(Cloud.TimerTask.MAP_NAME, "hcjf.cloud.timer.task.map");
defaults.put(Cloud.TimerTask.MAP_SUFFIX_NAME, "hcjf.cloud.timer.task.map.");
defaults.put(Cloud.TimerTask.LOCK_SUFFIX_NAME, "hcjf.cloud.timer.task.lock.");
defaults.put(Cloud.TimerTask.CONDITION_SUFFIX_NAME, "hcjf.cloud.timer.task.condition.");
defaults.put(Cloud.Cache.MAP_SUFFIX_NAME, "hcjf.cloud.cache.map.");
defaults.put(Cloud.Cache.LOCK_SUFFIX_NAME, "hcjf.cloud.cache.lock.");
defaults.put(Cloud.Cache.CONDITION_SUFFIX_NAME, "hcjf.cloud.cache.condition.");
defaults.put(Cloud.Cache.SIZE_STRATEGY_MAP_SUFFIX_NAME, "hcjf.cloud.cache.size.strategy.map.");
defaults.put(Grant.LOG_TAG, "GRANT");
defaults.put(Grant.CLOUD_DEPLOYMENT, "false");
defaults.put(Grant.CLOUD_MAP_NAME, "hcjf.grant.cloud.map.name");
Properties system = System.getProperties();
putAll(system);
System.setProperties(this);
}
/**
* Put the default value for a property.
* @param propertyName Property name.
* @param defaultValue Property default value.
* @throws NullPointerException Throw a {@link NullPointerException} when the
* property name or default value are null.
*/
public static void putDefaultValue(String propertyName, String defaultValue) {
if(propertyName == null) {
throw new NullPointerException("Invalid property name null");
}
if(defaultValue == null) {
throw new NullPointerException("Invalid default value null");
}
instance.defaults.put(propertyName, defaultValue);
}
/**
* Calls the <tt>Hashtable</tt> method {@code put}. Provided for
* parallelism with the <tt>getProperty</tt> method. Enforces use of
* strings for property keys and values. The value returned is the
* result of the <tt>Hashtable</tt> call to {@code put}.
*
* @param key the key to be placed into this property list.
* @param value the value corresponding to <tt>key</tt>.
* @return the previous value of the specified key in this property
* list, or {@code null} if it did not have one.
* @see #getProperty
* @since 1.2
*/
@Override
public synchronized Object setProperty(String key, String value) {
Object result = super.setProperty(key, value);
synchronized (instancesCache) {
instancesCache.remove(key);
}
try {
//TODO: Create listeners
} catch (Exception ex){}
return result;
}
/**
* This method return the string value of the system property
* named like the parameter.
* @param propertyName Name of the find property.
* @param validator Property validator.
* @return Return the value of the property or null if the property is no defined.
*/
public static String get(String propertyName, PropertyValueValidator<String> validator) {
String result = System.getProperty(propertyName);
if(result == null) {
org.hcjf.log.Log.d("Property not found: $1", propertyName);
}
if(validator != null) {
if(!validator.validate(result)){
throw new IllegalPropertyValueException(propertyName + "=" + result);
}
}
return result;
}
/**
* This method return the string value of the system property
* named like the parameter.
* @param propertyName Name of the find property.
* @return Return the value of the property or null if the property is no defined.
*/
public static String get(String propertyName) {
return get(propertyName, null);
}
/**
* This method return the value of the system property as boolean.
* @param propertyName Name of the find property.
* @return Value of the system property as boolean, or null if the property is not found.
*/
public static Boolean getBoolean(String propertyName) {
Boolean result = null;
synchronized (instance.instancesCache) {
result = (Boolean) instance.instancesCache.get(propertyName);
if (result == null) {
String propertyValue = get(propertyName);
try {
if (propertyValue != null) {
result = Boolean.valueOf(propertyValue);
instance.instancesCache.put(propertyName, result);
}
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a boolean valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the value of the system property as integer.
* @param propertyName Name of the find property.
* @return Value of the system property as integer, or null if the property is not found.
*/
public static Integer getInteger(String propertyName) {
Integer result = null;
synchronized (instance.instancesCache) {
result = (Integer) instance.instancesCache.get(propertyName);
if (result == null) {
String propertyValue = get(propertyName);
try {
if (propertyValue != null) {
result = Integer.decode(propertyValue);
instance.instancesCache.put(propertyName, result);
}
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a integer valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the value of the system property as long.
* @param propertyName Name of the find property.
* @return Value of the system property as long, or null if the property is not found.
*/
public static Long getLong(String propertyName) {
Long result = null;
synchronized (instance.instancesCache) {
result = (Long) instance.instancesCache.get(propertyName);
if (result == null) {
String propertyValue = get(propertyName);
try {
if (propertyValue != null) {
result = Long.decode(propertyValue);
instance.instancesCache.put(propertyName, result);
}
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a long valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the value of the system property as double.
* @param propertyName Name of the find property.
* @return Value of the system property as double, or null if the property is not found.
*/
public static Double getDouble(String propertyName) {
Double result = null;
synchronized (instance.instancesCache) {
result = (Double) instance.instancesCache.get(propertyName);
if(result == null) {
String propertyValue = get(propertyName);
try {
if (propertyValue != null) {
result = Double.valueOf(propertyValue);
instance.instancesCache.put(propertyName, result);
}
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a double valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the value of the system property as {@link UUID} instance.
* @param propertyName Name of the find property.
* @return Value of the system property as {@link UUID} instance, or null if the property is not found.
*/
public static UUID getUUID(String propertyName) {
UUID result = null;
synchronized (instance.instancesCache) {
result = (UUID) instance.instancesCache.get(propertyName);
if(result == null) {
String propertyValue = get(propertyName);
try {
if (propertyValue != null) {
result = UUID.fromString(propertyValue);
instance.instancesCache.put(propertyName, result);
}
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a UUID valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the value of the system property as {@link Path} instance.
* @param propertyName Name of the find property.
* @return Value of the system property as {@link Path} instance, or null if the property is not found.
*/
public static Path getPath(String propertyName) {
Path result = null;
synchronized (instance.instancesCache) {
result = (Path) instance.instancesCache.get(propertyName);
if(result == null) {
String propertyValue = get(propertyName);
try {
if (propertyValue != null) {
result = Paths.get(propertyValue);
instance.instancesCache.put(propertyName, result);
}
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a path valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the value of the system property as class.
* @param propertyName Name of the find property.
* @param <O> Type of the class instance expected.
* @return Class instance.
*/
public static <O extends Object> Class<O> getClass(String propertyName) {
Class<O> result;
synchronized (instance.instancesCache) {
result = (Class<O>) instance.instancesCache.get(propertyName);
if(result == null) {
String propertyValue = get(propertyName);
try {
if(propertyValue != null) {
result = (Class<O>) Class.forName(propertyValue);
instance.instancesCache.put(propertyName, result);
}
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a class name valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* Return the default charset of the JVM instance.
* @return Default charset.
*/
public static String getDefaultCharset() {
return System.getProperty(FILE_ENCODING);
}
/**
* This method return the value of the property as Locale instance.
* The instance returned will be stored on near cache and will be removed when the
* value of the property has been updated.
* @param propertyName Name of the property that contains locale representation.
* @return Locale instance.
*/
public static Locale getLocale(String propertyName) {
Locale result;
synchronized (instance.instancesCache) {
result = (Locale) instance.instancesCache.get(propertyName);
if(result == null) {
String propertyValue = get(propertyName);
try {
result = Locale.forLanguageTag(propertyValue);
instance.instancesCache.put(propertyName, result);
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a locale tag valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the valuo of the property called 'hcjf.default.locale' as a locale instance.
* The instance returned will be stored on near cache and will be removed when the
* value of the property has been updated.
* @return Locale instance.
*/
public static Locale getLocale() {
return getLocale(HCJF_DEFAULT_LOCALE);
}
/**
* This method return the value of the property as a DecimalFormat instnace.
* The instance returned will be stored on near cache and will be removed when the
* value of the property has been updated.
* @param propertyName Name of the property that contains decimal pattern.
* @return DecimalFormat instance.
*/
public static DecimalFormat getDecimalFormat(String propertyName) {
DecimalFormat result;
synchronized (instance.instancesCache) {
result = (DecimalFormat) instance.instancesCache.get(propertyName);
if(result == null) {
String propertyValue = get(propertyName);
try {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(get(HCJF_DEFAULT_DECIMAL_SEPARATOR).charAt(0));
symbols.setGroupingSeparator(get(HCJF_DEFAULT_GROUPING_SEPARATOR).charAt(0));
result = new DecimalFormat(propertyValue, symbols);
instance.instancesCache.put(propertyName, result);
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a decimal pattern valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the value of the property as a SimpleDateFormat instance.
* The instance returned will be stored on near cache and will be removed when the
* value of the property has been updated.
* @param propertyName Name of the property that contains date representation.
* @return Simple date format instance.
*/
public static SimpleDateFormat getDateFormat(String propertyName) {
SimpleDateFormat result;
synchronized (instance.instancesCache) {
result = (SimpleDateFormat) instance.instancesCache.get(propertyName);
if(result == null) {
String propertyValue = get(propertyName);
try {
result = new SimpleDateFormat(get(propertyName));
instance.instancesCache.put(propertyName, result);
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a date pattern valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the value of the property as instance of list.
* @param propertyName Name of the property that contains the json array representation.
* @return List instance.
*/
public static List<String> getList(String propertyName) {
String propertyValue = get(propertyName);
List<String> result = new ArrayList<>();
synchronized (instance.instancesCache) {
if (instance.instancesCache.containsKey(propertyName)) {
result.addAll((List<? extends String>) instance.instancesCache.get(propertyName));
} else {
try {
JsonArray array = (JsonArray) instance.jsonParser.parse(propertyValue);
array.forEach(A -> result.add(A.getAsString()));
List<String> cachedResult = new ArrayList<>();
cachedResult.addAll(result);
instance.instancesCache.put(propertyName, cachedResult);
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a json array valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the value of the property as instance of set.
* @param propertyName Name of the property that contains the json array representation.
* @return Set instance.
*/
public static Set<String> getSet(String propertyName) {
String propertyValue = get(propertyName);
Set<String> result = new TreeSet<>();
synchronized (instance.instancesCache) {
if (instance.instancesCache.containsKey(propertyName)) {
result.addAll((List<? extends String>) instance.instancesCache.get(propertyName));
} else {
try {
JsonArray array = (JsonArray) instance.jsonParser.parse(propertyValue);
array.forEach(A -> result.add(A.getAsString()));
List<String> cachedResult = new ArrayList<>();
cachedResult.addAll(result);
instance.instancesCache.put(propertyName, cachedResult);
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a json array valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
/**
* This method return the value of the property as instance of map.
* @param propertyName The name of the property that contains the json object representation.
* @return Map instance.
*/
public static Map<String, String> getMap(String propertyName) {
String propertyValue = get(propertyName);
Map<String, String> result = new HashMap<>();
synchronized (instance.instancesCache) {
if (instance.instancesCache.containsKey(propertyName)) {
result.putAll((Map<String, String>) instance.instancesCache.get(propertyName));
} else {
try {
JsonObject object = (JsonObject) instance.jsonParser.parse(propertyValue);
object.entrySet().forEach(S -> result.put(S.getKey(), object.get(S.getKey()).getAsString()));
Map<String, String> cachedResult = new HashMap<>();
cachedResult.putAll(result);
instance.instancesCache.put(propertyName, cachedResult);
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a json object valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
public static Pattern getPattern(String propertyName) {
return getPattern(propertyName, 0);
}
/**
* Return the compiled pattern from the property value.
* @param propertyName Name of the property.
* @param flags Regex flags.
* @return Compiled pattern.
*/
public static Pattern getPattern(String propertyName, int flags) {
String propertyValue = get(propertyName);
Pattern result;
synchronized (instance.instancesCache) {
if(instance.instancesCache.containsKey(propertyName)) {
result = (Pattern) instance.instancesCache.get(propertyName);
} else {
try {
result = Pattern.compile(propertyValue, flags);
instance.instancesCache.put(propertyName, result);
} catch (Exception ex) {
throw new IllegalArgumentException("The property value has not a regex valid format: '"
+ propertyName + ":" + propertyValue + "'", ex);
}
}
}
return result;
}
} |
package org.jboss.msc.service;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.value.Value;
import java.util.Collection;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Builder to configure service before installing it into the container.
* <p>
* Service may require multiple dependencies (named values) to be satisfied before starting.
* Every dependency requirement must be specified via {@link #requires(ServiceName)} method.
* <p>
* Single service can provide multiple values which can be requested by dependent services.
* Every named value service provides must be specified via {@link #provides(ServiceName...)} method.
* <p>
* Once all required and provided dependencies are defined, references to all {@link Consumer}s
* and {@link Supplier}s should be passed to service instance so they can be accessed by service
* at runtime.
* <p>
* Implementations of this interface are not thread safe.
*
* @param <T> service value type if service provides single value
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a>
*/
public interface ServiceBuilder<T> {
/**
* Adds aliases for this service.
*
* @param aliases the service names to use as aliases
* @return the builder
* @throws UnsupportedOperationException if this service builder
* wasn't created via {@link ServiceTarget#addService(ServiceName)} method.
*/
ServiceBuilder<T> addAliases(ServiceName... aliases);
<V> Supplier<V> requires(ServiceName name);
<V> Consumer<V> provides(ServiceName... names);
/**
* Sets initial service mode.
*
* @param mode initial service mode
* @return this builder
*/
ServiceBuilder<T> setInitialMode(ServiceController.Mode mode);
/**
* Sets service instance. If {@link #install()} method call is issued
* without this method being called then <code>NULL</code> service will be
* installed into the container.
* <p>
* When this method have been called then all subsequent
* calls of {@link #requires(ServiceName)}, and {@link #provides(ServiceName...)}
* methods will fail.
*
* @param service the service instance
* @return this configurator
*/
ServiceBuilder<T> setInstance(org.jboss.msc.Service service);
/**
* Adds a stability monitor to be added to the service.
*
* @param monitor the monitor to add to the service
* @return this builder
*/
ServiceBuilder<T> addMonitor(StabilityMonitor monitor);
/**
* Adds a service listener to be added to the service.
*
* @param listener the listener to add to the service
* @return this builder
*/
ServiceBuilder<T> addListener(LifecycleListener listener);
/**
* Installs configured service into the container.
*
* @return installed service controller
* @throws ServiceRegistryException if installation fails for any reason
*/
ServiceController<T> install();
// DEPRECATED METHODS //
/**
* Add multiple, non-injected dependencies.
*
* @param dependencies the service names to depend on
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #requires(ServiceName)} instead.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addDependencies(ServiceName... dependencies);
/**
* Add multiple, non-injected dependencies.
*
* @param dependencyType the dependency type; must not be {@code null}
* @param dependencies the service names to depend on
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Optional dependencies are <em>unsafe</em> and should not be used.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addDependencies(DependencyType dependencyType, ServiceName... dependencies);
/**
* Add multiple, non-injected dependencies.
*
* @param dependencies the service names to depend on
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #requires(ServiceName)} instead.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addDependencies(Iterable<ServiceName> dependencies);
/**
* Add multiple, non-injected dependencies.
*
* @param dependencyType the dependency type; must not be {@code null}
* @param dependencies the service names to depend on
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Optional dependencies are <em>unsafe</em> and should not be used.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addDependencies(DependencyType dependencyType, Iterable<ServiceName> dependencies);
/**
* Add a dependency. Calling this method multiple times for the same service name will only add it as a
* dependency one time; however this may be useful to specify multiple injections for one dependency.
*
* @param dependency the name of the dependency
* @return an injection builder for optionally injecting the dependency
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #requires(ServiceName)} instead.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addDependency(ServiceName dependency);
/**
* Add a dependency. Calling this method multiple times for the same service name will only add it as a
* dependency one time; however this may be useful to specify multiple injections for one dependency.
*
* @param dependencyType the dependency type; must not be {@code null}
* @param dependency the name of the dependency
* @return an injection builder for optionally injecting the dependency
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Optional dependencies are <em>unsafe</em> and should not be used.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addDependency(DependencyType dependencyType, ServiceName dependency);
/**
* Add a service dependency. Calling this method multiple times for the same service name will only add it as a
* dependency one time; however this may be useful to specify multiple injections for one dependency.
*
* @param dependency the name of the dependency
* @param target the injector into which the dependency should be stored
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #requires(ServiceName)} instead.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addDependency(ServiceName dependency, Injector<Object> target);
/**
* Add a service dependency. Calling this method multiple times for the same service name will only add it as a
* dependency one time; however this may be useful to specify multiple injections for one dependency.
*
* @param dependencyType the dependency type; must not be {@code null}
* @param dependency the name of the dependency
* @param target the injector into which the dependency should be stored
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Optional dependencies are <em>unsafe</em> and should not be used.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addDependency(DependencyType dependencyType, ServiceName dependency, Injector<Object> target);
/**
* Add a service dependency. The type of the dependency is checked before it is passed into the (type-safe) injector
* instance. Calling this method multiple times for the same service name will only add it as a
* dependency one time; however this may be useful to specify multiple injections for one dependency.
*
* @param dependency the name of the dependency
* @param type the class of the value of the dependency
* @param target the injector into which the dependency should be stored
* @param <I> the type of the value of the dependency
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #requires(ServiceName)} instead.
* This method will be removed in a future release.
*/
@Deprecated
<I> ServiceBuilder<T> addDependency(ServiceName dependency, Class<I> type, Injector<I> target);
/**
* Add a service dependency. The type of the dependency is checked before it is passed into the (type-safe) injector
* instance. Calling this method multiple times for the same service name will only add it as a
* dependency one time; however this may be useful to specify multiple injections for one dependency.
*
* @param dependencyType the dependency type; must not be {@code null}
* @param dependency the name of the dependency
* @param type the class of the value of the dependency
* @param target the injector into which the dependency should be stored
* @param <I> the type of the value of the dependency
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Optional dependencies are <em>unsafe</em> and should not be used.
* This method will be removed in a future release.
*/
@Deprecated
<I> ServiceBuilder<T> addDependency(DependencyType dependencyType, ServiceName dependency, Class<I> type, Injector<I> target);
/**
* Add an injection. The given value will be injected into the given injector before service start, and uninjected
* after service stop.
*
* @param target the injection target
* @param value the injection value
* @param <I> the injection type
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #requires(ServiceName)} instead.
* This method will be removed in a future release.
*/
@Deprecated
<I> ServiceBuilder<T> addInjection(Injector<? super I> target, I value);
/**
* Add an injection value. The given value will be injected into the given injector before service start, and uninjected
* after service stop.
*
* @param target the injection target
* @param value the injection value
* @param <I> the injection type
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #requires(ServiceName)} instead.
* This method will be removed in a future release.
*/
@Deprecated
<I> ServiceBuilder<T> addInjectionValue(Injector<? super I> target, Value<I> value);
/**
* Add an injection of this service into another target. The given injector will be given this service after
* start, and uninjected when this service stops.
* <p> Differently from other injection types, failures to perform an outward injection will not result in a failure
* to start the service.
*
* @param target the injector target
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #provides(ServiceName...)} instead.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addInjection(Injector<? super T> target);
/**
* Add service stability monitors that will be added to this service.
*
* @param monitors a list of stability monitors to add to the service
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #addMonitor(StabilityMonitor)} instead.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addMonitors(final StabilityMonitor... monitors);
/**
* Add a service listener that will be added to this service.
*
* @param listener the listener to add to the service
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #addListener(LifecycleListener)} instead.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addListener(ServiceListener<? super T> listener);
/**
* Add service listeners that will be added to this service.
*
* @param listeners a list of listeners to add to the service
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #addListener(LifecycleListener)} instead.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addListener(ServiceListener<? super T>... listeners);
/**
* Add service listeners that will be added to this service.
*
* @param listeners a collection of listeners to add to the service
* @return this builder
* @throws UnsupportedOperationException if this service builder
* was created via {@link ServiceTarget#addService(ServiceName)} method.
* @deprecated Use {@link #addListener(LifecycleListener)} instead.
* This method will be removed in a future release.
*/
@Deprecated
ServiceBuilder<T> addListener(Collection<? extends ServiceListener<? super T>> listeners);
/**
* The dependency type.
*
* @deprecated Optional dependencies are <em>unsafe</em> and should not be used.
* This enum will be removed in a future release.
*/
@Deprecated
enum DependencyType {
/**
* A required dependency.
*/
REQUIRED,
/**
* An optional dependency.
*/
OPTIONAL,
;
}
} |
package org.jboss.netty.channel;
import java.net.SocketAddress;
/**
* Represents the current or future state of a {@link Channel}.
* <p>
* The state of a {@link Channel} is interpreted differently depending on the
* {@linkplain ChannelStateEvent#getValue() value} of a {@link ChannelStateEvent}
* and the direction of the event in a {@link ChannelPipeline}:
*
* <table border="1" cellspacing="0" cellpadding="6">
* <tr>
* <th>Direction</th><th>State</th><th>Value</th><th>Meaning</th>
* </tr>
* <tr>
* <td>Upstream</td><td>{@link #OPEN}</td><td>{@code true}</td><td>The channel is open.</td>
* </tr>
* <tr>
* <td>Upstream</td><td>{@link #OPEN}</td><td>{@code false}</td><td>The channel is closed.</td>
* </tr>
* <tr>
* <td>Upstream</td><td>{@link #BOUND}</td><td>{@link SocketAddress}</td><td>The channel is bound to a local address.</td>
* </tr>
* <tr>
* <td>Upstream</td><td>{@link #BOUND}</td><td>{@code null}</td><td>The channel is unbound to a local address.</td>
* </tr>
* <tr>
* <td>Upstream</td><td>{@link #CONNECTED}</td><td>{@link SocketAddress}</td><td>The channel is connected to a remote address.</td>
* </tr>
* <tr>
* <td>Upstream</td><td>{@link #CONNECTED}</td><td>{@code null}</td><td>The channel is disconnected from a remote address.</td>
* </tr>
* <tr>
* <td>Upstream</td><td>{@link #INTEREST_OPS}</td><td>an integer</td><td>The channel interestOps has been changed.</td>
* </tr>
* <tr>
* <td>Downstream</td><td>{@link #OPEN}</td><td>{@code true}</td><td>N/A</td>
* </tr>
* <tr>
* <td>Downstream</td><td>{@link #OPEN}</td><td>{@code false}</td><td>Close the channel.</td>
* </tr>
* <tr>
* <td>Downstream</td><td>{@link #BOUND}</td><td>{@link SocketAddress}</td><td>Bind the channel to the specified local address.</td>
* </tr>
* <tr>
* <td>Downstream</td><td>{@link #BOUND}</td><td>{@code null}</td><td>Unbind the channel from the current local address.</td>
* </tr>
* <tr>
* <td>Downstream</td><td>{@link #CONNECTED}</td><td>{@link SocketAddress}</td><td>Connect the channel to the specified remote address.</td>
* </tr>
* <tr>
* <td>Downstream</td><td>{@link #CONNECTED}</td><td>{@code null}</td><td>Disconnect the channel from the current remote address.</td>
* </tr>
* <tr>
* <td>Downstream</td><td>{@link #INTEREST_OPS}</td><td>an integer</td><td>Change the interestOps of the channel.</td>
* </tr>
* </table>
* <p>
* To see how a {@link ChannelEvent} is interpreted further, please refer to
* {@link ChannelUpstreamHandler} and {@link ChannelDownstreamHandler}.
*
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Trustin Lee (tlee@redhat.com)
*
* @version $Rev$, $Date$
*/
public enum ChannelState {
/**
* Represents a {@link Channel}'s {@link Channel#isOpen() open} property
*/
OPEN,
/**
* Represents a {@link Channel}'s {@link Channel#isBound() bound} property
*/
BOUND,
/**
* Represents a {@link Channel}'s {@link Channel#isConnected() connected}
* property
*/
CONNECTED,
/**
* Represents a {@link Channel}'s {@link Channel#getInterestOps() interestOps}
* property
*/
INTEREST_OPS,
} |
package org.lazyluke.wintermock;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.getAllServeEvents;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import com.github.tomakehurst.wiremock.verification.NearMiss;
import wiremock.com.google.common.collect.Lists;
public final class FunctionCall implements Serializable {
private static final String RECORDED = "/recorded/";
private static final Logger LOGGER = LoggerFactory.getLogger(FunctionCall.class);
public static void record(String functionName, FunctionCallParameters regExToMatchFunctionParametersSerializedAsJson, Object functionReturnAsJsonString) {
String jsonReturn = functionReturnAsJsonString instanceof String ? (String) functionReturnAsJsonString : StubbingHelper.getAsJsonString(functionReturnAsJsonString);
// TODO parameters.getStringRepresentationOfParameters() is BEFORE delegate call
// TODO parameters.getParameters() has parameters after call - may not have the same StringRepresentationOfParameters AFTER call for IMPURE FUNCTION
stubFor(post(urlMatching(RECORDED + functionName))
.withRequestBody(equalTo(regExToMatchFunctionParametersSerializedAsJson.getStringRepresentationOfParameters()))
.willReturn(aResponse().withBody(jsonReturn).withStatus(200)));
}
public static void record(String functionName, FunctionCallParameters parameters) {
// TODO parameters.getStringRepresentationOfParameters() is BEFORE delegate call
// TODO parameters.getParameters() has parameters after call - may not have the same StringRepresentationOfParameters AFTER call for IMPURE FUNCTION
stubFor(post(urlMatching(RECORDED + functionName))
.withRequestBody(equalToJson(parameters.getStringRepresentationOfParameters()))
.willReturn(aResponse().withStatus(204)));
}
// TODO initally rename "expect"
// TODO then provide mockito style alternative when X.y then return X
public static void create(String nameOfTheFunctionCalled, String regExToMatchFunctionParametersSerializedAsJson, String functionReturnAsJsonString) {
regExToMatchFunctionParametersSerializedAsJson = replaceSingleQuoteWithDouble(regExToMatchFunctionParametersSerializedAsJson);
functionReturnAsJsonString = replaceSingleQuoteWithDouble(functionReturnAsJsonString);
String escapeJsonForRegex = escapeJsonForRegex(regExToMatchFunctionParametersSerializedAsJson);
if (!escapeJsonForRegex.startsWith(".*")) {
escapeJsonForRegex = ".*" + escapeJsonForRegex;
}
if (!escapeJsonForRegex.endsWith(".*")) {
escapeJsonForRegex = escapeJsonForRegex + ".*";
}
stubFor(post(urlMatching("/" + nameOfTheFunctionCalled)).withRequestBody(matching(escapeJsonForRegex)).willReturn(
aResponse().withBody(functionReturnAsJsonString).withStatus(201)));
}
public static String replaceSingleQuoteWithDouble(String s) {
return (s == null) ? "" : s.replace('\'', '"');
}
public static String escapeJsonForRegex(String expected) {
return expected
.replaceAll("\\{", "\\\\{")
.replaceAll("}", "\\\\}")
.replaceAll("\\[", "\\\\[")
.replaceAll("]", "\\\\]")
;
}
public static String createCodeAndFilesFromRecordedCalls() {
List<StubMapping> mappings = WireMock.listAllStubMappings().getMappings();
StringBuilder sb = new StringBuilder();
for (StubMapping mapping : mappings) {
sb.append("FunctionCall.create(\"" + getFunctionNameFromWiremockUrlPath(mapping.getRequest().getUrlPattern()) + "\", ");
String functionParametersAsJsonString = mapping.getRequest().getBodyPatterns().get(0).getExpected();
sb.append("\n Parameter1:\n " + functionParametersAsJsonString);
String functionReturnAsJsonString = mapping.getResponse().getBody();
sb.append("\n Parameter2:\n " + functionReturnAsJsonString);
sb.append("\n);\n");
}
//try {
// Thread.sleep(100000);
//} catch (InterruptedException e) {
// e.printStackTrace();
return sb.toString();
}
private static String getFunctionNameFromWiremockUrlPath(String urlPath) {
return urlPath.replaceAll(RECORDED, "").replace("/", "");
}
public static <T> T checkNextExpectedCallAndReturn(String functionName, FunctionCallParameters actualFunctionParameters, Class<T> classOfReturn) {
// WireMockServer wireMockServer = new WireMockServer(options().port(8080)); //No-args constructor will start on port 8080, no HTTPS
String body = actualFunctionParameters.getStringRepresentationOfParameters();
HttpEntity<String> request = new HttpEntity<>(body, new HttpHeaders());
String response = null;
try {
response = new RestTemplate().postForObject(StubbingHelper.WIREMOCK_URL + functionName, request, String.class);
} catch (RestClientException e) {
handleErrorsShowNearMisses(functionName, body, e);
}
T ret = (classOfReturn == String.class) ? (T) response : StubbingHelper.convertJsonStringToObjectOfClass(response, classOfReturn);
return ret;
}
public static <T> T checkNextExpectedCallAndReturn(String functionName, FunctionCallParameters actualFunctionParameters, TypeReference<T> typeRefOfReturn) {
String body = actualFunctionParameters.getStringRepresentationOfParameters();
HttpEntity<String> request = new HttpEntity<>(body, new HttpHeaders());
String response = null;
try {
response = new RestTemplate().postForObject(StubbingHelper.WIREMOCK_URL + functionName, request, String.class);
} catch (RestClientException e) {
handleErrorsShowNearMisses(functionName, body, e);
}
T ret = StubbingHelper.fromJSON(typeRefOfReturn, response);
return ret;
}
private static void handleErrorsShowNearMisses(String functionName, String body, RestClientException e) {
if (e instanceof HttpClientErrorException) {
HttpClientErrorException httpClientErrorException = (HttpClientErrorException) e;
if (httpClientErrorException.getStatusCode() == HttpStatus.NOT_FOUND) {
List<NearMiss> nearMisses = WireMock.findNearMissesFor(getRequestedFor(urlEqualTo("/" + functionName)).withRequestBody(equalTo(body)));
if (nearMisses.size() <= 0) {
LOGGER.error("\n\n**** No 'near misses' found to match call to " + functionName + " with request: " + body);
throw e;
}
LOGGER.error("\n\n**** Found one of more 'near misses' matching call " + functionName + " with request: " + body);
for (NearMiss nearMiss : nearMisses) {
String url = nearMiss.getRequest().getUrl().replaceFirst("/","");
LOGGER.error("\n\n**** Closest match " + url + " " + nearMiss.getRequest().getBodyAsString());
//StringValuePattern stringValuePattern = nearMiss.getStubMapping().getRequest().getBodyPatterns().get(0);
}
} else {
throw new IllegalStateException("Unexpected http status", e);
}
} else {
// not sure what this is so rethrow
throw e;
}
}
public static List<String> containsMatchingCall(String functionName, int callInstance, Map<String, String> parameterExpressionMap, Map<String, String> returnExpressionMap) {
List<ServeEvent> allServeEvents = getAllServeEvents();
List<ServeEvent> namedServeEventsMatched = new ArrayList<>(allServeEvents.size());
List<ServeEvent> namedServeEventsUnmatched = new ArrayList<>(allServeEvents.size());
List<String> errors = new ArrayList<>();
for (ServeEvent serveEvent : allServeEvents) {
String url = serveEvent.getRequest().getUrl();
// TODO contains?
if (url.contains(functionName)) {
if (serveEvent.getWasMatched()) {
namedServeEventsMatched.add(serveEvent);
} else {
namedServeEventsUnmatched.add(serveEvent);
}
}
}
if (namedServeEventsMatched.size() == 0) {
errors.add("No matched calls to " + functionName + " found. There were " + allServeEvents.size() + " other calls");
if (namedServeEventsUnmatched.size() > 0) {
errors.add("There were " + namedServeEventsUnmatched.size() + " calls to " + functionName + " that were not matched ");
}
errors.add(getServerEventsAsString(allServeEvents));
return errors;
}
if (callInstance == -1) {
namedServeEventsMatched = Lists.reverse(namedServeEventsMatched);
callInstance = 0;
}
if (callInstance >= namedServeEventsMatched.size()) {
errors.add("Trying to verify (zero based) call number " + callInstance + " of " + functionName + " but there are only " + namedServeEventsMatched.size());
errors.add(getServerEventsAsString(namedServeEventsMatched));
return errors;
}
ServeEvent serveEvent = namedServeEventsMatched.get(callInstance);
String params = serveEvent.getRequest().getBodyAsString();
String returns = serveEvent.getResponseDefinition().getBody();
if (JsonPathChecker.verifyContains(params, parameterExpressionMap) && JsonPathChecker.verifyContains(returns, returnExpressionMap)) {
errors.clear();
} else {
errors.add(String.format("Found call to %s but not with parameters %s %s, actual parameters were %s and %s", functionName, parameterExpressionMap, returnExpressionMap, params, returns));
}
return errors;
}
private static String getServerEventsAsString(List<ServeEvent> allServeEvents) {
try {
// have to use the wiremock version of ObjectMapper here to respect the wiremock jackson annotations on ServeEvent
return new wiremock.com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(allServeEvents);
} catch (wiremock.com.fasterxml.jackson.core.JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static int getNumberOfTimesCalled(String functionName) {
int count = 0;
for (ServeEvent serveEvent : getAllServeEvents()) {
String url = serveEvent.getRequest().getUrl();
if (url.contains(functionName)) {
count++;
}
}
return count;
}
} |
package org.lightmare.utils.earfile;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.lightmare.jpa.ConfigLoader;
import org.lightmare.utils.AbstractIOUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
import org.lightmare.utils.fs.FileType;
/**
* Implementation of {@link AbstractIOUtils} for ear directories
*
* @author levan
*
*/
public class DirUtils extends AbstractIOUtils {
public static final FileType type = FileType.EDIR;
public DirUtils(String path) {
super(path);
}
public DirUtils(File file) {
super(file);
}
public DirUtils(URL url) throws IOException {
super(url);
}
@Override
public FileType getType() {
return type;
}
@Override
public InputStream earReader() throws IOException {
String appXmlPath;
if (path.endsWith(FILE_SEPARATOR)) {
appXmlPath = StringUtils.concat(path, APPLICATION_XML_PATH);
} else {
appXmlPath = StringUtils.concat(path, FILE_SEPARATOR,
APPLICATION_XML_PATH);
}
File xmlFile = new File(appXmlPath);
InputStream stream = new FileInputStream(xmlFile);
return stream;
}
private void fillLibs(File libDirectory) throws IOException {
File[] libJars = libDirectory.listFiles(new FileFilter() {
@Override
public boolean accept(File jarFile) {
return jarFile.getName().endsWith(JAR_FILE_EXT)
&& ObjectUtils.notTrue(jarFile.isDirectory());
}
});
String jarPath;
URL jarURL;
if (ObjectUtils.available(libJars)) {
for (File libFile : libJars) {
URL url = libFile.toURI().toURL();
jarPath = StringUtils.concat(url.toString(), ARCHIVE_URL_DELIM,
FILE_SEPARATOR);
jarURL = new URL(JAR, StringUtils.EMPTY_STRING, jarPath);
getLibURLs().add(url);
getLibURLs().add(jarURL);
}
}
}
@Override
public void getEjbLibs() throws IOException {
File[] files = realFile.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.getName().endsWith(LIB) && file.isDirectory();
}
});
if (ObjectUtils.available(files)) {
for (File libDirectory : files) {
fillLibs(libDirectory);
}
}
}
private JarFile extracted(String jarName) throws IOException {
return new JarFile(jarName);
}
@Override
public boolean checkOnOrm(String jarName) throws IOException {
JarEntry xmlEntry = extracted(jarName).getJarEntry(
ConfigLoader.XML_PATH);
return ObjectUtils.notNull(xmlEntry);
}
@Override
public void extractEjbJars(Set<String> jarNames) throws IOException {
String xmlPath;
if (path.endsWith(FILE_SEPARATOR)) {
xmlPath = path;
} else {
xmlPath = StringUtils.concat(path, FILE_SEPARATOR);
}
String fillXmlPath;
String jarPath;
URL currentURL;
boolean checkOnOrm;
for (String jarName : jarNames) {
fillXmlPath = StringUtils.concat(xmlPath, jarName);
checkOnOrm = checkOnOrm(fillXmlPath);
currentURL = new File(fillXmlPath).toURI().toURL();
getEjbURLs().add(currentURL);
if (xmlFromJar && checkOnOrm) {
jarPath = StringUtils.concat(currentURL.toString(),
ARCHIVE_URL_DELIM, ConfigLoader.XML_PATH);
URL jarURL = new URL(JAR, StringUtils.EMPTY_STRING, jarPath);
getXmlFiles().put(jarName, jarURL);
getXmlURLs().put(currentURL, jarURL);
}
}
}
@Override
protected void scanArchive(Object... args) throws IOException {
if (ObjectUtils.available(args)) {
xmlFromJar = (Boolean) ObjectUtils.getFirst(args);
}
getEjbLibs();
Set<String> appNames = appXmlParser();
extractEjbJars(appNames);
}
} |
package org.minimalj.frontend.swing;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import org.minimalj.application.Application;
import org.minimalj.frontend.page.ActionGroup;
import org.minimalj.frontend.page.Page;
import org.minimalj.frontend.page.Separator;
import org.minimalj.frontend.swing.component.EditablePanel;
import org.minimalj.frontend.swing.component.History;
import org.minimalj.frontend.swing.component.History.HistoryListener;
import org.minimalj.frontend.swing.component.SwingPageBar;
import org.minimalj.frontend.swing.toolkit.SwingClientToolkit;
public class SwingTab extends EditablePanel {
private static final long serialVersionUID = 1L;
final SwingFrame frame;
final Action previousAction, nextAction, refreshAction;
final Action closeTabAction;
private final SwingToolBar toolBar;
private final SwingMenuBar menuBar;
private final JSplitPane splitPane;
private final JScrollPane menuScrollPane;
private final JScrollPane contentScrollPane;
private final JPanel verticalPanel;
private final History<Page> history;
private final List<Page> pages;
private final SwingPageContextHistoryListener historyListener;
private Page page;
public SwingTab(SwingFrame frame) {
super();
this.frame = frame;
historyListener = new SwingPageContextHistoryListener();
history = new History<>(historyListener);
pages = new ArrayList<Page>();
previousAction = new PreviousPageAction();
nextAction = new NextPageAction();
refreshAction = new RefreshAction();
closeTabAction = new CloseTabAction();
JPanel outerPanel = new JPanel(new BorderLayout());
menuBar = new SwingMenuBar(this);
outerPanel.add(menuBar, BorderLayout.NORTH);
setContent(outerPanel);
JPanel panel = new JPanel(new BorderLayout());
outerPanel.add(panel, BorderLayout.CENTER);
toolBar = new SwingToolBar(this);
panel.add(toolBar, BorderLayout.NORTH);
splitPane = new JSplitPane();
splitPane.setBorder(BorderFactory.createEmptyBorder());
panel.add(splitPane, BorderLayout.CENTER);
verticalPanel = new JPanel(new VerticalLayoutManager());
contentScrollPane = new JScrollPane(verticalPanel);
contentScrollPane.getVerticalScrollBar().setUnitIncrement(20);
contentScrollPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setRightComponent(contentScrollPane);
contentScrollPane.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
verticalPanel.revalidate();
}
});
ActionTree actionTree = new ActionTree(Application.getApplication().getMenu(), Application.getApplication().getName());
menuScrollPane = new JScrollPane(actionTree);
menuScrollPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setLeftComponent(menuScrollPane);
splitPane.setDividerLocation(200);
}
public static SwingTab getActiveTab() {
Window w = SwingFrame.getActiveWindow();
if (w instanceof SwingFrame) {
return ((SwingFrame) w).getVisibleTab();
}
return null;
}
public Page getVisiblePage() {
return page;
}
void onHistoryChanged() {
updateActions();
toolBar.onHistoryChanged();
frame.onHistoryChanged();
}
protected void updateActions() {
if (getVisiblePage() != null) {
previousAction.setEnabled(hasPast());
nextAction.setEnabled(hasFuture());
} else {
previousAction.setEnabled(false);
nextAction.setEnabled(false);
}
}
protected class PreviousPageAction extends SwingResourceAction {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
previous();
}
}
protected class NextPageAction extends SwingResourceAction {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
next();
}
}
protected class RefreshAction extends SwingResourceAction {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
refresh();
}
}
public void refresh() {
replace(getVisiblePage());
}
private class CloseTabAction extends SwingResourceAction {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
frame.closeTab();
}
}
// PageContext
private class SwingPageContextHistoryListener implements HistoryListener {
@Override
public void onHistoryChanged() {
page = history.getPresent();
closeAllPages();
addPage(page);
SwingTab.this.onHistoryChanged();
}
}
private void addPage(Page page) {
pages.add(page);
verticalPanel.add(new SwingPageBar(page.getTitle()));
JComponent content = (JComponent) page.getContent();
if (content != null) {
JPopupMenu menu = createMenu(page.getMenu());
content.setComponentPopupMenu(menu);
setInheritMenu(content);
verticalPanel.add(content, "");
} else {
verticalPanel.add(new JPanel(), "");
}
verticalPanel.revalidate();
verticalPanel.repaint();
}
private void closeAllPages() {
verticalPanel.removeAll();
pages.clear();
}
public class VerticalLayoutManager implements LayoutManager {
private Dimension preferredSize = new Dimension(100, 100);
private Rectangle lastParentBounds = null;
public VerticalLayoutManager() {
}
@Override
public Dimension preferredLayoutSize(Container parent) {
if (preferredSize == null) {
layoutContainer(parent);
}
return preferredSize;
}
@Override
public Dimension minimumLayoutSize(Container parent) {
return new Dimension(100, 100);
}
@Override
public void layoutContainer(Container parent) {
if (lastParentBounds != null && lastParentBounds.equals(parent.getBounds())) return;
lastParentBounds = parent.getBounds();
int minSum = 0;
for (Component component : parent.getComponents()) {
minSum += component.getMinimumSize().height;
}
Set<Component> verticallyGrowingComponents = new HashSet<>();
for (Component component : parent.getComponents()) {
if (component.getPreferredSize().height > component.getMinimumSize().height) {
verticallyGrowingComponents.add(component);
}
}
// the last one always gets to grow
if (parent.getComponentCount() > 0) {
verticallyGrowingComponents.add(parent.getComponent(parent.getComponentCount() - 1));
}
int y = 0;
int x = 0;
int width = parent.getWidth();
int widthWithoutIns = width - x;
// int moreThanMin = parent.getHeight() - minSum;
int moreThanMin = contentScrollPane.getHeight() - minSum;
if (moreThanMin < 0) {
verticallyGrowingComponents.clear();
}
for (Component component : parent.getComponents()) {
int height = component.getMinimumSize().height;
if (verticallyGrowingComponents.contains(component)) {
height += moreThanMin / verticallyGrowingComponents.size();
}
component.setBounds(x, y, widthWithoutIns, height);
y += height;
}
preferredSize = new Dimension(100, y);
}
@Override
public void addLayoutComponent(String name, Component comp) {
lastParentBounds = null;
preferredSize = null;
}
@Override
public void removeLayoutComponent(Component comp) {
lastParentBounds = null;
preferredSize = null;
}
}
public void add(Page page) {
history.add(page);
}
public void replace(Page page) {
history.replace(page);
}
public Page getPresent() {
return history.getPresent();
}
public boolean hasFuture() {
return history.hasFuture();
}
public boolean hasPast() {
return history.hasPast();
}
public void next() {
history.next();
}
public void previous() {
history.previous();
}
public void show(Page page) {
show(page, true);
}
public void show(Page page, boolean asTopPage) {
if (!SwingUtilities.isEventDispatchThread()) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
show(page, asTopPage);
};
});
} catch (InterruptedException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} else {
if (asTopPage) {
history.add(page);
} else {
this.page = page;
addPage(page);
}
}
}
private JPopupMenu createMenu(ActionGroup actionGroup) {
if (actionGroup != null && actionGroup.getItems() != null) {
JPopupMenu menu = new JPopupMenu(actionGroup.getName());
addActions(menu, actionGroup.getItems());
return menu;
}
return null;
}
public static void addActions(JPopupMenu menu, List<org.minimalj.frontend.toolkit.Action> actions) {
for (org.minimalj.frontend.toolkit.Action action : actions) {
if (action instanceof org.minimalj.frontend.page.ActionGroup) {
org.minimalj.frontend.page.ActionGroup actionGroup = (org.minimalj.frontend.page.ActionGroup) action;
JMenu subMenu = new JMenu(SwingClientToolkit.adaptAction(action));
SwingMenuBar.addActions(subMenu, actionGroup.getItems());
menu.add(subMenu);
} else if (action instanceof Separator) {
menu.addSeparator();
} else {
menu.add(new JMenuItem(SwingClientToolkit.adaptAction(action)));
}
}
}
private void setInheritMenu(JComponent component) {
component.setInheritsPopupMenu(true);
for (Component c : component.getComponents()) {
if (c instanceof JComponent) {
setInheritMenu((JComponent) c);
}
}
}
public boolean tryToClose() {
return tryToCloseDialogs();
}
} |
package org.petapico.nanopub.indexer;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.nanopub.MultiNanopubRdfHandler;
import org.nanopub.Nanopub;
import org.nanopub.NanopubUtils;
import org.nanopub.MultiNanopubRdfHandler.NanopubHandler;
import org.nanopub.extra.server.GetNanopub;
import org.nanopub.extra.server.NanopubServerUtils;
import org.nanopub.extra.server.ServerInfo;
import org.nanopub.extra.server.ServerIterator;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
public class Indexer {
public static final int SECTION_HEAD = 1;
public static final int SECTION_ASSERTION = 2;
public static final int SECTION_PROVENANCE = 3;
public static final int SECTION_PUBINFO = 4;
NanopubDatabase db = null;
int URItoobig;
boolean printlog;
public static List<Nanopub> nanopubs; //used by the callback function of the MultiNanopubRdfHandler class -> can we do this better?
public static void main(String[] args) throws IOException, RDFHandlerException, Exception {
//args = new String[2];
//args[0] = "root";
//args[1] = "admin";
boolean printlog = false;
if (args.length < 2){
System.out.printf("Invalid arguments expected: dbusername, dbpassword\n");
System.exit(1);
}
if (args.length == 3){
printlog = true;
}
Indexer indexer = new Indexer(args[0], args[1], printlog);
indexer.run();
}
public Indexer(String dbusername, String dbpassword, boolean printlog) throws ClassNotFoundException, SQLException {
db = new NanopubDatabase(dbusername, dbpassword);
URItoobig = 0;
this.printlog = printlog;
}
public void run() throws IOException, RDFHandlerException, Exception {
ServerIterator serverIterator = new ServerIterator();
while (serverIterator.hasNext()) {
ServerInfo si = serverIterator.next();
String serverName = si.getPublicUrl();
System.out.println("==========");
System.out.println("Server: " + serverName + "\n");
//retrieve server information
int peerPageSize = si.getPageSize(); //nanopubs per page
long peerNanopubNo = si.getNextNanopubNo(); //number of np's stored on the server
long peerJid = si.getJournalId(); //journal identifier of the server
System.out.printf("Info:\n %d peerpagesize\n %d peernanopubno\n %d peerjid\n\n", peerPageSize, peerNanopubNo, peerJid);
//retrieve stored server information
long dbNanopubNo = db.getNextNanopubNo(serverName); //number of np's stored according to db
long dbJid = db.getJournalId(serverName); //journal identifier according to db
System.out.printf("Db:\n %d dbnanopubno\n %d dbjid\n", dbNanopubNo, dbJid);
System.out.println("==========\n");
if (dbJid != peerJid){
dbNanopubNo = 0;
}
long currentNanopub = dbNanopubNo;
System.out.printf("Starting from: %d\n", currentNanopub);
try {
while (currentNanopub < peerNanopubNo){
int page = (int) (currentNanopub / peerPageSize) + 1;
int addedNanopubs = insertNanopubsFromPage(page, serverName);
if (addedNanopubs < peerPageSize) {System.out.printf("weird break\n"); break;} //something must have gone wrong
currentNanopub += addedNanopubs;
db.updateJournalId(serverName, peerJid);
db.updateNextNanopubNo(serverName, currentNanopub);
System.out.printf("URI to big on page %d: %d\n", page, URItoobig);
}
}
finally {
/*
db.updateJournalId(serverName, peerJid);
db.updateNextNanopubNo(serverName, currentNanopub);
*/
}
}
}
public int insertNanopubsFromPage(int page, String server) throws Exception{
int coveredNanopubs = 0;
getNanopubPackage(page, server); //fills the nanopub list
if (nanopubs.size() == 0) {return -1;} //this is no good..
for (Nanopub np : nanopubs) {
String artifactCode = np.getUri().toString();
log("inserting: " + artifactCode);
//if (!db.npInserted(artifactCode)){
insertNpInDatabase(np, artifactCode);
//else {
//System.out.printf("skip: %s\n", artifactCode);
coveredNanopubs ++;
}
return coveredNanopubs;
}
public int insertNpInDatabase(Nanopub np, String artifactCode) throws IOException, SQLException{
db.insertNp(artifactCode);
int totalURIs = 0;
//totalURIs += insertStatementsInDB(np.getHead(), artifactCode, stmt, SECTION_HEAD);
totalURIs += insertStatementsInDB(np.getAssertion(), artifactCode, SECTION_ASSERTION);
log("done assertion");
totalURIs += insertStatementsInDB(np.getProvenance(), artifactCode, SECTION_PROVENANCE);
log("done provenance");
totalURIs += insertStatementsInDB(np.getPubinfo(), artifactCode, SECTION_PUBINFO);
log("done pubinfo");
return totalURIs;
}
public int insertStatementsInDB(Set<Statement> statements, String artifactCode, int sectionID) throws IOException, SQLException{
Set<String> URIlist = new HashSet<String>();
for (Statement statement : statements){
Value object = statement.getObject();
URI predicate = statement.getPredicate();
Resource subject = statement.getSubject();
String objectStr = object.stringValue();
String predicateStr = predicate.toString();
String subjectStr = subject.stringValue();
URIlist.add(objectStr);
URIlist.add(predicateStr);
URIlist.add(subjectStr);
}
db.setArtifactCodeInsertPs(artifactCode);
db.setSectionInsertPs(sectionID);
//insert URIlist in database
for (String uri : URIlist){
if (uri.length() < 760){
db.setUriInsertPs(uri);
db.runInsertPs();
}
else {
URItoobig++;
}
}
return URIlist.size();
}
public void getNanopubPackage(int page, String server) throws Exception{
nanopubs = new ArrayList<Nanopub>();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build();
HttpClient c = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
String nanopubPackage = server + "package.gz?page=" + page;
HttpGet get = new HttpGet(nanopubPackage);
get.setHeader("Accept", "application/x-gzip");
HttpResponse resp = c.execute(get);
InputStream in = null;
try {
if (wasSuccessful(resp)) {
in = new GZIPInputStream(resp.getEntity().getContent());
} else {
System.out.println("Failed. Trying uncompressed package...");
// This is for compability with older versions; to be removed at some point...
get = new HttpGet(server + "package.gz?page=" + page);
get.setHeader("Accept", "application/trig");
resp = c.execute(get);
if (!wasSuccessful(resp)) {
System.out.println("HTTP request failed: " + resp.getStatusLine().getReasonPhrase());
throw new RuntimeException(resp.getStatusLine().getReasonPhrase());
}
in = resp.getEntity().getContent();
}
MultiNanopubRdfHandler.process(RDFFormat.TRIG, in, new NanopubHandler() {
@Override
public void handleNanopub(Nanopub np) {
try {
Indexer.nanopubs.add(np);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
});
} finally {
if (in != null){
//System.out.println(in.toString());
in.close();
}
}
}
public void log(String msg){
if (printlog){
System.out.printf("%s\n", msg);
}
}
private boolean wasSuccessful(HttpResponse resp) {
int c = resp.getStatusLine().getStatusCode();
return c >= 200 && c < 300;
}
} |
/**
Khalid
*/
package org.sikuli.slides.sikuli;
import static org.sikuli.api.API.browse;
import java.awt.Color;
import java.awt.Dimension;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import org.sikuli.api.DesktopScreenRegion;
import org.sikuli.api.ImageTarget;
import org.sikuli.api.ScreenRegion;
import org.sikuli.api.robot.Keyboard;
import org.sikuli.api.robot.Mouse;
import org.sikuli.api.robot.desktop.DesktopKeyboard;
import org.sikuli.api.robot.desktop.DesktopMouse;
import org.sikuli.api.visual.Canvas;
import org.sikuli.api.visual.ScreenRegionCanvas;
import org.sikuli.slides.core.SlideComponent;
import org.sikuli.slides.media.Sound;
import org.sikuli.slides.screenshots.SlideTargetRegion;
import org.sikuli.slides.shapes.SlideShape;
import org.sikuli.slides.utils.Constants;
import org.sikuli.slides.utils.Constants.DesktopEvent;
import org.sikuli.slides.utils.MyScreen;
import org.sikuli.slides.utils.UnitConverter;
import org.sikuli.slides.utils.UserPreferencesEditor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Slide action that performs input events operation specified in each slide.
* @author Khalid
*
*/
public class SlideAction {
private static final Logger logger = (Logger) LoggerFactory.getLogger(SlideAction.class);
private UserPreferencesEditor prefsEditor = new UserPreferencesEditor();
private File targetFile, labelFile;
private SlideShape slideShape;
private SlideTargetRegion slideTargetRegion, slideLabelRegion;
private Sound sound;
private SlideShape slideLabel;
public SlideAction(SlideComponent slideComponent){
this.targetFile = slideComponent.getTargetFile();
this.slideShape = slideComponent.getSlideShape();
this.slideTargetRegion = slideComponent.getSlideTargetRegion();
this.sound = slideComponent.getSound();
this.slideLabel = slideComponent.getSlideLabel();
this.labelFile = slideComponent.getLabelFile();
this.slideLabelRegion = slideComponent.getSlideLabelRegion();
}
public void doSlideAction(DesktopEvent desktopEvent){
// if the required action is one of the following actions, no need to search for target on the screen
// #1 Wait action
if(desktopEvent==DesktopEvent.WAIT){
performNonSikuliAction();
performSikuliAction(null, desktopEvent);
}
// #2 Open default browser
else if(desktopEvent==DesktopEvent.LAUNCH_BROWSER){
performNonSikuliAction();
performSikuliAction(null, desktopEvent);
}
else if(desktopEvent == null && slideLabel !=null){
performNonSikuliAction();
return;
}
// if the action is to find a target on the screen
// if the action is to interact with a target, find the target and perform the action
else{
ScreenRegion targetRegion=findTargetRegion(this.targetFile, this.slideTargetRegion);
performNonSikuliAction();
if(desktopEvent==DesktopEvent.EXIST){
logger.info("Checking whether the target image is visible on the screen.");
if(targetRegion==null){
logger.error("Test failed. Target image was not found on the screen.");
System.exit(1);
}
else{
logger.info("Test passed. Target image was found on the screen.");
return;
}
}
else if(desktopEvent==DesktopEvent.NOT_EXIST){
logger.info("Checking whether the target image is invisible on the screen.");
if(targetRegion==null){
logger.info("Test passed. Target image was invisible on the screen.");
return;
}
else{
logger.error("Test failed. Target image was visible on the screen.");
System.exit(1);
}
}
else{
/*if(targetRegion==null){
if(Constants.TUTORIAL_MODE){
logger.error("Couldn't find target on the screen.");
}
}*/
if(Constants.HELP_MODE){
new SlideTutorial(targetRegion, slideShape, desktopEvent).performTutorialSlideAction();
}
else if(Constants.TUTORIAL_MODE){
new SlideTutorial(targetRegion, slideShape, desktopEvent).performTutorialSlideAction();
}
else{
performSikuliAction(targetRegion, desktopEvent);
}
}
}
}
private ScreenRegion findTargetRegion(File targetFile, SlideTargetRegion slideTargetRegion){
final ImageTarget imageTarget=new ImageTarget(targetFile);
imageTarget.setMinScore(prefsEditor.getPreciseSearchScore());
if(imageTarget!=null){
ScreenRegion fullScreenRegion = new DesktopScreenRegion(Constants.ScreenId);
ScreenRegion targetRegion=fullScreenRegion.wait(imageTarget, prefsEditor.getMaxWaitTime());
if(targetRegion!=null){
// check if there are more than one occurrence of the target image.
SearchMultipleTarget searchMultipleTarget=new SearchMultipleTarget();
if(searchMultipleTarget.hasMultipleOccurance(imageTarget)){
ScreenRegion newScreenRegion=searchMultipleTarget.findNewScreenRegion(slideTargetRegion, imageTarget);
if(newScreenRegion!=null){
ScreenRegion newtargetRegion=newScreenRegion.find(imageTarget);
return newtargetRegion;
}
else{
logger.error("Failed to determine the target image among multiple similar targets on the screen."
+"\nTry to resize the shape in slide number "+slideTargetRegion.getslideNumber() + " or use the precision option to make the search more accurate.");
}
}
else{
return targetRegion;
}
}
else{
logger.error("Failed to find target on the screen. Slide no. "+slideTargetRegion.getslideNumber());
}
}
return null;
}
/**
* Performs non sikuli actions such as playing background sound and displaying annotations
* @param targetRegion
*/
private void performNonSikuliAction(){
// if the slide contains a sound, play it in background
if(sound!=null){
new Thread(new Runnable() {
@Override
public void run() {
sound.playSound();
}
}).start();
}
if(slideLabel!=null){
ScreenRegion labelScreenRegion = null;
if(this.labelFile !=null && this.slideLabelRegion != null){
labelScreenRegion = findTargetRegion(this.labelFile, this.slideLabelRegion);
}
displayLabel(labelScreenRegion);
}
}
private void performSikuliAction(ScreenRegion targetRegion,Constants.DesktopEvent desktopEvent){
if(desktopEvent==Constants.DesktopEvent.LEFT_CLICK){
performLeftClick(targetRegion);
}
else if(desktopEvent==Constants.DesktopEvent.RIGHT_CLICK){
performRightClick(targetRegion);
}
else if(desktopEvent==Constants.DesktopEvent.DOUBLE_CLICK){
performDoubleClick(targetRegion);
}
else if(desktopEvent==Constants.DesktopEvent.DRAG_N_DROP){
performDragDrop(targetRegion);
}
else if(desktopEvent==Constants.DesktopEvent.KEYBOARD_TYPING){
performKeyboardTyping(targetRegion);
}
else if(desktopEvent==Constants.DesktopEvent.LAUNCH_BROWSER){
performLaunchWebBrowser();
}
else if(desktopEvent==Constants.DesktopEvent.WAIT){
performWaitAction();
}
}
/**
* display a label on a target region
* @param targetRegion the target region to display the label on
*/
private void displayLabel(ScreenRegion targetRegion) {
/* if the target region is null or ther's no target to work on, use the default desktop region.
This is important in case of opening the default browser or label target region could not be found.
*/
if(targetRegion==null){
logger.error("Failed to find the target to display a label on.");
logger.info("Displaying the label on the center of the screen.");
Dimension dimension = MyScreen.getScreenDimensions();
int width = UnitConverter.emuToPixels(slideLabel.getCx());
int height = UnitConverter.emuToPixels(slideLabel.getCy());
int x = (dimension.width-width)/2;
int y = (dimension.height-height)/2;
targetRegion = new DesktopScreenRegion(Constants.ScreenId, x, y, width, height);
}
double fontSize=UnitConverter.WholePointsToPoints(slideLabel.getTextSize());
if(fontSize==0){
fontSize=prefsEditor.getInstructionHintFontSize();
}
Canvas canvas = new ScreenRegionCanvas(new DesktopScreenRegion(Constants.ScreenId));
canvas.addLabel(targetRegion, slideLabel.getText()).
withColor(Color.black).withFontSize((int)fontSize).withLineWidth(prefsEditor.getCanvasWidthSize());
canvas.display(prefsEditor.getLabelDisplayTime());
}
/**
* perform left click
* @param targetRegion the region to perform left click input event on.
*/
private void performLeftClick(ScreenRegion targetRegion){
logger.info("performing left click event on target...");
Mouse mouse = new DesktopMouse();
displayBoxOnRegion(targetRegion);
mouse.click(targetRegion.getCenter());
}
/**
* perform right click
* @param targetRegion the region to perform right click input event on.
*/
private void performRightClick(ScreenRegion targetRegion){
logger.info("performing right click event on target...");
Mouse mouse = new DesktopMouse();
displayBoxOnRegion(targetRegion);
mouse.rightClick(targetRegion.getCenter());
}
/**
* perform double click
* @param targetRegion the region to perform double click input event on.
*/
private void performDoubleClick(ScreenRegion targetRegion){
logger.info("performing double click event on target...");
Mouse mouse = new DesktopMouse();
displayBoxOnRegion(targetRegion);
mouse.doubleClick(targetRegion.getCenter());
}
/**
* perform drag and drop
* @param targetRegion the region to perform drag or drop input event on.
*/
private void performDragDrop(ScreenRegion targetRegion){
logger.info("performing drag and drop event on targets...");
Mouse mouse = new DesktopMouse();
if(slideShape.getOrder()==0){
displayBoxOnRegion(targetRegion);
mouse.drag(targetRegion.getCenter());
}
else if(slideShape.getOrder()==1){
displayBoxOnRegion(targetRegion);
mouse.drop(targetRegion.getCenter());
}
else{
logger.error("Couldn't find the start and end of the straight arrow connector " +
"that is used to connect the rounded rectangles. Make sure the arrow is connected to the two rounded rectangles.");
}
}
/**
* perform keyboard typing
* @param targetRegion the region to perform keyboard typing input event on.
*/
private void performKeyboardTyping(ScreenRegion targetRegion){
logger.info("performing keyboard typing event on target...");
Mouse mouse = new DesktopMouse();
Keyboard keyboard=new DesktopKeyboard();
displayBoxOnRegion(targetRegion);
mouse.click(targetRegion.getCenter());
keyboard.type(slideShape.getText());
}
/**
* launch the default browser
*/
private void performLaunchWebBrowser(){
logger.info("launching the default browser...");
try {
String userURL=slideShape.getText();
URL url=null;
if(userURL.startsWith("http:
url=new URL(userURL);
}
else{
url=new URL("http://"+userURL);
}
browse(url);
} catch (MalformedURLException e) {
logger.error("The text body of the Cloud shape doesn't contain a valid URL.");
System.exit(1);
}
}
/**
* Perform wait action. It waits for the specified time in seconds
*/
private void performWaitAction(){
logger.info("Performing wait operation...");
// extract the time unit
TimeUnit timeUnit=UnitConverter.extractTimeUnitFromString(slideShape.getText());
// if the time unit was not specified, default to seconds
if(timeUnit==null){
timeUnit=TimeUnit.SECONDS;
}
// extract the wait time string value, replace all non digits with blank
String waitTimeString=slideShape.getText().replaceAll("\\D", "");
if(waitTimeString==null){
logger.error("Error: Please enter the wait time value in a shape."
+" Valid examples include: 10 seconds, 10 minutes, 10 hours, or even 2 days.");
return;
}
try {
long timeout=Long.parseLong(waitTimeString);
if(Constants.TUTORIAL_MODE){
// Disable controllers UI buttons to prevent tutorial mode from navigating through steps.
Constants.IsWaitAction=true;
}
// display a label
Dimension dimension=MyScreen.getScreenDimensions();
ScreenRegion canvasRegion=new DesktopScreenRegion(Constants.ScreenId, 0, dimension.height-200,50,200);
Canvas canvas=new ScreenRegionCanvas(new DesktopScreenRegion(Constants.ScreenId));
String readyTime=getReadyDate(timeUnit, timeout);
String waitMessage="Please wait for "+timeout+" "+timeUnit.toString().toLowerCase()+"...."+
"This might end at "+readyTime;
logger.info(waitMessage);
canvas.addLabel(canvasRegion, waitMessage).withFontSize(prefsEditor.getInstructionHintFontSize());
canvas.show();
timeUnit.sleep(timeout);
Constants.IsWaitAction=false;
canvas.hide();
logger.info("Waking up...");
}
catch(NumberFormatException e){
logger.error("Error: Invalid wait time.");
}
catch (InterruptedException e) {
logger.error("Error in wait operation");
}
}
private String getReadyDate(TimeUnit timeUnit,long timeout) {
if(timeUnit != null){
// set timeout format
String dateFormat="HH:mm:ss";
if(timeUnit == TimeUnit.DAYS){
dateFormat="yyyy-MM-dd HH:mm:ss";
}
// get the end time in milli seconds
long waitTimeInMilliSeconds=timeUnit.toMillis(timeout);
logger.info("Wait time in milli seconds: "+waitTimeInMilliSeconds);
Calendar nowCalendar=Calendar.getInstance();
Calendar timeoutCalendar = Calendar.getInstance();
timeoutCalendar.setTimeInMillis(waitTimeInMilliSeconds+nowCalendar.getTimeInMillis());
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
return sdf.format(timeoutCalendar.getTime()).toString();
}
return null;
}
private void displayBoxOnRegion(ScreenRegion screenRegion){
if(screenRegion != null){
Canvas canvas=new ScreenRegionCanvas(screenRegion);
// Display the canvas around the target
canvas.addBox(screenRegion);
canvas.display(2);
}
}
} |
package org.sports.gate.model;
import gate.Annotation;
import gate.AnnotationSet;
import gate.Document;
import gate.util.InvalidOffsetException;
import java.util.ArrayList;
import java.util.List;
public class DocumentQuotes {
private List<PersonQuotes> personQuotes;
private Document doc;
private PersonQuotes getByPerson(String person) {
PersonQuotes result = null;
if (person != "") {
for (PersonQuotes quotes : this.personQuotes) {
String quotesPerson = quotes.getPerson().toLowerCase();
String lowerPerson = person.toLowerCase();
// If it's entity. Example Person John Smith equals "said Smith"
if (quotesPerson.contains(lowerPerson)) {
result = quotes;
break;
}
}
if (result == null) {
result = new PersonQuotes();
result.setPerson(person);
this.personQuotes.add(result);
}
}
return result;
}
private void addPersonQuote(String person, String quote) {
PersonQuotes personQuotes = this.getByPerson(person);
if (personQuotes != null) {
personQuotes.addQuote(quote);
}
}
private String extractQuote(AnnotationSet quotedText, Annotation personSay)
throws InvalidOffsetException {
AnnotationSet quote = quotedText.getContained(personSay.getStartNode()
.getOffset(), personSay.getEndNode().getOffset());
return doc
.getContent()
.getContent(quote.firstNode().getOffset(),
quote.lastNode().getOffset()).toString();
}
private String extractPerson(AnnotationSet quotes, Annotation personSay)
throws InvalidOffsetException {
String personString = "";
AnnotationSet containedQuotes = quotes
.getContained(personSay.getStartNode().getOffset(), personSay
.getEndNode().getOffset());
AnnotationSet persons = doc.getAnnotations().get("Person");
AnnotationSet person = persons.getContained(containedQuotes.firstNode()
.getOffset(), containedQuotes.lastNode().getOffset());
if (person.size() == 0) {
AnnotationSet entities = doc.getAnnotations().get("EntityAnnotation");
person = entities.getContained(containedQuotes.firstNode()
.getOffset(), containedQuotes.lastNode().getOffset());
}
if (person.size() > 0) {
personString = doc
.getContent()
.getContent(person.firstNode().getOffset(),
person.lastNode().getOffset()).toString();
}
return personString;
}
public List<PersonQuotes> getPersonQuotes() {
return personQuotes;
}
public void setPersonQuotes(List<PersonQuotes> personQuotes) {
this.personQuotes = personQuotes;
}
public DocumentQuotes(Document doc) {
this.doc = doc;
this.personQuotes = new ArrayList<PersonQuotes>();
}
public void extractQuotes() throws InvalidOffsetException {
AnnotationSet personSays = doc.getAnnotations().get("PersonSays");
AnnotationSet quotedText = doc.getAnnotations().get("QuotedText");
AnnotationSet quotes = doc.getAnnotations().get("Quote");
for (Annotation personSay : personSays) {
String quote = this.extractQuote(quotedText, personSay);
String person = this.extractPerson(quotes, personSay);
this.addPersonQuote(person, quote);
}
}
} |
package edu.ptu.javatest;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.junit.After;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.HashMap;
import static com.alibaba.fastjson.JSON.DEFAULT_GENERATE_FEATURE;
import static org.junit.runners.MethodSorters.NAME_ASCENDING;
@FixMethodOrder(value = MethodSorters.NAME_ASCENDING)
public class IoPerfomanceTest {
@Test
public void test001WriteObj() throws IOException {//str 64ms //json 167ms
ArrayList<String> strings = initObject();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./object"));
oos.writeObject(strings);
oos.close();
}
@Test
public void test002ReadObj() throws IOException, ClassNotFoundException {//str 160ms //json 518ms
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./object"));
Object o = ois.readObject();
ois.close();
}
@Test
public void test003PrintWriterString() throws FileNotFoundException {//str 30ms
ArrayList<String> strings = initObject();
PrintWriter oos = new PrintWriter(new OutputStreamWriter(new FileOutputStream("./object")));
for (int i = 0; i < strings.size(); i++) {
oos.println(strings.get(i));
}
oos.close();
}
@Test
public void test004ReadBufferedString() throws Exception {//str 14ms
ArrayList<String> newStr = new ArrayList<>();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("./object")));
String str = null;
while ((str = br.readLine()) != null) {
newStr.add(str);
}
br.close();
}
//200json toJson
ArrayList<Article> articles = initArticleList();
@Test
public void test011WriteSerializable() throws IOException {//1000 json 167ms, 15 json 11ms
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./object"));
oos.writeObject(articles);
oos.close();
}
@Test
public void test012ReadSerializable() throws IOException, ClassNotFoundException {//1000json 518ms ,15 json 18ms
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./object"));
Object o = ois.readObject();
ois.close();
}
@Test
public void test013WriteGsonJson() throws Exception {//1000json 277ms,15 json 211ms
String string = new Gson().toJson(articles, ArrayList.class);
BufferedWriter oos = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("./object")));
oos.write(string);
oos.close();
}
@Test
public void test014ReadGsonJson() throws Exception {//1000json 171ms,15 json 9ms
ArrayList<Article> articles = initArticleList();
BufferedReader oos = new BufferedReader(new InputStreamReader(new FileInputStream("./object")));
ArrayList string = new Gson().fromJson(oos, ArrayList.class);
oos.close();
}
@Test
public void test015WriteFastJson() throws Exception {//1000json 277ms,15 json 211ms
String string = JSON.toJSONString(articles);
BufferedWriter oos = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("./object")));
oos.write(string);
oos.close();
}
@Test
public void test016ReadFastJson() throws Exception {//1000json 171ms,15 json 9ms
ArrayList<Article> articles = initArticleList();
BufferedReader oos = new BufferedReader(new InputStreamReader(new FileInputStream("./object")));
ArrayList string = JSON.parseObject(new FileInputStream("./object"),ArrayList.class);
oos.close();
}
public ArrayList<String> initObject() {
ArrayList<String> objects = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
objects.add("string: " + i);
}
return objects;
}
public ArrayList<Article> initArticleList() {
ArrayList<Article> objects = new ArrayList<>();
for (int i = 0; i < 100; i++) {
objects.add(new Article());
}
return objects;
}
//Article{recoid='4195442930308615977', id='14441935368216035340', title=', , 1100!',
// sourceName='17173', originSourceName='17173', summary='', tags=[], category=[], content='', contentLength=0, thumbnails=[
// bottomleftmark=BottomLeftMark [mark=, markColor=0, markIconUrl=],
// images=[], commentCnt=80, videos=[], shareUrl='', cmtUrl='', showImpressionUrl='', likeCnt=27, supportCnt=0, opposeCnt=0,
// adContent={industry1=, ad_type=, scheme=, action_type=, industry2=, dmp_id=, search_id=, ad_id=, ad_source=, industry1_description=, industry2_description=, ad_source_description=, ad_is_effect=},
// ad_content_click_ad_url_array=null, ad_content_show_ad_url_array=null, fl_article_content_click_url_array=null, BottomLeftMark={}, openType=0
//NotSerializableException
public static class Article implements Serializable {
private static final long serialVersionUID = 1l;
private String recoid;
private String id;
private String title;
private int itemType;
private int styleType;
private int grabTime;
private long publishTime;
private String url;
private String sourceName;
private String originSourceName;
private String summary;
private ArrayList<String> tags;
private ArrayList<String> category;
private String content;
private int contentLength;
private ArrayList<Thumbnail> thumbnails;
private HashMap<String, BottomLeftMark> bottomleftmarkMap;
private ArrayList<Thumbnail> images;
private int commentCnt;
private ArrayList<String> videos;
private String shareUrl;
private String cmtUrl;
private String showImpressionUrl;
private int likeCnt;
private int supportCnt;
private int opposeCnt;
private HashMap<String, Thumbnail> adContent;
private String ad_content_click_ad_url_array;
private String ad_content_show_ad_url_array;
private String fl_article_content_click_url_array;
private BottomLeftMark bottomLeftMark;
private int openType;
}
public static class Thumbnail {
private String url;
private int width;
private int height;
private int type;
}
public static class BottomLeftMark {
private String mark;
private int markColor;
private String markIconUrl;
}
} |
package joshua.zmert;
import java.util.*;
import java.util.logging.Logger;
public class BLEU extends EvaluationMetric
{
private static final Logger logger = Logger.getLogger(BLEU.class.getName());
protected int maxGramLength;
protected EffectiveLengthMethod effLengthMethod;
// 1: closest, 2: shortest, 3: average
// protected HashMap[][] maxNgramCounts;
protected HashMap<String,Integer>[] maxNgramCounts;
protected int[][] refWordCount;
protected double[] weights;
public BLEU()
{
this(4,"closest");
}
public BLEU(String[] BLEU_options)
{
this(Integer.parseInt(BLEU_options[0]),BLEU_options[1]);
}
public BLEU(int mxGrmLn,String methodStr)
{
if (mxGrmLn >= 1) {
maxGramLength = mxGrmLn;
} else {
logger.severe("Maximum gram length must be positive");
System.exit(2);
}
if (methodStr.equals("closest")) {
effLengthMethod = EffectiveLengthMethod.CLOSEST;
} else if (methodStr.equals("shortest")) {
effLengthMethod = EffectiveLengthMethod.SHORTEST;
// } else if (methodStr.equals("average")) {
// effLengthMethod = EffectiveLengthMethod.AVERAGE;
} else {
logger.severe("Unknown effective length method string " + methodStr + ".");
// System.out.println("Should be one of closest, shortest, or average.");
logger.severe("Should be one of closest or shortest.");
System.exit(1);
}
initialize();
}
protected void initialize()
{
metricName = "BLEU";
toBeMinimized = false;
suffStatsCount = 2*maxGramLength + 2;
// 2 per gram length for its precision, and 2 for length info
set_weightsArray();
set_maxNgramCounts();
}
public double bestPossibleScore() { return 1.0; }
public double worstPossibleScore() { return 0.0; }
protected void set_weightsArray()
{
weights = new double[1+maxGramLength];
for (int n = 1; n <= maxGramLength; ++n) {
weights[n] = 1.0/maxGramLength;
}
}
@SuppressWarnings("unchecked")
protected void set_maxNgramCounts()
{
maxNgramCounts = new HashMap[numSentences];
String gram = "";
int oldCount = 0, nextCount = 0;
for (int i = 0; i < numSentences; ++i) {
maxNgramCounts[i] = getNgramCountsAll(refSentences[i][0]);
// initialize to ngramCounts[n] of the first reference translation...
// ...and update as necessary from the other reference translations
for (int r = 1; r < refsPerSen; ++r) {
HashMap<String,Integer> nextNgramCounts = getNgramCountsAll(refSentences[i][r]);
Iterator<String> it = (nextNgramCounts.keySet()).iterator();
while (it.hasNext()) {
gram = it.next();
nextCount = nextNgramCounts.get(gram);
if (maxNgramCounts[i].containsKey(gram)) { // update if necessary
oldCount = maxNgramCounts[i].get(gram);
if (nextCount > oldCount) {
maxNgramCounts[i].put(gram,nextCount);
}
} else { // add it
maxNgramCounts[i].put(gram,nextCount);
}
}
} // for (r)
} // for (i)
// For efficiency, calculate the reference lenghts, which will be used in effLength...
refWordCount = new int[numSentences][refsPerSen];
for (int i = 0; i < numSentences; ++i) {
for (int r = 0; r < refsPerSen; ++r) {
refWordCount[i][r] = wordCount(refSentences[i][r]);
}
}
}
public int[] suffStats(String cand_str, int i)
{
int[] stats = new int[suffStatsCount];
//int wordCount = words.length;
//for (int j = 0; j < wordCount; ++j) { words[j] = words[j].intern(); }
if (!cand_str.equals("")) {
String[] words = cand_str.split("\\s+");
set_prec_suffStats(stats,words,i);
stats[suffStatsCount-2] = words.length;
stats[suffStatsCount-1] = effLength(words.length,i);
} else {
String[] words = new String[0];
set_prec_suffStats(stats,words,i);
stats[suffStatsCount-2] = 0;
stats[suffStatsCount-1] = effLength(0,i);
}
return stats;
}
public void set_prec_suffStats(int[] stats, String[] words, int i)
{
HashMap<String,Integer>[] candCountsArray = getNgramCountsArray(words);
for (int n = 1; n <= maxGramLength; ++n) {
int correctGramCount = 0;
String gram = "";
int candGramCount = 0, maxRefGramCount = 0, clippedCount = 0;
Iterator<String> it = (candCountsArray[n].keySet()).iterator();
while (it.hasNext()) {
// for each n-gram type in the candidate
gram = it.next();
candGramCount = candCountsArray[n].get(gram);
// if (maxNgramCounts[i][n].containsKey(gram)) {
// maxRefGramCount = maxNgramCounts[i][n].get(gram);
if (maxNgramCounts[i].containsKey(gram)) {
maxRefGramCount = maxNgramCounts[i].get(gram);
} else {
maxRefGramCount = 0;
}
clippedCount = Math.min(candGramCount,maxRefGramCount);
correctGramCount += clippedCount;
}
stats[2*(n-1)] = correctGramCount;
stats[2*(n-1)+1] = Math.max(words.length-(n-1),0); // total gram count
} // for (n)
}
public int effLength(int candLength, int i)
{
if (effLengthMethod == EffectiveLengthMethod.CLOSEST) { // closest
int closestRefLength = refWordCount[i][0];
int minDiff = Math.abs(candLength-closestRefLength);
for (int r = 1; r < refsPerSen; ++r) {
int nextRefLength = refWordCount[i][r];
int nextDiff = Math.abs(candLength-nextRefLength);
if (nextDiff < minDiff) {
closestRefLength = nextRefLength;
minDiff = nextDiff;
} else if (nextDiff == minDiff && nextRefLength < closestRefLength) {
closestRefLength = nextRefLength;
minDiff = nextDiff;
}
}
return closestRefLength;
} else if (effLengthMethod == EffectiveLengthMethod.SHORTEST) { // shortest
int shortestRefLength = refWordCount[i][0];
for (int r = 1; r < refsPerSen; ++r) {
int nextRefLength = refWordCount[i][r];
if (nextRefLength < shortestRefLength) {
shortestRefLength = nextRefLength;
}
}
return shortestRefLength;
}
/* // commented out because it needs sufficient statistics to be doubles
else { // average
int totalRefLength = refWordCount[i][0];
for (int r = 1; r < refsPerSen; ++r) {
totalRefLength += refWordCount[i][r];
}
return totalRefLength/(double)refsPerSen;
}
*/
return candLength; // should never get here anyway
}
public double score(int[] stats)
{
if (stats.length != suffStatsCount) {
logger.severe("Mismatch between stats.length and suffStatsCount (" + stats.length + " vs. " + suffStatsCount + ")");
System.exit(2);
}
double BLEUsum = 0.0;
double smooth_addition = 1.0; // following bleu-1.04.pl
double c_len = stats[suffStatsCount-2];
double r_len = stats[suffStatsCount-1];
double correctGramCount, totalGramCount;
for (int n = 1; n <= maxGramLength; ++n) {
correctGramCount = stats[2*(n-1)];
totalGramCount = stats[2*(n-1)+1];
double prec_n;
if (totalGramCount > 0) {
prec_n = correctGramCount/totalGramCount;
} else {
prec_n = 1; // following bleu-1.04.pl ???????
}
if (prec_n == 0) {
smooth_addition *= 0.5;
prec_n = smooth_addition / (c_len-n+1);
// isn't c_len-n+1 just totalGramCount ???????
}
BLEUsum += weights[n] * Math.log(prec_n);
}
double BP = 1.0;
if (c_len < r_len) BP = Math.exp(1-(r_len/c_len));
// if c_len > r_len, no penalty applies
return BP*Math.exp(BLEUsum);
}
public void printDetailedScore_fromStats(int[] stats, boolean oneLiner)
{
double BLEUsum = 0.0;
double smooth_addition = 1.0; // following bleu-1.04.pl
double c_len = stats[suffStatsCount-2];
double r_len = stats[suffStatsCount-1];
double correctGramCount, totalGramCount;
if (oneLiner) {
System.out.print("Precisions: ");
}
for (int n = 1; n <= maxGramLength; ++n) {
correctGramCount = stats[2*(n-1)];
totalGramCount = stats[2*(n-1)+1];
double prec_n;
if (totalGramCount > 0) {
prec_n = correctGramCount/totalGramCount;
} else {
prec_n = 1; // following bleu-1.04.pl ???????
}
if (prec_n > 0) {
if (totalGramCount > 0) {
if (oneLiner) {
System.out.print(n + "=" + f4.format(prec_n) + ", ");
} else {
System.out.println("BLEU_precision(" + n + ") = " + (int)correctGramCount + " / " + (int)totalGramCount + " = " + f4.format(prec_n));
}
} else {
if (oneLiner) {
System.out.print(n + "=N/A, ");
} else {
System.out.println("BLEU_precision(" + n + ") = N/A (candidate has no " + n + "-grams)");
}
}
} else {
smooth_addition *= 0.5;
prec_n = smooth_addition / (c_len-n+1);
// isn't c_len-n+1 just totalGramCount ???????
if (oneLiner) {
System.out.print(n + "~" + f4.format(prec_n) + ", ");
} else {
System.out.println("BLEU_precision(" + n + ") = " + (int)correctGramCount + " / " + (int)totalGramCount + " ==smoothed==> " + f4.format(prec_n));
}
}
BLEUsum += weights[n] * Math.log(prec_n);
}
if (oneLiner) {
System.out.print("(overall=" + f4.format(Math.exp(BLEUsum)) + "), ");
} else {
System.out.println("BLEU_precision = " + f4.format(Math.exp(BLEUsum)));
System.out.println("");
}
double BP = 1.0;
if (c_len < r_len) BP = Math.exp(1-(r_len/c_len));
// if c_len > r_len, no penalty applies
if (oneLiner) {
System.out.print("BP=" + f4.format(BP) + ", ");
} else {
System.out.println("Length of candidate corpus = " + (int)c_len);
System.out.println("Effective length of reference corpus = " + (int)r_len);
System.out.println("BLEU_BP = " + f4.format(BP));
System.out.println("");
}
System.out.println("BLEU = " + f4.format(BP*Math.exp(BLEUsum)));
}
protected int wordCount(String cand_str)
{
if (!cand_str.equals("")) {
return cand_str.split("\\s+").length;
} else {
return 0;
}
}
public HashMap<String,Integer>[] getNgramCountsArray(String cand_str)
{
if (!cand_str.equals("")) {
return getNgramCountsArray(cand_str.split("\\s+"));
} else {
return getNgramCountsArray(new String[0]);
}
}
@SuppressWarnings("unchecked")
public HashMap<String,Integer>[] getNgramCountsArray(String[] words)
{
HashMap<String,Integer>[] ngramCountsArray = new HashMap[1+maxGramLength];
ngramCountsArray[0] = null;
for (int n = 1; n <= maxGramLength; ++n) {
ngramCountsArray[n] = new HashMap<String,Integer>();
}
int len = words.length;
String gram;
int st = 0;
for (; st <= len-maxGramLength; ++st) {
gram = words[st];
if (ngramCountsArray[1].containsKey(gram)) {
int oldCount = ngramCountsArray[1].get(gram);
ngramCountsArray[1].put(gram,oldCount+1);
} else {
ngramCountsArray[1].put(gram,1);
}
for (int n = 2; n <= maxGramLength; ++n) {
gram = gram + " " + words[st+n-1];
if (ngramCountsArray[n].containsKey(gram)) {
int oldCount = ngramCountsArray[n].get(gram);
ngramCountsArray[n].put(gram,oldCount+1);
} else {
ngramCountsArray[n].put(gram,1);
}
} // for (n)
} // for (st)
// now st is either len-maxGramLength+1 or zero (if above loop never entered, which
// happens with sentences that have fewer than maxGramLength words)
for (; st < len; ++st) {
gram = words[st];
if (ngramCountsArray[1].containsKey(gram)) {
int oldCount = ngramCountsArray[1].get(gram);
ngramCountsArray[1].put(gram,oldCount+1);
} else {
ngramCountsArray[1].put(gram,1);
}
int n = 2;
for (int fin = st+1; fin < len; ++fin) {
gram = gram + " " + words[st+n-1];
if (ngramCountsArray[n].containsKey(gram)) {
int oldCount = ngramCountsArray[n].get(gram);
ngramCountsArray[n].put(gram,oldCount+1);
} else {
ngramCountsArray[n].put(gram,1);
}
++n;
} // for (fin)
} // for (st)
return ngramCountsArray;
}
public HashMap<String,Integer> getNgramCountsAll(String cand_str)
{
if (!cand_str.equals("")) {
return getNgramCountsAll(cand_str.split("\\s+"));
} else {
return getNgramCountsAll(new String[0]);
}
}
public HashMap<String,Integer> getNgramCountsAll(String[] words)
{
HashMap<String,Integer> ngramCountsAll = new HashMap<String,Integer>();
int len = words.length;
String gram;
int st = 0;
for (; st <= len-maxGramLength; ++st) {
gram = words[st];
if (ngramCountsAll.containsKey(gram)) {
int oldCount = ngramCountsAll.get(gram);
ngramCountsAll.put(gram,oldCount+1);
} else {
ngramCountsAll.put(gram,1);
}
for (int n = 2; n <= maxGramLength; ++n) {
gram = gram + " " + words[st+n-1];
if (ngramCountsAll.containsKey(gram)) {
int oldCount = ngramCountsAll.get(gram);
ngramCountsAll.put(gram,oldCount+1);
} else {
ngramCountsAll.put(gram,1);
}
} // for (n)
} // for (st)
// now st is either len-maxGramLength+1 or zero (if above loop never entered, which
// happens with sentences that have fewer than maxGramLength words)
for (; st < len; ++st) {
gram = words[st];
if (ngramCountsAll.containsKey(gram)) {
int oldCount = ngramCountsAll.get(gram);
ngramCountsAll.put(gram,oldCount+1);
} else {
ngramCountsAll.put(gram,1);
}
int n = 2;
for (int fin = st+1; fin < len; ++fin) {
gram = gram + " " + words[st+n-1];
if (ngramCountsAll.containsKey(gram)) {
int oldCount = ngramCountsAll.get(gram);
ngramCountsAll.put(gram,oldCount+1);
} else {
ngramCountsAll.put(gram,1);
}
++n;
} // for (fin)
} // for (st)
return ngramCountsAll;
}
enum EffectiveLengthMethod {
CLOSEST,
SHORTEST,
AVERAGE
}
} |
package rickbw.crud.http;
import java.net.URI;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.ws.rs.core.MediaType;
import rickbw.crud.sync.SyncMapResourceDeleter;
import rickbw.crud.sync.SyncMapResourceProvider;
import rickbw.crud.sync.SyncMapResourceSetter;
import rickbw.crud.sync.SyncMapResourceUpdater;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.RequestBuilder;
import com.sun.jersey.api.client.UniformInterface;
import com.sun.jersey.api.client.UniformInterfaceException;
public final class SyncJerseyMapClient
implements SyncMapResourceProvider<URI, ClientResponse>,
SyncMapResourceDeleter<URI, ClientResponse>,
SyncMapResourceSetter<URI, Object, ClientResponse>,
SyncMapResourceUpdater<URI, Object, ClientResponse> {
private final Client restClient;
private final Optional<MediaType> type;
private final ImmutableMap<String, Object> headers;
/**
* Keeping this as an array is less safe than using an {@link ImmutableSet},
* but since we need it as an array for every request, the performance is
* better if we just do the transformation to an array once, up front.
*/
private final MediaType[] mediaTypes;
public SyncJerseyMapClient(final Client restClient, final Configuration config) {
this.restClient = Preconditions.checkNotNull(restClient);
this.type = Optional.fromNullable(config.getType());
this.headers = ImmutableMap.copyOf(config.getHeaders());
final Collection<MediaType> mediaTypesSet = config.getMediaTypes();
this.mediaTypes = mediaTypesSet.toArray(new MediaType[mediaTypesSet.size()]);
}
@Override
public ClientResponse getSync(final URI uri) throws UniformInterfaceIOException, ClientHandlerIOException {
final UniformInterface webResource = getResource(uri);
try {
final ClientResponse response = webResource.get(ClientResponse.class);
return response;
} catch (final UniformInterfaceException uix) {
throw new UniformInterfaceIOException(uix);
} catch (final ClientHandlerException chx) {
throw new ClientHandlerIOException(chx);
}
}
@Override
public ClientResponse deleteSync(final URI uri) throws UniformInterfaceIOException, ClientHandlerIOException {
final UniformInterface webResource = getResource(uri);
try {
final ClientResponse response = webResource.delete(ClientResponse.class);
return response;
} catch (final UniformInterfaceException uix) {
throw new UniformInterfaceIOException(uix);
} catch (final ClientHandlerException chx) {
throw new ClientHandlerIOException(chx);
}
}
@Override
public ClientResponse putSync(final URI uri, final Object update) throws UniformInterfaceIOException, ClientHandlerIOException {
final UniformInterface webResource = getResource(uri);
try {
final ClientResponse response = webResource.put(ClientResponse.class, update);
return response;
} catch (final UniformInterfaceException uix) {
throw new UniformInterfaceIOException(uix);
} catch (final ClientHandlerException chx) {
throw new ClientHandlerIOException(chx);
}
}
@Override
public ClientResponse updateSync(final URI uri, final Object update) throws UniformInterfaceIOException, ClientHandlerIOException {
final UniformInterface webResource = getResource(uri);
try {
final ClientResponse response = webResource.post(ClientResponse.class, update);
return response;
} catch (final UniformInterfaceException uix) {
throw new UniformInterfaceIOException(uix);
} catch (final ClientHandlerException chx) {
throw new ClientHandlerIOException(chx);
}
}
@Override
public final void close(final ClientResponse response) throws ClientHandlerIOException {
try {
response.close();
} catch (final ClientHandlerException chx) {
throw new ClientHandlerIOException(chx);
}
}
private UniformInterface getResource(final URI uri) {
RequestBuilder<?> resource = this.restClient.resource(uri);
if (this.mediaTypes.length > 0) {
resource = resource.accept(this.mediaTypes);
}
if (this.type.isPresent()) {
resource = resource.type(this.type.get());
}
for (final Map.Entry<String, Object> entry : this.headers.entrySet()) {
resource = resource.header(entry.getKey(), entry.getValue());
}
// WebResource and WebResource.Builder both implement UniformInterface
return (UniformInterface) resource;
}
public static final class Configuration {
@Nullable
private MediaType type = null;
private final Set<MediaType> mediaTypes = Sets.newHashSet();
private final Map<String, Object> headers = Maps.newHashMap();
@Nullable
public MediaType getType() {
return this.type;
}
public void setType(@Nullable final MediaType type) {
this.type = type;
}
public Collection<MediaType> getMediaTypes() {
return ImmutableSet.copyOf(this.mediaTypes);
}
public void setMediaTypes(final Collection<MediaType> newMediaTypes) {
this.mediaTypes.clear();
this.mediaTypes.addAll(newMediaTypes);
}
public void addMediaType(final MediaType newType) {
Preconditions.checkNotNull(newType);
this.mediaTypes.add(newType);
}
public Map<String, Object> getHeaders() {
return ImmutableMap.copyOf(this.headers);
}
public void setHeaders(final Map<String, Object> newHeaders) {
this.headers.clear();
this.headers.putAll(newHeaders);
}
public void addHeader(final String name, final Object value) {
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(value);
this.headers.put(name, value);
}
}
} |
package stud.mi.dachatserver.dto;
import java.util.ArrayList;
import java.util.List;
public class MessageList {
private String _id = "message_list";
private String _rev;
public List<Message> messages = new ArrayList<>();
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("{ id: ");
builder.append(_id);
builder.append(",\nrev: ");
builder.append(_rev);
builder.append(",\nmsgList: ");
builder.append(" [\n");
for (int i = 0; i < messages.size(); i++) {
builder.append(messages.get(i));
if (i < messages.size() - 1) {
builder.append(",");
}
}
builder.append(" ]");
builder.append("\n}");
return builder.toString();
}
} |
package trikita.talalarmo.alarm;
import android.Manifest;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Vibrator;
import trikita.talalarmo.App;
public class AlarmService extends Service {
// Time period between two vibration events
private final static int VIBRATE_DELAY_TIME = 2000;
// Vibrate for 1000 milliseconds
private final static int DURATION_OF_VIBRATION = 1000;
// Increase alarm volume gradually every 600ms
private final static int VOLUME_INCREASE_DELAY = 600;
// Volume level increasing step
private final static float VOLUME_INCREASE_STEP = 0.01f;
// Max player volume level
private final static float MAX_VOLUME = 1.0f;
private MediaPlayer mPlayer;
private Vibrator mVibrator;
private float mVolumeLevel = 0;
private Handler mHandler = new Handler();
private Runnable mVibrationRunnable = new Runnable() {
@Override
public void run() {
mVibrator.vibrate(DURATION_OF_VIBRATION);
// Provide loop for vibration
mHandler.postDelayed(mVibrationRunnable,
DURATION_OF_VIBRATION + VIBRATE_DELAY_TIME);
}
};
private Runnable mVolumeRunnable = new Runnable() {
@Override
public void run() {
// increase volume level until reach max value
if (mPlayer != null && mVolumeLevel < MAX_VOLUME) {
mVolumeLevel += VOLUME_INCREASE_STEP;
mPlayer.setVolume(mVolumeLevel, mVolumeLevel);
// set next increase in 600ms
mHandler.postDelayed(mVolumeRunnable, VOLUME_INCREASE_DELAY);
}
}
};
private MediaPlayer.OnErrorListener mErrorListener = (mp, what, extra) -> {
mp.stop();
mp.release();
mHandler.removeCallbacksAndMessages(null);
AlarmService.this.stopSelf();
return true;
};
@Override
public void onCreate() {
HandlerThread ht = new HandlerThread("alarm_service");
ht.start();
mHandler = new Handler(ht.getLooper());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startPlayer();
// Start the activity where you can stop alarm
Intent i = new Intent(Intent.ACTION_MAIN);
i.setComponent(new ComponentName(this, AlarmActivity.class));
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
if (mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
mHandler.removeCallbacksAndMessages(null);
}
private void startPlayer() {
mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(mErrorListener);
try {
// add vibration to alarm alert if it is set
if (App.getState().settings().vibrate()) {
mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
mHandler.post(mVibrationRunnable);
}
// Player setup is here
String ringtone = App.getState().settings().ringtone();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ringtone.startsWith("content://media/external/")
&& checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
}
mPlayer.setDataSource(this, Uri.parse(ringtone));
mPlayer.setLooping(true);
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mPlayer.setVolume(mVolumeLevel, mVolumeLevel);
mPlayer.prepare();
mPlayer.start();
if (App.getState().settings().ramping()) {
mHandler.postDelayed(mVolumeRunnable, VOLUME_INCREASE_DELAY);
} else {
mPlayer.setVolume(MAX_VOLUME, MAX_VOLUME);
}
} catch (Exception e) {
if (mPlayer.isPlaying()) {
mPlayer.stop();
}
stopSelf();
}
}
} |
package xyz.thepathfinder.android;
import org.glassfish.tyrus.client.ClientManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.websocket.ClientEndpointConfig;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class Pathfinder {
private static final Logger logger = LoggerFactory.getLogger(Action.class);
/**
* Keeps track of all the Pathfinder models and connection to the server.
*/
private PathfinderServices services;
/**
* URL to the Pathfinder server being connected to.
*/
private URI webSocketUrl;
public static Pathfinder create(String applicationIdentifier) throws IOException {
Pathfinder pf = new Pathfinder(applicationIdentifier, "");
pf.connect(applicationIdentifier);
return pf;
}
/**
* Constructs a Pathfinder object.
*
* @param applicationIdentifier application Identifier provided by a Pathfinder service provider
* @param userCredentials JWT of the user's credentials
*/
private Pathfinder(String applicationIdentifier, String userCredentials) {
try {
this.webSocketUrl = new URI("ws://api.thepathfinder.xyz/socket");
} catch(URISyntaxException e) {
logger.error(e.getMessage());
}
this.constructPathfinder(applicationIdentifier, userCredentials);
}
/**
* Constructs a Pathfinder object.
*
* @param applicationIdentifier application Identifier provided by a Pathfinder service provider
* @param userCredentials JWT of the user's credentials
* @param webSocketUrl URL to the Pathfinder web socket service provider
*/
protected Pathfinder(String applicationIdentifier, String userCredentials, URI webSocketUrl) {
this.webSocketUrl = webSocketUrl;
this.constructPathfinder(applicationIdentifier, userCredentials);
}
private void constructPathfinder(String applicationIdentifier, String userCredentials) {
ModelRegistry registry = new ModelRegistry();
Connection connection = new Connection(userCredentials);
this.services = new PathfinderServices(registry, connection);
connection.setServices(services);
}
/**
* Establishes a connection to the Pathfinder server, if the connection is not already open.
* This method blocks until the connection is established.
*/
private void connect(final String applicationIdentifier) throws IOException {
if (!this.isConnected()) {
ClientManager clientManager = new ClientManager();
ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
@Override
public void beforeRequest(Map<String, List<String>> header) {
header.put("Authorization", Arrays.asList(applicationIdentifier));
}
};
ClientEndpointConfig configuration = ClientEndpointConfig.Builder.create().configurator(configurator).build();
try {
// blocks until connection is established, JSR 356
clientManager.asyncConnectToServer(this.services.getConnection(), configuration, this.webSocketUrl);
} catch (DeploymentException e) {
// Invalid annotated connection object and connection problems
logger.error("Deployment Exception: " + e.getMessage());
throw new IOException(e);
}
}
}
/**
* Gets an unconnected cluster pointing to the default cluster for the application identifier provided.
*
* @return an unconnected cluster
*/
public Cluster getDefaultCluster() {
return Cluster.getInstance(Path.DEFAULT_PATH, this.services);
}
/**
* Gets an unconnected cluster pointing to the path specified.
*
* @param path to the cluster
* @return an unconnected cluster
*/
public Cluster getCluster(String path) {
return Cluster.getInstance(path, this.services);
}
/**
* Gets an unconnected commodity pointing to the path specified.
*
* @param path to the commodity
* @return an unconnected commodity
*/
public Commodity getCommodity(String path) {
return Commodity.getInstance(path, this.services);
}
/**
* Gets an unconnected transport pointing to the path specified.
*
* @param path to the transport
* @return an unconnected transport
*/
public Transport getTransport(String path) {
return Transport.getInstance(path, this.services);
}
/**
* Returns <tt>true</tt> if the web socket connection to the Pathfinder server is open.
*
* @return <tt>true</tt> if the connection is still open
*/
public boolean isConnected() {
return this.services.getConnection().isConnected();
}
/**
* Returns the number of web socket messages sent to the Pathfinder server.
*
* @return The number of web socket messages sent
*/
protected long getSentMessageCount() {
return this.services.getConnection().getSentMessageCount();
}
/**
* Returns the number of web socket messages received from the Pathfinder server.
*
* @return The number of web socket messsages received.
*/
protected long getReceivedMessageCount() {
return this.services.getConnection().getReceivedMessageCount();
}
/**
* Closes the web socket connection to the Pathfinder server with a normal close condition.
*
* @throws IOException If there was error closing the connection.
*/
public void close() throws IOException {
CloseReason reason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Connection ended by user");
this.close(reason);
}
/**
* Closes the web socket connection to the Pathfinder server, if it is still open, with the specified reason.
*
* @param reason The reason to close the connection.
* @throws IOException If there was error closing the connection.
*/
public void close(CloseReason reason) throws IOException {
if (this.isConnected()) {
logger.info("Connection closed");
this.services.getConnection().close(reason);
}
}
} |
package net.sourceforge.jtds.jdbc;
import java.sql.*;
/**
* Implements a cursor-based <code>ResultSet</code>. Implementation is based on
* the undocumented <code>sp_cursor</code> procedures.
*
* @created March 16, 2001
* @version 2.0
*/
public class CursorResultSet extends AbstractResultSet implements OutputParamHandler {
public static final int FETCH_FIRST = 1;
public static final int FETCH_NEXT = 2;
public static final int FETCH_PREVIOUS = 4;
public static final int FETCH_LAST = 8;
public static final int FETCH_ABSOLUTE = 16;
public static final int FETCH_RELATIVE = 32;
public static final int FETCH_REPEAT = 128;
public static final int FETCH_INFO = 256;
public static final int CURSOR_TYPE_KEYSET = 1;
public static final int CURSOR_TYPE_DYNAMIC = 2;
public static final int CURSOR_TYPE_FORWARD = 4;
public static final int CURSOR_TYPE_STATIC = 8;
public static final int CURSOR_CONCUR_READ_ONLY = 1;
public static final int CURSOR_CONCUR_SCROLL_LOCKS = 2;
public static final int CURSOR_CONCUR_OPTIMISTIC = 4;
public static final int CURSOR_OP_INSERT = 4;
public static final int CURSOR_OP_UPDATE = 33;
public static final int CURSOR_OP_DELETE = 34;
/**
* The row is unchanged.
*/
public static final int SQL_ROW_SUCCESS = 1;
/**
* The row has been deleted.
*/
public static final int SQL_ROW_DELETED = 2;
// @todo Check the values for the constants below (above are ok).
/**
* The row has been updated.
*/
public static final int SQL_ROW_UPDATED = 3;
/**
* There is no row that corresponds this position.
*/
public static final int SQL_ROW_NOROW = 4;
/**
* The row has been added.
*/
public static final int SQL_ROW_ADDED = 5;
/**
* The row is unretrievable due to an error.
*/
public static final int SQL_ROW_ERROR = 6;
private static final int POS_BEFORE_FIRST = -100000;
private static final int POS_AFTER_LAST = -200000;
private int pos = POS_BEFORE_FIRST;
private Integer cursorHandle;
private int rowsInResult;
private String sql;
private TdsStatement stmt;
private TdsConnection conn;
private int direction = FETCH_FORWARD;
private boolean open = false;
private Context context;
private PacketRowResult current;
/**
* Parameter list used for calling stored procedures.
*/
private ParameterListItem[] parameterList;
/**
* Stores return values from stored procedure calls.
*/
private Integer retVal;
/**
* Index of the last output parameter.
*/
private int lastOutParam = -1;
private int type;
private int concurrency;
/**
* Set when <code>moveToInsertRow()</code> was called.
*/
private boolean onInsertRow = false;
/**
* The "insert row".
*/
private PacketRowResult insertRow;
public Context getContext() {
return context;
}
public CursorResultSet(TdsStatement stmt, String sql, int fetchDir)
throws SQLException {
this.stmt = stmt;
this.conn = (TdsConnection) stmt.getConnection();
this.sql = sql;
this.direction = fetchDir == FETCH_UNKNOWN ? FETCH_FORWARD : fetchDir;
this.type = stmt.getResultSetType();
this.concurrency = stmt.getResultSetConcurrency();
// SAfe Until we're actually created use the Statement's warning chain.
warningChain = stmt.warningChain;
cursorCreate();
// SAfe Now we can create our own warning chain.
warningChain = new SQLWarningChain();
}
protected void finalize() {
try {
close();
} catch (SQLException ex) {
}
}
public void setFetchDirection(int direction) throws SQLException {
switch (direction) {
case FETCH_UNKNOWN:
case FETCH_REVERSE:
if (type != ResultSet.TYPE_FORWARD_ONLY) {
throw new SQLException("ResultSet is forward-only.");
}
// Fall through
case FETCH_FORWARD:
this.direction = direction;
break;
default:
throw new SQLException("Invalid fetch direction: "+direction);
}
}
public void setFetchSize(int rows) throws SQLException {
}
public String getCursorName() throws SQLException {
throw new SQLException("Positioned update not supported.");
}
public boolean isBeforeFirst() throws SQLException {
return (pos == POS_BEFORE_FIRST) && (rowsInResult != 0);
}
public boolean isAfterLast() throws SQLException {
return (pos == POS_AFTER_LAST) && (rowsInResult != 0);
}
public boolean isFirst() throws SQLException {
return pos == 1;
}
public boolean isLast() throws SQLException {
return pos == rowsInResult;
}
public int getRow() throws SQLException {
return pos>0 ? pos : 0;
}
public int getFetchDirection() throws SQLException {
return direction;
}
public int getFetchSize() throws SQLException {
return 1;
}
public int getType() throws SQLException {
return type;
}
public int getConcurrency() throws SQLException {
return concurrency;
}
public Statement getStatement() throws SQLException {
return stmt;
}
public void close() throws SQLException {
if (open) {
try {
warningChain.clearWarnings();
cursorClose();
} finally {
open = false;
stmt = null;
conn = null;
}
}
warningChain.checkForExceptions();
}
public SQLWarning getWarnings() throws SQLException {
return warningChain.getWarnings();
}
public boolean next() throws SQLException {
if (cursorFetch(FETCH_NEXT, 0)) {
pos += (pos < 0) ? (1-pos) : 1;
return true;
} else {
pos = POS_AFTER_LAST;
return false;
}
}
public void clearWarnings() throws SQLException {
warningChain.clearWarnings();
}
public void beforeFirst() throws SQLException {
if (pos != POS_BEFORE_FIRST) {
cursorFetch(FETCH_ABSOLUTE, 0);
pos = POS_BEFORE_FIRST;
}
}
public void afterLast() throws SQLException {
if (pos != POS_AFTER_LAST) {
cursorFetch(FETCH_ABSOLUTE, rowsInResult + 1);
pos = POS_AFTER_LAST;
}
}
public boolean first()
throws SQLException {
boolean res = cursorFetch(FETCH_FIRST, 0);
pos = 1;
return res;
}
public boolean last()
throws SQLException {
boolean res = cursorFetch(FETCH_LAST, 0);
pos = rowsInResult;
return res;
}
public boolean absolute(int row)
throws SQLException {
// If nothing was fetched, we got passed the beginning or end
if (!cursorFetch(FETCH_ABSOLUTE, row)) {
if (row > 0) {
pos = POS_AFTER_LAST;
} else {
pos = POS_BEFORE_FIRST;
}
return false;
}
pos = row;
return true;
}
public boolean relative(int rows) throws SQLException {
if (!cursorFetch(FETCH_RELATIVE, rows)) {
if (rows > 0) {
pos = POS_AFTER_LAST;
} else {
pos = POS_BEFORE_FIRST;
}
return false;
}
// If less than 0, it can only be POS_BEFORE_FIRST or POS_AFTER_LAST
if( pos < 0 ) {
if( pos == POS_BEFORE_FIRST ) {
pos = 0;
} else {
pos = rowsInResult;
}
}
pos += rows;
return true;
}
public boolean previous() throws SQLException {
if (cursorFetch(FETCH_PREVIOUS, 0)) {
pos -= (pos < 0) ? (pos-rowsInResult) : 1;
return true;
} else {
pos = POS_BEFORE_FIRST;
return false;
}
}
public boolean rowUpdated() throws SQLException {
return getRowStat() == SQL_ROW_UPDATED;
}
private int getRowStat() throws SQLException {
return (int) current.getLong(
context.getColumnInfo().realColumnCount());
}
public boolean rowInserted() throws SQLException {
return getRowStat() == this.SQL_ROW_ADDED;
}
public boolean rowDeleted() throws SQLException {
return getRowStat() == SQL_ROW_DELETED;
}
public void cancelRowUpdates() throws SQLException {
if (onInsertRow) {
throw new SQLException("The cursor is on the insert row.");
}
refreshRow();
}
public void moveToInsertRow() throws SQLException {
onInsertRow = true;
}
public void moveToCurrentRow() throws SQLException {
onInsertRow = false;
}
public PacketRowResult currentRow() throws SQLException {
if (onInsertRow) {
if (insertRow == null) {
insertRow = new PacketRowResult(context);
}
return insertRow;
}
if (current == null) {
throw new SQLException("No current row in the ResultSet");
}
return current;
}
public void insertRow() throws SQLException {
if (!onInsertRow) {
throw new SQLException("The cursor is not on the insert row.");
}
// This might just happen if the ResultSet has no writeable column.
// Very unlikely and very stupid, but who knows?
if (insertRow == null) {
insertRow = new PacketRowResult(context);
}
cursor(CURSOR_OP_INSERT, insertRow);
insertRow = new PacketRowResult(context);
}
public void updateRow() throws SQLException {
if (current == null) {
throw new SQLException("No current row in the ResultSet");
}
if (onInsertRow) {
throw new SQLException("The cursor is on the insert row.");
}
cursor(CURSOR_OP_UPDATE, current);
refreshRow();
}
public void deleteRow() throws SQLException {
if (current == null) {
throw new SQLException("No current row in the ResultSet");
}
if (onInsertRow) {
throw new SQLException("The cursor is on the insert row.");
}
cursor(CURSOR_OP_DELETE, null);
cursorFetch(FETCH_REPEAT, 1);
}
public void refreshRow() throws SQLException {
if (onInsertRow) {
throw new SQLException("The cursor is on the insert row.");
}
cursorFetch(FETCH_REPEAT, 1);
}
private void cursorCreate() throws SQLException {
warningChain.clearWarnings();
parameterList = new ParameterListItem[5];
int scrollOpt, ccOpt;
switch (type) {
case TYPE_SCROLL_INSENSITIVE:
scrollOpt = CURSOR_TYPE_STATIC;
break;
case TYPE_SCROLL_SENSITIVE:
scrollOpt = CURSOR_TYPE_KEYSET;
break;
case TYPE_FORWARD_ONLY:
default:
scrollOpt = CURSOR_TYPE_FORWARD;
break;
}
switch (concurrency) {
case CONCUR_READ_ONLY:
default:
ccOpt = CURSOR_CONCUR_READ_ONLY;
break;
case CONCUR_UPDATABLE:
ccOpt = CURSOR_CONCUR_SCROLL_LOCKS;
break;
}
ParameterListItem param[] = parameterList;
// Setup cursor handle param
param[0] = new ParameterListItem();
param[0].isSet = true;
param[0].type = Types.INTEGER;
param[0].isOutput = true;
// Setup statement param
param[1] = new ParameterListItem();
param[1].isSet = true;
param[1].type = Types.LONGVARCHAR;
param[1].maxLength = Integer.MAX_VALUE;
param[1].formalType = "ntext";
param[1].value = sql;
// Setup scroll options
param[2] = new ParameterListItem();
param[2].isSet = true;
param[2].type = Types.INTEGER;
param[2].value = new Integer(scrollOpt);
param[2].isOutput = true;
// Setup concurrency options
param[3] = new ParameterListItem();
param[3].isSet = true;
param[3].type = Types.INTEGER;
param[3].value = new Integer(ccOpt);
param[3].isOutput = true;
// Setup numRows parameter
param[4] = new ParameterListItem();
param[4].isSet = true;
param[4].type = Types.INTEGER;
param[4].isOutput = true;
lastOutParam = -1;
retVal = null;
// SAfe We have to synchronize this, in order to avoid mixing up our
// actions with another CursorResultSet's and eating up its
// results.
synchronized (conn.mainTdsMonitor) {
stmt.outParamHandler = this;
Tds tds = conn.allocateTds(true);
try {
tds.executeProcedure("sp_cursoropen", param, param, stmt,
warningChain, stmt.getQueryTimeout(), false);
// @todo Should maybe use a different statement here
if (stmt.getMoreResults(tds, warningChain, true)) {
context = stmt.results.context;
// Hide rowstat column.
context.getColumnInfo().setFakeColumnCount(
context.getColumnInfo().realColumnCount() - 1);
stmt.results.close();
} else {
warningChain.addException(new SQLException(
"Expected a ResultSet."));
}
if (stmt.getMoreResults(tds, warningChain, true)
|| (stmt.getUpdateCount() != -1)) {
warningChain.addException(new SQLException(
"No more results expected."));
}
} finally {
try {
conn.freeTds(tds);
} catch (TdsException ex) {
warningChain.addException(
new SQLException(ex.getMessage()));
}
lastOutParam = -1;
retVal = null;
stmt.outParamHandler = null;
}
}
cursorHandle = (Integer) param[0].value;
rowsInResult = ((Number) param[4].value).intValue();
int actualScroll = ((Number) param[2].value).intValue();
int actualCc = ((Number) param[3].value).intValue();
if ((actualScroll != scrollOpt) || (actualCc != ccOpt)) {
if (actualScroll != scrollOpt) {
switch (actualScroll) {
case CURSOR_TYPE_FORWARD:
type = TYPE_FORWARD_ONLY;
break;
case CURSOR_TYPE_STATIC:
type = TYPE_SCROLL_INSENSITIVE;
break;
case CURSOR_TYPE_DYNAMIC:
case CURSOR_TYPE_KEYSET:
type = TYPE_SCROLL_SENSITIVE;
break;
default:
warningChain.addException(new SQLException(
"Don't know how to handle cursor type "
+ actualScroll));
}
}
if (actualCc != ccOpt) {
switch (actualCc) {
case CURSOR_CONCUR_READ_ONLY:
concurrency = CONCUR_READ_ONLY;
break;
case CURSOR_CONCUR_SCROLL_LOCKS:
case CURSOR_CONCUR_OPTIMISTIC:
concurrency = CONCUR_UPDATABLE;
break;
default:
warningChain.addException(new SQLException(
"Don't know how to handle concurrency type "
+ actualScroll));
}
}
// @todo This warning should somehow go to the Statement
warningChain.addWarning(new SQLWarning(
"ResultSet type/concurrency downgraded."));
}
if ((retVal == null) || (retVal.intValue() != 0)) {
warningChain.addException(
new SQLException("Cursor open failed."));
}
warningChain.checkForExceptions();
open = true;
}
private boolean cursorFetch(int fetchType, int rowNum)
throws SQLException {
warningChain.clearWarnings();
ParameterListItem param[] = new ParameterListItem[4];
System.arraycopy(parameterList, 0, param, 0, 4);
boolean isInfo = (fetchType == FETCH_INFO);
if (fetchType != FETCH_ABSOLUTE && fetchType != FETCH_RELATIVE)
rowNum = 1;
// Setup cursor handle param
param[0].clear();
param[0].isSet = true;
param[0].type = Types.INTEGER;
param[0].value = cursorHandle;
// Setup fetchtype param
param[1].clear();
param[1].isSet = true;
param[1].type = Types.INTEGER;
param[1].value = new Integer(fetchType);
// Setup rownum
param[2].clear();
param[2].isSet = true;
param[2].type = Types.INTEGER;
param[2].value = isInfo ? null : new Integer(rowNum);
param[2].isOutput = isInfo;
// Setup numRows parameter
param[3].clear();
param[3].isSet = true;
param[3].type = Types.INTEGER;
param[3].value = isInfo ? null : new Integer(1);
param[3].isOutput = isInfo;
lastOutParam = -1;
retVal = null;
// SAfe We have to synchronize this, in order to avoid mixing up our
// actions with another CursorResultSet's and eating up its
// results.
synchronized (conn.mainTdsMonitor) {
stmt.outParamHandler = this;
Tds tds = conn.allocateTds(true);
try {
tds.executeProcedure("sp_cursorfetch", param, param, stmt,
warningChain, stmt.getQueryTimeout(), true);
current = tds.fetchRow(stmt, warningChain, context);
// @todo Should maybe use a different statement here
if (stmt.getMoreResults(tds, warningChain, true)
|| (stmt.getUpdateCount() != -1)) {
warningChain.addException(new SQLException(
"No results expected."));
}
if ((retVal == null) || (retVal.intValue() != 0)) {
warningChain.addException(
new SQLException("Cursor fetch failed."));
}
} finally {
try {
conn.freeTds(tds);
} catch (TdsException ex) {
warningChain.addException(
new SQLException(ex.getMessage()));
}
lastOutParam = -1;
retVal = null;
stmt.outParamHandler = null;
}
}
warningChain.checkForExceptions();
return current != null;
}
private void cursorClose() throws SQLException {
warningChain.clearWarnings();
ParameterListItem param[] = new ParameterListItem[1];
param[0] = parameterList[0];
// Setup cursor handle param
param[0].clear();
param[0].isSet = true;
param[0].type = Types.INTEGER;
param[0].value = cursorHandle;
lastOutParam = -1;
retVal = null;
// SAfe We have to synchronize this, in order to avoid mixing up our
// actions with another CursorResultSet's and eating up its
// results.
synchronized (conn.mainTdsMonitor) {
stmt.outParamHandler = this;
Tds tds = conn.allocateTds(true);
try {
tds.executeProcedure("sp_cursorclose", param, param, stmt,
warningChain, stmt.getQueryTimeout(), false);
// @todo Should maybe use a different statement here
if (stmt.getMoreResults(tds, warningChain, true)
|| (stmt.getUpdateCount() != -1)) {
warningChain.addException(new SQLException(
"No results expected."));
}
if ((retVal == null) || (retVal.intValue() != 0)) {
warningChain.addException(
new SQLException("Cursor close failed."));
}
} finally {
try {
conn.freeTds(tds);
} catch (TdsException ex) {
warningChain.addException(
new SQLException(ex.getMessage()));
}
lastOutParam = -1;
retVal = null;
stmt.outParamHandler = null;
}
}
warningChain.checkForExceptions();
}
private void cursor(int opType, PacketRowResult row) throws SQLException {
warningChain.clearWarnings();
ParameterListItem param[];
if (opType == CURSOR_OP_DELETE) {
if (row != null) {
throw new SQLException(
"Non-null row provided to delete operation.");
}
// 3 parameters for delete
param = new ParameterListItem[3];
System.arraycopy(parameterList, 0, param, 0, 3);
} else {
if (row == null) {
throw new SQLException(
"Null row provided to insert/update operation.");
}
// 4 parameters plus one for each column for insert/update
param = new ParameterListItem[4
+ row.context.getColumnInfo().fakeColumnCount()];
System.arraycopy(parameterList, 0, param, 0, 4);
}
// Setup cursor handle param
param[0].clear();
param[0].isSet = true;
param[0].type = Types.INTEGER;
param[0].value = cursorHandle;
// Setup optype param
param[1].clear();
param[1].isSet = true;
param[1].type = Types.INTEGER;
param[1].value = new Integer(opType);
// Setup rownum
param[2].clear();
param[2].isSet = true;
param[2].type = Types.INTEGER;
param[2].value = new Integer(1);
// If row is not null, we're dealing with an insert/update
if (row != null) {
// Setup table
param[3].clear();
param[3].isSet = true;
param[3].type = Types.VARCHAR;
param[3].value = "";
param[3].formalType = "nvarchar(4000)";
param[3].maxLength = 4000;
Columns cols = row.context.getColumnInfo();
int colCnt = cols.fakeColumnCount();
// Current column; we should only update/insert columns
// that are not read-only (such as identity columns)
int crtCol = 4;
for (int i=1; i <= colCnt; i++) {
// Only send non-read-only columns
if (!cols.isReadOnly(i).booleanValue()) {
param[crtCol] = new ParameterListItem();
param[crtCol].isSet = true;
param[crtCol].type = cols.getJdbcType(i);
param[crtCol].value = row.getObject(i);
param[crtCol].formalName = '@' + cols.getName(i);
param[crtCol].maxLength = cols.getBufferSize(i);
param[crtCol].scale = cols.getScale(i);
// This is only for Tds.executeProcedureInternal to
// know that it's a Unicode column
switch (cols.getNativeType(i)) {
case TdsDefinitions.SYBBIGNVARCHAR:
case TdsDefinitions.SYBNVARCHAR:
case TdsDefinitions.SYBNCHAR:
param[crtCol].formalType = "nvarchar(4000)";
break;
case TdsDefinitions.SYBNTEXT:
param[crtCol].formalType = "ntext";
break;
}
crtCol++;
} else {
if (row.getObject(i) != null)
throw new SQLException(
"Column " + i + "/" + cols.getName(i)
+ " is read-only.");
}
}
// If the count is different (i.e. there were read-only
// columns) reallocate the parameters into a shorter array
if (crtCol != colCnt+4) {
ParameterListItem[] newParam =
new ParameterListItem[crtCol];
System.arraycopy(param, 0, newParam, 0, crtCol);
param = newParam;
}
}
lastOutParam = -1;
retVal = null;
// SAfe We have to synchronize this, in order to avoid mixing up our
// actions with another CursorResultSet's and eating up its
// results.
synchronized (conn.mainTdsMonitor) {
stmt.outParamHandler = this;
Tds tds = conn.allocateTds(true);
try {
tds.executeProcedure("sp_cursor", param, param, stmt,
warningChain, stmt.getQueryTimeout(), false);
// @todo Should maybe use a different statement here
if (stmt.getMoreResults(tds, warningChain, true)
|| (stmt.getUpdateCount() != -1)) {
warningChain.addException(new SQLException(
"No results expected."));
}
if ((retVal == null) || (retVal.intValue() != 0)) {
warningChain.addException(
new SQLException("Cursor operation failed."));
}
} finally {
try {
conn.freeTds(tds);
} catch (TdsException ex) {
warningChain.addException(
new SQLException(ex.getMessage()));
}
lastOutParam = -1;
retVal = null;
stmt.outParamHandler = null;
}
}
warningChain.checkForExceptions();
}
/**
* Handle a return status.
*
* @param packet a RetStat packet
*/
public boolean handleRetStat(PacketRetStatResult packet) {
retVal = new Integer(packet.getRetStat());
return true;
}
/**
* Handle an output parameter.
*
* @param packet an OutputParam packet
* @throws SQLException if there is a handling exception
*/
public boolean handleParamResult(PacketOutputParamResult packet)
throws SQLException {
for (lastOutParam++; lastOutParam < parameterList.length; lastOutParam++)
if (parameterList[lastOutParam].isOutput) {
parameterList[lastOutParam].value = packet.value;
return true;
}
throw new SQLException("More output params than expected.");
}
} |
package org.brailleblaster.wordprocessor;
import java.awt.Desktop;
import org.brailleblaster.util.Notify;
import org.brailleblaster.BBIni;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.IOException;
/**
* This class handles the items on the help menu.
*/
class UserHelp {
private String helpPath;
Desktop desktop;
UserHelp (String helpName) {
helpPath = BBIni.getHelpDocsPath() + BBIni.getFileSep();
desktop = Desktop.getDesktop();
if (helpName.equals ("about")) {
new Notify (BBIni.getVersion() + ", released on " +
BBIni.getReleaseDate() +
". For questions and bug reports contact john.boyer@abilitiessoft.com");
}
else if (helpName.equals ("manuals")) {
showHelp ("manuals.html");
}
else if (helpName.equals ("helpinfo")) {
showHelp ("helpinfo.html");
}
else {
new Notify (helpName + " is being written.");
}
}
/**
* Display help documents in the local browser.
*/
void showHelp (String fileName) {
String URIString = "file://" + helpPath + fileName;
URI uri = null;
try {
uri = new URI (URIString);
} catch (URISyntaxException e) {
new Notify ("Syntax error in " +URIString);
return;
}
try {
desktop.browse (uri);
} catch (IOException e) {
new Notify ("Could not open " + uri.toString());
}
}
} |
package jsaf.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.nio.charset.Charset;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.TimerTask;
import java.util.zip.GZIPInputStream;
import jsaf.JSAFSystem;
import jsaf.Message;
import jsaf.intf.io.IFile;
import jsaf.intf.io.IFilesystem;
import jsaf.intf.io.IReader;
import jsaf.intf.system.IProcess;
import jsaf.intf.system.IComputerSystem;
import jsaf.intf.system.ISession;
import jsaf.intf.unix.system.IUnixSession;
import jsaf.io.PerishableReader;
import jsaf.io.SimpleReader;
import jsaf.io.Streams;
import jsaf.provider.SessionException;
/**
* A utility that simplifyies the execution of simple command-lines.
*
* @author David A. Solin
* @version %I% %G%
* @since 1.0
*/
public class SafeCLI {
/**
* An interface for processing data from a process stream (stdout or stderr), used by the exec method.
*
* If the command hangs diring processing (signaled to SafeCLI by an InterruptedIOException or SessionException),
* the SafeCLI will kill the old command, start a new command instance (up the the session's configured number of
* retries), and call handler.handle again.
*
* Therefore, the handler should initialize itself completely when handle is invoked, and not perform permanent
* output processing until the reader has reached the end of the process output.
*
* @since 1.3
*/
public interface IReaderHandler {
/**
* Handle data from the reader. Implementations must NEVER catch an IOException originating from the reader!
*
* @since 1.3
*/
public void handle(IReader reader) throws IOException;
}
/**
* An IReaderHandler that does nothing with data read from the IReader.
*
* @since 1.3
*/
public static final IReaderHandler DevNull = new IReaderHandler() {
public void handle(IReader reader) throws IOException {
String line;
while ((line = reader.readLine()) != null) {
}
}
};
public static String checkArgument(String arg, IComputerSystem sys) throws IllegalArgumentException {
char[] chars = arg.toCharArray();
switch(sys.getType()) {
case WINDOWS:
for (int i=0; i < chars.length; i++) {
// Powershell automatically converts 'smart-quotes' into regular quotes, so we have to specifically
// check for them.
switch((int)chars[i]) {
case 0x22: // ASCII double quote
case 0x27: // ASCII single quote
case 0x2018: // Unicode single left quote
case 0x2019: // Unicode single right quote
case 0x201a: // Unicode single low quote
case 0x201c: // Unicode double left quote
case 0x201d: // Unicode double right quote
case 0x201e: // Unicode double low quote
throw new IllegalArgumentException(Message.getMessage(Message.WARNING_UNSAFE_CHARS, arg));
default:
break;
}
}
break;
case UNIX:
for (int i=0; i < chars.length; i++) {
switch((int)chars[i]) {
case 0x22: // ASCII double quote
case 0x27: // ASCII single quote
case 0x60: // ASCII back-tick
throw new IllegalArgumentException(Message.getMessage(Message.WARNING_UNSAFE_CHARS, arg));
default:
break;
}
}
break;
}
return arg;
}
/**
* Run a command and get the first (non-empty) line of output.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final String exec(String cmd, IComputerSystem sys, ISession.Timeout readTimeout) throws Exception {
return exec(cmd, null, sys, sys.getTimeout(readTimeout));
}
/**
* Run a command and get the first (non-empty) line of output, using the specified environment.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final String exec(String cmd, String[] env, IComputerSystem sys, ISession.Timeout readTimeout) throws Exception {
return exec(cmd, env, null, sys, sys.getTimeout(readTimeout));
}
/**
* Run a command and get the first (non-empty) line of output, using the specified environment and start directory.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final String exec(String cmd, String[] env, String dir, IComputerSystem sys, ISession.Timeout readTimeout) throws Exception {
return exec(cmd, env, dir, sys, sys.getTimeout(readTimeout));
}
/**
* Run a command and get the first (non-empty) line of output.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final String exec(String cmd, IComputerSystem sys, long readTimeout) throws Exception {
return exec(cmd, null, null, sys, readTimeout);
}
/**
* Run a command and get the first (non-empty) line of output, using the specified environment.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final String exec(String cmd, String[] env, IComputerSystem sys, long readTimeout) throws Exception {
return exec(cmd, env, null, sys, readTimeout);
}
/**
* Run a command and get the first (non-empty) line of output, using the specified environment and start directory.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final String exec(String cmd, String[] env, String dir, IComputerSystem sys, long readTimeout) throws Exception {
List<String> lines = multiLine(cmd, env, dir, sys, readTimeout);
if (lines.size() == 2 && lines.get(0).equals("")) {
return lines.get(1);
} else {
return lines.get(0);
}
}
/**
* Run a command and get the resulting lines of output.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final List<String> multiLine(String cmd, IComputerSystem sys, ISession.Timeout readTimeout) throws Exception {
return multiLine(cmd, null, null, sys, sys.getTimeout(readTimeout));
}
/**
* Run a command and get the resulting lines of output, using the specified environment.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final List<String> multiLine(String cmd, String[] env, IComputerSystem sys, ISession.Timeout readTimeout) throws Exception {
return multiLine(cmd, env, null, sys, sys.getTimeout(readTimeout));
}
/**
* Run a command and get the resulting lines of output, using the specified environment and start directory.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final List<String> multiLine(String cmd, String[] env, String dir, IComputerSystem sys, ISession.Timeout readTimeout) throws Exception {
return multiLine(cmd, env, dir, sys, sys.getTimeout(readTimeout));
}
/**
* Run a command and get the resulting lines of output.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final List<String> multiLine(String cmd, IComputerSystem sys, long readTimeout) throws Exception {
return multiLine(cmd, null, null, sys, readTimeout);
}
/**
* Run a command and get the resulting lines of output, using the specified environment.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final List<String> multiLine(String cmd, String[] env, IComputerSystem sys, long readTimeout) throws Exception {
return multiLine(cmd, env, null, sys, readTimeout);
}
/**
* Run a command and get the resulting lines of output, using the specified environment.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final List<String> multiLine(String cmd, String[] env, String dir, IComputerSystem sys, long readTimeout) throws Exception {
return execData(cmd, env, dir, sys, readTimeout).getLines();
}
/**
* Run a command and get the resulting lines of output, using the specified environment. This command assumes that
* there will be a large volume of output from the command, so it will pipe the output to a file, transfer the file
* locally (if sys is a remote session), and then return an iterator that reads lines from the local file.
* When the end of the iterator is reached, the local file is deleted.
*
* @since 1.0.1
*/
public static final Iterator<String> manyLines(String cmd, String[] env, IUnixSession sys) throws Exception {
return manyLines(cmd, env, new ErrorLogger(sys), sys, sys.getTimeout(ISession.Timeout.XL));
}
/**
* Pass in a custom timeout to the manyLines command.
*
* @param timeout Specifies the maximum time that the command should take to finish executing.
*
* @since 1.3
*/
public static final Iterator<String> manyLines(String cmd, String[] env, IUnixSession sys, ISession.Timeout timeout) throws Exception {
return manyLines(cmd, env, sys, sys.getTimeout(timeout));
}
/**
* Pass in a custom timeout to the manyLines command.
*
* @param timeout Specifies the maximum time that the command should take to finish executing.
*
* @since 1.3
*/
public static final Iterator<String> manyLines(String cmd, String[] env, IUnixSession sys, long timeout) throws Exception {
return manyLines(cmd, env, new ErrorLogger(sys), sys, timeout);
}
/**
* Pass in a custom error stream handler to the manyLines command.
*
* @param timeout Specifies the maximum time that the command should take to finish executing.
*
* @since 1.3
*/
public static final Iterator<String> manyLines(String cmd, String[] env, IReaderHandler errHandler, IUnixSession sys, ISession.Timeout timeout)
throws Exception {
return manyLines(cmd, env, errHandler, sys, sys.getTimeout(timeout));
}
/**
* Pass in a custom error stream handler to the manyLines command, with a custom timeout.
*
* @param timeout Specifies the maximum time that the command should take to finish executing.
*
* @since 1.3
*/
public static final Iterator<String> manyLines(String cmd, String[] env, IReaderHandler errHandler, IUnixSession sys, long timeout) throws Exception {
// If no filesystem is available, then implement using execData.
if (sys.getFilesystem() == null) {
ExecData ed = execData(cmd, env, null, sys, timeout);
errHandler.handle(new SimpleReader(new ByteArrayInputStream(ed.getError()), sys.getLogger()));
return ed.getLines().iterator();
}
// Modify the command to redirect output to a temp file (compressed)
IFile remoteTemp = sys.getFilesystem().createTempFile("cmd", null, null);
String tempPath = remoteTemp.getPath();
if ((cmd.indexOf(";") != -1 || cmd.indexOf("&&") != -1) && !cmd.startsWith("(") && !cmd.endsWith(")")) {
// Multiple comands have to be grouped, or only the last one's output will be redirected.
cmd = new StringBuffer("(").append(cmd).append(")").toString();
}
switch(sys.getFlavor()) {
case HPUX:
cmd = new StringBuffer(cmd).append(" | /usr/contrib/bin/gzip > ").append(tempPath).toString();
break;
default:
cmd = new StringBuffer(cmd).append(" | gzip > ").append(tempPath).toString();
break;
}
// Execute the command, and monitor the size of the output file
FileMonitor mon = new FileMonitor(sys.getFilesystem(), tempPath);
JSAFSystem.getTimer().schedule(mon, 15000, 15000);
try {
BufferHandler out = new BufferHandler();
BufferHandler err = new BufferHandler();
exec(cmd, null, null, sys, timeout, out, err);
byte[] buff = err.getData();
if (buff.length > 0) {
errHandler.handle(new SimpleReader(new ByteArrayInputStream(buff), sys.getLogger()));
} else {
// Since stdout has been redirected to a file, and we've already attempted to process the buffered
// output from stderr, any data contained by the output buffer must be stderr output that's been
// directed for whatever reason to the stdout stream.
errHandler.handle(new SimpleReader(new ByteArrayInputStream(out.getData()), sys.getLogger()));
}
} finally {
mon.cancel();
JSAFSystem.getTimer().purge();
}
// Create and return a reader/Iterator<String> based on a local cache file
if (ISession.LOCALHOST.equals(sys.getHostname())) {
return new ReaderIterator(new File(tempPath));
} else {
File tempDir = sys.getWorkspace() == null ? new File(System.getProperty("user.home")) : sys.getWorkspace();
File localTemp = File.createTempFile("cmd", null, tempDir);
Streams.copy(remoteTemp.getInputStream(), new FileOutputStream(localTemp), true);
try {
remoteTemp.delete();
} catch (IOException e) {
try {
if (remoteTemp.exists()) {
exec(String.format("rm -f '%1$s'", remoteTemp.getPath()), sys, ISession.Timeout.S);
}
} catch (Exception e2) {
sys.getLogger().warn(Message.getMessage(Message.ERROR_EXCEPTION), e2);
}
}
return new ReaderIterator(localTemp);
}
}
/**
* Run a command and get the resulting ExecData, using the specified environment.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final ExecData execData(String cmd, String[] env, IComputerSystem sys, long readTimeout) throws Exception {
return execData(cmd, env, null, sys, readTimeout);
}
/**
* Run a command and get the resulting ExecData, using the specified environment and start directory.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @since 1.0
*/
public static final ExecData execData(String cmd, String[] env, String dir, IComputerSystem sys, long readTimeout) throws Exception {
SafeCLI cli = new SafeCLI(cmd, env, dir, sys, readTimeout);
cli.exec();
return cli.getResult();
}
/**
* Run a command, using the specified output and error handlers.
*
* @param readTimeout Specifies the maximum amount of time the command should go without producing any character output.
*
* @see IReaderHandler
* @since 1.3
*/
public static final void exec(String cmd, String[] env, String dir, IComputerSystem sys, long readTimeout, IReaderHandler out, IReaderHandler err)
throws Exception {
new SafeCLI(cmd, env, dir, sys, readTimeout).exec(out, err);
}
/**
* A container for information resulting from the execution of a process.
*
* @since 1.0
*/
public class ExecData {
int exitCode;
byte[] data, err;
ExecData() {
exitCode = -1;
data = null;
err = null;
}
/**
* Get the final (i.e., if there were retries) exit code of the process.
*
* @since 1.0
*/
public int getExitCode() {
return exitCode;
}
/**
* Get the raw data collected from the process stdout.
*
* @since 1.0
*/
public byte[] getData() {
return data;
}
/**
* Get the raw data collected from the process stderr.
*
* @since 1.3
*/
public byte[] getError() {
return err;
}
/**
* Guaranteed to have at least one entry.
*
* @since 1.0
*/
public List<String> getLines() throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
in.mark(data.length);
Charset encoding = Strings.ASCII;
try {
encoding = Streams.detectEncoding(in);
} catch (IOException e) {
in.reset();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
List<String> lines = new ArrayList<String>();
String line = null;
while((line = reader.readLine()) != null) {
lines.add(line);
}
if (lines.size() == 0) {
sys.getLogger().debug(Message.WARNING_MISSING_OUTPUT, cmd, exitCode, data.length);
lines.add("");
}
return lines;
}
}
// Private
private static int counter = 0;
private String cmd, dir;
private String[] env;
private IComputerSystem sys;
private ExecData result;
private long readTimeout;
private int execRetries = 0;
private SafeCLI(String cmd, String[] env, String dir, IComputerSystem sys, long readTimeout) throws Exception {
this.cmd = cmd;
this.env = env;
this.dir = dir;
this.sys = sys;
this.readTimeout = readTimeout;
execRetries = sys.getProperties().getIntProperty(IComputerSystem.PROP_EXEC_RETRIES);
result = new ExecData();
}
private ExecData getResult() {
return result;
}
private void exec(IReaderHandler outputHandler, IReaderHandler errorHandler) throws Exception {
boolean success = false;
for (int attempt=1; !success; attempt++) {
IProcess p = null;
PerishableReader reader = null;
HandlerThread errThread = null;
try {
p = sys.createProcess(cmd, env, dir);
p.start();
reader = PerishableReader.newInstance(p.getInputStream(), readTimeout);
reader.setLogger(sys.getLogger());
if (errorHandler == null) {
errThread = new HandlerThread(DevNull, "pipe to /dev/null");
errThread.start(PerishableReader.newInstance(p.getErrorStream(), sys.getTimeout(ISession.Timeout.XL)));
} else {
errThread = new HandlerThread(errorHandler, "stderr reader");
errThread.start(PerishableReader.newInstance(p.getErrorStream(), readTimeout));
}
outputHandler.handle(reader);
p.waitFor(sys.getTimeout(ISession.Timeout.M));
result.exitCode = p.exitValue();
success = true;
} catch (IOException e) {
if (e instanceof InterruptedIOException || e instanceof EOFException || e instanceof SocketException) {
if (attempt > execRetries) {
throw new Exception(Message.getMessage(Message.ERROR_PROCESS_RETRY, cmd, attempt), e);
} else {
// the process has hung up, so kill it
p.destroy();
p = null;
sys.getLogger().info(Message.STATUS_PROCESS_RETRY, cmd);
}
} else {
throw e;
}
} catch (SessionException e) {
if (attempt > execRetries) {
sys.getLogger().warn(Message.ERROR_PROCESS_RETRY, cmd, attempt);
throw e;
} else {
sys.getLogger().warn(Message.ERROR_SESSION_INTEGRITY, e.getMessage());
sys.getLogger().info(Message.STATUS_PROCESS_RETRY, cmd);
sys.disconnect();
}
} finally {
if (p != null && p.isRunning()) {
p.destroy();
} else {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
if (errThread != null) {
try {
errThread.close();
} catch (IOException e) {
}
}
}
if (errThread != null && errThread.isAlive()) {
try {
errThread.join(sys.getTimeout(ISession.Timeout.S));
} catch (InterruptedException e) {
}
}
}
}
}
private void exec() throws Exception {
BufferHandler out = new BufferHandler();
BufferHandler err = new BufferHandler();
exec(out, err);
result.data = out.getData();
result.err = err.getData();
}
/**
* An IReaderHandler that simply buffers data.
*/
static class BufferHandler implements IReaderHandler {
private ByteArrayOutputStream buff;
byte[] getData() {
if (buff == null) {
return null;
} else {
return buff.toByteArray();
}
}
public void handle(IReader reader) throws IOException {
buff = new ByteArrayOutputStream();
byte[] b = new byte[512];
int len = 0;
while((len = reader.getStream().read(b)) > 0) {
buff.write(b, 0, len);
}
buff.close();
}
}
class HandlerThread implements Runnable {
Thread thread;
String name;
IReader reader;
IReaderHandler handler;
HandlerThread(IReaderHandler handler, String name) {
this.handler = handler;
this.name = "ReaderHandler " + counter++ + ": " + name;
}
void start(IReader reader) throws IllegalStateException {
if (thread == null || !thread.isAlive()) {
this.reader = reader;
thread = new Thread(Thread.currentThread().getThreadGroup(), this, name);
thread.start();
} else {
throw new IllegalStateException("running");
}
}
void close() throws IOException {
if (thread != null && thread.isAlive()) {
thread.interrupt();
}
reader.close();
}
boolean isAlive() {
return thread.isAlive();
}
void join() throws InterruptedException {
join(0L);
}
void join(long millis) throws InterruptedException {
thread.join(millis);
}
// Implement Runnable
public void run() {
try {
handler.handle(reader);
} catch (IOException e) {
}
}
}
static class ErrorLogger implements IReaderHandler {
private IComputerSystem sys;
ErrorLogger(IComputerSystem sys) {
this.sys = sys;
}
// Implement IReaderHandler
public void handle(IReader reader) throws IOException {
String line = null;
while((line = reader.readLine()) != null) {
if (line.length() > 0) {
sys.getLogger().warn(Message.WARNING_COMMAND_OUTPUT, line);
}
}
}
}
static class FileMonitor extends TimerTask {
private IFilesystem fs;
private String path;
FileMonitor(IFilesystem fs, String path) {
this.fs = fs;
this.path = path;
fs.getLogger().debug(Message.STATUS_COMMAND_OUTPUT_TEMP, path);
}
public void run() {
try {
long len = fs.getFile(path, IFile.Flags.READVOLATILE).length();
fs.getLogger().info(Message.STATUS_COMMAND_OUTPUT_PROGRESS, len);
} catch (IOException e) {
}
}
}
static class ReaderIterator implements Iterator<String> {
File file;
BufferedReader reader;
String next = null;
ReaderIterator(File file) throws IOException {
this.file = file;
try {
InputStream in = new GZIPInputStream(new FileInputStream(file));
reader = new BufferedReader(new InputStreamReader(in, Strings.UTF8));
} catch (IOException e) {
close();
throw e;
}
}
@Override
protected void finalize() {
close();
}
// Implement Iterator<String>
public boolean hasNext() {
if (next == null) {
try {
next = next();
return true;
} catch (NoSuchElementException e) {
close();
return false;
}
} else {
return true;
}
}
public String next() throws NoSuchElementException {
if (next == null) {
try {
if ((next = reader.readLine()) == null) {
try {
reader.close();
} catch (IOException e) {
}
throw new NoSuchElementException();
}
} catch (IOException e) {
throw new NoSuchElementException(e.getMessage());
}
}
String temp = next;
next = null;
return temp;
}
public void remove() {
throw new UnsupportedOperationException();
}
// Private
/**
* Clean up the remote or local file.
*/
private void close() {
if (file != null) {
if (file.delete()) {
file = null;
}
}
}
}
} |
package org.exist.xquery.functions.util;
import java.util.Random;
import org.exist.dom.QName;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.DoubleValue;
import org.exist.xquery.value.IntegerValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.Type;
public class RandomFunction extends BasicFunction
{
public final static FunctionSignature signatures[] = {
new FunctionSignature(
new QName("random", UtilModule.NAMESPACE_URI, UtilModule.PREFIX),
"Returns a random number between 0.0 and 1.0",
null,
new SequenceType(Type.DOUBLE, Cardinality.EXACTLY_ONE)),
new FunctionSignature(
new QName("random", UtilModule.NAMESPACE_URI, UtilModule.PREFIX),
"Returns a random number between 0 and $a",
new SequenceType[] {
new SequenceType(Type.INTEGER, Cardinality.EXACTLY_ONE)
},
new SequenceType(Type.INTEGER, Cardinality.EXACTLY_ONE))
};
public RandomFunction(XQueryContext context, FunctionSignature signature)
{
super(context, signature);
}
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException
{
Random rndGen = new Random();
if(getArgumentCount() == 0)
{
return new DoubleValue(rndGen.nextDouble());
}
else
{
IntegerValue upper = (IntegerValue)args[0].convertTo(Type.INTEGER);
return new IntegerValue(rndGen.nextInt(upper.getInt()));
}
}
} |
package org.jamocha.dn.compiler;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toSet;
import static org.jamocha.util.ToArray.toArray;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.jamocha.dn.ConstructCache.Defrule;
import org.jamocha.dn.ConstructCache.Defrule.TranslatedPath;
import org.jamocha.filter.Path;
import org.jamocha.filter.PathCollector;
import org.jamocha.filter.PathFilter;
import org.jamocha.filter.PathFilter.PathFilterElement;
import org.jamocha.languages.common.ConditionalElement;
import org.jamocha.languages.common.ConditionalElement.AndFunctionConditionalElement;
import org.jamocha.languages.common.ConditionalElement.ExistentialConditionalElement;
import org.jamocha.languages.common.ConditionalElement.InitialFactConditionalElement;
import org.jamocha.languages.common.ConditionalElement.NegatedExistentialConditionalElement;
import org.jamocha.languages.common.ConditionalElement.NotFunctionConditionalElement;
import org.jamocha.languages.common.ConditionalElement.OrFunctionConditionalElement;
import org.jamocha.languages.common.ConditionalElement.SharedConditionalElementWrapper;
import org.jamocha.languages.common.ConditionalElement.TestConditionalElement;
import org.jamocha.languages.common.DefaultConditionalElementsVisitor;
import org.jamocha.languages.common.SingleFactVariable;
/**
* Collect all PathFilters inside all children of an OrFunctionConditionalElement, returning a List
* of Lists. Each inner List contains the PathFilters of one child.
*
* @author Fabian Ohler <fabian.ohler1@rwth-aachen.de>
* @author Christoph Terwelp <christoph.terwelp@rwth-aachen.de>
*/
@RequiredArgsConstructor
public class PathFilterConsolidator implements DefaultConditionalElementsVisitor {
private final Defrule rule;
@Getter
private List<Defrule.TranslatedPath> translateds = null;
public List<Defrule.TranslatedPath> consolidate() {
assert rule.getCondition().getConditionalElements().size() == 1;
return rule.getCondition().getConditionalElements().get(0).accept(this).translateds;
}
@Override
public void defaultAction(final ConditionalElement ce) {
// If we are to need the initial fact variable, there should be one within the CE
final SingleFactVariable initialFactVariable = SomeInitialFactFinder.find(ce);
// If there is no OrFunctionConditionalElement just proceed with the CE as it were
// the only child of an OrFunctionConditionalElement.
translateds =
Collections.singletonList(NoORsPFC.consolidate(rule, initialFactVariable, ce));
}
@Override
public void visit(final OrFunctionConditionalElement ce) {
// If we are to need the initial fact variable, there should be one within the CE
final SingleFactVariable initialFactVariable = SomeInitialFactFinder.find(ce);
// For each child of the OrCE ...
this.translateds =
ce.getChildren().stream().map(child ->
// ... collect all PathFilters in the child
NoORsPFC.consolidate(rule, initialFactVariable, child))
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* @author Fabian Ohler <fabian.ohler1@rwth-aachen.de>
* @author Christoph Terwelp <christoph.terwelp@rwth-aachen.de>
*/
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
static class NoORsPFC implements DefaultConditionalElementsVisitor {
private final SingleFactVariable initialFactVariable;
private final Map<SingleFactVariable, Path> paths;
private final boolean negated;
@Getter
private List<PathFilter> pathFilters = new ArrayList<>();
private NoORsPFC(final SingleFactVariable initialFactVariable,
final Map<SingleFactVariable, Path> paths) {
this(initialFactVariable, paths, false);
}
public static TranslatedPath consolidate(final Defrule rule,
final SingleFactVariable initialFactVariable, final ConditionalElement ce) {
final Map<SingleFactVariable, Path> pathMap = FactVariableCollector.collectPaths(ce);
final Set<Path> allPaths = new HashSet<>(pathMap.values());
final NoORsPFC instance = new NoORsPFC(initialFactVariable, pathMap).collect(ce);
final List<PathFilter> pathFilters = instance.getPathFilters();
final Set<Path> collectedPaths =
(pathFilters.isEmpty() ? Collections.<Path> emptySet() : PathCollector
.newHashSet()
.collectOnlyNonExistential(pathFilters.get(pathFilters.size() - 1))
.getPaths().stream().flatMap((p) -> p.getJoinedWith().stream())
.collect(toSet()));
final TranslatedPath translated = rule.newTranslated(pathFilters, pathMap);
if (collectedPaths.containsAll(allPaths)) {
return translated;
}
allPaths.addAll(collectedPaths);
pathFilters.add(new PathFilter(new PathFilter.DummyPathFilterElement(toArray(allPaths,
Path[]::new))));
return translated;
}
private <T extends ConditionalElement> NoORsPFC collect(final T ce) {
return ce.accept(this);
}
static List<PathFilter> processExistentialCondition(
final SingleFactVariable initialFactVariable, final ConditionalElement ce,
final Map<SingleFactVariable, Path> fact2Path, final boolean isPositive) {
// Collect the existential FactVariables and corresponding paths from the existentialCE
final Map<SingleFactVariable, Path> existentialFact2Path =
FactVariableCollector.collectPaths(ce);
// combine existential FactVariables and Paths with non existential ones for PathFilter
// generation
final Map<SingleFactVariable, Path> combinedFact2Path =
new HashMap<SingleFactVariable, Path>(fact2Path);
combinedFact2Path.putAll(existentialFact2Path);
// Only existential Paths without Variables
final Set<Path> existentialPaths = new HashSet<>(existentialFact2Path.values());
// Generate PathFilters from CE (recurse)
final List<PathFilter> filters =
new NoORsPFC(initialFactVariable, combinedFact2Path).collect(ce)
.getPathFilters();
// Collect all used Paths for every PathFilter
final Map<PathFilter, Set<Path>> filter2Paths =
filters.stream().collect(
Collectors.toMap(Function.identity(), filter -> PathCollector
.newHashSet().collect(filter).getPaths()));
// Split PathFilters into those only using existential Paths and those also using non
// existential Paths
final Map<Boolean, LinkedList<PathFilter>> tmp =
filters.stream().collect(
Collectors.partitioningBy(filter -> existentialPaths
.containsAll(filter2Paths.get(filter)),
toCollection(LinkedList::new)));
final LinkedList<PathFilter> pureExistentialFilters = tmp.get(Boolean.TRUE);
final LinkedList<PathFilter> nonPureExistentialFilters = tmp.get(Boolean.FALSE);
// Add all pureExistentialFilters to result List because they don't have to be combined
// or ordered
final List<PathFilter> resultFilters = new ArrayList<>(pureExistentialFilters);
if (nonPureExistentialFilters.isEmpty()) {
// if there are only existential filters, append one combining them with an initial
// fact path
resultFilters.add(new PathFilter(isPositive, existentialPaths,
new PathFilter.DummyPathFilterElement(fact2Path.computeIfAbsent(
initialFactVariable,
(x) -> new Path(initialFactVariable.getTemplate())))));
return resultFilters;
}
// Construct HashMap from Paths to Filters
final Map<Path, Set<PathFilter>> path2Filters = new HashMap<>();
filter2Paths.forEach((pathFilter, paths) -> paths.forEach(path -> path2Filters
.computeIfAbsent(path, x -> new HashSet<>()).add(pathFilter)));
// Find connected components of the existential Paths
final Map<Path, Set<Path>> joinedExistentialPaths = new HashMap<>();
final Set<Path> processedExistentialPaths = new HashSet<>();
// While there are unjoined Filters continue
while (!pureExistentialFilters.isEmpty()) {
// Take one arbitrary filter
final LinkedList<PathFilter> collectedFilters =
new LinkedList<>(Collections.singletonList(pureExistentialFilters.poll()));
Set<PathFilter> newCollectedFilters = new HashSet<>(collectedFilters);
final Set<Path> collectedPaths = new HashSet<>();
// While we found new PathFilters in the last round
while (!newCollectedFilters.isEmpty()) {
// search for all Paths used by the new Filters
final Set<Path> newCollectedPaths =
newCollectedFilters.stream().flatMap(f -> filter2Paths.get(f).stream())
.collect(Collectors.toSet());
// removed already known paths
newCollectedPaths.removeAll(collectedPaths);
// add the new ones to the collect set
collectedPaths.addAll(newCollectedPaths);
// search for all filters containing the new found paths
newCollectedFilters =
newCollectedPaths.stream()
.flatMap(path -> path2Filters.get(path).stream())
.collect(toSet());
// remove already known filters
newCollectedFilters.removeAll(collectedFilters);
// add them all to the collect set
collectedFilters.addAll(newCollectedFilters);
// remove them from the set of unassigned filters
pureExistentialFilters.removeAll(newCollectedFilters);
}
// save the connected components
for (final Path path : collectedPaths) {
joinedExistentialPaths.put(path, collectedPaths);
}
// mark the paths as processed
processedExistentialPaths.addAll(collectedPaths);
}
// Combine nonPureExistentialFilters if necessary and add them to result List
while (!nonPureExistentialFilters.isEmpty()) {
final List<PathFilter> collectedFilters =
new ArrayList<>(Collections.singletonList(nonPureExistentialFilters.poll()));
Set<PathFilter> newCollectedFilters = new HashSet<>(collectedFilters);
final Set<Path> collectedExistentialPaths = new HashSet<>();
while (!newCollectedFilters.isEmpty()) {
// search for all existential Paths used by the new Filters
final Set<Path> newCollectedExistentialPaths =
newCollectedFilters.stream()
.flatMap((final PathFilter f) -> filter2Paths.get(f).stream())
.collect(toSet());
newCollectedExistentialPaths.retainAll(existentialPaths);
// removed already known paths
newCollectedExistentialPaths.removeAll(collectedExistentialPaths);
// add all existential paths already joined with the new paths
{
final Set<Path> toDeplete = new HashSet<>(newCollectedExistentialPaths);
while (!toDeplete.isEmpty()) {
final Path path = toDeplete.iterator().next();
final Set<Path> joined = joinedExistentialPaths.get(path);
toDeplete.removeAll(joined);
newCollectedExistentialPaths.addAll(joined);
}
}
// add the new ones to the collect set
collectedExistentialPaths.addAll(newCollectedExistentialPaths);
// search for all filters containing the new found paths
newCollectedFilters =
newCollectedExistentialPaths.stream()
.flatMap(path -> path2Filters.get(path).stream())
.collect(toSet());
newCollectedFilters.retainAll(nonPureExistentialFilters);
// remove already known filters
newCollectedFilters.removeAll(collectedFilters);
// add them all to the collect set
collectedFilters.addAll(newCollectedFilters);
// remove them from the set of unassigned filters
nonPureExistentialFilters.removeAll(newCollectedFilters);
}
final List<PathFilterElement> filterElements = new ArrayList<>();
for (final PathFilter filter : collectedFilters) {
filterElements.addAll(Arrays.asList(filter.getFilterElements()));
}
resultFilters.add(new PathFilter(isPositive, collectedExistentialPaths, toArray(
filterElements, PathFilterElement[]::new)));
processedExistentialPaths.addAll(collectedExistentialPaths);
}
{
// if not all paths within this existential CE have been used in some test, add a
// dummy filter element to have them joined, too
final Set<Path> unprocessedExistentialPaths = new HashSet<>(existentialPaths);
unprocessedExistentialPaths.removeAll(processedExistentialPaths);
if (!unprocessedExistentialPaths.isEmpty()) {
resultFilters.add(new PathFilter(isPositive, unprocessedExistentialPaths,
new PathFilter.DummyPathFilterElement()));
}
}
return resultFilters;
}
@Override
public void defaultAction(final ConditionalElement ce) {
// Just ignore. InittialFactCEs and TemplateCEs already did their job during
// FactVariable collection
}
@Override
public void visit(final AndFunctionConditionalElement ce) {
pathFilters =
ce.getChildren()
.stream()
// Process all children CEs
.map(child -> child.accept(new NoORsPFC(initialFactVariable, paths))
.getPathFilters())
// merge Lists
.flatMap(List::stream).collect(Collectors.toCollection(ArrayList::new));
}
@Override
public void visit(final OrFunctionConditionalElement ce) {
throw new Error("There should not be any OrFunctionCEs at this level.");
}
@Override
public void visit(final ExistentialConditionalElement ce) {
assert ce.getChildren().size() == 1;
this.pathFilters =
processExistentialCondition(initialFactVariable, ce.getChildren().get(0),
paths, true);
}
@Override
public void visit(final NegatedExistentialConditionalElement ce) {
assert ce.getChildren().size() == 1;
this.pathFilters =
processExistentialCondition(initialFactVariable, ce.getChildren().get(0),
paths, false);
}
@Override
public void visit(final NotFunctionConditionalElement ce) {
assert ce.getChildren().size() == 1;
// Call a PathFilterCollector for the child of the NotFunctionCE with toggled negated
// flag.
this.pathFilters =
ce.getChildren().get(0)
.accept(new NoORsPFC(initialFactVariable, paths, !negated))
.getPathFilters();
}
@Override
public void visit(final SharedConditionalElementWrapper ce) {
// Just ignore the SharedCEWrapper and continue with the inner CE.
// TODO maybe it will be required to mark the resulting PathFilters for later
// optimization
ce.getCe().accept(this);
}
@Override
public void visit(final TestConditionalElement ce) {
this.pathFilters.add(new PathFilter(new PathFilter.PathFilterElement(
SymbolToPathTranslator.translate(ce.getPredicateWithArguments(), paths))));
}
}
private static class SomeInitialFactFinder implements DefaultConditionalElementsVisitor {
SingleFactVariable initialFactVariable = null;
static SingleFactVariable find(final ConditionalElement ce) {
return ce.accept(new SomeInitialFactFinder()).initialFactVariable;
}
@Override
public void defaultAction(final ConditionalElement ce) {
ce.getChildren().forEach(c -> c.accept(this));
}
@Override
public void visit(final InitialFactConditionalElement ce) {
this.initialFactVariable = ce.getInitialFactVariable();
}
}
} |
package org.jitsi.videobridge;
import java.beans.*;
import java.lang.ref.*;
import java.util.*;
import java.util.concurrent.*;
import org.jitsi.impl.neomedia.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.event.*;
import org.jitsi.util.*;
import org.jitsi.util.event.*;
/**
* Represents the speech activity of the <tt>Endpoint</tt>s in a
* <tt>Conference</tt>. Identifies the dominant speaker <tt>Endpoint</tt> in the
* <tt>Conference</tt> and maintains an ordered list of the <tt>Endpoint</tt>s
* in the <tt>Conference</tt> sorted by recentness of speaker domination and/or
* speech activity.
*
* @author Lyubomir Marinov
*/
class ConferenceSpeechActivity
extends PropertyChangeNotifier
implements PropertyChangeListener
{
/**
* The name of the <tt>ConferenceSpeechActivity</tt> property
* <tt>dominantEndpoint</tt> which identifies the dominant speaker in a
* multipoint conference.
*/
public static final String DOMINANT_ENDPOINT_PROPERTY_NAME
= ConferenceSpeechActivity.class.getName() + ".dominantEndpoint";
/**
* The name of the <tt>ConferenceSpeechActivity</tt> property
* <tt>endpoints</tt> which lists the <tt>Endpoint</tt>s
* participating in/contributing to a <tt>Conference</tt>.
*/
public static final String ENDPOINTS_PROPERTY_NAME
= ConferenceSpeechActivity.class.getName() + ".endpoints";
/**
* The pool of threads utilized by <tt>ConferenceSpeechActivity</tt>.
*/
private static final ExecutorService executorService
= ExecutorUtils.newCachedThreadPool(true, "ConferenceSpeechActivity");
/**
* The <tt>Logger</tt> used by the <tt>ConferenceSpeechActivity</tt> class
* and its instances to print debug information.
*/
private static final Logger logger
= Logger.getLogger(ConferenceSpeechActivity.class);
/**
* The <tt>ActiveSpeakerChangedListener</tt> which listens to
* {@link #activeSpeakerDetector} about changes in the active/dominant
* speaker in this multipoint conference.
*/
private final ActiveSpeakerChangedListener activeSpeakerChangedListener
= new ActiveSpeakerChangedListener()
{
@Override
public void activeSpeakerChanged(long ssrc)
{
ConferenceSpeechActivity.this.activeSpeakerChanged(
ssrc);
}
};
/**
* The <tt>ActiveSpeakerDetector</tt> which detects/identifies the
* active/dominant speaker in {@link #conference}.
*/
private ActiveSpeakerDetector activeSpeakerDetector;
/**
* The <tt>Object</tt> which synchronizes the access to
* {@link #activeSpeakerDetector}.
*/
private final Object activeSpeakerDetectorSyncRoot = new Object();
/**
* The <tt>Conference</tt> for which this instance represents the speech
* activity of its <tt>Endpoint</tt>s. The <tt>Conference</tt> is weakly
* referenced because <tt>ConferenceSpeechActivity</tt> is a part of
* <tt>Conference</tt> and the operation of the former in the absence of the
* latter is useless.
*/
private final WeakReference<Conference> conference;
/**
* The <tt>Endpoint</tt> which is the dominant speaker in
* {@link #conference}.
*/
private WeakReference<Endpoint> dominantEndpoint;
/**
* The indicator which signals to {@link #eventDispatcher} that
* {@link #dominantEndpoint} was changed and <tt>eventDispatcher</tt> may
* have to fire an event.
*/
private boolean dominantEndpointChanged = false;
/**
* The ordered list of <tt>Endpoint</tt>s participating in
* {@link #conference} with the dominant (speaker) <tt>Endpoint</tt> at the
* beginning of the list i.e. the dominant speaker history.
*/
private List<WeakReference<Endpoint>> endpoints;
/**
* The indicator which signals to {@link #eventDispatcher} that the
* <tt>endpoints</tt> set of {@link #conference} was changed and
* <tt>eventDispatcher</tt> may have to fire an event.
*/
private boolean endpointsChanged = false;
/**
* The background/daemon thread which fires <tt>PropertyChangeEvent</tt>s to
* notify registered <tt>PropertyChangeListener</tt>s about changes of the
* values of the <tt>dominantEndpoint</tt> and <tt>endpoints</tt> properties
* of this instance.
*/
private EventDispatcher eventDispatcher;
/**
* The time in milliseconds of the last execution of
* {@link #eventDispatcher}.
*/
private long eventDispatcherTime;
/**
* The <tt>Object</tt> used to synchronize the access to the state of this
* instance.
*/
private final Object syncRoot = new Object();
/**
* Initializes a new <tt>ConferenceSpeechActivity</tt> instance which is to
* represent the speech activity in a specific <tt>Conference</tt>.
*
* @param conference the <tt>Conference</tt> whose speech activity is to be
* represented by the new instance
*/
public ConferenceSpeechActivity(Conference conference)
{
this.conference = new WeakReference<Conference>(conference);
/*
* The PropertyChangeListener will weakly reference this instance and
* will unregister itself from the conference sooner or later.
*/
conference.addPropertyChangeListener(
new WeakReferencePropertyChangeListener(this));
}
/**
* Notifies this multipoint conference that the active/dominant speaker has
* changed to one identified by a specific synchronization source
* identifier/SSRC.
*
* @param ssrc the synchronization source identifier/SSRC of the new
* active/dominant speaker
*/
private void activeSpeakerChanged(long ssrc)
{
Conference conference = getConference();
if (conference != null)
{
if (logger.isTraceEnabled())
{
logger.trace(
"The dominant speaker in conference "
+ conference.getID() + " is now the SSRC " + ssrc
+ ".");
}
Endpoint endpoint
= conference.findEndpointByReceiveSSRC(ssrc, MediaType.AUDIO);
boolean maybeStartEventDispatcher = false;
synchronized (syncRoot)
{
if (endpoint == null)
{
/*
* We will NOT automatically elect a new dominant speaker
* HERE.
*/
maybeStartEventDispatcher = true;
}
else
{
Endpoint dominantEndpoint = getDominantEndpoint();
if (!endpoint.equals(dominantEndpoint))
{
this.dominantEndpoint
= new WeakReference<Endpoint>(endpoint);
maybeStartEventDispatcher = true;
}
}
if (maybeStartEventDispatcher)
{
dominantEndpointChanged = true;
maybeStartEventDispatcher();
}
}
}
}
/**
* Notifies this <tt>ConferenceSpeechActivity</tt> that an
* <tt>EventDispatcher</tt> has permanently stopped executing in its
* associated background thread. If the specified <tt>EventDispatcher</tt>
* is {@link #eventDispatcher}, this instance will note that it no longer
* has an associated (executing) <tt>EventDispatcher</tt>.
*
* @param eventDispatcher the <tt>EventDispatcher</tt> which has exited
*/
private void eventDispatcherExited(EventDispatcher eventDispatcher)
{
synchronized (syncRoot)
{
if (this.eventDispatcher == eventDispatcher)
{
this.eventDispatcher = eventDispatcher;
eventDispatcherTime = 0;
}
}
}
/**
* Gets the <tt>ActiveSpeakerDetector</tt> which detects/identifies the
* active/dominant speaker in this <tt>Conference</tt>.
*
* @return the <tt>ActiveSpeakerDetector</tt> which detects/identifies the
* active/dominant speaker in this <tt>Conference</tt>
*/
private ActiveSpeakerDetector getActiveSpeakerDetector()
{
ActiveSpeakerDetector activeSpeakerDetector;
boolean addActiveSpeakerChangedListener = false;
synchronized (activeSpeakerDetectorSyncRoot)
{
activeSpeakerDetector = this.activeSpeakerDetector;
if (activeSpeakerDetector == null)
{
this.activeSpeakerDetector
= activeSpeakerDetector
= new ActiveSpeakerDetectorImpl();
addActiveSpeakerChangedListener = true;
}
}
/*
* Listen to the activeSpeakerDetector about speaker switches in order
* to track the dominant speaker in the multipoint conference.
*/
if (addActiveSpeakerChangedListener && (getConference() != null))
{
activeSpeakerDetector.addActiveSpeakerChangedListener(
activeSpeakerChangedListener);
}
return activeSpeakerDetector;
}
/**
* Gets the <tt>Conference</tt> whose speech activity is represented by this
* instance.
*
* @return the <tt>Conference</tt> whose speech activity is represented by
* this instance
*/
private Conference getConference()
{
Conference conference = this.conference.get();
if (conference == null)
{
/*
* The Conference has expired so there is no point to listen to
* ActiveSpeakerDetector. Remove the activeSpeakerChangedListener
* for the purposes of completeness, not because it is strictly
* necessary.
*/
ActiveSpeakerDetector activeSpeakerDetector
= this.activeSpeakerDetector;
if (activeSpeakerDetector != null)
{
activeSpeakerDetector.removeActiveSpeakerChangedListener(
activeSpeakerChangedListener);
}
}
return conference;
}
/**
* Gets the <tt>Endpoint</tt> which is the dominant speaker in the
* multipoint conference represented by this instance.
*
* @return the <tt>Endpoint</tt> which is the dominant speaker in the
* multipoint conference represented by this instance or <tt>null</tt>
*/
public Endpoint getDominantEndpoint()
{
Endpoint dominantEndpoint;
synchronized (syncRoot)
{
if (this.dominantEndpoint == null)
{
dominantEndpoint = null;
}
else
{
dominantEndpoint = this.dominantEndpoint.get();
if (dominantEndpoint == null)
this.dominantEndpoint = null;
}
}
return dominantEndpoint;
}
/**
* Gets the ordered list of <tt>Endpoint</tt>s participating in the
* multipoint conference represented by this instance with the dominant
* (speaker) <tt>Endpoint</tt> at the beginning of the list i.e. the
* dominant speaker history.
*
* @return the ordered list of <tt>Endpoint</tt>s participating in the
* multipoint conference represented by this instance with the dominant
* (speaker) <tt>Endpoint</tt> at the beginning of the list
*/
public List<Endpoint> getEndpoints()
{
List<Endpoint> ret;
synchronized (syncRoot)
{
/*
* The list of Endpoints of this instance is ordered by recentness
* of speaker domination and/or speech activity. The list of
* Endpoints of Conference is ordered by recentness of Endpoint
* instance initialization. The list of Endpoints of this instance
* is initially populated with the Endpoints of the conference.
*/
if (endpoints == null)
{
Conference conference = getConference();
if (conference == null)
{
endpoints = new ArrayList<WeakReference<Endpoint>>();
}
else
{
List<Endpoint> conferenceEndpoints
= conference.getEndpoints();
endpoints
= new ArrayList<WeakReference<Endpoint>>(
conferenceEndpoints.size());
for (Endpoint endpoint : conferenceEndpoints)
endpoints.add(new WeakReference<Endpoint>(endpoint));
}
}
// The return value is the list of Endpoints of this instance.
ret = new ArrayList<Endpoint>(endpoints.size());
for (Iterator<WeakReference<Endpoint>> i = endpoints.iterator();
i.hasNext();)
{
Endpoint endpoint = i.next().get();
if (endpoint != null)
ret.add(endpoint);
}
}
return ret;
}
/**
* Notifies this instance that a new audio level was received or measured by
* a <tt>Channel</tt> for an RTP stream with a specific synchronization
* source identifier/SSRC.
*
* @param channel the <tt>Channel</tt> which received or measured the new
* audio level for the RTP stream identified by the specified <tt>ssrc</tt>
* @param ssrc the synchronization source identifier/SSRC of the RTP stream
* for which a new audio level was received or measured by the specified
* <tt>channel</tt>
* @param level the new audio level which was received or measured by the
* specified <tt>channel</tt> for the RTP stream with the specified
* <tt>ssrc</tt>
*/
public void levelChanged(Channel channel, long ssrc, int level)
{
// ActiveSpeakerDetector
ActiveSpeakerDetector activeSpeakerDetector
= getActiveSpeakerDetector();
if (activeSpeakerDetector != null)
activeSpeakerDetector.levelChanged(ssrc, level);
// Endpoint
Endpoint endpoint = channel.getEndpoint();
if (endpoint != null)
endpoint.audioLevelChanged(channel, ssrc, level);
}
/**
* Starts a new <tt>EventDispatcher</tt> or notifies an existing one to fire
* events to registered listeners about changes of the values of the
* <tt>dominantEndpoint</tt> and <tt>endpoints</tt> properties of this
* instance.
*/
private void maybeStartEventDispatcher()
{
synchronized (syncRoot)
{
if (this.eventDispatcher == null)
{
EventDispatcher eventDispatcher = new EventDispatcher(this);
boolean scheduled = false;
this.eventDispatcher = eventDispatcher;
eventDispatcherTime = 0;
try
{
executorService.execute(eventDispatcher);
scheduled = true;
}
finally
{
if (!scheduled && (this.eventDispatcher == eventDispatcher))
{
this.eventDispatcher = null;
eventDispatcherTime = 0;
}
}
}
else
{
syncRoot.notify();
}
}
}
/**
* Notifies this instance that there was a change in the value of a property
* of an object in which this instance is interested.
*
* @param ev a <tt>PropertyChangeEvent</tt> which specifies the object of
* interest, the name of the property and the old and new values of that
* property
*/
@Override
public void propertyChange(PropertyChangeEvent ev)
{
Conference conference = getConference();
if ((conference != null)
&& conference.equals(ev.getSource())
&& Conference.ENDPOINTS_PROPERTY_NAME.equals(
ev.getPropertyName()))
{
synchronized (syncRoot)
{
endpointsChanged = true;
maybeStartEventDispatcher();
}
}
}
/**
* Runs in the background thread of {@link #eventDispatcher} to possibly
* fire events.
*
* @param eventDispatcher the <tt>EventDispatcher</tt> which is calling back
* to this instance
* @return <tt>true</tt> if the specified <tt>eventDispatcher</tt> is to
* continue with its next iteration and call back to this instance again or
* <tt>false</tt> to have the specified <tt>eventDispatcher</tt> break out
* of its loop and not call back to this instance again
*/
private boolean runInEventDispatcher(EventDispatcher eventDispatcher)
{
boolean endpointsChanged = false;
boolean dominantEndpointChanged = false;
synchronized (syncRoot)
{
if (this.eventDispatcher != eventDispatcher)
return false;
long now = System.currentTimeMillis();
if (!this.dominantEndpointChanged && !this.endpointsChanged)
{
long wait = 100 - (now - eventDispatcherTime);
if (wait > 0)
{
try
{
syncRoot.wait(wait);
}
catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
}
return true;
}
}
eventDispatcherTime = now;
/*
* Synchronize the set of Endpoints of this instance with the set of
* Endpoints of the conference.
*/
Conference conference = getConference();
if (conference == null)
return false;
List<Endpoint> conferenceEndpoints = conference.getEndpoints();
if (endpoints == null)
{
endpoints
= new ArrayList<WeakReference<Endpoint>>(
conferenceEndpoints.size());
for (Endpoint endpoint : conferenceEndpoints)
{
endpoints.add(new WeakReference<Endpoint>(endpoint));
}
endpointsChanged = true;
}
else
{
/*
* Remove the Endpoints of this instance which are no longer in
* the conference.
*/
for (Iterator<WeakReference<Endpoint>> i = endpoints.iterator();
i.hasNext();)
{
Endpoint endpoint = i.next().get();
if (endpoint == null)
{
i.remove();
endpointsChanged = true;
}
else if (conferenceEndpoints.contains(endpoint))
{
conferenceEndpoints.remove(endpoint);
}
else
{
i.remove();
endpointsChanged = true;
}
}
/*
* Add the Endpoints of the conference which are not in this
* instance yet.
*/
if (conferenceEndpoints.size() != 0)
{
for (Endpoint endpoint : conferenceEndpoints)
{
endpoints.add(new WeakReference<Endpoint>(endpoint));
}
endpointsChanged = true;
}
}
this.endpointsChanged = false;
/*
* Make sure that the dominantEndpoint is at the top of the list of
* the Endpoints of this instance.
*/
Endpoint dominantEndpoint = getDominantEndpoint();
if (dominantEndpoint != null)
{
int dominantEndpointIndex = -1;
for (int i = 0, count = endpoints.size(); i < count; ++i)
{
if (dominantEndpoint.equals(endpoints.get(i).get()))
{
dominantEndpointIndex = i;
break;
}
}
if ((dominantEndpointIndex != -1)
&& (dominantEndpointIndex != 0))
{
WeakReference<Endpoint> weakReference
= endpoints.remove(dominantEndpointIndex);
endpoints.add(0, weakReference);
endpointsChanged = true;
}
}
/*
* The activeSpeakerDetector decides when the dominantEndpoint
* changes at the time of this writing.
*/
if (this.dominantEndpointChanged)
{
dominantEndpointChanged = true;
this.dominantEndpointChanged = false;
}
}
if (endpointsChanged)
firePropertyChange(ENDPOINTS_PROPERTY_NAME, null, null);
if (dominantEndpointChanged)
firePropertyChange(DOMINANT_ENDPOINT_PROPERTY_NAME, null, null);
return true;
}
/**
* Represents a background/daemon thread which fires events to registered
* listeners notifying about changes in the values of the
* <tt>dominantEndpoint</tt> and <tt>endpoints</tt> properties of a specific
* <tt>ConferenceSpeechActivity</tt>. Because <tt>EventDispatcher</tt> runs
* in a background/daemon <tt>Thread</tt> which is a garbage collection
* root, it keeps a <tt>WeakReference</tt> to the specified
* <tt>ConferenceSpeechActivity</tt> in order to not accidentally prevent
* its garbage collection.
*/
private static class EventDispatcher
implements Runnable
{
/**
* The <tt>ConferenceSpeechActivity</tt> which has initialized this
* instance and on behalf of which this instance is to fire events to
* registered listeners in the background.
*/
private final WeakReference<ConferenceSpeechActivity> owner;
/**
* Initializes a new <tt>EventDispatcher</tt> instance which is to fire
* events in the background to registered listeners on behalf of a
* specific <tt>ConferenceSpeechActivity</tt>.
*
* @param owner the <tt>ConferenceSpeechActivity</tt> which is
* initializing the new instance
*/
public EventDispatcher(ConferenceSpeechActivity owner)
{
this.owner = new WeakReference<ConferenceSpeechActivity>(owner);
}
/**
* Runs in a background/daemon thread and notifies registered listeners
* about changes in the values of the <tt>dominantEndpoint</tt> and
* <tt>endpoints</tt> properties of {@link #owner}.
*/
@Override
public void run()
{
try
{
do
{
ConferenceSpeechActivity owner = this.owner.get();
if ((owner == null) || !owner.runInEventDispatcher(this))
break;
}
while (true);
}
finally
{
/*
* Notify the ConferenceSpeechActivity that this EventDispatcher
* has exited in order to allow the former to forget about the
* latter.
*/
ConferenceSpeechActivity owner = this.owner.get();
if (owner != null)
owner.eventDispatcherExited(this);
}
}
}
} |
package org.jmist.packages;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.jmist.framework.AbstractParallelizableJob;
import org.jmist.framework.Material;
import org.jmist.framework.TaskWorker;
import org.jmist.framework.measurement.CollectorSphere;
import org.jmist.framework.measurement.Photometer;
import org.jmist.framework.reporting.ProgressMonitor;
import org.jmist.toolkit.SphericalCoordinates;
/**
* @author bkimmel
*
*/
public final class PhotometerParallelizableJob extends
AbstractParallelizableJob implements Serializable {
public PhotometerParallelizableJob(Material specimen,
SphericalCoordinates[] incidentAngles, double[] wavelengths,
long samplesPerMeasurement, long samplesPerTask, CollectorSphere prototype) {
this.worker = new PhotometerTaskWorker(specimen, prototype);
this.incidentAngles = incidentAngles.clone();
this.wavelengths = wavelengths.clone();
this.samplesPerMeasurement = samplesPerMeasurement;
this.samplesPerTask = samplesPerTask;
this.results = new CollectorSphere[wavelengths.length * incidentAngles.length];
for (int i = 0; i < this.results.length; i++) {
this.results[i] = prototype.clone();
}
}
/*
* (non-Javadoc)
*
* @see org.jmist.framework.ParallelizableJob#getNextTask()
*/
@Override
public Object getNextTask() {
if (!this.isComplete()) {
PhotometerTask task = this.getPhotometerTask(this.nextMeasurementIndex);
if (++this.nextMeasurementIndex >= this.results.length) {
this.outstandingSamplesPerMeasurement += this.samplesPerTask;
this.nextMeasurementIndex = 0;
}
return task;
} else {
return null;
}
}
private PhotometerTask getPhotometerTask(int measurementIndex) {
return new PhotometerTask(
this.getIncidentAngle(measurementIndex),
this.getWavelength(measurementIndex),
this.samplesPerTask,
measurementIndex
);
}
private SphericalCoordinates getIncidentAngle(int measurementIndex) {
return this.incidentAngles[measurementIndex / this.wavelengths.length];
}
private double getWavelength(int measurementIndex) {
return this.wavelengths[measurementIndex % this.wavelengths.length];
}
/* (non-Javadoc)
* @see org.jmist.framework.ParallelizableJob#submitTaskResults(java.lang.Object, java.lang.Object, org.jmist.framework.reporting.ProgressMonitor)
*/
@Override
public void submitTaskResults(Object task, Object results,
ProgressMonitor monitor) {
PhotometerTask info = (PhotometerTask) task;
CollectorSphere collector = (CollectorSphere) results;
this.results[info.measurementIndex].merge(collector);
}
/* (non-Javadoc)
* @see org.jmist.framework.ParallelizableJob#isComplete()
*/
@Override
public boolean isComplete() {
return this.outstandingSamplesPerMeasurement >= this.samplesPerMeasurement;
}
/* (non-Javadoc)
* @see org.jmist.framework.ParallelizableJob#writeJobResults(java.util.zip.ZipOutputStream)
*/
@Override
public void writeJobResults(ZipOutputStream stream) throws IOException {
stream.putNextEntry(new ZipEntry("photometer.csv"));
PrintStream out = new PrintStream(stream);
this.writeColumnHeadings(out);
for (int incidentAngleIndex = 0, n = 0; incidentAngleIndex < this.incidentAngles.length; incidentAngleIndex++) {
SphericalCoordinates incidentAngle = this.incidentAngles[incidentAngleIndex];
for (int wavelengthIndex = 0; wavelengthIndex < this.wavelengths.length; wavelengthIndex++, n++) {
double wavelength = this.wavelengths[wavelengthIndex];
CollectorSphere collector = this.results[n];
for (int sensor = 0; sensor < collector.sensors(); sensor++) {
SphericalCoordinates exitantAngle = collector.getSensorCenter(sensor);
double solidAngle = collector.getSensorSolidAngle(sensor);
double projectedSolidAngle = collector.getSensorProjectedSolidAngle(sensor);
long hits = collector.hits(sensor);
double reflectance = (double) hits / (double) this.outstandingSamplesPerMeasurement;
out.printf(
"%f,%f,%e,%d,%f,%f,%f,%f,%d,%d,%f,%e,%e\n",
incidentAngle.polar(),
incidentAngle.azimuthal(),
wavelength,
sensor,
exitantAngle.polar(),
exitantAngle.azimuthal(),
solidAngle,
projectedSolidAngle,
this.outstandingSamplesPerMeasurement,
hits,
reflectance,
reflectance / projectedSolidAngle,
reflectance / solidAngle
);
}
}
}
stream.closeEntry();
}
/**
* Writes the CSV column headings to the result stream.
* @param out The <code>PrintStream</code> to write the column headings to.
*/
private void writeColumnHeadings(PrintStream out) {
out.print("\"Incident Polar (radians)\",");
out.print("\"Incident Azimuthal (radians)\",");
out.print("\"Wavelength (m)\",");
out.print("\"Sensor\",");
out.print("\"Exitant Polar (radians)\",");
out.print("\"Exitant Azimuthal (radians)\",");
out.print("\"Solid Angle (sr)\",");
out.print("\"Projected Solid Angle (sr)\",");
out.print("\"Samples\",");
out.print("\"Hits\",");
out.print("\"Reflectance\",");
out.print("\"BSDF\",");
out.print("\"SPF\"");
out.println();
}
/* (non-Javadoc)
* @see org.jmist.framework.ParallelizableJob#worker()
*/
@Override
public TaskWorker worker() {
return this.worker;
}
private static class PhotometerTask {
public final SphericalCoordinates incident;
public final double wavelength;
public final long samples;
public final int measurementIndex;
public PhotometerTask(SphericalCoordinates incident, double wavelength, long samples, int measurementIndex) {
this.incident = incident;
this.wavelength = wavelength;
this.samples = samples;
this.measurementIndex = measurementIndex;
}
}
private static class PhotometerTaskWorker implements TaskWorker {
/**
* Creates a new <code>PhotometerTaskWorker</code>.
* @param specimen The <code>Material</code> to be measured.
* @param prototype The prototype <code>CollectorSphere</code> from
* which clones are constructed to record hits to.
*/
public PhotometerTaskWorker(Material specimen, CollectorSphere prototype) {
this.specimen = specimen;
this.prototype = prototype;
}
/* (non-Javadoc)
* @see org.jmist.framework.TaskWorker#performTask(java.lang.Object, org.jmist.framework.reporting.ProgressMonitor)
*/
@Override
public Object performTask(Object task, ProgressMonitor monitor) {
CollectorSphere collector = this.prototype.clone();
Photometer photometer = new Photometer(collector);
PhotometerTask info = (PhotometerTask) task;
photometer.setSpecimen(this.specimen);
photometer.setIncidentAngle(info.incident);
photometer.setWavelength(info.wavelength);
photometer.castPhotons(info.samples, monitor);
return collector;
}
/**
* The <code>Material</code> to be measured.
*/
private final Material specimen;
/**
* The prototype <code>CollectorSphere</code> from which clones are
* constructed to record hits to.
*/
private final CollectorSphere prototype;
/**
* Serialization version ID.
*/
private static final long serialVersionUID = -2402548700898513324L;
}
/** The <code>TaskWorker</code> that performs the work for this job. */
private final TaskWorker worker;
private final double[] wavelengths;
private final SphericalCoordinates[] incidentAngles;
private final long samplesPerMeasurement;
private final long samplesPerTask;
private final CollectorSphere[] results;
private int nextMeasurementIndex = 0;
private long outstandingSamplesPerMeasurement = 0;
/**
* Serialization version ID.
*/
private static final long serialVersionUID = 5640925441217948685L;
} |
package org.loklak.harvester.strategy;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.eclipse.jetty.util.ConcurrentHashSet;
import org.loklak.api.search.SearchServlet;
import org.loklak.api.search.SuggestServlet;
import org.loklak.data.DAO;
import org.loklak.harvester.PushThread;
import org.loklak.harvester.TwitterScraper;
import org.loklak.harvester.TwitterScraper.TwitterTweet;
import org.loklak.objects.QueryEntry;
import org.loklak.objects.ResultList;
import org.loklak.objects.Timeline;
import org.loklak.objects.Timeline.Order;
import org.loklak.tools.DateParser;
public class ClassicHarvester implements Harvester {
private final static int FETCH_MIN = 20;
private final static int HITS_LIMIT_4_QUERIES = 20;
private final static int MAX_PENDING = 300; // this could be much larger but we don't want to cache too many of these
private final static int MAX_HARVESTED = 10000; // just to prevent a memory leak with possible OOM after a long time we flush that cache after a while
private final static Random random = new Random(System.currentTimeMillis());
private final ExecutorService executor = Executors.newFixedThreadPool(1);
private LinkedHashSet<String> pendingQueries = new LinkedHashSet<>();
private ConcurrentLinkedDeque<String> pendingContext = new ConcurrentLinkedDeque<>();
private Set<String> harvestedContext = new ConcurrentHashSet<>();
private int hitsOnBackend = 100;
public void checkContext(Timeline tl, boolean front) {
for (TwitterTweet tweet: tl) {
for (String user: tweet.getMentions()) checkContext("from:" + user, front);
for (String hashtag: tweet.getHashtags()) checkContext(hashtag, front);
}
}
public void checkContext(String s, boolean front) {
if (!front && pendingContext.size() > MAX_PENDING) return; // queue is full
if (!harvestedContext.contains(s) && !pendingContext.contains(s)) {
if (front) pendingContext.addFirst(s); else pendingContext.addLast(s);
}
while (pendingContext.size() > MAX_PENDING) pendingContext.removeLast();
if (harvestedContext.size() > MAX_HARVESTED) harvestedContext.clear();
}
public int harvest() {
String[] backend = DAO.getBackend();
if (random.nextInt(100) != 0 && hitsOnBackend < HITS_LIMIT_4_QUERIES && pendingQueries.size() == 0 && pendingContext.size() > 0) {
// harvest using the collected keys instead using the queries
String q = pendingContext.removeFirst();
harvestedContext.add(q);
Timeline tl = TwitterScraper.search(q, Timeline.Order.CREATED_AT, true, true, 400);
if (tl == null || tl.size() == 0) return -1;
// find content query strings and store them in the context cache
checkContext(tl, false);
DAO.log("retrieval of " + tl.size() + " new messages for q = " + q + ", scheduled push; pendingQueries = " + pendingQueries.size() + ", pendingContext = " + pendingContext.size() + ", harvestedContext = " + harvestedContext.size());
return tl.size();
}
// load more queries if pendingQueries is empty
if (pendingQueries.size() == 0) {
try {
int fetch_random = Math.min(100, Math.max(FETCH_MIN, hitsOnBackend / 10));
ResultList<QueryEntry> rl = SuggestServlet.suggest(backend, "", "query", fetch_random * 5, "asc", "retrieval_next", DateParser.getTimezoneOffset(), null, "now", "retrieval_next", fetch_random);
for (QueryEntry qe: rl) {
pendingQueries.add(qe.getQuery());
}
hitsOnBackend = (int) rl.getHits();
DAO.log("got " + rl.size() + " suggestions for harvesting from " + hitsOnBackend + " in backend");
if (hitsOnBackend == 0) {
// the backend does not have any new query words for this time.
if (pendingContext.size() == 0) {
// try to fill the pendingContext using a matchall-query from the cache
Timeline tl = SearchServlet.search(backend, "", Timeline.Order.CREATED_AT, "cache", 100, 0, SearchServlet.backend_hash, 60000);
checkContext(tl, false);
}
// if we still don't have any context, we are a bit helpless and hope that this situation
// will be better in the future. To prevent that this is called excessively fast, do a pause.
if (pendingContext.size() == 0) try {Thread.sleep(10000);} catch (InterruptedException e) {}
}
} catch (IOException e) {
DAO.severe(e.getMessage());
try {Thread.sleep(10000);} catch (InterruptedException e1) {} // if the remote peer is down, throttle down
}
}
if (pendingQueries.size() == 0) return -1;
// take one of the pending queries or pending context and load the tweets
String q = "";
try {
q = pendingQueries.iterator().next();
pendingQueries.remove(q);
pendingContext.remove(q);
harvestedContext.add(q);
Timeline tl = TwitterScraper.search(q, Timeline.Order.CREATED_AT, true, false, 400);
if (tl == null || tl.size() == 0) {
// even if the result is empty, we must push this to the backend to make it possible that the query gets an update
if (tl == null) tl = new Timeline(Order.CREATED_AT);
tl.setQuery(q);
PushThread pushThread = new PushThread(backend, tl);
DAO.log( "starting push to backend; pendingQueries = " + pendingQueries.size() + ", pendingContext = " +
pendingContext.size() + ", harvestedContext = " + harvestedContext.size());
executor.execute(pushThread);
return -1;
}
// find content query strings and store them in the context cache
checkContext(tl, true);
// if we loaded a pending query, push results to backpeer right now
tl.setQuery(q);
PushThread pushThread = new PushThread(backend, tl);
DAO.log( "starting push to backend; pendingQueries = " + pendingQueries.size() + ", pendingContext = " +
pendingContext.size() + ", harvestedContext = " + harvestedContext.size());
executor.execute(pushThread);
return tl.size();
} catch (NoSuchElementException e) {
// this is a concurrency glitch. just do nothing.
return -1;
}
}
public void stop() {
executor.shutdown();
}
} |
package org.pentaho.di.core.database;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.row.ValueMetaInterface;
/**
* Contains DB2 specific information through static final members
*
* @author Matt
* @since 11-mrt-2005
*/
public class CacheDatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface
{
/**
* Construct a new database connections. Note that not all these parameters are not allways mandatory.
*
* @param name The database name
* @param access The type of database access
* @param host The hostname or IP address
* @param db The database name
* @param port The port on which the database listens.
* @param user The username
* @param pass The password
*/
public CacheDatabaseMeta(String name, String access, String host, String db, String port, String user, String pass)
{
super(name, access, host, db, port, user, pass);
}
public CacheDatabaseMeta()
{
}
public String getDatabaseTypeDesc()
{
return "CACHE";
}
public String getDatabaseTypeDescLong()
{
return "Intersystems Cache";
}
/**
* @return Returns the databaseType.
*/
public int getDatabaseType()
{
return DatabaseMeta.TYPE_DATABASE_CACHE;
}
public int[] getAccessTypeList()
{
return new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC, DatabaseMeta.TYPE_ACCESS_JNDI };
}
public int getDefaultDatabasePort()
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_NATIVE) return 1972;
return -1;
}
public boolean supportsSetCharacterStream()
{
return false;
}
public boolean isFetchSizeSupported()
{
return false;
}
/**
* @return Whether or not the database can use auto increment type of fields (pk)
*/
public boolean supportsAutoInc()
{
return false;
}
public String getDriverClass()
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC)
{
return "sun.jdbc.odbc.JdbcOdbcDriver";
}
else
{
return "com.intersys.jdbc.CacheDriver";
}
}
public String getURL(String hostname, String port, String databaseName)
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC)
{
return "jdbc:odbc:"+databaseName;
}
else
{
return "jdbc:Cache://"+hostname+":"+port+"/"+databaseName;
}
}
/**
* Generates the SQL statement to add a column to the specified table
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param use_autoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to add a column to the specified table
*/
public String getAddColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
return "ALTER TABLE "+tablename+" ADD COLUMN ( "+getFieldDefinition(v, tk, pk, use_autoinc, true, false)+" ) ";
}
/**
* Generates the SQL statement to drop a column from the specified table
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param use_autoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to drop a column from the specified table
*/
public String getDropColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
return "ALTER TABLE "+tablename+" DROP COLUMN "+v.getName()+Const.CR;
}
/**
* Generates the SQL statement to modify a column in the specified table
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param use_autoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to modify a column in the specified table
*/
public String getModifyColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
return "ALTER TABLE "+tablename+" ALTER COLUMN "+getFieldDefinition(v, tk, pk, use_autoinc, true, false);
}
public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr)
{
String retval="";
String fieldname = v.getName();
int length = v.getLength();
int precision = v.getPrecision();
if (add_fieldname) retval+=fieldname+" ";
int type = v.getType();
switch(type)
{
case ValueMetaInterface.TYPE_DATE : retval+="TIMESTAMP"; break;
case ValueMetaInterface.TYPE_BOOLEAN: retval+="CHAR(1)"; break;
case ValueMetaInterface.TYPE_NUMBER :
case ValueMetaInterface.TYPE_INTEGER:
case ValueMetaInterface.TYPE_BIGNUMBER:
if (fieldname.equalsIgnoreCase(tk)) // Technical & primary key : see at bottom
{
retval+="DECIMAL";
}
else
{
if ( length<0 || precision<0 )
{
retval+="DOUBLE";
}
else if ( precision>0 || length>9)
{
retval+="DECIMAL("+length;
if (precision>0)
{
retval+=", "+precision;
}
retval+=")";
}
else // Precision == 0 && length<=9
{
retval+="INT";
}
}
break;
case ValueMetaInterface.TYPE_STRING: // CLOBs are just VARCHAR in the Cache database: can be very large!
retval+="VARCHAR";
if (length>0)
{
retval+="("+length+")";
}
break;
default:
retval+=" UNKNOWN";
break;
}
if (add_cr) retval+=Const.CR;
return retval;
}
public String[] getUsedLibraries()
{
return new String[] { "CacheDB.jar" };
}
} |
package org.pentaho.di.core.lifecycle;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettlePluginException;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.plugins.LifecyclePluginType;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginTypeListener;
import org.pentaho.di.core.plugins.PluginRegistry;
public class LifecycleSupport implements LifecycleListener
{
private Set<LifecycleListener> lifeListeners;
private boolean started;
private LifeEventHandler handler;
public LifecycleSupport()
{
lifeListeners = Collections.synchronizedSet(new HashSet<LifecycleListener>());
final PluginRegistry registry = PluginRegistry.getInstance();
List<PluginInterface> plugins = registry.getPlugins(LifecyclePluginType.class);
for (PluginInterface plugin : plugins) {
try {
lifeListeners.add( registry.loadClass(plugin, LifecycleListener.class) );
} catch(KettleException e) {
LogChannel.GENERAL.logError("Unexpected error loading class for plugin "+plugin.getName(), e);
}
}
registry.addPluginListener(LifecyclePluginType.class, new PluginTypeListener() {
public void pluginAdded(Object serviceObject) {
LifecycleListener listener = null;
try {
listener = (LifecycleListener) PluginRegistry.getInstance().loadClass((PluginInterface) serviceObject);
} catch (KettlePluginException e) {
e.printStackTrace();
return;
}
lifeListeners.add(listener);
if(started){
try {
listener.onStart(handler);
} catch (LifecycleException e) {
e.printStackTrace();
}
}
}
public void pluginRemoved(Object serviceObject) {
lifeListeners.remove(serviceObject);
}
public void pluginChanged(Object serviceObject) {}
});
}
public void onStart(LifeEventHandler handler) throws LifecycleException
{
// Caching the last handler and the fact that start has been called. This would cause problems if onStart
// is called by more than one handler.
this.handler = handler;
started = true;
for (LifecycleListener listener : lifeListeners)
listener.onStart(handler);
}
public void onExit(LifeEventHandler handler) throws LifecycleException
{
for (LifecycleListener listener : lifeListeners)
listener.onExit(handler);
}
} |
package org.pentaho.di.job.entries.delay;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.integerValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.longValidator;
import java.util.List;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryType;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.w3c.dom.Node;
/**
* Job entry type to sleep for a time. It uses a piece of javascript to do this.
*
* @author Samatar
* @since 21-02-2007
*/
public class JobEntryDelay extends JobEntryBase implements Cloneable, JobEntryInterface
{
static private String DEFAULT_MAXIMUM_TIMEOUT = "0"; //$NON-NLS-1$
private String maximumTimeout; // maximum timeout in seconds
public int scaleTime;
public JobEntryDelay(String n)
{
super(n, ""); //$NON-NLS-1$
setID(-1L);
setJobEntryType(JobEntryType.DELAY);
}
public JobEntryDelay()
{
this(""); //$NON-NLS-1$
}
public JobEntryDelay(JobEntryBase jeb)
{
super(jeb);
}
public Object clone()
{
JobEntryDelay je = (JobEntryDelay) super.clone();
return je;
}
public String getXML()
{
StringBuffer retval = new StringBuffer(200);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("maximumTimeout", maximumTimeout)); //$NON-NLS-1$//$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("scaletime", scaleTime)); //$NON-NLS-1$ //$NON-NLS-2$
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, Repository rep) throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases);
maximumTimeout = XMLHandler.getTagValue(entrynode, "maximumTimeout"); //$NON-NLS-1$
scaleTime = Integer.parseInt(XMLHandler.getTagValue(entrynode, "scaletime")); //$NON-NLS-1$
} catch (Exception e)
{
throw new KettleXMLException(Messages.getString("JobEntryDelay.UnableToLoadFromXml.Label"), e); //$NON-NLS-1$
}
}
public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases) throws KettleException
{
try
{
super.loadRep(rep, id_jobentry, databases);
maximumTimeout = rep.getJobEntryAttributeString(id_jobentry, "maximumTimeout"); //$NON-NLS-1$
scaleTime = (int) rep.getJobEntryAttributeInteger(id_jobentry, "scaletime"); //$NON-NLS-1$
} catch (KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("JobEntryDelay.UnableToLoadFromRepo.Label") //$NON-NLS-1$
+ id_jobentry, dbe);
}
}
// Save the attributes of this job entry
public void saveRep(Repository rep, long id_job) throws KettleException
{
try
{
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "maximumTimeout", maximumTimeout); //$NON-NLS-1$
rep.saveJobEntryAttribute(id_job, getID(), "scaletime", scaleTime); //$NON-NLS-1$
} catch (KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("JobEntryDelay.UnableToSaveToRepo.Label") + id_job, dbe); //$NON-NLS-1$
}
}
/**
* Execute this job entry and return the result.
* In this case it means, just set the result boolean in the Result class.
* @param previousResult The result of the previous execution
* @return The Result of the execution.
*/
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
Result result = previousResult;
result.setResult(false);
int Multiple;
String Waitscale;
// Scale time
if (scaleTime == 0)
{
// Second
Multiple = 1000;
Waitscale = Messages.getString("JobEntryDelay.SScaleTime.Label"); //$NON-NLS-1$
} else if (scaleTime == 1)
{
// Minute
Multiple = 60000;
Waitscale = Messages.getString("JobEntryDelay.MnScaleTime.Label"); //$NON-NLS-1$
} else
{
// Hour
Multiple = 3600000;
Waitscale = Messages.getString("JobEntryDelay.HrScaleTime.Label"); //$NON-NLS-1$
}
try
{
// starttime (in seconds ,Minutes or Hours)
long timeStart = System.currentTimeMillis() / Multiple;
long iMaximumTimeout = Const.toInt(getMaximumTimeout(), Const.toInt(DEFAULT_MAXIMUM_TIMEOUT, 0));
if (log.isDetailed())
{
log.logDetailed(toString(), Messages.getString("JobEntryDelay.LetsWaitFor.Label", String //$NON-NLS-1$
.valueOf(iMaximumTimeout), String.valueOf(Waitscale)));
}
boolean continueLoop = true;
// Sanity check on some values, and complain on insanity
if (iMaximumTimeout < 0)
{
iMaximumTimeout = Const.toInt(DEFAULT_MAXIMUM_TIMEOUT, 0);
log.logBasic(toString(), Messages.getString(
"JobEntryDelay.MaximumTimeReset.Label", String.valueOf(iMaximumTimeout), String.valueOf(Waitscale))); //$NON-NLS-1$
}
// TODO don't contineously loop, but sleeping would be better.
while (continueLoop && !parentJob.isStopped())
{
// Update Time value
long now = System.currentTimeMillis() / Multiple;
// Let's check the limit time
if ((iMaximumTimeout > 0) && (now >= (timeStart + iMaximumTimeout)))
{
// We have reached the time limit
if (log.isDetailed())
{
log.logDetailed(toString(), Messages.getString("JobEntryDelay.WaitTimeIsElapsed.Label")); //$NON-NLS-1$
}
continueLoop = false;
result.setResult(true);
}
else
{
try {
Thread.sleep(100);
} catch (Exception e) {
// handling this exception would be kind of silly.
}
}
}
} catch (Exception e)
{
// We get an exception
result.setResult(false);
log.logError(toString(), "Error : " + e.getMessage()); //$NON-NLS-1$
}
return result;
}
public boolean resetErrorsBeforeExecution()
{
// we should be able to evaluate the errors in
// the previous jobentry.
return false;
}
public boolean evaluates()
{
return true;
}
public boolean isUnconditional()
{
return false;
}
public String getMaximumTimeout()
{
return environmentSubstitute(maximumTimeout);
}
public void setMaximumTimeout(String s)
{
maximumTimeout = s;
}
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta)
{
andValidator().validate(this, "maximumTimeout", remarks, putValidators(longValidator())); //$NON-NLS-1$
andValidator().validate(this, "scaleTime", remarks, putValidators(integerValidator())); //$NON-NLS-1$
}
public int getScaleTime()
{
return scaleTime;
}
public void setScaleTime(int scaleTime)
{
this.scaleTime = scaleTime;
}
} |
package org.prx.android.playerhater;
import java.io.FileDescriptor;
import java.io.IOException;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class PlayerHaterService extends Service implements OnErrorListener,
OnPreparedListener {
protected static final String TAG = "PlayerHater/Service";
protected static final int PROGRESS_UPDATE = 9747244;
protected static final int NOTIFICATION_NU = 9747245;
protected NotificationManager mNotificationManager;
protected Class<?> mNotificationIntentClass;
protected RemoteViews mNotificationView;
protected int mNotificationIcon;
protected String nowPlayingString;
protected String nowPlayingUrl;
protected FileDescriptor nowPlayingFile;
protected int nowPlayingType;
protected static final int URL = 55;
protected static final int FILE = 66;
private MediaPlayerWrapper mediaPlayer;
private UpdateProgressRunnable updateProgressRunner;
private Thread updateProgressThread;
private PlayerListenerManager playerListenerManager;
private OnErrorListener mOnErrorListener;
private OnPreparedListener mOnPreparedListener;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message m) {
switch (m.what) {
case PROGRESS_UPDATE:
if (mOnSeekbarChangeListener != null)
mOnSeekbarChangeListener.onProgressChanged(null, m.arg1,
false);
break;
default:
onHandlerMessage(m);
}
}
};
private OnSeekBarChangeListener mOnSeekbarChangeListener;
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if (playerListenerManager == null)
createPlayerListenerManager();
if (mediaPlayer == null)
createMediaPlayer();
if (updateProgressRunner == null)
createUpdateProgressRunner();
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
/*
* We override a couple of methods in PlayerHaterBinder so that we can see
* MediaPlayer onError and onPrepared events
*/
@Override
public IBinder onBind(Intent arg0) {
return new PlayerHaterBinder(this, playerListenerManager) {
@Override
public void setOnErrorListener(OnErrorListener listener) {
mOnErrorListener = listener;
}
@Override
public void setOnPreparedListener(OnPreparedListener listener) {
mOnPreparedListener = listener;
}
@Override
public void setOnProgressChangeListener(
OnSeekBarChangeListener listener) {
mOnSeekbarChangeListener = listener;
}
};
}
/*
* Oh, snap we're blowing up!
*/
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (updateProgressThread != null && updateProgressThread.isAlive()) {
mHandler.removeCallbacks(updateProgressRunner);
Log.d(TAG, "INTERRUPTING THE UPDATE PROGRESS THREAD");
updateProgressThread.interrupt();
updateProgressThread = null;
}
if (mOnErrorListener != null) {
return mOnErrorListener.onError(mp, what, extra);
}
return false;
}
/*
* We register ourselves to listen to the onPrepared event so we can start
* playing immediately.
*/
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
if (mOnPreparedListener != null) {
mOnPreparedListener.onPrepared(mp);
}
}
public boolean pause() throws IllegalStateException {
mediaPlayer.pause();
return true;
}
public void setNotificationIntentActivity(Activity activity) {
mNotificationIntentClass = activity.getClass();
}
public void setNotificationView(int view) {
mNotificationView = new RemoteViews(getPackageName(), view);
}
public int getState() {
return mediaPlayer.getState();
}
public String getNowPlaying() {
return nowPlayingString;
}
public boolean isPlaying() {
return (mediaPlayer.getState() == MediaPlayerWrapper.STARTED);
}
public boolean play(String stream) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException {
nowPlayingType = URL;
nowPlayingString = stream;
nowPlayingUrl = stream;
if (mediaPlayer.getState() != MediaPlayerWrapper.IDLE)
mediaPlayer.reset();
mediaPlayer.setDataSource(nowPlayingUrl);
play();
return true;
}
public boolean play(FileDescriptor fd) throws IllegalStateException,
IllegalArgumentException, SecurityException, IOException {
nowPlayingType = FILE;
nowPlayingString = fd.toString();
nowPlayingFile = fd;
if (mediaPlayer.getState() != MediaPlayerWrapper.IDLE)
mediaPlayer.reset();
mediaPlayer.setDataSource(nowPlayingFile);
return play();
}
public int getDuration() {
try {
return this.mediaPlayer.getDuration();
} catch (IllegalStateException e) {
return 0;
}
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int pos) {
try {
mediaPlayer.seekTo(pos);
} catch (Exception e) {
Log.d(TAG,
"Could not seek -- state is " + this.mediaPlayer.getState());
e.printStackTrace();
}
}
public void rewind() {
try {
int pos = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(pos - 30000);
} catch (Exception e) {
Log.d(TAG, "Could not skip backwards");
e.printStackTrace();
}
}
public void skipForward() {
try {
int pos = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(pos + 30000);
} catch (Exception e) {
Log.d(TAG, "Could not skip forward.");
e.printStackTrace();
}
}
public boolean play() throws IllegalStateException, IOException {
mediaPlayer.prepareAsync();
if (updateProgressThread != null && updateProgressThread.isAlive()) {
mHandler.removeCallbacks(updateProgressRunner);
updateProgressThread.interrupt();
updateProgressThread = null;
}
updateProgressThread = new Thread(updateProgressRunner);
updateProgressThread.start();
return true;
}
public boolean stop() {
mediaPlayer.stop();
return true;
}
/*
* These methods concern the creation of notifications. They should be
* ignored.
*/
protected Notification buildNotification() {
return buildNotification("Playing...", 0);
}
protected Notification buildNotification(int pendingFlag) {
return buildNotification("Playing...", pendingFlag);
}
protected Notification buildNotification(String text) {
return buildNotification(text, 0);
}
protected Notification buildNotification(String text, int pendingFlag) {
Notification notification = new Notification(mNotificationIcon, text,
System.currentTimeMillis());
if (mNotificationIntentClass != null && mNotificationView != null) {
notification.contentView = mNotificationView;
notification.contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, mNotificationIntentClass), pendingFlag);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
}
return notification;
}
/*
* creates a media player (wrapped, of course) and registers the listeners
* for all of the events.
*/
private void createMediaPlayer() {
mediaPlayer = new MediaPlayerWrapper();
playerListenerManager.setMediaPlayer(mediaPlayer);
}
/*
* creates a new update progress runner, which fires events back to this
* class' handler with the message we request and the duration which has
* passed
*/
private void createUpdateProgressRunner() {
updateProgressRunner = new UpdateProgressRunnable(mediaPlayer,
mHandler, PROGRESS_UPDATE);
}
/*
* This class basically just makes sure that we never need to re-bind
* ourselves.
*/
private void createPlayerListenerManager() {
playerListenerManager = new PlayerListenerManager();
playerListenerManager.setOnErrorListener(this);
playerListenerManager.setOnPreparedListener(this);
}
/*
* This should be overridden by subclasses which wish to handle messages
* sent to mHandler without re-implementing the handler. It is a noop by
* default.
*/
protected void onHandlerMessage(Message m) { /* noop */
}
} |
package org.springframework.aop.framework;
import org.aopalliance.intercept.Interceptor;
/**
* Factory for AOP proxies for programmatic use, rather than via a bean
* factory. This class provides a simple way of obtaining and configuring
* AOP proxies in code.
* @since 14-Mar-2003
* @author Rod Johnson
* @version $Id: ProxyFactory.java,v 1.3 2003-10-10 13:09:09 jhoeller Exp $
*/
public class ProxyFactory extends DefaultProxyConfig {
public ProxyFactory() {
}
/**
* Proxy all interfaces of the given target.
*/
public ProxyFactory(Object target) throws AopConfigException {
if (target == null) {
throw new AopConfigException("Can't proxy null object");
}
setInterfaces(AopUtils.getAllInterfaces(target));
addInterceptor(new InvokerInterceptor(target));
}
/**
* No target, only interfaces. Must add interceptors.
*/
public ProxyFactory(Class[] interfaces) {
setInterfaces(interfaces);
}
/**
* Create new proxy according to the settings in this factory.
* Can be called repeatedly. Effect will vary if we've added
* or removed interfaces. Can add and remove "interceptors"
* @return Object
*/
public Object getProxy() {
AopProxy proxy = new AopProxy(this);
return proxy.getProxy();
}
/**
* Create new proxy for the given interface and interceptor.
* Convenience method for creating a proxy for a single interceptor.
* @param proxyInterface the interface that the proxy should implement
* @param interceptor the interceptor that the proxy should invoke
* @return the new proxy
*/
public static Object getProxy(Class proxyInterface, Interceptor interceptor) {
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.addInterface(proxyInterface);
proxyFactory.addInterceptor(interceptor);
return proxyFactory.getProxy();
}
} |
package org.vitrivr.cineast.core.features;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.vitrivr.cineast.core.color.ColorConverter;
import org.vitrivr.cineast.core.color.ReadableLabContainer;
import org.vitrivr.cineast.core.config.ReadableQueryConfig;
import org.vitrivr.cineast.core.data.MultiImage;
import org.vitrivr.cineast.core.data.ReadableFloatVector;
import org.vitrivr.cineast.core.data.score.ScoreElement;
import org.vitrivr.cineast.core.data.segments.SegmentContainer;
import org.vitrivr.cineast.core.features.abstracts.AbstractFeatureModule;
import org.vitrivr.cineast.core.util.ColorUtils;
import org.vitrivr.cineast.core.util.TimeHelper;
public class AverageColor extends AbstractFeatureModule {
public AverageColor() {
super("features_AverageColor", 196f / 4f);
}
private static final Logger LOGGER = LogManager.getLogger();
public static ReadableLabContainer getAvg(MultiImage img) {
int avg = ColorUtils.getAvg(img.getColors());
return ColorConverter.cachedRGBtoLab(avg);
}
@Override
public void processSegment(SegmentContainer shot) {
TimeHelper.tic();
LOGGER.traceEntry();
if (!phandler.idExists(shot.getId())) {
if(shot.getAvgImg()==MultiImage.EMPTY_MULTIIMAGE){
LOGGER.debug("Empty Image, skipping");
LOGGER.traceExit();
}
ReadableLabContainer avg = getAvg(shot.getAvgImg());
persist(shot.getId(), avg);
LOGGER.debug("AverageColor.processShot() done in {}",
TimeHelper.toc());
}
LOGGER.traceExit();
}
@Override
public List<ScoreElement> getSimilar(SegmentContainer sc, ReadableQueryConfig qc) {
LOGGER.traceEntry();
long start = System.currentTimeMillis();
ReadableLabContainer query = getAvg(sc.getAvgImg());
List<ScoreElement> _return = getSimilar(ReadableFloatVector.toArray(query), qc);
LOGGER.debug("AverageColor.getSimilar() done in {}ms", (System.currentTimeMillis() - start));
return LOGGER.traceExit(_return);
}
} |
package io.reactivesocket;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public class ReactiveSocketPerf {
@Benchmark
public void requestResponseHello(Input input) {
Input.client.requestResponse(Input.HELLO_PAYLOAD).subscribe(input.latchedSubscriber);
}
@Benchmark
public void requestStreamHello1000(Input input) {
Input.client.requestStream(Input.HELLO_PAYLOAD).subscribe(input.latchedSubscriber);
}
@State(Scope.Thread)
public static class Input {
/**
* Use to consume values when the test needs to return more than a single value.
*/
public Blackhole bh;
static final ByteBuffer HELLO = ByteBuffer.wrap("HELLO".getBytes());
static final ByteBuffer HELLO_WORLD = ByteBuffer.wrap("HELLO_WORLD".getBytes());
static final ByteBuffer EMPTY = ByteBuffer.allocate(0);
static final Payload HELLO_PAYLOAD = new Payload() {
@Override
public ByteBuffer getMetadata() {
return EMPTY;
}
@Override
public ByteBuffer getData() {
HELLO.position(0);
return HELLO;
}
};
static final Payload HELLO_WORLD_PAYLOAD = new Payload() {
@Override
public ByteBuffer getMetadata() {
return EMPTY;
}
@Override
public ByteBuffer getData() {
HELLO_WORLD.position(0);
return HELLO_WORLD;
}
};
final static PerfTestConnection serverConnection = new PerfTestConnection();
final static PerfTestConnection clientConnection = new PerfTestConnection();
static {
clientConnection.connectToServerConnection(serverConnection);
}
private static Publisher<Payload> HELLO_1 = just(HELLO_WORLD_PAYLOAD);
private static Publisher<Payload> HELLO_1000;
static {
Payload[] ps = new Payload[1000];
for (int i = 0; i < ps.length; i++) {
ps[i] = HELLO_WORLD_PAYLOAD;
}
HELLO_1000 = just(ps);
}
final static ReactiveSocket serverSocket = ReactiveSocket.createResponderAndRequestor(new RequestHandler() {
@Override
public Publisher<Payload> handleRequestResponse(Payload payload) {
return HELLO_1;
}
@Override
public Publisher<Payload> handleRequestStream(Payload payload) {
return HELLO_1000;
}
@Override
public Publisher<Payload> handleRequestSubscription(Payload payload) {
return null;
}
@Override
public Publisher<Void> handleFireAndForget(Payload payload) {
return null;
}
});
final static ReactiveSocket client = ReactiveSocket.createRequestor();
static {
// start both the server and client and monitor for errors
serverSocket.connect(serverConnection).subscribe(new ErrorSubscriber<Void>());
client.connect(clientConnection).subscribe(new ErrorSubscriber<Void>());
}
LatchedSubscriber<Payload> latchedSubscriber;
@Setup
public void setup(Blackhole bh) {
this.bh = bh;
latchedSubscriber = new LatchedSubscriber<Payload>(bh);
}
}
private static Publisher<Payload> just(Payload... ps) {
return new Publisher<Payload>() {
@Override
public void subscribe(Subscriber<? super Payload> s) {
s.onSubscribe(new Subscription() {
int emitted = 0;
@Override
public void request(long n) {
// NOTE: This is not a safe implementation as it assumes synchronous request(n)
for (int i = 0; i < n; i++) {
s.onNext(ps[emitted++]);
if (emitted == ps.length) {
s.onComplete();
}
}
}
@Override
public void cancel() {
}
});
}
};
}
private static class ErrorSubscriber<T> implements Subscriber<T> {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(T t) {
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onComplete() {
}
}
} |
package main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
public class LineSpam {
private static String path = "";
private static String code = "";
private static String input = "";
//Linked List that contains the commands of the code
private static LinkedList<String> commands = new LinkedList<String>();
//ArrayList that contains the labels in the code
private static ArrayList<Label> labels = new ArrayList<Label>();
//arraylist that contains the errors
private static ArrayList<String> errors = new ArrayList<String>();
//array that stores memory. automatically allocates around 270kB or so
private static char[] memory;
/*
* main function. Just acts as a centralized place to execute all the essential functions
* Arguments:
*
* 1. File path
* 2. Input
* 3. bytes of memory allocation
*/
public static void main(String[] args) {
try {
path = args[0];
}catch(NullPointerException|ArrayIndexOutOfBoundsException e) {
System.out.println("Missing necessary arguments!");
System.exit(0);
}
try {
input = args[1];
}catch(NullPointerException|ArrayIndexOutOfBoundsException e) {
input = "";
}
try {
if(args[2].toUpperCase().equals("D")) {
memory = new char[16384];
}else memory = new char[Integer.parseInt(args[2])];
}catch (NullPointerException|ArrayIndexOutOfBoundsException e) {
memory = new char[16384];
}
code = getCode(path);
code = cleanseCode(code);
parse(code);
//finds and neatly packs all the pointers together
commands = findPointers(commands);
//finds and neatly packs all the numerical expressions together
commands = findExpr(commands);
//finds and neatly packs all the boolean expressions together
commands = labelIf(commands);
//printArray(commands);
execute(commands);
}
//This function parses through the code and converts individual tokens to commands
//pretty useful
private static void parse(String code) {
String tok = "";
/*
* The state of the parser;
* 0 = normal
* 1 = number parsing
*/
byte state = 0;
String currentCommand = "";
//runs through each character of code and matches the commands
for(char c : code.toCharArray()) {
tok += c;
if(state == 0) {
if(tok.equals("l[")) {
currentCommand = "POINTER";
tok = "";
commands.add(currentCommand);
currentCommand = "";
}else if(tok.equals("l]")) {
currentCommand = "CLOSE_POINTER";
tok = "";
commands.add(currentCommand);
currentCommand = "";
}else if(tok.equals("ll")) {
currentCommand = "EQUALS";
tok = "";
commands.add(currentCommand);
currentCommand = "";
}else if(tok.equals("l1")) {
currentCommand = "LABEL";
tok = "";
commands.add(currentCommand);
currentCommand = "";
}else if(tok.equals("l|")) {
currentCommand = "GOTO";
tok = "";
commands.add(currentCommand);
currentCommand = "";
}else if(tok.equals("|]")) {
currentCommand = "ADD";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("|[")) {
currentCommand = "SUBTRACT";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("|1")) {
currentCommand = "MULTIPLY";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("|l")) {
currentCommand = "DIVIDE";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("||")) {
currentCommand = "MODULO";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("1]")) {
currentCommand = "INPUT";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("1[")) {
currentCommand = "PRINT";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("1|[")) {
currentCommand = "IF";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("1|]")) {
currentCommand = "END";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("1l")) {
currentCommand = "ELSE";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("111")) {
currentCommand = "COMPARE";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("11[")) {
currentCommand = "LESS_THAN";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("11|")) {
currentCommand = "NOT";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("11]")) {
currentCommand = "GREATER_THAN";
commands.add(currentCommand);
tok = "";
currentCommand = "";
}else if(tok.equals("]") || tok.equals("[")) {
currentCommand = "NUMBER:";
state = 1;
}
}else{
//parses numbers; if the last digit is not [ or ], then the number has ended and a new command has begun
if(tok.substring(tok.length() - 1).equals("l") || tok.substring(tok.length() - 1).equals("|") || tok.substring(tok.length() - 1).equals("1")) {
state = 0;
//the current command becomes NUMBER: followed by the value of the string. that command is then added to the commands list
currentCommand += getValue(tok.substring(0,tok.length() - 1));
commands.add(currentCommand);
currentCommand = "";
tok = tok.substring(tok.length() - 1);
}
}
}
//runs if the last command was a number
if(currentCommand != "") commands.add(currentCommand + getValue(tok));
}
//This function looks through the list of commands, finds pointers, and collects the statements inside pointers for easier use later
private static LinkedList<String> findPointers(LinkedList<String> commands) {
int i = 0;
LinkedList<String> newCommands = new LinkedList<String>();
String newCommand = "";
while(i < commands.size()) {
if(commands.get(i).equals("POINTER")) {
/*
* keeps track of how many pointer instances are "open" per se
*
* example: pointer, pointer, close_pointer, close_pointer
*
* the counter goes: 1, 2, 1, 0
*/
byte pointerCounter = 0;
newCommand = "";
do {
if(commands.get(i).equals("POINTER")) {
pointerCounter++;
}else if(commands.get(i).equals("CLOSE_POINTER")) {
pointerCounter
}
newCommand += commands.get(i) + " ";
i++;
} while(pointerCounter != 0);
newCommands.add(newCommand);
}else{
newCommands.add(commands.get(i));
i++;
}
}
return newCommands;
}
private static LinkedList<String> labelIf(LinkedList<String> commands) {
int i = 0;
int level = 0;
LinkedList<String> newCommands = commands;
while(i < commands.size()) {
if(newCommands.get(i).equals("IF")) {
level++;
newCommands.set(i, "IF:" + level);
}else if(newCommands.get(i).equals("ELSE")) {
newCommands.set(i, "ELSE:" + level);
}else if(newCommands.get(i).equals("END")) {
newCommands.set(i, "END:"+ level);
level
}
i++;
}
return newCommands;
}
//searches through the list of commands
//finds possible expressions, validates that they are in fact expressions, then clumps the individual commands together into an EXPR commands
//This allows for easy computation of expressions later on down the road
private static LinkedList<String> findExpr(LinkedList<String> commands) {
int i = 0;
LinkedList<String> newCommands = new LinkedList<String>();
String newCommand = "";
while(i < commands.size()) {
try {
//checks to see if the commands are an operation. Ugly, I know
if(safeSubstring(commands.get(i),0,6).equals("NUMBER") || safeSubstring(commands.get(i),0,7).equals("POINTER") || commands.get(i).equals("INPUT")) {
if(commands.get(i + 1).equals("ADD") || commands.get(i + 1).equals("SUBTRACT") || commands.get(i + 1).equals("MULTIPLY") ||
commands.get(i + 1).equals("DIVIDE") || commands.get(i + 1).equals("MODULO")
|| commands.get(i + 1).equals("COMPARE") || commands.get(i + 1).equals("LESS_THAN") || commands.get(i + 1).equals("GREATER_THAN") || commands.get(i + 1).equals("NOT")) {
newCommand = "EXPR: ";
newCommand += (commands.get(i) + " " + commands.get(i + 1) + " " + commands.get(i + 2));
i+=3;
while(true && i < commands.size() - 1) {
if(commands.get(i).equals("ADD") || commands.get(i).equals("SUBTRACT") || commands.get(i).equals("MULTIPLY") || commands.get(i).equals("DIVIDE")
|| commands.get(i).equals("COMPARE") || commands.get(i + 1).equals("LESS_THAN") || commands.get(i + 1).equals("GREATER_THAN")|| commands.get(i + 1).equals("NOT")) {
newCommand += " " + commands.get(i) + " " + commands.get(i + 1);
i+=2;
}else{
break;
}
}
newCommands.add(newCommand);
newCommand = "";
}else{
newCommands.add(commands.get(i));
i++;
}
}else{
newCommands.add(commands.get(i));
i++;
}
}catch (IndexOutOfBoundsException e) {
try {
newCommands.add(commands.get(i));
i++;
} catch(IndexOutOfBoundsException e1) {
newCommands.add(newCommand);
}
}
}
return newCommands;
}
//Lights, Camera
//ACTION!
private static void execute(LinkedList<String> psuedo) throws StringIndexOutOfBoundsException{
//Creates LABELS, which are parameters for GOTO statements
//Runs before the rest of the program does
//Adds each new label to the list of LABELS for use when GOTO statements are called later in the program
for(int j = 0; j < psuedo.size(); j++) {
if(psuedo.get(j).equals("LABEL")) {
Label temp = new LineSpam.Label();
if(isNum(psuedo.get(j + 1))) {
temp.name = eval(psuedo.get(j + 1));
temp.location = j;
labels.add(temp);
}else{
errors.add("Label declaration at " + j + " is missing the proper arguments!");
System.out.println("Label declaration at " + j + " is missing the proper arguments!");
}
}
}
int i = 0;
//Program Execution
while(i < psuedo.size()) {
//Executes GOTO function
//GOTO: NUMBER or POINTER
if(psuedo.get(i).length() >= 4 && psuedo.get(i).substring(0,4).equals("GOTO")) {
if(isNum(psuedo.get(i + 1))) {
int newLocation = getLabelLocation(eval(psuedo.get(i + 1)));
if(newLocation != -1) {
i = newLocation;
}else{
errors.add("Label " + psuedo.get(i).substring(5) + " does not exist!");
i++;
}
}else{
errors.add("GOTO command at " + i + " is missing the proper arguments!");
System.out.println("GOTO command at " + i + " is missing the proper arguments!");
}
//executes PRINT function
//PRINT: NUMBER or POINTER
}else if(psuedo.get(i).length() >= 5 && psuedo.get(i).equals("PRINT")) {
if(isNum(psuedo.get(i + 1))) {
System.out.print((char)(eval(psuedo.get(i + 1))));
i+=2;
}else{
errors.add("Print function at " + i + " is missing proper arguments!");
System.out.println("Print function at " + i + " is missing proper arguments!");
i++;
}
//executed functions that may follow POINTER
//POINTER: EQUALS
//EQUALS : POINTER or NUMBER or EXPRESSION
}else if((psuedo.get(i).length() >= 7 && psuedo.get(i).substring(0, 7).equals("POINTER"))) {
if(psuedo.get(i + 1).equals("EQUALS")) {
String[] splitPtr = psuedo.get(i).split(" ");
String temp = "";
for(int j = 1; j < splitPtr.length - 1; j++) {
temp += " " + splitPtr[j];
}
int id = eval(temp);
if(isNum(psuedo.get(i + 2))) {
int value = eval(psuedo.get(i + 2));
addPointer(id, (char)value);
i+=3;
}else{
errors.add("Declaration at " + i + " is missing arguments!");
System.out.println("Declaration at " + i + " is missing arguments!");
i++;
}
}
//IF statements
}else if(psuedo.get(i).substring(0, 2).equals("IF")) {
int level = Integer.parseInt(psuedo.get(i).substring(3));
if(isNum(psuedo.get(i + 1))) {
if(eval(psuedo.get(i + 1)) > 0) {
i++;
}else if(eval(psuedo.get(i + 1)) == 0) {
i++;
while(true) {
if(safeSubstring(psuedo.get(i), 0, 4).equals("ELSE") && Integer.parseInt(psuedo.get(i).substring(5)) == level) {
break;
}
if(psuedo.get(i).substring(0, 3).equals("END") && Integer.parseInt(psuedo.get(i).substring(4)) == level) {
break;
}
i++;
}
i++;
}
}
}else if(safeSubstring(psuedo.get(i), 0, 4).equals("ELSE")) {
int level = Integer.parseInt(psuedo.get(i).substring(5));
i++;
while(true) {
if(psuedo.get(i).substring(0, 3).equals("END") && Integer.parseInt(psuedo.get(i).substring(4)) == level) break;
i++;
}
i++;
}else{
i++;
}
}
}
//evaluates a pointer and the expressions inside one
private static int evalPointer(String pointer) {
LinkedList<String> tokens = new LinkedList<String>(Arrays.asList(pointer.split(" ")));
tokens.removeFirstOccurrence("POINTER");
tokens.removeLastOccurrence("CLOSE_POINTER");
String temp = "";
int i = 0;
while(i < tokens.size()) {
if(tokens.get(i).equals("POINTER")) {
temp = "";
temp += tokens.get(i) + " ";
int startIndex = i, endIndex;
int pointerCounter = 1;
int tempCounter = i;
while(pointerCounter != 0) {
tempCounter++;
if(tokens.get(tempCounter).equals("POINTER")) pointerCounter++;
if(tokens.get(tempCounter).equals("CLOSE_POINTER")) pointerCounter
temp += tokens.get(tempCounter) + " ";
}
endIndex = tempCounter;
for(int j = startIndex; j < endIndex + 1; j++) {
tokens.remove(startIndex);
}
tokens.add(startIndex, "NUMBER:" + evalPointer(temp));
}
i++;
}
String expr = "";
for(int j = 0; j < tokens.size(); j++) {
expr += tokens.get(j) + " ";
}
int insidePtr = eval(expr);
return getPointerValue(insidePtr);
}
//evaluates expressions
private static int eval(String expr) {
LinkedList<String> ops = new LinkedList<String>(Arrays.asList(expr.split(" ")));
ops.remove("EXPR:");
ops = findPointers(ops);
ops.remove("");
int i = 0;
int size = ops.size();
while(i < size) {
if(ops.get(i).equals("MULTIPLY")) {
int value1 = findValue(ops.get(i - 1));
int value2 = findValue(ops.get(i + 1));
int value3 = value1 * value2;
ops.set(i, value3 + "");
ops.remove(i + 1);
ops.remove(i - 1);
}else if(ops.get(i).equals("DIVIDE")) {
int value1 = findValue(ops.get(i - 1));
int value2 = findValue(ops.get(i + 1));
int value3 = (int)(value1 / value2);
ops.set(i, value3 + "");
ops.remove(i + 1);
ops.remove(i - 1);
}else if(ops.get(i).equals("MODULO")) {
int value1 = findValue(ops.get(i - 1));
int value2 = findValue(ops.get(i + 1));
int value3 = value1 % value2;
ops.set(i, value3 + "");
ops.remove(i + 1);
ops.remove(i - 1);
}
i++;
size = ops.size();
}
i = 0;
while(i < size) {
if(ops.get(i).equals("ADD")) {
int value1 = findValue(ops.get(i - 1));
int value2 = findValue(ops.get(i + 1));
int value3 = value1 + value2;
ops.set(i, value3 + "");
ops.remove(i + 1);
ops.remove(i - 1);
}else if(ops.get(i).equals("SUBTRACT")) {
int value1 = findValue(ops.get(i - 1));
int value2 = findValue(ops.get(i + 1));
int value3 = value1 - value2;
ops.set(i, value3 + "");
ops.remove(i + 1);
ops.remove(i - 1);
}
i++;
size = ops.size();
}
i = 0;
while(i < size) {
if(ops.get(i).equals("COMPARE")) {
int value1 = findValue(ops.get(i - 1));
int value2 = findValue(ops.get(i + 1));
int value3 = 0;
if(value1 == value2) value3 = 1;
ops.set(i, value3 + "");
ops.remove(i + 1);
ops.remove(i - 1);
}else if(ops.get(i).equals("GREATER_THAN")) {
int value1 = findValue(ops.get(i - 1));
int value2 = findValue(ops.get(i + 1));
int value3 = 0;
if(value1 > value2) value3 = 1;
ops.set(i, value3 + "");
ops.remove(i + 1);
ops.remove(i - 1);
}else if(ops.get(i).equals("LESS_THAN")) {
int value1 = findValue(ops.get(i - 1));
int value2 = findValue(ops.get(i + 1));
int value3 = 0;
if(value1 < value2) value3 = 1;
ops.set(i, value3 + "");
ops.remove(i + 1);
ops.remove(i - 1);
}else if(ops.get(i).equals("NOT")) {
int value1 = findValue(ops.get(i - 1));
int value2 = findValue(ops.get(i + 1));
int value3 = 0;
if(value1 != value2) value3 = 1;
ops.set(i, value3 + "");
ops.remove(i + 1);
ops.remove(i - 1);
}
i++;
size = ops.size();
}
return findValue(ops.get(0));
}
//finds values given a NUMBER, POINTER, or INPUT. Used only in the eval() function
private static int findValue(String val) {
if(safeSubstring(val,0,6).equals("NUMBER")) {
return Integer.parseInt(val.substring(7));
}else if(safeSubstring(val,0,7).equals("POINTER")) {
return evalPointer(val);
}else if(val.equals("INPUT")) {
return getInput();
}
return Integer.parseInt(val);
}
private static char getInput() {
try {
char ch = input.charAt(0);
input = input.substring(1);
return ch;
}catch(NullPointerException|StringIndexOutOfBoundsException e) {
return 0;
}
}
//determines whether a command is a NUMBER, EXPR, or POINTER
//This method is useful because I was lazy and didnt want to copy/paste all the logic expressions over and over
private static boolean isNum(String s) {
if(safeSubstring(s,0,4).equals("EXPR") || safeSubstring(s,0,6).equals("NUMBER") || safeSubstring(s,0,7).equals("POINTER") || s.equals("INPUT")) return true;
return false;
}
//adds a new Pointer
private static void addPointer(int id, char value) {
memory[id] = value;
}
//returns the value of a pointer
public static int getPointerValue(int pointer) {
return memory[pointer];
}
//gets substring while avoiding StringIndexOutOfBounds exceptions
private static String safeSubstring(String s, int a, int b) {
try {
return s.substring(a, b);
} catch (Exception e) {
return "";
}
}
//gets substring while avoiding StringIndexOutOfBounds exceptions
private static String safeSubstring(String s, int a) {
try {
return s.substring(a);
} catch (Exception e) {
return "";
}
}
//gets the Value of a number, from binary([ and ]) to decimal
private static short getValue(String s) {
int length = s.length();
short value = 0;
for(int i = 0; i < length; i++) {
if(s.charAt(i) == '[') value += Math.pow(2, length - i - 1);
}
return value;
}
public static int getLabelLocation(int name) {
for(Label l : labels) {
if(l.name == name) return l.location;
}
return -1;
}
public static class Command {
public String command;
public short arg;
}
static class Label {
public int name;
public int location;
}
private static String getLastThreeChars(String s) {
try {
return s.substring(s.length() - 3, s.length());
}catch(StringIndexOutOfBoundsException e) {
return s;
}
}
private static String getLastTwoChars(String s) {
try {
return s.substring(s.length() - 2, s.length());
}catch(StringIndexOutOfBoundsException e) {
return s;
}
}
private static String removeLastTwoChars(String s) {
try {
return s.substring(0, s.length() - 2);
}catch(StringIndexOutOfBoundsException e) {
return s;
}
}
//getting the code stuff
private static String getCode(String path) {
File file = new File(path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while(line != null) {
code += line;
line = br.readLine();
}
return code;
} catch (FileNotFoundException e) {
System.out.println("File not found! Now Exiting...");
System.exit(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
return null;
}
private static String cleanseCode(String code) {
String newCode = "";
for(char c : code.toCharArray()) {
if(c == 'l' || c == '1' || c == ']' || c == '[' || c == '|') {
newCode += c;
}
}
return newCode;
}
} |
package learn;
import verification.AbstPane;
import lpn.parser.Abstraction;
import lpn.parser.LhpnFile;
import main.*;
import parser.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.prefs.Preferences;
import javax.swing.*;
//import org.sbml.libsbml.*;
/**
* This class creates a GUI for the Learn program. It implements the
* ActionListener class. This allows the GUI to perform actions when menu items
* and buttons are selected.
*
* @author Curtis Madsen
*/
public class LearnLHPN extends JPanel implements ActionListener, Runnable, ItemListener { // added ItemListener SB
private static final long serialVersionUID = -5806315070287184299L;
private JButton save, run, viewLhpn, saveLhpn, viewLog;
private JButton viewCoverage;
private JButton viewVHDL,viewVerilog;
private JComboBox debug;
private JTextField iteration, backgroundField, propertyG;
private JComboBox numBins;
private ArrayList<ArrayList<Component>> variables;
private JPanel variablesPanel;
private JRadioButton user, auto, range, points;
private JButton suggest;
private String directory, lrnFile;
private JLabel numBinsLabel;
private Log log;
private String separator;
private Gui biosim;
private String seedLpnFile, lhpnFile;
private boolean change, fail;
private ArrayList<String> variablesList;
private boolean firstRead, generate, execute;
private ArrayList<Variable> reqdVarsL;
private ArrayList<Integer> reqdVarIndices;
private ArrayList<ArrayList<Double>> data;
private ArrayList<String> varNames;
private int[][] bins;
private ArrayList<ArrayList<Double>> divisionsL;
private HashMap<String, ArrayList<Double>> thresholds;
private Double[][] rates;
private double[][] values;
private Double[] duration;
private int pathLengthBin ; //= 7 ;// intFixed 25 pd 7 integrator 15;
private int rateSampling ; //= -1 ; //intFixed 250; 20; //-1;
private LhpnFile g;
private Integer numPlaces = 0;
private Integer numTransitions = 0;
private HashMap<String, Properties> placeInfo;
private HashMap<String, Properties> transitionInfo;
private Double delayScaleFactor = 1.0;
private Double valScaleFactor = 1.0;
BufferedWriter out;
File logFile;
// Threshold parameters
private double epsilon ;
private int runLength ; //= 15; // the number of time points that a value must persist to be considered constant
private double runTime ; // = 5e-12; // 10e-6 for intFixed; 5e-6 for integrator. 5e-12 for pd;// the amount of time that must pass to be considered constant when using absoluteTime
private boolean absoluteTime ; // = true; // true for intfixed //false; true for pd; false for integrator// when False time points are used to determine DMVC and when true absolutime time is used to determine DMVC
private double percent ; // = 0.8; // a decimal value representing the percent of the total trace that must be constant to qualify to become a DMVC var
//private double unstableTime;
private double stableTolerance;
private boolean pseudoEnable;
private JTextField epsilonG;
private JTextField percentG;
private JCheckBox absTimeG;
private JTextField pathLengthBinG;
private JTextField pathLengthVarG;
private JTextField rateSamplingG;
private JTextField runTimeG;
private JTextField runLengthG;
// private JTextField unstableTimeG;
private JCheckBox pseudoEnableG;
private JTextField stableToleranceG;
private JTextField globalDelayScaling;
private JTextField globalValueScaling;
private JCheckBox defaultEnvG;
private boolean suggestIsSource = false;
private Double[] lowerLimit;
private Double[] upperLimit;
// private String failPropVHDL;
private HashMap<String, Properties> transientNetPlaces;
private HashMap<String, Properties> transientNetTransitions;
// private boolean vamsRandom = false;
private ArrayList<String> allVars;
private Thread LearnThread;
private HashMap<String,Properties> dmvcValuesUnique;
private String currentPlace;
private String[] currPlaceBin;
private LhpnFile lpnWithPseudo;
private int pseudoTransNum = 0;
private HashMap<String,Boolean> pseudoVars;
private ArrayList<HashMap<String, String>> constVal;
private boolean dmvDetectDone = false;
private boolean dmvStatusLoaded = false;
private int pathLengthVar = 40;
private JPanel advancedOptionsPanel;
String thresh;
String[] threshValues;
// Pattern lParenR = Pattern.compile("\\(+");
//Pattern floatingPointNum = Pattern.compile(">=(-*[0-9]+\\.*[0-9]*)");
/**
* This is the constructor for the Learn class. It initializes all the input
* fields, puts them on panels, adds the panels to the frame, and then
* displays the frame.
*/
public LearnLHPN(String directory, Log log, Gui biosim) {
if (File.separator.equals("\\")) {
separator = "\\\\";
} else {
separator = File.separator;
}
this.biosim = biosim;
this.log = log;
this.directory = directory;
String[] getFilename = directory.split(separator);
lhpnFile = getFilename[getFilename.length - 1] + ".lpn";
lrnFile = getFilename[getFilename.length - 1] + ".lrn";
Preferences biosimrc = Preferences.userRoot();
// Sets up the encodings area
JPanel radioPanel = new JPanel(new BorderLayout());
JPanel selection1 = new JPanel();
JPanel selection2 = new JPanel();
JPanel selection = new JPanel(new BorderLayout());
range = new JRadioButton("Minimize Range of Rates");
points = new JRadioButton("Equalize Points Per Bin");
user = new JRadioButton("Use User Generated Levels");
auto = new JRadioButton("Use Auto Generated Levels");
suggest = new JButton("Suggest Levels");
ButtonGroup select = new ButtonGroup();
select.add(auto);
select.add(user);
ButtonGroup select2 = new ButtonGroup();
select2.add(range);
select2.add(points);
user.addActionListener(this);
range.addActionListener(this);
auto.addActionListener(this);
suggest.addActionListener(this);
// if (biosimrc.get("biosim.learn.equaldata", "").equals("Equal Data Per
// Bins")) {
// data.setSelected(true);
// else {
range.setSelected(true);
points.addActionListener(this);
JLabel iterationLabel = new JLabel("Iterations of Optimization Algorithm");
iteration = new JTextField("10",4);
selection1.add(points);
selection1.add(range);
selection1.add(iterationLabel);
selection1.add(iteration);
selection2.add(auto);
selection2.add(user);
selection2.add(suggest);
auto.setSelected(true);
selection.add(selection1, "North");
selection.add(selection2, "Center");
suggest.setEnabled(false);
JPanel encodingPanel = new JPanel(new BorderLayout());
variablesPanel = new JPanel();
JPanel sP = new JPanel();
((FlowLayout) sP.getLayout()).setAlignment(FlowLayout.LEFT);
sP.add(variablesPanel);
JLabel encodingsLabel = new JLabel("Variable Levels:");
JScrollPane scroll2 = new JScrollPane();
scroll2.setMinimumSize(new Dimension(260, 200));
scroll2.setPreferredSize(new Dimension(276, 132));
scroll2.setViewportView(sP);
radioPanel.add(selection, "North");
radioPanel.add(encodingPanel, "Center");
encodingPanel.add(encodingsLabel, "North");
encodingPanel.add(scroll2, "Center");
// Sets up the thresholds area
JPanel thresholdPanel2 = new JPanel(new GridLayout(8, 2));
JPanel thresholdPanel1 = new JPanel(new GridLayout(1, 2));
JLabel backgroundLabel = new JLabel("Model File:");
backgroundField = new JTextField(lhpnFile);
backgroundField.setEditable(false);
thresholdPanel1.add(backgroundLabel);
thresholdPanel1.add(backgroundField);
//JLabel iterationLabel = new JLabel("Iterations of Optimization Algorithm");
//iteration = new JTextField("10");
//thresholdPanel1.add(iterationLabel);
//thresholdPanel1.add(iteration);
//Model Generation Parameters
//Advanced Options Tab
JLabel epsilonLabel = new JLabel("Epsilon");
epsilonG = new JTextField("0.1");
JLabel pathLengthBinLabel = new JLabel("Minimum bin pathLength");
pathLengthBinG = new JTextField("0");
JLabel pathLengthVarLabel = new JLabel("Minimum variable pathLength");
pathLengthVarG = new JTextField("0");
JLabel rateSamplingLabel = new JLabel("Window size");
rateSamplingG = new JTextField("-1");
JLabel absTimeLabel = new JLabel("Absolute time");
absTimeG = new JCheckBox();
absTimeG.setSelected(false);
absTimeG.addItemListener(this);
JLabel percentLabel = new JLabel("Fraction");
percentG = new JTextField("0.8");
JLabel runTimeLabel = new JLabel("DMV run time");
runTimeG = new JTextField("5e-6");
runTimeG.setEnabled(false);
JLabel runLengthLabel = new JLabel("DMV run length");
runLengthG = new JTextField("2");
runLengthG.setEnabled(true);
JLabel defaultEnvLabel = new JLabel("Default environment");
defaultEnvG = new JCheckBox();
defaultEnvG.setSelected(true);
defaultEnvG.addItemListener(this);
//JLabel unstableTimeLabel = new JLabel("Mode unstable time");
//unstableTimeG = new JTextField("5960.0");
//unstableTimeG.setEnabled(true);
JLabel stableToleranceLabel = new JLabel("Stable tolerance");
stableToleranceG = new JTextField("0.02");
stableToleranceG.setEnabled(true);
JLabel pseudoEnableLabel = new JLabel("Enable pseudo-transitions");
pseudoEnableG = new JCheckBox();
pseudoEnableG.setSelected(false);
pseudoEnableG.addItemListener(this);
epsilonG.addActionListener(this);
pathLengthBinG.addActionListener(this);
pathLengthVarG.addActionListener(this);
rateSamplingG.addActionListener(this);
percentG.addActionListener(this);
runTimeG.addActionListener(this);
runLengthG.addActionListener(this);
//unstableTimeG.addActionListener(this);
stableToleranceG.addActionListener(this);
JPanel panel4 = new JPanel();
((FlowLayout) panel4.getLayout()).setAlignment(FlowLayout.CENTER);
JPanel panel3 = new JPanel(new GridLayout(14, 2));
panel4.add(panel3, "Center");
panel3.add(epsilonLabel);
panel3.add(epsilonG);
panel3.add(rateSamplingLabel);
panel3.add(rateSamplingG);
panel3.add(pathLengthBinLabel);
panel3.add(pathLengthBinG);
panel3.add(pathLengthVarLabel);
panel3.add(pathLengthVarG);
panel3.add(absTimeLabel);
panel3.add(absTimeG);
panel3.add(percentLabel);
panel3.add(percentG);
panel3.add(runTimeLabel);
panel3.add(runTimeG);
panel3.add(runLengthLabel);
panel3.add(runLengthG);
panel3.add(defaultEnvLabel);
panel3.add(defaultEnvG);
//panel3.add(unstableTimeLabel);
//panel3.add(unstableTimeG);
panel3.add(stableToleranceLabel);
panel3.add(stableToleranceG);
panel3.add(pseudoEnableLabel);
panel3.add(pseudoEnableG);
thresholds = new HashMap<String, ArrayList<Double>>(); // <Each Variable, List of thresholds for each variable>
reqdVarsL = new ArrayList<Variable>(); //List of objects for variables that are marked as "ip/op" in variables panel
//Top panel in learn view
numBinsLabel = new JLabel("Number of Bins:");
String[] bins = { "Auto", "2", "3", "4", "5", "6", "7", "8", "16", "32"};//, "10", "11", "12", "13", "14", "15", "16", "17", "33", "65", "129", "257" };
numBins = new JComboBox(bins);
numBins.setSelectedItem(biosimrc.get("biosim.learn.bins", ""));
numBins.addActionListener(this);
numBins.setActionCommand("text");
selection2.add(numBinsLabel);
selection2.add(numBins);
JLabel propertyLabel = new JLabel("Assertion to be Verified");
propertyG = new JTextField("");
panel3.add(propertyLabel);
panel3.add(propertyG);
JLabel valueScaleLabel = new JLabel("Scale Factor for Values");
globalValueScaling = new JTextField("");
panel3.add(valueScaleLabel);
panel3.add(globalValueScaling);
JLabel delayScaleLabel = new JLabel("Scale Factor for Time");
globalDelayScaling = new JTextField("");
panel3.add(delayScaleLabel);
panel3.add(globalDelayScaling);
JPanel thresholdPanelHold1 = new JPanel();
thresholdPanelHold1.add(thresholdPanel1);
JLabel debugLabel = new JLabel("Debug Level:");
String[] options = new String[4];
options[0] = "0";
options[1] = "1";
options[2] = "2";
options[3] = "3";
debug = new JComboBox(options);
// debug.setSelectedItem(biosimrc.get("biosim.learn.debug", ""));
debug.addActionListener(this);
thresholdPanel2.add(debugLabel);
thresholdPanel2.add(debug);
// load parameters
// reading lrnFile twice. On the first read, only seedLpnFile (the seed lpn) is processed.
// In the gap b/w these reads, reqdVarsL is created based on the seedLpnFile
Properties load = new Properties();
seedLpnFile = "";
TSDParser extractVars;
ArrayList<String> datFileVars = new ArrayList<String>();
allVars = new ArrayList<String>();
Boolean varPresent = false;
//Finding the intersection of all the variables present in all data files.
for (int i = 1; (new File(directory + separator + "run-" + i + ".tsd")).exists(); i++) {
extractVars = new TSDParser(directory + separator + "run-" + i + ".tsd", false);
datFileVars = extractVars.getSpecies();
if (i == 1){
allVars.addAll(datFileVars);
}
for (String s : allVars){
varPresent = false;
for (String t : datFileVars){
if (s.equalsIgnoreCase(t)){
varPresent = true;
break;
}
}
if (!varPresent){
allVars.remove(s);
}
}
}
if (allVars.size() != 0){
if (allVars.get(0).toLowerCase(Locale.ENGLISH).contains("time")){
allVars.remove(0);
}
else{
JOptionPane.showMessageDialog(Gui.frame,
"Error!",
"AllVars doesnot have time at zeroeth element. Something wrong. Please check time variable", JOptionPane.ERROR_MESSAGE);
}
}
//System.out.println("All variables are : ");
//for (String s : allVars){
// System.out.print(s + " ");
try {
FileInputStream in = new FileInputStream(new File(directory
+ separator + lrnFile));
load.load(in);
in.close();
if (load.containsKey("learn.file")) {
String[] getProp = load.getProperty("learn.file").split(
separator);
seedLpnFile = directory.substring(0, directory.length()
- getFilename[getFilename.length - 1].length())
+ separator + getProp[getProp.length - 1];
backgroundField.setText(getProp[getProp.length - 1]);
}
} catch (IOException e) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
variablesList = new ArrayList<String>();
LhpnFile lhpn = new LhpnFile(log);
lhpn.load(seedLpnFile);
HashMap<String, Properties> variablesMap = lhpn.getContinuous(); //System.out.println("Variables MAp :"+variablesMap.keySet());
for (String s : variablesMap.keySet()) { //System.out.println("Variables MAp :"+s);
variablesList.add(s);
reqdVarsL.add(new Variable(s));
thresholds.put(s, new ArrayList<Double>());
}
// System.out.println("Hey :"+variablesList.size());
try {
FileInputStream in = new FileInputStream(new File(directory
+ separator + lrnFile));
load.load(in);
in.close();
if (load.containsKey("learn.iter")) {
iteration.setText(load.getProperty("learn.iter"));
}
if (load.containsKey("learn.valueScaling")) {
globalValueScaling.setText(load.getProperty("learn.valueScaling"));
}
if (load.containsKey("learn.delayScaling")) {
globalDelayScaling.setText(load.getProperty("learn.delayScaling"));
}
if (load.containsKey("learn.bins")) {
numBins.setSelectedItem(load.getProperty("learn.bins"));
}
if (load.containsKey("learn.prop")) {
propertyG.setText(load.getProperty("learn.prop"));
}
if (load.containsKey("learn.equal")) {
if (load.getProperty("learn.equal").equals("range")) {
range.setSelected(true);
} else {
points.setSelected(true);
}
}
if (load.containsKey("learn.use")) {
if (load.getProperty("learn.use").equals("auto")) {
auto.setSelected(true);
} else if (load.getProperty("learn.use").equals("user")) {
user.setSelected(true);
}
}
if (load.containsKey("learn.epsilon")){
epsilonG.setText(load.getProperty("learn.epsilon"));
}
if (load.containsKey("learn.rateSampling")){
rateSamplingG.setText(load.getProperty("learn.rateSampling"));
}
if (load.containsKey("learn.pathLengthBin")){
pathLengthBinG.setText(load.getProperty("learn.pathLengthBin"));
}
if (load.containsKey("learn.pathLengthVar")){
pathLengthVarG.setText(load.getProperty("learn.pathLengthVar"));
}
if (load.containsKey("learn.percent")){
percentG.setText(load.getProperty("learn.percent"));
}
if (load.containsKey("learn.absTime")){
absTimeG.setSelected(Boolean.parseBoolean(load.getProperty("learn.absTime")));
}
if (load.containsKey("learn.runTime")){
runTimeG.setText(load.getProperty("learn.runTime"));
}
if (load.containsKey("learn.runLength")){
runLengthG.setText(load.getProperty("learn.runLength"));
}
if (load.containsKey("learn.defaultEnv")){
defaultEnvG.setSelected(Boolean.parseBoolean(load.getProperty("learn.defaultEnv")));
}
if (load.containsKey("learn.pseudoEnable")){
pseudoEnableG.setSelected(Boolean.parseBoolean(load.getProperty("learn.pseudoEnable")));
}
if (load.containsKey("learn.stableTolerance")){
stableToleranceG.setText(load.getProperty("learn.stableTolerance"));
}
//levels();
String[] varsList = null;
if (load.containsKey("learn.varsList")){
String varsListString = load.getProperty("learn.varsList");
varsList = varsListString.split("\\s");
//System.out.println("VARSLIST :"+varsList);
for (String st1 : varsList){
boolean varFound = false;
String s = load.getProperty("learn.bins" + st1);
String[] savedBins = null;
if (s != null){
savedBins = s.split("\\s");
//for (int i = 2; i < savedBins.length ; i++){ System.out.println("saved bins[] :"+savedBins[i]);}
}
for (String st2 :variablesList){//("variables List it is :"+variablesList);
if (st1.equalsIgnoreCase(st2)){ //System.out.println("Match found");
varFound = true;
break;
}
}
if (varFound){
if (savedBins != null){//System.out.println("M in loop 2 ");
for (int i = 2; i < savedBins.length ; i++){ //System.out.println("saved bins["+i+"] :"+thresholds.get(st1));
thresholds.get(st1).add(Double.parseDouble(savedBins[i]));
}
}
}
else{
variablesList.add(st1); //System.out.println("variables List2:"+variablesList);
reqdVarsL.add(new Variable(st1));
thresholds.put(st1, new ArrayList<Double>());
if (savedBins != null){
for (int i = 2; i < savedBins.length ; i++){ // System.out.println("thresholds.get(st1)2 :"+thresholds.get(st1));
thresholds.get(st1).add(Double.parseDouble(savedBins[i]));
//System.out.println("threshold values : "+thresholds.get(st1).get(i));
}
}
}
String e = load.getProperty("learn.epsilon" + st1);
if ((findReqdVarslIndex(st1) != -1) && (e != null)){
reqdVarsL.get(findReqdVarslIndex(st1)).setEpsilon(Double.valueOf(e));
}
}
ArrayList<Variable> removeVars = new ArrayList<Variable>();
for (Variable v : reqdVarsL){
boolean varFound = false;
String st1 = v.getName();
for (String st2 : varsList){
if (st1.equalsIgnoreCase(st2)){
varFound = true;
}
}
if (!varFound){
variablesList.remove(st1);
removeVars.add(v);
//reqdVarsL.remove(v); not allowed. concurrent modification exception
thresholds.remove(st1);
}
}
for (Variable v : removeVars){
reqdVarsL.remove(v);
}
}
if (load.containsKey("learn.inputs")){
String s = load.getProperty("learn.inputs");
String[] savedInputs = s.split("\\s");
for (String st1 : savedInputs){
for (int i = 0; i < reqdVarsL.size(); i++){
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setInput(true);
}
}
}
}
if (load.containsKey("learn.destabs")){
String s = load.getProperty("learn.destabs");
String[] savedDestabs = s.split("\\s");
for (String st1 : savedDestabs){
for (int i = 0; i < reqdVarsL.size(); i++){
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setDestab(true);
}
}
}
}
if (load.containsKey("learn.dontcares")){
String s = load.getProperty("learn.dontcares");
String[] savedDontCares = s.split("\\s");
for (String st1 : savedDontCares){
for (int i = 0; i < reqdVarsL.size(); i++){
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setCare(false);
}
}
}
}
if (load.containsKey("learn.dmv")){
String s = load.getProperty("learn.dmv");
String[] savedInputs = s.split("\\s");
for (String st1 : savedInputs){
for (int i = 0; i < reqdVarsL.size(); i++){
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setDmvc(true);
}
}
}
dmvStatusLoaded = true;
}
if (load.containsKey("learn.cont")){
String s = load.getProperty("learn.cont");
String[] savedInputs = s.split("\\s");
for (String st1 : savedInputs){
for (int i = 0; i < reqdVarsL.size(); i++){
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setDmvc(false);
}
}
}
dmvStatusLoaded = true;
}
if (load.containsKey("learn.autoVar")){
String s = load.getProperty("learn.autoVar");
String[] savedInputs = s.split("\\s");
for (String st1 : savedInputs){
for (int i = 0; i < reqdVarsL.size(); i++){
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setDmvc(false);
}
}
}
}
} catch (IOException e) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
try {
FileWriter write = new FileWriter(new File(directory + separator + "background.lpn"));
BufferedReader input = new BufferedReader(new FileReader(new File(seedLpnFile)));
String line = null;
while ((line = input.readLine()) != null) {
write.write(line + "\n");
}
write.close();
input.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to create background file!",
"Error Writing Background", JOptionPane.ERROR_MESSAGE);
}
// sortSpecies();
JPanel runHolder = new JPanel();
//levels();
autogen(false);
if (auto.isSelected()) {
auto.doClick();
} else {
//user.doClick();
numBinsLabel.setEnabled(false);
numBins.setEnabled(false);
suggest.setEnabled(true);
}
// Creates the run button
run = new JButton("Save and Learn");
runHolder.add(run);
run.addActionListener(this);
run.setMnemonic(KeyEvent.VK_L);
// Creates the run button
save = new JButton("Save Parameters");
runHolder.add(save);
save.addActionListener(this);
save.setMnemonic(KeyEvent.VK_S);
// Creates the view circuit button
viewLhpn = new JButton("View Circuit");
runHolder.add(viewLhpn);
viewLhpn.addActionListener(this);
viewLhpn.setMnemonic(KeyEvent.VK_V);
// Creates the save circuit button
saveLhpn = new JButton("Save Circuit");
runHolder.add(saveLhpn);
saveLhpn.addActionListener(this);
saveLhpn.setMnemonic(KeyEvent.VK_C);
// Creates the view circuit button
viewLog = new JButton("View Run Log");
runHolder.add(viewLog);
viewLog.addActionListener(this);
viewLog.setMnemonic(KeyEvent.VK_R);
if (!(new File(directory + separator + lhpnFile).exists())) {
viewLhpn.setEnabled(false);
saveLhpn.setEnabled(false);
}
else{
viewLhpn.setEnabled(true);
saveLhpn.setEnabled(true);
}
if (!(new File(directory + separator + "run.log").exists())) {
viewLog.setEnabled(false);
}
viewCoverage = new JButton("View Coverage Report");
viewVHDL = new JButton("View VHDL-AMS Model");
viewVerilog = new JButton("View Verilog-AMS Model");
runHolder.add(viewCoverage);
runHolder.add(viewVHDL);
viewCoverage.addActionListener(this);
viewVHDL.addActionListener(this);
// viewCoverage.setMnemonic(KeyEvent.VK_R);
if (!(new File(directory + separator + "run.cvg").exists())) {
viewCoverage.setEnabled(false);
}
else{
viewCoverage.setEnabled(true);
}
// String vhdFile = lhpnFile.replace(".lpn",".vhd");
// if (!(new File(directory + separator + vhdFile).exists())) {
viewVHDL.setEnabled(false);
// else{
// viewVHDL.setEnabled(true);
// Creates the main panel
this.setLayout(new BorderLayout());
JPanel middlePanel = new JPanel(new BorderLayout());
JPanel firstTab = new JPanel(new BorderLayout());
JPanel firstTab1 = new JPanel(new BorderLayout());
JPanel secondTab = new JPanel(new BorderLayout()); // SB uncommented
middlePanel.add(radioPanel, "Center");
// firstTab1.add(initNet, "North");
firstTab1.add(thresholdPanelHold1, "Center");
firstTab.add(firstTab1, "North");
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
middlePanel, null);
splitPane.setDividerSize(0);
// secondTab.add(thresholdPanelHold2, "North");
// JPanel binsFileHoldPanel = new JPanel();
// binsFileHoldPanel.add(binsFilePanel);
//binsFileHoldPanel.setMinimumSize(new Dimension(10000,16000));
//binsFileHoldPanel.setPreferredSize(getPreferredSize());
//secondTab.add(binsFileHoldPanel, "Center");
// secondTab.add(newPanel,"Center");
secondTab.add(panel4, "Center");
firstTab.add(splitPane, "Center");
JTabbedPane tab = new JTabbedPane();
tab.addTab("Basic Options", firstTab);
tab.addTab("Advanced Options", secondTab);
this.add(firstTab, "Center");
advancedOptionsPanel = secondTab;
//this.addTab("Basic", (JComponent)firstTab);
//this.addTab("Advanced", (JComponent)firstTab);
// this.add(runHolder, "South");
firstRead = true;
/* if (user.isSelected()) {
auto.doClick();
user.doClick();
}
else {
user.doClick();
auto.doClick();
} */
firstRead = false;
change = false;
}
public JPanel getAdvancedOptionsPanel() {
return advancedOptionsPanel;
}
/**
* This method performs different functions depending on what menu items or
* buttons are selected.
*/
public void actionPerformed(ActionEvent e) {
/*
* if (e.getActionCommand().contains("box")) { int num =
* Integer.parseInt(e.getActionCommand().substring(3)) - 1; if
* (!((JCheckBox) this.species.get(num).get(0)).isSelected()) {
* ((JComboBox) this.species.get(num).get(2)).setSelectedItem("0");
* editText(num); speciesPanel.revalidate(); speciesPanel.repaint(); for
* (int i = 1; i < this.species.get(num).size(); i++) {
* this.species.get(num).get(i).setEnabled(false); } } else {
* this.species.get(num).get(1).setEnabled(true); if (user.isSelected()) {
* for (int i = 2; i < this.species.get(num).size(); i++) {
* this.species.get(num).get(i).setEnabled(true); } } } } else
*/
change = true;
if (e.getActionCommand().contains("text")) {
// int num = Integer.parseInt(e.getActionCommand().substring(4)) -
if (variables != null && user.isSelected()) { // System.out.println("Var :"+variables);// action source is any of the variables' combobox
for (int i = 0; i < variables.size(); i++) {
//editText(i);
String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
if (findReqdVarslIndex(currentVar) != -1){ // condition added after adding allVars
String selected = (String) (((JComboBox) variables.get(i).get(6)).getSelectedItem()); // changed 2 to 3 after required
int combox_selected;
if (!selected.equalsIgnoreCase("Auto"))
combox_selected = Integer.parseInt(selected); // changed 2 to 3 after required
else
combox_selected = 0;
ArrayList<Double> iThresholds = thresholds.get(currentVar);
if (combox_selected != 0){
if ((iThresholds != null) && ( iThresholds.size() >= combox_selected)){
for (int j = iThresholds.size() - 1; j >= (combox_selected-1) ; j
thresholds.get(currentVar).remove(j);
}
}
} else { // if 0 selected, then remove all the stored thresholds
if ((iThresholds != null) && ( iThresholds.size() >= 1)){
for (int j = iThresholds.size() - 1; j >= 0 ; j
thresholds.get(currentVar).remove(j);
}
}
}
}
}
}
else if ( auto.isSelected()) { // variables != null // action source is numBins on top
//int combox_selected = Integer.parseInt((String) numBins.getSelectedItem());
String selected = (String) (numBins.getSelectedItem()); // changed 2 to 3 after required
int combox_selected;
if (!selected.equalsIgnoreCase("Auto"))
combox_selected = Integer.parseInt(selected); // changed 2 to 3 after required
else
combox_selected = 0;
for (int i = 0; i < allVars.size(); i++) {
String currentVar = allVars.get(i);
// if (((String)(((JComboBox) variables.get(i).get(5)).getSelectedItem())).equals("DMV")){
// combox_selected = 0;
if (findReqdVarslIndex(currentVar) != -1){ // condition added after adding allVars
ArrayList<Double> iThresholds = thresholds.get(currentVar);
if (combox_selected != 0){
if ((iThresholds != null) && (iThresholds.size() >= combox_selected)){
for (int j = iThresholds.size() - 1; j >= (combox_selected-1) ; j
thresholds.get(currentVar).remove(j);
}
}
}
else{
if ((iThresholds != null) && ( iThresholds.size() >= 1)){
for (int j = iThresholds.size() - 1; j >= 0; j
thresholds.get(currentVar).remove(j);
}
}
}
}
}
}
variablesPanel.revalidate();
variablesPanel.repaint();
int j = 0;
for (Component c : variablesPanel.getComponents()) {
if (j == 0){ // recheck .. SB
j++;
continue;
}
String s = ((JTextField)((JPanel) c).getComponent(0)).getText().trim();
if (findReqdVarslIndex(s) != -1) { // condition added after adding allVars
if (reqdVarsL.get((findReqdVarslIndex(s))).isInput())
((JComboBox)((JPanel) c).getComponent(1)).setSelectedItem("Input"); // added after adding allVars
else
((JComboBox)((JPanel) c).getComponent(1)).setSelectedItem("Output"); // added after adding allVars
((JCheckBox)((JPanel) c).getComponent(2)).setEnabled(true);// added after adding allVars
((JCheckBox)((JPanel) c).getComponent(3)).setEnabled(true);
((JTextField)((JPanel) c).getComponent(4)).setEnabled(true);
((JComboBox)((JPanel) c).getComponent(5)).setEnabled(true);
// for (int i = 3; i < ((JPanel) c).getComponentCount(); i++) { // added after allVars
// ((JPanel) c).getComponent(i).setEnabled(true); // added after adding allVars
//if (reqdVarsL.get(j-1).isInput()){ changed after adding allVars
if (reqdVarsL.get(findReqdVarslIndex(s)).isDestab()){
((JCheckBox)((JPanel) c).getComponent(2)).setSelected(true); // // changed 1 to 2 after required
} else {
((JCheckBox)((JPanel) c).getComponent(2)).setSelected(false); // // changed 1 to 2 after required
}
if (reqdVarsL.get(findReqdVarslIndex(s)).isCare()){
((JCheckBox)((JPanel) c).getComponent(3)).setSelected(true); // // changed 1 to 2 after required
}
//for (Variable v : reqdVarsL){ //SB after required
// if ((v.getName()).equalsIgnoreCase(((JTextField)((JPanel) c).getComponent(0)).toString())){
// ((JCheckBox)((JPanel) c).getComponent(1)).setSelected(true); // for required
} else { // added after adding allVars
((JComboBox)((JPanel) c).getComponent(1)).setSelectedItem("Not used");
((JCheckBox)((JPanel) c).getComponent(2)).setEnabled(false);
((JCheckBox)((JPanel) c).getComponent(3)).setEnabled(false);
((JTextField)((JPanel) c).getComponent(4)).setEnabled(false);
((JComboBox)((JPanel) c).getComponent(5)).setEnabled(false);
for (int i = 6; i < ((JPanel) c).getComponentCount(); i++) { // added after allVars
((JPanel) c).getComponent(i).setEnabled(false); // added after adding allVars
}
}
j++;
}
//biosim.setGlassPane(true);
} else if (e.getSource() == numBins || e.getSource() == debug) {
//biosim.setGlassPane(true);
} //else if (e.getActionCommand().contains("dmv")) {
//int num = Integer.parseInt(e.getActionCommand().substring(3)) - 1;
//editText(num);
else if (e.getActionCommand().contains("DMV")) {
//int num = Integer.parseInt(e.getActionCommand().substring(5)); // -1; ??
//reqdVarsL.get(num).setInput(!reqdVarsL.get(num).isInput());
String var = e.getActionCommand().substring(3,e.getActionCommand().length());
/*for (int i = 0; i < reqdVarsL.size() ; i++){ // COMMENTED after adding required
if (var.equalsIgnoreCase(reqdVarsL.get(i).getName())){
reqdVarsL.get(i).setInput(!reqdVarsL.get(i).isInput());
break;
}
}*/
for (int i = 0 ; i < variables.size(); i++){
if ((((JTextField) variables.get(i).get(0)).getText().trim()).equalsIgnoreCase(var)){
if (!(((((JComboBox) variables.get(i).get(1)).getSelectedItem()).toString()).equalsIgnoreCase("Not used"))){
if (((String)(((JComboBox) variables.get(i).get(5)).getSelectedItem())).equals("DMV")){
int v = findReqdVarslIndex(((JTextField) variables.get(i).get(0)).getText().trim());
reqdVarsL.get(v).forceDmvc(true);
//reqdVarsL.get(v).setDmvc(true);
} else if (((String)(((JComboBox) variables.get(i).get(5)).getSelectedItem())).equals("Continuous")){
int v = findReqdVarslIndex(((JTextField) variables.get(i).get(0)).getText().trim());
reqdVarsL.get(v).forceDmvc(false);
//reqdVarsL.get(v).setDmvc(false);
} else {
int v = findReqdVarslIndex(((JTextField) variables.get(i).get(0)).getText().trim());
reqdVarsL.get(v).forceDmvc(null);
}
break;
}
}
}
}
else if (e.getActionCommand().contains("mode")) {
//int num = Integer.parseInt(e.getActionCommand().substring(5)); // -1; ??
//reqdVarsL.get(num).setInput(!reqdVarsL.get(num).isInput());
String var = e.getActionCommand().substring(4,e.getActionCommand().length());
/*for (int i = 0; i < reqdVarsL.size() ; i++){ // COMMENTED after adding required
if (var.equalsIgnoreCase(reqdVarsL.get(i).getName())){
reqdVarsL.get(i).setInput(!reqdVarsL.get(i).isInput());
break;
}
}*/
for (int i = 0 ; i < variables.size(); i++){
if ((((JTextField) variables.get(i).get(0)).getText().trim()).equalsIgnoreCase(var)){
if (!(((((JComboBox) variables.get(i).get(1)).getSelectedItem()).toString()).equalsIgnoreCase("Not used"))){
reqdVarsL.get(findReqdVarslIndex(((JTextField) variables.get(i).get(0)).getText().trim())).setDestab(((JCheckBox) variables.get(i).get(2)).isSelected());
}
}
}
}
else if (e.getActionCommand().contains("care")) {
String var = e.getActionCommand().substring(4,e.getActionCommand().length());
for (int i = 0 ; i < variables.size(); i++){
if ((((JTextField) variables.get(i).get(0)).getText().trim()).equalsIgnoreCase(var)){
if (!(((((JComboBox) variables.get(i).get(1)).getSelectedItem()).toString()).equalsIgnoreCase("Not used"))){
reqdVarsL.get(findReqdVarslIndex(((JTextField) variables.get(i).get(0)).getText().trim())).setCare(((JCheckBox) variables.get(i).get(3)).isSelected());
}
}
}
}
else if (e.getActionCommand().contains("port")) {
//int num = Integer.parseInt(e.getActionCommand().substring(5)); // -1; ??
//reqdVarsL.get(num).setInput(!reqdVarsL.get(num).isInput());
String var = e.getActionCommand().substring(4,e.getActionCommand().length());
for (int i = 0 ; i < variables.size(); i++){
String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
if ((currentVar).equalsIgnoreCase(var)){
if (!(((((JComboBox) variables.get(i).get(1)).getSelectedItem()).toString()).equalsIgnoreCase("Not used"))){
((JCheckBox) variables.get(i).get(2)).setEnabled(true);
((JCheckBox) variables.get(i).get(3)).setEnabled(true);
((JTextField) variables.get(i).get(4)).setEnabled(true);
((JComboBox) variables.get(i).get(5)).setEnabled(true);
if ( auto.isSelected()) {
//TODO: could disable the comboboxes & thresholds though
// they would already be disabled here.
}
else{
for (int j = 6; j < variables.get(i).size(); j++) { // added after allVars
variables.get(i).get(j).setEnabled(true); // added after adding allVars
}
}
if (findReqdVarslIndex(var) == -1){
reqdVarsL.add(new Variable(var));
//((JCheckBox) variables.get(i).get(3)).setSelected(true);
if (((JCheckBox) variables.get(i).get(2)).isSelected()){
if (reqdVarsL.get(reqdVarsL.size() - 1).getName().equalsIgnoreCase(var))
reqdVarsL.get(reqdVarsL.size() - 1).setDestab(true);
}
if (!(((JCheckBox) variables.get(i).get(3)).isSelected())){
if (reqdVarsL.get(reqdVarsL.size() - 1).getName().equalsIgnoreCase(var))
reqdVarsL.get(reqdVarsL.size() - 1).setCare(false);
}
}
if ((((((JComboBox) variables.get(i).get(1)).getSelectedItem()).toString()).equalsIgnoreCase("Input"))){
reqdVarsL.get(findReqdVarslIndex(var)).setInput(true);
} else {
reqdVarsL.get(findReqdVarslIndex(var)).setInput(false);
}
}
else{
((JCheckBox) variables.get(i).get(2)).setEnabled(false);
((JCheckBox) variables.get(i).get(3)).setEnabled(false);
((JTextField) variables.get(i).get(4)).setEnabled(false);
((JComboBox) variables.get(i).get(5)).setEnabled(false);
for (int j = 6; j < variables.get(i).size(); j++) { // added after allVars
variables.get(i).get(j).setEnabled(false); // added after adding allVars
}
int ind = findReqdVarslIndex(var);
if (ind != -1){
reqdVarsL.remove(ind);
//TODO: Should keep updating reqdVarsIndices all the times??
}
}
}
}
//for (int i = 0; i < reqdVarsL.size() ; i++){
// if (var.equalsIgnoreCase(reqdVarsL.get(i).getName())){
// reqdVarsL.get(i).setInput(!reqdVarsL.get(i).isInput());
// break;
}
else if (e.getActionCommand().contains("epsilon")) {
String var = e.getActionCommand().substring(7,e.getActionCommand().length());
for (int i = 0 ; i < variables.size(); i++){
if ((((JTextField) variables.get(i).get(0)).getText().trim()).equalsIgnoreCase(var)){
if (!(((((JComboBox) variables.get(i).get(1)).getSelectedItem()).toString()).equalsIgnoreCase("Not used"))){
reqdVarsL.get(findReqdVarslIndex(((JTextField) variables.get(i).get(0)).getText().trim())).setEpsilon(Double.valueOf(((JTextField) variables.get(i).get(4)).getText()));
}
}
}
}
else if (e.getSource() == user) { // System.out.println(" ITS USER SELECTED ");
// if (!firstRead) {
try {
for (int i = 0; i < variables.size(); i++) {
String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
if (findReqdVarslIndex(currentVar) != -1){
((JCheckBox) variables.get(i).get(2)).setEnabled(true);
((JCheckBox) variables.get(i).get(3)).setEnabled(true);
((JTextField) variables.get(i).get(4)).setEnabled(true);
((JComboBox) variables.get(i).get(5)).setEnabled(true);
((JComboBox) variables.get(i).get(6)).setEnabled(true);
ArrayList<Double> iThresholds = thresholds.get(currentVar);
//System.out.println("iThresholds :"+iThresholds);
if ((iThresholds == null) || ( iThresholds.size() == 0)){ // This condition added later.. This ensures that when you switch from auto to user, the options of auto are written to the textboxes. SB.. rechk
if (variables.get(i).get(variables.get(i).size()-1) instanceof JTextField
&& ((JTextField) variables.get(i).get(variables.get(i).size()-1)).getText().trim().equals("")) {
} else if (variables.get(i).get(variables.get(i).size()-1) instanceof JTextField) {
thresholds.put(currentVar,new ArrayList<Double>());
thresh = ((JTextField) variables.get(i).get(variables.get(i).size()-1)).getText().trim();
//System.out.println("thresh : "+thresh);
String[] threshValues = thresh.split(",");
//System.out.println("threshValues.length is : "+threshValues.length);
for (int m=0; m<threshValues.length; m++){
thresholds.get(currentVar).add(Double.parseDouble(threshValues[m]));
//System.out.println("m is : "+m);
//System.out.println("thresh : "+variables.get(i).get(m));
}
//System.out.println("Thresholds :"+thresholds);
}
}
}
else{
((JCheckBox) variables.get(i).get(2)).setEnabled(false);
((JCheckBox) variables.get(i).get(3)).setEnabled(false);
((JTextField) variables.get(i).get(4)).setEnabled(false);
((JComboBox) variables.get(i).get(5)).setEnabled(false);
((JComboBox) variables.get(i).get(6)).setEnabled(false);
}
// write.write("\n");
}
// write.close();
} catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Unable to save thresholds!",
"Error saving thresholds", JOptionPane.ERROR_MESSAGE);
}
numBinsLabel.setEnabled(false);
numBins.setEnabled(false);
suggest.setEnabled(true);
// levelsBin();
variablesPanel.revalidate();
variablesPanel.repaint();
levels(); // To be added later? if the scaled divisions are not supposed to be shown after auto to user switching, then should have something like divsB4scaling which should be passed as a parameter to
} else if (e.getSource() == auto) {
numBinsLabel.setEnabled(true);
numBins.setEnabled(true);
suggest.setEnabled(false);
//int j = 0; // recheck .. SB
for (Component c : variablesPanel.getComponents()) {
for (int i = 6; i < ((JPanel) c).getComponentCount(); i++) { // changed 1 to 2 SB
((JPanel) c).getComponent(i).setEnabled(false);
}
}
} else if (e.getSource() == suggest) {
suggestIsSource = true;
autogen(false);
//levels();
variablesPanel.revalidate();
variablesPanel.repaint();
int j = 0;
for (Component c : variablesPanel.getComponents()) {
if (j == 0){ // recheck .. SB
j++;
continue;
}
String currentVar = ((JTextField)((JPanel) c).getComponent(0)).getText().trim();
int ind = findReqdVarslIndex(currentVar);
if (ind != -1){ //this code shouldn't be required ideally.
if (reqdVarsL.get(ind).isInput()){ //tempPorts.get(j-1)){
((JComboBox)((JPanel) c).getComponent(1)).setSelectedItem("Input"); // SB // changed 1 to 2 after required
} else {
((JComboBox)((JPanel) c).getComponent(1)).setSelectedItem("Output"); // SB // changed 1 to 2 after required
}
if (reqdVarsL.get(ind).isDestab()){ //tempPorts.get(j-1)){
((JCheckBox)((JPanel) c).getComponent(2)).setSelected(true); // SB // changed 1 to 2 after required
} else {
((JCheckBox)((JPanel) c).getComponent(2)).setSelected(false); // SB // changed 1 to 2 after required
}
if (reqdVarsL.get(ind).isCare()){ //tempPorts.get(j-1)){
((JCheckBox)((JPanel) c).getComponent(3)).setSelected(true); // SB // changed 1 to 2 after required
}
}
j++;
}
variablesPanel.revalidate();
variablesPanel.repaint();
}
// if the browse initial network button is clicked
// else if (e.getSource() == browseInit) {
// Buttons.browse(this, new File(initNetwork.getText().trim()),
// initNetwork,
// JFileChooser.FILES_ONLY, "Open");
// if the run button is selected
else if (e.getSource() == run) {
if (!auto.isSelected()){
save();
learn();
}
else{
learn();
}
} else if (e.getSource() == save) {
save();
} else if (e.getSource() == viewLhpn) {
viewLhpn();
} else if (e.getSource() == viewLog) {
viewLog();
} else if (e.getSource() == saveLhpn) {
saveLhpn();
} else if (e.getSource() == viewCoverage) {
viewCoverage();
} else if (e.getSource() == viewVHDL) {
viewVHDL();
} else if (e.getSource() == viewVerilog) {
viewVerilog();
}
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == absTimeG) {
absoluteTime = !absoluteTime;
if (e.getStateChange() == ItemEvent.DESELECTED){
absTimeG.setSelected(false);
runTimeG.setEnabled(false);
runLengthG.setEnabled(true);
}
else{
absTimeG.setSelected(true);
runTimeG.setEnabled(true);
runLengthG.setEnabled(false);
}
} else if (source == defaultEnvG) {
if (e.getStateChange() == ItemEvent.DESELECTED){
defaultEnvG.setSelected(false);
}
else{
defaultEnvG.setSelected(true);
}
}
}
private void autogen(boolean readfile) {
try {
if (!readfile) {
if (variables !=null){
for (int i = 0; i < variables.size(); i++) {
//for (int j = 7; j < variables.get(i).size(); j++) { // changed 2 to 3 SB
// TODO: Needs to be updated to extract thresholds from comma-separated field
if (variables.get(i).get(variables.get(i).size()-1) instanceof JTextField
&& ((JTextField) variables.get(i).get(variables.get(i).size()-1)).getText().trim().equals("")) {
} else if (variables.get(i).get(variables.get(i).size()-1) instanceof JTextField) {
thresh = ((JTextField) variables.get(i).get(variables.get(i).size()-1)).getText().trim();
//System.out.println("thresh : "+thresh);
String[] threshValues = thresh.split(",");
int size = thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).size();
if (thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).size() <= threshValues.length-size){ // changed 3 to 4 after required
for (int m=threshValues.length-size; m<threshValues.length; m++){
thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).add(Double.parseDouble(threshValues[m]));}
}
else{
//int size = thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).size();
for (int m=threshValues.length-size; m<threshValues.length; m++){
thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).set(m,Double.parseDouble(threshValues[m]));} // changed 3 to 4 after required
}
}
}
}
generate = true;
execute = false;
LearnThread = new Thread(this);
LearnThread.start();
}
} catch (Exception e1) {
e1.printStackTrace();
levels();
}
}
private void levels() {
if (!directory.equals("")) {
if (true) {
variablesPanel.removeAll();
this.variables = new ArrayList<ArrayList<Component>>();
variablesPanel.setLayout(new GridLayout(allVars.size() + 1, 1));
int max = 0;
if (!thresholds.isEmpty()){
for (String s : thresholds.keySet()){
if (thresholds.get(s) != null) {
max = Math.max(max, thresholds.get(s).size()+2);
//System.out.println("Max is : "+thresholds.get(s).size());
}
}
}
JPanel label = new JPanel(new FlowLayout(FlowLayout.LEADING));
label.add(new JLabel("Variables "));
label.add(new JLabel("Port "));
label.add(new JLabel("Ctrl"));
label.add(new JLabel("Care"));
label.add(new JLabel("Epsilon"));
label.add(new JLabel("Type "));
label.add(new JLabel("# Bins "));
label.add(new JLabel("Levels"));
variablesPanel.add(label);
int j = 0;
for (String s : allVars) {
j++;
JPanel sp = new JPanel(new FlowLayout(FlowLayout.LEADING,0,0));
ArrayList<Component> specs = new ArrayList<Component>();
JTextField varsText = new JTextField(10);
varsText.setText(s);
specs.add(varsText);
String[] options = { "Auto", "2", "3", "4", "5", "6", "7", "8", "16", "32"};
JComboBox combo = new JComboBox(options);
String[] portOptions = {"Not used", "Input", "Output"};
JComboBox port = new JComboBox(portOptions);
JCheckBox mode = new JCheckBox();
JCheckBox care = new JCheckBox();
JTextField epsilonTb = new JTextField(3);
epsilonTb.setText(epsilonG.getText().trim());
String[] dmvOptions = {"DMV", "Continuous", "Auto"};
JComboBox dmv = new JComboBox(dmvOptions);
port.addActionListener(this);
mode.addActionListener(this);
care.addActionListener(this);
dmv.addActionListener(this);
epsilonTb.addActionListener(this);
port.setActionCommand("port" + s);
mode.setActionCommand("mode" + s);
care.setActionCommand("care" + s);
dmv.setActionCommand("DMV" + s);
dmv.setSelectedItem("Auto");
epsilonTb.setActionCommand("epsilon" + s);
combo.setSelectedItem(numBins.getSelectedItem());
specs.add(port);
specs.add(mode);
specs.add(care);
specs.add(epsilonTb);
specs.add(dmv);
specs.add(combo);
((JTextField) specs.get(0)).setEditable(false);
//System.out.println("this is specs :"+specs.get(2));
sp.add(specs.get(0));
sp.add(specs.get(1));
sp.add(specs.get(2));
sp.add(specs.get(3));
sp.add(specs.get(4));
sp.add(specs.get(5));
sp.add(specs.get(6));
if (findReqdVarslIndex(s) != -1){
if (reqdVarsL.get((findReqdVarslIndex(s))).isInput())
((JComboBox) specs.get(1)).setSelectedItem("Input");
else
((JComboBox) specs.get(1)).setSelectedItem("Output");
((JCheckBox) specs.get(2)).setEnabled(true);
((JCheckBox) specs.get(3)).setEnabled(true);
((JTextField) specs.get(4)).setEnabled(true);
((JComboBox) specs.get(5)).setEnabled(true);
((JComboBox) specs.get(6)).setEnabled(true);
if (reqdVarsL.get(findReqdVarslIndex(s)).isDestab()){
((JCheckBox) specs.get(2)).setSelected(true);
}
else{
((JCheckBox) specs.get(2)).setSelected(false);
}
if (reqdVarsL.get(findReqdVarslIndex(s)).isCare()){
((JCheckBox) specs.get(3)).setSelected(true);
}
else{
((JCheckBox) specs.get(3)).setSelected(false);
}
if (reqdVarsL.get(findReqdVarslIndex(s)).getEpsilon()!= null){
((JTextField) specs.get(4)).setText(String.valueOf(reqdVarsL.get(findReqdVarslIndex(s)).getEpsilon()));
} else if (epsilonG.getText() != ""){
((JTextField) specs.get(4)).setText(epsilonG.getText().trim());
}
if (!dmvDetectDone && !dmvStatusLoaded)
((JComboBox) specs.get(5)).setSelectedItem("Auto");
else{
if (reqdVarsL.get(findReqdVarslIndex(s)).isDmvc()){
((JComboBox) specs.get(5)).setSelectedItem("DMV");
}
else{
((JComboBox) specs.get(5)).setSelectedItem("Continuous");
}
}
}
else{ // variable not required
((JComboBox) specs.get(1)).setSelectedItem("Not used"); // changed 1 to 2 after required
((JCheckBox) specs.get(2)).setEnabled(false); // added after allVars
((JCheckBox) specs.get(3)).setEnabled(false); // added after allVars
((JTextField) specs.get(4)).setEnabled(false); // added after allVars
((JComboBox) specs.get(5)).setEnabled(false);
((JComboBox) specs.get(6)).setEnabled(false);
}
((JComboBox) specs.get(6)).addActionListener(this); // changed 1 to 2 SB
((JComboBox) specs.get(6)).setActionCommand("text" + j);// changed 1 to 2 SB
this.variables.add(specs);
/* TODO: fix here for new comma-separated thresholds. */
if (!thresholds.isEmpty()) {
if (findReqdVarslIndex(s) != -1){ //This condition added after adding allvarsL
ArrayList<Double> div = thresholds.get(s);
//System.out.println("Div size :"+div.size());
if ((div != null) && (div.size() > 0)){ //changed >= to >
((JComboBox) specs.get(6)).setSelectedItem(String.valueOf(div.size()+1));// changed 1 to 2 SB
String selected = (String) ((JComboBox) specs.get(6)).getSelectedItem();
//System.out.println("selected "+selected);
int combox_selected;
if (!selected.equalsIgnoreCase("Auto"))
combox_selected = Integer.parseInt(selected);
else
combox_selected = 0;
StringBuilder builder = new StringBuilder(div.size()); //DRK
for (int o=0;o<div.size();o++){//DRK
long app = (long) ((div.get(o))*valScaleFactor);
builder.append((double) (app/valScaleFactor));
//builder.
if (o!=div.size()-1)
builder.append(",");}//DRK
specs.add(new JTextField(builder.toString(),20)); //DRK
sp.add(specs.get(7)); //System.out.println("builder :"+builder.toString()); // changed 2 to 3 SB
selected = (String) ((JComboBox) specs.get(6)).getSelectedItem();
if (!selected.equalsIgnoreCase("Auto"))
combox_selected = Integer.parseInt(selected);
else
combox_selected = 0;
for (int i = combox_selected - 1; i < max - 2; i++) {// changed 1 to 2 SB
sp.add(new JLabel());
}
}
else{
}
String selected = (String) ((JComboBox) specs.get(6)).getSelectedItem();
int combox_selected;
if (!selected.equalsIgnoreCase("Auto"))
combox_selected = Integer.parseInt(selected);
else
combox_selected = 0;
//for (int i = 0; i < combox_selected - 1; i++) {
if (specs.size() > 7) {
((JTextField) specs.get(7)).setEnabled(true);
}
if (reqdVarsL.get((findReqdVarslIndex(s))).isInput())
((JComboBox) specs.get(1)).setSelectedItem("Input"); // changed 1 to 2 after required
else
((JComboBox) specs.get(1)).setSelectedItem("Output"); // changed 1 to 2 after required
((JCheckBox) specs.get(2)).setEnabled(true);
((JCheckBox) specs.get(3)).setEnabled(true);
((JTextField) specs.get(4)).setEnabled(true);
((JComboBox) specs.get(5)).setEnabled(true);
((JComboBox) specs.get(6)).setEnabled(true);
if (reqdVarsL.get(findReqdVarslIndex(s)).isDestab()){ // This was there before. removed on june 29 thinking redundant
((JCheckBox) specs.get(2)).setSelected(true);
} else {
((JCheckBox) specs.get(2)).setSelected(false);
}
if (reqdVarsL.get(findReqdVarslIndex(s)).isCare()){
((JCheckBox) specs.get(3)).setSelected(true);
}
if (!dmvDetectDone && !dmvStatusLoaded)
((JComboBox) specs.get(5)).setSelectedItem("Auto");
else{
if (reqdVarsL.get(findReqdVarslIndex(s)).isDmvc()){
((JComboBox) specs.get(5)).setSelectedItem("DMV");
}
else{
((JComboBox) specs.get(5)).setSelectedItem("Continuous");
}
}
}
else{
((JComboBox) specs.get(1)).setSelectedItem("Not used");
((JCheckBox) specs.get(2)).setEnabled(false);
((JCheckBox) specs.get(3)).setEnabled(false);
((JTextField) specs.get(4)).setEnabled(false);
((JComboBox) specs.get(5)).setEnabled(false);
((JComboBox) specs.get(6)).setEnabled(false);
String selected = (String) ((JComboBox) specs.get(6)).getSelectedItem();
int combox_selected;
if (!selected.equalsIgnoreCase("Auto"))
combox_selected = Integer.parseInt(selected);
else
combox_selected = 0;
}
} else {
if (findReqdVarslIndex(((JTextField) sp.getComponent(0)).getText().trim()) != -1){
if (reqdVarsL.get((findReqdVarslIndex(s))).isInput())
((JComboBox) specs.get(1)).setSelectedItem("Input"); // changed 1 to 2 after required
else
((JComboBox) specs.get(1)).setSelectedItem("Output"); // changed 1 to 2 after required
((JCheckBox) specs.get(2)).setEnabled(true);
((JCheckBox) specs.get(3)).setEnabled(true);
((JTextField) specs.get(4)).setEnabled(true);
((JComboBox) specs.get(5)).setEnabled(true);
((JComboBox) specs.get(6)).setEnabled(true);
if (reqdVarsL.get(findReqdVarslIndex(s)).isDestab()){
((JCheckBox) specs.get(2)).setSelected(true);
} else {
((JCheckBox) specs.get(2)).setSelected(false);
}
if (reqdVarsL.get(findReqdVarslIndex(s)).isCare()){
((JCheckBox) specs.get(3)).setSelected(true);
}
if (!dmvDetectDone && !dmvStatusLoaded)
((JComboBox) specs.get(5)).setSelectedItem("Auto");
else{
if (reqdVarsL.get(findReqdVarslIndex(s)).isDmvc()){
((JComboBox) specs.get(5)).setSelectedItem("DMV");
}
else{
((JComboBox) specs.get(5)).setSelectedItem("Continuous");
}
}
}
else{
((JComboBox) specs.get(1)).setSelectedItem("Not used");
((JCheckBox) specs.get(2)).setEnabled(false);
((JCheckBox) specs.get(3)).setEnabled(false);
((JTextField) specs.get(4)).setEnabled(false);
((JComboBox) specs.get(5)).setEnabled(false);
((JComboBox) specs.get(6)).setEnabled(false);
}
String selected = (String) ((JComboBox) specs.get(6)).getSelectedItem();
int combox_selected;
if (!selected.equalsIgnoreCase("Auto")){//System.out.println("I am here");
combox_selected = Integer.parseInt(selected);}
else
combox_selected = 0;
specs.add(new JTextField("",20));
sp.add(specs.get(7));// changed 1 to 2 SB //changed to 4 bcoz of a bug
if (findReqdVarslIndex(((JTextField) sp.getComponent(0)).getText().trim()) != -1){
((JTextField) specs.get(7)).setEnabled(true);
}
else{
((JTextField) specs.get(7)).setEnabled(false);
}
}
variablesPanel.add(sp);
}
}
}
variablesPanel.revalidate(); //july 21,2010
variablesPanel.repaint(); //july 21,2010
//editText(0);
}
private int findReqdVarslIndex(String s) {
for (int i = 0; i < reqdVarsL.size() ; i++){
if (s.equalsIgnoreCase(reqdVarsL.get(i).getName())){
return i;
}
}
return -1;
}
public void saveLhpn() {
try {
if (true) {// (new File(directory + separator +
// "method.gcm").exists()) {
String copy = JOptionPane.showInputDialog(Gui.frame,
"Enter Circuit Name:", "Save Circuit",
JOptionPane.PLAIN_MESSAGE);
if (copy != null) {
copy = copy.trim();
} else {
return;
}
if (!copy.equals("")) {
if (copy.length() > 1) {
if (copy.length() < 4 || !copy.substring(copy.length() - 4).equals(".lpn")) {
copy += ".lpn";
}
} else {
copy += ".lpn";
}
}
biosim.saveLhpn(copy, directory + separator + lhpnFile);
} else {
JOptionPane.showMessageDialog(Gui.frame,
"No circuit has been generated yet.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to save model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewLhpn() {
try {
File work = new File(directory);
if (new File(directory + separator + lhpnFile).exists()) {
String dotFile = lhpnFile.replace(".lpn", ".dot");
File dot = new File(directory + separator + dotFile);
dot.delete();
LhpnFile lhpn = new LhpnFile(log);
lhpn.load(directory + separator + lhpnFile);
lhpn.printDot(directory + separator + dotFile);
//log.addText("Executing:\n" + "atacs -cPllodpl " + lhpnFile);
Runtime exec = Runtime.getRuntime();
//Process load = exec.exec("atacs -cPllodpl " + lhpnFile, null,
// work);
//load.waitFor();
if (dot.exists()) {
viewLhpn.setEnabled(true);
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open " + dotFile;
log.addText("gnome-open " + directory + separator
+ dotFile + "\n");
} else {
command = "open " + dotFile;
log.addText("open " + directory + separator + dotFile
+ "\n");
}
exec.exec(command, null, work);
} else {
File log = new File(directory + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(
log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea
.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls,
"Log", JOptionPane.INFORMATION_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(Gui.frame,
"No circuit has been generated yet.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to view LPN Model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewLog() {
try {
if (new File(directory + separator + "run.log").exists()) {
File log = new File(directory + separator + "run.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls,
"Run Log", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(Gui.frame,
"No run log exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to view run log.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewLearnComplete() {
JFrame learnComplete = new JFrame("LEMA");
learnComplete.setResizable(false);
JPanel all = new JPanel(new BorderLayout());
JLabel label = new JLabel("<html><b>Learning Completed</b></html>",SwingConstants.CENTER);
all.add(label, BorderLayout.CENTER);
Dimension screenSize;
learnComplete.setContentPane(all);
learnComplete.setMinimumSize(new Dimension(300,140));
learnComplete.pack();
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
} catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = learnComplete.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
learnComplete.setLocation(x, y);
learnComplete.setVisible(true);
// learnComplete.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
public void viewCoverage() {
try {
if (new File(directory + separator + "run.cvg").exists()) {
File cvgRpt = new File(directory + separator + "run.cvg");
BufferedReader input = new BufferedReader(new FileReader(cvgRpt));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls,
"Coverage Report", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(Gui.frame,
"No Coverage Report exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to view Coverage Report.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewVHDL() {
try {
String vhdFile = lhpnFile.replace(".lpn", ".vhd");
if (new File(directory + separator + vhdFile).exists()) {
File vhdlAmsFile = new File(directory + separator + vhdFile);
BufferedReader input = new BufferedReader(new FileReader(vhdlAmsFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls,
"VHDL-AMS Model", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(Gui.frame,
"VHDL-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to view VHDL-AMS model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewVerilog() {
try {
String vamsFileName = lhpnFile.replace(".lpn", ".sv");
if (new File(directory + separator + vamsFileName).exists()) {
File vamsFile = new File(directory + separator + vamsFileName);
BufferedReader input = new BufferedReader(new FileReader(vamsFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls,
"Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(Gui.frame,
"Verilog-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to view Verilog-AMS model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void save() {
/* TODO: update for new threshold field */
try {
Properties prop = new Properties();
FileInputStream in = new FileInputStream(new File(directory + separator + lrnFile));
prop.load(in);
in.close();
prop.setProperty("learn.file", seedLpnFile);
prop.setProperty("learn.iter", this.iteration.getText().trim());
prop.setProperty("learn.valueScaling", this.globalValueScaling.getText().trim());
prop.setProperty("learn.delayScaling", this.globalDelayScaling.getText().trim());
prop.setProperty("learn.bins", (String) this.numBins.getSelectedItem());
prop.setProperty("learn.prop", (String) this.propertyG.getText().trim());
String varsList = null;
if (range.isSelected()) {
prop.setProperty("learn.equal", "range");
} else {
prop.setProperty("learn.equal", "points");
}
if (auto.isSelected()) {
prop.setProperty("learn.use", "auto");
int k = 0; // added later .. so that the exact divisions are stored to file when auto is selected. & not the divisions in the textboxes
int inputCount = 0, dmvCount = 0, contCount = 0, autoVarCount = 0, dontcareCount = 0, destabCount = 0;
String ip = null, dmv = null, cont = null, autoVar = null, dontcares = null, destab = null;
String selected = this.numBins.getSelectedItem().toString();
//int numOfBins = Integer.parseInt(this.numBins.getSelectedItem().toString());
int numOfBins;
if (!selected.equalsIgnoreCase("Auto"))
numOfBins = Integer.parseInt(selected);
else
numOfBins = 0;
//int numThresholds = numOfBins -1;
for (Component c : variablesPanel.getComponents()) {
if (k == 0){
k++;
continue;
}
if (!((((JComboBox)((JPanel)c).getComponent(1)).getSelectedItem().toString()).equalsIgnoreCase("Not used"))){ // added after required
if (varsList == null){
varsList = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
varsList += " "+ ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
String currentVar = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
String s = currentVar + " " + numOfBins;
if ((thresholds != null) && (thresholds.size() != 0)){
for (int i = 0; i < (numOfBins -1); i++){
if ((thresholds.get(currentVar)!= null) && (thresholds.get(currentVar).size() > i)){
s += " ";
s += thresholds.get(currentVar).get(i);
}
}
}
prop.setProperty("learn.bins"+ currentVar, s);
if ((((JComboBox)((JPanel)c).getComponent(1)).getSelectedItem().toString()).equalsIgnoreCase("Input")){ // changed 1 to 2 after required
if (inputCount == 0){
inputCount++;
ip = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
ip = ip + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
if (((JCheckBox)((JPanel)c).getComponent(2)).isSelected()){ // changed 1 to 2 after required
if (destabCount == 0){
destabCount++;
destab = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
destab = destab + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
if (!(((JCheckBox)((JPanel)c).getComponent(3)).isSelected())){
if (dontcareCount == 0){
dontcareCount++;
dontcares = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
dontcares = dontcares + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
if (!(((JTextField)((JPanel)c).getComponent(4)).getText().trim().equalsIgnoreCase(""))){
String e = ((JTextField)((JPanel)c).getComponent(4)).getText().trim();
prop.setProperty("learn.epsilon"+ ((JTextField)((JPanel)c).getComponent(0)).getText().trim(), e);
}
if (((String)(((JComboBox)((JPanel)c).getComponent(5)).getSelectedItem())).equals("DMV")){
if (dmvCount == 0){
dmvCount++;
dmv = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
dmv = dmv + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
if (((String)(((JComboBox)((JPanel)c).getComponent(5)).getSelectedItem())).equals("Continuous")){
if (contCount == 0){
contCount++;
cont = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
cont = cont + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
if (((String)(((JComboBox)((JPanel)c).getComponent(5)).getSelectedItem())).equals("Auto")){
if (autoVarCount == 0){
autoVarCount++;
autoVar = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
autoVar = autoVar + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
}
k++;
}
if (inputCount != 0){
prop.setProperty("learn.inputs", ip);
}
else{
prop.remove("learn.inputs");
}
if (destabCount != 0){
prop.setProperty("learn.destabs", ip);
}
else{
prop.remove("learn.destabs");
}
if (dontcareCount != 0){
prop.setProperty("learn.dontcares", dontcares);
}
else{
prop.remove("learn.dontcares");
}
if (dmvCount != 0)
prop.setProperty("learn.dmv", dmv);
else
prop.remove("learn.dmv");
if (contCount != 0)
prop.setProperty("learn.cont", cont);
else
prop.remove("learn.cont");
if (autoVarCount != 0)
prop.setProperty("learn.autoVar", autoVar);
else
prop.remove("learn.autoVar");
} else {
prop.setProperty("learn.use", "user");
int k = 0;
int inputCount = 0, dmvCount = 0, contCount = 0, autoVarCount = 0, dontcareCount = 0, destabCount = 0;
String ip = null, dmv = null, cont = null, autoVar = null, dontcares = null, destab = null;
for (Component c : variablesPanel.getComponents()) {
if (k == 0){
k++;
continue;
}
if (!((((JComboBox)((JPanel)c).getComponent(1)).getSelectedItem().toString()).equalsIgnoreCase("Not used"))){
if (varsList == null) { //(k == 1){
varsList = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
varsList += " "+ ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
String selected = (String)((JComboBox)((JPanel)c).getComponent(6)).getSelectedItem(); // changed to 3 after required
int numOfBins;
if (!selected.equalsIgnoreCase("Auto"))
numOfBins = Integer.parseInt(selected)-1; // added -1; chk if issues.
else
numOfBins = 0;
String s = ((JTextField)((JPanel)c).getComponent(0)).getText().trim() + " " + numOfBins; // changed to 3 after required
//int numOfBins = Integer.parseInt((String)((JComboBox)((JPanel)c).getComponent(6)).getSelectedItem())-1; // changed to 3 after required
if (numOfBins > 0) {
s += " " + ((JTextField)(((JPanel)c).getComponent(7))).getText().trim().replace(",", " ");
}
//for (int i = 0; i < numOfBins; i++){
// s += ((JTextField)(((JPanel)c).getComponent(i+7))).getText().trim();// changed to 4 after required
prop.setProperty("learn.bins"+ ((JTextField)((JPanel)c).getComponent(0)).getText().trim(), s);
if ((((JComboBox)((JPanel)c).getComponent(1)).getSelectedItem().toString()).equalsIgnoreCase("Input")){ // changed 1 to 2 after required
if (inputCount == 0){
inputCount++;
ip = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
ip = ip + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
if (((JCheckBox)((JPanel)c).getComponent(2)).isSelected()){ // changed 1 to 2 after required
if (destabCount == 0){
destabCount++;
destab = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
destab = destab + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
if (!(((JCheckBox)((JPanel)c).getComponent(3)).isSelected())){
if (dontcareCount == 0){
dontcareCount++;
dontcares = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();//((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
dontcares = dontcares + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
if (!(((JTextField)((JPanel)c).getComponent(4)).getText().trim().equalsIgnoreCase(""))){
String e = ((JTextField)((JPanel)c).getComponent(4)).getText().trim();
prop.setProperty("learn.epsilon"+ ((JTextField)((JPanel)c).getComponent(0)).getText().trim(), e);
}
if (((String)(((JComboBox)((JPanel)c).getComponent(5)).getSelectedItem())).equals("DMV")){ // changed 1 to 2 after required
if (dmvCount == 0){
dmvCount++;
dmv = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
dmv = dmv + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
if (((String)(((JComboBox)((JPanel)c).getComponent(5)).getSelectedItem())).equals("Continuous")){ // changed 1 to 2 after required
if (contCount == 0){
contCount++;
cont = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
cont = cont + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
if (((String)(((JComboBox)((JPanel)c).getComponent(5)).getSelectedItem())).equals("Auto")){
if (autoVarCount == 0){
autoVarCount++;
autoVar = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
autoVar = autoVar + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
}
k++;
}
if (inputCount != 0){
prop.setProperty("learn.inputs", ip);
}
else{
prop.remove("learn.inputs");
}
if (dontcareCount != 0){
prop.setProperty("learn.dontcares", dontcares);
}
else{
prop.remove("learn.dontcares");
}
if (dmvCount != 0)
prop.setProperty("learn.dmv", dmv);
else
prop.remove("learn.dmv");
if (contCount != 0)
prop.setProperty("learn.cont", cont);
else
prop.remove("learn.cont");
if (autoVarCount != 0)
prop.setProperty("learn.autoVar", autoVar);
else
prop.remove("learn.autoVar");
}
prop.setProperty("learn.epsilon", this.epsilonG.getText().trim());
prop.setProperty("learn.pathLengthBin", this.pathLengthBinG.getText().trim());
prop.setProperty("learn.pathLengthVar", this.pathLengthVarG.getText().trim());
prop.setProperty("learn.rateSampling", this.rateSamplingG.getText().trim());
prop.setProperty("learn.percent", this.percentG.getText().trim());
prop.setProperty("learn.absTime",String.valueOf(this.absTimeG.isSelected()));
prop.setProperty("learn.runTime",this.runTimeG.getText().trim());
prop.setProperty("learn.runLength",this.runLengthG.getText().trim());
prop.setProperty("learn.defaultEnv",String.valueOf(this.defaultEnvG.isSelected()));
if (varsList != null){
prop.setProperty("learn.varsList",varsList);
}
else{
prop.remove("learn.varsList");
}
log.addText("Saving learn parameters to file:\n" + directory
+ separator + lrnFile + "\n");
FileOutputStream out = new FileOutputStream(new File(directory + separator + lrnFile));
prop.store(out, seedLpnFile);
out.close();
// log.addText("Creating levels file:\n" + directory + separator +
// binFile + "\n");
// String command = "autogenT.py -b" + binFile + " -t"
// + numBins.getSelectedItem().toString() + " -i" +
// iteration.getText();
// if (range.isSelected()) {
// command = command + " -cr";
// File work = new File(directory);
// Runtime.getRuntime().exec(command, null, work);
change = false;
} catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Unable to save parameter file!", "Error Saving File",
JOptionPane.ERROR_MESSAGE);
}
}
public void reload(String newname) {
backgroundField.setText(newname);
}
public void learn() {
// TODO: needs to be update for new thresholds
try {
if (auto.isSelected()) {
for (int i = 0; i < variables.size(); i++) {
if (variables.get(i).get(variables.get(i).size()-1) instanceof JTextField
&&(((JTextField) variables.get(i).get(7)).getText().trim().equals(""))) {
} else if (variables.get(i).get(variables.get(i).size()-1) instanceof JTextField) {
String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
//System.out.println("Current Var :"+currentVar);
thresholds.put(currentVar,new ArrayList<Double>());
thresh = ((JTextField) variables.get(i).get(variables.get(i).size()-1)).getText().trim();
String[] threshValues = thresh.split(",");
//System.out.println("threshvalues.length : "+threshValues.length);
for (int m=0; m<threshValues.length; m++){
thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).add(Double.parseDouble(threshValues[m]));
//System.out.println("thresh : "+variables.get(i).get(m));
}
}
}
generate = true;
//System.out.println("Generate true");
} else {
//System.out.println("else part");
for (int i = 0; i < variables.size(); i++) {
if ((variables.get(i).get(variables.get(i).size()-1) instanceof JTextField
&&((JTextField) variables.get(i).get(7)).getText().trim().equals(""))) {
} else if ((variables.get(i).get(variables.get(i).size()-1) instanceof JTextField)) {
int size = thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).size();
String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
thresh = ((JTextField) variables.get(i).get(variables.get(i).size()-1)).getText().trim();
//System.out.println("thresh : "+thresh);
String[] threshValues = thresh.split(",");
thresholds.put(currentVar,new ArrayList<Double>());
for (int m=0; m<threshValues.length; m++){
thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).add(Double.parseDouble(threshValues[m]));
}
}
}
generate = false;
}
execute = true;
LearnThread = new Thread(this);
LearnThread.start();
}
catch (NullPointerException e1) {
e1.printStackTrace();
System.out.println("Some problem with thresholds hashmap");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Some problem");
}
}
public void run() { // System.out.println("M in run");
/* TODO: need to update for new thresholds */
new File(directory + separator + lhpnFile).delete();
fail = false;
try {
//File work = new File(directory);
final JFrame running = new JFrame("Progress");
//running.setUndecorated(true);
final JButton cancel = new JButton("Cancel");
running.setResizable(false);
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
running.dispose();
}
public void windowOpened(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowActivated(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
};
running.addWindowListener(w);
JPanel text = new JPanel();
JPanel progBar = new JPanel();
JPanel button = new JPanel();
JPanel all = new JPanel(new BorderLayout());
JLabel label = new JLabel("Running...");
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
// progress.setStringPainted(true);
// progress.setString("");
progress.setValue(0);
text.add(label);
progBar.add(progress);
button.add(cancel);
all.add(text, "North");
all.add(progBar, "Center");
all.add(button, "South");
running.setContentPane(all);
running.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
} catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = running.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
running.setLocation(x, y);
running.setVisible(true);
running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
logFile = new File(directory + separator + "run.log");
logFile.createNewFile();
out = new BufferedWriter(new FileWriter(logFile));
cancel.setActionCommand("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
running.setCursor(null);
running.dispose();
if (LearnThread != null) {
LearnThread.stop();
}
//throw new RuntimeException();
//TODO: Need to kill thread somehow???
}
});
HashMap<String,Double> tPar = getThreshPar(); //reqdVarsL should be correct b4 this call
if (generate) {
out.write("Running autoGenT\n");
thresholds = autoGenT(running);
if (!execute) {
levels();
}
else{ //added later.. for saving the autogenerated thresholds into learn file after generating thresholds & before running data2lhpn
save();
}
}
if (execute && !fail) {
File lhpn = new File(directory + separator + lhpnFile);
lhpn.delete();
// dataToLHPN(running);
int moduleNumber = 0;
String failProp = getProp();
// for (int k = 0; k < reqdVarsL.size(); k++){
// if ((reqdVarsL.get(k).getName().equalsIgnoreCase("muxsel")) || (reqdVarsL.get(k).getName().equalsIgnoreCase("dacsel")) || (reqdVarsL.get(k).getName().equalsIgnoreCase("clk")))
// reqdVarsL.get(k).setCare(false);
LearnModel l = new LearnModel();
out.write("Sending the following thresholds for model generation \n");
// Warn the user if the internal thresholds don't match those being
// displayed in the GUI. Useful for debugging.
boolean warned = false;
for (String st1 : thresholds.keySet()){ //System.out.println("threshold key set :"+thresholds.keySet());
out.write(st1 + " -> ");
for (int i = 0; i < variables.size(); i++){
String cVar = ((JTextField) variables.get(i).get(0)).getText().trim();
if ((cVar.equalsIgnoreCase(st1)) && (((JComboBox) variables.get(i).get(6)).isEnabled())){ // System.out.println("st1 2:"+variables.get(i).get(0));
//int combox_selected = Integer.parseInt((String) ((JComboBox) variables.get(i).get(6)).getSelectedItem()); // changed 2 to 3 after required
String selected = (String) (((JComboBox) variables.get(i).get(6)).getSelectedItem());
// System.out.println("selected :"+selected);
// changed 2 to 3 after required
int combox_selected;
if (!selected.equalsIgnoreCase("Auto"))
combox_selected = Integer.parseInt(selected); // changed 2 to 3 after required
else
combox_selected = 0;
if (thresholds.get(st1).size() == (combox_selected -1)){
thresh = ((JTextField) variables.get(i).get(variables.get(i).size()-1)).getText().trim();
String[] threshValues = thresh.split(",");
if (thresh!=null) {
//int size = thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).size();
for (int j = 0; j < thresholds.get(st1).size(); j++){ //System.out.println("hellos :"+st1);
//if (!warned &&(thresholds.get(st1).get(j)!= null)&& (thresholds.get(st1).get(j)!= Double.parseDouble(threshValues[j]))){
if (!warned &&(thresholds.get(st1).get(j)!= null)&& ((threshValues[j])!= null)){
if (thresholds.get(st1).get(j)!= Double.parseDouble(threshValues[j])){ //System.out.println("the error value is :");
warned = true;
out.write("WARNING: THRESHOLDS OF " + st1 + " NOT MATCHING THOSE IN THE GUI. WRONG!");
JOptionPane.showMessageDialog(Gui.frame,
"Thresholds of " + st1 + " not matching those displayed in the gui.",
"WARNING!", JOptionPane.WARNING_MESSAGE);
}
}
}}
} else {
if (!warned && (thresh!=null)){
warned = true;
out.write("WARNING: THRESHOLDS OF " + st1 + " NOT MATCHING THOSE IN THE GUI. WRONG!");
JOptionPane.showMessageDialog(Gui.frame,
"Thresholds of " + st1 + " not matching those displayed in the gui.",
"WARNING!", JOptionPane.WARNING_MESSAGE);
}
}
break;
}
}
for (Double d : thresholds.get(st1)){
out.write(d + ";"); //System.out.println("d :"+d);
}
out.write("\n");
}
// Add destabilizing signals
ArrayList <Variable> varsWithStables = new ArrayList <Variable>();
for (Variable v : reqdVarsL){
Variable var = new Variable("");
var.copy(v);
//System.out.println("var v :"+v.getName());
varsWithStables.add(var);
}
HashMap<String, ArrayList<String>> destabMap = new HashMap<String, ArrayList<String>>();
ArrayList<String> destab_out = new ArrayList<String>();
for (Variable v2 : reqdVarsL){
if ((v2.isInput()) && (v2.isDestab())){
destab_out.add(v2.getName());
}
}
if (destab_out.size() != 0){ //System.out.println("in old destab :");
for (Variable v1 : reqdVarsL){
if (!v1.isInput()){
destabMap.put(v1.getName(), destab_out);
Variable vStable = new Variable("stable");
vStable.setCare(true);
vStable.setDmvc(true);
vStable.setInput(true);
vStable.setOutput(false);
vStable.forceDmvc(true);
vStable.setEpsilon(0.1); // since stable is always 0 or 1 and threshold is 0.5. even epsilon of 0.3 is fine
varsWithStables.add(vStable);
ArrayList<Double> tStable = new ArrayList<Double>();
tStable.add(0.5);
thresholds.put("stable", tStable);
}
}
}
LhpnFile g = l.learnModel(directory, log, biosim, moduleNumber, thresholds, tPar, varsWithStables, destabMap, false, false, false, valScaleFactor, delayScaleFactor, failProp);
// the false parameter above says that it's not generating a net for stable
if (new File(seedLpnFile).exists()){ //directory + separator + "complete.lpn").exists()){//
LhpnFile seedLpn = new LhpnFile();
seedLpn.load(seedLpnFile);
g = mergeLhpns(seedLpn,g);
}
valScaleFactor = l.getValueScaleFactor();
delayScaleFactor = l.getDelayScaleFactor();
globalValueScaling.setText(Double.toString(valScaleFactor));
globalDelayScaling.setText(Double.toString(delayScaleFactor));
boolean defaultStim = defaultEnvG.isSelected();
if (defaultStim){
int j = 0;
//stables = new ArrayList<String>();
destabMap = new HashMap<String, ArrayList<String>>();
for (Variable v : reqdVarsL){
if (v.isInput()){
j++;
ArrayList <Variable> varsT = new ArrayList <Variable>();
Variable input = new Variable("");
input.copy(v);
input.setInput(false);
input.setOutput(true);
input.setCare(true);
varsT.add(input);
l = new LearnModel();
//LhpnFile moduleLPN = l.learnModel(directory, log, biosim, j, thresholds, tPar, varsT, destabMap, false, false, valScaleFactor, delayScaleFactor, null);
LhpnFile moduleLPN = l.learnModel(directory, log, biosim, j, thresholds, tPar, varsT, destabMap, false, false, false, valScaleFactor, delayScaleFactor, null);
// new Lpn2verilog(directory + separator + lhpnFile); //writeSVFile(directory + separator + lhpnFile);
g = mergeLhpns(moduleLPN,g);
}
}
}
g.save(directory + separator + lhpnFile);
viewLog.setEnabled(true);
//System.out.println(directory + separator + lhpnFile);
if (new File(directory + separator + lhpnFile).exists()) {
// System.out.println(" exists \n");
viewVHDL.setEnabled(true);
viewVerilog.setEnabled(true);
viewLhpn.setEnabled(true);
viewCoverage.setEnabled(true);
saveLhpn.setEnabled(true);
//viewLearnComplete(); // SB
JFrame learnComplete = new JFrame();
JOptionPane.showMessageDialog(learnComplete,
"Learning Complete.",
"LEMA",
JOptionPane.PLAIN_MESSAGE);
//viewLhpn();
biosim.updateMenu(true,true);
} else {
// System.out.println(" does not exist \n");
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLhpn.setEnabled(false);
viewCoverage.setEnabled(false);
saveLhpn.setEnabled(false);
fail = true;
biosim.updateMenu(true,false);
}
}
out.close();
running.setCursor(null);
running.dispose();
if (fail) {
viewLog();
}
} catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Unable to create log file.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
/*catch (RuntimeException e1) {
JOptionPane.showMessageDialog(BioSim.frame,
"Learning was" + " canceled by the user.",
"Canceled Learning", JOptionPane.ERROR_MESSAGE);
} */
}
public HashMap<String,Double> getThreshPar(){
HashMap<String,Double> tPar = new HashMap<String,Double>();
try{
int k = 0;
for (Component c : variablesPanel.getComponents()) {
if (k == 0){
k++;
continue;
}
String v = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
if (findReqdVarslIndex(v) != -1){
if (((JTextField)((JPanel)c).getComponent(4)).getText().trim().matches("[\\d]+\\.?[\\d]+?")){
reqdVarsL.get(findReqdVarslIndex(v)).setEpsilon(Double.valueOf(((JTextField)((JPanel)c).getComponent(4)).getText().trim()));
out.write("Epsilon is " + reqdVarsL.get(findReqdVarslIndex(v)).getEpsilon() + " for " + v + "\n");
}
else if (epsilonG.getText().matches("[\\d]+\\.?[\\d]+?")){
reqdVarsL.get(findReqdVarslIndex(v)).setEpsilon(Double.parseDouble(epsilonG.getText().trim()));
out.write("Can't parse epsilon for " + v + ". Using global one\n");
}
else {
reqdVarsL.get(findReqdVarslIndex(v)).setEpsilon(0.1);
out.write("Can't parse epsilon. Using default of 0.1\n");
}
}
}
if (epsilonG.getText().matches("[\\d]+\\.?[\\d]+?"))
epsilon = Double.parseDouble(epsilonG.getText().trim());
else {
epsilon = 0.1;
System.out.println("Can't parse epsilon. Using default\n");
}
if (rateSamplingG.getText().matches("[\\d]+"))
rateSampling = Integer.parseInt(rateSamplingG.getText().trim());
else{
rateSampling = -1;
out.write("Can't parse rateSampling. Using default\n");
}
if (pathLengthBinG.getText().matches("[\\d]+"))
pathLengthBin = Integer.parseInt(pathLengthBinG.getText().trim());
else{
pathLengthBin = 0;
System.out.println("Can't parse pathLengthBin. Using default\n");
}
if (pathLengthVarG.getText().matches("[\\d]+"))
pathLengthVar = Integer.parseInt(pathLengthVarG.getText().trim());
else{
pathLengthVar = 0;
System.out.println("Can't parse pathLengthVar. Using default\n");
}
if (percentG.getText().matches("[\\d]+\\.?[\\d]+?"))
percent = Double.parseDouble(percentG.getText().trim());
else{
percent = 0.2;
System.out.println("Can't parse percent. Using default\n");
}
if (runLengthG.getText().matches("[\\d]+"))
runLength = Integer.parseInt(runLengthG.getText().trim());
else{
runLength = 30;
System.out.println("Can't parse runLength. Using default\n");
}
if ((runTimeG.getText().matches("[\\d]+\\.?[\\d]+?")) || (runTimeG.getText().matches("[\\d]+\\.??[\\d]*?[e]??[-]??[\\d]+")))
runTime = Double.parseDouble(runTimeG.getText().trim());
else{
runTime = 5e-6;
System.out.println("Can't parse runTime. Using default\n");
}
absoluteTime = absTimeG.isSelected();
if (globalValueScaling.getText().matches("[\\d]+\\.??[\\d]*")){
valScaleFactor = Double.parseDouble(globalValueScaling.getText().trim());
//System.out.println("valScaleFactor " + valScaleFactor);
} else
valScaleFactor = -1.0;
if (globalDelayScaling.getText().matches("[\\d]+\\.??[\\d]*")){
delayScaleFactor = Double.parseDouble(globalDelayScaling.getText().trim());
//System.out.println("delayScaleFactor " + delayScaleFactor);
} else
delayScaleFactor = -1.0;
/* if ((unstableTimeG.getText().matches("[\\d]+\\.?[\\d]+?")) || (unstableTimeG.getText().matches("[\\d]+\\.??[\\d]*?[e]??[-]??[\\d]+")))
unstableTime = Double.parseDouble(unstableTimeG.getText().trim());
else{
unstableTime = 5e-6;
System.out.println("Can't parse unstableTime. Using default\n");
}*/
if ((stableToleranceG.getText().matches("[\\d]+\\.?[\\d]+?")) || (stableToleranceG.getText().matches("[\\d]+\\.??[\\d]*?[e]??[-]??[\\d]+")))
stableTolerance = Double.parseDouble(stableToleranceG.getText().trim());
else{
stableTolerance = 0.02;
System.out.println("Can't parse unstableTime. Using default\n");
}
out.write("epsilon = " + epsilon + "; ratesampling = " + rateSampling + "; pathLengthBin = " + pathLengthBin + "; percent = " + percent + "; runlength = " + runLength + "; runtime = " + runTime + "; absoluteTime = " + absoluteTime + "; delayscalefactor = " + delayScaleFactor + "; valuescalefactor = " + valScaleFactor + "; unstableTime = " + stableTolerance + "\n");
tPar.put("epsilon", epsilon);
tPar.put("pathLengthBin", Double.valueOf((double) pathLengthBin));
tPar.put("pathLengthVar", Double.valueOf((double) pathLengthVar));
tPar.put("rateSampling", Double.valueOf((double) rateSampling));
tPar.put("percent", percent);
if (absoluteTime)
tPar.put("runTime", runTime);
else
tPar.put("runLength", Double.valueOf((double) runLength));
// tPar.put("unstableTime", unstableTime);
tPar.put("stableTolerance", stableTolerance);
} catch (IOException e){
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Unable to create log file.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
return tPar;
}
public String getProp(){
String failProp = null;
if (!(propertyG.getText()).equals("")){
failProp = propertyG.getText().trim();
failProp = "~(" + failProp + ")";
failProp = failProp.replaceAll("\\.[0-9]*","");
}
return failProp;
}
public boolean hasChanged() {
return change;
}
public boolean isComboSelected() {
if (debug.isFocusOwner() || numBins.isFocusOwner()) {
return true;
}
if (variables == null) {
return false;
}
for (int i = 0; i < variables.size(); i++) {
if (((JComboBox) variables.get(i).get(4)).isFocusOwner()) { // changed 1 to 2 SB
return true;
}
}
return false;
}
public boolean getViewLhpnEnabled() {
return viewLhpn.isEnabled();
}
public boolean getSaveLhpnEnabled() {
return saveLhpn.isEnabled();
}
public boolean getViewLogEnabled() {
return viewLog.isEnabled();
}
public boolean getViewCoverageEnabled() {
return viewCoverage.isEnabled();
}
public boolean getViewVHDLEnabled() {
return viewVHDL.isEnabled();
}
public boolean getViewVerilogEnabled() {
return viewVerilog.isEnabled();
}
public void updateSpecies(String newLearnFile) {
seedLpnFile = newLearnFile;
variablesList = new ArrayList<String>();
thresholds = new HashMap<String, ArrayList<Double>>();
reqdVarsL = new ArrayList<Variable>();
LhpnFile lhpn = new LhpnFile();
lhpn.load(seedLpnFile);
HashMap<String, Properties> variablesMap = lhpn.getContinuous();
for (String s : variablesMap.keySet()) {
variablesList.add(s);
reqdVarsL.add(new Variable(s));
thresholds.put(s,new ArrayList<Double>());
}
Properties load = new Properties();
try {
FileInputStream in = new FileInputStream(new File(directory
+ separator + lrnFile));
load.load(in);
in.close();
//int j = 0;
if (load.containsKey("learn.varsList")){
String varsListString = load.getProperty("learn.varsList");
String[] varsList = varsListString.split("\\s");
//j = 0;
for (String st1 : varsList){
int varNum = findReqdVarslIndex(st1);
if (varNum == -1){
continue;
}
else{
String s = load.getProperty("learn.bins" + st1);
String[] savedBins = s.split("\\s");
//variablesList.add(savedBins[0]);
// ((JComboBox)(((JPanel)variablesPanel.getComponent(j+1)).getComponent(2))).setSelectedItem(savedBins[1]);
for (int i = 2; i < savedBins.length ; i++){
// ((JTextField)(((JPanel)variablesPanel.getComponent(j+1)).getComponent(i+1))).setText(savedBins[i]);
if (varNum < variablesMap.size()) { // chk for varNum or j ????
thresholds.get(st1).add(Double.parseDouble(savedBins[i]));
}
}
}
}
}
if (load.containsKey("learn.inputs")){
String s = load.getProperty("learn.inputs");
String[] savedInputs = s.split("\\s");
for (String st1 : savedInputs){
int ind = findReqdVarslIndex(st1); //after adding allVars
if (ind != -1){
reqdVarsL.get(ind).setInput(true);
}
/*for (int i = 0; i < reqdVarsL.size(); i++){//commented after adding allVars
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setInput(true);
break;
}
}*/
}
}
if (load.containsKey("learn.destabs")){
String s = load.getProperty("learn.destabs");
String[] savedDestabs = s.split("\\s");
for (String st1 : savedDestabs){
int ind = findReqdVarslIndex(st1); //after adding allVars
if (ind != -1){
reqdVarsL.get(ind).setDestab(true);
}
/*for (int i = 0; i < reqdVarsL.size(); i++){//commented after adding allVars
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setInput(true);
break;
}
}*/
}
}
if (load.containsKey("learn.dontcares")){
String s = load.getProperty("learn.dontcares");
String[] savedDontCares = s.split("\\s");
for (String st1 : savedDontCares){
int ind = findReqdVarslIndex(st1); //after adding allVars
if (ind != -1){
reqdVarsL.get(ind).setCare(false);
}
/*for (int i = 0; i < reqdVarsL.size(); i++){//commented after adding allVars
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setInput(true);
break;
}
}*/
}
}
} catch (IOException e) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
/*
* try { FileWriter write = new FileWriter( new File(directory +
* separator + "background.gcm")); BufferedReader input = new
* BufferedReader(new FileReader(new File(seedLpnFile))); String line =
* null; while ((line = input.readLine()) != null) { write.write(line +
* "\n"); } write.close(); input.close(); } catch (Exception e) {
* JOptionPane.showMessageDialog(BioSim.frame, "Unable to create
* background file!", "Error Writing Background",
* JOptionPane.ERROR_MESSAGE); }
*/
sortVariables();
if (user.isSelected()) {
// auto.doClick(); commented SB
// user.doClick(); commented SB
numBinsLabel.setEnabled(false);
numBins.setEnabled(false);
suggest.setEnabled(true);
variablesPanel.revalidate();
variablesPanel.repaint();
} else {
// user.doClick(); commented SB
// auto.doClick(); commented SB
numBinsLabel.setEnabled(true);
numBins.setEnabled(true);
suggest.setEnabled(false);
}
levels();
}
private void sortVariables() {
int i, j;
String index;
//TODO: AllVars has to be sorted?? Is sorting required at all??
for (i = 1; i < variablesList.size(); i++) {
index = variablesList.get(i);
j = i;
while ((j > 0)
&& variablesList.get(j - 1).compareToIgnoreCase(index) > 0) {
variablesList.set(j, variablesList.get(j - 1));
j = j - 1;
}
variablesList.set(j, index);
}
/* Collections.sort(divisionsL, new Comparator<ArrayList<Double>>(){
public int compare(ArrayList<Double> a, ArrayList<Double> b){
int ind1 = divisionsL.indexOf(a);
int ind2 = divisionsL.indexOf(b);
String var1 = reqdVarsL.get(ind1).getName();
String var2 = reqdVarsL.get(ind2).getName();
return (reqdVarsL.get(divisionsL.indexOf(a)).compareTo(reqdVarsL.get(divisionsL.indexOf(b))));
}
});*/
//TODO: SORTING OF thresholds NOT NECESSARY LIKE ABOVE ???
Collections.sort(reqdVarsL);
// sort divisionsL
}
public void setDirectory(String directory) {
this.directory = directory;
String[] getFilename = directory.split(separator);
lrnFile = getFilename[getFilename.length - 1] + ".lrn";
}
private boolean isTransientPlace(String st1) {
for (String s : transientNetPlaces.keySet()){
if (st1.equalsIgnoreCase("p" + transientNetPlaces.get(s).getProperty("placeNum"))){
return true;
}
}
return false;
}
private boolean isTransientTransition(String st1) {
for (String s : transientNetTransitions.keySet()){
if (st1.equalsIgnoreCase("t" + transientNetTransitions.get(s).getProperty("transitionNum"))){
return true;
}
}
return false;
}
public void resetAll(){
numPlaces = 0;
numTransitions = 0;
delayScaleFactor = 1.0;
valScaleFactor = 1.0;
for (Variable v: reqdVarsL){
v.reset();
}
}
public void findReqdVarIndices(){
reqdVarIndices = new ArrayList<Integer>();
for (int i = 0; i < reqdVarsL.size(); i++) {
for (int j = 1; j < varNames.size(); j++) {
if (reqdVarsL.get(i).getName().equalsIgnoreCase(varNames.get(j))) {
reqdVarIndices.add(j);
}
}
}
}
public void addInitPlace(HashMap<String,ArrayList<Double>> scaledThresholds){
int initPlaceNum = numPlaces;
g.addPlace("p" + numPlaces, true);
numPlaces++;
try{
for (String st : transientNetPlaces.keySet()){
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + initPlaceNum, "t" + numTransitions);
g.addMovement("t" + numTransitions, "p" + transientNetPlaces.get(st).getProperty("placeNum"));
g.changeInitialMarking("p" + transientNetPlaces.get(st).getProperty("placeNum"), false);
out.write("Added transition t" + numTransitions + " b/w initPlace and transient place p" + transientNetPlaces.get(st).getProperty("placeNum") + "\n");
String[] binOutgoing = st.split(",");
String condStr = "";
for (int j = 0; j < reqdVarsL.size(); j++){
String st2 = reqdVarsL.get(j).getName();
if (reqdVarsL.get(j).isInput()){
int bin = Integer.valueOf(binOutgoing[j]);
if (bin == 0){
if (!condStr.equalsIgnoreCase(""))
condStr += "&";
condStr += "~(" + st2 + ">=" + (int) Math.ceil(scaledThresholds.get(st2).get(bin).doubleValue()) + ")";
} else if (bin == (scaledThresholds.get(st2).size())){
if (!condStr.equalsIgnoreCase(""))
condStr += "&";
condStr += "(" + st2 + ">=" + (int) Math.floor(scaledThresholds.get(st2).get(bin-1).doubleValue()) + ")";
} else{
if (!condStr.equalsIgnoreCase(""))
condStr += "&";
condStr += "(" + st2 + ">=" + (int) Math.floor(scaledThresholds.get(st2).get(bin-1).doubleValue()) + ")&~(" + st2 + ">=" + (int) Math.ceil(scaledThresholds.get(st2).get(bin).doubleValue()) + ")";
}
} else {
if (reqdVarsL.get(j).isDmvc()){
int minv = (int) Math.floor(Double.parseDouble(transientNetPlaces.get(st).getProperty(st2 + "_vMin")));
int maxv = (int) Math.ceil(Double.parseDouble(transientNetPlaces.get(st).getProperty(st2 + "_vMax")));
if (minv != maxv)
g.addIntAssign("t" + numTransitions,st2,"uniform(" + minv + ","+ maxv + ")");
else
g.addIntAssign("t" + numTransitions,st2,String.valueOf(minv));
out.write("Added assignment to " + st2 + " at transition t" + numTransitions + "\n");
}
// deal with rates for continuous here
}
}
out.write("Changed enabling of t" + numTransitions + " to " + condStr + "\n");
g.addEnabling("t" + numTransitions, condStr);
numTransitions++;
}
for (HashMap<String,String> st1 : constVal){ // for output signals that are constant throughout the trace.
if (st1.size() != 0){
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + initPlaceNum, "t" + numTransitions);
for (String st2: st1.keySet()){
g.addIntAssign("t" + numTransitions,st2,st1.get(st2));
}
numTransitions++;
}
}
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Log file couldn't be opened in addInitPlace.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
} catch (NullPointerException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Null exception in addInitPlace.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
public void genBinsRates(HashMap<String, ArrayList<Double>> localThresholds) {
try{
// generate bins
reqdVarIndices = new ArrayList<Integer>();
bins = new int[reqdVarsL.size()][data.get(0).size()];
for (int i = 0; i < reqdVarsL.size(); i++) {
for (int j = 1; j < varNames.size(); j++) {
String currentVar = reqdVarsL.get(i).getName();
if (currentVar.equalsIgnoreCase(varNames.get(j))) {
reqdVarIndices.add(j);
for (int k = 0; k < data.get(j).size(); k++) {
ArrayList<Double> thresh = localThresholds.get(currentVar);
bins[i][k] = getRegion(data.get(j).get(k),thresh);
if ((k != 0) && (bins[i][k] != bins[i][k-1])){
int length = 0;
for (int m = k; m < data.get(j).size(); m++) {
if (getRegion(data.get(j).get(m),thresh) == bins[i][k])
length++;
else
break;
}
if (length < pathLengthVar){
out.write("Short bin for variable " + currentVar + " at " + data.get(0).get(k) + " until " + data.get(0).get(k+length-1) + " due to min pathLengthVar. Using " + bins[i][k-1] + " instead of " + bins[i][k] + " \n");
for (int m = k; m < k+length; m++) {
bins[i][m] = bins[i][k-1];
}
} else {
for (int m = k; m < k+length; m++) {
bins[i][m] = bins[i][k];
}
}
k = k+length-1;
}
}
}
}
}
/*
* System.out.println("array bins is :"); for (int i = 0; i <
* reqdVarsL.size(); i++) { System.out.print(reqdVarsL.get(i).getName() + "
* "); for (int k = 0; k < data.get(0).size(); k++) {
* System.out.print(bins[i][k] + " "); } System.out.print("\n"); }
*/
// generate rates
rates = new Double[reqdVarsL.size()][data.get(0).size()];
values = new double[reqdVarsL.size()][data.get(0).size()];
duration = new Double[data.get(0).size()];
int mark, k, previous = 0; // indices of rates not same as that of the variable. if
// wanted, then size of rates array should be varNames
// not reqdVars
if (rateSampling == -1) { // replacing inf with -1
mark = 0;
for (int i = 0; i < data.get(0).size(); i++) {
if (i < mark) {
continue;
}
while ((mark < data.get(0).size()) && (compareBins(i, mark))) {
for (int j = 0; j < reqdVarsL.size(); j++){
k = reqdVarIndices.get(j);
values[j][i] = (values[j][i]*(mark-i) + data.get(k).get(mark))/(mark-i+1);
}
mark++;
}
if ((data.get(0).get(mark - 1) != data.get(0).get(i)) && ((mark - i) >= pathLengthBin) && (mark != data.get(0).size())) { // && (mark != (data.get(0).size() - 1 condition added on nov 23.. to avoid the last region bcoz it's not complete. rechk
if (!compareBins(previous,i)){
for (int j = 0; j < reqdVarsL.size(); j++) {
k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(k).get(mark - 1) - data.get(k).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i)));
}
duration[i] = data.get(0).get(mark) - data.get(0).get(i); // changed (mark - 1) to mark on may 28,2010
previous = i;
} else{ // There was a glitch and you returned to the same region
for (int j = 0; j < reqdVarsL.size(); j++) {
k = reqdVarIndices.get(j);
rates[j][previous] = ((data.get(k).get(mark - 1) - data.get(k).get(previous)) / (data.get(0).get(mark - 1) - data.get(0).get(previous)));
}
duration[previous] = data.get(0).get(mark) - data.get(0).get(previous); // changed (mark - 1) to mark on may 28,2010
}
} else if ((mark - i) < pathLengthBin) { // account for the glitch duration //
out.write("Short bin at " + data.get(0).get(i) + " until " + data.get(0).get(mark) + " due to min pathLengthBin. This delay being added to " + previous + " \n");
duration[previous] += data.get(0).get(mark) - data.get(0).get(i);
} else if (data.get(0).get(mark - 1) == data.get(0).get(i)){ // bin with only one point. Added this condition on June 9,2010
//Rates are meaningless here since the bin has just one point.
//But calculating the rate because if it is null, then places won't be created in genBinsRates for one point bins.
//Calculating rate b/w start point of next bin and start point of this bin
out.write("Bin with one point at time " + data.get(0).get(i) + "\n");
for (int j = 0; j < reqdVarsL.size(); j++) {
k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(k).get(mark) - data.get(k).get(i)) / (data.get(0).get(mark) - data.get(0).get(i)));
}
duration[i] = data.get(0).get(mark) - data.get(0).get(i); // changed (mark - 1) to mark on may 28,2010
previous = i;
}
}
} else { //TODO: This may have bugs in duration calculation etc.
boolean calcRate;
boolean prevFail = true;
int binStartPoint = 0, binEndPoint = 0;
for (int i = 0; i < (data.get(0).size() - rateSampling); i++) {
calcRate = true;
for (int l = 0; l < rateSampling; l++) {
if (!compareBins(i, i + l)) {
if (!prevFail){
binEndPoint = i -2 + rateSampling;
duration[binStartPoint] = data.get(0).get(binEndPoint) - data.get(0).get(binStartPoint);
}
calcRate = false;
prevFail = true;
break;
}
}
if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) {
for (int j = 0; j < reqdVarsL.size(); j++) {
k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(k).get(i + rateSampling) - data.get(k).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i)));
}
if (prevFail){
binStartPoint = i;
}
prevFail = false;
}
}
// commented on nov 23. don't need this. should avoid rate calculation too for this region. but not avoiding now.
/* if (!prevFail){ // for the last genuine rate-calculating region of the trace; this may not be required if the trace is incomplete.trace data may not necessarily end at a region endpt
duration[binStartPoint] = data.get(0).get(data.get(0).size()-1) - data.get(0).get(binStartPoint);
}*/
}
} catch (NullPointerException e){
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Bins/Rates could not be generated. Please check thresholds.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
} catch (IOException e){
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Log file couldn't be opened for writing genBinsRates messages.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
public int getRegion(double value, ArrayList<Double> varThresholds){
int bin = 0;
for (int l = 0; l < varThresholds.size(); l++) {
if (value <= varThresholds.get(l)) {
bin = l;
break;
} else {
bin = l + 1;
}
}
return bin;
}
public boolean compareBins(int j, int mark) {
for (int i = 0; i < reqdVarsL.size(); i++) {
if (bins[i][j] != bins[i][mark]) {
return false;
} else {
continue;
}
}
return true;
}
public HashMap<String, ArrayList<Double>> detectDMV(ArrayList<ArrayList<Double>> data, Boolean callFromAutogen) {
int startPoint, endPoint, mark, numPoints;
HashMap<String, ArrayList<Double>> dmvDivisions = new HashMap<String, ArrayList<Double>>();
double absTime;
try{
for (int i = 0; i < reqdVarsL.size(); i++) {
if (reqdVarsL.get(i).isForcedCont()){
reqdVarsL.get(i).setDmvc(false);
out.write(reqdVarsL.get(i).getName() + " is forced to be continuous \n");
} else {
absTime = 0;
mark = 0;
DMVCrun runs = reqdVarsL.get(i).getRuns();
runs.clearAll(); // flush all the runs from previous dat file.
int lastRunPointsWithoutTransition = 0;
Double lastRunTimeWithoutTransition = 0.0;
Double lastRunValueWithoutTransition = null;
if (!callFromAutogen) { // This flag is required because if the call is from autogenT, then data has just the reqdVarsL but otherwise, it has all other vars too. So reqdVarIndices not reqd when called from autogen
for (int j = 0; j <= data.get(0).size(); j++) {
if (j < mark)
continue;
if (((j+1) < data.get(reqdVarIndices.get(i)).size()) &&
Math.abs(data.get(reqdVarIndices.get(i)).get(j) - data.get(reqdVarIndices.get(i)).get(j + 1)) <= reqdVarsL.get(i).getEpsilon()) {
startPoint = j;
runs.addValue(data.get(reqdVarIndices.get(i)).get(j)); // chk carefully reqdVarIndices.get(i)
while (((j + 1) < data.get(0).size()) && (bins[i][startPoint] == bins[i][j+1]) && (Math.abs(data.get(reqdVarIndices.get(i)).get(startPoint) - data.get(reqdVarIndices.get(i)).get(j + 1)) <= reqdVarsL.get(i).getEpsilon())) { //checking of same bins[] condition added on May 11,2010.
runs.addValue(data.get(reqdVarIndices.get(i)).get(j + 1)); // chk carefully reqdVarIndices.get(i)
j++;
}
endPoint = j;
if (!absoluteTime) {
if ((endPoint < (data.get(0).size() - 1)) && ((endPoint - startPoint) + 1) >= runLength) {
runs.addStartPoint(startPoint);
runs.addEndPoint(endPoint);
} else if (((endPoint - startPoint) + 1) >= runLength) {
lastRunPointsWithoutTransition = endPoint - startPoint + 1;
lastRunValueWithoutTransition = runs.getLastValue();
} else {
runs.removeValue();
}
} else {
if ((endPoint < (data.get(0).size() - 1)) && (calcDelay(startPoint, endPoint) >= runTime)) {
runs.addStartPoint(startPoint);
runs.addEndPoint(endPoint);
absTime += calcDelay(startPoint, endPoint);
} else if (((endPoint - startPoint) + 1) >= runLength) {
lastRunTimeWithoutTransition = calcDelay(startPoint, endPoint);
lastRunValueWithoutTransition = runs.getLastValue();
} else {
runs.removeValue();
}
}
mark = endPoint;
}
}
numPoints = runs.getNumPoints();
if (!reqdVarsL.get(i).isForcedDmv() && ((absoluteTime && (((absTime + lastRunTimeWithoutTransition)/ (data.get(0).get(data.get(0).size() - 1) - data
.get(0).get(0))) < percent)) || (!absoluteTime && (((numPoints + lastRunPointsWithoutTransition)/ (double) data.get(0).size()) < percent)))){ // isForced condition added on may 28
runs.clearAll();
reqdVarsL.get(i).setDmvc(false);
out.write(reqdVarsL.get(i).getName() + " is not a dmvc \n");
} else {
reqdVarsL.get(i).setDmvc(true);
Double[] dmvcValues;
if (lastRunValueWithoutTransition != null ){
Double[] dVals = reqdVarsL.get(i).getRuns().getAvgVals();
//for (int x=0; x<dVals.length;x++) System.out.println("dvals :"+dVals[x]);
dmvcValues = new Double[dVals.length + 1];
for (int j = 0; j < dVals.length; j++){
dmvcValues[j] = dVals[j];
}
dmvcValues[dVals.length] = lastRunValueWithoutTransition;
} else
dmvcValues = reqdVarsL.get(i).getRuns().getAvgVals();
Arrays.sort(dmvcValues);
if (!dmvcValuesUnique.containsKey(reqdVarsL.get(i).getName()))
dmvcValuesUnique.put(reqdVarsL.get(i).getName(),new Properties());
out.write("DMV values of " + reqdVarsL.get(i).getName() + " are ");
if (dmvcValues.length == 0){// constant value throughout the trace
dmvcValues = new Double[1];
dmvcValues[0]= reqdVarsL.get(i).getRuns().getConstVal();
}
for (int j = 0; j < dmvcValues.length; j++){
if (dmvcValues[j] < thresholds.get(reqdVarsL.get(i).getName()).get(0)){
dmvcValuesUnique.get(reqdVarsL.get(i).getName()).put("0",dmvcValues[j].toString());
//System.out.println("For variable " + reqdVarsL.get(i).getName() + " value for bin 0 is " + dmvcValues[j] + "\n");
}
else if (dmvcValues[j] >= thresholds.get(reqdVarsL.get(i).getName()).get(thresholds.get(reqdVarsL.get(i).getName()).size() - 1)){
dmvcValuesUnique.get(reqdVarsL.get(i).getName()).put(String.valueOf(thresholds.get(reqdVarsL.get(i).getName()).size()),dmvcValues[j].toString());
//System.out.println("For variable " + reqdVarsL.get(i).getName() + " value for bin " + thresholds.get(reqdVarsL.get(i).getName()).size() + " is " + dmvcValues[j] + "\n");
}
else{
for (int k = 0; k < thresholds.get(reqdVarsL.get(i).getName()).size()-1; k++){
if ((dmvcValues[j] >= thresholds.get(reqdVarsL.get(i).getName()).get(k)) && (dmvcValues[j] < thresholds.get(reqdVarsL.get(i).getName()).get(k+1))){
dmvcValuesUnique.get(reqdVarsL.get(i).getName()).put(String.valueOf(k+1),dmvcValues[j].toString());
//System.out.println("For variable " + reqdVarsL.get(i).getName() + " value for bin " + String.valueOf(k+1) + " is " + dmvcValues[j] + "\n");
break;
}
}
}
out.write(dmvcValues[j] + " ");
}
out.write(reqdVarsL.get(i).getName() + " is a dmvc \n");
}
} else {
getThreshPar();
out.write("epsilon = " + epsilon + "; percent = " + percent + "; runlength = " + runLength + "; runtime = " + runTime + "; absoluteTime = " + absoluteTime + "\n");
for (int j = 0; j <= data.get(0).size(); j++) {
if (j < mark) // not reqd??
continue;
if (((j+1) < data.get(i+1).size()) &&
Math.abs(data.get(i+1).get(j) - data.get(i+1).get(j + 1)) <= reqdVarsL.get(i).getEpsilon()) { //i+1 and not i bcoz 0th col is time
startPoint = j;
runs.addValue(data.get(i+1).get(j)); // chk carefully reqdVarIndices.get(i)
while (((j + 1) < data.get(0).size()) && (Math.abs(data.get(i+1).get(startPoint) - data.get(i+1).get(j + 1)) <= reqdVarsL.get(i).getEpsilon())) {
// VERY IMP: add condition data.get(0).get(startPoint) < data.get(0).get(j+1) to make sure that you don't run into the next data file..
runs.addValue(data.get(i+1).get(j + 1)); // chk carefully reqdVarIndices.get(i)
j++;
}
endPoint = j;
if (!absoluteTime) {
if ((endPoint < (data.get(0).size() - 1)) && ((endPoint - startPoint) + 1) >= runLength) {
runs.addStartPoint(startPoint);
runs.addEndPoint(endPoint);
} else if (((endPoint - startPoint) + 1) >= runLength) {
lastRunPointsWithoutTransition = endPoint - startPoint + 1;
lastRunValueWithoutTransition = runs.getLastValue();
} else {
runs.removeValue();
}
} else {
if ((endPoint < (data.get(0).size() - 1)) && (calcDelayWithData(startPoint, endPoint, data) >= runTime)) {
runs.addStartPoint(startPoint);
runs.addEndPoint(endPoint);
absTime += calcDelayWithData(startPoint, endPoint, data);
} else if (((endPoint - startPoint) + 1) >= runLength) {
lastRunTimeWithoutTransition = calcDelayWithData(startPoint, endPoint, data);
lastRunValueWithoutTransition = runs.getLastValue();
} else {
runs.removeValue();
}
}
mark = endPoint;
}
}
numPoints = runs.getNumPoints();
if (!reqdVarsL.get(i).isForcedDmv() && ((absoluteTime && (((absTime + lastRunTimeWithoutTransition)/ (data.get(0).get(data.get(0).size() - 1) - data
.get(0).get(0))) < percent)) || (!absoluteTime && (((numPoints + lastRunPointsWithoutTransition)/ (double) data.get(0).size()) < percent)))) {// isForced condition added on may 28
runs.clearAll();
reqdVarsL.get(i).setDmvc(false);
out.write(reqdVarsL.get(i).getName() + " is not a dmvc \n");
} else {
reqdVarsL.get(i).setDmvc(true);
Double[] dmvcValues;
if (lastRunValueWithoutTransition != null ){
Double[] dVals = reqdVarsL.get(i).getRuns().getAvgVals(); //for (int x=0; x<dVals.length; x++) System.out.println("dVals :"+dVals[x]);
dmvcValues = new Double[dVals.length + 1];
for (int j = 0; j < dVals.length; j++){
dmvcValues[j] = dVals[j];
}
dmvcValues[dVals.length] = lastRunValueWithoutTransition;
} else
dmvcValues = reqdVarsL.get(i).getRuns().getAvgVals();
Arrays.sort(dmvcValues);
//System.out.println("Sorted DMV values of " + reqdVarsL.get(i).getName() + " are ");
//for (Double l : dmvcValues){
// System.out.print(l + " ");
if (!dmvcValuesUnique.containsKey(reqdVarsL.get(i).getName()))
dmvcValuesUnique.put(reqdVarsL.get(i).getName(),new Properties());
ArrayList<Double> dmvSplits = new ArrayList<Double>();
out.write("Final DMV values of " + reqdVarsL.get(i).getName() + " are ");
int l = 0;
for (int j = 0; j < dmvcValues.length; j++){
dmvcValuesUnique.get(reqdVarsL.get(i).getName()).put(String.valueOf(l),dmvcValues[j].toString());
out.write(dmvcValues[j] + ", ");
if (dmvcValuesUnique.get(reqdVarsL.get(i).getName()).size() > 1){
Properties p3 = dmvcValuesUnique.get(reqdVarsL.get(i).getName());
double d1 = (Double.valueOf(p3.getProperty(String.valueOf(p3.size() - 1))) + Double.valueOf(p3.getProperty(String.valueOf(p3.size() - 2))))/2.0;
d1 = d1*10000;
int d2 = (int) d1;
dmvSplits.add(((double)d2)/10000.0); // truncating to 4 decimal places
}
l++;
for (int k = j+1; k < dmvcValues.length; k++){
if (Math.abs((dmvcValues[j] - dmvcValues[k])) > reqdVarsL.get(i).getEpsilon()){
j = k-1;
break;
}
else if (k >= (dmvcValues.length -1)){
j = k;
}
}
}
out.write("\n");
dmvDivisions.put(reqdVarsL.get(i).getName(), dmvSplits);
out.write(reqdVarsL.get(i).getName() + " is a dmvc in detectDMV. Final check will be done using the generated thresholds \n");
}
}
}
}
}catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Log file couldn't be opened for writing rates and bins.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
if (callFromAutogen)
checkthresholds(data,dmvDivisions);
dmvDetectDone = true;
return(dmvDivisions);
}
public void checkthresholds(ArrayList<ArrayList<Double>> data, HashMap<String, ArrayList<Double>> localThresholds){
int[][] bins = new int[reqdVarsL.size()][data.get(0).size()];
for (int i = 0; i < reqdVarsL.size(); i++) {
if (reqdVarsL.get(i).isDmvc()){
String currentVar = reqdVarsL.get(i).getName();
for (int k = 0; k < data.get(i+1).size(); k++) {
for (int l = 0; l < localThresholds.get(currentVar).size(); l++) {
if (data.get(i+1).get(k) <= localThresholds.get(currentVar).get(l)) {
bins[i][k] = l;
break;
} else {
bins[i][k] = l + 1; // indices of bins not same as that of the variable. i here. not j; if j
// wanted, then size of bins array should be varNames not reqdVars
}
}
}
}
}
int startPoint, endPoint, mark, numPoints;
double absTime;
try{
for (int i = 0; i < reqdVarsL.size(); i++) {
if (reqdVarsL.get(i).isDmvc()){ // recheck with new thresholds has to be done only for those variables which are detected as dmv already.
absTime = 0;
mark = 0;
DMVCrun runs = reqdVarsL.get(i).getRuns();
runs.clearAll(); // flush all the runs from previous dat file.
int lastRunPointsWithoutTransition = 0;
Double lastRunTimeWithoutTransition = 0.0;
for (int j = 0; j <= data.get(0).size(); j++) {
if (j < mark) // not reqd??
continue;
if (((j+1) < data.get(i+1).size()) &&
Math.abs(data.get(i+1).get(j) - data.get(i+1).get(j + 1)) <= reqdVarsL.get(i).getEpsilon()) { //i+1 and not i bcoz 0th col is time
startPoint = j;
runs.addValue(data.get(i+1).get(j)); // chk carefully reqdVarIndices.get(i)
while (((j + 1) < data.get(0).size()) && (bins[i][startPoint] == bins[i][j+1]) && (Math.abs(data.get(i+1).get(startPoint) - data.get(i+1).get(j + 1)) <= reqdVarsL.get(i).getEpsilon())) {
// VERY IMP: add condition data.get(0).get(startPoint) < data.get(0).get(j+1) to make sure that you don't run into the next data file..
runs.addValue(data.get(i+1).get(j + 1)); // chk carefully
// reqdVarIndices.get(i)
j++;
}
endPoint = j;
if (!absoluteTime) {
if ((endPoint < (data.get(0).size() - 1)) && ((endPoint - startPoint) + 1) >= runLength) {
runs.addStartPoint(startPoint);
runs.addEndPoint(endPoint);
} else if (((endPoint - startPoint) + 1) >= runLength) {
lastRunPointsWithoutTransition = endPoint - startPoint + 1;
} else {
runs.removeValue();
}
} else {
if ((endPoint < (data.get(0).size() - 1)) && (calcDelayWithData(startPoint, endPoint, data) >= runTime)) {
runs.addStartPoint(startPoint);
runs.addEndPoint(endPoint);
absTime += calcDelayWithData(startPoint, endPoint, data);
} else if (((endPoint - startPoint) + 1) >= runLength) {
lastRunTimeWithoutTransition = calcDelayWithData(startPoint, endPoint, data);
} else {
runs.removeValue();
}
}
mark = endPoint;
}
}
numPoints = runs.getNumPoints();
if (!reqdVarsL.get(i).isForcedDmv() && ((absoluteTime && (((absTime + lastRunTimeWithoutTransition)/ (data.get(0).get(data.get(0).size() - 1) - data
.get(0).get(0))) < percent)) || (!absoluteTime && (((numPoints + lastRunPointsWithoutTransition)/ (double) data.get(0).size()) < percent)))) {
runs.clearAll();
reqdVarsL.get(i).setDmvc(false);
out.write("After checking with the generated thresholds " + reqdVarsL.get(i).getName() + " is not a dmv \n");
} else {
if (reqdVarsL.get(i).isForcedDmv())
out.write(reqdVarsL.get(i).getName() + " is a forced dmv. So, generated thresholds not being checked \n");
else
out.write("After checking with the generated thresholds " + reqdVarsL.get(i).getName() + " is a dmv \n");
}
}
}
}catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Log file couldn't be opened for writing rates and bins.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
public double calcDelay(int i, int j) {
return (data.get(0).get(j) - data.get(0).get(i));
}
public double calcDelayWithData(int i, int j, ArrayList<ArrayList<Double>> data) {
return (data.get(0).get(j) - data.get(0).get(i));
}
public void addValue(Properties p, String name, Double v) {
Double vMin;
Double vMax;
if ((p.getProperty(name + "_vMin") == null)
&& (p.getProperty(name + "_vMax") == null)) {
p.setProperty(name + "_vMin", v.toString());
p.setProperty(name + "_vMax", v.toString());
return;
} else {
vMin = Double.parseDouble(p.getProperty(name + "_vMin"));
vMax = Double.parseDouble(p.getProperty(name + "_vMax"));
if (v < vMin) {
vMin = v;
} else if (v > vMax) {
vMax = v;
}
}
p.setProperty(name + "_vMin", vMin.toString());
p.setProperty(name + "_vMax", vMax.toString());
}
public void addRate(Properties p, String name, Double r) {
Double rMin;
Double rMax;
if ((p.getProperty(name + "_rMin") == null)
&& (p.getProperty(name + "_rMax") == null)) {
p.setProperty(name + "_rMin", r.toString());
p.setProperty(name + "_rMax", r.toString());
return;
} else {
rMin = Double.parseDouble(p.getProperty(name + "_rMin"));
rMax = Double.parseDouble(p.getProperty(name + "_rMax"));
if (r < rMin) {
rMin = r;
} else if (r > rMax) {
rMax = r;
}
}
p.setProperty(name + "_rMin", rMin.toString());
p.setProperty(name + "_rMax", rMax.toString());
}
public HashMap<String,ArrayList<Double>> scaleValue(Double scaleFactor, HashMap<String,ArrayList<Double>> localThresholds) {
String place;
Properties p;
try{
for (String st1 : g.getPlaceList()) {
if (!isTransientPlace(st1)){
place = getPlaceInfoIndex(st1);
p = placeInfo.get(place);
}
else{
place = getTransientNetPlaceIndex(st1);
p = transientNetPlaces.get(place);
}
if (place != "failProp"){
for (Variable v : reqdVarsL) {
if (!v.isDmvc()) {
p.setProperty(v.getName() + "_rMin", Double
.toString(Double.parseDouble(p.getProperty(v.getName()
+ "_rMin"))* scaleFactor));
p.setProperty(v.getName() + "_rMax", Double
.toString(Double.parseDouble(p.getProperty(v.getName()
+ "_rMax"))* scaleFactor));
} else {
if (!v.isInput()) {
p.setProperty(v.getName() + "_vMin", Double
.toString(Double.parseDouble(p.getProperty(v.getName()
+ "_vMin"))* scaleFactor));
p.setProperty(v.getName() + "_vMax", Double
.toString(Double.parseDouble(p.getProperty(v.getName()
+ "_vMax")) * scaleFactor));
}
}
}
}
}
for (Variable v : reqdVarsL) {
v.scaleInitByVar(scaleFactor);
for (int j = 0; j < localThresholds.get(v.getName()).size(); j++) {
localThresholds.get(v.getName()).set(j,localThresholds.get(v.getName()).get(j) * scaleFactor);
}
}
for (HashMap<String,String> st1 : constVal){ // for output signals that are constant throughout the trace.
for (String st2: st1.keySet()){
st1.put(st2,String.valueOf(Double.valueOf(st1.get(st2))*scaleFactor));
}
}
}
catch (NullPointerException e){
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Not all regions have values for all dmv variables",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
return localThresholds;
}
public void scaleDelay(Double scaleFactor) {
try{
String place;
Properties p;
for (String t : g.getTransitionList()) {
if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){
if (!isTransientTransition(t)){
if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) {
String pPrev = g.getPreset(t)[0];
String nextPlace = g.getPostset(t)[0];
Double mind = Double.parseDouble(transitionInfo.get(getPlaceInfoIndex(pPrev) + getPlaceInfoIndex(nextPlace)).getProperty("dMin"));
Double maxd = Double.parseDouble(transitionInfo.get(getPlaceInfoIndex(pPrev) + getPlaceInfoIndex(nextPlace)).getProperty("dMax"));
transitionInfo.get(getPlaceInfoIndex(pPrev) + getPlaceInfoIndex(nextPlace)).setProperty("dMin",Double.toString(mind*scaleFactor));
transitionInfo.get(getPlaceInfoIndex(pPrev) + getPlaceInfoIndex(nextPlace)).setProperty("dMax",Double.toString(maxd*scaleFactor));
}
} else {
if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition
String pPrev = g.getPreset(t)[0];
String nextPlace = g.getPostset(t)[0];
Double mind = Double.parseDouble(transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+getPlaceInfoIndex(nextPlace)).getProperty("dMin"));
Double maxd = Double.parseDouble(transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+getPlaceInfoIndex(nextPlace)).getProperty("dMax"));
transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+getPlaceInfoIndex(nextPlace)).setProperty("dMin",Double.toString(mind*scaleFactor));
transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+getPlaceInfoIndex(nextPlace)).setProperty("dMax",Double.toString(maxd*scaleFactor));
}
}
}
}
for (String st1 : g.getPlaceList()) {
if (!isTransientPlace(st1)){
place = getPlaceInfoIndex(st1);
p = placeInfo.get(place);
}
else{
place = getTransientNetPlaceIndex(st1);
p = transientNetPlaces.get(place);
}
if (place != "failProp"){
for (Variable v : reqdVarsL) {
if (!v.isDmvc()) {
p.setProperty(v.getName() + "_rMin", Double
.toString(Double.parseDouble(p.getProperty(v
.getName() + "_rMin")) / scaleFactor));
p.setProperty(v.getName() + "_rMax", Double
.toString(Double.parseDouble(p.getProperty(v
.getName() + "_rMax")) / scaleFactor));
}
}
}
}
for (Variable v : reqdVarsL) {
// if (!v.isDmvc()){ this if maynot be required.. rates do exist for dmvc ones as well.. since calculated before detectDMV
v.scaleInitByDelay(scaleFactor);
}
// SEE IF RATES IN TRANSITIONS HAVE TO BE ADJUSTED HERE
}
catch(NullPointerException e){
System.out.println("Delay scaling error due to null. Check");
}
catch(java.lang.ArrayIndexOutOfBoundsException e){
System.out.println("Delay scaling error due to Array Index.");
}
}
public Double getMinDiv(HashMap<String, ArrayList<Double>> divisions) {
Double minDiv = null;
for (String s : divisions.keySet()) {
if (minDiv == null){
minDiv = divisions.get(s).get(0);
}
for (int j = 0; j < divisions.get(s).size(); j++) {
if (divisions.get(s).get(j) < minDiv) {
minDiv = divisions.get(s).get(j);
}
}
}
return minDiv;
}
public Double getMaxDiv(HashMap<String, ArrayList<Double>> divisions) {
Double maxDiv = null;
for (String s : divisions.keySet()) {
if (maxDiv == null){
maxDiv = divisions.get(s).get(0);
}
for (int j = 0; j < divisions.get(s).size(); j++) {
if (divisions.get(s).get(j) > maxDiv) {
maxDiv = divisions.get(s).get(j);
}
}
}
return maxDiv;
}
public Double getMinRate() { // minimum of entire lpn
Double minRate = null;
for (String place : placeInfo.keySet()) {
Properties p = placeInfo.get(place);
if (p.getProperty("type").equals("RATE")) {
for (Variable v : reqdVarsL) {
if (!v.isDmvc()){
if ((minRate == null)
&& (p.getProperty(v.getName() + "_rMin") != null)) {
minRate = Double.parseDouble(p.getProperty(v.getName()
+ "_rMin"));
} else if ((p.getProperty(v.getName() + "_rMin") != null)
&& (Double.parseDouble(p.getProperty(v.getName()
+ "_rMin")) < minRate)
&& (Double.parseDouble(p.getProperty(v.getName()
+ "_rMin")) != 0.0)) {
minRate = Double.parseDouble(p.getProperty(v.getName()
+ "_rMin"));
}
}
}
}
}
return minRate;
}
public Double getMaxRate() {
Double maxRate = null;
for (String place : placeInfo.keySet()) {
Properties p = placeInfo.get(place);
if (p.getProperty("type").equals("RATE")) {
for (Variable v : reqdVarsL) {
if (!v.isDmvc()){
if ((maxRate == null)
&& (p.getProperty(v.getName() + "_rMax") != null)) {
maxRate = Double.parseDouble(p.getProperty(v.getName()
+ "_rMax"));
} else if ((p.getProperty(v.getName() + "_rMax") != null)
&& (Double.parseDouble(p.getProperty(v.getName()
+ "_rMax")) > maxRate)
&& (Double.parseDouble(p.getProperty(v.getName()
+ "_rMax")) != 0.0)) {
maxRate = Double.parseDouble(p.getProperty(v.getName()
+ "_rMax"));
}
}
}
}
}
return maxRate;
}
public Double getMinDelay() {
Double minDelay = null;
Double mind;
try{
for (String t : g.getTransitionList()) {
if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){
if (!isTransientTransition(t)){
if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) {
String pPrev = g.getPreset(t)[0];
String nextPlace = g.getPostset(t)[0];
out.write("Transition " + g.getTransition(t).getName() + " b/w " + pPrev + " and " + nextPlace + " : finding delay \n");
if (transitionInfo.get(getPlaceInfoIndex(pPrev) + getPlaceInfoIndex(nextPlace)).getProperty("dMin") != null){
mind = Double.parseDouble(transitionInfo.get(getPlaceInfoIndex(pPrev) + getPlaceInfoIndex(nextPlace)).getProperty("dMin"));
if (minDelay == null)
minDelay = mind;
else if ((minDelay > mind) && (mind != 0))
minDelay = mind;
}
}
} else {
if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition
String pPrev = g.getPreset(t)[0];
String nextPlace = g.getPostset(t)[0];
if (transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+getPlaceInfoIndex(nextPlace)).getProperty("dMin") != null){
mind = Double.parseDouble(transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+getPlaceInfoIndex(nextPlace)).getProperty("dMin"));
if (minDelay == null)
minDelay = mind;
else if ((minDelay > mind) && (mind != 0))
minDelay = mind;
}
}
}
}
}
} catch (IOException e){
e.printStackTrace();
}
return minDelay;
}
public Double getMaxDelay() {
Double maxDelay = null;
Double maxd;
for (String t : g.getTransitionList()) {
if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){
if (!isTransientTransition(t)){
if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) {
String pPrev = g.getPreset(t)[0];
String nextPlace = g.getPostset(t)[0];
if (transitionInfo.get(getPlaceInfoIndex(pPrev) + getPlaceInfoIndex(nextPlace)).getProperty("dMax") != null){
maxd = Double.parseDouble(transitionInfo.get(getPlaceInfoIndex(pPrev) + getPlaceInfoIndex(nextPlace)).getProperty("dMax"));
if (maxDelay == null)
maxDelay = maxd;
else if ((maxDelay < maxd) && (maxd != 0))
maxDelay = maxd;
}
}
} else {
if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition
String pPrev = g.getPreset(t)[0];
String nextPlace = g.getPostset(t)[0];
if (transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+getPlaceInfoIndex(nextPlace)).getProperty("dmax") != null){
maxd = Double.parseDouble(transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+getPlaceInfoIndex(nextPlace)).getProperty("dmax"));
if (maxDelay == null)
maxDelay = maxd;
else if ((maxDelay < maxd) && (maxd != 0))
maxDelay = maxd;
}
}
}
}
}
return maxDelay;
}
public void addDuration(Properties p, Double d) {
Double dMin;
Double dMax;
// d = d*(10^6);
if ((p.getProperty("dMin") == null) && (p.getProperty("dMax") == null)) {
// p.setProperty("dMin", Integer.toString((int)(Math.floor(d))));
// p.setProperty("dMax", Integer.toString((int)(Math.floor(d))));
p.setProperty("dMin", d.toString());
p.setProperty("dMax", d.toString());
return;
} else {
dMin = Double.parseDouble(p.getProperty("dMin"));
dMax = Double.parseDouble(p.getProperty("dMax"));
if (d < dMin) {
dMin = d;
} else if (d > dMax) {
dMax = d;
}
}
p.setProperty("dMin", dMin.toString());
p.setProperty("dMax", dMax.toString());
}
public String getPlaceInfoIndex(String s) {
String index = null;
for (String st2 : placeInfo.keySet()) {
if (("p" + placeInfo.get(st2).getProperty("placeNum"))
.equalsIgnoreCase(s)) {
index = st2;
break;
}
}
return index;
}
public String getTransientNetPlaceIndex(String s) {
String index = null;
for (String st2 : transientNetPlaces.keySet()) {
if (("p" + transientNetPlaces.get(st2).getProperty("placeNum"))
.equalsIgnoreCase(s)) {
index = st2;
break;
}
}
return index;
}
public ArrayList<Integer> diff(String pre_bin, String post_bin) {
ArrayList<Integer> diffL = new ArrayList<Integer>();
String[] preset_encoding = pre_bin.split(",");
String[] postset_encoding = post_bin.split(",");
for (int j = 0; j < preset_encoding.length; j++) { // to account for "" being created in the array
if (Integer.parseInt(preset_encoding[j]) != Integer.parseInt(postset_encoding[j])) {
diffL.add(j);// to account for "" being created in the array
}
}
return (diffL);
}
public int getMinRate(String place, String name) {
Properties p = placeInfo.get(place);
return ((int) Math.floor(Double.parseDouble(p.getProperty(name
+ "_rMin"))));
// return(rMin[i]);
}
public int getMaxRate(String place, String name) {
Properties p = placeInfo.get(place);
return ((int) Math.floor(Double.parseDouble(p.getProperty(name
+ "_rMax"))));
// return(rMin[i]);
}
public HashMap <String, Double[]> getDataExtrema(ArrayList<ArrayList<Double>> data){
HashMap <String, Double[]> extrema = new HashMap <String, Double[]>();
for (int i=0; i<reqdVarsL.size(); i++){
//Object obj = Collections.min(data.get(reqdVarIndices.get(i)));
Object obj = Collections.min(data.get(i+1));
extrema.put(reqdVarsL.get(i).getName(),new Double[2]);
extrema.get(reqdVarsL.get(i).getName())[0] = Double.parseDouble(obj.toString());
//obj = Collections.max(data.get(reqdVarIndices.get(i)));
obj = Collections.max(data.get(i+1));
extrema.get(reqdVarsL.get(i).getName())[1] = Double.parseDouble(obj.toString());
}
return extrema;
}
public HashMap<String, ArrayList<Double>> initDivisions(HashMap<String,Double[]> extrema){
// this method won't be called in auto case.. so dont worry?
int numThresholds;
if (numBins.getSelectedItem().toString().equalsIgnoreCase("Auto"))
numThresholds = -1;
else
numThresholds = Integer.parseInt(numBins.getSelectedItem().toString()) - 1;
double interval;
HashMap<String, ArrayList<Double>> localThresholds = new HashMap<String, ArrayList<Double>> ();
for (int i = 0; i < reqdVarsL.size(); i++){
localThresholds.put(reqdVarsL.get(i).getName(),new ArrayList<Double>());
if (!suggestIsSource){ // could use user.isselected instead of this.
//numThresholds = Integer.parseInt(numBins.getSelectedItem().toString()) - 1;
}
else{
for (int j = 1; j < variablesPanel.getComponentCount(); j++){
if ((((JTextField)((JPanel)variablesPanel.getComponent(j)).getComponent(0)).getText().trim()).equalsIgnoreCase(reqdVarsL.get(i).getName())){
if (((String)((JComboBox)((JPanel)variablesPanel.getComponent(j)).getComponent(6)).getSelectedItem()).equalsIgnoreCase("Auto"))
numThresholds = -1;
else
numThresholds = Integer.parseInt((String)((JComboBox)((JPanel)variablesPanel.getComponent(j)).getComponent(6)).getSelectedItem())-1; // changed 2 to 3 after required
break;
}
}
}
if (numThresholds != -1){
interval = (Math.abs(extrema.get(reqdVarsL.get(i).getName())[1] - extrema.get(reqdVarsL.get(i).getName())[0]))/(numThresholds + 1);
for (int j = 0; j< numThresholds; j++){
if (localThresholds.get(reqdVarsL.get(i).getName()).size() <= j){
localThresholds.get(reqdVarsL.get(i).getName()).add(extrema.get(reqdVarsL.get(i).getName())[0] + interval*(j+1));
}
else{
localThresholds.get(reqdVarsL.get(i).getName()).set(j,extrema.get(reqdVarsL.get(i).getName())[0] + interval*(j+1));
}
}
}
}
suggestIsSource = false;
return localThresholds;
}
/**
* This method generates thresholds for the variables in the learn view.
* If auto generate option is selected, then the number of thresholds for
* all the variables is same as the number selected in the number of bins.
* If user generation option is selected & suggest button is pressed, then
* the number of thresholds for each variable is equal to the number selected
* in the combobox against that variable in the variablesPanel.
*
* Rev. 1 - Scott Little (autogenT.py)
* Rev. 2 - Satish Batchu ( autogenT() ) -- Aug 12, 2009
*/
public HashMap<String,ArrayList<Double>> autoGenT(JFrame running){
//int iterations = Integer.parseInt(iteration.getText());
ArrayList<ArrayList<Double>> fullData = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> singleFileData = new ArrayList<ArrayList<Double>>();
HashMap<String, ArrayList<Double>> localThresholds = new HashMap<String, ArrayList<Double>>();
int i = 1;
try{
while (new File(directory + separator + "run-" + i + ".tsd").exists()) {
TSDParser tsd = new TSDParser(directory + separator + "run-" + i +".tsd", false);
singleFileData = tsd.getData();
varNames = tsd.getSpecies();
if (i == 1){
fullData.add(new ArrayList<Double>());
}
(fullData.get(0)).addAll(singleFileData.get(0));
for (int k = 0; k < reqdVarsL.size(); k++){
boolean found = false;
for (int j = 0; j< singleFileData.size(); j++){
if (reqdVarsL.get(k).getName().equalsIgnoreCase(varNames.get(j))) {
if (i == 1){
fullData.add(new ArrayList<Double>());
}
(fullData.get(k+1)).addAll(singleFileData.get(j));
found = true;
break;
}
}
if (!found){
out.write("variable " + reqdVarsL.get(k).getName() + " is required var somehow. But its data is not present. Adding empty array.\n");
fullData.add(new ArrayList<Double>());
}
}
i++;
}
int numThresholds = -1;
findReqdVarIndices(); // not required in this case
dmvcValuesUnique = new HashMap<String, Properties>();
HashMap<String, ArrayList<Double>> dmvDivs = detectDMV(fullData,true); //System.out.println("dmvDivs :"+dmvDivs);
HashMap<String, Integer> varThresholds = new HashMap<String, Integer>();
if (!suggestIsSource){
out.write("suggest is not the source\n");
String selected = numBins.getSelectedItem().toString();
if (!selected.equalsIgnoreCase("Auto"))
numThresholds = Integer.parseInt(selected) - 1;
else
numThresholds = -1;
//numThresholds = Integer.parseInt(numBins.getSelectedItem().toString()) - 1; //after adding 0 to comboboxes
if (numThresholds == -1){
for (String k : dmvDivs.keySet()){
for (int l = 0; l < reqdVarsL.size(); l++){
if (!reqdVarsL.get(l).isDmvc()){
JOptionPane.showMessageDialog(Gui.frame,
"Can't generate the number of thresholds for continuous variables.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
out.write(reqdVarsL.get(l).getName() + " is not a dmv. So.. ");
out.write("ERROR! Can't generate the number of thresholds for continuous variables.");
out.close();
running.setCursor(null);
running.dispose();
return(localThresholds);
} else {
out.write(reqdVarsL.get(l).getName() + " is a dmv in autogenT.");
}
if (k.equalsIgnoreCase(reqdVarsL.get(l).getName())){
localThresholds.put(k,dmvDivs.get(k));
}
}
}
} else {
out.write("auto generate. All variables get " + numThresholds + " threholds \n");
}
}
else{
out.write("suggest is the source\n");
for (int k = 0; k < reqdVarsL.size(); k++){
for (int j = 1; j < variablesPanel.getComponentCount(); j++){
if ((((JTextField)((JPanel)variablesPanel.getComponent(j)).getComponent(0)).getText().trim()).equalsIgnoreCase(reqdVarsL.get(k).getName())){
String selected = (String) (((JComboBox) ((JPanel)variablesPanel.getComponent(j)).getComponent(6)).getSelectedItem()); // changed 2 to 3 after required
if (!selected.equalsIgnoreCase("Auto"))
numThresholds = Integer.parseInt(selected) - 1; // changed 2 to 3 after required
else
numThresholds = -1;
//numThresholds = Integer.parseInt((String)((JComboBox)((JPanel)variablesPanel.getComponent(j)).getComponent(6)).getSelectedItem()) -1; // changed 2 to 3 after required
varThresholds.put(reqdVarsL.get(k).getName(),Integer.valueOf(numThresholds));
if (numThresholds == -1){
if (!reqdVarsL.get(k).isDmvc()){
JOptionPane.showMessageDialog(Gui.frame,
"Can't generate the number of thresholds for continuous variables.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
out.write(reqdVarsL.get(k).getName() + " is not a dmv. So.. ");
out.write("ERROR! Can't generate the number of thresholds for continuous variables.");
out.close();
running.setCursor(null);
running.dispose();
return(localThresholds);
}
//else {
//localThresholds.put(reqdVarsL.get(k).getName(),dmvDivs.get(reqdVarsL.get(k).getName()));
out.write("saving auto generated thresholds for " + reqdVarsL.get(k).getName() + " whether or not it is a dmv\n");
localThresholds.put(reqdVarsL.get(k).getName(),dmvDivs.get(reqdVarsL.get(k).getName()));
} else {
out.write(reqdVarsL.get(k).getName() + " is a dmv in autogenT.");
}
break;
}
}
}
}
if ((suggestIsSource && (Collections.max(varThresholds.values()) == -1)) || (!suggestIsSource && (numThresholds == -1))){
}
else if (suggestIsSource && !(Collections.max(varThresholds.values()) == -1)) {
HashMap<String, Double[]> extrema = getDataExtrema(fullData); //CHANGE THIS TO HASHMAP for replacing divisionsL by threholds
//divisions = initDivisions(extrema,divisions);
localThresholds = initDivisions(extrema);
//System.out.println("local 1 :"+localThresholds);
//localThresholds = greedyOpt(localThresholds,fullData,extrema); // commented it on March 26th 2011, not required
//System.out.println("local 2 :"+localThresholds);
// Overwriting dmv divisions calculated above with those that come from detectDMV here.
for (int l = 0; l < reqdVarsL.size(); l++){
for (String k : dmvDivs.keySet()){ //System.out.println("k :"+k);
//if(varThresholds.get(k)!=null){ System.out.println("varthresh :");
if ((k.equalsIgnoreCase(reqdVarsL.get(l).getName())) && (varThresholds.get(k) == -1)){ //System.out.println("k2 :");
//if (k.equalsIgnoreCase(reqdVarsL.get(l).getName())){ System.out.println("k2 :");
localThresholds.get(reqdVarsL.get(l).getName()).clear();
localThresholds.get(reqdVarsL.get(l).getName()).addAll(dmvDivs.get(k));
}
}
}
}
else{
HashMap<String, Double[]> extrema = getDataExtrema(fullData); //CHANGE THIS TO HASHMAP for replacing divisionsL by threholds
//divisions = initDivisions(extrema,divisions);
localThresholds = initDivisions(extrema);
//System.out.println("local 1 :"+localThresholds);
//localThresholds = greedyOpt(localThresholds,fullData,extrema);
//System.out.println("local 2 :"+localThresholds);
// Overwriting dmv divisions calculated above with those that come from detectDMV here.
for (int l = 0; l < reqdVarsL.size(); l++){
for (String k : dmvDivs.keySet()){
//if(varThresholds.get(k)!=null){ System.out.println("varthresh :");
//if ((k.equalsIgnoreCase(reqdVarsL.get(l).getName())) && (varThresholds.get(k) == -1)){ System.out.println("k2 :");
if (k.equalsIgnoreCase(reqdVarsL.get(l).getName())){
localThresholds.get(reqdVarsL.get(l).getName()).clear();
localThresholds.get(reqdVarsL.get(l).getName()).addAll(dmvDivs.get(k));
}
}
}
}
}
catch(NullPointerException e){
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Unable to calculate rates.\nThresholds could not be generated\nWindow size or pathLengthBin must be reduced.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
running.setCursor(null);
running.dispose();
} catch (IOException e2) {
e2.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Unable to write into log file in autogenT.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
} catch (NoSuchElementException e3) {
e3.printStackTrace();
if (reqdVarsL.size() == 0){
JOptionPane.showMessageDialog(Gui.frame,
"No input or output variables.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
return localThresholds;
}
public HashMap<String, ArrayList<Double>> greedyOpt(HashMap<String, ArrayList<Double>> localThresholds,ArrayList<ArrayList<Double>> fullData, HashMap<String,Double[]> extrema){
HashMap<String, ArrayList<Double>> newThresholds = new HashMap<String, ArrayList<Double>>(); // = divisions; // initialization rechk??
ArrayList<Integer> res = new ArrayList<Integer>();
int updateVar = 0;
Double bestCost =0.0,newCost;
Double distance = 0.0;
boolean pointsSelected = false;
int numMoves = 0;
int iterations = Integer.parseInt(iteration.getText());
if (points.isSelected()){
pointsSelected = true;
bestCost = pointDistCost(fullData, localThresholds,res,updateVar);
}
else if (range.isSelected()){
pointsSelected = false;
bestCost = rateRangeCost(fullData, localThresholds);
}
while (numMoves < iterations){ // Infinite loop here if thresholds not present in localThresholds
for (int i = 0; i < localThresholds.size(); i++){
for (int j = 0; j < localThresholds.get(reqdVarsL.get(i).getName()).size(); j++){
if (j == 0){
if (localThresholds.get(reqdVarsL.get(i).getName()).get(j) != null){
distance = Math.abs(localThresholds.get(reqdVarsL.get(i).getName()).get(j) - extrema.get(reqdVarsL.get(i).getName())[0])/2;
}
else{// will else case ever occur???
distance = Math.abs(localThresholds.get(reqdVarsL.get(i).getName()).get(j) - localThresholds.get(reqdVarsL.get(i).getName()).get(j-1))/2;
}
}
else{
distance = Math.abs(localThresholds.get(reqdVarsL.get(i).getName()).get(j) - localThresholds.get(reqdVarsL.get(i).getName()).get(j-1))/2;
}
// deep copy
//newDivs = divisions;
newThresholds = new HashMap<String, ArrayList<Double>>();
for (String s : localThresholds.keySet()){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : localThresholds.get(s)){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
newThresholds.put(s, tempDiv);
}
newThresholds.get(reqdVarsL.get(i).getName()).set(j,newThresholds.get(reqdVarsL.get(i).getName()).get(j)-distance);
if (pointsSelected){
newCost = pointDistCost(fullData,newThresholds,res,i+1);
}
else{
newCost = rateRangeCost(fullData, newThresholds);
}
numMoves++;
if (numMoves % 500 == 0){
System.out.println("Iteration "+ numMoves + "/" + iterations);
}
if (newCost < bestCost){
bestCost = newCost;
localThresholds = new HashMap<String, ArrayList<Double>>();
for (String s : newThresholds.keySet()){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : newThresholds.get(s)){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
localThresholds.put(s, tempDiv);
}
// divisions = newDivs; deep copy ?????
}
else{
if (j == (localThresholds.get(reqdVarsL.get(i).getName()).size() - 1)){
distance = Math.abs(extrema.get(reqdVarsL.get(i).getName())[1] - localThresholds.get(reqdVarsL.get(i).getName()).get(j))/2;
}
else{
distance = Math.abs(localThresholds.get(reqdVarsL.get(i).getName()).get(j+1) - localThresholds.get(reqdVarsL.get(i).getName()).get(j))/2;
}
// deep copy
//newDivs = divisions;
newThresholds = new HashMap<String, ArrayList<Double>>();
for (String s : localThresholds.keySet()){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : localThresholds.get(s)){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
newThresholds.put(s, tempDiv);
}
newThresholds.get(reqdVarsL.get(i).getName()).set(j,newThresholds.get(reqdVarsL.get(i).getName()).get(j)+distance);
if (pointsSelected){
newCost = pointDistCost(fullData,newThresholds,res,i+1);
}
else{
newCost = rateRangeCost(fullData, newThresholds);
}
numMoves++;
if (numMoves % 500 == 0){
System.out.println("Iteration "+ numMoves + "/" + iterations);
}
if (newCost < bestCost){
bestCost = newCost;
localThresholds = new HashMap<String, ArrayList<Double>>();
for (String s : newThresholds.keySet()){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : newThresholds.get(s)){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
localThresholds.put(s, tempDiv);
}
// divisions = newDivs; deep copy ?????
}
if (numMoves > iterations){
return localThresholds;
}
}
}
}
}
return localThresholds;
}
// CHANGE EXTREMA TO HASHMAP for for replacing divisionsL by threholds in autogenT
public Double rateRangeCost(ArrayList<ArrayList<Double>> fullData, HashMap<String, ArrayList<Double>> localThresholds){
Double total = 0.0;
Double[] minMaxR = {null,null};
//genBinsRates(datFile, divisions);
Double[][] rates = genBinsRatesForAutogen(fullData, localThresholds);
for (int i = 0; i < localThresholds.size(); i++){
minMaxR = getMinMaxRates(rates[i]);
total += Math.abs(minMaxR[1] - minMaxR[0]);
}
return total;
}
public Double pointDistCost(ArrayList<ArrayList<Double>> fullData,HashMap<String, ArrayList<Double>> localThresholds, ArrayList<Integer> res, int updateVar ){
Double total = 0.0;
int pts = 0;
if (updateVar == 0){
for (int i = 0; i < localThresholds.size() + 1; i++){
res.add(0);
}
for (int i = 0; i < localThresholds.size(); i++){
pts = pointDistCostVar(fullData.get(i+1),localThresholds.get(reqdVarsL.get(i).getName()));
total += pts;
res.set(i,pts);
}
}
else if (updateVar > 0){ // res is kind of being passed by reference. it gets altered outside too.
res.set(updateVar-1, pointDistCostVar(fullData.get(updateVar),localThresholds.get(reqdVarsL.get(updateVar-1).getName())));
for (Integer i : res){
total += i;
}
//for (int i = 0; i < res.size(); i++){
// if ((updateVar - 1) != i){
// total += res.get(i);
// else{
// total += pointDistCostVar(fullData.get(updateVar),divisions.get(updateVar-1))
}
else{
for (int i = 0; i < localThresholds.size(); i++){
total += pointDistCostVar(fullData.get(i+1),localThresholds.get(reqdVarsL.get(i).getName()));
}
}
return total;
}
public int pointDistCostVar(ArrayList<Double> dat,ArrayList<Double> div){
int optPointsPerBin = dat.size()/(div.size()+1);
boolean top = false;
ArrayList<Integer> pointsPerBin = new ArrayList<Integer>();
for (int i =0; i < (div.size() +1); i++){
pointsPerBin.add(0);
}
for (int i = 0; i <dat.size() ; i++){
top = true;
for (int j =0; j < div.size(); j++){
if (dat.get(i) <= div.get(j)){
pointsPerBin.set(j, pointsPerBin.get(j)+1);
top = false;
break;
}
}
if (top){
pointsPerBin.set(div.size(), pointsPerBin.get(div.size()) + 1);
}
}
int score = 0;
for (Integer pts : pointsPerBin){
score += Math.abs(pts - optPointsPerBin );
}
return score;
}
public Double[] getMinMaxRates(Double[] rateList){
ArrayList<Double> cmpL = new ArrayList<Double>();
Double[] minMax = {null,null};// new Double[2];
for (Double r : rateList){
if (r != null){
cmpL.add(r);
}
}
if (cmpL.size() > 0){
Object obj = Collections.min(cmpL);
minMax[0] = Double.parseDouble(obj.toString());
obj = Collections.max(cmpL);
minMax[1] = Double.parseDouble(obj.toString());
}
return minMax;
}
public Double[][] genBinsRatesForAutogen(ArrayList<ArrayList<Double>> data,HashMap<String, ArrayList<Double>> localThresholds) { // genBins
rateSampling = Integer.parseInt(rateSamplingG.getText().trim());
pathLengthBin = Integer.parseInt(pathLengthBinG.getText().trim());
pathLengthVar = Integer.parseInt(pathLengthVarG.getText().trim());
int[][] bins = new int[reqdVarsL.size()][data.get(0).size()];
for (int i = 0; i < reqdVarsL.size(); i++) {
// for (int j = 1; j < varNames.size(); j++) {
// if (reqdVarsL.get(i).getName().equalsIgnoreCase(varNames.get(j))) {
// System.out.println(reqdVarsL.get(i) + " matched "+
// varNames.get(j) + " i = " + i + " j = " + j);
// reqdVarIndices.add(j);
String currentVar = reqdVarsL.get(i).getName();
for (int k = 0; k < data.get(i+1).size(); k++) {
ArrayList<Double> thresh = localThresholds.get(currentVar);
bins[i][k] = getRegion(data.get(i+1).get(k),thresh);
if ((k != 0) && (bins[i][k] != bins[i][k-1])){
int length = 0;
for (int m = k; m < data.get(i+1).size(); m++) {
if (getRegion(data.get(i+1).get(m),thresh) == bins[i][k])
length++;
else
break;
}
if (length < pathLengthVar){
// out.write("Short bin for variable " + currentVar + " at " + data.get(0).get(k) + " until " + data.get(0).get(k+length-1) + " due to min pathLengthVar. Using " + bins[i][k-1] + " instead of " + bins[i][k] + " \n");
for (int m = k; m < k+length; m++) {
bins[i][m] = bins[i][k-1];
}
} else {
for (int m = k; m < k+length; m++) {
bins[i][m] = bins[i][k];
}
}
k = k+length-1;
}
}
}
// genRates
Double[][] rates = new Double[reqdVarsL.size()][data.get(0).size()];
Double[] duration = new Double[data.get(0).size()];
int mark ; //, k; // indices of rates not same as that of the variable. if
// wanted, then size of rates array should be varNames not reqdVars
if (rateSampling == -1) { // replacing inf with -1 since int
mark = 0;
for (int i = 0; i < data.get(0).size(); i++) {
if (i < mark) {
continue;
}
while ((mark < data.get(0).size()) && (compareBins(i, mark,bins))) {
mark++;
}
if ((data.get(0).get(mark - 1) != data.get(0).get(i)) && ((mark - i) >= pathLengthBin)) {
for (int j = 0; j < reqdVarsL.size(); j++) {
//k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(j+1).get(mark - 1) - data.get(j+1).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i)));
}
duration[i] = data.get(0).get(mark - 1) - data.get(0).get(i);
}
}
} else {
boolean calcRate;
boolean prevFail = true;
int binStartPoint = 0, binEndPoint = 0;
for (int i = 0; i < (data.get(0).size() - rateSampling); i++) {
calcRate = true;
for (int l = 0; l < rateSampling; l++) {
if (!compareBins(i, i + l,bins)) {
if (!prevFail){
binEndPoint = i -2 + rateSampling;
duration[binStartPoint] = data.get(0).get(binEndPoint) - data.get(0).get(binStartPoint);
}
calcRate = false;
prevFail = true;
break;
}
}
if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) {
for (int j = 0; j < reqdVarsL.size(); j++) {
//k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(j+1).get(i + rateSampling) - data.get(j+1).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i)));
}
if (prevFail){
binStartPoint = i;
}
prevFail = false;
}
}
if (!prevFail){ // for the last genuine rate-calculating region of the trace; this may not be required if the trace is incomplete.trace data may not necessarily end at a region endpt
duration[binStartPoint] = data.get(0).get(data.get(0).size()-1) - data.get(0).get(binStartPoint);
}
}
/*
try {
logFile = new File(directory + separator + "tmp.log");
logFile.createNewFile();
out = new BufferedWriter(new FileWriter(logFile));
for (int i = 0; i < (data.get(0).size()); i++) {
for (int j = 0; j < reqdVarsL.size(); j++) {
//k = reqdVarIndices.get(j);
out.write(data.get(j+1).get(i) + " ");// + bins[j][i] + " " +
// rates[j][i] + " ");
}
for (int j = 0; j < reqdVarsL.size(); j++) {
out.write(bins[j][i] + " ");
}
for (int j = 0; j < reqdVarsL.size(); j++) {
out.write(rates[j][i] + " ");
}
out.write(duration[i] + " ");
out.write("\n");
}
out.close();
} catch (IOException e) {
System.out.println("Log file couldn't be opened for writing rates and bins ");
}*/
return rates;
}
public boolean compareBins(int j, int mark,int[][] bins) {
for (int i = 0; i < reqdVarsL.size(); i++) {
if (bins[i][j] != bins[i][mark]) {
return false;
} else {
continue;
}
}
return true;
}
public void addPseudo(HashMap<String,ArrayList<Double>> scaledThresholds){
lpnWithPseudo = new LhpnFile();
lpnWithPseudo = mergeLhpns(lpnWithPseudo,g);
pseudoVars = new HashMap<String,Boolean>();
pseudoVars.put("ctl",true);
for (String st : g.getPlaceList()){
currentPlace = st;
//TODO: do this only if not prop type place
if (getPlaceInfoIndex(st) != null)
currPlaceBin = getPlaceInfoIndex(st).split(",");
else
currPlaceBin = getTransientNetPlaceIndex(st).split(",");
traverse(scaledThresholds);
}
}
private void traverse(HashMap<String,ArrayList<Double>> scaledThresholds){
for (String nextPlace : g.getPlaceList()){
if ((!nextPlace.equalsIgnoreCase(currentPlace)) && (getPlaceInfoIndex(nextPlace) != null)){
if ((getPlaceInfoIndex(currentPlace) != null) && (!transitionInfo.containsKey(getPlaceInfoIndex(currentPlace) + getPlaceInfoIndex(nextPlace)))){
addPseudoTrans(nextPlace, scaledThresholds);
} else if ((getTransientNetPlaceIndex(currentPlace) != null) && (!transientNetTransitions.containsKey(getTransientNetPlaceIndex(currentPlace) + getPlaceInfoIndex(nextPlace)))){
addPseudoTrans(nextPlace, scaledThresholds);
}
}
}
}
private void addPseudoTrans(String nextPlace, HashMap<String, ArrayList<Double>> scaledThresholds){ // Adds pseudo transition b/w currentPlace and nextPlace
String[] nextPlaceBin = getPlaceInfoIndex(nextPlace).split(",");
String enabling = "";
int bin;
String st;
Boolean pseudo = false;
for (int i = 0; i < reqdVarsL.size(); i++) {
if (reqdVarsL.get(i).isInput()){
if (Integer.valueOf(currPlaceBin[i]) == Integer.valueOf(nextPlaceBin[i])){
continue;
} else {
if (!pseudoVars.containsKey(reqdVarsL.get(i).getName())){
pseudo = false;
break;
}
if (Math.abs(Integer.valueOf(currPlaceBin[i]) - Integer.valueOf(nextPlaceBin[i])) > 1){
pseudo = false;
break;
}
pseudo = true;
bin = Integer.valueOf(nextPlaceBin[i]);
st = reqdVarsL.get(i).getName();
if (bin == 0){
if (!enabling.equalsIgnoreCase(""))
enabling += "&";
enabling += "~(" + st + ">=" + (int) Math.ceil(scaledThresholds.get(st).get(bin).doubleValue()) + ")";
} else if (bin == (scaledThresholds.get(st).size())){
if (!enabling.equalsIgnoreCase(""))
enabling += "&";
enabling += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")";
} else{
if (!enabling.equalsIgnoreCase(""))
enabling += "&";
enabling += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")&~(" + st + ">=" + (int) Math.ceil(scaledThresholds.get(st).get(bin).doubleValue()) + ")";
}
}
} else {
if (Integer.valueOf(currPlaceBin[i]) != Integer.valueOf(nextPlaceBin[i])){
pseudo = false;
break;
}
}
}
if (pseudo){
System.out.println("Adding pseudo-transition pt" + pseudoTransNum + " between " + currentPlace + " and " + nextPlace + " with enabling " + enabling + "\n");
lpnWithPseudo.addTransition("pt" + pseudoTransNum);
lpnWithPseudo.addMovement(currentPlace, "pt" + pseudoTransNum);
lpnWithPseudo.addMovement("pt" + pseudoTransNum, nextPlace);
lpnWithPseudo.addEnabling("pt" + pseudoTransNum, enabling);
pseudoTransNum++;
}
}
public void addMetaBins(){ // TODO: DIDN'T REPLACE divisionsL by thresholds IN THIS METHOD
boolean foundBin = false;
for (String st1 : g.getPlaceList()){
String p = getPlaceInfoIndex(st1);
String[] binEncoding ;
ArrayList<Integer> syncBinEncoding;
String o1;
// st1 w.r.t g
// p w.r.t placeInfo
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
// String [] bE = p.split("");
String [] bE = p.split(",");
binEncoding = new String[bE.length - 1];
for (int i = 0; i < bE.length; i++){
binEncoding[i] = bE[i]; // since p.split("") gives ,0,1 if p was 01
}
for (int i = 0; i < binEncoding.length ; i++){
if (!reqdVarsL.get(i).isDmvc()){
if ((lowerLimit[i] != null) && (getMinRate(p,reqdVarsL.get(i).getName()) < 0)){
syncBinEncoding = new ArrayList<Integer>();
// deep copy of bin encoding
for (int n = 0; n < binEncoding.length; n++){
o1 = binEncoding[n];
if (o1 == "A"){
syncBinEncoding.add(-1);
}
else if (o1 == "Z"){
syncBinEncoding.add(divisionsL.get(n).size());
}
else{
syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here
}
}
foundBin = false;
while (!foundBin){
syncBinEncoding.set(i,syncBinEncoding.get(i) - 1);
String key = "";
for (int m = 0; m < syncBinEncoding.size(); m++){
if (syncBinEncoding.get(m) != -1){
key += syncBinEncoding.get(m).toString();
}
else{
key += "A";
}
}
if ((syncBinEncoding.get(i) == -1) && (!placeInfo.containsKey(key))){
foundBin = true;
Properties p0 = new Properties();
placeInfo.put(key, p0);
p0.setProperty("placeNum", numPlaces.toString());
p0.setProperty("type", "RATE");
p0.setProperty("initiallyMarked", "false");
p0.setProperty("metaType","true");
p0.setProperty("metaVar", String.valueOf(i));
g.addPlace("p" + numPlaces, false);
//ratePlaces.add("p"+numPlaces);
numPlaces++;
if (getMaxRate(p,reqdVarsL.get(i).getName()) > 0){ // minrate is 0; maxrate remains the same if positive
addRate(p0, reqdVarsL.get(i).getName(), 0.0);
addRate(p0, reqdVarsL.get(i).getName(), (double)getMaxRate(p,reqdVarsL.get(i).getName()));
/*
* This transition should be added only in this case but
* since dotty cribs if there's no place on a transition's postset,
* moving this one down so that this transition is created even if the
* min,max rate is 0 in which case it wouldn't make sense to have this
* transition
* Properties p2 = new Properties();
transitionInfo.put(key + p, p2);
p2.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addControlFlow("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum"));
g.addControlFlow("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum"));
g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")" + "&~fail");
numTransitions++; */
}
else{
addRate(p0, reqdVarsL.get(i).getName(), 0.0); // if the maximum rate was negative, then make the min & max rates both as zero
}
Properties p1 = new Properties();
transitionInfo.put(p + key, p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(p + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
// g.addEnabling("t" + numTransitions, "~fail");
g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")");
int minr = getMinRate(key, reqdVarsL.get(i).getName());
int maxr = getMaxRate(key, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
numTransitions++;
Properties p2 = new Properties();
transitionInfo.put(key + p, p2);
p2.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum"));
g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")");
minr = getMinRate(p, reqdVarsL.get(i).getName());
maxr = getMaxRate(p, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
numTransitions++;
}
else if (placeInfo.containsKey(key)){
foundBin = true;
//Properties syncP = placeInfo.get(key);
Properties p1;
if (!transitionInfo.containsKey(p + key)) { // instead of tuple
p1 = new Properties();
transitionInfo.put(p + key, p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(p + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
// g.addEnabling("t" + numTransitions, "~fail");
g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")");
int minr = getMinRate(key, reqdVarsL.get(i).getName());
int maxr = getMaxRate(key, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
numTransitions++;
}
}
}
}
if ((upperLimit[i] != null) && getMaxRate(p,reqdVarsL.get(i).getName()) > 0){
syncBinEncoding = new ArrayList<Integer>();
// deep copy of bin encoding
for (int n = 0; n < binEncoding.length; n++){
o1 = binEncoding[n];
if (o1 == "A"){
syncBinEncoding.add(-1);
}
else if (o1 == "Z"){
syncBinEncoding.add(divisionsL.get(n).size()+1);
}
else{
syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here
}
}
foundBin = false;
while (!foundBin){
syncBinEncoding.set(i,syncBinEncoding.get(i) + 1);
String key = "";
for (int m = 0; m < syncBinEncoding.size(); m++){
if (syncBinEncoding.get(m) < divisionsL.get(i).size()+1){
key += syncBinEncoding.get(m).toString();
}
else{
key += "Z";
// encoding not required here.. but may be useful to distinguish the pseudobins from normal bins in future
}
}
if ((syncBinEncoding.get(i) == divisionsL.get(i).size() + 1) && (!placeInfo.containsKey(key))){
// divisionsL.get(i).size() + 1 or divisionsL.get(i).size()???
foundBin = true;
Properties p0 = new Properties();
placeInfo.put(key, p0);
p0.setProperty("placeNum", numPlaces.toString());
p0.setProperty("type", "RATE");
p0.setProperty("initiallyMarked", "false");
p0.setProperty("metaType","true");
p0.setProperty("metaVar", String.valueOf(i));
//ratePlaces.add("p"+numPlaces);
g.addPlace("p" + numPlaces, false);
numPlaces++;
if (getMinRate(p,reqdVarsL.get(i).getName()) < 0){ // maxrate is 0; minrate remains the same if negative
addRate(p0, reqdVarsL.get(i).getName(), 0.0);
addRate(p0, reqdVarsL.get(i).getName(), (double)getMinRate(p,reqdVarsL.get(i).getName()));
/*
* This transition should be added only in this case but
* since dotty cribs if there's no place on a transition's postset,
* moving this one down so that this transition is created even if the
* min,max rate is 0 in which case it wouldn't make sense to have this
* transition
*
Properties p2 = new Properties();
transitionInfo.put(key + p, p2);
p2.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addControlFlow("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum"));
g.addControlFlow("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum"));
g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")" + "&~fail");
numTransitions++;
*/
}
else{
addRate(p0, reqdVarsL.get(i).getName(), 0.0); // if the minimum rate was positive, then make the min & max rates both as zero
}
Properties p1 = new Properties();
transitionInfo.put(p + key, p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(p + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
// g.addEnabling("t" + numTransitions, "~fail");
int minr = getMinRate(key, reqdVarsL.get(i).getName());
int maxr = getMaxRate(key, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")");
numTransitions++;
Properties p2 = new Properties();
transitionInfo.put(key + p, p2);
p2.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum"));
g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")");
minr = getMinRate(p, reqdVarsL.get(i).getName());
maxr = getMaxRate(p, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
numTransitions++;
}
else if (placeInfo.containsKey(key)){
foundBin = true;
//Properties syncP = placeInfo.get(key);
Properties p1;
if (!transitionInfo.containsKey(p + key)) { // instead of tuple
p1 = new Properties();
transitionInfo.put(p + key, p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(p + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
// g.addEnabling("t" + numTransitions, "~fail");
int minr = getMinRate(key, reqdVarsL.get(i).getName());
int maxr = getMaxRate(key, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")");
numTransitions++;
}
}
}
}
}
}
}
}
}
/* public void writeVHDLAMSFile(String vhdFile){
try{
ArrayList<String> ratePlaces = new ArrayList<String>();
ArrayList<String> dmvcPlaces = new ArrayList<String>();
File VHDLFile = new File(directory + separator + vhdFile);
VHDLFile.createNewFile();
BufferedWriter vhdlAms = new BufferedWriter(new FileWriter(VHDLFile));
StringBuffer buffer = new StringBuffer();
String pNum;
vhdlAms.write("library IEEE;\n");
vhdlAms.write("use IEEE.std_logic_1164.all;\n");
vhdlAms.write("use work.handshake.all;\n");
vhdlAms.write("use work.nondeterminism.all;\n\n");
vhdlAms.write("entity amsDesign is\n");
vhdlAms.write("end amsDesign;\n\n");
vhdlAms.write("architecture "+vhdFile.split("\\.")[0]+" of amsDesign is\n");
for (Variable v : reqdVarsL){
vhdlAms.write("\tquantity "+v.getName()+":real;\n");
}
for (int i = 0; i < numPlaces; i++){
if (!isTransientPlace("p"+i)){
String p = getPlaceInfoIndex("p"+i);
if (!placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
continue;
}
}
else {
String p = getTransientNetPlaceIndex("p"+i);
if (!transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
continue;
}
}
vhdlAms.write("\tshared variable place:integer:= "+i+";\n");
break;
}
if (failPropVHDL != null){
//TODO: Make this an assertion
//vhdlAms.write("\tshared variable fail:boolean:= false;\n");
}
for (String st1 : g.getPlaceList()){
if (!isTransientPlace(st1)){
String p = getPlaceInfoIndex(st1);
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
ratePlaces.add(st1); // w.r.t g here
}
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("PROP")) {
}
}
else{
String p = getTransientNetPlaceIndex(st1);
if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")){
ratePlaces.add(st1); // w.r.t g here
}
}
}
Collections.sort(dmvcPlaces,new Comparator<String>(){
public int compare(String a, String b){
if (Integer.parseInt(a.split("_")[1]) < Integer.parseInt(b.split("_")[1])){
return -1;
}
else if (Integer.parseInt(a.split("_")[1]) == Integer.parseInt(b.split("_")[1])){
return 0;
}
else{
return 1;
}
}
});
Collections.sort(ratePlaces,new Comparator<String>(){
String v1,v2;
public int compare(String a, String b){
if (!isTransientPlace(a) && !isTransientPlace(b)){
v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum");
v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum");
}
else if (!isTransientPlace(a) && isTransientPlace(b)){
v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum");
v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum");
}
else if (isTransientPlace(a) && !isTransientPlace(b)){
v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum");
v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum");
}
else {
v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum");
v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum");
}
if (Integer.parseInt(v1) < Integer.parseInt(v2)){
return -1;
}
else if (Integer.parseInt(v1) == Integer.parseInt(v2)){
return 0;
}
else{
return 1;
}
}
});
// sending the initial place to the end of the list. since if statements begin with preset of each place
//ratePlaces.add(ratePlaces.get(0));
//ratePlaces.remove(0);
vhdlAms.write("begin\n");
//buffer.append("\nbegin\n");
String[] vals;
for (Variable v : reqdVarsL){ // taking the lower value from the initial value range. Ok?
//vhdlAms.write("\tbreak "+v.getName()+" => "+((((v.getInitValue()).split("\\,"))[0]).split("\\["))[1]+".0;\n");
vals = v.getInitValue().split("\\,");
vhdlAms.write("\tbreak "+v.getName()+" => span("+((vals[0]).split("\\["))[1]+".0,"+ ((vals[1]).split("\\]"))[0] +".0);\n");
//buffer.append("\tbreak "+v.getName()+" => span("+((vals[0]).split("\\["))[1]+".0,"+ ((vals[1]).split("\\]"))[0] +".0);\n");
}
vhdlAms.write("\n");
//buffer.append("\n");
for (Variable v : reqdVarsL){
if (v.isDmvc()){
vhdlAms.write("\t"+v.getName()+"'dot == 0.0;\n");
//buffer.append("\t"+v.getName()+"'dot == 0.0;\n");
}
}
vhdlAms.write("\n");
//buffer.append("\n");
ArrayList<ArrayList<String>> dmvcVarPlaces = new ArrayList<ArrayList<String>>();
boolean contVarExists = false;
for (Variable v: reqdVarsL){
dmvcVarPlaces.add(new ArrayList<String>());
if (v.isDmvc()){
continue;
}
else{
contVarExists = true;
}
}
for (String st:dmvcPlaces){
dmvcVarPlaces.get(Integer.parseInt(st.split("_")[1])).add(st);
}
if (contVarExists){
if (ratePlaces.size() != 0){
//vhdlAms.write("\tcase place use\n");
buffer.append("\tcase place use\n");
}
//vhdlAms.write("\ntype rate_places is (");
for (String p : ratePlaces){
pNum = p.split("p")[1];
//vhdlAms.write("\t\twhen "+p.split("p")[1] +" =>\n");
buffer.append("\t\twhen "+ pNum +" =>\n");
if (!isTransientPlace(p)){
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
//if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){
//vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n");
buffer.append("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n");
}
}
}
else{
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
//if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){
//vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n");
buffer.append("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getTransientNetPlaceIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getTransientNetPlaceIndex(p), reqdVarsL.get(j).getName())+".0);\n");
}
}
}
}
vhdlAms.write(buffer.toString());
vhdlAms.write("\t\twhen others =>\n");
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
//if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){
vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == 0.0;\n");
}
}
vhdlAms.write("\tend case;\n");
}
vhdlAms.write("\tprocess\n");
vhdlAms.write("\tbegin\n");
vhdlAms.write("\tcase place is\n");
buffer.delete(0, buffer.length());
String[] transL;
int transNum;
for (String p : ratePlaces){
pNum = p.split("p")[1];
vhdlAms.write("\t\twhen "+pNum +" =>\n");
vhdlAms.write("\t\t\twait until ");
transL = g.getPostset(p);
if (transL.length == 1){
transNum = Integer.parseInt(transL[0].split("t")[1]);
vhdlAms.write(transEnablingsVHDL[transNum] + ";\n");
if (transDelayAssignVHDL[transNum] != null){
vhdlAms.write("\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n");
//vhdlAms.write("\t\t\tbreak "+ transIntAssignVHDL[transNum]+";\n");
for (String s : transIntAssignVHDL[transNum]){
if (s != null){
vhdlAms.write("\t\t\tbreak "+ s +";\n");
}
}
}
if (g.getPostset(transL[0]).length != 0)
vhdlAms.write("\t\t\tplace := " + g.getPostset(transL[0])[0].split("p")[1] + ";\n");
}
else{
boolean firstTrans = true;
buffer.delete(0, buffer.length());
for (String t : transL){
transNum = Integer.parseInt(t.split("t")[1]);
if (firstTrans){
firstTrans = false;
vhdlAms.write("(" + transEnablingsVHDL[transNum]);
buffer.append("\t\t\tif " + transEnablingsVHDL[transNum] + " then\n");
if (transDelayAssignVHDL[transNum] != null){
buffer.append("\t\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n");
for (String s : transIntAssignVHDL[transNum]){
if (s != null){
buffer.append("\t\t\t\tbreak "+ s +";\n");
}
}
}
buffer.append("\t\t\t\tplace := " + g.getPostset(t)[0].split("p")[1] + ";\n");
}
else{
vhdlAms.write(" or " +transEnablingsVHDL[transNum] );
buffer.append("\t\t\telsif " + transEnablingsVHDL[transNum] + " then\n");
if (transDelayAssignVHDL[transNum] != null){
buffer.append("\t\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n");
//buffer.append("\t\t\t\tbreak "+ transIntAssignVHDL[transNum]+";\n");
for (String s : transIntAssignVHDL[transNum]){
if (s != null){
buffer.append("\t\t\t\tbreak "+ s +";\n");
}
}
}
buffer.append("\t\t\t\tplace := " + g.getPostset(t)[0].split("p")[1] + ";\n");
}
}
vhdlAms.write(");\n");
buffer.append("\t\t\tend if;\n");
vhdlAms.write(buffer.toString());
}
}
vhdlAms.write("\t\twhen others =>\n\t\t\twait for 0.0;\n\t\t\tplace := "+ ratePlaces.get(0).split("p")[1] + ";\n\tend case;\n\tend process;\n");
for (int i = 0; i < dmvcVarPlaces.size(); i++){
if (dmvcVarPlaces.get(i).size() != 0){
vhdlAms.write("\tprocess\n");
vhdlAms.write("\tbegin\n");
for (String p : dmvcVarPlaces.get(i)){
if (!transientNetPlaces.containsKey(p)){
vhdlAms.write("\t\twait for delay("+ (int) Math.floor(Double.parseDouble(placeInfo.get(p).getProperty("dMin")))+","+(int)Math.ceil(Double.parseDouble(placeInfo.get(p).getProperty("dMax"))) +");\n");
// recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/
vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ (int) Math.floor(Double.parseDouble(placeInfo.get(p).getProperty("DMVCValue"))) + ".0;\n");
}
else{
vhdlAms.write("\t\twait for delay("+ (int) Math.floor(Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))+","+(int)Math.ceil(Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))) +");\n");
// recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/
vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ (int) Math.floor(Double.parseDouble(transientNetPlaces.get(p).getProperty("DMVCValue"))) + ".0;\n");
}
}
vhdlAms.write("\tend process;\n\n");
}
}
if (failPropVHDL != null){
vhdlAms.write("\tprocess\n");
vhdlAms.write("\tbegin\n");
vhdlAms.write("\t\twait until " + failPropVHDL + ";\n");
//TODO: Change this to assertion
//vhdlAms.write("\t\tfail := true;\n");
vhdlAms.write("\tend process;\n\n");
}
// vhdlAms.write("\tend process;\n\n");
vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n");
vhdlAms.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(BioSim.frame,
"VHDL-AMS model couldn't be created/written.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
catch(Exception e){
JOptionPane.showMessageDialog(BioSim.frame,
"Error in VHDL-AMS model generation.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
public void writeVerilogAMSFile(String vamsFileName){
try{
ArrayList<String> ratePlaces = new ArrayList<String>();
ArrayList<String> dmvcPlaces = new ArrayList<String>();
File vamsFile = new File(directory + separator + vamsFileName);
vamsFile.createNewFile();
Double rateFactor = valScaleFactor/delayScaleFactor;
BufferedWriter vams = new BufferedWriter(new FileWriter(vamsFile));
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
StringBuffer buffer3 = new StringBuffer();
StringBuffer buffer4 = new StringBuffer();
StringBuffer initBuffer = new StringBuffer();
vams.write("`include \"constants.vams\"\n");
vams.write("`include \"disciplines.vams\"\n");
vams.write("`timescale 1ps/1ps\n\n");
vams.write("module "+vamsFileName.split("\\.")[0]+" (");
buffer.append("\tparameter delay = 0, rtime = 1p, ftime = 1p;\n");
Variable v;
String[] vals;
for (int i = 0; i < reqdVarsL.size(); i++){
v = reqdVarsL.get(i);
if ( i!= 0){
vams.write(",");
}
vams.write(" "+v.getName());
if (v.isInput()){
buffer.append("\tinput "+v.getName()+";\n\telectrical "+v.getName()+";\n");
} else{
buffer.append("\tinout "+v.getName()+";\n\telectrical "+v.getName()+";\n");
if (!v.isDmvc()){
buffer2.append("\treal change_"+v.getName()+";\n");
buffer2.append("\treal rate_"+v.getName()+";\n");
vals = v.getInitValue().split("\\,");
double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor);
initBuffer.append("\t\tchange_"+v.getName()+" = "+ spanAvg+";\n");
vals = v.getInitRate().split("\\,");
spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*rateFactor);
initBuffer.append("\t\trate_"+v.getName()+" = "+ (int)spanAvg+";\n");
}
else{
buffer2.append("\treal "+v.getName()+"Val;\n"); // changed from real to int.. check??
vals = reqdVarsL.get(i).getInitValue().split("\\,");
double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor);
initBuffer.append("\t\t"+reqdVarsL.get(i).getName()+"Val = "+ spanAvg+";\n");
}
}
}
// if (failPropVHDL != null){
// buffer.append("\toutput reg fail;\n\tlogic fail;\n");
// vams.write(", fail");
// }
vams.write(");\n" + buffer+"\n");
if (buffer2.length() != 0){
vams.write(buffer2.toString());
}
vams.write("\treal entryTime;\n");
if (vamsRandom){
vams.write("\tinteger seed;\n\tinteger del;\n");
}
vams.write("\tinteger place;\n\n\tinitial\n\tbegin\n");
vams.write(initBuffer.toString());
vams.write("\t\tentryTime = 0;\n");
if (vamsRandom){
vams.write("\t\tseed = 0;\n");
}
buffer.delete(0, buffer.length());
buffer2.delete(0, buffer2.length());
for (int i = 0; i < numPlaces; i++){
String p;
if (!isTransientPlace("p"+i)){
p = getPlaceInfoIndex("p"+i);
if (!placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
continue;
}
}
else{
p = getTransientNetPlaceIndex("p"+i);
if (!transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
continue;
}
}
vams.write("\t\tplace = "+i+";\n");
break;
}
//if (failPropVHDL != null){
// vams.write("\t\t\tfail = 1'b0;\n");
//}
vams.write("\tend\n\n");
for (String st1 : g.getPlaceList()){
if (!isTransientPlace(st1)){
String p = getPlaceInfoIndex(st1);
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
ratePlaces.add(st1); // w.r.t g here
}
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("PROP")) {
}
}
else{
String p = getTransientNetPlaceIndex(st1);
if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")){
ratePlaces.add(st1); // w.r.t g here
}
}
}
Collections.sort(dmvcPlaces,new Comparator<String>(){
public int compare(String a, String b){
if (Integer.parseInt(a.split("_")[1]) < Integer.parseInt(b.split("_")[1])){
return -1;
}
else if (Integer.parseInt(a.split("_")[1]) == Integer.parseInt(b.split("_")[1])){
if (Integer.parseInt(a.split("_")[2]) < Integer.parseInt(b.split("_")[2])){
return -1;
}
else if (Integer.parseInt(a.split("_")[2]) == Integer.parseInt(b.split("_")[2])){
return 0;
}
else{
return 1;
}
}
else{
return 1;
}
}
});
Collections.sort(ratePlaces,new Comparator<String>(){
String v1,v2;
public int compare(String a, String b){
if (!isTransientPlace(a) && !isTransientPlace(b)){
v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum");
v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum");
}
else if (!isTransientPlace(a) && isTransientPlace(b)){
v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum");
v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum");
}
else if (isTransientPlace(a) && !isTransientPlace(b)){
v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum");
v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum");
}
else {
v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum");
v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum");
}
if (Integer.parseInt(v1) < Integer.parseInt(v2)){
return -1;
}
else if (Integer.parseInt(v1) == Integer.parseInt(v2)){
return 0;
}
else{
return 1;
}
}
});
ArrayList<String> transitions = new ArrayList<String>();
for (String t : g.getTransitionList()){
transitions.add(t);
}
Collections.sort(transitions,new Comparator<String>(){
public int compare(String a, String b){
String v1 = a.split("t")[1];
String v2 = b.split("t")[1];
if (Integer.parseInt(v1) < Integer.parseInt(v2)){
return -1;
}
else if (Integer.parseInt(v1) == Integer.parseInt(v2)){
return 0;
}
else{
return 1;
}
}
});
// sending the initial place to the end of the list. since if statements begin with preset of each place
//ratePlaces.add(ratePlaces.get(0));
//ratePlaces.remove(0);
ArrayList<ArrayList<String>> dmvcVarPlaces = new ArrayList<ArrayList<String>>();
boolean contVarExists = false;
for (Variable var: reqdVarsL){
dmvcVarPlaces.add(new ArrayList<String>());
if (var.isDmvc()){
continue;
}
else{
contVarExists = true;
}
}
for (String st:dmvcPlaces){
dmvcVarPlaces.get(Integer.parseInt(st.split("_")[1])).add(st);
}
int transNum;
buffer.delete(0, buffer.length());
initBuffer.delete(0, initBuffer.length());
String presetPlace = null,postsetPlace = null;
StringBuffer[] transBuffer = new StringBuffer[transitions.size()];
int cnt = 0;
StringBuffer transAlwaysPlaceBuffer = new StringBuffer();
int placeAlwaysBlockNum = -1;
for (String t : transitions){
presetPlace = g.getPreset(t)[0];
//if (g.getPostset(t) != null){
// postsetPlace = g.getPostset(t)[0];
//}
transNum = Integer.parseInt(t.split("t")[1]);
cnt = transNum;
if (!isTransientTransition(t)){
if (placeInfo.get(getPlaceInfoIndex(presetPlace)).getProperty("type").equals("RATE")){
if (g.getPostset(t).length != 0)
postsetPlace = g.getPostset(t)[0];
for (int j = 0; j < transNum; j++){
if ((transEnablingsVAMS[j] != null) && (transEnablingsVAMS[j].equalsIgnoreCase(transEnablingsVAMS[transNum]))){
cnt = j;
break;
}
}
if ( cnt == transNum){
transBuffer[cnt] = new StringBuffer();
if (transEnablingsVAMS[transNum].equalsIgnoreCase("")){
//transBuffer[cnt].append("\talways@(place)" + "\n\tbegin\n"); May 14, 2010
placeAlwaysBlockNum = cnt;
}
else{
transBuffer[cnt].append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n");
transAlwaysPlaceBuffer.append("\t\t" + transConditionalsVAMS[transNum] + "\n\t\tbegin\n\t\t\tentryTime = $abstime;\n");
if (g.getPostset(t).length != 0)
transAlwaysPlaceBuffer.append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n");
}
}
else{
String s = transBuffer[cnt].toString();
s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n");
transBuffer[cnt].delete(0, transBuffer[cnt].length());
transBuffer[cnt].append(s);
if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){
transAlwaysPlaceBuffer.append("\t\t" + transConditionalsVAMS[transNum] + "\n\t\tbegin\n\t\t\tentryTime = $abstime;\n" + "\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n");
}
}
transBuffer[cnt].append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n");
if (transDelayAssignVAMS[transNum] != null){
transBuffer[cnt].append("\t\t\t"+transDelayAssignVAMS[transNum]+";\n");
for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){
if (transIntAssignVAMS[transNum][i] != null){
transBuffer[cnt].append("\t\t\t"+ transIntAssignVAMS[transNum][i]);
}
}
}
transBuffer[cnt].append("\t\t\tentryTime = $abstime;\n");
transBuffer[cnt].append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n");
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
transBuffer[cnt].append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n");
transBuffer[cnt].append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n");
if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){
transAlwaysPlaceBuffer.append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n");
transAlwaysPlaceBuffer.append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n");
}
}
}
transBuffer[cnt].append("\t\tend\n");
//if ( cnt == transNum){
transBuffer[cnt].append("\tend\n");
//}
if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){
transAlwaysPlaceBuffer.append("\t\tend\n");
}
}
}
else{
if (transientNetPlaces.get(getTransientNetPlaceIndex(presetPlace)).getProperty("type").equals("RATE")){
if (g.getPostset(t).length != 0)
postsetPlace = g.getPostset(t)[0];
for (int j = 0; j < transNum; j++){
if ((transEnablingsVAMS[j] != null) && (transEnablingsVAMS[j].equalsIgnoreCase(transEnablingsVAMS[transNum]))){
cnt = j;
break;
}
}
if ( cnt == transNum){
transBuffer[cnt] = new StringBuffer();
transBuffer[cnt].append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n");
}
else{
String s = transBuffer[cnt].toString();
s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n");
transBuffer[cnt].delete(0, transBuffer[cnt].length());
transBuffer[cnt].append(s);
}
transBuffer[cnt].append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n");
if (transDelayAssignVAMS[transNum] != null){
transBuffer[cnt].append("\t\t\t"+transDelayAssignVAMS[transNum]+";\n");
for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){
if (transIntAssignVAMS[transNum][i] != null){
transBuffer[cnt].append("\t\t\t"+ transIntAssignVAMS[transNum][i]);
}
}
}
transBuffer[cnt].append("\t\t\tentryTime = $abstime;\n");
if (g.getPostset(t).length != 0)
transBuffer[cnt].append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n");
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
transBuffer[cnt].append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n");
transBuffer[cnt].append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n");
}
}
transBuffer[cnt].append("\t\tend\n");
//if ( cnt == transNum){
transBuffer[cnt].append("\tend\n");
//}
}
}
//if (transDelayAssignVAMS[transNum] != null){
// buffer.append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n");
// buffer.append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n");
// buffer.append("\t\t\t#"+transDelayAssignVAMS[transNum]+";\n");
// for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){
// if (transIntAssignVAMS[transNum][i] != null){
// buffer.append("\t\t\t"+reqdVarsL.get(i).getName()+"Val = "+ transIntAssignVAMS[transNum][i]+";\n");
// }
// }
// buffer.append("\t\tend\n\tend\n");
//}
}
if (placeAlwaysBlockNum == -1){
vams.write("\talways@(place)" + "\n\tbegin\n");
vams.write(transAlwaysPlaceBuffer.toString());
vams.write("\tend\n");
}
else{
String s = transBuffer[placeAlwaysBlockNum].toString();
s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n");
transBuffer[placeAlwaysBlockNum].delete(0, transBuffer[placeAlwaysBlockNum].length());
transBuffer[placeAlwaysBlockNum].append("\talways@(place)" + "\n\tbegin\n");
transBuffer[placeAlwaysBlockNum].append(transAlwaysPlaceBuffer);
transBuffer[placeAlwaysBlockNum].append(s);
transBuffer[placeAlwaysBlockNum].append("\tend\n");
}
for (int j = 0; j < transitions.size(); j++){
if (transBuffer[j] != null){
vams.write(transBuffer[j].toString());
}
}
vams.write("\tanalog\n\tbegin\n");
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
vams.write("\t\tV("+reqdVarsL.get(j).getName()+") <+ transition(change_" + reqdVarsL.get(j).getName() + " + rate_" + reqdVarsL.get(j).getName()+"*($abstime-entryTime));\n");
}
if ((!reqdVarsL.get(j).isInput()) && (reqdVarsL.get(j).isDmvc())){
vams.write("\t\tV("+reqdVarsL.get(j).getName()+") <+ transition(" + reqdVarsL.get(j).getName() + "Val,delay,rtime,ftime);\n");
//vals = reqdVarsL.get(j).getInitValue().split("\\,");
//double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor);
//initBuffer.append("\t\t"+reqdVarsL.get(j).getName()+"Val = "+ spanAvg+";\n");
}
}
vams.write("\tend\n");
// if (initBuffer.length() != 0){
// vams.write("\n\tinitial\n\tbegin\n"+initBuffer+"\tend\n");
// }
//if (buffer.length() != 0){
// vams.write(buffer.toString());
//}
vams.write("endmodule\n\n");
buffer.delete(0, buffer.length());
buffer2.delete(0, buffer2.length());
initBuffer.delete(0, initBuffer.length());
int count = 0;
for (int i = 0; i < dmvcVarPlaces.size(); i++){
if (dmvcVarPlaces.get(i).size() != 0){
if (count == 0){
vams.write("module driver ( " + reqdVarsL.get(i).getName() + "drive ");
count++;
}
else{
vams.write(", " + reqdVarsL.get(i).getName() + "drive ");
count++;
}
buffer.append("\n\toutput "+ reqdVarsL.get(i).getName() + "drive;\n");
buffer.append("\telectrical "+ reqdVarsL.get(i).getName() + "drive;\n");
buffer2.append("\treal " + reqdVarsL.get(i).getName() + "Val" + ";\n");
vals = reqdVarsL.get(i).getInitValue().split("\\,");
double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor);
initBuffer.append("\n\tinitial\n\tbegin\n"+"\t\t"+ reqdVarsL.get(i).getName() + "Val = "+ spanAvg+";\n");
if ((count == 1) && (vamsRandom) ){
initBuffer.append("\t\tseed = 0;\n");
}
//buffer3.append("\talways\n\tbegin\n");
boolean transientDoneFirst = false;
for (String p : dmvcVarPlaces.get(i)){
if (!transientNetPlaces.containsKey(p)){ // since p is w.r.t placeInfo & not w.r.t g
// buffer3.append("\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
// recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/
// buffer3.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + placeInfo.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n");
if (transientDoneFirst){
initBuffer.append("\t\tforever\n\t\tbegin\n");
transientDoneFirst = false;
}
if (g.getPostset("p" + placeInfo.get(p).getProperty("placeNum")).length != 0){
if (!vamsRandom){
//initBuffer.append("\t\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
initBuffer.append("\t\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax"))))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
}
else{
//initBuffer.append("\t\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(placeInfo.get(p).getProperty("dMin")))/delayScaleFactor)*Math.pow(10, 12)) + "," +(int)Math.ceil((Double.parseDouble(placeInfo.get(p).getProperty("dMax"))/delayScaleFactor)*Math.pow(10, 12)) + ");\n\t\t\t#del "); // converting seconds to ns using math.pow(10,9)
initBuffer.append("\t\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(placeInfo.get(p).getProperty("dMin")))/delayScaleFactor)) + "," +(int)Math.ceil((Double.parseDouble(placeInfo.get(p).getProperty("dMax"))/delayScaleFactor)) + ");\n\t\t\t#del "); // converting seconds to ns using math.pow(10,9)
}
initBuffer.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + placeInfo.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n");
}
else{
}
}
else{
transientDoneFirst = true;
if (!vamsRandom){
//initBuffer.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
initBuffer.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
}
else{
//initBuffer.append("\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))/delayScaleFactor)*Math.pow(10, 12)) + "," +(int)Math.ceil((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))/delayScaleFactor)*Math.pow(10, 12)) + ");\n\t\t#del "); // converting seconds to ns using math.pow(10,9)
initBuffer.append("\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))/delayScaleFactor)) + "," +(int)Math.ceil((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))/delayScaleFactor)) + ");\n\t\t#del "); // converting seconds to ns using math.pow(10,9)
}
initBuffer.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + transientNetPlaces.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n" );
// initBuffer.append("\tend\n");
}
}
// buffer3.append("\tend\n");
initBuffer.append("\t\tend\n\tend\n");
buffer4.append("\t\tV("+reqdVarsL.get(i).getName() + "drive) <+ transition("+reqdVarsL.get(i).getName() + "Val,delay,rtime,ftime);\n");
}
}
BufferedWriter topV = new BufferedWriter(new FileWriter(new File(directory + separator + "top.vams")));
topV.write("`timescale 1ps/1ps\n\nmodule top();\n\n");
if (count != 0){
vams.write(");\n");
vams.write("\tparameter delay = 0, rtime = 1p, ftime = 1p;\n");
if (vamsRandom){
vams.write("\tinteger del;\n\tinteger seed;\n");
}
vams.write(buffer+"\n"+buffer2+initBuffer+buffer3);
vams.write("\tanalog\n\tbegin\n"+buffer4+"\tend\nendmodule");
count = 0;
for (int i = 0; i < dmvcVarPlaces.size(); i++){
if (dmvcVarPlaces.get(i).size() != 0){
if (count == 0){
topV.write("\tdriver tb(\n\t\t." + reqdVarsL.get(i).getName() + "drive(" + reqdVarsL.get(i).getName() + ")");
count++;
}
else{
topV.write(",\n\t\t." + reqdVarsL.get(i).getName() + "drive(" + reqdVarsL.get(i).getName() + ")");
count++;
}
}
}
topV.write("\n\t);\n\n");
}
for (int i = 0; i < reqdVarsL.size(); i++){
v = reqdVarsL.get(i);
if ( i== 0){
topV.write("\t"+vamsFileName.split("\\.")[0]+" dut(\n\t\t."+ v.getName() + "(" + v.getName() + ")");
}
else{
topV.write(",\n\t\t." + v.getName() + "(" + reqdVarsL.get(i).getName() + ")");
count++;
}
}
topV.write("\n\t);\n\nendmodule");
topV.close();
vams.close();
}
catch(IOException e){
e.printStackTrace();
JOptionPane.showMessageDialog(BioSim.frame,
"Verilog-AMS model couldn't be created/written.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
catch(Exception e){
JOptionPane.showMessageDialog(BioSim.frame,
"Error in Verilog-AMS model generation.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
//T[] aux = (T[])a.clone();
*/
public LhpnFile mergeLhpns(LhpnFile l1,LhpnFile l2){//(LhpnFile l1, LhpnFile l2){
String place1 = "p([-\\d]+)", place2 = "P([-\\d]+)";
String transition1 = "t([-\\d]+)", transition2 = "T([-\\d]+)";
int placeNum, transitionNum;
int minPlace=0, maxPlace=0, minTransition = 0, maxTransition = 0;
Boolean first = true;
try{
for (String st1: l1.getPlaceList()){
if ((st1.matches(place1)) || (st1.matches(place2))){
st1 = st1.replaceAll("p", "");
st1 = st1.replaceAll("P", "");
placeNum = Integer.valueOf(st1);
if (placeNum > maxPlace){
maxPlace = placeNum;
if (first){
first = false;
minPlace = placeNum;
}
}
if (placeNum < minPlace){
minPlace = placeNum;
if (first){
first = false;
maxPlace = placeNum;
}
}
}
}
for (String st1: l2.getPlaceList()){
if ((st1.matches(place1)) || (st1.matches(place2))){
st1 = st1.replaceAll("p", "");
st1 = st1.replaceAll("P", "");
placeNum = Integer.valueOf(st1);
if (placeNum > maxPlace)
maxPlace = placeNum;
if (placeNum < minPlace)
minPlace = placeNum;
}
}
//System.out.println("min place and max place in both lpns are : " + minPlace + "," + maxPlace);
for (String st2: l2.getPlaceList()){
for (String st1: l1.getPlaceList()){
if (st1.equalsIgnoreCase(st2)){
maxPlace++;
l2.renamePlace(st2, "p" + maxPlace);//, l2.getPlace(st2).isMarked());
break;
}
}
}
first = true;
for (String st1: l1.getTransitionList()){
if ((st1.matches(transition1)) || (st1.matches(transition2))){
st1 = st1.replaceAll("t", "");
st1 = st1.replaceAll("T", "");
transitionNum = Integer.valueOf(st1);
if (transitionNum > maxTransition){
maxTransition = transitionNum;
if (first){
first = false;
minTransition = transitionNum;
}
}
if (transitionNum < minTransition){
minTransition = transitionNum;
if (first){
first = false;
maxTransition = transitionNum;
}
}
}
}
for (String st1: l2.getTransitionList()){
if ((st1.matches(transition1)) || (st1.matches(transition2))){
st1 = st1.replaceAll("t", "");
st1 = st1.replaceAll("T", "");
transitionNum = Integer.valueOf(st1);
if (transitionNum > maxTransition)
maxTransition = transitionNum;
if (transitionNum < minTransition)
minTransition = transitionNum;
}
}
//System.out.println("min transition and max transition in both lpns are : " + minTransition + "," + maxTransition);
for (String st2: l2.getTransitionList()){
for (String st1: l1.getTransitionList()){
if (st1.equalsIgnoreCase(st2)){
maxTransition++;
l2.renameTransition(st2, "t" + maxTransition);
break;
}
}
}
l2.save(directory + separator + "tmp.lpn");
l1.load(directory + separator + "tmp.lpn");
File tmp = new File(directory + separator + "tmp.lpn");
tmp.delete();
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Problem while merging lpns",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
return l1;
}
} |
// LB.java
package ed.net.lb;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.util.*;
import java.util.concurrent.*;
import java.text.*;
import org.apache.commons.cli.*;
import ed.io.*;
import ed.js.*;
import ed.log.*;
import ed.net.*;
import ed.cloud.*;
import ed.net.httpserver.*;
public class LB extends NIOClient {
static final long WAIT_FOR_POOL_TIMEOUT = 10000;
static final String LBIDENT = DNSUtil.getLocalHost().getHostName() + " : v0" ;
enum State { WAITING , IN_HEADER , READY_TO_STREAM , STREAMING , ERROR , DONE };
public LB( int port , MappingFactory mappingFactory , int verbose )
throws IOException {
super( "LB" , 15 , verbose );
_port = port;
_handler = new LBHandler();
_logger = Logger.getLogger( "LB" );
_logger.setLevel( Level.forDebugId( verbose ) );
_server = new HttpServer( port );
_server.addGlobalHandler( _handler ) ;
_router = new Router( mappingFactory );
_loadMonitor = new LoadMonitor( _router );
_addMonitors();
_httpLog = new AsyncAppender();
_httpLog.addAppender( new DailyFileAppender( new File( "logs/httplog/" ) , "lb" , new HttpLogEventFormatter() ) );
setDaemon( true );
}
public void start(){
_server.start();
super.start();
}
public void run(){
_logger.debug( "Started" );
super.run();
}
protected void shutdown(){
_logger.error( "SHUTDOWN starting" );
_server.stopServer();
super.shutdown();
Thread t = new Thread(){
public void run(){
try {
Thread.sleep( 1000 * 60 );
}
catch ( Exception e ){}
System.exit(0);
}
};
t.start();
}
protected void serverError( InetSocketAddress addr , ServerErrorType type , Exception why ){
// TODO: uh oh
_logger.debug( 1 , "serverError" , addr + ":" + type );
}
class RR extends Call {
RR( HttpRequest req , HttpResponse res ){
_request = req;
_response = res;
reset();
_lastCalls[_lastCallsPos] = this;
_lastCallsPos++;
if ( _lastCallsPos >= _lastCalls.length )
_lastCallsPos = 0;
}
void reset(){
_response.clearHeaders();
_response.setHeader( "X-lb" , LBIDENT );
_state = State.WAITING;
_line = null;
}
void success(){
done();
_router.success( _request , _response , _lastWent );
_loadMonitor.hit( _request , _response );
}
public void done(){
super.done();
log( this );
}
protected InetSocketAddress where(){
_lastWent = _router.chooseAddress( _request , _request.elapsed() > WAIT_FOR_POOL_TIMEOUT );
return _lastWent;
}
protected InetSocketAddress lastWent(){
return _lastWent;
}
protected void error( ServerErrorType type , Exception e ){
_logger.debug( 1 , "backend error" , e );
_loadMonitor._all.networkEvent();
_router.error( _request , _response , _lastWent , type , e );
if ( type != ServerErrorType.WEIRD &&
( _state == State.WAITING || _state == State.IN_HEADER ) &&
++_numFails <= 3 ){
reset();
_logger.debug( 1 , "retrying" );
add( this );
return;
}
try {
_response.setResponseCode( 500 );
_response.getJxpWriter().print( "backend error : " + e + "\n\n" );
_response.done();
_state = State.ERROR;
done();
_loadMonitor.hit( _request , _response );
}
catch ( IOException ioe2 ){
ioe2.printStackTrace();
}
}
void backendError( ServerErrorType type , String msg ){
backendError( type , new IOException( msg ) );
}
void backendError( ServerErrorType type , IOException ioe ){
_logger.debug( 1 , "backend error" , ioe );
error( type , ioe );
}
protected WhatToDo handleRead( ByteBuffer buf , Connection conn ){
if ( _state == State.WAITING || _state == State.IN_HEADER ){
// TODO: should i read this all in at once
if ( _line == null )
_line = new StringBuilder();
while ( buf.hasRemaining() ){
char c = (char)buf.get();
if ( c == '\r' )
continue;
if ( c == '\n' ){
if ( _line.length() == 0 ){
_logger.debug( 3 , "end of header" );
_state = State.READY_TO_STREAM;
break;
}
String line = _line.toString();
if ( _state == State.WAITING ){
int idx = line.indexOf( " " );
if ( idx < 0 ){
backendError( ServerErrorType.INVALID , "invalid first line [" + line + "]" );
return WhatToDo.ERROR;
}
line = line.substring( idx + 1 ).trim();
idx = line.indexOf( " " );
if ( idx < 0 )
_response.setResponseCode( Integer.parseInt( line ) );
else
_response.setStatus( Integer.parseInt( line.substring( 0 , idx ) ) , line.substring( idx + 1 ).trim() );
_logger.debug( 3 , "got first line " , line );
_state = State.IN_HEADER;
}
else {
int idx = line.indexOf( ":" );
if ( idx < 0 ){
backendError( ServerErrorType.INVALID , "invalid line [ " + line + "]" );
return WhatToDo.ERROR;
}
String name = line.substring( 0 , idx );
String value = line.substring( idx + 1 ).trim();
_logger.debug( 3 , "got header line " , line );
if ( name.equalsIgnoreCase( "Connection" ) ){
_keepalive = ! value.toLowerCase().contains( "close" );
}
else {
_response.addHeader( name , value );
}
}
_line.setLength( 0 );
continue;
}
_line.append( c );
}
if ( _state != State.READY_TO_STREAM )
return WhatToDo.CONTINUE;
_logger.debug( 3 , "starting to stream data" );
}
if ( _state == State.READY_TO_STREAM ){
MyChunk chunk = new MyChunk( this , conn , _response.getContentLength() , buf );
_response.sendFile( new MySender( chunk ) );
_state = State.STREAMING;
}
try {
_response.done();
}
catch ( IOException ioe ){
_logger.debug( 2 , "client error" , ioe );
return WhatToDo.ERROR;
}
return WhatToDo.PAUSE;
}
protected ByteStream fillInRequest( ByteBuffer buf ){
buf.put( generateRequestHeader().getBytes() );
if ( _request.getPostData() != null )
return _request.getPostData().getByteStream();
return null;
}
String generateRequestHeader(){
StringBuilder buf = new StringBuilder( _request.getRawHeader().length() + 200 );
buf.append( _request.getMethod().toUpperCase() ).append( " " ).append( _request.getURL() ).append( " HTTP/1.0\r\n" );
buf.append( "Connection: keep-alive\r\n" );
buf.append( HttpRequest.REAL_IP_HEADER ).append( ": " ).append( _request.getRemoteIP() ).append( "\r\n" );
for ( String n : _request.getHeaderNameKeySet() ){
if ( n.equalsIgnoreCase( "Connection" ) ||
n.equalsIgnoreCase( HttpRequest.REAL_IP_HEADER ) )
continue;
String v = _request.getHeader( n );
buf.append( n ).append( ": " ).append( v ).append( "\r\n" );
}
buf.append( "\r\n" );
_logger.debug( 3 , "request\n" , buf );
return buf.toString();
}
public String toString(){
return _request.getFullURL();
}
final HttpRequest _request;
final HttpResponse _response;
int _numFails = 0;
private InetSocketAddress _lastWent;
private boolean _keepalive;
private State _state;
private StringBuilder _line;
}
class MySender extends JSFile.Sender {
MySender( MyChunk chunk ){
super( chunk , chunk._length );
}
}
class MyChunk extends JSFileChunk {
MyChunk( RR rr , Connection conn , long length , ByteBuffer buf ){
_rr = rr;
_conn = conn;
_length = length;
_buf = buf;
_data = new MyBinaryData( _buf );
_sent += _data.length();
}
public JSBinaryData getData(){
return _data;
}
public MyChunk getNext(){
_logger.debug( 4, "want next chunk of data" );
if ( _sent == _length ){
_logger.debug( 4 , "no more data" );
_conn.done( ! _rr._keepalive );
_rr._state = State.DONE;
_rr.success();
return null;
}
_conn.doRead( _length > 0 );
_sent += _data.length();
_last = _data.length();
_logger.debug( _last == 0 ? 4 : 3 , "sent " + _sent + "/" + _length );
return this;
}
long _sent = 0;
long _last = -1;
final RR _rr;
final Connection _conn;
final long _length;
final ByteBuffer _buf;
final MyBinaryData _data;
}
class MyBinaryData extends JSBinaryData {
MyBinaryData( ByteBuffer buf ){
_buf = buf;
}
public int length(){
return _buf.remaining();
}
public void put( ByteBuffer buf ){
throw new RuntimeException( "not allowed" );
}
public void write( OutputStream out ){
throw new RuntimeException( "not allowed" );
}
public ByteBuffer asByteBuffer(){
return _buf;
}
final ByteBuffer _buf;
}
class LBHandler implements HttpHandler {
public boolean handles( HttpRequest request , Info info ){
info.admin = false;
info.fork = false;
info.doneAfterHandles = false;
return true;
}
public void handle( HttpRequest request , HttpResponse response ){
if ( add( new RR( request , response ) ) )
return;
JxpWriter out = response.getJxpWriter();
out.print( "new request queue full (lb 1)" );
try {
response.done();
}
catch ( IOException ioe ){
ioe.printStackTrace();
}
}
public double priority(){
return Double.MAX_VALUE;
}
}
void log( RR rr ){
_httpLog.append( new HttpEvent( rr ) );
}
void _addMonitors(){
HttpServer.addGlobalHandler( new WebViews.LBOverview( this ) );
HttpServer.addGlobalHandler( new WebViews.LBLast( this ) );
HttpServer.addGlobalHandler( new WebViews.LoadMonitorWebView( this._loadMonitor ) );
HttpServer.addGlobalHandler( new WebViews.RouterPools( this._router ) );
HttpServer.addGlobalHandler( new WebViews.RouterServers( this._router ) );
HttpServer.addGlobalHandler( new HttpHandler(){
public boolean handles( HttpRequest request , Info info ){
if ( ! "/~kill".equals( request.getURI() ) )
return false;
if ( ! "127.0.0.1".equals( request.getPhysicalRemoteAddr() ) )
return false;
info.fork = false;
info.admin = true;
return true;
}
public void handle( HttpRequest request , HttpResponse response ){
JxpWriter out = response.getJxpWriter();
if ( isShutDown() ){
out.print( "alredy shutdown" );
return;
}
LB.this.shutdown();
out.print( "done" );
}
public double priority(){
return Double.MIN_VALUE;
}
}
);
}
class HttpLogEventFormatter implements EventFormatter {
public synchronized String format( Event old ){
HttpEvent e = (HttpEvent)old;
RR rr = e._rr;
_buf.append( "[" ).append( e.getDate().format( _format ) ).append( "] " );
_buf.append( rr._request.getRemoteIP() );
_buf.append( " retry:" ).append( rr._numFails );
_buf.append( " went:" ).append( rr._lastWent );
_buf.append( " " ).append( rr._response.getResponseCode() );
_buf.append( " " ).append( rr._request.getMethod() );
_buf.append( " \"" ).append( rr._request.getFullURL() ).append( "\"" );
_buf.append( " " ).append( rr._response.handleTime() );
_buf.append( " \"" ).append( rr._request.getHeader( "User-Agent" ) ).append( "\"" );
_buf.append( " \"" ).append( rr._request.getHeader( "Referer" ) ).append( "\"" );
_buf.append( " \"" ).append( rr._request.getHeader( "Cookie" ) ).append( "\"" );
_buf.append( "\n" );
String s = _buf.toString();
if ( _buf.length() > _bufSize )
_buf = new StringBuilder( _bufSize );
else
_buf.setLength( 0 );
return s;
}
final int _bufSize = 1024;
StringBuilder _buf = new StringBuilder( _bufSize );
final SimpleDateFormat _format = new SimpleDateFormat( "MM/dd/yyyy hh:mm:ss.SSS z" );
}
class HttpEvent extends Event {
HttpEvent( RR rr ){
super( null , rr._request.getStart() , null , null , null , null );
_rr = rr;
}
final RR _rr;
}
final int _port;
final LBHandler _handler;
final HttpServer _server;
final Router _router;
final LoadMonitor _loadMonitor;
final Logger _logger;
final AsyncAppender _httpLog;
final RR[] _lastCalls = new RR[1000];
int _lastCallsPos = 0;
public static void main( String args[] )
throws Exception {
int verbose = 0;
for ( int i=0; i<args.length; i++ ){
if ( args[i].matches( "\\-v+" ) ){
verbose = args[i].length() - 1;
args[i] = "";
}
}
Options o = new Options();
o.addOption( "p" , "port" , true , "Port to Listen On" );
o.addOption( "v" , "verbose" , false , "Verbose" );
o.addOption( "mapfile" , "m" , true , "file from which to load mappings" );
CommandLine cl = ( new BasicParser() ).parse( o , args );
final int port = Integer.parseInt( cl.getOptionValue( "p" , "8080" ) );
MappingFactory mf = null;
if ( cl.hasOption( "m" ) )
mf = new TextMapping.Factory( cl.getOptionValue( "m" , null ) );
else
mf = new GridMapping.Factory();
System.out.println( "10gen load balancer" );
System.out.println( "\t port \t " + port );
System.out.println( "\t verbose \t " + verbose );
int retriesLeft = 2;
LB lb = null;
while ( retriesLeft
try {
lb = new LB( port , mf , verbose );
break;
}
catch ( BindException be ){
be.printStackTrace();
System.out.println( "can't bind to port. going to try to kill old one" );
HttpDownload.downloadToJS( new URL( "http://127.0.0.1:" + port + "/~kill" ) );
Thread.sleep( 100 );
}
}
if ( lb == null ){
System.err.println( "couldn't ever bind" );
System.exit(-1);
return;
}
lb.start();
lb.join();
System.exit(0);
}
} |
package ops;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
public class OPS
{
private List<MemoryElement> _wm = new ArrayList<MemoryElement>();
private List<Rule> _rules = new ArrayList<Rule>();
private List<PreparedRule> _preparedRules = new ArrayList<PreparedRule>();
private Map<String, MemoryElement> _templates = new HashMap<String, MemoryElement>();
private ConcurrentLinkedQueue<MemoryElement> _memoryInQueue = new ConcurrentLinkedQueue<MemoryElement>();
private boolean _debug = true;
private boolean _halt = false;
private boolean _waitForWork = false;
public void reset()
{
_halt = false;
_rules.clear();
_templates.clear();
_wm.clear();
}
public void waitForWork(boolean wait)
{
_waitForWork = wait;
}
public void halt()
{
_halt = true;
}
public void literalize(MemoryElement template)
{
_templates.put(template.Type, template);
}
public void insert(MemoryElement element)
{
_wm.add(element);
}
public void remove(MemoryElement element)
{
_wm.remove(element);
}
public MemoryElement make(MemoryElement element)
{
MemoryElement newElement = null;
try
{
if (!_templates.containsKey(element.Type))
{
throw new IllegalArgumentException(String.format("memory element type %s not literalized", element.Type));
}
newElement = _templates.get(element.Type).make(element.Values);
_memoryInQueue.add(newElement);
// notify();
return newElement;
}
catch (Exception e)
{
e.printStackTrace();
}
return newElement;
}
public void drainInMemoryQueue()
{
while(!_memoryInQueue.isEmpty())
{
_wm.add(_memoryInQueue.remove());
}
}
public void run()
{
run(Integer.MAX_VALUE);
}
public void run(int steps)
{
_halt = false;
while (steps-- > 0 && !_halt)
{
drainInMemoryQueue();
Match match = match();
if (match == null)
{
if (!_memoryInQueue.isEmpty())
{
continue;
}
break;
/*
if (!_waitForWork) break;
try
{
wait();
continue;
} catch (InterruptedException e)
{
break;
}
*/
}
CommandContext context = new CommandContext(this, match.Elements, match.Vars);
for (ProductionSpec production : match.Rule.Productions)
{
Object[] args = new Object[production.Params.length];
for (int i = 0; i < args.length; i++)
{
args[i] = context.resolveValue(production.Params[i]);
}
try
{
production.Command.exec(context, args);
}
catch (Exception e)
{
System.err.println(production.toString());
e.printStackTrace();
}
}
// if (_debug) dumpWorkingMemory();
}
_halt = true;
}
private void dumpWorkingMemory()
{
for (MemoryElement me : _wm)
{
System.out.println(me.toString());
}
}
public void addRules(List<Rule> rules)
{
_rules.addAll(rules);
prepareQueries();
}
public void addRule(Rule rule)
{
_rules.add(rule);
prepareQueries();
}
private void prepareQueries()
{
_preparedRules.clear();
for (Rule rule : _rules)
{
PreparedRule preparedRule = new PreparedRule();
preparedRule.Rule = rule;
preparedRule.Specificity = computeSpecificity(rule);
_preparedRules.add(preparedRule);
}
Collections.sort(_preparedRules, new Comparator<PreparedRule>()
{
@Override
public int compare(PreparedRule preparedRule, PreparedRule preparedRule1)
{
return preparedRule1.Specificity.compareTo(preparedRule.Specificity);
}
});
_rules.clear();
for (PreparedRule preparedRule : _preparedRules)
{
_rules.add(preparedRule.Rule);
}
}
private Integer computeSpecificity(Rule rule)
{
Integer specificity = 0;
for (QueryElement element : rule.Query)
{
Integer elementSpecificity = 0;
for (QueryPair queryPair : element.QueryPairs)
{
if (!(queryPair.Value instanceof String)) continue;
String strVal = (String) queryPair.Value;
if (!strVal.startsWith("$")) continue;
elementSpecificity++;
}
specificity += elementSpecificity;
}
return specificity;
}
private class PreparedRule
{
Rule Rule;
Integer Specificity;
}
private Match match()
{
Match match = null;
for (Rule rule : _rules)
{
List<MemoryElement> elements = new ArrayList<MemoryElement>();
Map<String, Object> vars = new HashMap<String, Object>();
for (QueryElement qe : rule.Query)
{
boolean haveMatch = false;
for (MemoryElement me : _wm)
{
if (elements.contains(me)) continue;
Map<String, Object> tmpVars = new HashMap<String, Object>(vars);
haveMatch = compare(qe, me, tmpVars);
if (haveMatch)
{
vars = tmpVars;
elements.add(me);
break;
}
}
if (!haveMatch)
{
break;
}
}
if (elements.size() == rule.Query.size())
{
match = new Match(rule, elements, vars);
break;
}
}
return match;
}
private boolean compare(QueryElement qe, MemoryElement me, Map<String, Object> vars)
{
if (!(me.Type.equals(qe.Type))) return false;
for (QueryPair qp : qe.QueryPairs)
{
Object val = me.Values.containsKey(qp.Key) ? me.Values.get(qp.Key) : null;
if (qp.Value == null)
{
if (val == null)
{
// match
}
else
{
return false;
}
}
else
{
if (qp.Value instanceof String)
{
String strQpVal = (String)qp.Value;
if (strQpVal.startsWith("$"))
{
if (vars.containsKey(strQpVal))
{
if (!vars.get(strQpVal).equals(val))
{
return false;
}
}
else
{
// variable matches everything
vars.put(strQpVal, val);
}
}
else
{
if (!strQpVal.equals(val))
{
return false;
}
}
}
else
{
if (!qp.Value.equals(val))
{
return false;
}
}
}
}
return true;
}
private class Match
{
public Rule Rule;
public List<MemoryElement> Elements;
public Map<String, Object> Vars;
public Match(Rule rule, List<MemoryElement> elements, Map<String, Object> vars)
{
Rule = rule;
Elements = elements;
Vars = vars;
}
}
} |
/**
* Contains Linear Prediction Coefficent functions.
*
* Created: Wed Dec 25 11:06:02 2002
*
* @author <a href="mailto:rsingh@cs.cmu.edu">rsingh</a>
* @version 1.0
*/
package edu.cmu.sphinx.frontend.plp;
/**
* TODO: Describe this LinearPredictor.
*/
public class LinearPredictor {
private int order;
private int cepstrumOrder;
private double[] reflectionCoeffs;
private double[] ARParameters;
private double alpha;
private double[] cepstra;
private double[] bilinearCepstra;
/**
* Constructs a LinearPredictor with the given order.
*
* @param order the order of the LinearPredictor
*/
public LinearPredictor(int order){
this.order = order;
// Set the rest to null values
reflectionCoeffs = null;
ARParameters = null;
alpha = 0;
cepstra = null;
bilinearCepstra = null;
}
/**
* Routine to compute Linear Prediction Coefficients for a frame of speech.
* Returns the energy of the frame (alpha in the Levinson recursion)
* Assumes the following sign convention:<br>
* prediction(x[t]) = Sum_i {Ar[i] * x[t-i]}
*/
public double[] getARFilter(double[] autocor){
if (autocor[0] == 0) return null; /* No signal */
reflectionCoeffs = new double[order+1];
ARParameters = new double[order+1];
double[] backwardPredictor = new double[order+1];
alpha = autocor[0];
reflectionCoeffs[1] = -autocor[1]/autocor[0];
ARParameters[0] = 1.0;
ARParameters[1] = reflectionCoeffs[1];
alpha *= (1 - reflectionCoeffs[1]*reflectionCoeffs[1]);
for (int i=2; i<=order; i++){
for (int j=1; j<i; j++){
backwardPredictor[j] = ARParameters[i-j];
}
reflectionCoeffs[i] = 0;
for (int j=0; j<i; j++){
reflectionCoeffs[i] -= ARParameters[j]*autocor[i-j];
}
reflectionCoeffs[i] /= alpha;
for (int j=1; j<i; j++){
ARParameters[j] += reflectionCoeffs[i]*backwardPredictor[j];
}
ARParameters[i] = reflectionCoeffs[i];
alpha *= (1 - reflectionCoeffs[i]*reflectionCoeffs[i]);
if (alpha <= 0.0){
return null;
}
}
return ARParameters;
}
/**
* Computes AR parameters from a given set of reflection coefficients.
*
* @param RC double array of reflection coefficients. The RC array
* must begin at 1 (RC[0] is a dummy value)
* @param lpcorder AR order desired
*/
public double[] reflectionCoeffsToARParameters(double[] RC, int lpcorder) {
double[][] tmp = new double[lpcorder+1][lpcorder+1];
order = lpcorder;
int RCorder = RC.length;
reflectionCoeffs = new double[RCorder];
for (int i=0; i<RCorder; i++)
reflectionCoeffs[i] = RC[i];
for (int i=1; i<=lpcorder; i++) {
for (int m=1; m<i; m++) {
tmp[i][m] = tmp[i-1][m] - RC[i]*tmp[i-1][i-m];
}
tmp [i][i] = RC[i];
}
ARParameters[0] = 1;
for (int m=1; m<=lpcorder; m++) {
ARParameters[m] = tmp[m][m];
}
return ARParameters;
}
/**
* Computes LPC Cepstra from the AR predictor parameters and alpha
* using a recursion invented by Oppenheim et al.
*
* @param ceporder is the order of the LPC cepstral vector to be
* computed. The literature shows the optimal value of
* order to be .75*LPCorder <= ceporder <= 1.25*LPCorder
*/
public double[] getCepstrum(int ceporder) {
int i;
double sum;
if (ceporder <= 0) {
return null;
}
cepstrumOrder = ceporder;
cepstra = new double[cepstrumOrder];
cepstra[0] = Math.log(alpha);
if (cepstrumOrder == 1) return cepstra;
cepstra[1] = -ARParameters[1];
for (i=2; i<Math.min(cepstrumOrder,order+1); i++){
sum = (double)i * ARParameters[i];
for (int j=1; j<i; j++){
sum += ARParameters[j] * cepstra[i-j]* (double)(i-j);
}
cepstra[i] = -sum/(double) i;
}
for (; i<cepstrumOrder ; i++){ // Only if cepstrumOrder > order+1
sum = 0;
for (int j=1; j<=order; j++){
sum += ARParameters[j]*cepstra[i-j]*(double)(i-j);
}
cepstra[i] = -sum/(double)i;
}
return cepstra;
}
/**
* Computes a bi-linear frequency warped version of the LPC cepstrum
* from the LPC cepstrum.
* The recursive alogrithm used is defined in Oppenheim's paper in
* Proceedings of IEEE, June 1972
* The program has been written using g[x,y] = g_o[x,-y] where g_o
* is the array used by Oppenheim. To handle the reversed array
* index the recursion has been done DOWN the array index.
*
* @param warp is the warping coefficient. For 16KHz speech 0.6 is
* good valued.
* @param nbilincepstra is the number of bilinear cepstral values to
* be computed from the linear frequency cepstrum.
*/
public double[] getBilinearCepstra(double warp, int nbilincepstra){
double[][] g = new double[nbilincepstra][cepstrumOrder];
// Make a local copy as this gets destroyed
double[] lincep = new double[cepstrumOrder];
for (int i=0; i<cepstrumOrder; i++) lincep[i] = cepstra[i];
bilinearCepstra[0] = lincep[0];
lincep[0] = 0;
g[0][cepstrumOrder-1] = lincep[cepstrumOrder-1];
for (int i=1; i<nbilincepstra; i++) g[i][cepstrumOrder-1] = 0;
for (int i=cepstrumOrder-2; i>=0; i
g[0][i] = warp*g[0][i+1] + lincep[i];
g[1][i] = (1-warp*warp)*g[0][i+1] + warp*g[1][i+1];
for (int j=2; j<nbilincepstra; j++){
g[j][i] = warp*(g[j][i+1] - g[j-1][i]) + g[j-1][i+1];
}
}
for (int i=1; i<=nbilincepstra; i++){
bilinearCepstra[i] = g[i][0];
}
return bilinearCepstra;
}
} |
package etomica.space3d;
import etomica.exception.MethodNotImplementedException;
import etomica.lattice.IndexIteratorSequential;
import etomica.math.geometry.Plane;
import etomica.math.geometry.Polygon;
import etomica.math.geometry.Polyhedron;
import etomica.math.geometry.TruncatedOctahedron;
import etomica.simulation.Simulation;
import etomica.space.Boundary;
import etomica.space.BoundaryPeriodic;
import etomica.space.IVector;
import etomica.space.Space;
/**
* This class enables creation of a periodic truncated-octahedron boundary.
* Truncated octahedrons are spacefillers; unlike spheres, about which voids
* form when placed in an array, truncated octahedrons can be flush with other
* truncated octahedrons at every face when grouped in an array. Moreover,
* truncated octahedrons are considerably more sphere-like than cubes, and using
* a truncated octahedron as a boundary greatly increases the isotropy of the
* system.
* <p>
* There are no subclasses for periodic and nonperiodic boundary conditions for
* this class because nonperiodic boundary conditions are not applicable for
* truncated octahedrons.
*/
public class BoundaryTruncatedOctahedron extends Boundary implements
BoundaryPeriodic {
public BoundaryTruncatedOctahedron(Simulation sim) {
this(sim.getSpace(), sim.getDefaults().boxSize);
}
public BoundaryTruncatedOctahedron(Space space, double boxSize) {
super(space, new TruncatedOctahedron(space));
isPeriodic = new boolean[space.D()];
for (int i = 0; i < space.D(); i++)
isPeriodic[i] = true;
dimensions = space.makeVector();
dimensions.E(boxSize);
rrounded = space.makeVector();
intoTruncatedOctahedron = space.makeVector();
intoContainingCube = space.makeVector();
dimensionsCopy = space.makeVector();
dimensionsHalf = space.makeVector();
dimensionsHalfCopy = space.makeVector();
indexIterator = new IndexIteratorSequential(space.D());
needShift = new boolean[space.D()];//used by getOverflowShifts
updateDimensions();
}
public boolean[] getPeriodicity() {
return isPeriodic;
}
public final IVector getDimensions() {
return dimensionsCopy;
}
public IVector randomPosition() {
throw new MethodNotImplementedException();
//temp.setRandom(dimensions);
//return temp;
}
private final void updateDimensions() {
dimensionsHalf.Ea1Tv1(0.5, dimensions);
dimensionsCopy.E(dimensions);
((TruncatedOctahedron) shape).setContainingCubeEdgeLength(dimensions
.x(0));
}
public void setDimensions(IVector v) {
dimensions.E(v);
updateDimensions();
}
public double[][] imageOrigins(int nShells) {
if(nShells == 0) {
return new double[0][];
} else if(nShells == 1) {
Polygon[] faces = ((Polyhedron)shape).getFaces();
double[][] origins = new double[faces.length][];
double multiplier = ((TruncatedOctahedron)shape).getContainingCubeEdgeLength();
for(int i=0; i<faces.length; i++) {
IVector[] vertices = faces[i].getVertices();
plane.setThreePoints((Vector3D)vertices[0], (Vector3D)vertices[1], (Vector3D)vertices[2]);
plane.getNormalVector(normal);
normal.TE(multiplier);
origins[i] = normal.toArray();
}
return origins;
}
//algorithm for nShells > 1 misses many of the images (those through the hexagon faces)
IVector workVector = space.makeVector();
int shellFormula = (2 * nShells) + 1;
int nImages = space.powerD(shellFormula) - 1;
double[][] origins = new double[nImages][space.D()];
indexIterator.setSize(shellFormula);
indexIterator.reset();
int k = 0;
while (indexIterator.hasNext()) {
int[] index = indexIterator.next();
workVector.E(index);
workVector.PE(-(double) nShells);
if (workVector.isZero())
continue;
workVector.TE(dimensions);
workVector.assignTo(origins[k++]);
}
return origins;
}
public float[][] getOverflowShifts(IVector rr, double distance) {
int D = space.D();
int numVectors = 1;
for (int i = 1; i < D; i++) {
if ((rr.x(i) - distance < 0.0)
|| (rr.x(i) + distance > dimensions.x(i))) {
//each previous vector will need an additional copy in this
// dimension
numVectors *= 2;
//remember that
needShift[i] = true;
} else {
needShift[i] = false;
}
}
if (numVectors == 1)
return shift0;
float[][] shifts = new float[numVectors][D];
double[] rrArray = rr.toArray();
for (int i = 0; i < D; i++) {
shifts[0][i] = (float) rrArray[i];
}
int iVector = 1;
for (int i = 0; iVector < numVectors; i++) {
if (!needShift[i]) {
//no shift needed for this dimension
continue;
}
double delta = -dimensions.x(i);
if (rr.x(i) - distance < 0.0) {
delta = -delta;
}
//copy all previous vectors and apply a shift of delta to the
// copies
for (int jVector = 0; jVector < iVector; jVector++) {
for (int j = 0; j < D; j++) {
shifts[jVector + iVector][j] = shifts[jVector][j];
}
shifts[jVector + iVector][i] += delta;
}
iVector *= 2;
}
return shifts;
}
public void nearestImage(IVector dr) {
dr.PEa1Tv1(0.5, dimensions);
dr.PE(centralImage(dr));
dr.PEa1Tv1(-0.5, dimensions);
// double n =
// ((TruncatedOctahedron)shape).getContainingCubeEdgeLength();
// intoContainingCube.EModShift(dr, dimensions);
// rrounded.Ev1Pv2(dr,intoContainingCube);
// rrounded.TE(1./n);
// int aint =
// (int)(4.0/3.0*(Math.abs(rrounded.x(0))+Math.abs(rrounded.x(1))+Math.abs(rrounded.x(2))));
// double corr = 0.5 * n * aint;
// if(corr != 0.0) {
// if(rrounded.x(0) > 0) intoTruncatedOctahedron.setX(0,
// intoContainingCube.x(0) - corr);
// else intoTruncatedOctahedron.setX(0, intoContainingCube.x(0) + corr);
// if(rrounded.x(1) > 0) intoTruncatedOctahedron.setX(1,
// intoContainingCube.x(1) - corr);
// else intoTruncatedOctahedron.setX(1, intoContainingCube.x(1) + corr);
// if(rrounded.x(2) > 0) intoTruncatedOctahedron.setX(2,
// intoContainingCube.x(2) - corr);
// else intoTruncatedOctahedron.setX(2, intoContainingCube.x(2) + corr);
// } else {
// intoTruncatedOctahedron.E(intoContainingCube);
// dr.PE(intoTruncatedOctahedron);
}
public IVector centralImage(IVector r) {
double n = ((TruncatedOctahedron) shape).getContainingCubeEdgeLength();
intoContainingCube.EModShift(r, dimensions);
rrounded.Ev1Pv2(r, intoContainingCube);
rrounded.TE(1. / n);
int aint = (int) (4.0 / 3.0 * (Math.abs(rrounded.x(0))
+ Math.abs(rrounded.x(1)) + Math.abs(rrounded.x(2))));
double corr = 0.5 * n * aint;
intoTruncatedOctahedron.E(intoContainingCube);
if (corr != 0.0) {
intoTruncatedOctahedron.PEa1SGNv1(-corr, rrounded);
}
return intoTruncatedOctahedron;
}
public IVector getBoundingBox() {
return dimensionsCopy;
}
public IVector getCenter() {
return dimensionsHalfCopy;
}
private static final long serialVersionUID = 1L;
protected final IVector intoTruncatedOctahedron;
protected final IVector rrounded;
protected final IVector intoContainingCube;
protected final IVector dimensions;
protected final IVector dimensionsCopy;
protected final IVector dimensionsHalf;
protected final IVector dimensionsHalfCopy;
private final IndexIteratorSequential indexIterator;
private final boolean[] needShift;
protected final boolean[] isPeriodic;
protected final float[][] shift0 = new float[0][0];
protected float[][] shift;
private final Plane plane = new Plane();
private final Vector3D normal = new Vector3D();
} |
package models;
import java.util.List;
import views.formdata.ContactFormData;
/**
* A simple in-memory repository for Contacts.
* @author Alvin Wang
*
*/
public class ContactDB {
/**
* Add a contact to the contact list.
* @param user User.
* @param formData Contact data.
*/
public static void addContact(String user, ContactFormData formData) {
boolean isNewContact = (formData.id == -1);
if (isNewContact) {
Contact contact = new Contact(formData.firstName, formData.lastName, formData.telephone, formData.telephoneType);
UserInfo userInfo = UserInfo.find().where().eq("email", user).findUnique();
if (userInfo == null) {
throw new RuntimeException("Could not find user: " + user);
}
userInfo.addContact(contact);
contact.setUserInfo(userInfo);
contact.save();
userInfo.save();
}
else {
Contact contact = Contact.find().byId(formData.id);
contact.setFirstName(formData.firstName);
contact.setLastName(formData.lastName);
contact.setTelephone(formData.telephone);
contact.setTelephoneType(formData.telephoneType);
contact.save();
}
}
/**
* Returns a list of contacts.
* @param user User.
* @return list of contacts.
*/
public static List<Contact> getContacts(String user) {
UserInfo userInfo = UserInfo.find().where().eq("email", user).findUnique();
if (userInfo == null) {
return null;
}
else {
return userInfo.getContacts();
}
}
/**
* Returns true if the user is defined in the DB.
* @param user User.
* @return True if user is defined.
*/
public static boolean isUser(String user) {
return (UserInfo.find().where().eq("email", user).findUnique() != null);
}
/**
* Returns a contact associated with the passed id.
* @param user User.
* @param id the ID.
* @return THe retrieved contact.
*/
public static Contact getContact(String user, long id) {
Contact contact = Contact.find().byId(id);
if (contact == null) {
throw new RuntimeException("Contact ID not found: " + id);
}
UserInfo userInfo = contact.getUserInfo();
if (!user.equals(userInfo.getEmail())) {
throw new RuntimeException("User is not same one store with the contect.");
}
return contact;
}
/**
* Deletes a contact with the passed in User and ID.
* @param user User.
* @param id The ID.
*/
public static void deleteContact(String user, long id) {
Contact contact = Contact.find().byId(id);
UserInfo userInfo = UserInfo.find().where().eq("email", user).findUnique();
userInfo.getContacts().remove(contact);
userInfo.save();
contact.setUserInfo(null);
contact.delete();
}
} |
package models;
import java.util.List;
/**
* A repository that stores update information.
* @author Rob Namahoe
*
*/
public class UpdatesDB {
/**
* Add an update log.
* @param surferUpdate Update information.
*/
public static void addUpdate(Updates surferUpdate) {
surferUpdate.save();
}
/**
* Retrieves a List of updates.
* @return list of updates.
*/
public static List<Updates> getUpdates() {
return Updates.find().all();
}
} |
package org.eigenbase.util;
import java.util.HashMap;
/**
* Implements a double key hash table.
* Use this class when you have two keys mapping to a value. For example.
* <blockquote><pre><code>
* DoubleKeyMap areaCodeMap = new DoubleKeyMap();
* areaCodeMap.put("San Francisco", "CA", "415");
* areaCodeMap.put("Berkeley", "CA", "510");
* areaCodeMap.put("Berkeley", "MO", "315"); //Yes this city really exists
* ...
* Object obj = areaCodeMap.get("San Francisco", "CA");
* System.out.println(obj); //outputs "415"
* </code></pre></blockquote>
* @author Wael Chatila
* @since Jul 27, 2004
* @version $Id$
*/
public class DoubleKeyMap
{
private HashMap root;
private boolean enforceUniquness;
public DoubleKeyMap()
{
root = new HashMap();
enforceUniquness = false;
}
/**
* Set to true if you want to ennforces the inserting of one key pair once
*/
public void setEnforceUniqueness(boolean enforce)
{
enforceUniquness = enforce;
}
/**
* Inserts a value into the hashmap with keys key0 and key1
* <blockquote><pre><code>
* DoubleKeyMap areaCodeMap = new DoubleKeyMap();
* </code></pre></blockquote>
* @pre null != key0
* @pre null != key1
* @throws RuntimeException if key pair is already defined when
* {@link #enforceUniquness} is set to true
*/
public void put(
Object key0,
Object key1,
Object value)
{
Util.pre(null != key0, "null != key0");
Util.pre(null != key1, "null != key1");
HashMap key0Hash = (HashMap) root.get(key0);
if (null == key0Hash) {
key0Hash = new HashMap();
root.put(key0, key0Hash);
}
if (enforceUniquness && key0Hash.containsKey(key1)) {
throw new RuntimeException("The key-pair <" + key0.toString()
+ ", " + key1.toString() + "> is already defined");
}
key0Hash.put(key1, value);
}
/**
* Convenience method to define a set of key pairs at once. All pairs will
* be created with the same value. For Example
* <blockquote><pre><code>
* Object[] 408SantaClaraCountyCities = new Object[]{"San Jose", "Sunnyvale",...};
* DoubleKeyMap areaCodeMap = new DoubleKeyMap();
* areaCodeMap.put(408SantaClaraCountyCitites, "CA", "408");
* </code></pre></blockquote>
* is equivalent to
* <blockquote><pre><code>
* DoubleKeyMap areaCodeMap = new DoubleKeyMap();
* areaCodeMap.put("San Jose", "CA", "408");
* areaCodeMap.put("Sunnyvale", "CA", "408");
* ...
* </code></pre></blockquote>
* @pre null != key0s
* @pre null != key1
* @pre null != keys0[i] for all 0<= i <= keys0.length
* @throws RuntimeException if key pairs are already defined when
* {@link #enforceUniquness} is set to true
*/
public void put(
Object [] keys0,
Object key1,
Object value)
{
Util.pre(null != keys0, "null != keys0");
for (int i = 0; i < keys0.length; i++) {
Object key0 = keys0[i];
put(key0, key1, value);
}
}
/**
* Convenience method to define a set of key pairs at once. All pairs will
* be created with the same value.
* @see {@link #put(java.lang.Object[], java.lang.Object, java.lang.Object)}
*
* @pre null != key0
* @pre null != key1s
* @pre null != keys1[i] for all 0<= i <= keys1.length
* @throws RuntimeException if key pairs are already defined when
* {@link #enforceUniquness} is set to true
*/
public void put(
Object key0,
Object [] keys1,
Object value)
{
Util.pre(null != keys1, "null != keys1");
for (int i = 0; i < keys1.length; i++) {
Object key1 = keys1[i];
put(key0, key1, value);
}
}
/**
* Convenience method to define a set of key pairs at once. All pairs will
* be created with the same value. For Example
* <blockquote><pre><code>
* Object[] a = new Object[]{objA0, objA1};
* Object[] b = new Object[]{objB0, objB1, objB2};
* Object v = "value";
* DoubleKeyMap dblMap = new DoubleKeyMap();
* dblMap.put(a, b, v);
* </code></pre></blockquote>
* is equivalent to
* <blockquote><pre><code>
* dblMap.put(objA0, objB0, v);
* dblMap.put(objA0, objB1, v);
* dblMap.put(objA0, objB2, v);
* dblMap.put(objA1, objB0, v);
* dblMap.put(objA1, objB1, v);
* dblMap.put(objA1, objB2, v);
* </code></pre></blockquote>
* @pre null != key0s
* @pre null != key1s
* @pre null != keys0[i] for all 0<= i <= keys0.length
* @pre null != keys1[i] for all 0<= i <= keys1.length
* @throws RuntimeException if key pairs are already defined when
* {@link #enforceUniquness} is set to true
*/
public void put(
Object [] keys0,
Object [] keys1,
Object value)
{
Util.pre(null != keys0, "null != keys0");
Util.pre(null != keys1, "null != keys1");
for (int i = 0; i < keys0.length; i++) {
Object key0 = keys0[i];
put(key0, keys1, value);
}
}
/**
* @pre null != key0
* @pre null != key1
* @return Returns the value inserted with the key pair (key0, key1).
* Returns null if key pair not defined or the value was inserted with null
*/
public Object get(
Object key0,
Object key1)
{
HashMap key0Hash = (HashMap) root.get(key0);
if (null == key0Hash) {
return null;
}
return key0Hash.get(key1);
}
} |
package integration.forms;
/**
*
* @author fs93730
*/
public class BooleanValidator extends integration.forms.ControlValidator
{
private boolean m_preventChecked;
private com.sun.star.uno.AnyConverter m_converter;
/** Creates a new instance of BooleanValidator */
public BooleanValidator( boolean preventChecked )
{
m_preventChecked = preventChecked;
m_converter = new com.sun.star.uno.AnyConverter();
}
public String explainInvalid( Object Value )
{
try
{
if ( m_converter.isVoid( Value ) )
return "'indetermined' is not an allowed state";
boolean value = ((Boolean)Value).booleanValue();
if ( m_preventChecked && ( value == true ) )
return "no no no. Don't check it.";
}
catch( java.lang.Exception e )
{
return "ooops. Unknown error";
}
return "";
}
public boolean isValid( Object Value )
{
try
{
if ( m_converter.isVoid( Value ) )
return false;
boolean value = ((Boolean)Value).booleanValue();
if ( m_preventChecked && ( value == true ) )
return false;
return true;
}
catch( java.lang.Exception e )
{
}
return false;
}
} |
package com.camnter.smartrouter;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.camnter.smartrouter.core.Filter;
import com.camnter.smartrouter.core.Router;
import java.util.HashMap;
import java.util.Map;
/**
* @author CaMnter
*/
public final class SmartRouters {
private static final Map<String, Router> ROUTER_MAP = new HashMap<>();
private static final Map<String, Class<? extends Activity>> ACTIVITY_CLASS_MAP
= new HashMap<>();
private static String SCHEME = "routers";
private static String HOST = "";
private static Filter FILTER;
public static String getScheme() {
return SCHEME;
}
public static void setScheme(@NonNull final String scheme) {
SCHEME = scheme;
}
public static String getHost() {
return HOST;
}
public static void setHost(String host) {
HOST = host;
}
public static Filter getFilter() {
return FILTER;
}
public static void setgetFilter(Filter getFilter) {
FILTER = getFilter;
}
@SuppressWarnings("unchecked")
public static void running(@NonNull final Activity activity) {
final String targetFullName = activity.getClass().getName();
try {
Router router = ROUTER_MAP.get(targetFullName);
if (router == null) {
Class<?> routerClass = Class.forName(targetFullName + "_SmartRouter");
router = (Router) routerClass.newInstance();
ROUTER_MAP.put(targetFullName, router);
}
router.setFieldValue(activity);
} catch (Exception e) {
new Throwable("[SmartRouters] [running] " + targetFullName, e).printStackTrace();
}
}
public static void register(@NonNull final Router register) {
register.register(ACTIVITY_CLASS_MAP);
}
private static Class<? extends Activity> getActivityClass(@NonNull final String url,
@NonNull final Uri uri) {
final int index = url.indexOf('?');
// scheme:host?
final String schemeAndHost = index > 0 ? url.substring(0, index) : url;
Class<? extends Activity> clazz = ACTIVITY_CLASS_MAP.get(schemeAndHost);
if (clazz != null) {
return clazz;
}
String host;
if (SCHEME.equals(uri.getScheme())) {
host = uri.getHost();
return ACTIVITY_CLASS_MAP.get(host);
}
return null;
}
public static boolean start(@NonNull final Context context,
@NonNull final String url) {
if (TextUtils.isEmpty(url)) {
return false;
}
if (FILTER != null) {
final String mapUrl = FILTER.map(url);
if (FILTER.start(context, mapUrl)) {
return false;
}
}
final Uri uri = Uri.parse(url);
Class clazz = getActivityClass(url, uri);
if (clazz == null) {
new Throwable(url + "can't start").printStackTrace();
return false;
}
Intent intent = new Intent(context, clazz);
intent.setData(uri);
if (!(context instanceof Activity)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
return true;
}
public static boolean startForResult(@NonNull final Activity activity,
@NonNull final String url,
final int requestCode) {
if (TextUtils.isEmpty(url)) {
return false;
}
if (FILTER != null) {
final String mapUrl = FILTER.map(url);
if (FILTER.startForResult(activity, mapUrl, requestCode)) {
return false;
}
}
final Uri uri = Uri.parse(url);
Class clazz = getActivityClass(url, uri);
if (clazz == null) {
new Throwable(url + "can't startForResult").printStackTrace();
return false;
}
Intent intent = new Intent(activity, clazz);
intent.setData(uri);
activity.startActivityForResult(intent, requestCode);
return true;
}
public static boolean startForResult(@NonNull final Fragment fragment,
@NonNull final String url,
final int requestCode) {
if (TextUtils.isEmpty(url)) {
return false;
}
if (FILTER != null) {
final String mapUrl = FILTER.map(url);
if (FILTER.startForResult(fragment, mapUrl, requestCode)) {
return false;
}
}
final Uri uri = Uri.parse(url);
Class clazz = getActivityClass(url, uri);
if (clazz == null) {
new Throwable(url + "can't startForResult").printStackTrace();
return false;
}
Intent intent = new Intent(fragment.getActivity(), clazz);
intent.setData(uri);
fragment.startActivityForResult(intent, requestCode);
return true;
}
public static boolean startForResult(@NonNull final android.support.v4.app.Fragment fragment,
@NonNull final String url,
final int requestCode) {
if (TextUtils.isEmpty(url)) {
return false;
}
if (FILTER != null) {
final String mapUrl = FILTER.map(url);
if (FILTER.startForResult(fragment, mapUrl, requestCode)) {
return false;
}
}
final Uri uri = Uri.parse(url);
Class clazz = getActivityClass(url, uri);
if (clazz == null) {
new Throwable(url + "can't startForResult").printStackTrace();
return false;
}
Intent intent = new Intent(fragment.getActivity(), clazz);
intent.setData(uri);
fragment.startActivityForResult(intent, requestCode);
return true;
}
} |
package solver.constraints.propagators;
import choco.kernel.ESat;
import choco.kernel.memory.IEnvironment;
import choco.kernel.memory.structure.Operation;
import com.sun.istack.internal.Nullable;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import solver.Configuration;
import solver.ICause;
import solver.Identity;
import solver.Solver;
import solver.constraints.Constraint;
import solver.exception.ContradictionException;
import solver.explanations.Deduction;
import solver.explanations.Explanation;
import solver.explanations.VariableState;
import solver.variables.EventType;
import solver.variables.IntVar;
import solver.variables.Variable;
import solver.variables.view.Views;
import java.io.Serializable;
/**
* A <code>Propagator</code> class defines methods to react on a <code>Variable</code> objects modifications.
* It is observed by <code>Constraint</code> objects and can notify them when a <code>Variable</code> event occurs.
* <br/>
* Propagator methods are assumed to be idempotent, ie :
* Let f be a propagator method, such that f : D -> D' include D, where D the union of variable domains involved in f.
* Then, f(D)=f(D').
* <p/>
* <br/>
* A <code>Propagator</code> declares a filtering algorithm to apply to the <code>Variables</code> objects
* in scope in order to reduce their <code>Domain</code> objects.
* That's why the <code>propagate</code> method should be adapted to the expected filtering algorithm.
* This method is called through <code>Constraint</code> observers when an event occurs on a scoped <code>Variable</code>
* object. <code>propagate</code> method can throw a <code>ContradictionException</code>
* when this <code>Propagator</code> object detects a contradiction, within its filtering algorithm, like domain wipe out,
* out of domain value instantiation or other incoherencies.
* <br/>
* Furthermore, a <code>Propagator</code> object can be <i>entailed</i> : considering the current state of its <code>Variable</code>
* objects, the internal filtering algorithm becomes useless (for example: NEQ propagator and a couple of <code>Variable</code>
* objects with disjoint domains). In other words, whatever are the future events occurring on <code>Variable</code> objects,
* new calls to <code>propagate</code> method would be useless.
* <br/>
* <code>this</code> can be desactivate using the <code>setPassive</code>method.
* It automatically informs <code>Constraint</code> observers of this new "state".
*
* @author Xavier Lorca
* @author Charles Prud'homme
* @version 0.01, june 2010
* @see solver.variables.Variable
* @see solver.constraints.Constraint
* @since 0.01
*/
public abstract class Propagator<V extends Variable> implements Serializable, ICause, Identity, Comparable<Propagator> {
private static final long serialVersionUID = 2L;
protected final static Logger LOGGER = LoggerFactory.getLogger(Propagator.class);
protected static final short NEW = 0, ACTIVE = 1, PASSIVE = 2;
private final int ID; // unique id of this
/**
* List of <code>variable</code> objects
*/
protected V[] vars;
protected int[] vindices; // index of this within the list of propagator of the i^th variable
protected Operation[] operations;
/**
* Reference to the <code>Solver</code>'s <code>IEnvironment</code>,
* to deal with internal backtrackable structure.
*/
public IEnvironment environment;
/**
* Backtrackable boolean indicating wether <code>this</code> is active
*/
protected short state; // 0 : new -- 1 : active -- 2 : passive
protected int nbPendingEvt = 0; // counter of enqued records -- usable as trigger for complex algorithm
public long fineERcalls, coarseERcalls; // statistics of calls to filter
protected int fails;
/**
* Declaring constraint
*/
protected Constraint constraint;
protected final PropagatorPriority priority;
protected final boolean reactOnPromotion;
protected final Solver solver;
private static TIntSet set = new TIntHashSet();
protected Propagator aCause; // cause of variable modifications.
// The default value is 'this" but it can be overridden when using in reified propagator
// 2012-06-13 <cp>: multiple occurrences of variables in a propagator is strongly inadvisable
private static <V extends Variable> void checkVariable(V[] vars) {
set.clear();
for (int i = 0; i < vars.length; i++) {
Variable v = vars[i];
if ((v.getTypeAndKind() & Variable.CSTE) == 0) {
if (set.contains(v.getId())) {
if ((v.getTypeAndKind() & Variable.INT) != 0) {
vars[i] = (V) Views.eq((IntVar) v);
} else {
throw new UnsupportedOperationException(v.toString() + " occurs more than one time in this propagator. " +
"This is forbidden; you must consider using a View or a EQ constraint.");
}
}
set.add(vars[i].getId());
}
}
}
@SuppressWarnings({"unchecked"})
protected Propagator(V[] vars, Solver solver, Constraint<V, Propagator<V>> constraint, PropagatorPriority priority, boolean reactOnPromotion) {
checkVariable(vars);
this.vars = vars.clone();
this.vindices = new int[vars.length];
this.solver = solver;
this.environment = solver.getEnvironment();
this.state = NEW;
this.constraint = constraint;
this.priority = priority;
this.reactOnPromotion = reactOnPromotion;
this.aCause = this;
for (int v = 0; v < vars.length; v++) {
vindices[v] = vars[v].link(this, v);
/*if (!vars[v].instantiated()) {
nbNi++;
}*/
}
fails = 0;
ID = solver.nextId();
operations = new Operation[]{
new Operation() {
@Override
public void undo() {
state = NEW;
}
},
new Operation() {
@Override
public void undo() {
state = ACTIVE;
}
}
};
}
protected Propagator(V[] vars, Solver solver, Constraint<V, Propagator<V>> constraint, PropagatorPriority priority) {
this(vars, solver, constraint, priority, true);
}
@Override
public int getId() {
return ID;
}
public Solver getSolver() {
return solver;
}
/**
* Overrides the default cause of this.
* This is commonly used when this is declared
*
* @param nCause the new cause.
*/
public void overrideCause(Propagator nCause) {
this.aCause = nCause;
}
/**
* Return the specific mask indicating the <b>propagation events</b> on which <code>this</code> can react. <br/>
*
* @return
*/
public int getPropagationConditions() {
return EventType.FULL_PROPAGATION.mask;
}
/**
* Return the specific mask indicating the <b>variable events</b> on which this <code>Propagator</code> object can react.<br/>
* <i>Checks are made applying bitwise AND between the mask and the event.</i>
*
* @param vIdx index of the variable within the propagator
* @return int composed of <code>REMOVE</code> and/or <code>INSTANTIATE</code>
* and/or <code>DECUPP</code> and/or <code>INCLOW</code>
*/
public abstract int getPropagationConditions(int vIdx);
/**
* Call the main filtering algorithm to apply to the <code>Domain</code> of the <code>Variable</code> objects.
* It considers the current state of this objects to remove some values from domains and/or instantiate some variables.
* Calling this method is done from 2 (and only 2) steps:
* <br/>- at the initial propagation step,
* <br/>- when involved in a reified constraint.
* <br/>
* It should initialized the internal data structure and apply filtering algorithm from scratch.
*
* @param evtmask type of propagation event <code>this</code> must consider.
* @throws ContradictionException when a contradiction occurs, like domain wipe out or other incoherencies.
*/
public abstract void propagate(int evtmask) throws ContradictionException;
/**
* Advise a propagator of a modification occurring on one of its variables,
* and decide if <code>this</code> should be scheduled.
* At least, this method SHOULD check the propagation condition of the event received.
* In addition, this method can be used to update internal state of <code>this</code>.
* This method can returns <code>true</code> even if the propagator is already scheduled.
*
* @param idxVarInProp index of the modified variable
* @param mask modification event mask
* @return <code>true</code> if <code>this</code> should be scheduled, <code>false</code> otherwise.
*/
public boolean advise(int idxVarInProp, int mask) {
return (mask & getPropagationConditions(idxVarInProp)) != 0;
}
/**
* Call filtering algorihtm defined within the <code>Propagator</code> objects.
*
* @param idxVarInProp index of the variable <code>var</code> in <code>this</code>
* @param mask type of event
* @throws solver.exception.ContradictionException
* if a contradiction occurs
*/
public abstract void propagate(int idxVarInProp, int mask) throws ContradictionException;
/**
* Add the coarse event recorder into the engine
*
* @param evt event type
*/
public final void forcePropagate(EventType evt) throws ContradictionException {
//coarseER.update(evt);
//solver.getEngine().schedulePropagator(this, evt);
if (Configuration.PRINT_PROPAGATION)
LoggerFactory.getLogger("solver").info("\tFP {}", "<< {} ::" + this.toString() + " >>");
if (nbPendingEvt == 0) {
coarseERcalls++;
propagate(evt.getStrengthenedMask());
}
}
public void setActive() {
assert isStateLess() : "the propagator is already active, it cannot set active";
state = ACTIVE;
environment.save(operations[NEW]);
// update activity mask of variables
for (int v = 0; v < vars.length; v++) {
vars[v].recordMask(getPropagationConditions(v));
}
// to handle properly reified constraint, the cause must be checked
if (aCause == this) {
solver.getEngine().activatePropagator(this);
}
}
@SuppressWarnings({"unchecked"})
public void setPassive() {
assert isActive() : this.toString() + " is already passive, it cannot set passive more than once in one filtering call";
state = PASSIVE;
environment.save(operations[ACTIVE]);
// to handle properly reified constraint, the cause must be checked
if (aCause == this) {
solver.getEngine().desactivatePropagator(this);
}
}
public boolean isStateLess() {
return state == NEW;
}
public boolean isActive() {
return state == ACTIVE;
}
public boolean isPassive() {
return state == PASSIVE;
}
/**
* Check wether <code>this</code> is entailed according to the current state of its internal structure.
* At least, should check the satisfaction of <code>this</code> (when all is instantiated).
*
* @return ESat.TRUE if entailed, ESat.FALSE if not entailed, ESat.UNDEFINED if unknown
*/
public abstract ESat isEntailed();
/**
* Returns the element at the specified position in this internal list of <code>V</code> objects.
*
* @param i index of the element
* @return a <code>V</code> object
*/
public final V getVar(int i) {
return vars[i];
}
public final V[] getVars() {
return vars;
}
/**
* index of the propagator within its variables
*
* @return
*/
public int[] getVIndices() {
return vindices;
}
public void setVIndices(int idx, int val) {
vindices[idx] = val;
}
public void unlink() {
for (int v = 0; v < vars.length; v++) {
vars[v].unlink(this, vindices[v]);
vindices[v] = -1;
}
}
/**
* Returns the number of variables involved in <code>this</code>.
*
* @return number of variables
*/
public final int getNbVars() {
return vars.length;
}
/**
* Returns the constraint including this propagator
*
* @return Constraint
*/
@Override
public final Constraint getConstraint() {
return constraint;
}
public final PropagatorPriority getPriority() {
return priority;
}
public final boolean reactOnPromotion() {
return reactOnPromotion;
}
/**
* returns a explanation for the decision mentionned in parameters
*
* @param d : a <code>Deduction</code> to explain
* @return a set of constraints and past decisions
*/
@Override
public Explanation explain(Deduction d) {
Explanation expl = Explanation.build();
// the current deduction is due to the current domain of the involved variables
for (Variable v : this.vars) {
expl.add(v.explain(VariableState.DOM));
}
// and the application of the current propagator
expl.add(this);
return expl;
}
public boolean isCompletelyInstantiated() {
for (int i = 0; i < vars.length; i++) {
if (!vars[i].instantiated()) {
return false;
}
}
return true;
}
public int getNbPendingEvt() {
return nbPendingEvt;
}
public void incNbPendingEvt() {
assert (nbPendingEvt >= 0) : "number of enqued records is < 0";
nbPendingEvt++;
}
public void decNbPendingEvt() {
assert (nbPendingEvt > 0) : "number of enqued records is < 0";
nbPendingEvt
}
public void flushPendingEvt() {
nbPendingEvt = 0;
}
/**
* Returns the number of uninstanciated variables
*
* @return number of uninstanciated variables
*/
public int arity() {
int arity = 0;
for (int i = 0; i < vars.length; i++) {
arity += vars[i].instantiated() ? 0 : 1;
}
return arity;
}
public int dynPriority() {
int arity = 0;
for (int i = 0; i < vars.length && arity <= 3; i++) {
arity += vars[i].instantiated() ? 0 : 1;
}
if (arity > 3) {
return priority.priority;
} else return arity;
}
/**
* Throws a contradiction exception based on <variable, message>
*
* @param variable involved variable
* @param message detailed message
* @throws ContradictionException expected behavior
*/
public void contradiction(@Nullable Variable variable, String message) throws ContradictionException {
solver.getEngine().fails(aCause, variable, message);
}
@Override
public int compareTo(Propagator o) {
return this.ID - o.ID;
}
@Override
public int hashCode() {
return ID;
}
} |
package org.jasig.portal.channels.groupsmanager.commands;
import java.util.*;
import java.io.*;
import org.jasig.portal.*;
import org.jasig.portal.channels.groupsmanager.*;
import org.jasig.portal.groups.*;
import org.jasig.portal.services.*;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
/** This command delegates to the GroupsService to find entities requested
* by the user.
*/
public class Search extends org.jasig.portal.channels.groupsmanager.commands.GroupsManagerCommand {
/**
* put your documentation comment here
*/
public Search() {
}
/**
* put your documentation comment here
* @param sessionData
*/
public void execute (CGroupsManagerSessionData sessionData) {
Utility.logMessage("DEBUG", "SearchForEntities::execute(): Start");
ChannelStaticData staticData = sessionData.staticData;
ChannelRuntimeData runtimeData= sessionData.runtimeData;
Class type;
String grpTypeName = null;
EntityIdentifier[] results;
String grpPrefix = "IEntityGroup::";
boolean isGroupSearch;
// if present, the command arg will be the ancestor
String ancestorKey = getCommandArg(runtimeData);
IEntityGroup entGrp = GroupsManagerXML.retrieveGroup(ancestorKey);
String query = runtimeData.getParameter("grpQuery");
String method = runtimeData.getParameter("grpMethod");
int methodInt = Integer.getInteger(method).intValue();
// For an EntityGroup search, the grpType will have the form of "IEntityGroup::classname"
// For an Entity search, the grpType will have the form of "classname"
String grpType = runtimeData.getParameter("grpType");
String searchCriteria = "grpQuery." + query + "|" + "grpMethod." + method + "|"
+ "grpType." + grpType + "|" + "ancestor." + ancestorKey;
try{
if (grpType.startsWith(grpPrefix)){
isGroupSearch = true;
grpTypeName = grpType.substring(grpPrefix.length());
}
else{
isGroupSearch = false;
grpTypeName = grpType;
}
type = Class.forName(grpTypeName);
if (isGroupSearch){
if (entGrp != null){
results = GroupService.searchForGroups(query, methodInt, type, entGrp);
}
else{
results = GroupService.searchForGroups(query, methodInt, type);
}
}
else{
if (entGrp != null){
results = GroupService.searchForEntities(query, methodInt, type, entGrp);
}
else{
results = GroupService.searchForEntities(query, methodInt, type);
}
}
/* addional attributes:
canEdit = "false
criteria = "query::method::type::ancestor"
*/
Document model = sessionData.model;
Element searchElem = GroupsManagerXML.createElement("Search [" + query + "]", model, false);
searchElem.setAttribute("id", "srch:"+GroupsManagerXML.getNextUid());
//searchElem.setAttribute("key", "");
searchElem.setAttribute("expanded", String.valueOf(results.length > 0));
searchElem.setAttribute("searchCriteria", searchCriteria);
searchElem.setAttribute("canEdit", "false");
Element myGroups = GroupsManagerXML.getElementById (model, "0");
myGroups.appendChild(searchElem);
for (int sub=0 ; sub < results.length ; sub++) {
EntityIdentifier entID = results[sub];
IGroupMember resultGroup = (IGroupMember)GroupsManagerXML.retrieveGroup(entID.getKey());
Element result = GroupsManagerXML.getGroupMemberXml(resultGroup, false, null, model);
model.appendChild(searchElem);
}
sessionData.highlightedGroupID = searchElem.getAttribute("id");
if((sessionData.lockedGroup!=null) && (!sessionData.lockedGroup.getEntityIdentifier().getKey().equals(sessionData.highlightedGroupID)) && (!sessionData.mode.equals("select"))){
try{
sessionData.lockedGroup.getLock().release();
}
catch(Exception e){}
sessionData.lockedGroup = null;
sessionData.mode = BROWSE_MODE;
}
}
catch (GroupsException ge){
Utility.logMessage("ERROR", "Search failed for criteria = " + searchCriteria + "/n" + ge);
}
catch (ClassNotFoundException cnfe){
Utility.logMessage("ERROR", "Unable to instantiate class for " + grpTypeName + "/n" + cnfe);
}
}
} |
package redstone.xmlrpc.interceptors;
import javax.servlet.ServletContext;
import redstone.xmlrpc.XmlRpcInvocation;
import redstone.xmlrpc.XmlRpcInvocationInterceptor;
/**
* Simple invocation processor that traces the calls made through an XmlRpcServer.
* This is used for debugging purposes only. This may be replaced with a more
* competent logging processor that perhaps is only logging exceptions that occur.<p>
*
* Logging occurs either on System.out or on the servlet container log depending
* on if a ServletContext is supplied or not when constructing the interceptor.
*
* @author Greger Olsson
*/
public class DebugInvocationInterceptor implements XmlRpcInvocationInterceptor
{
/**
* Empty default constructor. Using this constructor rather than the
* one accepting a ServletContext will cause the output to be printed
* on System.out instead of the servlet container log.
*/
public DebugInvocationInterceptor()
{
}
/**
* Constructs the interceptor while associating it with the supplied
* servlet context. Output will be directed to the servlet container log.
*
* @param servletContext The servlet context to be used for logging.
*/
public DebugInvocationInterceptor( ServletContext servletContext )
{
this.servletContext = servletContext;
}
/**
* Outputs information bout the invocation, the method, and its arguments.
*
* @param invocation The invocation.
*/
public boolean before( XmlRpcInvocation invocation )
{
StringBuffer message = new StringBuffer( 192 );
message.append( invocation.getInvocationId() )
.append( ": " )
.append( invocation.getHandlerName() )
.append( '.' )
.append( invocation.getMethodName() )
.append( invocation.getArguments().toString() );
if ( servletContext != null )
{
servletContext.log( message.toString() );
}
else
{
System.out.println( message.toString() );
}
return true;
}
/**
* Prints trace info on the invocation return value.
*
* @param invocation The invocation.
* @param returnValue The value returned from the method.
*/
public Object after( XmlRpcInvocation invocation, Object returnValue )
{
StringBuffer message = new StringBuffer( 192 );
message.append( invocation.getInvocationId() )
.append( ": " )
.append( returnValue );
if ( servletContext != null )
{
servletContext.log( message.toString() );
}
else
{
System.out.println( message.toString() );
}
return returnValue;
}
/**
* Prints trace info on the invocation exception.
*
* @param invocation The invocation.
* @param invocation The exception thrown by the method.
*/
public void onException( XmlRpcInvocation invocation, Throwable exception )
{
StringBuffer message = new StringBuffer( 192 );
message.append( invocation.getInvocationId() )
.append( ": " )
.append( exception.getMessage() );
if ( servletContext != null )
{
servletContext.log( message.toString(), exception );
}
else
{
if ( exception.getCause() != null )
{
message.append( exception.getCause().getMessage() );
}
System.out.println( message.toString() );
}
}
/** The servlet context that logging will be performed over. */
private ServletContext servletContext;
} |
package com.google.code.ssm.spring;
import java.util.concurrent.TimeoutException;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import com.google.code.ssm.aop.support.PertinentNegativeNull;
import com.google.code.ssm.providers.CacheException;
public class SSMCache implements Cache {
private final static Logger LOGGER = LoggerFactory.getLogger(SSMCache.class);
@Getter
private final com.google.code.ssm.Cache cache;
@Getter
private final int expiration;
@Getter
private final boolean allowClear;
public SSMCache(final com.google.code.ssm.Cache cache, final int expiration, final boolean allowClear) {
this.cache = cache;
this.expiration = expiration;
this.allowClear = allowClear;
}
public SSMCache(final com.google.code.ssm.Cache cache, final int expiration) {
this(cache, expiration, false);
}
public SSMCache(final SSMCache ssmCache, final int expiration) {
this(ssmCache.cache, expiration, ssmCache.allowClear);
}
@Override
public String getName() {
return cache.getName();
}
@Override
public Object getNativeCache() {
return cache;
}
@Override
public ValueWrapper get(final Object key) {
Object value = null;
try {
value = cache.get(getKey(key), null);
} catch (TimeoutException e) {
LOGGER.warn("An error has ocurred for cache " + getName() + " and key " + getKey(key), e);
} catch (CacheException e) {
LOGGER.warn("An error has ocurred for cache " + getName() + " and key " + getKey(key), e);
}
if (value == null) {
LOGGER.info("Cache miss. Get by key {} from cache {}", key, cache.getName());
return null;
}
LOGGER.info("Cache hit. Get by key {} from cache {} value '{}'", new Object[] { key, cache.getName(), value });
return value instanceof PertinentNegativeNull ? new SimpleValueWrapper(null) : new SimpleValueWrapper(value);
}
@Override
public void put(final Object key, final Object value) {
if (key != null) {
try {
LOGGER.info("Put '{}' under key {} to cache {}", new Object[] { value, key, cache.getName() });
Object store = value;
if (value == null) {
store = PertinentNegativeNull.NULL;
}
cache.set(getKey(key), expiration, store, null);
} catch (TimeoutException e) {
LOGGER.warn("An error has ocurred for cache " + getName() + " and key " + getKey(key), e);
} catch (CacheException e) {
LOGGER.warn("An error has ocurred for cache " + getName() + " and key " + getKey(key), e);
}
} else {
LOGGER.info("Cannot put to cache {} because key is null", cache.getName());
}
}
@Override
public void evict(final Object key) {
if (key != null) {
try {
LOGGER.info("Evict {} from cache {}", key, cache.getName());
cache.delete(getKey(key));
} catch (TimeoutException e) {
LOGGER.warn("An error has ocurred for cache " + getName() + " and key " + getKey(key), e);
} catch (CacheException e) {
LOGGER.warn("An error has ocurred for cache " + getName() + " and key " + getKey(key), e);
}
} else {
LOGGER.info("Cannot evict from cache {} because key is null", cache.getName());
}
}
@Override
public void clear() {
if (!allowClear) {
LOGGER.error("Clearing cache '{}' is not allowed. To enable it set allowClear to true. "
+ "Make sure that caches don't overlap (one memcached instance isn't used by more than one cache) "
+ "otherwise clearing one cache will affect another.", getName());
throw new IllegalStateException("Cannot clear cache " + getName());
}
try {
LOGGER.info("Clear {}", cache.getName());
cache.flush();
} catch (TimeoutException e) {
LOGGER.warn("An error has ocurred for cache " + getName(), e);
} catch (CacheException e) {
LOGGER.warn("An error has ocurred for cache " + getName(), e);
}
}
private String getKey(final Object key) {
return key.toString();
}
} |
package au.edu.griffith.ict;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
// custManager: CustomerManager
// itemManager: Menu
// orders: Order[*]
// users: User[*]
/** A reference to the Customer Manager*/
private CustomerManager customers;
/** A reference to the Menu */
private Menu menu;
/** A non-persistent list of Orders */
private LinkedList<Order> orders;
/** A non-presistent list of Users */
private HashMap<Integer, User> users;
/** A running total of the day's takings. */
private float dayTotal; //This wasn't in the design docs.
/** The Main method. */
public static void main(String[] args){
System.out.println("Hello World");
}
/**
* Adds an Order to the list of orders.
* @param order The Order to add to the list.
*/
public void addOrder(Order order){
throw new UnsupportedOperationException("Not implemented yet.");
}
/**
* Removes an order from the list of orders, effectively deleting the order.
* @param order The order to be removed.
*/
public void removeOrder(Order order){
throw new UnsupportedOperationException("Not implemented yet.");
}
/**
* Gets an array of orders that belong to a given customer.
* @param customer The customer to query for.
* @return An array of Order objects.
*/
public Order[] getOrders(Customer customer){
throw new UnsupportedOperationException("Not implemented yet.");
}
/**
* Get the total takings for the day.
* A day is considered to be the time since the program started.
* @return A float representing the day's takings.
*/
public float getDayTotal(){
throw new UnsupportedOperationException("Not implemented yet.");
}
/**
* Display the answer to the meaning of life (42).
*/
public void display(){
throw new UnsupportedOperationException("Not implemented yet.");
}
/**
* An Order factory.
* @return An initialised Order object.
*/
private Order buildOrder(){
Order
}
/** Prints the menu out to the user */
private void displayMenu(){
for(int i = 0; i < menu.getItems(); i++){
MenuItem item = menu.getItem(i);
if(item == null) continue;
System.out.printf("%.4f %.20s %.2f", item.getItemNo(), item.getName(), item.getPrice());
}
}
/**
* Requests the user to input a new menu item
* @return Displays the menu to the user and requests they enter an item.
* Returns null if there is no new item.
*/
private MenuItem requestItem(){
System.out.println("Please select a menu item. To cancel, just press enter.");
displayMenu();
System.out.println("Menu item ID: ");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
sc.close();
if(s.isEmpty()) return null;
try{
MenuItem item = menu.getItem(Integer.parseInt(s));
return item;
}
catch(NumberFormatException e){
System.out.println(s + " is not a valid number! Cancelling.");
}
return null;
}
/** Requests the user input a new integer
* @return The int they entered
*/
private int requestNumber(){
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
sc.close();
return i;
}
} |
package util.game;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import util.configuration.RemoteResourceLoader;
import util.gdl.grammar.Gdl;
import util.kif.KifReader;
import external.JSON.JSONArray;
import external.JSON.JSONException;
import external.JSON.JSONObject;
/**
* Remote game repositories provide access to game resources stored on game
* repository servers on the web. These require a network connection to work.
*
* @author Sam
*/
public final class RemoteGameRepository extends GameRepository {
private final String theRepoURL;
public RemoteGameRepository(String theURL) {
theRepoURL = theURL;
}
public Set<String> getUncachedGameKeys() {
try {
Set<String> theGameKeys = new HashSet<String>();
JSONArray theArray = RemoteResourceLoader.loadJSONArray(theRepoURL + "/games/");
for(int i = 0; i < theArray.length(); i++) {
theGameKeys.add(theArray.getString(i));
}
return theGameKeys;
} catch (Exception e) {
// TODO: Log this exception somewhere?
return null;
}
}
public Game getUncachedGame(String theKey) {
try {
JSONObject theMetadata = getGameMetadataFromRepository(theKey);
String theName = null;
try {
theName = theMetadata.getString("gameName");
} catch(JSONException e) {}
String theRepositoryURL = theRepoURL + "/games/" + theKey + "/";
String theDescription = getGameResourceFromMetadata(theKey, theMetadata, "description");
String theStylesheet = getGameResourceFromMetadata(theKey, theMetadata, "stylesheet");
List<Gdl> theRules = getGameRulesheetFromMetadata(theKey, theMetadata);
return new Game(theKey, theName, theDescription, theRepositoryURL, theStylesheet, theRules);
} catch(IOException e) {
return null;
}
}
public JSONObject getGameMetadataFromRepository(String theGame) throws IOException {
return RemoteResourceLoader.loadJSON(theRepoURL + "/games/" + theGame + "/");
}
public String getGameResourceFromMetadata(String theGame, JSONObject theMetadata, String theResource) {
try {
String theResourceFile = theMetadata.getString(theResource);
return RemoteResourceLoader.loadRaw(theRepoURL + "/games/" + theGame + "/" + theResourceFile);
} catch (Exception e) {
return null;
}
}
public List<Gdl> getGameRulesheetFromMetadata(String theGame, JSONObject theMetadata) {
try {
String theRulesheetFile = theMetadata.getString("rulesheet");
return KifReader.readURL(theRepoURL + "/games/" + theGame + "/" + theRulesheetFile);
} catch (Exception e) {
return null;
}
}
} |
package org.apache.xerces.impl.dv.xs;
import org.apache.xerces.impl.dv.XSSimpleType;
import org.apache.xerces.impl.dv.XSFacets;
import org.apache.xerces.impl.dv.DatatypeException;
import org.apache.xerces.impl.dv.InvalidDatatypeValueException;
import org.apache.xerces.impl.dv.InvalidDatatypeFacetException;
import org.apache.xerces.impl.dv.ValidatedInfo;
import org.apache.xerces.impl.validation.ValidationContext;
import org.apache.xerces.impl.xs.XSTypeDecl;
import org.apache.xerces.impl.xs.psvi.*;
import org.apache.xerces.impl.xs.SchemaGrammar;
import org.apache.xerces.impl.xs.SchemaSymbols;
import org.apache.xerces.impl.xs.util.EnumerationImpl;
import org.apache.xerces.impl.xs.util.XSObjectListImpl;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.impl.xpath.regex.RegularExpression;
import org.apache.xerces.xni.NamespaceContext;
import java.util.Vector;
import java.util.Enumeration;
import java.util.StringTokenizer;
/**
* @author Sandy Gao, IBM
* @author Neeraj Bajaj, Sun Microsystems, inc.
*
* @version $Id$
*/
public class XSSimpleTypeDecl implements XSSimpleType {
static final short DV_STRING = PRIMITIVE_STRING;
static final short DV_BOOLEAN = PRIMITIVE_BOOLEAN;
static final short DV_DECIMAL = PRIMITIVE_DECIMAL;
static final short DV_FLOAT = PRIMITIVE_FLOAT;
static final short DV_DOUBLE = PRIMITIVE_DOUBLE;
static final short DV_DURATION = PRIMITIVE_DURATION;
static final short DV_DATETIME = PRIMITIVE_DATETIME;
static final short DV_TIME = PRIMITIVE_TIME;
static final short DV_DATE = PRIMITIVE_DATE;
static final short DV_GYEARMONTH = PRIMITIVE_GYEARMONTH;
static final short DV_GYEAR = PRIMITIVE_GYEAR;
static final short DV_GMONTHDAY = PRIMITIVE_GMONTHDAY;
static final short DV_GDAY = PRIMITIVE_GDAY;
static final short DV_GMONTH = PRIMITIVE_GMONTH;
static final short DV_HEXBINARY = PRIMITIVE_HEXBINARY;
static final short DV_BASE64BINARY = PRIMITIVE_BASE64BINARY;
static final short DV_ANYURI = PRIMITIVE_ANYURI;
static final short DV_QNAME = PRIMITIVE_QNAME;
static final short DV_NOTATION = PRIMITIVE_NOTATION;
static final short DV_ANYSIMPLETYPE = 0;
static final short DV_ID = DV_NOTATION + 1;
static final short DV_IDREF = DV_NOTATION + 2;
static final short DV_ENTITY = DV_NOTATION + 3;
static final short DV_LIST = DV_NOTATION + 4;
static final short DV_UNION = DV_NOTATION + 5;
static final TypeValidator[] fDVs = {
new AnySimpleDV(),
new StringDV(),
new BooleanDV(),
new DecimalDV(),
new FloatDV(),
new DoubleDV(),
new DurationDV(),
new DateTimeDV(),
new TimeDV(),
new DateDV(),
new YearMonthDV(),
new YearDV(),
new MonthDayDV(),
new DayDV(),
new MonthDV(),
new HexBinaryDV(),
new Base64BinaryDV(),
new AnyURIDV(),
new QNameDV(),
new QNameDV(), // notation use the same one as qname
new IDDV(),
new IDREFDV(),
new EntityDV(),
new ListDV(),
new UnionDV()
};
static final short SPECIAL_PATTERN_NONE = 0;
static final short SPECIAL_PATTERN_NMTOKEN = 1;
static final short SPECIAL_PATTERN_NAME = 2;
static final short SPECIAL_PATTERN_NCNAME = 3;
static final short SPECIAL_PATTERN_INTEGER = 4;
static final String[] SPECIAL_PATTERN_STRING = {
"NONE", "NMTOKEN", "Name", "NCName", "integer"
};
static final String[] WS_FACET_STRING = {
"preserve", "collapse", "replace",
};
private XSSimpleTypeDecl fItemType;
private XSSimpleTypeDecl[] fMemberTypes;
private String fTypeName;
private String fTargetNamespace;
private short fFinalSet = 0;
private XSSimpleTypeDecl fBase;
private short fVariety = -1;
private short fValidationDV = -1;
private short fFacetsDefined = 0;
private short fFixedFacet = 0;
//for constraining facets
private short fWhiteSpace = 0;
private int fLength = -1;
private int fMinLength = -1;
private int fMaxLength = -1;
private int fTotalDigits = -1;
private int fFractionDigits = -1;
private Vector fPattern;
private Vector fEnumeration;
private Object fMaxInclusive;
private Object fMaxExclusive;
private Object fMinExclusive;
private Object fMinInclusive;
private short fPatternType = SPECIAL_PATTERN_NONE;
// for fundamental facets
private short fOrdered;
private boolean fFinite;
private boolean fBounded;
private boolean fNumeric;
// default constructor
public XSSimpleTypeDecl(){}
//Create a new built-in primitive types (and id/idref/entity)
protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, short validateDV,
short ordered, boolean bounded,
boolean finite, boolean numeric) {
fBase = base;
fTypeName = name;
fTargetNamespace = SchemaDVFactoryImpl.URI_SCHEMAFORSCHEMA;
// To simplify the code for anySimpleType, we treat it as an atomic type
fVariety = VARIETY_ATOMIC;
fValidationDV = validateDV;
fFacetsDefined = FACET_WHITESPACE;
if (validateDV == DV_STRING) {
fWhiteSpace = WS_PRESERVE;
} else {
fWhiteSpace = WS_COLLAPSE;
fFixedFacet = FACET_WHITESPACE;
}
this.fOrdered = ordered;
this.fBounded = bounded;
this.fFinite = finite;
this.fNumeric = numeric;
}
//Create a new simple type for restriction.
protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, String uri, short finalSet) {
fBase = base;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fVariety = fBase.fVariety;
fValidationDV = fBase.fValidationDV;
switch (fVariety) {
case VARIETY_ATOMIC:
break;
case VARIETY_LIST:
fItemType = fBase.fItemType;
break;
case VARIETY_UNION:
fMemberTypes = fBase.fMemberTypes;
break;
}
// always inherit facets from the base.
// in case a type is created, but applyFacets is not called
fLength = fBase.fLength;
fMinLength = fBase.fMinLength;
fMaxLength = fBase.fMaxLength;
fPattern = fBase.fPattern;
fEnumeration = fBase.fEnumeration;
fWhiteSpace = fBase.fWhiteSpace;
fMaxExclusive = fBase.fMaxExclusive;
fMaxInclusive = fBase.fMaxInclusive;
fMinExclusive = fBase.fMinExclusive;
fMinInclusive = fBase.fMinInclusive;
fTotalDigits = fBase.fTotalDigits;
fFractionDigits = fBase.fFractionDigits;
fPatternType = fBase.fPatternType;
fFixedFacet = fBase.fFixedFacet;
fFacetsDefined = fBase.fFacetsDefined;
//we also set fundamental facets information in case applyFacets is not called.
caclFundamentalFacets();
}
//Create a new simple type for list.
protected XSSimpleTypeDecl(String name, String uri, short finalSet, XSSimpleTypeDecl itemType) {
fBase = fAnySimpleType;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fVariety = VARIETY_LIST;
fItemType = (XSSimpleTypeDecl)itemType;
fValidationDV = DV_LIST;
fFacetsDefined = FACET_WHITESPACE;
fFixedFacet = FACET_WHITESPACE;
fWhiteSpace = WS_COLLAPSE;
//setting fundamental facets
caclFundamentalFacets();
}
//Create a new simple type for union.
protected XSSimpleTypeDecl(String name, String uri, short finalSet, XSSimpleTypeDecl[] memberTypes) {
fBase = fAnySimpleType;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fVariety = VARIETY_UNION;
fMemberTypes = memberTypes;
fValidationDV = DV_UNION;
// even for union, we set whitespace to something
// this will never be used, but we can use fFacetsDefined to check
// whether applyFacets() is allwwed: it's not allowed
// if fFacetsDefined != 0
fFacetsDefined = FACET_WHITESPACE;
fWhiteSpace = WS_COLLAPSE;
//setting fundamental facets
caclFundamentalFacets();
}
//set values for restriction.
protected XSSimpleTypeDecl setRestrictionValues(XSSimpleTypeDecl base, String name, String uri, short finalSet) {
fBase = base;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fVariety = fBase.fVariety;
fValidationDV = fBase.fValidationDV;
switch (fVariety) {
case VARIETY_ATOMIC:
break;
case VARIETY_LIST:
fItemType = fBase.fItemType;
break;
case VARIETY_UNION:
fMemberTypes = fBase.fMemberTypes;
break;
}
// always inherit facets from the base.
// in case a type is created, but applyFacets is not called
fLength = fBase.fLength;
fMinLength = fBase.fMinLength;
fMaxLength = fBase.fMaxLength;
fPattern = fBase.fPattern;
fEnumeration = fBase.fEnumeration;
fWhiteSpace = fBase.fWhiteSpace;
fMaxExclusive = fBase.fMaxExclusive;
fMaxInclusive = fBase.fMaxInclusive;
fMinExclusive = fBase.fMinExclusive;
fMinInclusive = fBase.fMinInclusive;
fTotalDigits = fBase.fTotalDigits;
fFractionDigits = fBase.fFractionDigits;
fPatternType = fBase.fPatternType;
fFixedFacet = fBase.fFixedFacet;
fFacetsDefined = fBase.fFacetsDefined;
//we also set fundamental facets information in case applyFacets is not called.
caclFundamentalFacets();
return this;
}
//set values for list.
protected XSSimpleTypeDecl setListValues(String name, String uri, short finalSet, XSSimpleTypeDecl itemType) {
fBase = fAnySimpleType;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fVariety = VARIETY_LIST;
fItemType = (XSSimpleTypeDecl)itemType;
fValidationDV = DV_LIST;
fFacetsDefined = FACET_WHITESPACE;
fFixedFacet = FACET_WHITESPACE;
fWhiteSpace = WS_COLLAPSE;
//setting fundamental facets
caclFundamentalFacets();
return this;
}
//set values for union.
protected XSSimpleTypeDecl setUnionValues(String name, String uri, short finalSet, XSSimpleTypeDecl[] memberTypes) {
fBase = fAnySimpleType;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fVariety = VARIETY_UNION;
fMemberTypes = memberTypes;
fValidationDV = DV_UNION;
// even for union, we set whitespace to something
// this will never be used, but we can use fFacetsDefined to check
// whether applyFacets() is allwwed: it's not allowed
// if fFacetsDefined != 0
fFacetsDefined = FACET_WHITESPACE;
fWhiteSpace = WS_COLLAPSE;
//setting fundamental facets
caclFundamentalFacets();
return this;
}
public short getType () {
return XSConstants.TYPE_DEFINITION;
}
public short getTypeCategory () {
return SIMPLE_TYPE;
}
public String getName() {
return fTypeName;
}
public String getNamespace() {
return fTargetNamespace;
}
public short getFinal(){
return fFinalSet;
}
public boolean getIsFinal(short derivation) {
return (fFinalSet & derivation) != 0;
}
public XSTypeDefinition getBaseType(){
return fBase;
}
public boolean getIsAnonymous() {
return fTypeName == null;
}
public short getVariety(){
// for anySimpleType, return absent variaty
return fValidationDV == DV_ANYSIMPLETYPE ? VARIETY_ABSENT : fVariety;
}
public boolean isIDType(){
switch (fVariety) {
case VARIETY_ATOMIC:
return fValidationDV == DV_ID;
case VARIETY_LIST:
return fItemType.isIDType();
case VARIETY_UNION:
for (int i = 0; i < fMemberTypes.length; i++) {
if (fMemberTypes[i].isIDType())
return true;
}
}
return false;
}
public short getWhitespace() throws DatatypeException{
if (fVariety == VARIETY_UNION) {
throw new DatatypeException("dt-whitespace", new Object[]{fTypeName});
}
return fWhiteSpace;
}
public short getPrimitiveKind() {
if (fVariety == VARIETY_ATOMIC && fValidationDV != DV_ANYSIMPLETYPE) {
if (fVariety == DV_ID || fVariety == DV_IDREF || fVariety == DV_ENTITY)
return DV_STRING;
else
return fValidationDV;
}
else {
// REVISIT: error situation. runtime exception?
return (short)0;
}
}
public XSSimpleTypeDefinition getPrimitiveType() {
if (fVariety == VARIETY_ATOMIC && fValidationDV != DV_ANYSIMPLETYPE) {
XSSimpleTypeDecl pri = this;
// recursively get base, until we reach anySimpleType
while (pri.fBase != fAnySimpleType)
pri = pri.fBase;
return pri;
}
else {
// REVISIT: error situation. runtime exception?
return null;
}
}
public XSSimpleTypeDefinition getItemType() {
if (fVariety == VARIETY_LIST) {
return fItemType;
}
else {
// REVISIT: error situation. runtime exception?
return null;
}
}
public XSObjectList getMemberTypes() {
if (fVariety == VARIETY_UNION) {
return new XSObjectListImpl(fMemberTypes, fMemberTypes.length);
}
else {
// REVISIT: error situation. runtime exception?
return null;
}
}
/**
* If <restriction> is chosen
*/
public void applyFacets(XSFacets facets, short presentFacet, short fixedFacet, ValidationContext context)
throws InvalidDatatypeFacetException {
applyFacets(facets, presentFacet, fixedFacet, SPECIAL_PATTERN_NONE, context);
}
/**
* built-in derived types by restriction
*/
void applyFacets1(XSFacets facets, short presentFacet, short fixedFacet) {
try {
applyFacets(facets, presentFacet, fixedFacet, SPECIAL_PATTERN_NONE, fDummyContext);
} catch (InvalidDatatypeFacetException e) {
// should never gets here, internel error
throw new RuntimeException("internal error");
}
}
/**
* built-in derived types by restriction
*/
void applyFacets1(XSFacets facets, short presentFacet, short fixedFacet, short patternType) {
try {
applyFacets(facets, presentFacet, fixedFacet, patternType, fDummyContext);
} catch (InvalidDatatypeFacetException e) {
// should never gets here, internel error
throw new RuntimeException("internal error");
}
}
/**
* If <restriction> is chosen, or built-in derived types by restriction
*/
void applyFacets(XSFacets facets, short presentFacet, short fixedFacet, short patternType, ValidationContext context)
throws InvalidDatatypeFacetException {
ValidatedInfo tempInfo = new ValidatedInfo();
// clear facets. because we always inherit facets in the constructor
// REVISIT: in fact, we don't need to clear them.
// we can convert 5 string values (4 bounds + 1 enum) to actual values,
// store them somewhere, then do facet checking at once, instead of
// going through the following steps. (lots of checking are redundant:
// for example, ((presentFacet & FACET_XXX) != 0))
fFacetsDefined = 0;
fFixedFacet = 0;
int result = 0 ;
// step 1: parse present facets
short allowedFacet = fDVs[fValidationDV].getAllowedFacets();
// length
if ((presentFacet & FACET_LENGTH) != 0) {
if ((allowedFacet & FACET_LENGTH) == 0) {
reportError("cos-applicable-facets", new Object[]{"length"});
} else {
fLength = facets.length;
fFacetsDefined |= FACET_LENGTH;
if ((fixedFacet & FACET_LENGTH) != 0)
fFixedFacet |= FACET_LENGTH;
}
}
// minLength
if ((presentFacet & FACET_MINLENGTH) != 0) {
if ((allowedFacet & FACET_MINLENGTH) == 0) {
reportError("cos-applicable-facets", new Object[]{"minLength"});
} else {
fMinLength = facets.minLength;
fFacetsDefined |= FACET_MINLENGTH;
if ((fixedFacet & FACET_MINLENGTH) != 0)
fFixedFacet |= FACET_MINLENGTH;
}
}
// maxLength
if ((presentFacet & FACET_MAXLENGTH) != 0) {
if ((allowedFacet & FACET_MAXLENGTH) == 0) {
reportError("cos-applicable-facets", new Object[]{"maxLength"});
} else {
fMaxLength = facets.maxLength;
fFacetsDefined |= FACET_MAXLENGTH;
if ((fixedFacet & FACET_MAXLENGTH) != 0)
fFixedFacet |= FACET_MAXLENGTH;
}
}
// pattern
if ((presentFacet & FACET_PATTERN) != 0) {
if ((allowedFacet & FACET_PATTERN) == 0) {
reportError("cos-applicable-facets", new Object[]{"pattern"});
} else {
RegularExpression regex = null;
try {
regex = new RegularExpression(facets.pattern, "X");
} catch (Exception e) {
reportError("InvalidRegex", new Object[]{facets.pattern, e.getLocalizedMessage()});
}
if (regex != null) {
fPattern = new Vector();
fPattern.addElement(regex);
fFacetsDefined |= FACET_PATTERN;
if ((fixedFacet & FACET_PATTERN) != 0)
fFixedFacet |= FACET_PATTERN;
}
}
}
// enumeration
if ((presentFacet & FACET_ENUMERATION) != 0) {
if ((allowedFacet & FACET_ENUMERATION) == 0) {
reportError("cos-applicable-facets", new Object[]{"enumeration"});
} else {
fEnumeration = new Vector();
Vector enumVals = facets.enumeration;
Vector enumNSDecls = facets.enumNSDecls;
ValidationContextImpl ctx = new ValidationContextImpl(context);
for (int i = 0; i < enumVals.size(); i++) {
if (enumNSDecls != null)
ctx.setNSContext((NamespaceContext)enumNSDecls.elementAt(i));
try {
// check 4.3.5.c0 must: enumeration values from the value space of base
fEnumeration.addElement(this.fBase.validate((String)enumVals.elementAt(i), ctx, tempInfo));
} catch (InvalidDatatypeValueException ide) {
reportError("enumeration-valid-restriction", new Object[]{enumVals.elementAt(i)});
}
}
fFacetsDefined |= FACET_ENUMERATION;
if ((fixedFacet & FACET_ENUMERATION) != 0)
fFixedFacet |= FACET_ENUMERATION;
}
}
// whiteSpace
if ((presentFacet & FACET_WHITESPACE) != 0) {
if ((allowedFacet & FACET_WHITESPACE) == 0) {
reportError("cos-applicable-facets", new Object[]{"whiteSpace"});
} else {
fWhiteSpace = facets.whiteSpace;
fFacetsDefined |= FACET_WHITESPACE;
if ((fixedFacet & FACET_WHITESPACE) != 0)
fFixedFacet |= FACET_WHITESPACE;
}
}
boolean needCheckBase = true;
// maxInclusive
if ((presentFacet & FACET_MAXINCLUSIVE) != 0) {
if ((allowedFacet & FACET_MAXINCLUSIVE) == 0) {
reportError("cos-applicable-facets", new Object[]{"maxInclusive"});
} else {
try {
fMaxInclusive = getActualValue(facets.maxInclusive, context, tempInfo);
fFacetsDefined |= FACET_MAXINCLUSIVE;
if ((fixedFacet & FACET_MAXINCLUSIVE) != 0)
fFixedFacet |= FACET_MAXINCLUSIVE;
} catch (InvalidDatatypeValueException ide) {
reportError("FacetValueFromBase", new Object[]{facets.maxInclusive, "maxInclusive"});
}
// maxInclusive from base
if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxInclusive);
if ((fBase.fFixedFacet & FACET_MAXINCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"maxInclusive", getStringValue(fMaxInclusive), getStringValue(fBase.fMaxInclusive)});
}
if (result == 0) {
needCheckBase = false;
}
}
if (needCheckBase) {
try {
fBase.validate(context, tempInfo);
} catch (InvalidDatatypeValueException ide) {
reportError("FacetValueFromBase", new Object[]{facets.maxInclusive, "maxInclusive"});
}
}
}
}
// maxExclusive
if ((presentFacet & FACET_MAXEXCLUSIVE) != 0) {
if ((allowedFacet & FACET_MAXEXCLUSIVE) == 0) {
reportError("cos-applicable-facets", new Object[]{"maxExclusive"});
} else {
try {
fMaxExclusive = getActualValue(facets.maxExclusive, context, tempInfo);
fFacetsDefined |= FACET_MAXEXCLUSIVE;
if ((fixedFacet & FACET_MAXEXCLUSIVE) != 0)
fFixedFacet |= FACET_MAXEXCLUSIVE;
} catch (InvalidDatatypeValueException ide) {
reportError("FacetValueFromBase", new Object[]{facets.maxExclusive, "maxExclusive"});
}
// maxExclusive from base
if (((fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxExclusive);
if ((fBase.fFixedFacet & FACET_MAXEXCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"maxExclusive", facets.maxExclusive, getStringValue(fBase.fMaxExclusive)});
}
if (result == 0) {
needCheckBase = false;
}
}
if (needCheckBase) {
try {
fBase.validate(context, tempInfo);
} catch (InvalidDatatypeValueException ide) {
reportError("FacetValueFromBase", new Object[]{facets.maxExclusive, "maxExclusive"});
}
}
}
}
// minExclusive
if ((presentFacet & FACET_MINEXCLUSIVE) != 0) {
if ((allowedFacet & FACET_MINEXCLUSIVE) == 0) {
reportError("cos-applicable-facets", new Object[]{"minExclusive"});
} else {
try {
fMinExclusive = getActualValue(facets.minExclusive, context, tempInfo);
fFacetsDefined |= FACET_MINEXCLUSIVE;
if ((fixedFacet & FACET_MINEXCLUSIVE) != 0)
fFixedFacet |= FACET_MINEXCLUSIVE;
} catch (InvalidDatatypeValueException ide) {
reportError("FacetValueFromBase", new Object[]{facets.minExclusive, "minExclusive"});
}
// minExclusive from base
if (((fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinExclusive);
if ((fBase.fFixedFacet & FACET_MINEXCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"minExclusive", facets.minExclusive, getStringValue(fBase.fMinExclusive)});
}
if (result == 0) {
needCheckBase = false;
}
}
if (needCheckBase) {
try {
fBase.validate(context, tempInfo);
} catch (InvalidDatatypeValueException ide) {
reportError("FacetValueFromBase", new Object[]{facets.minExclusive, "minExclusive"});
}
}
}
}
// minInclusive
if ((presentFacet & FACET_MININCLUSIVE) != 0) {
if ((allowedFacet & FACET_MININCLUSIVE) == 0) {
reportError("cos-applicable-facets", new Object[]{"minInclusive"});
} else {
try {
fMinInclusive = getActualValue(facets.minInclusive, context, tempInfo);
fFacetsDefined |= FACET_MININCLUSIVE;
if ((fixedFacet & FACET_MININCLUSIVE) != 0)
fFixedFacet |= FACET_MININCLUSIVE;
} catch (InvalidDatatypeValueException ide) {
reportError("FacetValueFromBase", new Object[]{facets.minInclusive, "minInclusive"});
}
// minInclusive from base
if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinInclusive);
if ((fBase.fFixedFacet & FACET_MININCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"minInclusive", facets.minInclusive, getStringValue(fBase.fMinInclusive)});
}
if (result == 0) {
needCheckBase = false;
}
}
if (needCheckBase) {
try {
fBase.validate(context, tempInfo);
} catch (InvalidDatatypeValueException ide) {
reportError("FacetValueFromBase", new Object[]{facets.minInclusive, "minInclusive"});
}
}
}
}
// totalDigits
if ((presentFacet & FACET_TOTALDIGITS) != 0) {
if ((allowedFacet & FACET_TOTALDIGITS) == 0) {
reportError("cos-applicable-facets", new Object[]{"totalDigits"});
} else {
fTotalDigits = facets.totalDigits;
fFacetsDefined |= FACET_TOTALDIGITS;
if ((fixedFacet & FACET_TOTALDIGITS) != 0)
fFixedFacet |= FACET_TOTALDIGITS;
}
}
// fractionDigits
if ((presentFacet & FACET_FRACTIONDIGITS) != 0) {
if ((allowedFacet & FACET_FRACTIONDIGITS) == 0) {
reportError("cos-applicable-facets", new Object[]{"fractionDigits"});
} else {
fFractionDigits = facets.fractionDigits;
fFacetsDefined |= FACET_FRACTIONDIGITS;
if ((fixedFacet & FACET_FRACTIONDIGITS) != 0)
fFixedFacet |= FACET_FRACTIONDIGITS;
}
}
// token type: internal use, so do less checking
if (patternType != SPECIAL_PATTERN_NONE) {
fPatternType = patternType;
}
// step 2: check facets against each other: length, bounds
if(fFacetsDefined != 0) {
// check 4.3.1.c1 error: length & (maxLength | minLength)
if((fFacetsDefined & FACET_LENGTH) != 0 ){
if ((fFacetsDefined & FACET_MINLENGTH) != 0 ||
(fFacetsDefined & FACET_MAXLENGTH) != 0 ) {
reportError("length-minLength-maxLength", null);
}
}
// check 4.3.2.c1 must: minLength <= maxLength
if(((fFacetsDefined & FACET_MINLENGTH ) != 0 ) && ((fFacetsDefined & FACET_MAXLENGTH) != 0))
{
if(fMinLength > fMaxLength)
reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fMinLength), Integer.toString(fMaxLength)});
}
// check 4.3.8.c1 error: maxInclusive + maxExclusive
if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
reportError( "maxInclusive-maxExclusive", null);
}
// check 4.3.9.c1 error: minInclusive + minExclusive
if (((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
reportError("minInclusive-minExclusive", null);
}
// check 4.3.7.c1 must: minInclusive <= maxInclusive
if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinInclusive, fMaxInclusive);
if (result != -1 && result != 0)
reportError("minInclusive-less-than-equal-to-maxInclusive", new Object[]{getStringValue(fMinInclusive), getStringValue(fMaxInclusive)});
}
// check 4.3.8.c2 must: minExclusive <= maxExclusive ??? minExclusive < maxExclusive
if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinExclusive, fMaxExclusive);
if (result != -1 && result != 0)
reportError( "minExclusive-less-than-equal-to-maxExclusive", new Object[]{getStringValue(fMinExclusive), getStringValue(fMaxExclusive)});
}
// check 4.3.9.c2 must: minExclusive < maxInclusive
if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && ((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
if (fDVs[fValidationDV].compare(fMinExclusive, fMaxInclusive) != -1)
reportError( "minExclusive-less-than-maxInclusive", new Object[]{getStringValue(fMinExclusive), getStringValue(fMaxInclusive)});
}
// check 4.3.10.c1 must: minInclusive < maxExclusive
if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
if (fDVs[fValidationDV].compare(fMinInclusive, fMaxExclusive) != -1)
reportError( "minInclusive-less-than-maxExclusive", new Object[]{getStringValue(fMinInclusive), getStringValue(fMaxExclusive)});
}
// check 4.3.12.c1 must: fractionDigits <= totalDigits
if (((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) &&
((fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
if (fFractionDigits > fTotalDigits)
reportError( "fractionDigits-totalDigits", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fTotalDigits)});
}
// step 3: check facets against base
// check 4.3.1.c1 error: length & (fBase.maxLength | fBase.minLength)
if ( ((fFacetsDefined & FACET_LENGTH ) != 0 ) ) {
if ((fBase.fFacetsDefined & FACET_MAXLENGTH ) != 0 ||
(fBase.fFacetsDefined & FACET_MINLENGTH ) != 0 ) {
reportError("length-minLength-maxLength", null);
}
else if ( (fBase.fFacetsDefined & FACET_LENGTH) != 0 ) {
// check 4.3.1.c2 error: length != fBase.length
if ( fLength != fBase.fLength )
reportError( "length-valid-restriction", new Object[]{Integer.toString(fLength), Integer.toString(fBase.fLength)});
}
}
// check 4.3.1.c1 error: fBase.length & (maxLength | minLength)
if ( ((fBase.fFacetsDefined & FACET_LENGTH ) != 0 ) ) {
if ((fFacetsDefined & FACET_MAXLENGTH ) != 0 ||
(fFacetsDefined & FACET_MINLENGTH ) != 0 ) {
reportError("length-minLength-maxLength", null);
}
}
// check 4.3.2.c1 must: minLength <= fBase.maxLength
if ( ((fFacetsDefined & FACET_MINLENGTH ) != 0 ) ) {
if ( (fBase.fFacetsDefined & FACET_MAXLENGTH ) != 0 ) {
if ( fMinLength > fBase.fMaxLength ) {
reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fMinLength), Integer.toString(fBase.fMaxLength)});
}
}
else if ( (fBase.fFacetsDefined & FACET_MINLENGTH) != 0 ) {
if ( (fBase.fFixedFacet & FACET_MINLENGTH) != 0 && fMinLength != fBase.fMinLength ) {
reportError( "FixedFacetValue", new Object[]{"minLength", Integer.toString(fMinLength), Integer.toString(fBase.fMinLength)});
}
// check 4.3.2.c2 error: minLength < fBase.minLength
if ( fMinLength < fBase.fMinLength ) {
reportError( "minLength-valid-restriction", new Object[]{Integer.toString(fMinLength), Integer.toString(fBase.fMinLength)});
}
}
}
// check 4.3.2.c1 must: maxLength < fBase.minLength
if ( ((fFacetsDefined & FACET_MAXLENGTH ) != 0 ) && ((fBase.fFacetsDefined & FACET_MINLENGTH ) != 0 )) {
if ( fMaxLength < fBase.fMinLength) {
reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fBase.fMinLength), Integer.toString(fMaxLength)});
}
}
// check 4.3.3.c1 error: maxLength > fBase.maxLength
if ( (fFacetsDefined & FACET_MAXLENGTH) != 0 ) {
if ( (fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 ){
if(( (fBase.fFixedFacet & FACET_MAXLENGTH) != 0 )&& fMaxLength != fBase.fMaxLength ) {
reportError( "FixedFacetValue", new Object[]{"maxLength", Integer.toString(fMaxLength), Integer.toString(fBase.fMaxLength)});
}
if ( fMaxLength > fBase.fMaxLength ) {
reportError( "maxLength-valid-restriction", new Object[]{Integer.toString(fMaxLength), Integer.toString(fBase.fMaxLength)});
}
}
}
/* // check 4.3.7.c2 error:
// maxInclusive > fBase.maxInclusive
// maxInclusive >= fBase.maxExclusive
// maxInclusive < fBase.minInclusive
// maxInclusive <= fBase.minExclusive
if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxInclusive);
if ((fBase.fFixedFacet & FACET_MAXINCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"maxInclusive", getStringValue(fMaxInclusive), getStringValue(fBase.fMaxInclusive)});
}
if (result != -1 && result != 0) {
reportError( "maxInclusive-valid-restriction.1", new Object[]{getStringValue(fMaxInclusive), getStringValue(fBase.fMaxInclusive)});
}
}
if (((fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxExclusive) != -1){
reportError( "maxInclusive-valid-restriction.1", new Object[]{getStringValue(fMaxInclusive), getStringValue(fBase.fMaxExclusive)});
}
if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMinInclusive);
if (result != 1 && result != 0) {
reportError( "maxInclusive-valid-restriction.1", new Object[]{getStringValue(fMaxInclusive), getStringValue(fBase.fMinInclusive)});
}
}
if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMinExclusive ) != 1)
reportError( "maxInclusive-valid-restriction.1", new Object[]{getStringValue(fMaxInclusive), getStringValue(fBase.fMinExclusive)});
}
// check 4.3.8.c3 error:
// maxExclusive > fBase.maxExclusive
// maxExclusive > fBase.maxInclusive
// maxExclusive <= fBase.minInclusive
// maxExclusive <= fBase.minExclusive
if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) {
if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) {
result= fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxExclusive);
if ((fBase.fFixedFacet & FACET_MAXEXCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"maxExclusive", getStringValue(fMaxExclusive), getStringValue(fBase.fMaxExclusive)});
}
if (result != -1 && result != 0) {
reportError( "maxExclusive-valid-restriction.1", new Object[]{getStringValue(fMaxExclusive), getStringValue(fBase.fMaxExclusive)});
}
}
if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
result= fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxInclusive);
if (result != -1 && result != 0) {
reportError( "maxExclusive-valid-restriction.2", new Object[]{getStringValue(fMaxExclusive), getStringValue(fBase.fMaxInclusive)});
}
}
if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMinExclusive ) != 1)
reportError( "maxExclusive-valid-restriction.3", new Object[]{getStringValue(fMaxExclusive), getStringValue(fBase.fMinExclusive)});
if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMinInclusive) != 1)
reportError( "maxExclusive-valid-restriction.4", new Object[]{getStringValue(fMaxExclusive), getStringValue(fBase.fMinInclusive)});
}
// check 4.3.9.c3 error:
// minExclusive < fBase.minExclusive
// minExclusive > fBase.maxInclusive
// minExclusive < fBase.minInclusive
// minExclusive >= fBase.maxExclusive
if (((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
result= fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinExclusive);
if ((fBase.fFixedFacet & FACET_MINEXCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"minExclusive", getStringValue(fMinExclusive), getStringValue(fBase.fMinExclusive)});
}
if (result != 1 && result != 0) {
reportError( "minExclusive-valid-restriction.1", new Object[]{getStringValue(fMinExclusive), getStringValue(fBase.fMinExclusive)});
}
}
if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
result=fDVs[fValidationDV].compare(fMinExclusive, fBase.fMaxInclusive);
if (result != -1 && result != 0) {
reportError( "minExclusive-valid-restriction.2", new Object[]{getStringValue(fMinExclusive), getStringValue(fBase.fMaxInclusive)});
}
}
if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinInclusive);
if (result != 1 && result != 0) {
reportError( "minExclusive-valid-restriction.3", new Object[]{getStringValue(fMinExclusive), getStringValue(fBase.fMinInclusive)});
}
}
if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMinExclusive, fBase.fMaxExclusive) != -1)
reportError( "minExclusive-valid-restriction.4", new Object[]{getStringValue(fMinExclusive), getStringValue(fBase.fMaxExclusive)});
}
// check 4.3.10.c2 error:
// minInclusive < fBase.minInclusive
// minInclusive > fBase.maxInclusive
// minInclusive <= fBase.minExclusive
// minInclusive >= fBase.maxExclusive
if (((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinInclusive);
if ((fBase.fFixedFacet & FACET_MININCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"minInclusive", getStringValue(fMinInclusive), getStringValue(fBase.fMinInclusive)});
}
if (result != 1 && result != 0) {
reportError( "minInclusive-valid-restriction.1", new Object[]{getStringValue(fMinInclusive), getStringValue(fBase.fMinInclusive)});
}
}
if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
result=fDVs[fValidationDV].compare(fMinInclusive, fBase.fMaxInclusive);
if (result != -1 && result != 0) {
reportError( "minInclusive-valid-restriction.2", new Object[]{getStringValue(fMinInclusive), getStringValue(fBase.fMaxInclusive)});
}
}
if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinExclusive ) != 1)
reportError( "minInclusive-valid-restriction.3", new Object[]{getStringValue(fMinInclusive), getStringValue(fBase.fMinExclusive)});
if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMinInclusive, fBase.fMaxExclusive) != -1)
reportError( "minInclusive-valid-restriction.4", new Object[]{getStringValue(fMinInclusive), getStringValue(fBase.fMaxExclusive)});
}
*/
// check 4.3.11.c1 error: totalDigits > fBase.totalDigits
if (((fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
if ((( fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
if ((fBase.fFixedFacet & FACET_TOTALDIGITS) != 0 && fTotalDigits != fBase.fTotalDigits) {
reportError("FixedFacetValue", new Object[]{"totalDigits", Integer.toString(fTotalDigits), Integer.toString(fBase.fTotalDigits)});
}
if (fTotalDigits > fBase.fTotalDigits) {
reportError( "totalDigits-valid-restriction", new Object[]{Integer.toString(fTotalDigits), Integer.toString(fBase.fTotalDigits)});
}
}
}
// check fixed value for fractionDigits
if (((fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) {
if ((( fBase.fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) {
if ((fBase.fFixedFacet & FACET_FRACTIONDIGITS) != 0 && fFractionDigits != fBase.fFractionDigits) {
reportError("FixedFacetValue", new Object[]{"fractionDigits", Integer.toString(fFractionDigits), Integer.toString( fBase.fFractionDigits)});
}
}
}
// check 4.3.6.c1 error:
// (whiteSpace = preserve || whiteSpace = replace) && fBase.whiteSpace = collapese or
// whiteSpace = preserve && fBase.whiteSpace = replace
if ( (fFacetsDefined & FACET_WHITESPACE) != 0 && (fBase.fFacetsDefined & FACET_WHITESPACE) != 0 ){
if ( (fBase.fFixedFacet & FACET_WHITESPACE) != 0 && fWhiteSpace != fBase.fWhiteSpace ) {
reportError( "FixedFacetValue", new Object[]{"whiteSpace", whiteSpaceValue(fWhiteSpace), whiteSpaceValue(fBase.fWhiteSpace)});
}
if ( (fWhiteSpace == WS_PRESERVE || fWhiteSpace == WS_REPLACE) && fBase.fWhiteSpace == WS_COLLAPSE ){
reportError( "whiteSpace-valid-restriction.1", null);
}
if ( fWhiteSpace == WS_PRESERVE && fBase.fWhiteSpace == WS_REPLACE ){
reportError( "whiteSpace-valid-restriction.2", null);
}
}
}//fFacetsDefined != null
// step 4: inherit other facets from base (including fTokeyType)
// inherit length
if ( (fFacetsDefined & FACET_LENGTH) == 0 && (fBase.fFacetsDefined & FACET_LENGTH) != 0 ) {
fFacetsDefined |= FACET_LENGTH;
fLength = fBase.fLength;
}
// inherit minLength
if ( (fFacetsDefined & FACET_MINLENGTH) == 0 && (fBase.fFacetsDefined & FACET_MINLENGTH) != 0 ) {
fFacetsDefined |= FACET_MINLENGTH;
fMinLength = fBase.fMinLength;
}
// inherit maxLength
if ((fFacetsDefined & FACET_MAXLENGTH) == 0 && (fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 ) {
fFacetsDefined |= FACET_MAXLENGTH;
fMaxLength = fBase.fMaxLength;
}
// inherit pattern
if ( (fBase.fFacetsDefined & FACET_PATTERN) != 0 ) {
if ((fFacetsDefined & FACET_PATTERN) == 0) {
fPattern = new Vector();
fFacetsDefined |= FACET_PATTERN;
}
for (int i = fBase.fPattern.size()-1; i >= 0; i
fPattern.addElement(fBase.fPattern.elementAt(i));
}
// inherit whiteSpace
if ( (fFacetsDefined & FACET_WHITESPACE) == 0 && (fBase.fFacetsDefined & FACET_WHITESPACE) != 0 ) {
fFacetsDefined |= FACET_WHITESPACE;
fWhiteSpace = fBase.fWhiteSpace;
}
// inherit enumeration
if ((fFacetsDefined & FACET_ENUMERATION) == 0 && (fBase.fFacetsDefined & FACET_ENUMERATION) != 0) {
fFacetsDefined |= FACET_ENUMERATION;
fEnumeration = fBase.fEnumeration;
}
// inherit maxExclusive
if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
!((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
fFacetsDefined |= FACET_MAXEXCLUSIVE;
fMaxExclusive = fBase.fMaxExclusive;
}
// inherit maxInclusive
if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0) &&
!((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
fFacetsDefined |= FACET_MAXINCLUSIVE;
fMaxInclusive = fBase.fMaxInclusive;
}
// inherit minExclusive
if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
!((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
fFacetsDefined |= FACET_MINEXCLUSIVE;
fMinExclusive = fBase.fMinExclusive;
}
// inherit minExclusive
if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0) &&
!((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
fFacetsDefined |= FACET_MININCLUSIVE;
fMinInclusive = fBase.fMinInclusive;
}
// inherit totalDigits
if ((( fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0) &&
!((fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
fFacetsDefined |= FACET_TOTALDIGITS;
fTotalDigits = fBase.fTotalDigits;
}
// inherit fractionDigits
if ((( fBase.fFacetsDefined & FACET_FRACTIONDIGITS) != 0)
&& !((fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) {
fFacetsDefined |= FACET_FRACTIONDIGITS;
fFractionDigits = fBase.fFractionDigits;
}
//inherit tokeytype
if ((fPatternType == SPECIAL_PATTERN_NONE ) && (fBase.fPatternType != SPECIAL_PATTERN_NONE)) {
fPatternType = fBase.fPatternType ;
}
// step 5: mark fixed values
fFixedFacet |= fBase.fFixedFacet;
//step 6: setting fundamental facets
caclFundamentalFacets();
} //applyFacets()
/**
* validate a value, and return the compiled form
*/
public Object validate(String content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
if (validatedInfo == null)
validatedInfo = new ValidatedInfo();
// first normalize string value, and convert it to actual value
Object ob = getActualValue(content, context, validatedInfo);
validate(context, validatedInfo);
return ob;
}
/**
* validate an actual value against this DV
*
* @param value the actual value that needs to be validated
* @param context the validation context
* @param validatedInfo used to provide the actual value and member types
*/
public void validate(ValidationContext context, ValidatedInfo validatedInfo)
throws InvalidDatatypeValueException {
// then validate the actual value against the facets
if (context.needFacetChecking() &&
(fFacetsDefined != 0 && fFacetsDefined != FACET_WHITESPACE)) {
checkFacets(validatedInfo);
}
// now check extra rules: for ID/IDREF/ENTITY
if (context.needExtraChecking()) {
checkExtraRules(context, validatedInfo);
}
}
private void checkFacets(ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
Object ob = validatedInfo.actualValue;
String content = validatedInfo.normalizedValue;
int length = fDVs[fValidationDV].getDataLength(ob);
// maxLength
if ( (fFacetsDefined & FACET_MAXLENGTH) != 0 ) {
if ( length > fMaxLength ) {
throw new InvalidDatatypeValueException("cvc-maxLength-valid",
new Object[]{content, Integer.toString(length), Integer.toString(fMaxLength)});
}
}
//minLength
if ( (fFacetsDefined & FACET_MINLENGTH) != 0 ) {
if ( length < fMinLength ) {
throw new InvalidDatatypeValueException("cvc-minLength-valid",
new Object[]{content, Integer.toString(length), Integer.toString(fMinLength)});
}
}
//length
if ( (fFacetsDefined & FACET_LENGTH) != 0 ) {
if ( length != fLength ) {
throw new InvalidDatatypeValueException("cvc-length-valid",
new Object[]{content, Integer.toString(length), Integer.toString(fLength)});
}
}
//enumeration
if ( ((fFacetsDefined & FACET_ENUMERATION) != 0 ) ) {
boolean present = false;
for (int i = 0; i < fEnumeration.size(); i++) {
if (isEqual(ob, fEnumeration.elementAt(i))) {
present = true;
break;
}
}
if(!present){
throw new InvalidDatatypeValueException("cvc-enumeration-valid",
new Object [] {content, fEnumeration.toString()});
}
}
//fractionDigits
if ((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) {
int scale = fDVs[fValidationDV].getFractionDigits(ob);
if (scale > fFractionDigits) {
throw new InvalidDatatypeValueException("cvc-fractionDigits-valid",
new Object[] {content, Integer.toString(scale), Integer.toString(fFractionDigits)});
}
}
//totalDigits
if ((fFacetsDefined & FACET_TOTALDIGITS)!=0) {
int totalDigits = fDVs[fValidationDV].getTotalDigits(ob);
if (totalDigits > fTotalDigits) {
throw new InvalidDatatypeValueException("cvc-totalDigits-valid",
new Object[] {content, Integer.toString(totalDigits), Integer.toString(fTotalDigits)});
}
}
int compare;
//maxinclusive
if ( (fFacetsDefined & FACET_MAXINCLUSIVE) != 0 ) {
compare = fDVs[fValidationDV].compare(ob, fMaxInclusive);
if (compare != -1 && compare != 0) {
throw new InvalidDatatypeValueException("cvc-maxInclusive-valid",
new Object[] {content, fMaxInclusive});
}
}
//maxExclusive
if ( (fFacetsDefined & FACET_MAXEXCLUSIVE) != 0 ) {
compare = fDVs[fValidationDV].compare(ob, fMaxExclusive );
if (compare != -1) {
throw new InvalidDatatypeValueException("cvc-maxExclusive-valid",
new Object[] {content, fMaxExclusive});
}
}
//minInclusive
if ( (fFacetsDefined & FACET_MININCLUSIVE) != 0 ) {
compare = fDVs[fValidationDV].compare(ob, fMinInclusive);
if (compare != 1 && compare != 0) {
throw new InvalidDatatypeValueException("cvc-minInclusive-valid",
new Object[] {content, fMinInclusive});
}
}
//minExclusive
if ( (fFacetsDefined & FACET_MINEXCLUSIVE) != 0 ) {
compare = fDVs[fValidationDV].compare(ob, fMinExclusive);
if (compare != 1) {
throw new InvalidDatatypeValueException("cvc-minExclusive-valid",
new Object[] {content, fMinExclusive});
}
}
}
private void checkExtraRules(ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
Object ob = validatedInfo.actualValue;
if (fVariety == VARIETY_ATOMIC) {
fDVs[fValidationDV].checkExtraRules(ob, context);
} else if (fVariety == VARIETY_LIST) {
Object[] values = (Object[])ob;
if (fItemType.fVariety == VARIETY_UNION) {
XSSimpleTypeDecl[] memberTypes = (XSSimpleTypeDecl[])validatedInfo.memberTypes;
XSSimpleType memberType = validatedInfo.memberType;
for (int i = values.length-1; i >= 0; i
validatedInfo.actualValue = values[i];
validatedInfo.memberType = memberTypes[i];
fItemType.checkExtraRules(context, validatedInfo);
}
validatedInfo.memberType = memberType;
} else { // (fVariety == VARIETY_ATOMIC)
for (int i = values.length-1; i >= 0; i
validatedInfo.actualValue = values[i];
fItemType.checkExtraRules(context, validatedInfo);
}
}
validatedInfo.actualValue = values;
} else { // (fVariety == VARIETY_UNION)
((XSSimpleTypeDecl)validatedInfo.memberType).checkExtraRules(context, validatedInfo);
}
}// checkExtraRules()
//we can still return object for internal use.
private Object getActualValue(String content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException{
if (fVariety == VARIETY_ATOMIC) {
String nvalue;
if (context==null ||context.needToNormalize()) {
nvalue = normalize(content, fWhiteSpace);
} else {
nvalue = content;
}
// validate special kinds of token, in place of old pattern matching
if (fPatternType != SPECIAL_PATTERN_NONE) {
boolean seenErr = false;
if (fPatternType == SPECIAL_PATTERN_NMTOKEN) {
// PATTERN "\\c+"
seenErr = !XMLChar.isValidNmtoken(nvalue);
}
else if (fPatternType == SPECIAL_PATTERN_NAME) {
// PATTERN "\\i\\c*"
seenErr = !XMLChar.isValidName(nvalue);
}
else if (fPatternType == SPECIAL_PATTERN_NCNAME) {
// PATTERN "[\\i-[:]][\\c-[:]]*"
seenErr = !XMLChar.isValidNCName(nvalue);
}
else if (fPatternType == SPECIAL_PATTERN_INTEGER) {
// REVISIT: the pattern is not published yet
// we only need to worry about the period '.'
// other parts are taken care of by the DecimalDV
seenErr = nvalue.indexOf('.') >= 0;
}
if (seenErr) {
throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1",
new Object[]{nvalue, SPECIAL_PATTERN_STRING[fPatternType]});
}
}
if ( (fFacetsDefined & FACET_PATTERN ) != 0 ) {
RegularExpression regex;
for (int idx = fPattern.size()-1; idx >= 0; idx
regex = (RegularExpression)fPattern.elementAt(idx);
if (!regex.matches(nvalue)){
throw new InvalidDatatypeValueException("cvc-pattern-valid",
new Object[]{content, regex});
}
}
}
Object avalue = fDVs[fValidationDV].getActualValue(nvalue, context);
validatedInfo.actualValue = avalue;
validatedInfo.normalizedValue = nvalue;
return avalue;
} else if (fVariety == VARIETY_LIST) {
String nvalue;
if (context==null ||context.needToNormalize()) {
nvalue = normalize(content, fWhiteSpace);
} else {
nvalue = content;
}
StringTokenizer parsedList = new StringTokenizer(nvalue);
int countOfTokens = parsedList.countTokens() ;
Object[] avalue = new Object[countOfTokens];
XSSimpleTypeDecl[] memberTypes = new XSSimpleTypeDecl[countOfTokens];
for(int i = 0 ; i < countOfTokens ; i ++){
// we can't call fItemType.validate(), otherwise checkExtraRules()
// will be called twice: once in fItemType.validate, once in
// validate method of this type.
// so we take two steps to get the actual value:
// 1. fItemType.getActualValue()
// 2. fItemType.chekcFacets()
avalue[i] = fItemType.getActualValue(parsedList.nextToken(), context, validatedInfo);
if (context.needFacetChecking() &&
(fItemType.fFacetsDefined != 0 && fItemType.fFacetsDefined != FACET_WHITESPACE)) {
fItemType.checkFacets(validatedInfo);
}
memberTypes[i] = (XSSimpleTypeDecl)validatedInfo.memberType;
}
validatedInfo.actualValue = avalue;
validatedInfo.normalizedValue = nvalue;
validatedInfo.memberTypes = memberTypes;
return avalue;
} else { // (fVariety == VARIETY_UNION)
for(int i = 0 ; i < fMemberTypes.length; i++) {
try {
// we can't call fMemberType[i].validate(), otherwise checkExtraRules()
// will be called twice: once in fMemberType[i].validate, once in
// validate method of this type.
// so we take two steps to get the actual value:
// 1. fMemberType[i].getActualValue()
// 2. fMemberType[i].chekcFacets()
Object aValue = fMemberTypes[i].getActualValue(content, context, validatedInfo);
if (context.needFacetChecking() &&
(fMemberTypes[i].fFacetsDefined != 0 && fMemberTypes[i].fFacetsDefined != FACET_WHITESPACE)) {
fMemberTypes[i].checkFacets(validatedInfo);
}
validatedInfo.memberType = fMemberTypes[i];
return aValue;
} catch(InvalidDatatypeValueException invalidValue) {
}
}
throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.2",
new Object[]{content, fTypeName});
}
}//getActualValue()
public boolean isEqual(Object value1, Object value2) {
if (fVariety == VARIETY_ATOMIC)
return fDVs[fValidationDV].isEqual(value1,value2);
else if (fVariety == VARIETY_LIST) {
if (!(value1 instanceof Object[]) || !(value2 instanceof Object[]))
return false;
Object[] v1 = (Object[])value1;
Object[] v2 = (Object[])value2;
int count = v1.length;
if (count != v2.length)
return false;
for (int i = 0 ; i < count ; i++) {
if (!fItemType.isEqual(v1[i], v2[i]))
return false;
}//end of loop
//everything went fine.
return true;
} else if (fVariety == VARIETY_UNION) {
for (int i = fMemberTypes.length-1; i >= 0; i
if (fMemberTypes[i].isEqual(value1,value2)){
return true;
}
}
return false;
}
return false;
}//isEqual()
// normalize the string according to the whiteSpace facet
public static String normalize(String content, short ws) {
int len = content == null ? 0 : content.length();
if (len == 0 || ws == WS_PRESERVE)
return content;
StringBuffer sb = new StringBuffer();
if (ws == WS_REPLACE) {
char ch;
// when it's replace, just replace #x9, #xa, #xd by #x20
for (int i = 0; i < len; i++) {
ch = content.charAt(i);
if (ch != 0x9 && ch != 0xa && ch != 0xd)
sb.append(ch);
else
sb.append((char)0x20);
}
} else {
char ch;
int i;
boolean isLeading = true;
// when it's collapse
for (i = 0; i < len; i++) {
ch = content.charAt(i);
// append real characters, so we passed leading ws
if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) {
sb.append(ch);
isLeading = false;
}
else {
// for whitespaces, we skip all following ws
for (; i < len-1; i++) {
ch = content.charAt(i+1);
if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20)
break;
}
// if it's not a leading or tailing ws, then append a space
if (i < len - 1 && !isLeading)
sb.append((char)0x20);
}
}
}
return sb.toString();
}
void reportError(String key, Object[] args) throws InvalidDatatypeFacetException {
throw new InvalidDatatypeFacetException(key, args);
}
private String whiteSpaceValue(short ws){
return WS_FACET_STRING[ws];
}
public String getStringValue(Object value){
if(value != null) {
if (fDVs[fValidationDV] instanceof AbstractDateTimeDV)
return ((AbstractDateTimeDV)fDVs[fValidationDV]).dateToString((int[])value);
else
return value.toString();
} else {
return null;
}
}
public short getOrdered() {
return fOrdered;
}
public boolean getIsBounded(){
return fBounded;
}
public boolean getIsFinite(){
return fFinite;
}
public boolean getIsNumeric(){
return fNumeric;
}
public boolean getIsDefinedFacet(short facetName) {
return (fFacetsDefined & facetName) != 0;
}
public short getDefinedFacets() {
return fFacetsDefined;
}
public boolean getIsFixedFacet(short facetName) {
return (fFixedFacet & facetName) != 0;
}
public short getFixedFacets() {
return fFixedFacet;
}
public String getLexicalFacetValue(short facetName) {
switch (facetName) {
case FACET_LENGTH:
return Integer.toString(fLength);
case FACET_MINLENGTH:
return Integer.toString(fMinLength);
case FACET_MAXLENGTH:
return Integer.toString(fMaxLength);
case FACET_WHITESPACE:
return WS_FACET_STRING[fWhiteSpace];
case FACET_MAXINCLUSIVE:
return getStringValue(fMaxInclusive);
case FACET_MAXEXCLUSIVE:
return getStringValue(fMaxExclusive);
case FACET_MINEXCLUSIVE:
return getStringValue(fMinExclusive);
case FACET_MININCLUSIVE:
return getStringValue(fMinInclusive);
case FACET_TOTALDIGITS:
return Integer.toString(fTotalDigits);
case FACET_FRACTIONDIGITS:
return Integer.toString(fFractionDigits);
}
return null;
}
public Enumeration getLexicalEnumerations() {
int size = fEnumeration.size();
String[] strs = new String[size];
for (int i = 0; i < size; i++)
strs[i] = getStringValue(fEnumeration.elementAt(i));
return new EnumerationImpl(strs, size);
}
public Enumeration getLexicalPatterns() {
int size = fPattern.size();
String[] strs = new String[size];
for (int i = 0; i < size; i++)
strs[i] = ((RegularExpression)fPattern.elementAt(i)).toString();
return new EnumerationImpl(strs, size);
}
public XSAnnotation getAnnotation() {
// REVISIT: SCAPI: to implement
return null;
}
private void caclFundamentalFacets() {
setOrdered();
setNumeric();
setBounded();
setCardinality();
}
private void setOrdered(){
// When {variety} is atomic, {value} is inherited from {value} of {base type definition}. For all primitive types {value} is as specified in the table in Fundamental Facets (C.1).
if(fVariety == VARIETY_ATOMIC){
this.fOrdered = fBase.fOrdered;
}
// When {variety} is list, {value} is false.
else if(fVariety == VARIETY_LIST){
this.fOrdered = ORDERED_FALSE;
}
// When {variety} is union, the {value} is partial unless one of the following:
// 1. If every member of {member type definitions} is derived from a common ancestor other than the simple ur-type, then {value} is the same as that ancestor's ordered facet.
// 2. If every member of {member type definitions} has a {value} of false for the ordered facet, then {value} is false.
else if(fVariety == VARIETY_UNION){
int length = fMemberTypes.length;
// REVISIT: is the length possible to be 0?
if (length == 0) {
this.fOrdered = ORDERED_PARTIAL;
return;
}
// we need to process the first member type before entering the loop
short ancestorId = getPrimitiveDV(fMemberTypes[0].fValidationDV);
boolean commonAnc = ancestorId != DV_ANYSIMPLETYPE;
boolean allFalse = fMemberTypes[0].fOrdered == ORDERED_FALSE;
// for the other member types, check whether the value is false
// and whether they have the same ancestor as the first one
for (int i = 1; i < fMemberTypes.length && (commonAnc || allFalse); i++) {
if (commonAnc)
commonAnc = ancestorId == getPrimitiveDV(fMemberTypes[i].fValidationDV);
if (allFalse)
allFalse = fMemberTypes[i].fOrdered == ORDERED_FALSE;
}
if (commonAnc) {
// REVISIT: all member types should have the same ordered value
// just use the first one. Can we assume this?
this.fOrdered = fMemberTypes[0].fOrdered;
} else if (allFalse) {
this.fOrdered = ORDERED_FALSE;
} else {
this.fOrdered = ORDERED_PARTIAL;
}
}
}//setOrdered
private void setNumeric(){
if(fVariety == VARIETY_ATOMIC){
this.fNumeric = fBase.fNumeric;
}
else if(fVariety == VARIETY_LIST){
this.fNumeric = false;
}
else if(fVariety == VARIETY_UNION){
XSSimpleType[] memberTypes = fMemberTypes;
for(int i = 0 ; i < memberTypes.length ; i++){
if(!memberTypes[i].getIsNumeric() ){
this.fNumeric = false;
return;
}
}
this.fNumeric = true;
}
}//setNumeric
private void setBounded(){
if(fVariety == VARIETY_ATOMIC){
if( (((this.fFacetsDefined & FACET_MININCLUSIVE) != 0) || ((this.fFacetsDefined & FACET_MINEXCLUSIVE) != 0))
&& (((this.fFacetsDefined & FACET_MAXINCLUSIVE) != 0) || ((this.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) ){
this.fBounded = true;
}
else{
this.fBounded = false;
}
}
else if(fVariety == VARIETY_LIST){
if( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ( ((this.fFacetsDefined & FACET_MINLENGTH) != 0 )
&& ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 )) ){
this.fBounded = true;
}
else{
this.fBounded = false;
}
}
else if(fVariety == VARIETY_UNION){
XSSimpleTypeDecl [] memberTypes = this.fMemberTypes;
short ancestorId = 0 ;
if(memberTypes.length > 0){
ancestorId = getPrimitiveDV(memberTypes[0].fValidationDV);
}
for(int i = 0 ; i < memberTypes.length ; i++){
if(!memberTypes[i].getIsBounded() || (ancestorId != getPrimitiveDV(memberTypes[i].fValidationDV)) ){
this.fBounded = false;
return;
}
}
this.fBounded = true;
}
}//setBounded
private boolean specialCardinalityCheck(){
if( (fBase.fValidationDV == XSSimpleTypeDecl.DV_DATE) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GYEARMONTH)
|| (fBase.fValidationDV == XSSimpleTypeDecl.DV_GYEAR) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GMONTHDAY)
|| (fBase.fValidationDV == XSSimpleTypeDecl.DV_GDAY) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GMONTH) ){
return true;
}
return false;
} //specialCardinalityCheck()
private void setCardinality(){
if(fVariety == VARIETY_ATOMIC){
if(fBase.fFinite){
this.fFinite = true;
}
else {// (!fBase.fFinite)
if ( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 )
|| ((this.fFacetsDefined & FACET_TOTALDIGITS) != 0 ) ){
this.fFinite = true;
}
else if( (((this.fFacetsDefined & FACET_MININCLUSIVE) != 0 ) || ((this.fFacetsDefined & FACET_MINEXCLUSIVE) != 0 ))
&& (((this.fFacetsDefined & FACET_MAXINCLUSIVE) != 0 ) || ((this.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0 )) ){
if( ((this.fFacetsDefined & FACET_FRACTIONDIGITS) != 0 ) || specialCardinalityCheck()){
this.fFinite = true;
}
else{
this.fFinite = false;
}
}
else{
this.fFinite = false;
}
}
}
else if(fVariety == VARIETY_LIST){
if( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ( ((this.fFacetsDefined & FACET_MINLENGTH) != 0 )
&& ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 )) ){
this.fFinite = true;
}
else{
this.fFinite = false;
}
}
else if(fVariety == VARIETY_UNION){
XSSimpleType [] memberTypes = fMemberTypes;
for(int i = 0 ; i < memberTypes.length ; i++){
if(!(memberTypes[i].getIsFinite()) ){
this.fFinite = false;
return;
}
}
this.fFinite = true;
}
}//setCardinality
private short getPrimitiveDV(short validationDV){
if (validationDV == DV_ID || validationDV == DV_IDREF || validationDV == DV_ENTITY){
return DV_STRING;
}
else{
return validationDV;
}
}//getPrimitiveDV()
public boolean derivedFrom(XSTypeDefinition ancestor) {
// ancestor is null, retur false
if (ancestor == null)
return false;
// ancestor is anyType, return true
if (ancestor == SchemaGrammar.fAnyType)
return true;
// recursively get base, and compare it with ancestor
XSTypeDefinition type = this;
while (type != ancestor && // compare with ancestor
type != SchemaGrammar.fAnySimpleType) { // reached anySimpleType
type = type.getBaseType();
}
return type == ancestor;
}
public boolean derivedFrom(String ancestorNS, String ancestorName) {
// ancestor is null, retur false
if (ancestorName == null)
return false;
// ancestor is anyType, return true
if (ancestorNS != null &&
ancestorNS.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) &&
ancestorName.equals(SchemaSymbols.ATTVAL_ANYTYPE)) {
return true;
}
// recursively get base, and compare it with ancestor
XSTypeDecl type = this;
while (!(ancestorName.equals(type.getName()) &&
((ancestorNS == null && type.getNamespace() == null) ||
(ancestorNS != null && ancestorNS.equals(type.getNamespace())))) && // compare with ancestor
type != SchemaGrammar.fAnySimpleType) { // reached anySimpleType
type = (XSTypeDecl)type.getBaseType();
}
return type != SchemaGrammar.fAnySimpleType;
}
static final XSSimpleTypeDecl fAnySimpleType = new XSSimpleTypeDecl(null, "anySimpleType", DV_ANYSIMPLETYPE, ORDERED_FALSE, false, true, false);
/**
* Validation context used to validate facet values.
*/
static final ValidationContext fDummyContext = new ValidationContext() {
public boolean needFacetChecking() {
return true;
}
public boolean needExtraChecking() {
return false;
}
public boolean needToNormalize() {
return false;
}
public boolean isEntityDeclared(String name) {
return false;
}
public boolean isEntityUnparsed(String name) {
return false;
}
public boolean isIdDeclared(String name) {
return false;
}
public void addId(String name) {
}
public void addIdRef(String name) {
}
public String getSymbol (String symbol) {
return null;
}
public String getURI(String prefix) {
return null;
}
};
/**
* A wrapper of ValidationContext, to provide a way of switching to a
* different Namespace declaration context.
*/
class ValidationContextImpl implements ValidationContext {
ValidationContext fExternal;
ValidationContextImpl(ValidationContext external) {
fExternal = external;
}
NamespaceContext fNSContext;
void setNSContext(NamespaceContext nsContext) {
fNSContext = nsContext;
}
public boolean needFacetChecking() {
return fExternal.needFacetChecking();
}
public boolean needExtraChecking() {
return fExternal.needExtraChecking();
}
public boolean needToNormalize() {
return fExternal.needToNormalize();
}
public boolean isEntityDeclared (String name) {
return fExternal.isEntityDeclared(name);
}
public boolean isEntityUnparsed (String name) {
return fExternal.isEntityUnparsed(name);
}
public boolean isIdDeclared (String name) {
return fExternal.isIdDeclared(name);
}
public void addId(String name) {
fExternal.addId(name);
}
public void addIdRef(String name) {
fExternal.addIdRef(name);
}
public String getSymbol (String symbol) {
return fExternal.getSymbol(symbol);
}
public String getURI(String prefix) {
if (fNSContext == null)
return fExternal.getURI(prefix);
else
return fNSContext.getURI(prefix);
}
}
public void reset(){
fItemType = null;
fMemberTypes = null;
fTypeName = null;
fTargetNamespace = null;
fFinalSet = 0;
fBase = null;
fVariety = -1;
fValidationDV = -1;
fFacetsDefined = 0;
fFixedFacet = 0;
//for constraining facets
fWhiteSpace = 0;
fLength = -1;
fMinLength = -1;
fMaxLength = -1;
fTotalDigits = -1;
fFractionDigits = -1;
fPattern = null;
fEnumeration = null;
fMaxInclusive = null;
fMaxExclusive = null;
fMinExclusive = null;
fMinInclusive = null;
fPatternType = SPECIAL_PATTERN_NONE;
// REVISIT: reset for fundamental facets
}
} // class XSComplexTypeDecl |
package org.appwork.utils.swing.dialog;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.HashMap;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
import org.appwork.storage.JSonStorage;
import org.appwork.utils.BinaryLogic;
import org.appwork.utils.locale.APPWORKUTILS;
import org.appwork.utils.logging.Log;
import org.appwork.utils.swing.LockPanel;
import org.appwork.utils.swing.SwingUtils;
public abstract class AbstractDialog<T> extends TimerDialog implements ActionListener, WindowListener {
private static final long serialVersionUID = 1831761858087385862L;
private static final HashMap<String, Integer> SESSION_DONTSHOW_AGAIN = new HashMap<String, Integer>();
/**
* @return
*/
private static Integer getSessionDontShowAgainValue(final String key) {
final Integer ret = AbstractDialog.SESSION_DONTSHOW_AGAIN.get(key);
if (ret == null) { return -1; }
return ret;
}
public static void resetDialogInformations() {
try {
AbstractDialog.SESSION_DONTSHOW_AGAIN.clear();
JSonStorage.getStorage("Dialogs").clear();
} catch (final Exception e) {
Log.exception(e);
}
}
protected JButton cancelButton;
private final String cancelOption;
private JPanel defaultButtons;
private JCheckBox dontshowagain;
protected int flagMask;
private final ImageIcon icon;
private boolean initialized = false;
protected JButton okButton;
private final String okOption;
protected JComponent panel;
private int returnBitMask = 0;
public AbstractDialog(final int flag, final String title, final ImageIcon icon, final String okOption, final String cancelOption) {
super(Dialog.getInstance().getParentOwner());
this.flagMask = flag;
this.setTitle(title);
this.icon = BinaryLogic.containsAll(flag, Dialog.STYLE_HIDE_ICON) ? null : icon;
this.okOption = okOption == null ? APPWORKUTILS.ABSTRACTDIALOG_BUTTON_OK.s() : okOption;
this.cancelOption = cancelOption == null ? APPWORKUTILS.ABSTRACTDIALOG_BUTTON_CANCEL.s() : cancelOption;
}
/* this function will init and show the dialog */
private void _init() {
dont: if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
try {
final int i = BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT) ? AbstractDialog.getSessionDontShowAgainValue(this.getDontShowAgainKey()) : JSonStorage.getStorage("Dialogs").get(this.getDontShowAgainKey(), -1);
if (i >= 0) {
// filter saved return value
int ret = i & (Dialog.RETURN_OK | Dialog.RETURN_CANCEL);
// add flags
ret |= Dialog.RETURN_DONT_SHOW_AGAIN | Dialog.RETURN_SKIPPED_BY_DONT_SHOW;
/*
* if LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL or
* LOGIC_DONT_SHOW_AGAIN_IGNORES_OK are used, we check here
* if we should handle the dont show again feature
*/
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL) && BinaryLogic.containsAll(ret, Dialog.RETURN_CANCEL)) {
break dont;
}
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_IGNORES_OK) && BinaryLogic.containsAll(ret, Dialog.RETURN_OK)) {
break dont;
}
this.returnBitMask = ret;
return;
}
} catch (final Exception e) {
Log.exception(e);
}
}
try {
if (Dialog.getInstance().getParentOwner() != null) {
LockPanel.create(Dialog.getInstance().getParentOwner()).lock(500);
}
} catch (final Exception e) {
}
if (Dialog.getInstance().getParentOwner() == null || !Dialog.getInstance().getParentOwner().isShowing()) {
this.setAlwaysOnTop(true);
}
// The Dialog Modal
this.setModal(true);
// Layout manager
this.setLayout(new MigLayout("ins 5", "[]", "[fill,grow][]"));
// Dispose dialog on close
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
this.addWindowListener(this);
// create panel for the dialog's buttons
this.defaultButtons = this.getDefaultButtonPanel();
this.okButton = new JButton(this.okOption);
/*
* We set the focus on the ok button. if no ok button is shown, we set
* the focus on cancel button
*/
JButton focus = this.okButton;
this.cancelButton = new JButton(this.cancelOption);
// add listeners here
this.okButton.addActionListener(this);
this.cancelButton.addActionListener(this);
// add icon if available
if (this.icon != null) {
this.add(new JLabel(this.icon), "split 2,alignx left,aligny center,shrinkx,gapright 10");
}
// Layout the dialog content and add it to the contentpane
this.panel = this.layoutDialogContent();
this.add(this.panel, "pushx,growx,pushy,growy,spanx,aligny center,wrap");
// add the countdown timer
this.add(this.timerLbl, "split 3,growx,hidemode 2");
if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
this.dontshowagain = new JCheckBox(APPWORKUTILS.ABSTRACTDIALOG_STYLE_SHOW_DO_NOT_DISPLAY_AGAIN.s());
this.dontshowagain.setHorizontalAlignment(SwingConstants.TRAILING);
this.dontshowagain.setHorizontalTextPosition(SwingConstants.LEADING);
this.add(this.dontshowagain, "growx,pushx,alignx right,gapleft 20");
} else {
this.add(Box.createHorizontalGlue(), "growx,pushx,alignx right,gapleft 20");
}
this.add(this.defaultButtons, "alignx right,shrinkx");
if ((this.flagMask & Dialog.BUTTONS_HIDE_OK) == 0) {
// Set OK as defaultbutton
this.getRootPane().setDefaultButton(this.okButton);
this.okButton.addHierarchyListener(new HierarchyListener() {
public void hierarchyChanged(final HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) {
final JButton defaultButton = (JButton) e.getComponent();
final JRootPane root = SwingUtilities.getRootPane(defaultButton);
if (root != null) {
root.setDefaultButton(defaultButton);
}
}
}
});
focus = this.okButton;
this.defaultButtons.add(this.okButton, "alignx right,tag ok,sizegroup confirms");
}
if (!BinaryLogic.containsAll(this.flagMask, Dialog.BUTTONS_HIDE_CANCEL)) {
this.defaultButtons.add(this.cancelButton, "alignx right,tag cancel,sizegroup confirms");
if (BinaryLogic.containsAll(this.flagMask, Dialog.BUTTONS_HIDE_OK)) {
this.getRootPane().setDefaultButton(this.cancelButton);
this.cancelButton.requestFocusInWindow();
// focus is on cancel if OK is hidden
focus = this.cancelButton;
}
}
this.addButtons(this.defaultButtons);
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_COUNTDOWN)) {
// show timer
this.initTimer(Dialog.getInstance().getCoundownTime());
} else {
this.timerLbl.setVisible(false);
}
// pack dialog
this.invalidate();
// this.setMinimumSize(this.getPreferredSize());
this.pack();
this.setResizable(true);
this.setMinimumSize(this.getPreferredSize());
this.toFront();
if (this.getDesiredSize() != null) {
this.setSize(this.getDesiredSize());
}
if (Dialog.getInstance().getParentOwner() == null || !Dialog.getInstance().getParentOwner().isDisplayable() || !Dialog.getInstance().getParentOwner().isVisible()) {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(new Point((int) (screenSize.getWidth() - this.getWidth()) / 2, (int) (screenSize.getHeight() - this.getHeight()) / 2));
} else if (Dialog.getInstance().getParentOwner().getExtendedState() == Frame.ICONIFIED) {
// dock dialog at bottom right if mainframe is not visible
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(new Point((int) (screenSize.getWidth() - this.getWidth() - 20), (int) (screenSize.getHeight() - this.getHeight() - 60)));
} else {
this.setLocation(SwingUtils.getCenter(Dialog.getInstance().getParentOwner(), this));
}
// register an escape listener to cancel the dialog
final KeyStroke ks = KeyStroke.getKeyStroke("ESCAPE");
focus.getInputMap().put(ks, "ESCAPE");
focus.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, "ESCAPE");
focus.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "ESCAPE");
focus.getActionMap().put("ESCAPE", new AbstractAction() {
private static final long serialVersionUID = -6666144330707394562L;
public void actionPerformed(final ActionEvent e) {
AbstractDialog.this.dispose();
}
});
focus.requestFocus();
this.packed();
this.setVisible(true);
/*
* workaround a javabug that forces the parentframe to stay always on
* top
*/
if (Dialog.getInstance().getParentOwner() != null) {
Dialog.getInstance().getParentOwner().setAlwaysOnTop(true);
Dialog.getInstance().getParentOwner().setAlwaysOnTop(false);
}
}
/*
* (non-Javadoc)
*
* @seeorg.appwork.utils.event.Event.ActionListener#actionPerformed(com.
* rapidshare.utils.event.Event.ActionEvent)
*/
public void actionPerformed(final ActionEvent e) {
if (e.getSource() == this.okButton) {
this.setReturnmask(true);
} else if (e.getSource() == this.cancelButton) {
this.setReturnmask(false);
}
this.dispose();
}
/**
* Overwrite this method to add additional buttons
*/
protected void addButtons(final JPanel buttonBar) {
}
/**
* called when user closes the window
*
* @return <code>true</code>, if and only if the dialog should be closeable
**/
public boolean closeAllowed() {
return true;
}
protected abstract T createReturnValue();
/**
* This method has to be called to display the dialog. make sure that all
* settings have beens et before, becvause this call very likly display a
* dialog that blocks the rest of the gui until it is closed
*/
public AbstractDialog<T> displayDialog() {
if (this.initialized) { return this; }
this.initialized = true;
this._init();
return this;
}
@Override
public void dispose() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
try {
if (Dialog.getInstance().getParentOwner() != null) {
LockPanel.create(Dialog.getInstance().getParentOwner()).unlock(300);
}
} catch (final AWTException e1) {
}
super.dispose();
}
/**
* @return
*/
protected JPanel getDefaultButtonPanel() {
return new JPanel(new MigLayout("ins 0", "[fill,grow]", "[fill,grow]"));
}
/**
* should be overwritten and return a Dimension of the dialog should have a
* special size
*
* @return
*/
protected Dimension getDesiredSize() {
return null;
}
/**
* Create the key to save the don't showmagain state in database. should be
* overwritten in same dialogs. by default, the dialogs get differed by
* their title and their classname
*
* @return
*/
protected String getDontShowAgainKey() {
return "ABSTRACTDIALOG_DONT_SHOW_AGAIN_" + this.getClass().getSimpleName() + "_" + this.toString();
}
/**
* Return the returnbitmask
*
* @return
*/
public int getReturnmask() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
return this.returnBitMask;
}
public T getReturnValue() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
return this.createReturnValue();
}
/**
* This method has to be overwritten to implement custom content
*
* @return musst return a JComponent
*/
abstract public JComponent layoutDialogContent();
/**
* Handle timeout
*/
@Override
protected void onTimeout() {
this.setReturnmask(false);
this.returnBitMask |= Dialog.RETURN_TIMEOUT;
this.dispose();
}
/**
* may be overwritten to set focus to special components etc.
*/
protected void packed() {
}
/**
* Sets the returnvalue and saves the don't show again states to the
* database
*
* @param b
*/
protected void setReturnmask(final boolean b) {
this.returnBitMask = b ? Dialog.RETURN_OK : Dialog.RETURN_CANCEL;
if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
if (this.dontshowagain.isSelected() && this.dontshowagain.isEnabled()) {
this.returnBitMask |= Dialog.RETURN_DONT_SHOW_AGAIN;
try {
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT)) {
AbstractDialog.SESSION_DONTSHOW_AGAIN.put(this.getDontShowAgainKey(), this.returnBitMask);
} else {
JSonStorage.getStorage("Dialogs").put(this.getDontShowAgainKey(), this.returnBitMask);
}
} catch (final Exception e) {
Log.exception(e);
}
}
}
}
/**
* Returns an id of the dialog based on it's title;
*/
@Override
public String toString() {
return ("dialog-" + this.getTitle()).replaceAll("\\W", "_");
}
public void windowActivated(final WindowEvent arg0) {
}
public void windowClosed(final WindowEvent arg0) {
}
public void windowClosing(final WindowEvent arg0) {
if (this.closeAllowed()) {
this.returnBitMask |= Dialog.RETURN_CLOSED;
this.dispose();
}
}
public void windowDeactivated(final WindowEvent arg0) {
}
public void windowDeiconified(final WindowEvent arg0) {
}
public void windowIconified(final WindowEvent arg0) {
}
public void windowOpened(final WindowEvent arg0) {
}
} |
package org.biojava.bio.seq.db;
import java.util.Set;
public interface SequenceDBInstallation {
/**
* Return all sequence dbs available in this sequence db
* installation. This is not just the set of sequence dbs already
* returned by getSequenceDB() but the entire set of sequence dbs
* supported by this object.
*
* @return a set of SequenceDB objects which may be empty. An
* implementation may also return null if it is not at all possible
* to determine which sequence dbs are part of this installation.
*/
public Set getSequenceDBs();
/**
* <p>
* Return the SequenceDB for the given identifier. The identifier
* can (but need not) be the name of the sequence db. An
* implementation may support any number of identifiers to
* (uniquely) identify a particular sequence db - but the name of
* the sequence db (returned by SequenceDB.getName()) must always be
* among them.
* </p>
*
* <p>
* If the sequence db identified by the given identifier has not
* been requested through this object, it will be created and
* returned (hence this method is a factory method). If the sequence
* db identified by the given identifier has already been requested,
* the same object is returned.
* </p>
*
* @param identifier the string that identifies the sequence db. May
* not be null.
*
* @return the SequenceDB object that matches the given identifier
* or null if no such SequenceDB object could be found. (It is the
* responsibility of the implementation to take care that all
* identifiers are unique so if it turns out that the given
* identifier identifies more than one sequence db, this method
* should throw a RuntimeException.)
*/
public SequenceDB getSequenceDB(String identifier);
/**
* <code>addSequenceDB</code> adds a new <code>SequenceDB</code>
* under its own identifier which will additionally be recognised
* by the set of other identifiers. It is up to the implementation
* as to how conflicting identifiers are handled.
*
* @param sequenceDB a <code>SequenceDB</code>.
* @param otherIdentifiers a <code>Set</code>.
*/
public void addSequenceDB(SequenceDB sequenceDB, Set otherIdentifiers);
} |
package org.encog.neural.networks.layers;
import org.encog.neural.activation.ActivationFunction;
import org.encog.neural.activation.ActivationTANH;
import org.encog.neural.data.NeuralData;
import org.encog.neural.data.basic.BasicNeuralData;
import org.encog.persist.Persistor;
import org.encog.persist.persistors.ContextLayerPersistor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implements a context layer. A context layer is used to implement a simple
* recurrent neural network, such as an Elman or Jordan neural network. The
* context layer has a short-term memory. The context layer accept input, and
* provide the same data as output on the next cycle. This continues, and the
* context layer's output "one step" out of sync with the input.
*
* @author jheaton
*
*/
public class ContextLayer extends BasicLayer {
/**
* The serial id.
*/
private static final long serialVersionUID = -5588659547177460637L;
/**
* The context data that this layer will store.
*/
private final NeuralData context;
/**
* The logging object.
*/
@SuppressWarnings("unused")
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Default constructor, mainly so the workbench can easily create a default
* layer.
*/
public ContextLayer() {
this(1);
}
/**
* Construct a context layer with the parameters specified.
* @param thresholdFunction The threshold function to use.
* @param hasThreshold Does this layer have thresholds?
* @param neuronCount The neuron count to use.
*/
public ContextLayer(final ActivationFunction thresholdFunction,
final boolean hasThreshold, final int neuronCount) {
super(thresholdFunction, hasThreshold, neuronCount);
this.context = new BasicNeuralData(neuronCount);
}
/**
* Construct a default context layer that has the TANH activation function
* and the specified number of neurons. Use threshold values.
* @param neuronCount The number of neurons on this layer.
*/
public ContextLayer(final int neuronCount) {
this(new ActivationTANH(), true, neuronCount);
}
/**
* Create a persistor for this layer.
*
* @return The new persistor.
*/
@Override
public Persistor createPersistor() {
return new ContextLayerPersistor();
}
/**
* Called to process input from the previous layer. Simply store the
* output in the context.
* @param pattern The pattern to store in the context.
*/
@Override
public void process(final NeuralData pattern) {
for (int i = 0; i < pattern.size(); i++) {
this.context.setData(i, pattern.getData(i));
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("Updated ContextLayer to {}", pattern);
}
}
/**
* Called to get the output from this layer when called in a recurrent
* manor. Simply return the context that was kept from the last iteration.
* @return The recurrent output.
*/
@Override
public NeuralData recur() {
return this.context;
}
public NeuralData getContext()
{
return this.context;
}
} |
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.ensembl.healthcheck.AssemblyNameInfo;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.Utils;
/**
* Checks the metadata table to make sure it is OK. Only one meta table at a
* time is done here; checks for the consistency of the meta table across
* species are done in MetaCrossSpecies.
*/
public class Meta extends SingleDatabaseTestCase {
// format for genebuild.version
private static final String GBV_REGEXP = "[0-9]{4}[a-zA-Z]*";
/**
* Creates a new instance of CheckMetaDataTableTestCase
*/
public Meta() {
addToGroup("post_genebuild");
addToGroup("release");
setDescription("Check that the meta table exists, has data, the entries correspond to the "
+ "database name, and that the values in assembly.type match what's in the meta table");
}
/**
* Check various aspects of the meta table.
*
* @param dbre
* The database to check.
* @return True if the test passed.
*/
public boolean run(final DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
result &= checkTableExists(con);
result &= tableHasRows(con);
if (dbre.getType() == DatabaseType.CORE) {
result &= checkKeysPresent(con);
}
result &= checkSpeciesClassification(dbre);
result &= checkAssemblyMapping(con);
result &= checkTaxonomyID(dbre);
result &= checkGenebuildVersion(con);
result &= checkCoordSystemTableCases(con);
if (dbre.getType() == DatabaseType.CORE) {
result &= checkGenebuildID(con);
}
result &= checkSchemaVersionDBName(dbre);
// Use an AssemblyNameInfo object to get the assembly information
AssemblyNameInfo assembly = new AssemblyNameInfo(con);
String metaTableAssemblyDefault = assembly.getMetaTableAssemblyDefault();
logger.finest("assembly.default from meta table: " + metaTableAssemblyDefault);
String dbNameAssemblyVersion = assembly.getDBNameAssemblyVersion();
logger.finest("Assembly version from DB name: " + dbNameAssemblyVersion);
String metaTableAssemblyVersion = assembly.getMetaTableAssemblyVersion();
logger.finest("meta table assembly version: " + metaTableAssemblyVersion);
String metaTableAssemblyPrefix = assembly.getMetaTableAssemblyPrefix();
logger.finest("meta table assembly prefix: " + metaTableAssemblyPrefix);
if (metaTableAssemblyVersion == null || metaTableAssemblyDefault == null || metaTableAssemblyPrefix == null
|| dbNameAssemblyVersion == null) {
ReportManager.problem(this, con, "Cannot get all information from meta table - check for null values");
} else {
// check that assembly.default matches the version of the coord_system
// with the lowest
// rank value
// String lowestRankCS = getRowColumnValue(con,
// "SELECT version FROM coord_system WHERE version IS NOT NULL ORDER BY
// rank DESC LIMIT 1");
// if (!lowestRankCS.equals(metaTableAssemblyDefault)) {
// if (lowestRankCS.length() > 0) {
// ReportManager.problem(this, con, "assembly.default from meta table is "
// + metaTableAssemblyDefault
// + " but lowest ranked coordinate system has version " + lowestRankCS);
// } else {
// ReportManager
// .problem(
// this,
// con,
// "assembly.default from meta table is "
// + metaTableAssemblyDefault
// + " but lowest ranked coordinate system has blank or missing version.
// Note lowest ranked == has HIGHEST numerical rank value");
// result &= checkAssemblyVersion(con, dbNameAssemblyVersion,
// metaTableAssemblyVersion);
// Check that assembly prefix is valid and corresponds to this species
// Prefix is OK as long as it starts with the valid one
Species dbSpecies = dbre.getSpecies();
String correctPrefix = Species.getAssemblyPrefixForSpecies(dbSpecies);
if (correctPrefix == null) {
logger.info("Can't get correct assembly prefix for " + dbSpecies.toString());
} else {
if (metaTableAssemblyPrefix != null) {
if (!metaTableAssemblyPrefix.toUpperCase().startsWith(correctPrefix.toUpperCase())) {
ReportManager.problem(this, con, "Database species is " + dbSpecies + " but assembly prefix " + metaTableAssemblyPrefix
+ " should have prefix beginning with " + correctPrefix);
result = false;
} else {
ReportManager.correct(this, con, "Meta table assembly prefix (" + metaTableAssemblyPrefix + ") is correct for "
+ dbSpecies);
}
} else {
ReportManager.problem(this, con, "Can't get assembly prefix from meta table");
}
}
}
return result;
} // run
private boolean checkTableExists(Connection con) {
boolean result = true;
if (!checkTableExists(con, "meta")) {
result = false;
ReportManager.problem(this, con, "Meta table not present");
} else {
ReportManager.correct(this, con, "Meta table present");
}
return result;
}
private boolean tableHasRows(Connection con) {
boolean result = true;
int rows = countRowsInTable(con, "meta");
if (rows == 0) {
result = false;
ReportManager.problem(this, con, "meta table is empty");
} else {
ReportManager.correct(this, con, "meta table has data");
}
return result;
}
private boolean checkKeysPresent(Connection con) {
boolean result = true;
// check that there are species, classification and taxonomy_id entries
// also assembly.name, assembly.date, species.classification - needed by the
// website
String[] metaKeys = { "assembly.default", "species.classification", "species.common_name", "species.taxonomy_id",
"assembly.name", "assembly.date", "species.description" };
for (int i = 0; i < metaKeys.length; i++) {
String metaKey = metaKeys[i];
int rows = getRowCount(con, "SELECT COUNT(*) FROM meta WHERE meta_key='" + metaKey + "'");
if (rows == 0) {
result = false;
ReportManager.problem(this, con, "No entry in meta table for " + metaKey);
} else {
ReportManager.correct(this, con, metaKey + " entry present");
}
}
return result;
}
private boolean checkSpeciesClassification(DatabaseRegistryEntry dbre) {
boolean result = true;
String dbName = dbre.getName();
Connection con = dbre.getConnection();
// Check that species.classification matches database name
String[] metaTableSpeciesGenusArray = getColumnValues(con,
"SELECT LCASE(meta_value) FROM meta WHERE meta_key='species.classification' ORDER BY meta_id LIMIT 2");
// if all is well, metaTableSpeciesGenusArray should contain the
// species and genus
// (in that order) from the meta table
if (metaTableSpeciesGenusArray != null && metaTableSpeciesGenusArray.length == 2 && metaTableSpeciesGenusArray[0] != null
&& metaTableSpeciesGenusArray[1] != null) {
String[] dbNameGenusSpeciesArray = dbName.split("_");
String dbNameGenusSpecies = dbNameGenusSpeciesArray[0] + "_" + dbNameGenusSpeciesArray[1];
String metaTableGenusSpecies = metaTableSpeciesGenusArray[1] + "_" + metaTableSpeciesGenusArray[0];
logger.finest("Classification from DB name:" + dbNameGenusSpecies + " Meta table: " + metaTableGenusSpecies);
if (!dbNameGenusSpecies.equalsIgnoreCase(metaTableGenusSpecies)) {
result = false;
// warn(con, "Database name does not correspond to
// species/genus data from meta
// table");
ReportManager.problem(this, con, "Database name does not correspond to species/genus data from meta table");
} else {
ReportManager.correct(this, con, "Database name corresponds to species/genus data from meta table");
}
} else {
// logger.warning("Cannot get species information from meta
// table");
ReportManager.problem(this, con, "Cannot get species information from meta table");
}
return result;
}
private boolean checkAssemblyMapping(Connection con) {
boolean result = true;
// Check formatting of assembly.mapping entries; should be of format
// coord_system1{:default}|coord_system2{:default} with optional third
// coordinate system
// and all coord systems should be valid from coord_system
// can also have # instead of | as used in unfinished contigs etc
Pattern assemblyMappingPattern = Pattern
.compile("^([a-zA-Z0-9.]+)(:[a-zA-Z0-9._]+)?[\\|#]([a-zA-Z0-9._]+)(:[a-zA-Z0-9._]+)?([\\|#]([a-zA-Z0-9.]+)(:[a-zA-Z0-9._]+)?)?$");
String[] validCoordSystems = getColumnValues(con, "SELECT name FROM coord_system");
String[] mappings = getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.mapping'");
for (int i = 0; i < mappings.length; i++) {
Matcher matcher = assemblyMappingPattern.matcher(mappings[i]);
if (!matcher.matches()) {
result = false;
ReportManager.problem(this, con, "Coordinate system mapping " + mappings[i] + " is not in the correct format");
} else {
// if format is OK, check coord systems are valid
boolean valid = true;
String cs1 = matcher.group(1);
String cs2 = matcher.group(3);
String cs3 = matcher.group(6);
if (!Utils.stringInArray(cs1, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Source co-ordinate system " + cs1 + " is not in the coord_system table");
}
if (!Utils.stringInArray(cs2, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Target co-ordinate system " + cs2 + " is not in the coord_system table");
}
// third coordinate system is optional
if (cs3 != null && !Utils.stringInArray(cs3, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Third co-ordinate system in mapping (" + cs3 + ") is not in the coord_system table");
}
if (valid) {
ReportManager.correct(this, con, "Coordinate system mapping " + mappings[i] + " is OK");
}
result &= valid;
// check that coord systems are specified in lower-case
result &= checkCoordSystemCase(con, cs1, "meta assembly.mapping");
result &= checkCoordSystemCase(con, cs2, "meta assembly.mapping");
result &= checkCoordSystemCase(con, cs3, "meta assembly.mapping");
}
}
return result;
}
/**
* @return true if cs is all lower case (or null), false otherwise.
*/
private boolean checkCoordSystemCase(Connection con, String cs, String desc) {
if (cs == null) {
return true;
}
boolean result = true;
if (cs.equals(cs.toLowerCase())) {
ReportManager.correct(this, con, "Co-ordinate system name " + cs + " all lower case in " + desc);
result = true;
} else {
ReportManager.problem(this, con, "Co-ordinate system name " + cs + " is not all lower case in " + desc);
result = false;
}
return result;
}
/**
* Check that all coord systems in the coord_system table are lower case.
*/
private boolean checkCoordSystemTableCases(Connection con) {
// TODO - table name in report
boolean result = true;
String[] coordSystems = getColumnValues(con, "SELECT name FROM coord_system");
for (int i = 0; i < coordSystems.length; i++) {
result &= checkCoordSystemCase(con, coordSystems[i], "coord_system");
}
return result;
}
private boolean checkTaxonomyID(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// Check that the taxonomy ID matches a known one.
// The taxonomy ID-species mapping is held in the Species class.
Species species = dbre.getSpecies();
String dbTaxonID = getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='species.taxonomy_id'");
logger.finest("Taxonomy ID from database: " + dbTaxonID);
if (dbTaxonID.equals(Species.getTaxonomyID(species))) {
ReportManager.correct(this, con, "Taxonomy ID " + dbTaxonID + " is correct for " + species.toString());
} else {
result = false;
ReportManager.problem(this, con, "Taxonomy ID " + dbTaxonID + " in database is not correct - should be "
+ Species.getTaxonomyID(species) + " for " + species.toString());
}
return result;
}
private boolean checkGenebuildVersion(Connection con) {
String gbv = getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.version'");
logger.finest("genebuild.version from database: " + gbv);
if (gbv == null || gbv.length() == 0) {
ReportManager.problem(this, con, "No genebuild.version entry in meta table");
return false;
} else {
if (!gbv.matches(GBV_REGEXP)) {
ReportManager.problem(this, con, "genebuild.version " + gbv + " is not in correct format - should match " + GBV_REGEXP);
return false;
} else {
int year = Integer.parseInt(gbv.substring(0, 2));
if (year < 0 || year > 99) {
ReportManager.problem(this, con, "Year part of genebuild.version (" + year + ") is incorrect");
return false;
}
int month = Integer.parseInt(gbv.substring(2, 4));
if (month < 1 || month > 12) {
ReportManager.problem(this, con, "Month part of genebuild.version (" + month + ") is incorrect");
return false;
}
}
}
ReportManager.correct(this, con, "genebuild.version " + gbv + " is present & in a valid format");
return true;
}
private boolean checkGenebuildID(Connection con) {
String gbid = getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.id'");
logger.finest("genebuild.id from database: " + gbid);
if (gbid == null || gbid.length() == 0) {
ReportManager.problem(this, con, "No genebuild.id entry in meta table");
return false;
} else if (!gbid.matches("[0-9]+")) {
ReportManager.problem(this, con, "genebuild.id " + gbid + " is not numeric");
return false;
}
ReportManager.correct(this, con, "genebuild.id " + gbid + " is present and numeric");
return true;
}
/**
* Check that the schema_version in the meta table is present and matches the
* database name.
*/
private boolean checkSchemaVersionDBName(DatabaseRegistryEntry dbre) {
boolean result = true;
// get version from database name
String dbNameVersion = dbre.getSchemaVersion();
logger.finest("Schema version from database name: " + dbNameVersion);
// get version from meta table
Connection con = dbre.getConnection();
if (dbNameVersion == null) {
ReportManager.warning(this, con, "Can't deduce schema version from database name.");
return false;
}
String schemaVersion = getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='schema_version'");
logger.finest("schema_version from meta table: " + schemaVersion);
if (schemaVersion == null || schemaVersion.length() == 0) {
ReportManager.problem(this, con, "No schema_version entry in meta table");
return false;
} else if (!schemaVersion.matches("[0-9]+")) {
ReportManager.problem(this, con, "Meta schema_version " + schemaVersion + " is not numeric");
return false;
} else if (!dbNameVersion.equals(schemaVersion)) {
ReportManager.problem(this, con, "Meta schema_version " + schemaVersion
+ " does not match version inferred from database name (" + dbNameVersion + ")");
return false;
} else {
ReportManager.correct(this, con, "schema_version " + schemaVersion + " matches database name version " + dbNameVersion);
}
return result;
}
/**
* Check that the assembly_version in the meta table is present and matches
* the database name.
*/
private boolean checkAssemblyVersion(Connection con, String dbNameAssemblyVersion, String metaTableAssemblyVersion) {
boolean result = true;
if (metaTableAssemblyVersion == null || metaTableAssemblyVersion.length() == 0) {
ReportManager.problem(this, con, "No assembly_version entry in meta table");
return false;
} else if (!dbNameAssemblyVersion.equals(metaTableAssemblyVersion)) {
ReportManager.problem(this, con, "Meta assembly_version " + metaTableAssemblyVersion
+ " does not match version inferred from database name (" + dbNameAssemblyVersion + ")");
return false;
} else {
ReportManager.correct(this, con, "assembly_version " + metaTableAssemblyVersion + " matches database name version "
+ dbNameAssemblyVersion);
}
return result;
}
} // Meta |
package org.exist.storage.io;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.exist.util.ByteArray;
import org.exist.util.FastByteBuffer;
/**
* A byte array output stream using variable byte encoding.
*
* @author wolf
*/
public class VariableByteOutputStream extends OutputStream {
protected FastByteBuffer buf;
private final byte[] temp = new byte[5];
public VariableByteOutputStream() {
super();
buf = new FastByteBuffer(9);
}
public VariableByteOutputStream(int size) {
super();
buf = new FastByteBuffer(size);
}
public void clear() {
buf.setLength(0);
}
public void close() throws IOException {
buf = null;
}
public int size() {
return buf.length();
}
public void flush() throws IOException {
}
public int position() {
return buf.size();
}
public byte[] toByteArray() {
byte[] b = new byte[buf.size()];
buf.copyTo(b, 0);
return b;
}
public ByteArray data() {
return buf;
}
public void write(int b) throws IOException {
buf.append((byte) b);
}
public void write(byte[] b) {
buf.append(b);
}
public void write(byte[] b, int off, int len) throws IOException {
buf.append(b, off, len);
}
public void write(ByteArray b) {
b.copyTo(buf);
}
public void writeByte(byte b) {
buf.append(b);
}
public void writeShort(int s) {
while ((s & ~0177) != 0) {
buf.append((byte) ((s & 0177) | 0200));
s >>>= 7;
}
buf.append((byte) s);
}
public void writeInt(int i) {
int count = 0;
while ((i & ~0177) != 0) {
temp[count++] = (byte) ((i & 0177) | 0200);
i >>>= 7;
}
temp[count++] = (byte) i;
buf.append(temp, 0, count);
}
public void writeFixedInt(int i) {
temp[0] = (byte) ( ( i >>> 0 ) & 0xff );
temp[1] = (byte) ( ( i >>> 8 ) & 0xff );
temp[2] = (byte) ( ( i >>> 16 ) & 0xff );
temp[3] = (byte) ( ( i >>> 24 ) & 0xff );
buf.append(temp, 0, 4);
}
public void writeFixedInt(int position, int i) {
buf.set(position, (byte) ( ( i >>> 0 ) & 0xff ));
buf.set(position + 1, (byte) ( ( i >>> 8 ) & 0xff ));
buf.set(position + 2, (byte) ( ( i >>> 16 ) & 0xff ));
buf.set(position + 3, (byte) ( ( i >>> 24 ) & 0xff ));
}
public void writeInt(int position, int i) {
while ((i & ~0177) != 0) {
buf.set(position++, (byte) ((i & 0177) | 0200));
i >>>= 7;
}
buf.set(position, (byte) i);
}
public void writeLong(long l) {
while ((l & ~0177) != 0) {
buf.append((byte) ((l & 0177) | 0200));
l >>>= 7;
}
buf.append((byte) l);
}
public void writeFixedLong(long l) {
buf.append((byte) ((l >>> 56) & 0xff));
buf.append((byte) ((l >>> 48) & 0xff));
buf.append((byte) ((l >>> 40) & 0xff));
buf.append((byte) ((l >>> 32) & 0xff));
buf.append((byte) ((l >>> 24) & 0xff));
buf.append((byte) ((l >>> 16) & 0xff));
buf.append((byte) ((l >>> 8) & 0xff));
buf.append((byte) ((l >>> 0) & 0xff));
}
public void writeUTF(String s) throws IOException {
byte[] data = null;
try {
data = s.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
data = s.getBytes();
}
writeInt(data.length);
write(data, 0, data.length);
}
} |
package org.griphyn.cPlanner.common;
import org.griphyn.cPlanner.classes.NameValue;
import org.griphyn.common.catalog.transformation.TCMode;
import org.griphyn.common.util.VDSProperties;
import org.griphyn.common.util.Boolean;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.Collections;
import java.util.List;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.Set;
import java.util.HashSet;
/**
* A Central Properties class that keeps track of all the properties used by
* Pegasus. All other classes access the methods in this class to get the value
* of the property. It access the VDSProperties class to read the property file.
*
* @author Karan Vahi
* @author Gaurang Mehta
*
* @version $Revision$
*
* @see org.griphyn.common.util.VDSProperties
*/
public class PegasusProperties {
//Replica Catalog Constants
public static final String DEFAULT_RC_COLLECTION = "GriphynData";
public static final String DEFAULT_RLI_URL = null;
public static final String DEFAULT_RLS_QUERY_MODE = "bulk";
public static final String DEFAULT_RLS_EXIT_MODE = "error";
public static final String DEFAULT_REPLICA_MODE = "rls";
public static final String DEFAULT_RLS_QUERY_ATTRIB = "false";
public static final String DEFAULT_LRC_IGNORE_URL = null;
public static final String DEFAULT_RLS_TIMEOUT = "30";
public static final String DEFAULT_EXEC_DIR = "";
public static final String DEFAULT_STORAGE_DIR = "";
public static final String DEFAULT_TC_MODE = TCMode.DEFAULT_TC_CLASS;
public static final String DEFAULT_POOL_MODE = "XML";
public static final String DEFAULT_CONDOR_BIN_DIR = "";
public static final String DEFAULT_CONDOR_CONFIG_DIR = "";
public static final String DEFAULT_POSTSCRIPT_MODE = "none";
public static final String POOL_CONFIG_FILE = "sites.";
public static final String CONDOR_KICKSTART = "kickstart-condor";
//transfer constants
public static final String DEFAULT_TRANSFER_IMPLEMENTATION = "Transfer";
public static final String DEFAULT_SETUP_TRANSFER_IMPLEMENTATION = "GUC";
public static final String DEFAULT_TRANSFER_REFINER = "Default";
public static final String DEFAULT_STAGING_DELIMITER = "-";
public static final String DEFAULT_TRANSFER_PROCESSES = "4";
public static final String DEFAULT_TRANSFER_STREAMS = "1";
//grid start constants
public static final String DEFAULT_GRIDSTART_MODE = "Kickstart";
public static final String DEFAULT_INVOKE_LENGTH = "4000";
//site selector constants
public static final String DEFAULT_SITE_SELECTOR = "Random";
public static final String DEFAULT_SITE_SELECTOR_TIMEOUT = "300";
public static final String DEFAULT_SITE_SELECTOR_KEEP = "onerror";
///some simulator constants that are used
public static final String DEFAULT_DATA_MULTIPLICATION_FACTOR = "1";
public static final String DEFAULT_COMP_MULTIPLICATION_FACTOR = "1";
public static final String DEFAULT_COMP_ERROR_PERCENTAGE = "0";
public static final String DEFAULT_COMP_VARIANCE_PERCENTAGE = "0";
//collapsing constants
public static final String DEFAULT_JOB_AGGREGATOR = "SeqExec";
//some tranformation catalog constants
public static final String DEFAULT_TC_MAPPER_MODE = "All";
public static final String DEFAULT_TX_SELECTOR_MODE = "Random";
public static final String TC_DATA_FILE = "tc.data";
//logging constants
public static final String DEFAULT_LOGGING_FILE = "stdout";
/**
* Default properties that applies priorities to all kinds of transfer
* jobs.
*/
public static final String ALL_TRANSFER_PRIORITY_PROPERTY =
"pegasus.transfer.*.priority";
/**
* The default DAXCallback that is loaded, if none is specified by the user.
*/
private static final String DEFAULT_DAX_CALLBACK = "DAX2Graph";
/**
* Ensures only one object is created always. Implements the Singleton.
*/
private static PegasusProperties pegProperties = null;
/**
* The value of the PEGASUS_HOME environment variable.
*/
private String mPegasusHome;
/**
* The object holding all the properties pertaining to the VDS system.
*/
private VDSProperties mProps;
/**
* The Logger object.
*/
// private LogManager mLogger;
/**
* The String containing the messages to be logged.
*/
private String mLogMsg;
/**
* The default path to the transformation catalog.
*/
private String mDefaultTC;
/**
* The default path to the pool file.
*/
private String mDefaultPoolFile;
/**
* The default path to the kickstart condor script, that allows the user to
* submit the concrete DAG directly to the underlying CondorG.
*/
private String mDefaultCondorKickStart;
/**
* The default transfer priority that needs to be applied to the transfer
* jobs.
*/
private String mDefaultTransferPriority;
/**
* The set containing the deprecated properties specified by the user.
*/
private Set mDeprecatedProperties;
/**
* The pointer to the properties file that is written out in the submit directory.
*/
private String mPropsInSubmitDir;
/**
* Returns an instance to this properties object.
*
* @return a handle to the Properties class.
*/
public static PegasusProperties getInstance( ){
return nonSingletonInstance( null );
}
/**
* Returns an instance to this properties object.
*
* @param propFileName name of the properties file to picked from
* $PEGASUS_HOME/etc/ directory.
*
* @return a handle to the Properties class.
*/
public static PegasusProperties getInstance( String propFileName ){
return nonSingletonInstance( propFileName );
}
/**
* To get a reference to the the object. The properties file that is loaded is
* from the path specified in the argument.
* This is *not implemented* as singleton. However the invocation of this
* does modify the internally held singleton object.
*
* @param propFileName name of the properties file to picked from
* $PEGASUS_HOME/etc/ directory.
*
* @return a handle to the Properties class.
*/
protected static PegasusProperties nonSingletonInstance( String propFileName ) {
return new PegasusProperties( propFileName );
}
/**
* To get a reference to the the object. The properties file that is loaded is
* from the path specified in the argument.
*
* This is *not implemented* as singleton. However the invocation of this
* does modify the internally held singleton object.
*
*
* @return a handle to the Properties class.
*/
public static PegasusProperties nonSingletonInstance() {
return nonSingletonInstance( VDSProperties.PROPERTY_FILENAME );
}
/**
* The constructor that constructs the default paths to the various
* configuration files, and populates the singleton instance as required. If
* the properties file passed is null, then the singleton instance is
* invoked, else the non singleton instance is invoked.
*
* @param propertiesFile name of the properties file to picked
* from $PEGASUS_HOME/etc/ directory.
*/
private PegasusProperties( String propertiesFile ) {
// mLogger = LogManager.getInstance();
mDeprecatedProperties = new HashSet(5);
initializePropertyFile( propertiesFile );
mPegasusHome = mProps.getPegasusHome();
mDefaultCondorKickStart = getDefaultPathToCondorKickstart();
mDefaultPoolFile = getDefaultPathToSC();
mDefaultTC = getDefaultPathToTC();
mDefaultTransferPriority= getDefaultTransferPriority();
}
/**
* Returns the default path to the transformation catalog. Currently the
* default path defaults to $PEGASUS_HOME/var/tc.data.
*
* @return the default path to tc.data.
*/
public String getDefaultPathToTC() {
StringBuffer sb = new StringBuffer( 50 );
sb.append( mPegasusHome );
sb.append( File.separator );
sb.append( "var" );
File f = new File( sb.toString(), TC_DATA_FILE );
return f.getAbsolutePath();
}
/**
* Returns the default path to the site catalog file.
* The default path is constructed on the basis of the mode set by
* the user.
*
* @return $PEGASUS_HOME/etc/sites.txt if the pool mode is Text, else
* $PEGASUS_HOME/etc/sites.xml
*
* @see #getPoolMode()
*/
public String getDefaultPathToSC() {
String name = POOL_CONFIG_FILE;
name += (getPoolMode().equalsIgnoreCase("Text"))?
"txt":
"xml";
File f = new File( mProps.getSysConfDir(),name);
//System.err.println("Default Path to SC is " + f.getAbsolutePath());
return f.getAbsolutePath();
}
/**
* Returns the default path to the condor kickstart. Currently the path
* defaults to $PEGASUS_HOME/bin/kickstart-condor.
*
* @return default path to kickstart condor.
*/
public String getDefaultPathToCondorKickstart() {
StringBuffer sb = new StringBuffer( 50 );
sb.append( mPegasusHome );
sb.append( File.separator );
sb.append( "bin" );
sb.append( File.separator );
sb.append( CONDOR_KICKSTART );
return sb.toString();
}
/**
* Gets the handle to the properties file. The singleton instance is
* invoked if the properties file is null (partly due to the way VDSProperties
* is implemented ), else the non singleton is invoked. If you want to pick
* up the default properties file in a non singleton manner, specify
* VDSProperties.PROPERTY_FILENAME as a parameter.
*
* @param propertiesFile name of the properties file to picked
* from $PEGASUS_HOME/etc/ directory.
*/
private void initializePropertyFile( String propertiesFile ) {
try {
mProps = ( propertiesFile == null ) ?
//invoke the singleton instance
VDSProperties.instance() :
//invoke the non singleton instance
VDSProperties.nonSingletonInstance( propertiesFile );
} catch ( IOException e ) {
mLogMsg = "unable to read property file: " + e.getMessage();
System.err.println( mLogMsg );
// mLogger.log( mLogMsg , LogManager.FATAL_MESSAGE_LEVEL);
System.exit( 1 );
} catch ( MissingResourceException e ) {
mLogMsg = "You forgot to set -Dpegasus.home=$PEGASUS_HOME!";
System.err.println( mLogMsg );
// mLogger.log( mLogMsg , LogManager.FATAL_MESSAGE_LEVEL);
System.exit( 1 );
}
}
/**
* It allows you to get any property from the property file without going
* through the corresponding accesor function in this class. For coding
* and clarity purposes, the function should be used judiciously, and the
* accessor function should be used as far as possible.
*
* @param key the property whose value is desired.
* @return String
*/
public String getProperty( String key ) {
return mProps.getProperty( key );
}
/**
* Returns the VDSProperties that this object encapsulates. Use only when
* absolutely necessary. Use accessor methods whereever possible.
*
* @return VDSProperties
*/
public VDSProperties getVDSProperties(){
return this.mProps;
}
/**
* Accessor: Overwrite any properties from within the program.
*
* @param key is the key to look up
* @param value is the new property value to place in the system.
* @return the old value, or null if it didn't exist before.
*/
public Object setProperty( String key, String value ) {
return mProps.setProperty( key, value );
}
/**
* Extracts a specific property key subset from the known properties.
* The prefix may be removed from the keys in the resulting dictionary,
* or it may be kept. In the latter case, exact matches on the prefix
* will also be copied into the resulting dictionary.
*
* @param prefix is the key prefix to filter the properties by.
* @param keepPrefix if true, the key prefix is kept in the resulting
* dictionary. As side-effect, a key that matches the prefix exactly
* will also be copied. If false, the resulting dictionary's keys are
* shortened by the prefix. An exact prefix match will not be copied,
* as it would result in an empty string key.
*
* @return a property dictionary matching the filter key. May be
* an empty dictionary, if no prefix matches were found.
*
* @see #getProperty( String ) is used to assemble matches
*/
public Properties matchingSubset( String prefix, boolean keepPrefix ) {
return mProps.matchingSubset( prefix, keepPrefix );
}
/**
* Returns the properties matching a particular prefix as a list of
* sorted name value pairs, where name is the full name of the matching
* property (including the prefix) and value is it's value in the properties
* file.
*
* @param prefix the prefix for the property names.
* @param system boolean indicating whether to match only System properties
* or all including the ones in the property file.
*
* @return list of <code>NameValue</code> objects corresponding to the matched
* properties sorted by keys.
* null if no matching property is found.
*/
public List getMatchingProperties( String prefix, boolean system ) {
//sanity check
if ( prefix == null ) {
return null;
}
Properties p = (system)?
System.getProperties():
matchingSubset(prefix,true);
java.util.Enumeration e = p.propertyNames();
List l = ( e.hasMoreElements() ) ? new java.util.ArrayList() : null;
while ( e.hasMoreElements() ) {
String key = ( String ) e.nextElement();
NameValue nv = new NameValue( key, p.getProperty( key ) );
l.add( nv );
}
Collections.sort(l);
return ( l.isEmpty() ) ? null : l;
}
/**
* Accessor to $PEGASUS_HOME/etc. The files in this directory have a low
* change frequency, are effectively read-only, they reside on a
* per-machine basis, and they are valid usually for a single user.
*
* @return the "etc" directory of the VDS runtime system.
*/
public File getSysConfDir() {
return mProps.getSysConfDir();
}
/**
* Accessor: Obtains the root directory of the Pegasus runtime
* system.
*
* @return the root directory of the Pegasus runtime system, as initially
* set from the system properties.
*/
public String getPegasusHome() {
return mProps.getPegasusHome();
}
//PROPERTIES RELATED TO SCHEMAS
/**
* Returns the location of the schema for the DAX.
*
* Referred to by the "pegasus.schema.dax" property.
*
* @return location to the DAX schema.
*/
public String getDAXSchemaLocation() {
return this.getDAXSchemaLocation( null );
}
/**
* Returns the location of the schema for the DAX.
*
* Referred to by the "pegasus.schema.dax" property.
*
* @param defaultLocation the default location to the schema.
*
* @return location to the DAX schema specified in the properties file,
* else the default location if no value specified.
*/
public String getDAXSchemaLocation( String defaultLocation ) {
return mProps.getProperty( "pegasus.schema.dax", defaultLocation );
}
/**
* Returns the location of the schema for the PDAX.
*
* Referred to by the "pegasus.schema.pdax" property
*
* @param defaultLocation the default location to the schema.
*
* @return location to the PDAX schema specified in the properties file,
* else the default location if no value specified.
*/
public String getPDAXSchemaLocation( String defaultLocation ) {
return mProps.getProperty( "pegasus.schema.pdax", defaultLocation );
}
//DIRECTORY CREATION PROPERTIES
/**
* Returns the name of the class that the user wants, to insert the
* create directory jobs in the graph in case of creating random
* directories.
*
* Referred to by the "pegasus.dir.create.strategy" property.
*
* @return the create dir classname if specified in the properties file,
* else Tentacles.
*/
public String getCreateDirClass() {
return getProperty( "pegasus.dir.create.strategy",
"pegasus.dir.create",
"Tentacles" );
}
/**
* Returns the name of the class that the user wants, to render the directory
* creation jobs. It dictates what mechanism is used to create the directory
* for a workflow.
*
* Referred to by the "pegasus.dir.create.impl" property.
*
* @return the create dir classname if specified in the properties file,
* else DefaultImplementation.
*/
public String getCreateDirImplementation() {
return mProps.getProperty( "pegasus.dir.create.impl", "DefaultImplementation" );
}
/**
* It specifies whether to use the extended timestamp format for generation
* of timestamps that are used to create the random directory name, and for
* the classads generation.
*
* Referred to by the "pegasus.dir.timestamp.extended" property.
*
* @return the value specified in the properties file if valid boolean, else
* false.
*/
public boolean useExtendedTimeStamp() {
return Boolean.parse(mProps.getProperty( "pegasus.dir.timestamp.extended"),
false );
}
/**
* Returns a boolean indicating whether to use timestamp for directory
* name creation or not.
*
* Referred to by "pegasus.dir.useTimestamp" property.
*
* @return the boolean value specified in the properties files, else false.
*/
public boolean useTimestampForDirectoryStructure(){
return Boolean.parse( mProps.getProperty( "pegasus.dir.useTimestamp" ),
false );
}
/**
* Returns the execution directory suffix or absolute specified
* that is appended/replaced to the exec-mount-point specified in the
* pool catalog for the various pools.
*
* Referred to by the "pegasus.dir.exec" property
*
* @return the value specified in the properties file,
* else the default suffix.
*
* @see #DEFAULT_EXEC_DIR
*/
public String getExecDirectory() {
return mProps.getProperty( "pegasus.dir.exec", DEFAULT_EXEC_DIR );
}
/**
* Returns the storage directory suffix or absolute specified
* that is appended/replaced to the storage-mount-point specified in the
* pool catalog for the various pools.
*
* Referred to by the "pegasus.dir.storage" property.
*
* @return the value specified in the properties file,
* else the default suffix.
*
* @see #DEFAULT_STORAGE_DIR
*/
public String getStorageDirectory() {
return mProps.getProperty( "pegasus.dir.storage", DEFAULT_STORAGE_DIR );
}
/**
* Returns a boolean indicating whether to have a deep storage directory
* structure or not while staging out data to the output site.
*
* Referred to by the "pegasus.dir.storage.deep" property.
*
* @return the boolean value specified in the properties files, else false.
*/
public boolean useDeepStorageDirectoryStructure(){
return Boolean.parse( mProps.getProperty( "pegasus.dir.storage.deep" ),
false );
}
//PROPERTIES RELATED TO CLEANUP
/**
* Returns the name of the Strategy class that the user wants, to insert the
* cleanup jobs in the graph.
*
* Referred to by the "pegasus.file.cleanup.strategy" property.
*
* @return the create dir classname if specified in the properties file,
* else InPlace.
*/
public String getCleanupStrategy() {
return mProps.getProperty( "pegasus.file.cleanup.strategy", "InPlace" );
}
/**
* Returns the name of the class that the user wants, to render the cleanup
* jobs. It dictates what mechanism is used to remove the files on a remote
* system.
*
* Referred to by the "pegasus.file.cleanup.impl" property.
*
* @return the cleanup implementation classname if specified in the properties file,
* else Cleanup.
*/
public String getCleanupImplementation() {
return mProps.getProperty( "pegasus.file.cleanup.impl", "Cleanup" );
}
//PROPERTIES RELATED TO THE TRANSFORMATION CATALOG
/**
* Returns the mode to be used for accessing the Transformation Catalog.
*
* Referred to by the "pegasus.catalog.transformation" property.
*
* @return the value specified in properties file,
* else DEFAULT_TC_MODE.
*
* @see #DEFAULT_TC_MODE
*/
public String getTCMode() {
return mProps.getProperty( "pegasus.catalog.transformation", DEFAULT_TC_MODE );
}
/**
* Returns the location of the transformation catalog.
*
* Referred to by "pegasus.catalog.transformation.file" property.
*
* @return the value specified in the properties file,
* else default path specified by mDefaultTC.
*
* @see #mDefaultTC
*/
public String getTCPath() {
return mProps.getProperty( "pegasus.catalog.transformation.file", mDefaultTC );
}
/**
* Returns the mode for loading the transformation mapper that sits in
* front of the transformation catalog.
*
* Referred to by the "pegasus.catalog.transformation.mapper" property.
*
* @return the value specified in the properties file,
* else default tc mapper mode.
*
* @see #DEFAULT_TC_MAPPER_MODE
*/
public String getTCMapperMode() {
return mProps.getProperty( "pegasus.catalog.transformation.mapper", DEFAULT_TC_MAPPER_MODE );
}
//REPLICA CATALOG PROPERTIES
/**
* Returns the replica mode. It identifies the ReplicaMechanism being used
* by Pegasus to determine logical file locations.
*
* Referred to by the "pegasus.catalog.replica" property.
*
* @return the replica mode, that is used to load the appropriate
* implementing class if property is specified,
* else the DEFAULT_REPLICA_MODE
*
* @see #DEFAULT_REPLICA_MODE
*/
public String getReplicaMode() {
return mProps.getProperty( "pegasus.catalog.replica", DEFAULT_REPLICA_MODE);
}
/**
* Returns the url to the RLI of the RLS.
*
* Referred to by the "pegasus.rls.url" property.
*
* @return the value specified in properties file,
* else DEFAULT_RLI_URL.
*
* @see #DEFAULT_RLI_URL
*/
public String getRLIURL() {
return mProps.getProperty( "pegasus.catalog.replica.url", DEFAULT_RLI_URL );
}
/**
* It returns the timeout value in seconds after which to timeout in case of
* no activity from the RLS.
*
* Referred to by the "pegasus.rc.rls.timeout" property.
*
* @return the timeout value if specified else,
* DEFAULT_RLS_TIMEOUT.
*
* @see #DEFAULT_RLS_TIMEOUT
*/
public int getRLSTimeout() {
String prop = mProps.getProperty( "pegasus.catalog.replica.rls.timeout",
DEFAULT_RLS_TIMEOUT );
int val;
try {
val = Integer.parseInt( prop );
} catch ( Exception e ) {
return Integer.parseInt( DEFAULT_RLS_TIMEOUT );
}
return val;
}
//PROPERTIES RELATED TO SITE CATALOG
/**
* Returns the mode to be used for accessing the pool information.
*
* Referred to by the "pegasus.catalog.site" property.
*
* @return the pool mode, that is used to load the appropriate
* implementing class if the property is specified,
* else default pool mode specified by DEFAULT_POOL_MODE
*
* @see #DEFAULT_POOL_MODE
*/
public String getPoolMode() {
return mProps.getProperty( "pegasus.catalog.site", DEFAULT_POOL_MODE );
}
/**
* Returns the path to the pool file.
*
* Referred to by the "pegasus.catalog.site.file" property.
*
* @return the path to the pool file specified in the properties file,
* else the default path specified by mDefaultPoolFile.
*
* @see #mDefaultPoolFile
*/
public String getPoolFile() {
return mProps.getProperty( "pegasus.catalog.site.file",
mDefaultPoolFile );
}
/**
* Returns the location of the schema for the DAX.
*
* Referred to by the "pegasus.schema.sc" property.
*
* @return the location of pool schema if specified in properties file,
* else null.
*/
public String getPoolSchemaLocation() {
return this.getPoolSchemaLocation( null );
}
/**
* Returns the location of the schema for the site catalog file.
*
* Referred to by the "pegasus.schema.sc" property
*
* @param defaultLocation the default location where the schema should be
* if no other location is specified.
*
* @return the location specified by the property,
* else defaultLocation.
*/
public String getPoolSchemaLocation( String defaultLocation ) {
return mProps.getProperty("pegasus.schema.sc",
defaultLocation );
}
//PROVENANCE CATALOG PROPERTIES
/**
* Returns the provenance store to use to log the refiner actions.
*
* Referred to by the "pegasus.catalog.provenance.refinement" property.
*
* @return the value set in the properties, else null if not set.
*/
public String getRefinementProvenanceStore( ){
return mProps.getProperty( "pegasus.catalog.provenance.refinement" );
}
//TRANSFER MECHANISM PROPERTIES
/**
* Returns the transfer implementation that is to be used for constructing
* the transfer jobs.
*
* Referred to by the "pegasus.transfer.*.impl" property.
*
* @return the transfer implementation, else the
* DEFAULT_TRANSFER_IMPLEMENTATION.
*
* @see #DEFAULT_TRANSFER_IMPLEMENTATION
*/
public String getTransferImplementation(){
return getTransferImplementation( "pegasus.transfer.*.impl" );
}
/**
* Returns the sls transfer implementation that is to be used for constructing
* the transfer jobs.
*
* Referred to by the "pegasus.transfer.sls.*.impl" property.
*
* @return the transfer implementation, else the
* DEFAULT_TRANSFER_IMPLEMENTATION.
*
* @see #DEFAULT_TRANSFER_IMPLEMENTATION
*/
public String getSLSTransferImplementation(){
return getTransferImplementation( "pegasus.transfer.sls.*.impl" );
}
/**
* Returns the transfer implementation.
*
* @param property property name.
*
* @return the transfer implementation,
* else the one specified by "pegasus.transfer.*.impl",
* else the DEFAULT_TRANSFER_IMPLEMENTATION.
*/
public String getTransferImplementation(String property){
String value = mProps.getProperty(property,
getDefaultTransferImplementation());
String dflt = property.equals( "pegasus.transfer.setup.impl" ) ?
DEFAULT_SETUP_TRANSFER_IMPLEMENTATION:
DEFAULT_TRANSFER_IMPLEMENTATION ;
return (value == null)?
dflt :
value;
}
/**
* Returns the transfer refiner that is to be used for adding in the
* transfer jobs in the workflow
*
* Referred to by the "pegasus.transfer.refiner" property.
*
* @return the transfer refiner, else the DEFAULT_TRANSFER_REFINER.
*
* @see #DEFAULT_TRANSFER_REFINER
*/
public String getTransferRefiner(){
String value = mProps.getProperty("pegasus.transfer.refiner");
//put in default if still we have a non null
return (value == null)?
DEFAULT_TRANSFER_REFINER:
value;
}
/**
* Returns whether to introduce quotes around url's before handing to
* g-u-c and condor.
*
* Referred to by "pegasus.transfer.single.quote" property.
*
* @return boolean value specified in the properties file, else
* true in case of non boolean value being specified or property
* not being set.
*/
public boolean quoteTransferURL() {
return Boolean.parse(mProps.getProperty( "pegasus.transfer.single.quote"),
true);
}
/**
* It returns the number of processes of g-u-c that the transfer script needs to
* spawn to do the transfers. This is applicable only in the case where the
* transfer executable has the capability of spawning processes. It should
* not be confused with the number of streams that each process opens.
* By default it is set to 4. In case a non integer value is specified in
* the properties file it returns the default value.
*
* Referred to by "pegasus.transfer.throttle.processes" property.
*
* @return the number of processes specified in properties file, else
* DEFAULT_TRANSFER_PROCESSES
*
* @see #DEFAULT_TRANSFER_PROCESSES
*/
public String getNumOfTransferProcesses() {
String prop = mProps.getProperty( "pegasus.transfer.throttle.processes",
DEFAULT_TRANSFER_PROCESSES );
int val = -1;
try {
val = Integer.parseInt( prop );
} catch ( Exception e ) {
return DEFAULT_TRANSFER_PROCESSES;
}
return Integer.toString( val );
}
/**
* It returns the number of streams that each transfer process uses to do the
* ftp transfer. By default it is set to 1.In case a non integer
* value is specified in the properties file it returns the default value.
*
* Referred to by "pegasus.transfer.throttle.streams" property.
*
* @return the number of streams specified in the properties file, else
* DEFAULT_TRANSFER_STREAMS.
*
* @see #DEFAULT_TRANSFER_STREAMS
*/
public String getNumOfTransferStreams() {
String prop = mProps.getProperty( "pegasus.transfer.throttle.streams",
DEFAULT_TRANSFER_STREAMS );
int val = -1;
try {
val = Integer.parseInt( prop );
} catch ( Exception e ) {
return DEFAULT_TRANSFER_STREAMS;
}
return Integer.toString( val );
}
/**
* It specifies whether the underlying transfer mechanism being used should
* use the force option if available to transfer the files.
*
* Referred to by "pegasus.transfer.force" property.
*
* @return boolean value specified in the properties file,else
* false in case of non boolean value being specified or
* property not being set.
*/
public boolean useForceInTransfer() {
return Boolean.parse(mProps.getProperty( "pegasus.transfer.force"),
false);
}
/**
* It returns whether the use of symbolic links in case where the source
* and destination files happen to be on the same file system.
*
* Referred to by "pegasus.transfer.links" property.
*
* @return boolean value specified in the properties file, else
* false in case of non boolean value being specified or
* property not being set.
*/
public boolean getUseOfSymbolicLinks() {
String value = mProps.getProperty( "pegasus.transfer.links" );
return Boolean.parse(value,false);
}
/**
* Returns the comma separated list of third party sites, specified in the
* properties.
*
* @param property property name.
*
* @return the comma separated list of sites.
*/
public String getThirdPartySites(String property){
String value = mProps.getProperty(property);
return value;
}
/**
* Returns the comma separated list of third party sites for which
* the third party transfers are executed on the remote sites.
*
*
* @param property property name.
*
* @return the comma separated list of sites.
*/
public String getThirdPartySitesRemote(String property){
return mProps.getProperty(property);
}
/**
* Returns the delimiter to be used for constructing the staged executable
* name, during transfer of executables to remote sites.
*
* Referred to by the "pegasus.transfer.staging.delimiter" property.
*
* @return the value specified in the properties file, else
* DEFAULT_STAGING_DELIMITER
*
* @see #DEFAULT_STAGING_DELIMITER
*/
public String getStagingDelimiter(){
return mProps.getProperty("pegasus.transfer.staging.delimiter",
DEFAULT_STAGING_DELIMITER);
}
/**
* Returns the list of sites for which the chmod job creation has to be
* disabled for executable staging.
*
* Referred to by the "pegasus.transfer.disable.chmod" property.
*
* @return a comma separated list of site names.
*/
public String getChmodDisabledSites() {
return mProps.getProperty( "pegasus.transfer.disable.chmod.sites" );
}
/**
* It specifies if for a job execution the proxy is to be transferred
* from the submit host or not.
*
* Referred to by "pegasus.transfer.proxy" property.
*
* @return boolean value specified in the properties file,else
* false in case of non boolean value being specified or
* property not being set.
*/
public boolean transferProxy() {
return Boolean.parse(mProps.getProperty( "pegasus.transfer.proxy"),
false);
}
/**
* Returns the arguments with which the transfer executable needs
* to be invoked.
*
* Referred to by "pegasus.transfer.arguments" property.
*
* @return the arguments specified in the properties file,
* else null if property is not specified.
*/
public String getTransferArguments() {
return mProps.getProperty("pegasus.transfer.arguments");
}
/**
* Returns the priority to be set for the stage in transfer job.
*
* Referred to by "pegasus.transfer.stagein.priority" property if set,
* else by "pegasus.transfer.*.priority" property.
*
* @return the priority as String if a valid integer specified in the
* properties, else null.
*/
public String getTransferStageInPriority(){
return getTransferPriority("pegasus.transfer.stagein.priority");
}
/**
* Returns the priority to be set for the stage out transfer job.
*
* Referred to by "pegasus.transfer.stageout.priority" property if set,
* else by "pegasus.transfer.*.priority" property.
*
* @return the priority as String if a valid integer specified in the
* properties, else null.
*/
public String getTransferStageOutPriority(){
return getTransferPriority("pegasus.transfer.stageout.priority");
}
/**
* Returns the priority to be set for the interpool transfer job.
*
* Referred to by "pegasus.transfer.inter.priority" property if set,
* else by "pegasus.transfer.*.priority" property.
*
* @return the priority as String if a valid integer specified in the
* properties, else null.
*/
public String getTransferInterPriority(){
return getTransferPriority("pegasus.transfer.inter.priority");
}
/**
* Returns the transfer priority.
*
* @param property property name.
*
* @return the priority as String if a valid integer specified in the
* properties as value to property, else null.
*/
private String getTransferPriority(String property){
String value = mProps.getProperty(property, mDefaultTransferPriority);
int val = -1;
try {
val = Integer.parseInt( value );
} catch ( Exception e ) {
}
//if value in properties file is corrupted
//again use the default transfer priority
return ( val < 0 ) ? mDefaultTransferPriority : Integer.toString( val );
}
//REPLICA SELECTOR FUNCTIONS
/**
* Returns the mode for loading the transformation selector that selects
* amongst the various candidate transformation catalog entry objects.
*
* Referred to by the "pegasus.selector.transformation" property.
*
* @return the value specified in the properties file,
* else default transformation selector.
*
* @see #DEFAULT_TC_MAPPER_MODE
*/
public String getTXSelectorMode() {
return mProps.getProperty( "pegasus.selector.transformation",
DEFAULT_TX_SELECTOR_MODE );
}
/**
* Returns the name of the selector to be used for selection amongst the
* various replicas of a single lfn.
*
* Referred to by the "pegasus.selector.replica" property.
*
* @return the name of the selector if the property is specified,
* else null
*/
public String getReplicaSelector(){
return mProps.getProperty( "pegasus.selector.replica" );
}
/**
* Returns a comma separated list of sites, that are restricted in terms of
* data movement from the site.
*
* Referred to by the "pegasus.rc.restricted.sites" property.
*
* @return comma separated list of sites.
*/
// public String getRestrictedSites(){
// return mProps.getProperty("pegasus.rc.restricted.sites","");
/**
* Returns a comma separated list of sites, from which to prefer data
* transfers for all sites.
*
* Referred to by the "pegasus.selector.replica.*.prefer.stagein.sites" property.
*
* @return comma separated list of sites.
*/
public String getAllPreferredSites(){
return mProps.getProperty( "pegasus.selector.replica.*.prefer.stagein.sites","");
}
/**
* Returns a comma separated list of sites, from which to ignore data
* transfers for all sites. Replaces the old pegasus.rc.restricted.sites
* property.
*
* Referred to by the "pegasus.selector.ignore.*.prefer.stagein.sites" property.
*
* @return comma separated list of sites.
*/
public String getAllIgnoredSites(){
return mProps.getProperty("pegasus.selector.replica.*.ignore.stagein.sites",
"");
}
//SITE SELECTOR PROPERTIES
/**
* Returns the class name of the site selector, that needs to be invoked to do
* the site selection.
*
* Referred to by the "pegasus.selector.site" property.
*
* @return the classname corresponding to the site selector that needs to be
* invoked if specified in the properties file, else the default
* selector specified by DEFAULT_SITE_SELECTOR.
*
* @see #DEFAULT_SITE_SELECTOR
*/
public String getSiteSelectorMode() {
return mProps.getProperty( "pegasus.selector.site",
DEFAULT_SITE_SELECTOR );
}
/**
* Returns the path to the external site selector that needs to be called
* out to make the decision of site selection.
*
* Referred to by the "pegasus.selector.site.path" property.
*
* @return the path to the external site selector if specified in the
* properties file, else null.
*/
public String getSiteSelectorPath() {
return mProps.getProperty( "pegasus.selector.site.path" );
}
/**
* It returns the timeout value in seconds after which to timeout in case of
* no activity from the external site selector.
*
* Referred to by the "pegasus.selector.site.timeout" property.
*
* @return the timeout value if specified else,
* DEFAULT_SITE_SELECTOR_TIMEOUT.
*
* @see #DEFAULT_SITE_SELECTOR_TIMEOUT
*/
public int getSiteSelectorTimeout() {
String prop = mProps.getProperty( "pegasus.selector.site.timeout",
DEFAULT_SITE_SELECTOR_TIMEOUT );
int val;
try {
val = Integer.parseInt( prop );
} catch ( Exception e ) {
return Integer.parseInt( DEFAULT_SITE_SELECTOR_TIMEOUT );
}
return val;
}
/**
* Returns a value designating whether we need to keep the temporary files
* that are passed to the external site selectors. The check for the valid
* tristate value should be done at the calling function end. This just
* passes on the value user specified in the properties file.
*
* Referred to by the "pegasus.selector.site.keep.tmp" property.
*
* @return the value of the property is specified, else
* DEFAULT_SITE_SELECTOR_KEEP
*
* @see #DEFAULT_SITE_SELECTOR_KEEP
*/
public String getSiteSelectorKeep() {
return mProps.getProperty( "pegasus.selector.site.keep.tmp",
DEFAULT_SITE_SELECTOR_KEEP );
}
//PROPERTIES RELATED TO KICKSTART AND EXITCODE
/**
* Returns the GRIDSTART that is to be used to launch the jobs on the grid.
*
* Referred to by the "pegasus.gridstart" property.
*
* @return the value specified in the property file,
* else DEFAULT_GRIDSTART_MODE
*
* @see #DEFAULT_GRIDSTART_MODE
*/
public String getGridStart(){
return mProps.getProperty("pegasus.gridstart",DEFAULT_GRIDSTART_MODE);
}
/**
* Return a boolean indicating whether to turn the stat option for kickstart
* on or not. By default it is turned on.
*
* Referred to by the "pegasus.gridstart.kickstart.stat" property.
*
* @return the boolean value specified in the property file,
* else false if not specified or non boolean specified.
*/
public boolean doStatWithKickstart(){
return Boolean.parse( mProps.getProperty( "pegasus.gridstart.kickstart.stat"),
false );
}
/**
* Return a boolean indicating whether to generate the LOF files for the jobs
* or not. This is used to generate LOF files, but not trigger the stat option
*
* Referred to by the "pegasus.gridstart.kickstart.generate.loft" property.
*
* @return the boolean value specified in the property file,
* else false if not specified or non boolean specified.
*/
public boolean generateLOFFiles(){
return Boolean.parse( mProps.getProperty( "pegasus.gridstart.generate.lof"),
false );
}
/**
* Returns a boolean indicating whether to use invoke in kickstart always
* or not.
*
* Referred to by the "pegasus.gridstart.invoke.always" property.
*
* @return the boolean value specified in the property file,
* else false if not specified or non boolean specified.
*/
public boolean useInvokeInGridStart(){
return Boolean.parse( mProps.getProperty( "pegasus.gridstart.invoke.always"),
false );
}
/**
* Returns the trigger value for invoking an application through kickstart
* using kickstart. If the arguments value being constructed in the condor
* submit file is more than this value, then invoke is used to pass the
* arguments to the remote end. Helps in bypassing the Condor 4K limit.
*
* Referred to by "pegasus.gridstart.invoke.length" property.
*
* @return the long value specified in the properties files, else
* DEFAULT_INVOKE_LENGTH
*
* @see #DEFAULT_INVOKE_LENGTH
*/
public long getGridStartInvokeLength(){
long value = new Long(this.DEFAULT_INVOKE_LENGTH).longValue();
String st = mProps.getProperty( "pegasus.gridstart.invoke.length",
this.DEFAULT_INVOKE_LENGTH );
try {
value = new Long( st ).longValue();
} catch ( Exception e ) {
//ignore malformed values from
//the property file
}
return value;
}
/**
* Returns a boolean indicating whehter to pass extra options to kickstart
* or not. The extra options have appeared only in VDS version 1.4.2 (like -L
* and -T).
*
* Referred to by "pegasus.gridstart.label" property.
*
* @return the boolean value specified in the property file,
* else true if not specified or non boolean specified.
*/
public boolean generateKickstartExtraOptions(){
return Boolean.parse( mProps.getProperty( "pegasus.gridstart.label"),
true );
}
/**
* Returns the mode adding the postscripts for the jobs. At present takes in
* only two values all or none default being none.
*
* Referred to by the "pegasus.exitcode.scope" property.
*
* @return the mode specified by the property, else
* DEFAULT_POSTSCRIPT_MODE
*
* @see #DEFAULT_POSTSCRIPT_MODE
*/
public String getPOSTScriptScope() {
return mProps.getProperty( "pegasus.exitcode.scope",
DEFAULT_POSTSCRIPT_MODE );
}
/**
* Returns the postscript to use with the jobs in the workflow. They
* maybe overriden by values specified in the profiles.
*
* Referred to by the "pegasus.exitcode.impl" property.
*
* @return the postscript to use for the workflow, else null if not
* specified in the properties.
*/
public String getPOSTScript(){
return mProps.getProperty( "pegasus.exitcode.impl" );
}
/**
* Returns the path to the exitcode executable to be used.
*
* Referred to by the "pegasus.exitcode.path.[value]" property, where [value]
* is replaced by the value passed an input to this function.
*
* @param value the short name of the postscript whose path we want.
*
* @return the path to the postscript if specified in properties file.
*/
public String getPOSTScriptPath( String value ){
value = ( value == null ) ? "*" : value;
StringBuffer key = new StringBuffer();
key.append( "pegasus.exitcode.path." ).append( value );
return mProps.getProperty( key.toString() );
}
/**
* Returns the argument string containing the arguments by which exitcode is
* invoked.
*
* Referred to by the "pegasus.exitcode.arguments" property.
*
* @return String containing the arguments,else empty string.
*/
public String getPOSTScriptArguments() {
return mProps.getProperty( "pegasus.exitcode.arguments", "");
}
/**
* Returns a boolean indicating whether to turn debug on or not for exitcode.
* By default false is returned.
*
* Referred to by the "pegasus.exitcode.debug" property.
*
* @return boolean value.
*/
public boolean setPostSCRIPTDebugON(){
return Boolean.parse( mProps.getProperty( "pegasus.exitcode.debug"), false );
}
/**
* Returns the argument string containing the arguments by which prescript is
* invoked.
*
* Referred to by the "pegasus.prescript.arguments" property.
*
* @return String containing the arguments.
* null if not specified.
*/
public String getPrescriptArguments() {
return mProps.getProperty( "pegasus.prescript.arguments","" );
}
//PROPERTIES RELATED TO REMOTE SCHEDULERS
/**
* Returns the project names that need to be appended to the RSL String
* while creating the submit files. Referred to by
* pegasus.remote.projects property. If present, Pegasus ends up
* inserting an RSL string (project = value) in the submit file.
*
* @return a comma separated list of key value pairs if property specified,
* else null.
*/
public String getRemoteSchedulerProjects() {
return mProps.getProperty( "pegasus.remote.scheduler.projects" );
}
/**
* Returns the queue names that need to be appended to the RSL String while
* creating the submit files. Referred to by the pegasus.remote.queues
* property. If present, Pegasus ends up inserting an RSL string
* (project = value) in the submit file.
*
* @return a comma separated list of key value pairs if property specified,
* else null.
*/
public String getRemoteSchedulerQueues() {
return mProps.getProperty( "pegasus.remote.scheduler.queues" );
}
/**
* Returns the maxwalltimes for the various pools that need to be appended
* to the RSL String while creating the submit files. Referred to by the
* pegasus.scheduler.remote.queues property. If present, Pegasus ends up
* inserting an RSL string (project = value) in the submit file.
*
*
* @return a comma separated list of key value pairs if property specified,
* else null.
*/
public String getRemoteSchedulerMaxWallTimes() {
return mProps.getProperty( "pegasus.remote.scheduler.min.maxwalltime" );
}
/**
* Returns the minimum walltimes that need to be enforced.
*
* Referred to by "pegasus.scheduler.remote.min.[key]" property.
*
* @param key the appropriate globus RSL key. Generally are
* maxtime|maxwalltime|maxcputime
*
* @return the integer value as specified, -1 in case of no value being specified.
*/
public int getMinimumRemoteSchedulerTime( String key ){
StringBuffer property = new StringBuffer();
property.append( "pegasus.remote.scheduler.min." ).append( key );
int val = -1;
try {
val = Integer.parseInt( mProps.getProperty( property.toString() ) );
} catch ( Exception e ) {
}
return val;
}
//PROPERTIES RELATED TO CONDOR
/**
* Returns a boolean indicating whether we want to Condor Quote the
* arguments of the job or not.
*
* Referred to by the "pegasus.condor.arguments.quote" property.
*
* @return boolean
*/
public boolean useCondorQuotingForArguments(){
return Boolean.parse( mProps.getProperty("pegasus.condor.arguments.quote"),
true);
}
/**
* Returns the number of release attempts that are written into the condor
* submit files. Condor holds jobs on certain kind of failures, which many
* a time are transient, and if a job is released it usually progresses.
*
* Referred to by the "pegasus.condor.release" property.
*
* @return an int denoting the number of times to release.
* null if not specified or invalid entry.
*/
public String getCondorPeriodicReleaseValue() {
String prop = mProps.getProperty( "pegasus.condor.release" );
int val = -1;
try {
val = Integer.parseInt( prop );
} catch ( Exception e ) {
return null;
}
return ( val < 0 ) ? null : Integer.toString( val );
}
/**
* Returns the number of release attempts that are attempted before
* Condor removes the job from the queue and marks it as failed.
*
* Referred to by the "pegasus.condor.remove" property.
*
* @return an int denoting the number of times to release.
* null if not specified or invalid entry.
*/
public String getCondorPeriodicRemoveValue() {
String prop = mProps.getProperty( "pegasus.condor.remove" );
int val = -1;
try {
val = Integer.parseInt( prop );
} catch ( Exception e ) {
return null;
}
return ( val < 0 ) ? null : Integer.toString( val );
}
/**
* Returns the number of times Condor should retry running a job in case
* of failure. The retry ends up reinvoking the prescript, that can change
* the site selection decision in case of failure.
*
* Referred to by the "pegasus.dagman.retry" property.
*
* @return an int denoting the number of times to retry.
* null if not specified or invalid entry.
*/
public String getCondorRetryValue() {
String prop = mProps.getProperty( "pegasus.dagman.retry" );
int val = -1;
try {
val = Integer.parseInt( prop );
} catch ( Exception e ) {
return null;
}
return Integer.toString( val );
}
/**
* Tells whether to stream condor output or not. By default it is true ,
* meaning condor streams the output from the remote hosts back to the submit
* hosts, instead of staging it. This helps in saving filedescriptors at the
* jobmanager end.
*
* If it is set to false, output is not streamed back. The line
* "stream_output = false" should be added in the submit files for kickstart
* jobs.
*
* Referred to by the "pegasus.condor.output.stream" property.
*
* @return the boolean value specified by the property, else
* true in case of invalid value or property not being specified.
*
*/
public boolean streamCondorOutput() {
return Boolean.parse(mProps.getProperty( "pegasus.condor.output.stream"),
true );
}
/**
* Tells whether to stream condor error or not. By default it is true ,
* meaning condor streams the error from the remote hosts back to the submit
* hosts instead of staging it in. This helps in saving filedescriptors at
* the jobmanager end.
*
* Referred to by the "pegasus.condor.error.stream" property.
*
* If it is set to false, output is not streamed back. The line
* "stream_output = false" should be added in the submit files for kickstart
* jobs.
*
* @return the boolean value specified by the property, else
* true in case of invalid value or property not being specified.
*/
public boolean streamCondorError() {
return Boolean.parse(mProps.getProperty( "pegasus.condor.error.stream"),
true);
}
//PROPERTIES RELATED TO STORK
/**
* Returns the credential name to be used for the stork transfer jobs.
*
* Referred to by the "pegasus.transfer.stork.cred" property.
*
* @return the credential name if specified by the property,
* else null.
*/
public String getCredName() {
return mProps.getProperty( "pegasus.transfer.stork.cred" );
}
//SOME LOGGING PROPERTIES
/**
* Returns the log manager to use.
*
* Referred to by the "pegasus.log.manager" property.
*
* @return the value in the properties file, else Default
*/
public String getLogManager() {
return mProps.getProperty( "pegasus.log.manager", "Default" );
}
/**
* Returns the log formatter to use.
*
* Referred to by the "pegasus.log.formatter" property.
*
* @return the value in the properties file, else Simple
*/
public String getLogFormatter() {
return mProps.getProperty( "pegasus.log.formatter", "Simple" );
}
/**
* Returns the http url for log4j properties for windward project.
*
* Referred to by the "log4j.configuration" property.
*
* @return the value in the properties file, else null
*/
public String getHttpLog4jURL() {
//return mProps.getProperty( "pegasus.log.windward.log4j.http.url" );
return mProps.getProperty( "log4j.configuration" );
}
/**
* Returns the file to which all the logging needs to be directed to.
*
* Referred to by the "pegasus.log.*" property.
*
* @return the value of the property that is specified, else
* null
*/
public String getLoggingFile(){
return mProps.getProperty("pegasus.log.*");
}
/**
* Returns the location of the local log file where you want the messages to
* be logged. Not used for the moment.
*
* Referred to by the "pegasus.log4j.log" property.
*
* @return the value specified in the property file,else null.
*/
public String getLog4JLogFile() {
return mProps.getProperty( "pegasus.log4j.log" );
}
/**
* Returns a boolean indicating whether to write out the planner metrics
* or not.
*
* Referred to by the "pegasus.log.metrics" property.
*
* @return boolean in the properties, else true
*/
public boolean writeOutMetrics(){
return Boolean.parse( mProps.getProperty( "pegasus.log.metrics" ), true );
}
/**
* Returns the path to the file that is used to be logging metrics
*
* Referred to by the "pegasus.log.metrics.file" property.
*
* @return path to the metrics file if specified, else $PEGASUS_HOME/var/pegasus.log
*/
public String getMetricsLogFile(){
String file = mProps.getProperty( "pegasus.log.metrics.file" );
if( file == null || file.length() == 0 ){
//construct the default path
File dir = new File( this.getPegasusHome(), "var" );
file = new File( dir, "pegasus.log" ).getAbsolutePath();
}
return file;
}
//SOME MISCELLANEOUS PROPERTIES
/**
* Return returns the environment string specified for the local pool. If
* specified the registration jobs are set with these environment variables.
*
* Referred to by the "pegasus.local.env" property
*
* @return the environment string for local pool in properties file if
* defined, else null.
*/
public String getLocalPoolEnvVar() {
return mProps.getProperty( "pegasus.local.env" );
}
/**
* Returns a boolean indicating whether to have jobs executing on worker
* node tmp or not.
*
* Referred to by the "pegasus.execute.*.filesystem.local" property.
*
* @return boolean value in the properties file, else false if not specified
* or an invalid value specified.
*/
public boolean executeOnWorkerNode( ){
return Boolean.parse( mProps.getProperty( "pegasus.execute.*.filesystem.local" ) ,
false );
}
/**
* Returns a boolean indicating whether to treat the entries in the cache
* files as a replica catalog or not.
*
* @return boolean
*/
public boolean treatCacheAsRC(){
return Boolean.parse(mProps.getProperty( "pegasus.catalog.replica.cache.asrc" ),
false);
}
/**
* Returns a boolean indicating whether to preserver line breaks.
*
* Referred to by the "pegasus.parser.dax.preserve.linebreaks" property.
*
* @return boolean value in the properties file, else false if not specified
* or an invalid value specified.
*/
public boolean preserveParserLineBreaks( ){
return Boolean.parse( mProps.getProperty( "pegasus.parser.dax.preserve.linebreaks" ),
false) ;
}
/**
* Returns the path to the wings properties file.
*
* Referred to by the "pegasus.wings.properties" property.
*
* @return value in the properties file, else null.
*/
public String getWingsPropertiesFile( ){
return mProps.getProperty( "pegasus.wings.properties" ) ;
}
/**
* Returns the request id.
*
* Referred to by the "pegasus.wings.request-id" property.
*
* @return value in the properties file, else null.
*/
public String getWingsRequestID( ){
return mProps.getProperty( "pegasus.wings.request.id" ) ;
}
/**
* Returns the timeout value in seconds after which to timeout in case of
* opening sockets to grid ftp server.
*
* Referred to by the "pegasus.auth.gridftp.timeout" property.
*
* @return the timeout value if specified else,
* null.
*
* @see #DEFAULT_SITE_SELECTOR_TIMEOUT
*/
public String getGridFTPTimeout(){
return mProps.getProperty("pegasus.auth.gridftp.timeout");
}
/**
* Returns which submit mode to be used to submit the jobs on to the grid.
*
* Referred to by the "pegasus.submit" property.
*
* @return the submit mode specified in the property file,
* else the default i.e condor.
*/
public String getSubmitMode() {
return mProps.getProperty( "pegasus.submit", "condor" );
}
/**
* Returns the mode for parsing the dax while writing out the partitioned
* daxes.
*
* Referred to by the "pegasus.partition.parser.load" property.
*
* @return the value specified in the properties file, else
* the default value i.e single.
*/
public String getPartitionParsingMode() {
return mProps.getProperty( "pegasus.partition.parser.load", "single" );
}
/**
* Returns the default priority that needs to be applied to all job.
*
* Referred to by the "pegasus.job.priority" property.
*
* @return the value specified in the properties file, null if a non
* integer value is passed.
*/
public String getJobPriority(){
String prop = mProps.getProperty( "pegasus.job.priority" );
int val = -1;
try {
val = Integer.parseInt( prop );
} catch ( Exception e ) {
return null;
}
return ( val < 0 ) ? null : Integer.toString( val );
}
//JOB COLLAPSING PROPERTIES
/**
* Returns a comma separated list for the node collapsing criteria for the
* execution pools. This determines how many jobs one fat node gobbles up.
*
* Referred to by the "pegasus.cluster.nodes" property.
*
* @return the value specified in the properties file, else null.
*/
public String getCollapseFactors() {
return mProps.getProperty( "pegasus.clusterer.nodes" );
}
/**
* Returns what job aggregator is to be used to aggregate multiple
* compute jobs into a single condor job.
*
* Referred to by the "pegasus.cluster.job.aggregator" property.
*
* @return the value specified in the properties file, else
* DEFAULT_JOB_AGGREGATOR
*
* @see #DEFAULT_JOB_AGGREGATOR
*/
public String getJobAggregator(){
return mProps.getProperty("pegasus.clusterer.job.aggregator",DEFAULT_JOB_AGGREGATOR);
}
/**
* Returns whether the seqexec job aggregator should log progress to a log or not.
*
* Referred to by the "pegasus.clusterer.job.aggregator.seqexec.log" property.
*
* @return the value specified in the properties file, else false
*
*/
public boolean logJobAggregatorProgress(){
return Boolean.parse( getProperty( "pegasus.clusterer.job.aggregator.seqexec.log" ),
false );
}
/**
* Returns whether the seqexec job aggregator should write to a global log or not.
* This comes into play only if "pegasus.clusterer.job.aggregator.seqexec.log"
* is set to true.
*
* Referred to by the "pegasus.clusterer.job.aggregator.seqexec.log.global" property.
*
* @return the value specified in the properties file, else true
*
*/
public boolean logJobAggregatorProgressToGlobal(){
return Boolean.parse( getProperty( "pegasus.clusterer.job.aggregator.seqexec.log.global",
"pegasus.clusterer.job.aggregator.seqexec.hasgloballog"),
true );
}
/**
* Returns a boolean indicating whether seqexec trips on the first job failure.
*
* Referred to by the "pegasus.cluster.job.aggregator.seqexec.firstjobfail" property.
*
* @return the value specified in the properties file, else false
*
*/
public boolean abortOnFirstJobFailure(){
return Boolean.parse( mProps.getProperty( "pegasus.clusterer.job.aggregator.seqexec.firstjobfail" ),
false );
}
//DEFERRED PLANNING PROPERTIES
/**
* Returns the DAXCallback that is to be used while parsing the DAX.
*
* Referred to by the "pegasus.parser.dax.callback" property.
*
* @return the value specified in the properties file, else
* DEFAULT_DAX_CALLBACK
*
* @see #DEFAULT_DAX_CALLBACK
*/
public String getDAXCallback(){
return mProps.getProperty("pegasus.parser.dax.callback",DEFAULT_DAX_CALLBACK);
}
/**
* Returns the key that is to be used as a label key, for labelled
* partitioning.
*
* Referred to by the "pegasus.partitioner.label.key" property.
*
* @return the value specified in the properties file.
*/
public String getPartitionerLabelKey(){
return mProps.getProperty( "pegasus.partitioner.label.key" );
}
/**
* Returns the bundle value for a particular transformation.
*
* Referred to by the "pegasus.partitioner.horziontal.bundle.[txname]" property,
* where [txname] is replaced by the name passed an input to this function.
*
* @param name the logical name of the transformation.
*
* @return the path to the postscript if specified in properties file,
* else null.
*/
public String getHorizontalPartitionerBundleValue( String name ){
StringBuffer key = new StringBuffer();
key.append( "pegasus.partitioner.horizontal.bundle." ).append( name );
return mProps.getProperty( key.toString() );
}
/**
* Returns the collapse value for a particular transformation.
*
* Referred to by the "pegasus.partitioner.horziontal.collapse.[txname]" property,
* where [txname] is replaced by the name passed an input to this function.
*
* @param name the logical name of the transformation.
*
* @return the path to the postscript if specified in properties file,
* else null.
*/
public String getHorizontalPartitionerCollapseValue( String name ){
StringBuffer key = new StringBuffer();
key.append( "pegasus.partitioner.horizontal.collapse." ).append( name );
return mProps.getProperty( key.toString() );
}
/**
* Returns the key that is to be used as a label key, for labelled
* clustering.
*
* Referred to by the "pegasus.clusterer.label.key" property.
*
* @return the value specified in the properties file.
*/
public String getClustererLabelKey(){
return mProps.getProperty( "pegasus.clusterer.label.key");
}
/**
* Returns the path to the property file that has been writting out in
* the submit directory.
*
* @return path to the property file
*
* @exception RuntimeException in case of file not being generated.
*/
public String getPropertiesInSubmitDirectory( ){
if ( mPropsInSubmitDir == null || mPropsInSubmitDir.length() == 0 ){
throw new RuntimeException( "Properties file does not exist in directory " );
}
return mPropsInSubmitDir;
}
/**
* Writes out the properties to a temporary file in the directory passed.
*
* @param directory the directory in which the properties file needs to
* be written to.
*
* @return the absolute path to the properties file written in the directory.
*
* @throws IOException in case of error while writing out file.
*/
public String writeOutProperties( String directory ) throws IOException{
File dir = new File(directory);
//sanity check on the directory
sanityCheck( dir );
//we only want to write out the VDS properties for time being
Properties properties = mProps.matchingSubset( "pegasus", true );
//create a temporary file in directory
File f = File.createTempFile( "pegasus.", ".properties", dir );
//the header of the file
StringBuffer header = new StringBuffer(64);
header.append("Pegasus USER PROPERTIES AT RUNTIME \n")
.append("#ESCAPES IN VALUES ARE INTRODUCED");
//create an output stream to this file and write out the properties
OutputStream os = new FileOutputStream(f);
properties.store( os, header.toString() );
os.close();
//also set it to the internal variable
mPropsInSubmitDir = f.getAbsolutePath();
return mPropsInSubmitDir;
}
/**
* Checks the destination location for existence, if it can
* be created, if it is writable etc.
*
* @param dir is the new base directory to optionally create.
*
* @throws IOException in case of error while writing out files.
*/
protected static void sanityCheck( File dir ) throws IOException{
if ( dir.exists() ) {
// location exists
if ( dir.isDirectory() ) {
// ok, isa directory
if ( dir.canWrite() ) {
// can write, all is well
return;
} else {
// all is there, but I cannot write to dir
throw new IOException( "Cannot write to existing directory " +
dir.getPath() );
}
} else {
// exists but not a directory
throw new IOException( "Destination " + dir.getPath() + " already " +
"exists, but is not a directory." );
}
} else {
// does not exist, try to make it
if ( ! dir.mkdirs() ) {
throw new IOException( "Unable to create directory destination " +
dir.getPath() );
}
}
}
/**
* This function is used to check whether a deprecated property is used or
* not. If a deprecated property is used,it logs a warning message specifying
* the new property. If both properties are not set by the user, the function
* returns the default property. If no default property then null.
*
* @param newProperty the new property that should be used.
* @param deprecatedProperty the deprecated property that needs to be
* replaced.
*
* @return the appropriate value.
*/
private String getProperty( String newProperty, String deprecatedProperty ) {
return this.getProperty( newProperty, deprecatedProperty, null );
}
/**
* This function is used to check whether a deprecated property is used or
* not. If a deprecated property is used,it logs a warning message specifying
* the new property. If both properties are not set by the user, the
* function returns the default property. If no default property then null.
*
*
* @param newProperty the new property that should be used.
* @param deprecatedProperty the deprecated property that needs to be
* replaced.
* @param defaultValue the default value that should be returned.
*
* @return the appropriate value.
*/
private String getProperty( String newProperty,
String deprecatedProperty,
String defaultValue ) {
String value = null;
//try for the new property
//first
value = mProps.getProperty( newProperty );
if ( value == null ) {
//try the deprecated property if set
value = mProps.getProperty( deprecatedProperty );
//if the value is not null
if ( value != null ) {
//print the warning message
logDeprecatedWarning(deprecatedProperty,newProperty);
return value;
} else { //else return the default value
return defaultValue;
}
}
return value;
}
/**
* Logs a warning about the deprecated property. Logs a warning only if
* it has not been displayed before.
*
* @param deprecatedProperty the deprecated property that needs to be
* replaced.
* @param newProperty the new property that should be used.
*/
private void logDeprecatedWarning(String deprecatedProperty,
String newProperty){
if(!mDeprecatedProperties.contains(deprecatedProperty)){
//log only if it had already not been logged
StringBuffer sb = new StringBuffer();
sb.append( "The property " ).append( deprecatedProperty ).
append( " has been deprecated. Use " ).append( newProperty ).
append( " instead." );
// mLogger.log(sb.toString(),LogManager.WARNING_MESSAGE_LEVEL );
System.err.println( "[WARNING] " + sb.toString() );
//push the property in to indicate it has already been
//warned about
mDeprecatedProperties.add(deprecatedProperty);
}
}
/**
* Returns a boolean indicating whether to use third party transfers for
* all types of transfers or not.
*
* Referred to by the "pegasus.transfer.*.thirdparty" property.
*
* @return the boolean value in the properties files,
* else false if no value specified, or non boolean specified.
*/
// private boolean useThirdPartyForAll(){
// return Boolean.parse("pegasus.transfer.*.thirdparty",
// false);
/**
* Returns the default list of third party sites.
*
* Referred to by the "pegasus.transfer.*.thirdparty.sites" property.
*
* @return the value specified in the properties file, else
* null.
*/
private String getDefaultThirdPartySites(){
return mProps.getProperty("pegasus.transfer.*.thirdparty.sites");
}
/**
* Returns the default transfer implementation to be picked up for
* constructing transfer jobs.
*
* Referred to by the "pegasus.transfer.*.impl" property.
*
* @return the value specified in the properties file, else
* null.
*/
private String getDefaultTransferImplementation(){
return mProps.getProperty("pegasus.transfer.*.impl");
}
/**
* Returns the default priority for the transfer jobs if specified in
* the properties file.
*
* @return the value specified in the properties file, else null if
* non integer value or no value specified.
*/
private String getDefaultTransferPriority(){
String prop = mProps.getProperty( this.ALL_TRANSFER_PRIORITY_PROPERTY);
int val = -1;
try {
val = Integer.parseInt( prop );
} catch ( Exception e ) {
return null;
}
return Integer.toString( val );
}
/**
* Gets the reference to the internal singleton object. This method is
* invoked with the assumption that the singleton method has been invoked once
* and has been populated. Also that it has not been disposed by the garbage
* collector. Can be potentially a buggy way to invoke.
*
* @return a handle to the Properties class.
*/
// public static PegasusProperties singletonInstance() {
// return singletonInstance( null );
/**
* Gets a reference to the internal singleton object.
*
* @param propFileName name of the properties file to picked
* from $PEGASUS_HOME/etc/ directory.
*
* @return a handle to the Properties class.
*/
// public static PegasusProperties singletonInstance( String propFileName ) {
// if ( pegProperties == null ) {
// //only the default properties file
// //can be picked up due to the way
// //Singleton implemented in VDSProperties.???
// pegProperties = new PegasusProperties( null );
// return pegProperties;
} |
package datastruct;
import gui.AlignmentWindow;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Vector;
/** klassen som skter om skrivning till filer och lsning frn filer */
public class IOHandler {
private static String settingsPath = null;
private static String iconsPath = null;
/** skapar ett objekt av klassen */
public IOHandler() {
}
/** skriver ut en html-sida med filnamnet fileName och med rubriken header utifrn resultatlistan result */
public void outputToHTML(String fileName, ResultList result, String header, int align) throws IOException {
ResultList res = result;
boolean[] extras = res.getExtras();
String alignment;
if(align == AlignmentWindow.LEFT) {
alignment = "left";
} else if (align == AlignmentWindow.CENTER) {
alignment = "center";
} else {
alignment = "right";
}
String startRow = "<tr>";
String endRow = "</tr>";
String startCol;
String startColEmpty = "<td>";
String startColStartNbr = "<td style=\"text-align:" + alignment + "\">";
String startColPlaceNbr = "<td style=\"text-align:" + alignment + "\">";
String startColLicense = "<td>";
String startColName = "<td>";
String startColClub = "<td>";
String startColResult;
if(res.getNbrRounds() <= 5) {
startColResult = "<td style=\"text-align:" + alignment + "\">";
} else {
startColResult = "<td style=\"text-align:" + alignment + "\">";
}
String startColSum = "<td style=\"text-align:" + alignment + "\">";
String endCol = "</td>";
BufferedWriter bufferOut = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")
);
bufferOut.write("<!DOCTYPE HTML PUBLIC \"-
bufferOut.newLine();
bufferOut.write("<html lang=\"sv\">");
bufferOut.newLine();
bufferOut.write("<head>");
bufferOut.newLine();
bufferOut.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
bufferOut.newLine();
bufferOut.write("<title>" + header + "</title>");
bufferOut.newLine();
bufferOut.write("<style type=\"text/css\">" +
"body {font-family: arial} " +
"td {font-size: 10.0pt; padding-right: 10px; vertical-align: super; white-space: nowrap}" +
"</style>");
bufferOut.newLine();
bufferOut.write("</head>");
bufferOut.newLine();
bufferOut.write("<body style=\"background-color:white\">");
bufferOut.newLine();
bufferOut.write("<h1 style=\"font-size: 14.0pt\">" + header + "</h1>");
bufferOut.newLine();
String[][] output = res.getOutput();
String[][] outputStyle = res.getOutputStyle();
bufferOut.write("<table cellpadding=\"1\" cellspacing=\"1\">");
bufferOut.newLine();
for(int i = 0; i < output.length; i++) {
if(output[i][0] != " ") {
bufferOut.write(startRow);
bufferOut.newLine();
for(int j = 0; j < output[i].length; j++) {
String boldStart = "";
String boldStop = "";
if(outputStyle[i][j] == null) {
outputStyle[i][j] = "black";
} else if(outputStyle[i][j].equals("Bold")) {
boldStart = "<b>";
boldStop = "</b>";
outputStyle[i][j] = "black";
} else if(outputStyle[i][j].equals("Bold+")) {
// Hantering av klassrubrik
boldStart = "<b style=\"font-size:12.0pt\">";
boldStop = "</b>";
outputStyle[i][j] = "black";
bufferOut.write("<td colspan=\"0\">" + boldStart + output[i][j] + boldStop + endCol);
bufferOut.newLine();
break;
}
if(output[i][j] == null) {
output[i][j] = "";
startCol = startColEmpty;
} else if(j == 0) {
startCol = startColName;
} else if(j == 1) {
startCol = startColClub;
} else if(j == 2 && extras[1]) {
startCol = startColLicense;
} else if((j == 2 && extras[2]) || (j == 3 && (extras[1] && extras[2]))) {
startCol = startColStartNbr;
} else if((j == output[i].length-1 && extras[0]) || (j == output[i].length-2 && extras[0])) {
startCol = startColPlaceNbr;
} else {
startCol = startColResult;
}
if(outputStyle[i][j].startsWith("S:a") || output[i][j].startsWith("S:a")) {
startCol = startColSum;
outputStyle[i][j] = outputStyle[i][j].replaceFirst("S:a", "");
}
if (! outputStyle[i][j].equals("black"))
startCol = addStyle(startCol, "color", outputStyle[i][j]);
bufferOut.write(startCol + boldStart + output[i][j] + boldStop + endCol);
bufferOut.newLine();
}
bufferOut.write(endRow);
bufferOut.newLine();
} else if (outputStyle[i][0] == null || !outputStyle[i][0].equals("Bold+")) {
bufferOut.write("<tr><td style=\"height:15px\"> </td></tr>");
bufferOut.newLine();
}
}
bufferOut.write("</table>");
bufferOut.newLine();
bufferOut.write("<p><br>");
bufferOut.newLine();
bufferOut.write("<div style=\"font-size:7.5pt\">Denna sida r skapad av <a href=\"http://bangolfresultat.manet.se/\">"
+ "BangolfResultat</a></div>");
bufferOut.newLine();
bufferOut.write("</body>");
bufferOut.newLine();
bufferOut.write("</html>");
bufferOut.flush();
bufferOut.close();
}
/** skriver ut resultatlistan result till en semikolonseparerad fil med namnet fileName dr tvlingens namn stts till header */
public void outputToSKV(String fileName, String fileNameHTM, ResultList result,
String header, boolean[] editData) throws IOException {
LinkedList res = result.sortResults();
BufferedWriter bufferOut = getTextFileWriter(fileName);
if(header.equals("")) {
header = " ";
}
bufferOut.write(header);
bufferOut.write(";");
if(fileNameHTM == null || fileNameHTM.equals("")) {
fileNameHTM = "null";
}
bufferOut.write(fileNameHTM);
bufferOut.newLine();
bufferOut.write(String.valueOf(result.getNbrRounds()));
bufferOut.write(";");
bufferOut.write(String.valueOf(result.getSurface()));
bufferOut.write(";");
bufferOut.write(String.valueOf(result.getExtraData()));
bufferOut.write(";");
for(int i = 0; i < editData.length; i++) {
if(editData[i]) {
bufferOut.write("1");
} else {
bufferOut.write("0");
}
}
for(int i = 0; i < res.size(); i++) {
PersonResult pr = (PersonResult) res.get(i);
String name = pr.getName();
String club = pr.getClub();
String ident = (new Integer(pr.getPersonID())).toString();
bufferOut.newLine();
bufferOut.write(String.valueOf(pr.getStartNr()));
bufferOut.write(";");
bufferOut.write(name);
bufferOut.write(";");
bufferOut.write(club);
bufferOut.write(";");
bufferOut.write(String.valueOf(pr.getLicenseNr()));
bufferOut.write(";");
bufferOut.write(pr.getKlass());
bufferOut.write(";");
bufferOut.write(String.valueOf(pr.getPrio()));
bufferOut.write(";");
bufferOut.write(String.valueOf(pr.getRounds()));
bufferOut.write(";");
int nbrRoundsFinished = pr.getNbrRoundsFinished();
bufferOut.write(String.valueOf(nbrRoundsFinished));
int[] results = pr.getResultList();
for(int j = 0; j < nbrRoundsFinished; j++) {
bufferOut.write(";");
bufferOut.write(String.valueOf(results[j]));
}
bufferOut.write(";");
bufferOut.write(ident);
}
bufferOut.flush();
bufferOut.close();
}
/** skriver ut resultatlistan result till en semikolonseparerad fil med namnet fileName dr tvlingens namn stts till header */
public void outputToSNITT(String fileName, CompareFile compareFile) throws IOException {
LinkedList res = compareFile.sortResults();
BufferedWriter bufferOut = getTextFileWriter(fileName);
bufferOut.write(String.valueOf(compareFile.getSurface()));
for(int i = 0; i < res.size(); i++) {
PersonMean personMean = (PersonMean) res.get(i);
String idNbr = String.valueOf(personMean.getID());
String name = personMean.getName();
String club = personMean.getClub();
String mean = personMean.getMeanAsString();
bufferOut.newLine();
bufferOut.write(idNbr);
bufferOut.write(";");
bufferOut.write(name);
bufferOut.write(";");
bufferOut.write(club);
bufferOut.write(";");
bufferOut.write(mean);
}
bufferOut.flush();
bufferOut.close();
}
/** lser in resultat frn en semikolonseparerad fil med filnamnet fileName
returnerar tvlingens namn, resultatlista samt startnummer- och idnummerhashmap */
public Object[] inputFromSKV(String fileName) throws IOException, NoSuchElementException {
boolean[] editData;
boolean[] startData = new boolean[2];
startData[0] = false;
startData[1] = false;
Object[] objects = new Object[5];
BufferedReader fileIn = getTextFileReader(fileName);
String inLine = fileIn.readLine();
StringTokenizer inString = new StringTokenizer(inLine, ";");
String header = inString.nextToken();
if(header.equals(" ")) {
header = "";
}
objects[0] = header;
try {
String fileNameHTM = inString.nextToken();
if(fileNameHTM.equals("null")) {
throw new NullPointerException();
}
objects[1] = fileNameHTM;
} catch (Exception e) {
objects[1] = null;
}
inLine = fileIn.readLine();
inString = new StringTokenizer(inLine, ";");
int nbrRounds = Integer.parseInt(inString.nextToken());
int surface = Integer.parseInt(inString.nextToken());
int extraData = Integer.parseInt(inString.nextToken());
if(extraData == ResultList.START_AND_ID_NBR) {
startData[0] = true;
startData[1] = true;
} else if(extraData == ResultList.START_NBR) {
startData[0] = true;
} else if(extraData == ResultList.ID_NBR) {
startData[1] = true;
}
editData = new boolean[1+nbrRounds-2];
try {
String editString = inString.nextToken();
for(int i = 0; i < editData.length; i++) {
if(editString.charAt(i) == '1') {
editData[i] = true;
} else {
editData[i] = false;
}
}
} catch (Exception e) {
for(int i = 0; i < editData.length; i++) {
editData[i] = false;
}
}
ResultList res = new ResultList(nbrRounds, surface, startData);
HashMap startNbrMap = new HashMap();
if(inLine != null) {
inLine = fileIn.readLine();
while (inLine != null) {
inString = new StringTokenizer(inLine, ";");
if(inString.countTokens() != 0) {
int startNr = Integer.parseInt(inString.nextToken());
startNbrMap.put(new Integer(startNr), null);
String name = inString.nextToken();
String club = inString.nextToken();
String licenseNr = inString.nextToken();
String klass = inString.nextToken();
int prioNr = Integer.parseInt(inString.nextToken());
nbrRounds = Integer.parseInt(inString.nextToken());
int nbrRoundsFinished = Integer.parseInt(inString.nextToken());
int[] results = new int[nbrRounds];
for(int i = 0; i < nbrRoundsFinished; i++) {
results[i] = Integer.parseInt(inString.nextToken());
}
int personID = Integer.parseInt(inString.nextToken());
res.addResult(startNr, name, club, licenseNr, results, nbrRounds, klass, prioNr, nbrRoundsFinished, personID);
}
inLine = fileIn.readLine();
}
}
fileIn.close();
objects[2] = res;
objects[3] = startNbrMap;
objects[4] = editData;
return objects;
}
/** lser in resultat frn en semikolonseparerad fil med filnamnet fileName
returnerar tvlingens namn, resultatlista samt startnummer- och idnummerhashmap */
public CompareFile inputFromSNITT(String fileName) throws IOException, NoSuchElementException {
BufferedReader fileIn = getTextFileReader(fileName);
String inLine = fileIn.readLine();
int surface = Integer.parseInt(inLine);
CompareFile compareFile = new CompareFile(surface);
StringTokenizer inString;
if(inLine != null) {
inLine = fileIn.readLine();
while (inLine != null) {
inString = new StringTokenizer(inLine, ";");
if(inString.countTokens() != 0) {
Integer idNbr = Integer.valueOf(inString.nextToken());
String name = inString.nextToken();
String club = inString.nextToken();
double mean = Double.parseDouble(inString.nextToken());
compareFile.addMean(idNbr, name, club, mean);
}
inLine = fileIn.readLine();
}
}
fileIn.close();
return compareFile;
}
/** skriver ut en lista med vilka strngar som r valda och vilka som ej r valda till filen fileName
utifrn innehllet i vektorn v */
public void writeFileList(String fileName, Vector[] v) throws IOException {
Vector[] vector = v;
BufferedWriter bufferOut = getTextFileWriter(getSettingsPath()
+ fileName);
for(int i = 0; i < vector.length; i++) {
if(i%2 == 0) {
bufferOut.write("Unselected");
} else {
bufferOut.write("Selected");
}
bufferOut.newLine();
for(int j = 0; j < vector[i].size(); j++) {
bufferOut.write((String)vector[i].get(j));
bufferOut.newLine();
}
}
bufferOut.flush();
bufferOut.close();
}
/** lser in antalet size listor med vilka strngar som r valda och ej valda frn filen fileName */
public Vector[] readFileList(String fileName, int size) throws IOException {
Vector[] vector = new Vector[size];
for(int i = 0; i < vector.length; i++) {
vector[i] = new Vector();
}
BufferedReader fileIn = getTextFileReader(getSettingsPath()
+ fileName);
String inLine = fileIn.readLine();
int i = -1;
while(inLine != null && !inLine.trim().equals("")) {
if(inLine.equals("Selected") || inLine.equals("Unselected")) {
i++;
} else {
vector[i].addElement(inLine);
}
inLine = fileIn.readLine();
}
fileIn.close();
return vector;
}
/** lser av vilken sorts underlag tvlingen i filen fileName har spelats p */
public int readSurface(String fileName) throws IOException, NoSuchElementException {
BufferedReader fileIn = getTextFileReader(fileName);
String inLine = fileIn.readLine();
inLine = fileIn.readLine();
StringTokenizer inString = new StringTokenizer(inLine, ";");
inString.nextToken();
int surface = Integer.parseInt(inString.nextToken());
fileIn.close();
return surface;
}
/**
* Returns a {@link BufferedReader} for the given file name. The file will
* be read according to charset UTF-8 if the first line in the file equals
* <tt>UTF-8</tt>, otherwise the default charset will be used.
*
* @param fileName name of the file to read
* @return a BufferedReader for the file represented by the
* given file name
* @throws IOException if an I/O error occurs
*/
public static BufferedReader getTextFileReader(String fileName) throws IOException {
BufferedReader fileIn = new BufferedReader(new InputStreamReader(
new FileInputStream(fileName), "UTF-8"
));
String inLine = fileIn.readLine();
if (inLine == null)
{
// do nothing, default charset will be used
}
else if (inLine.equals("UTF-8"))
{
return fileIn;
}
// use default charset
fileIn.close();
return new BufferedReader(new FileReader(fileName));
}
/**
* Returns a {@link BufferedWriter} for the given file name. Charset UTF-8
* is used and this method writes the first line of the file as
* <tt>UTF-8</tt> before the {@link BufferedWriter} is returned.
*
* @param fileName name of the file for which to get a
* {@link BufferedWriter}
* @return a {@link BufferedWriter} using charset UTF-8
* @throws IOException if an I/O error occurs
*/
public static BufferedWriter getTextFileWriter(String fileName) throws IOException {
BufferedWriter bufferOut = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")
);
bufferOut.write("UTF-8");
bufferOut.newLine();
return bufferOut;
}
/** sparar objektet o till filen file */
public void save(String file, Object o) throws IOException {
FileOutputStream fos;
ObjectOutputStream os;
fos = new FileOutputStream(getSettingsPath() + file);
os = new ObjectOutputStream(fos);
os.writeObject(o);
os.close();
}
/** returnerar objektet som lsts in frn filen file */
public Object load(String file) throws IOException, ClassNotFoundException {
FileInputStream fis;
ObjectInputStream ois;
Object o = null;
fis = new FileInputStream(getSettingsPath() + file);
ois = new ObjectInputStream(fis);
o = ois.readObject();
ois.close();
return o;
}
/** loggar informationen om ett exception som har uppsttt till filen error.log
* och returnerar true om operationen lyckas */
public static boolean logError(Throwable throwable) {
LinkedList list = new LinkedList();
try {
BufferedReader fileIn = getTextFileReader("error.log");
String inLine = fileIn.readLine();
while(inLine != null) {
list.add(inLine);
inLine = fileIn.readLine();
}
fileIn.close();
} catch (Exception e) {}
try {
PrintStream printStream = new PrintStream("error.log", "UTF-8");
printStream.println("UTF-8");
Date date = new Date(System.currentTimeMillis());
printStream.println(date.toString());
throwable.printStackTrace(printStream);
printStream.println();
while(list.size() != 0) {
printStream.println((String)list.removeFirst());
}
printStream.flush();
printStream.close();
} catch (Exception e) {
return false;
}
return true;
}
/** lgger till ett styleproperty till en HTML-tagg */
public static String addStyle(String tag, String property, String value) {
int styleIndex = tag.indexOf("style");
if (styleIndex == -1) {
int endOfTag;
if (tag.endsWith(">")) {
endOfTag = tag.lastIndexOf('>');
} else {
return tag;
}
String begin = tag.substring(0, endOfTag);
String end = tag.substring(endOfTag, tag.length());
tag = begin + " style=\"\"" + end;
}
int startQuoteIndex = tag.indexOf('"', styleIndex);
int endQuoteIndex = tag.indexOf('"', startQuoteIndex+1);
if (startQuoteIndex != -1 && endQuoteIndex != -1) {
String begin = tag.substring(0, endQuoteIndex);
String end = tag.substring(endQuoteIndex, tag.length());
String separator;
if (startQuoteIndex + 1 == endQuoteIndex)
separator = "";
else
separator ="; ";
return begin + separator + property + ":" + value + end;
}
return tag;
}
/**
* Returns the path to the application settings directory.
* <p>
* The path contains a trailing system-depending name-separator character.
*
* @return the path to the application settings directory
*/
public static String getSettingsPath() {
if (settingsPath == null) {
String settingsPathProperty = System.getProperty("settingsPath");
if (settingsPathProperty != null) {
settingsPath = getCanonicalPath(new File(settingsPathProperty));
} else {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
String appDataFolder = System.getenv("AppData");
settingsPath = getCanonicalPath(new File(appDataFolder
+ File.separator + "BangolfResultat"
+ File.separator + "Settings" + File.separator));
} else {
settingsPath = getCanonicalPath(new File("settings"
+ File.separator));
}
}
settingsPath += File.separator;
}
return settingsPath;
}
/**
* Returns the path to the icons directory.
* <p>
* The path contains a trailing system-depending name-separator character.
*
* @return the path to the icons directory
*/
public static String getIconsPath() {
if (iconsPath == null) {
iconsPath = getCanonicalPath(new File("icons"
+ File.separator));
iconsPath += File.separator;
}
return iconsPath;
}
/**
* Returns the canonical path for the given file, or the absolute path if an
* error occurs while getting the canonical path.
*
* @param file
* file to get canonical path for
* @return the canonical path, or the absolute path if an error occurs
*/
public static String getCanonicalPath(File file) {
try {
return file.getCanonicalPath();
} catch (IOException e) {
return file.getAbsolutePath();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.