answer
stringlengths 17
10.2M
|
|---|
package fr.adrienbrault.idea.symfony2plugin.routing;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.LineMarkerProvider;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.jetbrains.php.lang.psi.PhpFile;
import com.jetbrains.php.lang.psi.elements.*;
import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons;
import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;
import fr.adrienbrault.idea.symfony2plugin.util.resource.FileResourceUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpLineMarkerProvider implements LineMarkerProvider {
@Nullable
@Override
public LineMarkerInfo<?> getLineMarkerInfo(@NotNull PsiElement psiElement) {
return null;
}
@Override
public void collectSlowLineMarkers(@NotNull List<? extends PsiElement> psiElements, @NotNull Collection<? super LineMarkerInfo<?>> lineMarkerInfos) {
if(psiElements.size() == 0 || !Symfony2ProjectComponent.isEnabled(psiElements.get(0))) {
return;
}
for(PsiElement psiElement : psiElements) {
attachRouteActions(lineMarkerInfos, psiElement);
if(psiElement instanceof PhpFile) {
RelatedItemLineMarkerInfo<PsiElement> lineMarker = FileResourceUtil.getFileImplementsLineMarker((PsiFile) psiElement);
if(lineMarker != null) {
lineMarkerInfos.add(lineMarker);
}
}
}
}
private void attachRouteActions(@NotNull Collection<? super LineMarkerInfo<?>> lineMarkerInfos, @NotNull PsiElement psiElement) {
if (!(psiElement instanceof MethodReference)) {
return;
}
MethodReference methodCall = (MethodReference) psiElement;
String controllerMethod = RouteHelper.getPhpController(methodCall);
PsiElement[] methods = RouteHelper.getMethodsOnControllerShortcut(psiElement.getProject(), controllerMethod);
if(methods.length > 0) {
NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.TWIG_CONTROLLER_LINE_MARKER).
setTargets(methods).
setTooltipText("Navigate to action");
lineMarkerInfos.add(builder.createLineMarkerInfo(methodCall.getParameters()[0].getFirstChild()));
}
}
}
|
package io.github.lukehutch.fastclasspathscanner.scanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner;
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner.ClassMatcher;
import io.github.lukehutch.fastclasspathscanner.classfileparser.ClassInfo;
import io.github.lukehutch.fastclasspathscanner.classfileparser.ClassInfo.ClassInfoUnlinked;
import io.github.lukehutch.fastclasspathscanner.classfileparser.ClassfileBinaryParser;
import io.github.lukehutch.fastclasspathscanner.classgraph.ClassGraphBuilder;
import io.github.lukehutch.fastclasspathscanner.classpath.ClasspathFinder;
import io.github.lukehutch.fastclasspathscanner.matchprocessor.StaticFinalFieldMatchProcessor;
import io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.ScanSpecPathMatch;
import io.github.lukehutch.fastclasspathscanner.utils.Log;
import io.github.lukehutch.fastclasspathscanner.utils.Log.DeferredLog;
public class RecursiveScanner {
/**
* The number of threads to use for parsing classfiles in parallel. Empirical testing shows that on a modern
* system with an SSD, NUM_THREADS = 6 is a good default. Raising the number of threads too high can actually
* hurt performance due to storage contention.
*/
private final int NUM_THREADS = 6;
/** The classpath finder. */
private final ClasspathFinder classpathFinder;
/** The scanspec (whitelisted and blacklisted packages, etc.). */
private final ScanSpec scanSpec;
/** The class matchers. */
private final ArrayList<ClassMatcher> classMatchers;
/** A map from class name to static final fields to match within the class. */
private final Map<String, HashSet<String>> classNameToStaticFinalFieldsToMatch;
/**
* A map from (className + "." + staticFinalFieldName) to StaticFinalFieldMatchProcessor(s) that should be
* called if that class name and static final field name is encountered with a static constant initializer
* during scan.
*/
private final Map<String, ArrayList<StaticFinalFieldMatchProcessor>>
fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors;
/** A list of file path testers and match processor wrappers to use for file matching. */
private final List<FilePathTesterAndMatchProcessorWrapper> filePathTestersAndMatchProcessorWrappers =
new ArrayList<>();
/**
* The set of absolute directory/zipfile paths scanned (after symlink resolution), to prevent the same resource
* from being scanned twice.
*/
private final Set<String> previouslyScannedCanonicalPaths = new HashSet<>();
/**
* The set of relative file paths scanned (without symlink resolution), to allow for classpath masking of
* resources (only the first resource with a given relative path should be visible within the classpath, as per
* Java conventions).
*/
private final Set<String> previouslyScannedRelativePaths = new HashSet<>();
/** A map from class name to ClassInfo object for the class. */
private final Map<String, ClassInfo> classNameToClassInfo = new HashMap<>();
/** The class graph builder. */
private ClassGraphBuilder classGraphBuilder;
/** The total number of regular directories scanned. */
private final AtomicInteger numDirsScanned = new AtomicInteger();
/** The total number of jarfile-internal directories scanned. */
private final AtomicInteger numJarfileDirsScanned = new AtomicInteger();
/** The total number of regular files scanned. */
private final AtomicInteger numFilesScanned = new AtomicInteger();
/** The total number of jarfile-internal files scanned. */
private final AtomicInteger numJarfileFilesScanned = new AtomicInteger();
/** The total number of jarfiles scanned. */
private final AtomicInteger numJarfilesScanned = new AtomicInteger();
/** The total number of classfiles scanned. */
private final AtomicInteger numClassfilesScanned = new AtomicInteger();
/**
* The latest last-modified timestamp of any file, directory or sub-directory in the classpath, in millis since
* the Unix epoch. Does not consider timestamps inside zipfiles/jarfiles, but the timestamp of the zip/jarfile
* itself is considered.
*/
private long lastModified = 0;
/** An interface used to test whether a file's relative path matches a given specification. */
public static interface FilePathTester {
public boolean filePathMatches(final File classpathElt, final String relativePathStr);
}
/** An interface called when the corresponding FilePathTester returns true. */
public static interface FileMatchProcessorWrapper {
public void processMatch(final File classpathElt, final String relativePath, final InputStream inputStream,
final long fileSize) throws IOException;
}
private static class FilePathTesterAndMatchProcessorWrapper {
FilePathTester filePathTester;
FileMatchProcessorWrapper fileMatchProcessorWrapper;
public FilePathTesterAndMatchProcessorWrapper(final FilePathTester filePathTester,
final FileMatchProcessorWrapper fileMatchProcessorWrapper) {
this.filePathTester = filePathTester;
this.fileMatchProcessorWrapper = fileMatchProcessorWrapper;
}
}
public void addFilePathMatcher(final FilePathTester filePathTester,
final FileMatchProcessorWrapper fileMatchProcessorWrapper) {
filePathTestersAndMatchProcessorWrappers
.add(new FilePathTesterAndMatchProcessorWrapper(filePathTester, fileMatchProcessorWrapper));
}
/**
* Recursive classpath scanner. Pass in a specification of whitelisted packages/jars to scan and blacklisted
* packages/jars not to scan, where blacklisted entries are prefixed with the '-' character.
*
* Examples of values for scanSpecs:
*
* ["com.x"] => scans the package "com.x" and its sub-packages in all directories and jars on the classpath.
*
* ["com.x", "-com.x.y"] => scans "com.x" and all sub-packages except "com.x.y" in all directories and jars on
* the classpath.
*
* ["com.x", "-com.x.y", "jar:deploy.jar"] => scans "com.x" and all sub-packages except "com.x.y", but only
* looks in jars named "deploy.jar" on the classpath (i.e. whitelisting a "jar:" entry prevents non-jar entries
* from being searched). Note that only the leafname of a jarfile can be specified.
*
* ["com.x", "-jar:irrelevant.jar"] => scans "com.x" and all sub-packages in all directories and jars on the
* classpath *except* "irrelevant.jar" (i.e. blacklisting a jarfile doesn't prevent directories from being
* scanned the way that whitelisting a jarfile does).
*
* ["com.x", "jar:"] => scans "com.x" and all sub-packages, but only looks in jarfiles on the classpath, doesn't
* scan directories (i.e. all jars are whitelisted, and whitelisting jarfiles prevents non-jars (directories)
* from being scanned).
*
* ["com.x", "-jar:"] => scans "com.x" and all sub-packages, but only looks in directories on the classpath,
* doesn't scan jarfiles (i.e. all jars are blacklisted.)
*
* @param fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors
*/
public RecursiveScanner(final ClasspathFinder classpathFinder, final ScanSpec scanSpec,
final ArrayList<ClassMatcher> classMatchers,
final Map<String, HashSet<String>> classNameToStaticFinalFieldsToMatch,
final Map<String, ArrayList<StaticFinalFieldMatchProcessor>>
fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors) {
this.classpathFinder = classpathFinder;
this.scanSpec = scanSpec;
this.classMatchers = classMatchers;
this.classNameToStaticFinalFieldsToMatch = classNameToStaticFinalFieldsToMatch;
this.fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors =
fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors;
}
/** The combination of a classpath element and a relative path within this classpath element. */
private static class ClassfileResource {
final File classpathElt;
final String relativePath;
public ClassfileResource(final File classpathElt, final String relativePath) {
this.classpathElt = classpathElt;
this.relativePath = relativePath;
}
}
/**
* Class for calling ClassfileBinaryParser in parallel for classfile resources. Consumes ClassfileResource
* objects from the classfileResourcesToScan queue and produces ClassInfoUnlinked objects, placing them in the
* classInfoUnlinkedOut queue.
*/
private class ClassfileBinaryParserCaller implements Runnable {
private final Queue<ClassfileResource> classpathResources;
private final Queue<ClassInfoUnlinked> classInfoUnlinkedOut;
private final ConcurrentHashMap<String, String> stringInternMap;
private final AtomicBoolean killThreads;
private final DeferredLog log;
public ClassfileBinaryParserCaller(final Queue<ClassfileResource> classfileResourcesToScan,
final Queue<ClassInfoUnlinked> classInfoUnlinkedOut,
final ConcurrentHashMap<String, String> stringInternMap, AtomicBoolean killThreads,
final DeferredLog log) {
this.classpathResources = classfileResourcesToScan;
this.classInfoUnlinkedOut = classInfoUnlinkedOut;
this.stringInternMap = stringInternMap;
this.killThreads = killThreads;
this.log = log;
}
@Override
public void run() {
ZipFile currentlyOpenZipFile = null;
try {
ClassfileResource prevClassfileResource = null;
// Reuse one ClassfileBinaryParser for all classfiles parsed by a given thread, to avoid
// the overhead of re-allocating buffers between classfiles.
final ClassfileBinaryParser classfileBinaryParser = new ClassfileBinaryParser(scanSpec, log);
for (ClassfileResource classfileResource; (classfileResource = classpathResources
.poll()) != null; prevClassfileResource = classfileResource) {
if (killThreads.get()) {
// Some other thread died; kill this one too
return;
}
final long fileStartTime = System.nanoTime();
final boolean classfileResourceIsJar = classfileResource.classpathElt.isFile();
// Compare classpath element of current resource to that of previous resource
if (prevClassfileResource == null
|| classfileResource.classpathElt != prevClassfileResource.classpathElt) {
// Classpath element has changed
if (currentlyOpenZipFile != null) {
// Close previous zipfile, if one is open
try {
currentlyOpenZipFile.close();
} catch (final IOException e) {
// Ignore
}
currentlyOpenZipFile = null;
}
if (classfileResourceIsJar) {
// Open a new zipfile, if new resource is a jar
try {
currentlyOpenZipFile = new ZipFile(classfileResource.classpathElt);
} catch (final IOException e) {
if (FastClasspathScanner.verbose) {
log.log(2, "Exception while trying to open " + classfileResource.classpathElt
+ ": " + e);
}
continue;
}
}
}
// Get input stream from classpath element and relative path
try (InputStream inputStream = classfileResourceIsJar
? currentlyOpenZipFile
.getInputStream(currentlyOpenZipFile.getEntry(classfileResource.relativePath))
: new FileInputStream(classfileResource.classpathElt.getPath() + File.separator
+ (File.separatorChar == '/' ? classfileResource.relativePath
: classfileResource.relativePath.replace('/', File.separatorChar)))) {
// Parse classpath binary format, creating a ClassInfoUnlinked object
final ClassInfoUnlinked thisClassInfoUnlinked = classfileBinaryParser
.readClassInfoFromClassfileHeader(inputStream, classfileResource.relativePath,
classNameToStaticFinalFieldsToMatch, stringInternMap);
// If class was successfully read, add new ClassInfoUnlinked object to output queue
if (thisClassInfoUnlinked != null) {
classInfoUnlinkedOut.add(thisClassInfoUnlinked);
// Log info about class
thisClassInfoUnlinked.logClassInfo(log);
}
} catch (final IOException e) {
if (FastClasspathScanner.verbose) {
log.log(2,
"Exception while trying to open " + classfileResource.relativePath + ": " + e);
}
}
if (FastClasspathScanner.verbose) {
log.log(3, "Parsed classfile " + classfileResource.relativePath,
System.nanoTime() - fileStartTime);
}
}
} finally {
if (currentlyOpenZipFile != null) {
// Close last zipfile
try {
currentlyOpenZipFile.close();
} catch (final IOException e) {
// Ignore
}
currentlyOpenZipFile = null;
}
}
}
}
/**
* Return true if the canonical path (after resolving symlinks and getting absolute path) for this dir, jarfile
* or file hasn't been seen before during this scan.
*/
private boolean previouslyScanned(final File fileOrDir) {
try {
// Get canonical path (resolve symlinks, and make the path absolute), then see if this canonical path
// has been scanned before
return !previouslyScannedCanonicalPaths.add(fileOrDir.getCanonicalPath());
} catch (final IOException | SecurityException e) {
// If something goes wrong while getting the real path, just return true.
return true;
}
}
/**
* Return true if the relative path for this file hasn't been seen before during this scan (indicating that a
* resource at this path relative to the classpath hasn't been scanned).
*/
private boolean previouslyScanned(final String relativePath) {
return !previouslyScannedRelativePaths.add(relativePath);
}
/**
* Scan a directory for matching file path patterns.
*/
private void scanDir(final File classpathElt, final File dir, final int ignorePrefixLen,
boolean inWhitelistedPath, final boolean scanTimestampsOnly,
final Queue<ClassfileResource> classfileResourcesToScanOut) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Scanning directory: " + dir);
}
updateLastModifiedTimestamp(dir.lastModified());
numDirsScanned.incrementAndGet();
final String dirPath = dir.getPath();
final String dirRelativePath = ignorePrefixLen > dirPath.length() ? "/"
: dirPath.substring(ignorePrefixLen).replace(File.separatorChar, '/') + "/";
final ScanSpecPathMatch matchStatus = scanSpec.pathWhitelistMatchStatus(dirRelativePath);
if (matchStatus == ScanSpecPathMatch.NOT_WITHIN_WHITELISTED_PATH
|| matchStatus == ScanSpecPathMatch.WITHIN_BLACKLISTED_PATH) {
// Reached a non-whitelisted or blacklisted path -- stop the recursive scan
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached non-whitelisted (or blacklisted) directory: " + dirRelativePath);
}
return;
} else if (matchStatus == ScanSpecPathMatch.WITHIN_WHITELISTED_PATH) {
// Reached a whitelisted path -- can start scanning directories and files from this point
inWhitelistedPath = true;
}
final long startTime = System.nanoTime();
final File[] filesInDir = dir.listFiles();
if (filesInDir == null) {
if (FastClasspathScanner.verbose) {
Log.log(4, "Invalid directory " + dir);
}
return;
}
for (final File fileInDir : filesInDir) {
if (fileInDir.isDirectory()) {
if (inWhitelistedPath
|| matchStatus == ScanSpecPathMatch.ANCESTOR_OF_WHITELISTED_PATH) {
// Recurse into subdirectory
scanDir(classpathElt, fileInDir, ignorePrefixLen, inWhitelistedPath, scanTimestampsOnly,
classfileResourcesToScanOut);
}
} else if (fileInDir.isFile()) {
final String fileInDirRelativePath = dirRelativePath.isEmpty() || "/".equals(dirRelativePath)
? fileInDir.getName() : dirRelativePath + fileInDir.getName();
// Class can only be scanned if it's within a whitelisted path subtree, or if it is a classfile
// that has been specifically-whitelisted
if (!inWhitelistedPath && (matchStatus != ScanSpecPathMatch.AT_WHITELISTED_CLASS_PACKAGE
|| !scanSpec.isSpecificallyWhitelistedClass(fileInDirRelativePath))) {
// Ignore files that are siblings of specifically-whitelisted files, but that are not
// themselves specifically whitelisted
continue;
}
// Make sure file with same absolute path or same relative path hasn't been scanned before.
// (N.B. don't inline these two different calls to previouslyScanned() into a single expression
// using "||", because they have intentional side effects)
final boolean subFilePreviouslyScannedCanonical = previouslyScanned(fileInDir);
final boolean subFilePreviouslyScannedRelative = previouslyScanned(fileInDirRelativePath);
if (subFilePreviouslyScannedRelative || subFilePreviouslyScannedCanonical) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached duplicate path, ignoring: " + fileInDirRelativePath);
}
continue;
}
if (FastClasspathScanner.verbose) {
Log.log(3, "Found whitelisted file: " + fileInDirRelativePath);
}
updateLastModifiedTimestamp(fileInDir.lastModified());
if (!scanTimestampsOnly) {
boolean matchedFile = false;
// Store relative paths of any classfiles encountered
if (fileInDirRelativePath.endsWith(".class")) {
matchedFile = true;
classfileResourcesToScanOut.add(new ClassfileResource(classpathElt, fileInDirRelativePath));
numClassfilesScanned.incrementAndGet();
}
// Match file paths against path patterns
for (final FilePathTesterAndMatchProcessorWrapper fileMatcher :
filePathTestersAndMatchProcessorWrappers) {
if (fileMatcher.filePathTester.filePathMatches(classpathElt, fileInDirRelativePath)) {
// File's relative path matches.
matchedFile = true;
final long fileStartTime = System.nanoTime();
try (FileInputStream inputStream = new FileInputStream(fileInDir)) {
fileMatcher.fileMatchProcessorWrapper.processMatch(classpathElt,
fileInDirRelativePath, inputStream, fileInDir.length());
} catch (final Exception e) {
throw new RuntimeException(
"Exception while processing match " + fileInDirRelativePath, e);
}
if (FastClasspathScanner.verbose) {
Log.log(4, "Processed file match " + fileInDirRelativePath,
System.nanoTime() - fileStartTime);
}
}
}
if (matchedFile) {
numFilesScanned.incrementAndGet();
}
}
}
}
if (FastClasspathScanner.verbose) {
Log.log(3, "Scanned directory " + dir + " and subdirectories", System.nanoTime() - startTime);
}
}
/**
* Scan a zipfile for matching file path patterns.
*/
private void scanZipfile(final File classpathElt, final ZipFile zipFile,
final Queue<ClassfileResource> classfileResourcesToScanOut) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Scanning jarfile: " + classpathElt);
}
final long startTime = System.nanoTime();
String prevParentRelativePath = null;
ScanSpecPathMatch prevParentMatchStatus = null;
for (final Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries.hasMoreElements();) {
final ZipEntry zipEntry = entries.nextElement();
String relativePath = zipEntry.getName();
if (relativePath.startsWith("/")) {
// Shouldn't happen with the standard Java zipfile implementation (but just to be safe)
relativePath = relativePath.substring(1);
}
// Ignore directory entries, they are not needed
final boolean isDir = zipEntry.isDirectory();
if (isDir) {
if (prevParentMatchStatus == ScanSpecPathMatch.WITHIN_WHITELISTED_PATH) {
numJarfileDirsScanned.incrementAndGet();
if (FastClasspathScanner.verbose) {
numJarfileFilesScanned.incrementAndGet();
}
}
continue;
}
// Only accept first instance of a given relative path within classpath.
if (previouslyScanned(relativePath)) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached duplicate relative path, ignoring: " + relativePath);
}
continue;
}
// Get match status of the parent directory if this zipentry file's relative path
// (or reuse the last match status for speed, if the directory name hasn't changed).
final int lastSlashIdx = relativePath.lastIndexOf("/");
final String parentRelativePath = lastSlashIdx < 0 ? "/" : relativePath.substring(0, lastSlashIdx + 1);
final ScanSpecPathMatch parentMatchStatus =
prevParentRelativePath == null || !parentRelativePath.equals(prevParentRelativePath)
? scanSpec.pathWhitelistMatchStatus(parentRelativePath) : prevParentMatchStatus;
prevParentRelativePath = parentRelativePath;
prevParentMatchStatus = parentMatchStatus;
// Class can only be scanned if it's within a whitelisted path subtree, or if it is a classfile
// that has been specifically-whitelisted
if (parentMatchStatus != ScanSpecPathMatch.WITHIN_WHITELISTED_PATH
&& (parentMatchStatus != ScanSpecPathMatch.AT_WHITELISTED_CLASS_PACKAGE
|| !scanSpec.isSpecificallyWhitelistedClass(relativePath))) {
continue;
}
if (FastClasspathScanner.verbose) {
Log.log(3, "Found whitelisted file in jarfile: " + relativePath);
}
boolean matchedFile = false;
// Store relative paths of any classfiles encountered
if (relativePath.endsWith(".class")) {
matchedFile = true;
classfileResourcesToScanOut.add(new ClassfileResource(classpathElt, relativePath));
numClassfilesScanned.incrementAndGet();
}
// Match file paths against path patterns
for (final FilePathTesterAndMatchProcessorWrapper fileMatcher :
filePathTestersAndMatchProcessorWrappers) {
if (fileMatcher.filePathTester.filePathMatches(classpathElt, relativePath)) {
// File's relative path matches.
try {
matchedFile = true;
final long fileStartTime = System.nanoTime();
try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
fileMatcher.fileMatchProcessorWrapper.processMatch(classpathElt, relativePath,
inputStream, zipEntry.getSize());
}
if (FastClasspathScanner.verbose) {
Log.log(4, "Processed file match " + relativePath, System.nanoTime() - fileStartTime);
}
} catch (final Exception e) {
throw new RuntimeException("Exception while processing match " + relativePath, e);
}
}
}
if (matchedFile) {
numJarfileFilesScanned.incrementAndGet();
}
}
if (FastClasspathScanner.verbose) {
Log.log(4, "Scanned jarfile " + classpathElt, System.nanoTime() - startTime);
}
}
/**
* Scan the classpath, and call any MatchProcessors on files or classes that match.
*
* @param scanTimestampsOnly
* If true, scans the classpath for matching files, and calls any match processors if a match is
* identified. If false, only scans timestamps of files.
*/
private synchronized void scan(final boolean scanTimestampsOnly) {
if (FastClasspathScanner.verbose) {
Log.log("FastClasspathScanner version " + FastClasspathScanner.getVersion());
}
final long scanStart = System.nanoTime();
// Get classpath elements
final List<File> uniqueClasspathElts = classpathFinder.getUniqueClasspathElements();
if (FastClasspathScanner.verbose) {
Log.log("Classpath elements: " + classpathFinder.getUniqueClasspathElements());
}
// Initialize scan
previouslyScannedCanonicalPaths.clear();
previouslyScannedRelativePaths.clear();
numDirsScanned.set(0);
numFilesScanned.set(0);
numJarfileDirsScanned.set(0);
numJarfileFilesScanned.set(0);
numJarfilesScanned.set(0);
numClassfilesScanned.set(0);
if (!scanTimestampsOnly) {
classNameToClassInfo.clear();
}
if (FastClasspathScanner.verbose) {
Log.log(1, "Starting scan" + (scanTimestampsOnly ? " (scanning classpath timestamps only)" : ""));
}
// Iterate through path elements and recursively scan within each directory and jar for matching paths
final Queue<ClassfileResource> classfileResourcesToScan = new ConcurrentLinkedQueue<>();
for (final File classpathElt : uniqueClasspathElts) {
final long eltStartTime = System.nanoTime();
final String path = classpathElt.getPath();
// ClasspathFinder determines that anything that is not a directory is a jarfile
final boolean isDirectory = classpathElt.isDirectory(), isJar = !isDirectory;
if (previouslyScanned(classpathElt)) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached duplicate classpath entry, ignoring: " + classpathElt);
}
continue;
}
if (FastClasspathScanner.verbose) {
Log.log(2, "Found " + (isDirectory ? "directory" : "jar") + " on classpath: " + path);
}
if (isDirectory && scanSpec.scanNonJars) {
// Scan within a directory tree and call file MatchProcessors on any matches
// Scan dirs recursively, looking for matching paths; call FileMatchProcessors on any matches.
// Also store relative paths of all whitelisted classfiles in whitelistedClassfileRelativePaths.
scanDir(classpathElt, classpathElt, /* ignorePrefixLen = */ path.length() + 1,
/* inWhitelistedPath = */ false, scanTimestampsOnly, classfileResourcesToScan);
if (FastClasspathScanner.verbose) {
Log.log(2, "Scanned classpath directory " + classpathElt, System.nanoTime() - eltStartTime);
}
} else if (isJar && scanSpec.scanJars) {
// Scan within a jar/zipfile and call file MatchProcessors on any matches
if (!scanSpec.jarIsWhitelisted(classpathElt.getName())) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Skipping jarfile that did not match whitelist/blacklist criteria: "
+ classpathElt.getName());
}
continue;
}
// Use the timestamp of the jar/zipfile as the timestamp for all files,
// since the timestamps within the zip directory may be unreliable.
updateLastModifiedTimestamp(classpathElt.lastModified());
numJarfilesScanned.incrementAndGet();
if (!scanTimestampsOnly) {
// Don't actually scan the contents of the zipfile if we're only scanning timestamps,
// since only the timestamp of the zipfile itself will be used.
try (ZipFile zipFile = new ZipFile(classpathElt)) {
scanZipfile(classpathElt, zipFile, classfileResourcesToScan);
} catch (final IOException e) {
// Ignore, can only be thrown by zipFile.close()
}
if (FastClasspathScanner.verbose) {
Log.log(2, "Scanned classpath jarfile " + classpathElt, System.nanoTime() - eltStartTime);
}
}
} else {
if (FastClasspathScanner.verbose) {
Log.log(2, "Skipping classpath element " + path);
}
}
}
// Parse classfile binary format for all classfiles found in this classpath element,
// and populate classNameToClassInfo with ClassInfo objects for each classfile and the
// classes they reference (as superclasses, interfaces etc.).
if (FastClasspathScanner.verbose) {
Log.log(1, "Starting parallel scan of classfile binaries");
}
final long parseStartTime = System.nanoTime();
// Create one logger per thread, so that log output is not interleaved
final DeferredLog[] logs = new DeferredLog[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
logs[i] = new DeferredLog();
}
// Scan classfiles in parallel
final Queue<ClassInfoUnlinked> classInfoUnlinked = new ConcurrentLinkedQueue<>();
final ConcurrentHashMap<String, String> stringInternMap = new ConcurrentHashMap<>();
final Thread[] threads = new Thread[NUM_THREADS];
final AtomicBoolean killThreads = new AtomicBoolean(false);
try {
for (int i = 0; i < NUM_THREADS; i++) {
// Create and start a new ClassfileBinaryParserCaller thread that consumes entries from
// the classfileResourcesToScan queue and creates objects in the classInfoUnlinked queue
threads[i] = new Thread(this.new ClassfileBinaryParserCaller(classfileResourcesToScan,
classInfoUnlinked, stringInternMap, killThreads, logs[i]));
threads[i].start();
}
} finally {
// Wait for thread termination
boolean wasInterrupted = false;
for (int i = 0; i < NUM_THREADS; i++) {
if (threads[i] != null) {
try {
threads[i].join();
threads[i] = null;
} catch (final InterruptedException e) {
// Kill remaining threads
killThreads.set(true);
// Try joining this thread again
--i;
}
}
// Dump out any log output that was added by this thread
logs[i].flush();
}
if (wasInterrupted) {
// Set interrupted status on current thread
Thread.currentThread().interrupt();
}
}
if (FastClasspathScanner.verbose) {
Log.log(2, "Parsed classfile binaries", System.nanoTime() - parseStartTime);
}
// Build class graph and call class MatchProcessors on any matches
final long graphStartTime = System.nanoTime();
// Convert ClassInfoUnlinked to linked ClassInfo objects
for (final ClassInfoUnlinked c : classInfoUnlinked) {
c.link(classNameToClassInfo);
}
// After creating ClassInfo objects for each classfile, build the class graph, and run any
// MatchProcessors on matching classes.
if (!scanTimestampsOnly) {
// Build class, interface and annotation graph out of all the ClassInfo objects.
classGraphBuilder = new ClassGraphBuilder(classNameToClassInfo);
// Call any class, interface and annotation MatchProcessors
for (final ClassMatcher classMatcher : classMatchers) {
classMatcher.lookForMatches();
}
// Call static final field match processors on matching fields
for (final ClassInfo classInfo : classNameToClassInfo.values()) {
if (classInfo.fieldValues != null) {
for (final Entry<String, Object> ent : classInfo.fieldValues.entrySet()) {
final String fieldName = ent.getKey();
final Object constValue = ent.getValue();
final String fullyQualifiedFieldName = classInfo.className + "." + fieldName;
final ArrayList<StaticFinalFieldMatchProcessor> staticFinalFieldMatchProcessors =
fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors
.get(fullyQualifiedFieldName);
if (staticFinalFieldMatchProcessors != null) {
if (FastClasspathScanner.verbose) {
Log.log(1, "Calling MatchProcessor for static final field " + classInfo.className
+ "." + fieldName + " = " + constValue);
}
for (final StaticFinalFieldMatchProcessor staticFinalFieldMatchProcessor :
staticFinalFieldMatchProcessors) {
staticFinalFieldMatchProcessor.processMatch(classInfo.className, fieldName,
constValue);
}
}
}
}
}
}
if (FastClasspathScanner.verbose) {
Log.log(2, "Built class graph", System.nanoTime() - graphStartTime);
}
if (FastClasspathScanner.verbose) {
Log.log(1, "Number of resources scanned: directories: " + numDirsScanned.get() + "; files: "
+ numFilesScanned.get() + "; jarfiles: " + numJarfilesScanned.get()
+ "; jarfile-internal directories: " + numJarfileDirsScanned + "; jarfile-internal files: "
+ numJarfileFilesScanned + "; classfiles: " + numClassfilesScanned);
}
if (FastClasspathScanner.verbose) {
Log.log("Finished scan", System.nanoTime() - scanStart);
}
}
/**
* Scan the classpath, and call any MatchProcessors on files or classes that match.
*
* @param scanTimestampsOnly
* If true, scans the classpath for matching files, and calls any match processors if a match is
* identified. If false, only scans timestamps of files.
*/
public void scan() {
scan(/* scanTimestampsOnly = */false);
}
/**
* Get the class, interface and annotation graph builder, containing the results of the last full scan, or null
* if a scan has not yet been completed.
*/
public ClassGraphBuilder getClassGraphBuilder() {
return classGraphBuilder;
}
/** Update the last modified timestamp, given the timestamp of a Path. */
private void updateLastModifiedTimestamp(final long fileLastModified) {
// Find max last modified timestamp, but don't accept values greater than the current time
lastModified = Math.max(lastModified, Math.min(System.currentTimeMillis(), fileLastModified));
}
/**
* Returns true if the classpath contents have been changed since scan() was last called. Only considers
* classpath prefixes whitelisted in the call to the constructor. Returns true if scan() has not yet been run.
* Much faster than standard classpath scanning, because only timestamps are checked, and jarfiles don't have to
* be opened.
*/
public boolean classpathContentsModifiedSinceScan() {
final long oldLastModified = this.lastModified;
if (oldLastModified == 0) {
return true;
} else {
scan(/* scanTimestampsOnly = */true);
final long newLastModified = this.lastModified;
return newLastModified > oldLastModified;
}
}
/**
* Returns the maximum "last modified" timestamp in the classpath (in epoch millis), or zero if scan() has not
* yet been called (or if nothing was found on the classpath).
*
* The returned timestamp should be less than the current system time if the timestamps of files on the
* classpath and the system time are accurate. Therefore, if anything changes on the classpath, this value
* should increase.
*/
public long classpathContentsLastModifiedTime() {
return this.lastModified;
}
}
|
package microsoft.exchange.webservices.data.notification;
import microsoft.exchange.webservices.data.core.EwsServiceXmlReader;
import microsoft.exchange.webservices.data.core.ILazyMember;
import microsoft.exchange.webservices.data.core.LazyMember;
import microsoft.exchange.webservices.data.core.XmlElementNames;
import microsoft.exchange.webservices.data.core.enumeration.notification.EventType;
import microsoft.exchange.webservices.data.core.enumeration.misc.XmlNamespace;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Represents a collection of notification events.
*/
public final class GetEventsResults {
/**
* Watermark in event.
*/
private String newWatermark;
/**
* Subscription id.
*/
private String subscriptionId;
/**
* Previous watermark.
*/
private String previousWatermark;
/**
* True if more events available for this subscription.
*/
private boolean moreEventsAvailable;
/**
* Collection of notification events.
*/
private Collection<NotificationEvent> events =
new ArrayList<NotificationEvent>();
/**
* Map XML element name to notification event type. If you add a new
* notification event type, you'll need to add a new entry to the Map here.
*/
private static LazyMember<Map<String, EventType>>
xmlElementNameToEventTypeMap =
new LazyMember<Map<String, EventType>>(
new ILazyMember<Map<String, EventType>>() {
@Override
public Map<String, EventType> createInstance() {
Map<String, EventType> result =
new HashMap<String, EventType>();
result.put(XmlElementNames.CopiedEvent, EventType.Copied);
result.put(XmlElementNames.CreatedEvent, EventType.Created);
result.put(XmlElementNames.DeletedEvent, EventType.Deleted);
result.put(XmlElementNames.ModifiedEvent,
EventType.Modified);
result.put(XmlElementNames.MovedEvent, EventType.Moved);
result.put(XmlElementNames.NewMailEvent, EventType.NewMail);
result.put(XmlElementNames.StatusEvent, EventType.Status);
result.put(XmlElementNames.FreeBusyChangedEvent,
EventType.FreeBusyChanged);
return result;
}
});
/**
* Gets the XML element name to event type mapping.
*
* @return The XML element name to event type mapping.
*/
protected static Map<String, EventType> getXmlElementNameToEventTypeMap() {
return GetEventsResults.xmlElementNameToEventTypeMap.getMember();
}
/**
* Initializes a new instance.
*/
public GetEventsResults() {
}
/**
* Loads from XML.
*
* @param reader the reader
* @throws Exception the exception
*/
public void loadFromXml(EwsServiceXmlReader reader) throws Exception {
reader.readStartElement(XmlNamespace.Messages,
XmlElementNames.Notification);
this.subscriptionId = reader.readElementValue(XmlNamespace.Types,
XmlElementNames.SubscriptionId);
this.previousWatermark = reader.readElementValue(XmlNamespace.Types,
XmlElementNames.PreviousWatermark);
this.moreEventsAvailable = reader.readElementValue(Boolean.class,
XmlNamespace.Types, XmlElementNames.MoreEvents);
do {
reader.read();
if (reader.isStartElement()) {
String eventElementName = reader.getLocalName();
EventType eventType;
if (xmlElementNameToEventTypeMap.getMember().containsKey(
eventElementName)) {
eventType = xmlElementNameToEventTypeMap.getMember().get(
eventElementName);
this.newWatermark = reader.readElementValue(
XmlNamespace.Types, XmlElementNames.Watermark);
if (eventType == EventType.Status) {
// We don't need to return status events
reader.readEndElementIfNecessary(XmlNamespace.Types,
eventElementName);
} else {
this.loadNotificationEventFromXml(reader,
eventElementName, eventType);
}
} else {
reader.skipCurrentElement();
}
}
} while (!reader.isEndElement(XmlNamespace.Messages,
XmlElementNames.Notification));
}
/**
* Loads a notification event from XML.
*
* @param reader the reader
* @param eventElementName the event element name
* @param eventType the event type
* @throws Exception the exception
*/
private void loadNotificationEventFromXml(EwsServiceXmlReader reader,
String eventElementName, EventType eventType) throws Exception {
Date date = reader.readElementValue(Date.class, XmlNamespace.Types,
XmlElementNames.TimeStamp);
NotificationEvent notificationEvent;
reader.read();
if (reader.getLocalName().equals(XmlElementNames.FolderId)) {
notificationEvent = new FolderEvent(eventType, date);
} else {
notificationEvent = new ItemEvent(eventType, date);
}
notificationEvent.loadFromXml(reader, eventElementName);
this.events.add(notificationEvent);
}
/**
* Gets the Id of the subscription the collection is associated with.
*
* @return the subscription id
*/
protected String getSubscriptionId() {
return subscriptionId;
}
/**
* Gets the subscription's previous watermark.
*
* @return the previous watermark
*/
protected String getPreviousWatermark() {
return previousWatermark;
}
/**
* Gets the subscription's new watermark.
*
* @return the new watermark
*/
public String getNewWatermark() {
return newWatermark;
}
/**
* Gets a value indicating whether more events are available on the Exchange
* server.
*
* @return true, if is more events available
*/
protected boolean isMoreEventsAvailable() {
return moreEventsAvailable;
}
/**
* Gets the collection of folder events.
*
* @return the folder events
*/
public Iterable<FolderEvent> getFolderEvents() {
Collection<FolderEvent> folderEvents = new ArrayList<FolderEvent>();
for (Object event : this.events) {
if (event instanceof FolderEvent) {
folderEvents.add((FolderEvent) event);
}
}
return folderEvents;
}
/**
* Gets the collection of item events.
*
* @return the item events
*/
public Iterable<ItemEvent> getItemEvents() {
Collection<ItemEvent> itemEvents = new ArrayList<ItemEvent>();
for (Object event : this.events) {
if (event instanceof ItemEvent) {
itemEvents.add((ItemEvent) event);
}
}
return itemEvents;
}
/**
* Gets the collection of all events.
*
* @return the all events
*/
public Collection<NotificationEvent> getAllEvents() {
return this.events;
}
}
|
package no.uio.ifi.trackfind.frontend.listeners;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.ui.TextArea;
import no.uio.ifi.trackfind.frontend.data.TreeNode;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Moves attribute or value(s) from Tree to TextArea.
*
* @author Dmytro Titov
*/
@SuppressWarnings("PMD.NonStaticInitializer")
public abstract class MoveAttributeValueHandler {
private static final Map<Boolean, String> CONDITIONS = new HashMap<Boolean, String>() {{
put(true, "AND ");
put(false, "OR ");
}};
private static final String EQUALITY_OPERATOR = " ? ";
private String datasetPrefix;
private String levelsSeparator;
public MoveAttributeValueHandler(String levelsSeparator) {
this.levelsSeparator = levelsSeparator;
}
/**
* Fetches mouse click details and processes single or multiple drop.
*
* @param textArea Target: TextArea to move to.
* @param mouseEventDetails Vaadin MouseEventDetails (with states of keyboard keys as well).
* @param selectedItems Set of items selected (being dropped).
*/
protected void processDragAndDrop(TextArea textArea, MouseEventDetails mouseEventDetails, Set<TreeNode> selectedItems) {
boolean logicalOperation = mouseEventDetails == null || !mouseEventDetails.isAltKey();
boolean inversion = mouseEventDetails != null && mouseEventDetails.isShiftKey();
int size = CollectionUtils.size(selectedItems);
if (size == 1) {
processDragAndDropSingle(textArea, logicalOperation, inversion, selectedItems.iterator().next());
} else if (size > 1) {
processDragAndDropMultiple(textArea, logicalOperation, inversion, selectedItems);
}
}
/**
* Processes drop of multiple items.
*
* @param textArea Target: TextArea to move to.
* @param logicalOperation true for AND, false for OR.
* @param inversion true for NOT
* @param items Items to drop (always values).
*/
private void processDragAndDropMultiple(TextArea textArea, boolean logicalOperation, boolean inversion, Set<TreeNode> items) {
String condition = CONDITIONS.get(logicalOperation);
StringBuilder query = new StringBuilder(textArea.getValue());
if (StringUtils.isNoneEmpty(query.toString())) {
query.append(condition);
}
if (inversion) {
query.append("NOT ");
}
query.append(datasetPrefix).append(levelsSeparator);
TreeNode firstItem = items.iterator().next();
String path = firstItem.getPath();
String queryTerm = path.substring(0, path.lastIndexOf(levelsSeparator));
query.append(queryTerm).append(" ?| array[");
for (TreeNode item : items) {
String value = getValue(item);
query.append(value).append(", ");
}
query = new StringBuilder(query.subSequence(0, query.length() - 2) + "]\n");
textArea.setValue(query.toString());
}
/**
* Processes drop of single item.
*
* @param textArea Target: TextArea to move to.
* @param logicalOperation true for AND, false for OR.
* @param inversion true for NOT
* @param item Item to drop (either attribute or value).
*/
private void processDragAndDropSingle(TextArea textArea, boolean logicalOperation, boolean inversion, TreeNode item) {
String condition = CONDITIONS.get(logicalOperation);
String query = textArea.getValue();
if (StringUtils.isNoneEmpty(query)) {
query += condition;
}
if (inversion) {
query += "NOT ";
}
query += datasetPrefix + levelsSeparator;
String path = item.getPath();
if (item.isValue()) {
String value = getValue(item);
query += path.substring(0, path.lastIndexOf(levelsSeparator)) + EQUALITY_OPERATOR + value;
} else {
query += path + EQUALITY_OPERATOR;
}
query += "\n";
textArea.setValue(query);
}
protected String getValue(TreeNode item) {
return "'" + item.toString() + "'";
}
public void setDatasetPrefix(String datasetPrefix) {
this.datasetPrefix = datasetPrefix;
}
}
|
package uk.ac.cam.cl.dtg.teaching.hibernate;
import java.io.IOException;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HibernateSessionRequestFilter implements Filter {
private HibernateUtil hibernateUtil;
private static Logger log = LoggerFactory.getLogger(HibernateSessionRequestFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
hibernateUtil = HibernateUtil.getInstance();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (hibernateUtil.isReady()) {
try {
hibernateUtil.getSF().getCurrentSession().beginTransaction();
} catch (HibernateException e) {
// failed to get a new transaction - one reason for this might
// be that the connection pool is empty
log.error("Unable to open a database connection");
((HttpServletResponse)response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Unable to open a database connection");
return;
}
}
chain.doFilter(request, response);
if (hibernateUtil.isReady()) {
Transaction t = hibernateUtil.getSF().getCurrentSession()
.getTransaction();
try {
t.commit();
} catch (HibernateException e) {
try {
log.warn("Caught exception when trying to commit transaction. Rolling back.",e);
t.rollback();
((HttpServletResponse)response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"");
throw new HibernateException(
"Caught exception trying to commit transaction", e);
} catch (HibernateException e2) {
log.error("Failed to rollback transaction after failing to commit",e2);
HibernateException e3 = new HibernateException(
"Got exception trying to rollback transaction after failure",
e2);
e3.addSuppressed(e);
throw e3;
}
}
}
}
@Override
public void destroy() {
hibernateUtil.getSession().close();
hibernateUtil.close();
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
try {
log.info("Deregistering {}",driver.toString());
DriverManager.deregisterDriver(driver);
} catch (SQLException e) {
}
}
}
}
|
package xdi2.messaging.target.contributor.impl.filesys;
import java.io.File;
import java.net.URLEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xdi2.core.features.nodetypes.XdiAbstractEntity;
import xdi2.core.features.nodetypes.XdiAbstractMemberUnordered;
import xdi2.core.features.nodetypes.XdiEntity;
import xdi2.core.features.nodetypes.XdiEntityCollection;
import xdi2.core.features.nodetypes.XdiEntityMember;
import xdi2.core.util.GraphUtil;
import xdi2.core.xri3.XDI3Segment;
import xdi2.messaging.GetOperation;
import xdi2.messaging.MessageResult;
import xdi2.messaging.context.ExecutionContext;
import xdi2.messaging.exceptions.Xdi2MessagingException;
import xdi2.messaging.target.MessagingTarget;
import xdi2.messaging.target.Prototype;
import xdi2.messaging.target.contributor.AbstractContributor;
import xdi2.messaging.target.contributor.ContributorMount;
import xdi2.messaging.target.contributor.ContributorResult;
import xdi2.messaging.target.impl.graph.GraphMessagingTarget;
@ContributorMount(contributorXris={"(#test)"})
public class FileSysContributor extends AbstractContributor implements Prototype<FileSysContributor> {
private static final Logger log = LoggerFactory.getLogger(FileSysContributor.class);
private static final String DEFAULT_BASE_PATH = ".";
private static final String DEFAULT_GRAPH_PATH = null;
private static final XDI3Segment XRI_S_EC_DIR = XDI3Segment.create("[#dir]");
private static final XDI3Segment XRI_S_EC_FILE = XDI3Segment.create("[#file]");
private static final XDI3Segment XRI_S_AS_NAME = XDI3Segment.create("<#name>");
private static final XDI3Segment XRI_S_AS_SIZE = XDI3Segment.create("<#size>");
private String basePath;
private String graphPath;
public FileSysContributor() {
super();
this.basePath = DEFAULT_BASE_PATH;
this.graphPath = DEFAULT_GRAPH_PATH;
this.getContributors().addContributor(new FileSysDirContributor());
}
/*
* Prototype
*/
@Override
public FileSysContributor instanceFor(PrototypingContext prototypingContext) throws Xdi2MessagingException {
// create new contributor
FileSysContributor contributor = new FileSysContributor();
// set the something
// contributor.setTokenGraph(this.getTokenGraph());
// done
return contributor;
}
/*
* Init and shutdown
*/
@Override
public void init(MessagingTarget messagingTarget) throws Exception {
super.init(messagingTarget);
// determine base path
if (this.getBasePath() == null) throw new Xdi2MessagingException("No base path.", null, null);
if (! this.getBasePath().endsWith("/")) this.setBasePath(this.getBasePath() + "/");
// determine graph path
if (this.getGraphPath() == null && messagingTarget instanceof GraphMessagingTarget) {
String relativeGraphPath = URLEncoder.encode(GraphUtil.getOwnerXri(((GraphMessagingTarget) messagingTarget).getGraph()).toString(), "UTF-8");
this.setGraphPath(this.getBasePath() + relativeGraphPath);
}
if (this.getGraphPath() == null) throw new Xdi2MessagingException("No graph path.", null, null);
}
/*
* Sub-Contributors
*/
@ContributorMount(contributorXris={"#dir"})
private class FileSysDirContributor extends AbstractContributor {
private FileSysDirContributor() {
super();
this.getContributors().addContributor(new FileSysOtherContributor());
}
@Override
public ContributorResult executeGetOnAddress(XDI3Segment[] contributorXris, XDI3Segment contributorsXri, XDI3Segment relativeTargetAddress, GetOperation operation, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException {
XDI3Segment fileSysContextXri = contributorXris[contributorXris.length - 2];
XDI3Segment fileSysDirContextXri = contributorXris[contributorXris.length - 1];
log.debug("fileSysContextXri: " + fileSysContextXri + ", fileSysDirContextXri: " + fileSysDirContextXri);
// map the directory
File graphRootDir = new File(FileSysContributor.this.getGraphPath());
XdiEntity xdiEntity = XdiAbstractEntity.fromContextNode(messageResult.getGraph().setDeepContextNode(contributorsXri));
mapDir(graphRootDir, xdiEntity);
// done
return ContributorResult.SKIP_MESSAGING_TARGET;
}
}
@ContributorMount(contributorXris={"{}"})
private class FileSysOtherContributor extends AbstractContributor {
private FileSysOtherContributor() {
super();
}
@Override
public ContributorResult executeGetOnAddress(XDI3Segment[] contributorXris, XDI3Segment contributorsXri, XDI3Segment relativeTargetAddress, GetOperation operation, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException {
XDI3Segment fileSysContextXri = contributorXris[contributorXris.length - 2];
XDI3Segment fileSysDirContextXri = contributorXris[contributorXris.length - 1];
log.debug("fileSysContextXri: " + fileSysContextXri + ", fileSysDirContextXri: " + fileSysDirContextXri);
// parse identifiers
// done
return new ContributorResult(true, false, true);
}
}
/*
* Helper methods
*/
private static void mapDir(File dir, XdiEntity xdiEntity) {
XdiEntityCollection dirXdiEntityCollection = xdiEntity.getXdiEntityCollection(XRI_S_EC_DIR, true);
XdiEntityCollection fileXdiEntityCollection = xdiEntity.getXdiEntityCollection(XRI_S_EC_FILE, true);
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
if (log.isDebugEnabled()) log.debug("In " + dir.getAbsolutePath() + ": Directory: " + file.getAbsolutePath());
XdiEntityMember dirXdiEntityMember = dirXdiEntityCollection.setXdiMemberUnordered(XdiAbstractMemberUnordered.createRandomUuidArcXri(false));
dirXdiEntityMember.getXdiAttribute(XRI_S_AS_NAME, true).getXdiValue(true).setLiteralString(file.getName());
dirXdiEntityMember.getXdiAttribute(XRI_S_AS_SIZE, true).getXdiValue(true).setLiteralNumber(Double.valueOf(file.getTotalSpace()));
mapDir(file, dirXdiEntityMember);
}
if (file.isFile()) {
if (log.isDebugEnabled()) log.debug("In " + dir.getAbsolutePath() + ": File: " + file.getAbsolutePath());
XdiEntityMember fileXdiEntityMember = fileXdiEntityCollection.setXdiMemberUnordered(XdiAbstractMemberUnordered.createRandomUuidArcXri(false));
fileXdiEntityMember.getXdiAttribute(XRI_S_AS_NAME, true).getXdiValue(true).setLiteralString(file.getName());
fileXdiEntityMember.getXdiAttribute(XRI_S_AS_SIZE, true).getXdiValue(true).setLiteralNumber(Double.valueOf(file.getTotalSpace()));
}
}
}
/*
* Getters and setters
*/
public String getBasePath() {
return this.basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getGraphPath() {
return this.graphPath;
}
public void setGraphPath(String graphPath) {
this.graphPath = graphPath;
}
}
|
package oshi.data.windows;
import java.util.EnumMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jna.platform.win32.Variant; //NOSONAR
import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiQuery;
import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiResult;
import oshi.util.platform.windows.PerfDataUtil;
import oshi.util.platform.windows.PerfDataUtil.PerfCounter;
import oshi.util.platform.windows.WmiQueryHandler;
import oshi.util.platform.windows.WmiUtil;
public class PerfCounterQuery<T extends Enum<T>> {
private static final Logger LOG = LoggerFactory.getLogger(PerfCounter.class);
/*
* Set on instantiation
*/
protected final Class<T> propertyEnum;
protected final String perfObject;
protected final String perfWmiClass;
protected final String queryKey;
protected CounterDataSource source;
protected PerfCounterQueryHandler pdhQueryHandler;
protected WmiQueryHandler wmiQueryHandler;
/*
* Only one will be non-null depending on source
*/
private EnumMap<T, PerfCounter> counterMap = null;
protected WmiQuery<T> counterQuery = null;
/*
* Multiple classes use these constants
*/
public static final String TOTAL_INSTANCE = "_Total";
public static final String TOTAL_INSTANCES = "*_Total";
public static final String NOT_TOTAL_INSTANCE = "^" + TOTAL_INSTANCE;
public static final String NOT_TOTAL_INSTANCES = "^" + TOTAL_INSTANCES;
/**
* Construct a new object to hold performance counter data source and
* results
*
* @param propertyEnum
* An enum which implements {@link PdhCounterProperty} and
* contains the WMI field (Enum value) and PDH Counter string
* (instance and counter)
* @param perfObject
* The PDH object for this counter; all counters on this object
* will be refreshed at the same time
* @param perfWmiClass
* The WMI PerfData_RawData_* class corresponding to the PDH
* object
*/
public PerfCounterQuery(Class<T> propertyEnum, String perfObject, String perfWmiClass) {
this(propertyEnum, perfObject, perfWmiClass, perfObject);
}
/**
* Construct a new object to hold performance counter data source and
* results
*
* @param propertyEnum
* An enum which implements {@link PdhCounterProperty} and
* contains the WMI field (Enum value) and PDH Counter string
* (instance and counter)
* @param perfObject
* The PDH object for this counter; all counters on this object
* will be refreshed at the same time
* @param perfWmiClass
* The WMI PerfData_RawData_* class corresponding to the PDH
* object
* @param queryKey
* An optional key for PDH counter updates; defaults to the PDH
* object name
*/
public PerfCounterQuery(Class<T> propertyEnum, String perfObject, String perfWmiClass, String queryKey) {
if (PdhCounterProperty.class.isAssignableFrom(propertyEnum.getDeclaringClass())) {
throw new IllegalArgumentException(
propertyEnum.getClass().getName() + " must implement PdhCounterProperty.");
}
this.propertyEnum = propertyEnum;
this.perfObject = perfObject;
this.perfWmiClass = perfWmiClass;
this.queryKey = queryKey;
this.pdhQueryHandler = PerfCounterQueryHandler.getInstance();
this.wmiQueryHandler = WmiQueryHandler.createInstance();
// Start off with PDH as source; if query here fails we will permanently
// fall back to WMI
this.source = CounterDataSource.PDH;
}
/**
* Set the Data Source for these counters
*
* @param source
* The source of data
* @return Whether the data source was successfully set
*/
public boolean setDataSource(CounterDataSource source) {
this.source = source;
switch (source) {
case PDH:
LOG.debug("Attempting to set PDH Data Source.");
unInitWmiCounters();
return initPdhCounters();
case WMI:
LOG.debug("Attempting to set WMI Data Source.");
unInitPdhCounters();
initWmiCounters();
return true;
default:
// This should never happen unless you've added a new source and
// forgot to add a case for it
throw new IllegalArgumentException("Invalid Data Source specified.");
}
}
/**
* Initialize PDH counters for this data source. Adds necessary counters to
* a PDH Query.
*
* @return True if the counters were successfully added.
*/
protected boolean initPdhCounters() {
this.counterMap = new EnumMap<>(propertyEnum);
for (T prop : propertyEnum.getEnumConstants()) {
PerfCounter counter = PerfDataUtil.createCounter(perfObject, ((PdhCounterProperty) prop).getInstance(),
((PdhCounterProperty) prop).getCounter());
counterMap.put(prop, counter);
if (!pdhQueryHandler.addCounterToQuery(counter, this.queryKey)) {
unInitPdhCounters();
return false;
}
}
return true;
}
/**
* Uninitialize PDH counters for this data source. Removes necessary
* counters from the PDH Query, releasing their handles.
*/
protected void unInitPdhCounters() {
pdhQueryHandler.removeAllCountersFromQuery(this.queryKey);
this.counterMap = null;
}
/**
* Initialize the WMI query object needed to retrieve counters for this data
* source.
*/
protected void initWmiCounters() {
this.counterQuery = new WmiQuery<>(perfWmiClass, propertyEnum);
}
/**
* Uninitializes the WMI query object needed to retrieve counters for this
* data source, allowing it to be garbage collected.
*/
protected void unInitWmiCounters() {
this.counterQuery = null;
}
/**
* Query the current data source (PDH or WMI) for the Performance Counter
* values corresponding to the property enum.
*
* @return A map of the values by the counter enum.
*/
public Map<T, Long> queryValues() {
EnumMap<T, Long> valueMap = new EnumMap<>(propertyEnum);
T[] props = this.propertyEnum.getEnumConstants();
if (source.equals(CounterDataSource.PDH)) {
// Set up the query and counter handles, and query
if (initPdhCounters() && queryPdh(valueMap, props)) {
// If both init and query return true, then valueMap contains
// the results. Release the handles.
unInitPdhCounters();
} else {
// If either init or query failed, switch to WMI
setDataSource(CounterDataSource.WMI);
}
}
if (source.equals(CounterDataSource.WMI)) {
queryWmi(valueMap, props);
}
return valueMap;
}
private boolean queryPdh(Map<T, Long> valueMap, T[] props) {
if (counterMap != null && 0 < pdhQueryHandler.updateQuery(this.queryKey)) {
for (T prop : props) {
valueMap.put(prop, pdhQueryHandler.queryCounter(counterMap.get(prop)));
}
return true;
}
// Zero timestamp means update failed after muliple
// attempts; fallback to WMI
return false;
}
private void queryWmi(Map<T, Long> valueMap, T[] props) {
WmiResult<T> result = wmiQueryHandler.queryWMI(this.counterQuery);
if (result.getResultCount() > 0) {
for (T prop : props) {
switch (result.getVtType(prop)) {
case Variant.VT_I2:
valueMap.put(prop, Long.valueOf(WmiUtil.getUint16(result, prop, 0)));
break;
case Variant.VT_I4:
valueMap.put(prop, WmiUtil.getUint32asLong(result, prop, 0));
break;
case Variant.VT_BSTR:
valueMap.put(prop, WmiUtil.getUint64(result, prop, 0));
break;
default:
throw new ClassCastException("Unimplemented VT Type Mapping.");
}
}
}
}
/**
* Source of performance counter data.
*/
public enum CounterDataSource {
/**
* Performance Counter data will be pulled from a PDH Counter
*/
PDH,
/**
* Performance Counter data will be pulled from a WMI PerfData_RawData_*
* table
*/
WMI;
}
/**
* Contract for Counter Property Enums
*/
public interface PdhCounterProperty {
/**
* @return Returns the instance.
*/
String getInstance();
/**
* @return Returns the counter.
*/
String getCounter();
}
}
|
package org.apache.pig.backend.hadoop.executionengine.spark.converter;
import java.io.IOException;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POSort;
import org.apache.pig.backend.hadoop.executionengine.spark.SparkUtil;
import org.apache.pig.data.Tuple;
import scala.Tuple2;
import scala.math.Ordered;
import scala.runtime.AbstractFunction1;
import spark.api.java.JavaRDD;
import spark.api.java.JavaPairRDD;
import spark.api.java.function.FlatMapFunction;
import spark.RDD;
@SuppressWarnings("serial")
public class SortConverter implements POConverter<Tuple, Tuple, POSort> {
private static final Log LOG = LogFactory.getLog(SortConverter.class);
private static final FlatMapFunction<Iterator<Tuple2<Tuple, Object>>, Tuple> TO_VALUE_FUNCTION = new ToValueFunction();
@Override
public RDD<Tuple> convert(List<RDD<Tuple>> predecessors, POSort sortOperator)
throws IOException {
SparkUtil.assertPredecessorSize(predecessors, sortOperator, 1);
RDD<Tuple> rdd = predecessors.get(0);
RDD<Tuple2<Tuple, Object>> rddPair =
rdd.map(new ToKeyValueFunction(),
SparkUtil.<Tuple, Object>getTuple2Manifest());
JavaPairRDD<Tuple, Object> r = new JavaPairRDD<Tuple, Object>(rddPair, SparkUtil.getManifest(Tuple.class),
SparkUtil.getManifest(Object.class));
JavaPairRDD<Tuple, Object> sorted = r.sortByKey(sortOperator.getmComparator(), true);
JavaRDD<Tuple> mapped = sorted.mapPartitions(TO_VALUE_FUNCTION);
return mapped.rdd();
}
private static class ToValueFunction extends FlatMapFunction<Iterator<Tuple2<Tuple, Object>>, Tuple> implements Serializable {
private class Tuple2TransformIterable implements Iterable<Tuple> {
Iterator<Tuple2<Tuple, Object>> in;
Tuple2TransformIterable(Iterator<Tuple2<Tuple, Object>> input) {
in = input;
}
public Iterator<Tuple> iterator() {
return new IteratorTransform<Tuple2<Tuple, Object>, Tuple>(in) {
@Override
protected Tuple transform(Tuple2<Tuple, Object> next) {
return next._1();
}
};
}
}
@Override
public Iterable<Tuple> call(Iterator<Tuple2<Tuple, Object>> input) {
return new Tuple2TransformIterable(input);
}
}
private static class OrderedTuple implements Ordered<Tuple>, Serializable {
private final Tuple tuple;
private final Comparator<Tuple> comparator;
public OrderedTuple(Tuple tuple, Comparator<Tuple> comparator) {
this.tuple = tuple;
this.comparator = comparator;
}
@Override
public boolean $greater(Tuple o) {
return compareTo(o) > 0;
}
@Override
public boolean $greater$eq(Tuple o) {
return compareTo(o) >= 0;
}
@Override
public boolean $less(Tuple o) {
return compareTo(o) < 0;
}
@Override
public boolean $less$eq(Tuple o) {
return compareTo(o) <= 0;
}
@Override
public int compare(Tuple o) {
return compareTo(o);
}
@Override
public int compareTo(Tuple o) {
return comparator.compare(tuple, o);
}
}
private static class ToKeyValueFunction extends AbstractFunction1<Tuple,Tuple2<Tuple, Object>> implements Serializable {
@Override
public Tuple2<Tuple, Object> apply(Tuple t) {
if (LOG.isDebugEnabled()) {
LOG.debug("Sort ToKeyValueFunction in "+t);
}
Tuple key = t;
Object value = null;
// (key, value)
Tuple2<Tuple, Object> out = new Tuple2<Tuple, Object>(key, value);
if (LOG.isDebugEnabled()) {
LOG.debug("Sort ToKeyValueFunction out "+out);
}
return out;
}
}
}
|
package org.mtransit.parser.ca_saskatoon_transit_bus;
import java.util.HashSet;
import java.util.Locale;
import java.util.regex.Pattern;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.mt.data.MTrip;
public class SaskatoonTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-saskatoon-transit-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new SaskatoonTransitBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating Saskatoon Transit bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("\nGenerating Saskatoon Transit bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public long getRouteId(GRoute gRoute) {
return Long.parseLong(gRoute.getRouteShortName().trim()); // using route short name as route ID
}
@Override
public String getRouteShortName(GRoute gRoute) {
return String.valueOf(Integer.parseInt(gRoute.getRouteShortName().trim())); // remove leading '0'
}
private static final String AGENCY_COLOR_BLUE = "027AA7"; // BLUE (from web site CSS)
private static final String AGENCY_COLOR = AGENCY_COLOR_BLUE;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_DART_GREEN = "8CC63F"; // GREEN (from system map PDF)
@Override
public String getRouteColor(GRoute gRoute) {
int rsn = Integer.parseInt(gRoute.getRouteShortName().trim());
switch (rsn) {
// @formatter:off
case 1: return null;
case 2: return null;
case 3: return null;
case 4: return null;
case 5: return null;
case 6: return null;
case 7: return null;
case 8: return null;
case 9: return null;
case 10: return null;
case 11: return null;
case 12: return null;
case 13: return null;
case 14: return null;
case 17: return null;
case 20: return null;
case 21: return null;
case 22: return null;
case 23: return null;
case 25: return null;
case 26: return null;
case 28: return null;
case 29: return null;
case 50: return COLOR_DART_GREEN;
case 60: return COLOR_DART_GREEN;
case 70: return COLOR_DART_GREEN;
case 75: return COLOR_DART_GREEN;
case 80: return COLOR_DART_GREEN;
case 85: return null;
case 100: return null;
case 104: return null;
case 180: return null;
case 200: return null;
// @formatter:on
default:
System.out.println("Unexpected route color " + gRoute);
System.exit(-1);
return null;
}
}
private static final String WILDWOOD = "Wildwood";
private static final String EXHIBITION = "Exhibition";
private static final String HUDSON_BAY_PARK = "Hudson Bay Park";
private static final String COLLEGE_PARK = "College Park";
private static final String MAYFAIR = "Mayfair";
private static final String WILLOWGROVE_SQ = "Willowgrove Sq";
private static final String MC_CORMACK = "McCormack";
private static final String BRIARWOOD = "Briarwood";
private static final String _8TH_ST = "8th St";
private static final String RIVER_HEIGHTS = "River Heights";
private static final String AIRPORT = "Airport";
private static final String LAWSON_HEIGHTS = "Lawson Heights";
private static final String BROADWAY = "Broadway";
private static final String STONEBRIDGE = "Stonebridge";
private static final String MARKET_MALL = "Market Mall";
private static final String MONTGOMERY = "Montgomery";
private static final String BLAIRMORE = "Blairmore";
private static final String NORTH_INDUSTRIAL = "North Industrial";
private static final String UNIVERSITY_FOREST_GROVE = "University / Forest Grove";
private static final String LAKEVIEW = "Lakeview";
private static final String PACIFIC_HEIGHTS = "Pacific Heights";
private static final String LAKERIDGE = "Lakeridge";
private static final String CONFEDERATION = "Confederation";
private static final String CITY_CTR = "City Ctr";
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (mRoute.id == 1l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(WILDWOOD, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(EXHIBITION, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 3l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(HUDSON_BAY_PARK, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(COLLEGE_PARK, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 4l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(MAYFAIR, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(WILLOWGROVE_SQ, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 5l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(MC_CORMACK, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(BRIARWOOD, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 6l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(BROADWAY, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(MARKET_MALL, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 8l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(_8TH_ST, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 12l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(RIVER_HEIGHTS, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(AIRPORT, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 13l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(LAWSON_HEIGHTS, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(BROADWAY, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 14l) {
if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 17l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(STONEBRIDGE, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(MARKET_MALL, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 22l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(MONTGOMERY, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 23l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString("Hampton Village", gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(BLAIRMORE, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 25l) {
if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(NORTH_INDUSTRIAL, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 28l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(UNIVERSITY_FOREST_GROVE, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 50l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(LAKEVIEW, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(PACIFIC_HEIGHTS, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 60l) {
if (gTrip.getDirectionId() == 0) {
mTrip.setHeadsignString(LAKERIDGE, gTrip.getDirectionId());
return;
} else if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(CONFEDERATION, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 75l) {
if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 80l) {
if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.getDirectionId());
return;
}
} else if (mRoute.id == 85l) {
if (gTrip.getDirectionId() == 1) {
mTrip.setHeadsignString(CITY_CTR, gTrip.getDirectionId());
return;
}
}
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId());
}
private static final Pattern CENTER = Pattern.compile("(cent(er|re))", Pattern.CASE_INSENSITIVE);
private static final String CENTER_REPLACEMENT = "Ctr";
private static final String VIA = " via ";
@Override
public String cleanTripHeadsign(String tripHeadsign) {
int indexOfVIA = tripHeadsign.toLowerCase(Locale.ENGLISH).indexOf(VIA);
if (indexOfVIA >= 0) {
tripHeadsign = tripHeadsign.substring(0, indexOfVIA);
}
tripHeadsign = CENTER.matcher(tripHeadsign).replaceAll(CENTER_REPLACEMENT);
return CleanUtils.cleanLabel(tripHeadsign);
}
@Override
public String cleanStopName(String gStopName) {
gStopName = CleanUtils.cleanStreetTypes(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public int getStopId(GStop gStop) {
try {
return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID
} catch (Exception e) {
System.out.println("Error while extracting stop ID from " + gStop);
e.printStackTrace();
System.exit(-1);
return -1;
}
}
}
|
package net.hyperic.sigar.test;
import java.io.PrintStream;
import junit.framework.TestCase;
import net.hyperic.sigar.Sigar;
//helper to add optional tracing.
public abstract class SigarTestCase extends TestCase {
private Sigar sigar = null;
private static boolean verbose = false;
private static PrintStream out = System.out;
public SigarTestCase(String name) {
super(name);
}
public Sigar getSigar() {
if (this.sigar == null) {
this.sigar = new Sigar();
if (getVerbose()) {
this.sigar.enableLogging(true);
}
}
return this.sigar;
}
public static void setVerbose(boolean value) {
verbose = value;
}
public static boolean getVerbose() {
return verbose;
}
public static void setWriter(PrintStream value) {
out = value;
}
public static PrintStream getWriter() {
return out;
}
public void traceln(String msg) {
if (getVerbose()) {
getWriter().println(msg);
}
}
public void trace(String msg) {
if (getVerbose()) {
getWriter().print(msg);
}
}
public void assertTrueTrace(String msg, String value) {
traceln(msg + "=" + value);
assertTrue(msg, value != null);
}
public void assertLengthTrace(String msg, String value) {
assertTrueTrace(msg, value);
assertTrue(msg, value.length() > 0);
}
public void assertGtZeroTrace(String msg, long value) {
traceln(msg + "=" + value);
assertTrue(msg, value > 0);
}
public void assertGtEqZeroTrace(String msg, long value) {
traceln(msg + "=" + value);
assertTrue(msg, value >= 0);
}
public void assertEqualsTrace(String msg, long expected, long actual) {
traceln(msg + "=" + actual + "/" + expected);
assertEquals(msg, expected, actual);
}
}
|
package org.pentaho.reporting.platform.plugin.connection;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.security.Principal;
import java.util.*;
import java.util.Map.Entry;
import org.pentaho.platform.api.engine.IParameterProvider;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.api.engine.IPluginManager;
import org.pentaho.platform.engine.core.solution.SimpleParameterProvider;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.reporting.engine.classic.core.DataRow;
import org.pentaho.reporting.engine.classic.core.ReportDataFactoryException;
import org.pentaho.reporting.engine.classic.core.util.TypedTableModel;
import org.pentaho.reporting.engine.classic.extensions.datasources.cda.CdaQueryBackend;
import org.pentaho.reporting.engine.classic.extensions.datasources.cda.CdaResponseParser;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Class that implements CDA to be used LOCAL inside pentaho platform
*
* @author dduque
*/
public class CdaPluginLocalQueryBackend extends CdaQueryBackend {
public CdaPluginLocalQueryBackend() {
}
public TypedTableModel fetchData( final DataRow dataRow, final String method,
final Map<String, String> extraParameter ) throws ReportDataFactoryException {
try {
final Map<String, Object> parameters = new HashMap<String, Object>();
final Set<Entry<String, String>> parameterSet = extraParameter.entrySet();
for ( final Entry<String, String> entry : parameterSet ) {
parameters.put( entry.getKey(), entry.getValue() );
}
parameters.put( "outputType", "xml" );
parameters.put( "solution", getSolution() );
parameters.put( "path", getPath() );
parameters.put( "file", getFile() );
final String responseBody = callPlugin( "cda", method, parameters );
// convert String into InputStream
final InputStream responseBodyIs = new ByteArrayInputStream( responseBody.getBytes( "UTF-8" ) );
return CdaResponseParser.performParse( responseBodyIs );
} catch ( UnsupportedEncodingException use ) {
throw new ReportDataFactoryException( "Failed to encode parameter", use );
} catch ( Exception e ) {
throw new ReportDataFactoryException( "Failed to send request", e );
}
}
private static String callPlugin( final String pluginName, final String method, final Map<String, Object> parameters )
throws ReportDataFactoryException {
final IPentahoSession userSession = PentahoSessionHolder.getSession();
final IPluginManager pluginManager = PentahoSystem.get( IPluginManager.class, userSession );
try {
Object cdaBean = pluginManager.getBean("cda.api");
Class cdaBeanClass = cdaBean.getClass();
Class[] paramTypes;
Object[] paramValues;
Method m;
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if ( "listParameters".equals( method ) ) {
IParameterProvider params = new SimpleParameterProvider( parameters );
paramTypes = new Class[] { String.class, String.class, String.class, String.class, String.class,
HttpServletResponse.class, HttpServletRequest.class };
m = cdaBeanClass.getMethod("listParameters", paramTypes);
paramValues = new Object[7];
paramValues[0] = params.getStringParameter( "path", null );
paramValues[1] = params.getStringParameter( "solution", "" );
paramValues[2] = params.getStringParameter( "file", "" );
paramValues[3] = params.getStringParameter( "outputType", "json" );
paramValues[4] = params.getStringParameter( "dataAccessId", "<blank>" );
paramValues[5] = getResponse( outputStream );
paramValues[6] = getRequest( parameters );
m.invoke(cdaBean, paramValues);
return outputStream.toString();
} else {
paramTypes = new Class[] { HttpServletRequest.class };
m = cdaBeanClass.getMethod("doQueryInterPlugin", paramTypes);
paramValues = new Object[1];
paramValues[0] = getRequest( parameters );
return (String) m.invoke(cdaBean, paramValues);
}
} catch ( Exception e ) {
throw new ReportDataFactoryException( "Failed to acquire " + pluginName + " plugin: ", e );
}
}
private static HttpServletRequest getRequest( final Map<String, Object> parameters ) {
final IParameterProvider requestParameters = new SimpleParameterProvider( parameters );
return new HttpServletRequest() {
@Override
public String getAuthType() {
return null;
}
@Override
public Cookie[] getCookies() {
return new Cookie[0];
}
@Override
public long getDateHeader(String s) {
return 0;
}
@Override
public String getHeader(String s) {
return null;
}
@Override
public Enumeration getHeaders(String s) {
return null;
}
@Override
public Enumeration getHeaderNames() {
return null;
}
@Override
public int getIntHeader(String s) {
return 0;
}
@Override
public String getMethod() {
return null;
}
@Override
public String getPathInfo() {
return null;
}
@Override
public String getPathTranslated() {
return null;
}
@Override
public String getContextPath() {
return null;
}
@Override
public String getQueryString() {
return null;
}
@Override
public String getRemoteUser() {
return null;
}
@Override
public boolean isUserInRole(String s) {
return false;
}
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public String getRequestedSessionId() {
return null;
}
@Override
public String getRequestURI() {
return null;
}
@Override
public StringBuffer getRequestURL() {
return null;
}
@Override
public String getServletPath() {
return null;
}
@Override
public HttpSession getSession(boolean b) {
return null;
}
@Override
public HttpSession getSession() {
return null;
}
@Override
public boolean isRequestedSessionIdValid() {
return false;
}
@Override
public boolean isRequestedSessionIdFromCookie() {
return false;
}
@Override
public boolean isRequestedSessionIdFromURL() {
return false;
}
@Override
public boolean isRequestedSessionIdFromUrl() {
return false;
}
@Override
public Object getAttribute(String s) {
return null;
}
@Override
public Enumeration getAttributeNames() {
return null;
}
@Override
public String getCharacterEncoding() {
return null;
}
@Override
public void setCharacterEncoding(String s) throws UnsupportedEncodingException {
}
@Override
public int getContentLength() {
return 0;
}
@Override
public String getContentType() {
return null;
}
@Override
public ServletInputStream getInputStream() throws IOException {
return null;
}
@Override
public String getParameter( String s ) {
return requestParameters.getStringParameter( s, null );
}
@Override
public Enumeration getParameterNames() {
return Collections.enumeration( parameters.keySet() );
}
@Override
public String[] getParameterValues( String s ) {
return requestParameters.getStringArrayParameter( s, new String[0] );
}
@Override
public Map getParameterMap() {
return parameters;
}
@Override
public String getProtocol() {
return null;
}
@Override
public String getScheme() {
return null;
}
@Override
public String getServerName() {
return null;
}
@Override
public int getServerPort() {
return 0;
}
@Override
public BufferedReader getReader() throws IOException {
return null;
}
@Override
public String getRemoteAddr() {
return null;
}
@Override
public String getRemoteHost() {
return null;
}
@Override
public void setAttribute(String s, Object o) {
}
@Override
public void removeAttribute(String s) {
}
@Override
public Locale getLocale() {
return null;
}
@Override
public Enumeration getLocales() {
return null;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public RequestDispatcher getRequestDispatcher(String s) {
return null;
}
@Override
public String getRealPath(String s) {
return null;
}
@Override
public int getRemotePort() {
return 0;
}
@Override
public String getLocalName() {
return null;
}
@Override
public String getLocalAddr() {
return null;
}
@Override
public int getLocalPort() {
return 0;
}
};
}
private static HttpServletResponse getResponse (final OutputStream stream) {
return new HttpServletResponse() {
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new DelegatingServletOutputStream(stream);
}
//Needed to override but no implementation provided
@Override
public void addCookie(Cookie cookie) {
}
@Override
public boolean containsHeader(String s) {
return false;
}
@Override
public String encodeURL(String s) {
return null;
}
@Override
public String encodeRedirectURL(String s) {
return null;
}
@Override
public String encodeUrl(String s) {
return null;
}
@Override
public String encodeRedirectUrl(String s) {
return null;
}
@Override
public void sendError(int i, String s) throws IOException {
}
@Override
public void sendError(int i) throws IOException {
}
@Override
public void sendRedirect(String s) throws IOException {
}
@Override
public void setDateHeader(String s, long l) {
}
@Override
public void addDateHeader(String s, long l) {
}
@Override
public void setHeader(String s, String s2) {
}
@Override
public void addHeader(String s, String s2) {
}
@Override
public void setIntHeader(String s, int i) {
}
@Override
public void addIntHeader(String s, int i) {
}
@Override
public void setStatus(int i) {
}
@Override
public void setStatus(int i, String s) {
}
@Override
public String getCharacterEncoding() {
return null;
}
@Override
public String getContentType() {
return null;
}
@Override
public PrintWriter getWriter() throws IOException {
return null;
}
@Override
public void setCharacterEncoding(String s) {
}
@Override
public void setContentLength(int i) {
}
@Override
public void setContentType(String s) {
}
@Override
public void setBufferSize(int i) {
}
@Override
public int getBufferSize() {
return 0;
}
@Override
public void flushBuffer() throws IOException {
}
@Override
public void resetBuffer() {
}
@Override
public boolean isCommitted() {
return false;
}
@Override
public void reset() {
}
@Override
public void setLocale(Locale locale) {
}
@Override
public Locale getLocale() {
return null;
}
} ;
}
private static class DelegatingServletOutputStream extends ServletOutputStream {
private final OutputStream targetStream;
/**
* Create a new DelegatingServletOutputStream.
* @param targetStream the target OutputStream
*/
public DelegatingServletOutputStream(OutputStream targetStream) {
this.targetStream = targetStream;
}
public void write(int b) throws IOException {
this.targetStream.write(b);
}
public void flush() throws IOException {
super.flush();
this.targetStream.flush();
}
public void close() throws IOException {
super.close();
this.targetStream.close();
}
}
}
|
package org.intermine.bio.io.gff3;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Iterator;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.intermine.util.StringUtil;
/**
* A class that represents one line of a GFF3 file. Some of this code is
* derived from BioJava.
*
* @author Kim Rutherford
*/
public class GFF3Record
{
private String sequenceID;
private String source;
private String type;
private int start;
private int end;
private Double score;
private String strand;
private String phase;
private Map attributes = new LinkedHashMap();
private static Map replacements;
/**
* Create a GFF3Record from a line of a GFF3 file
* @param line the String to parse
* @throws IOException if there is an error during parsing the line
*/
public GFF3Record(String line) throws IOException {
StringTokenizer st = new StringTokenizer(line, "\t", false);
if (st.countTokens() < 8) {
throw new IOException("GFF line too short (" + st.countTokens() + " fields): " + line);
}
sequenceID = fixEntityNames(URLDecoder.decode(st.nextToken(), "UTF-8")).trim();
source = st.nextToken().trim();
if (source.equals("") || source.equals(".")) {
source = null;
}
type = st.nextToken().trim();
String startString = st.nextToken().trim();
try {
if (startString.equals(".")) {
start = -1;
} else {
start = Integer.parseInt(startString);
}
} catch (NumberFormatException nfe) {
throw new IOException("can not parse integer for start position: " + startString);
}
String endString = st.nextToken().trim();
try {
if (endString.equals(".")) {
end = -1;
} else {
end = Integer.parseInt(endString);
}
} catch (NumberFormatException nfe) {
throw new IOException("can not parse integer for end position: " + endString);
}
String scoreString = st.nextToken().trim();
if (scoreString.equals("") || scoreString.equals(".")) {
score = null;
} else {
try {
score = new Double(scoreString);
} catch (NumberFormatException nfe) {
throw new IOException("can not parse score: " + scoreString);
}
}
strand = st.nextToken().trim();
if (strand.equals("") || strand.equals(".")) {
strand = null;
}
phase = st.nextToken().trim();
if (phase.equals("") || phase.equals(".")) {
phase = null;
}
if (st.hasMoreTokens()) {
parseAttribute(st.nextToken(), line);
}
}
/**
* Create a new GFF3Record
* @param sequenceID the sequence name
* @param source the source
* @param type the feature type
* @param start the start coordinate on the sequence given by sequenceID
* @param end the end coordinate on the sequence
* @param score the feature score or null if there is no score
* @param strand the feature strand or null
* @param phase the phase or null
* @param attributes a Map from attribute name to a List of attribute values
*/
public GFF3Record(String sequenceID, String source, String type, int start, int end,
Double score, String strand, String phase, Map attributes) {
this.sequenceID = sequenceID.trim();
this.source = source.trim();
this.type = type.trim();
this.start = start;
this.end = end;
this.score = score;
this.strand = strand.trim();
this.phase = phase.trim();
this.attributes = attributes;
}
private void parseAttribute(String attributeString, String line) throws IOException {
StringTokenizer sTok = new StringTokenizer(attributeString, ";", false);
while (sTok.hasMoreTokens()) {
String attVal = sTok.nextToken().trim();
if (attVal.length() == 0) {
continue;
}
String attName;
List valList = new ArrayList();
int spaceIndx = attVal.indexOf("=");
if (spaceIndx == -1) {
throw new IOException("the attributes section must contain name=value pairs, "
+ "while parsing: " + line);
} else {
attName = attVal.substring(0, spaceIndx);
attributeString = attVal.substring(spaceIndx + 1).trim();
while (attributeString.length() > 0) {
if (attributeString.startsWith("\"")) {
attributeString = attributeString.substring(1);
int quoteIndx = attributeString.indexOf("\"");
if (quoteIndx > 0) {
valList.add(attributeString.substring(0, quoteIndx));
attributeString = attributeString.substring(quoteIndx + 1).trim();
if (attributeString.startsWith(",")) {
attributeString = attributeString.substring(1).trim();
}
} else {
throw new IOException("unmatched quote in this line: " + line);
}
} else {
int commaIndx = attributeString.indexOf(",");
if (commaIndx == -1) {
valList.add(attributeString);
attributeString = "";
} else {
valList.add(attributeString.substring(0, commaIndx));
attributeString = attributeString.substring(commaIndx + 1).trim();
}
}
}
}
// Decode values
for (int i = 0; i < valList.size(); i++) {
String value = (String) valList.get(i);
if (!attName.equals("Target") && !attName.equals("Gap")) {
value = URLDecoder.decode(value, "UTF-8");
}
value = fixEntityNames(value);
valList.set(i, value);
}
attributes.put(attName, valList);
}
}
/**
* Return the sequenceID field of this record.
* @return the sequenceID field of this record
*/
public String getSequenceID () {
return sequenceID;
}
/**
* Return the source field of this record.
* @return the source field of this record
*/
public String getSource () {
return source;
}
/**
* Return the type field of this record.
* @return the type field of this record
*/
public String getType () {
return type;
}
/**
* Set the type of this record.
* @param type the new type
*/
public void setType(String type) {
this.type = type;
}
/**
* Return the start field of this record.
* @return the start field of this record
*/
public int getStart () {
return start;
}
/**
* Return the end field of this record.
* @return the end field of this record
*/
public int getEnd () {
return end;
}
/**
* Return the score field of this record.
* @return the score field of this record
*/
public Double getScore () {
return score;
}
/**
* Return the strand field of this record.
* @return returns null if the strand is unset (ie. with an empty field or contained "." in the
* original GFF3 file)
*/
public String getStrand () {
return strand;
}
/**
* Return the phase field of this record.
* @return returns null if the phase is unset (ie. with an empty field or contained "." in the
* original GFF3 file)
*/
public String getPhase () {
return phase;
}
/**
* Return the first value of the Id field from the attributes of this record.
* @return the Id from the attributes of this record or null of there isn't a value
*/
public String getId () {
if (getAttributes().containsKey("ID")) {
return (String) ((List) getAttributes().get("ID")).get(0);
} else {
return null;
}
}
/**
* Set the Id of this GFF3Record.
* @param id the new id
*/
public void setId(String id) {
attributes.put("ID", Collections.singletonList(id));
}
/**
* Return the list of the Name field from the attributes of this record.
* @return the Name from the attributes of this record or null of there isn't a value
*/
public List<String> getNames() {
if (getAttributes().containsKey("Name")) {
return (List) getAttributes().get("Name");
} else {
return null;
}
}
/**
* Return the first value of the Alias field from the attributes of this record.
* @return the Alias from the attributes of this record or null of there isn't a value
*/
public String getAlias () {
if (getAttributes().containsKey("Alias")) {
return (String) ((List) getAttributes().get("Alias")).get(0);
} else {
return null;
}
}
/**
* Return the list of the Parent field from the attributes of this record.
* @return the Parent from the attributes of this record or null of there isn't a value
*/
public List<String> getParents () {
if (getAttributes().containsKey("Parent")) {
return (List) getAttributes().get("Parent");
} else {
return null;
}
}
/**
* Return the first value of the Target field from the attributes of this record.
* @return the Target from the attributes of this record or null of there isn't a value
*/
public String getTarget() {
if (getAttributes().containsKey("Target")) {
return (String) ((List) getAttributes().get("Target")).get(0);
} else {
return null;
}
}
/**
* Return the first value of the Gap field from the attributes of this record.
* @return the Gap from the attributes of this record or null of there isn't a value
*/
public String getGap() {
if (getAttributes().containsKey("Gap")) {
return (String) ((List) getAttributes().get("Gap")).get(0);
} else {
return null;
}
}
/**
* Return the first value of the Note field from the attributes of this record.
* @return the Note from the attributes of this record or null of there isn't a value
*/
public String getNote() {
if (getAttributes().containsKey("Note")) {
return (String) ((List) getAttributes().get("Note")).get(0);
} else {
return null;
}
}
/**
* Return the first value of the Dbxref field from the attributes of this record.
* @return the Dbxref from the attributes of this record or null of there isn't a value
*/
public List<String> getDbxrefs() {
if (getAttributes().containsKey("Dbxref")) {
return (List) getAttributes().get("Dbxref");
} else {
return null;
}
}
/**
* Return the first value of the OntologyTerm field from the attributes of this record.
* @return the OntologyTerm from the attributes of this record or null of there isn't a value
*/
public String getOntologyTerm () {
if (getAttributes().containsKey("Ontology_term")) {
return (String) ((List) getAttributes().get("Ontology_term")).get(0);
} else {
return null;
}
}
/**
* Return the attributes of this record as a Map from attribute key to Lists of attribute
* values.
* @return the attributes of this record
*/
public Map getAttributes () {
return attributes;
}
/**
* {@inheritDoc}
*/
public String toString() {
return "<GFF3Record: sequenceID: " + sequenceID + " source: " + source + " type: "
+ type + " start: " + start + " end: " + end + " score: " + score + " strand: "
+ strand + " phase: " + phase + " attributes: " + attributes + ">";
}
/**
* Return this record in GFF format. The String is suitable for output to a GFF file.
* @return a GFF line
*/
public String toGFF3() {
try {
return URLEncoder.encode(sequenceID, "UTF-8") + "\t"
+ ((source == null) ? "." : source) + "\t"
+ type + "\t" + start + "\t" + end + "\t"
+ ((score == null) ? "." : score.toString()) + "\t"
+ ((strand == null) ? "." : strand) + "\t"
+ ((phase == null) ? "." : phase) + "\t"
+ writeAttributes();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("error while encoding: " + sequenceID, e);
}
}
private String writeAttributes() {
StringBuffer sb = new StringBuffer();
boolean first = true;
Iterator iter = attributes.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
if (!first) {
sb.append(";");
}
first = false;
String listValue;
if (entry.getValue() instanceof List) {
List oldList = (List) entry.getValue();
List encodedList = new ArrayList(oldList);
for (int i = 0; i < encodedList.size(); i++) {
Object oldValue = encodedList.get(i);
String newValue;
try {
newValue = URLEncoder.encode("" + oldValue, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("error while encoding: " + oldValue, e);
}
encodedList.set(i, newValue);
}
listValue = StringUtil.join(encodedList, ",");
} else {
try {
listValue = URLEncoder.encode("" + entry.getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("error while encoding: " + entry.getValue(), e);
}
}
sb.append(entry.getKey() + "=" + listValue);
}
return sb.toString();
}
/**
* Replace greek character entity names with entity names that work in HTML.
* @param value input string
* @return string with replacements
*/
protected static String fixEntityNames(String value) {
synchronized (GFF3Record.class) {
if (replacements == null) {
replacements = new HashMap();
replacements.put("agr", "alpha");
replacements.put("Agr", "Alpha");
replacements.put("bgr", "beta");
replacements.put("Bgr", "Beta");
replacements.put("ggr", "gamma");
replacements.put("Ggr", "Gamma");
replacements.put("dgr", "delta");
replacements.put("Dgr", "Delta");
replacements.put("egr", "epsilon");
replacements.put("Egr", "Epsilon");
replacements.put("zgr", "zeta");
replacements.put("Zgr", "Zeta");
replacements.put("eegr", "eta");
replacements.put("EEgr", "Eta");
replacements.put("thgr", "theta");
replacements.put("THgr", "Theta");
replacements.put("igr", "iota");
replacements.put("Igr", "Iota");
replacements.put("kgr", "kappa");
replacements.put("Kgr", "Kappa");
replacements.put("lgr", "lambda");
replacements.put("Lgr", "Lambda");
replacements.put("mgr", "mu");
replacements.put("Mgr", "Mu");
replacements.put("ngr", "nu");
replacements.put("Ngr", "Nu");
replacements.put("xgr", "xi");
replacements.put("Xgr", "Xi");
replacements.put("ogr", "omicron");
replacements.put("Ogr", "Omicron");
replacements.put("pgr", "pi");
replacements.put("Pgr", "Pi");
replacements.put("rgr", "rho");
replacements.put("Rgr", "Rho");
replacements.put("sgr", "sigma");
replacements.put("Sgr", "Sigma");
replacements.put("sfgr", "sigmaf");
replacements.put("tgr", "tau");
replacements.put("Tgr", "Tau");
replacements.put("ugr", "upsilon");
replacements.put("Ugr", "Upsilon");
replacements.put("phgr", "phi");
replacements.put("PHgr", "Phi");
replacements.put("khgr", "chi");
replacements.put("KHgr", "Chi");
replacements.put("psgr", "psi");
replacements.put("PSgr", "Psi");
replacements.put("ohgr", "omega");
replacements.put("OHgr", "Omega");
}
}
for (Iterator iter = replacements.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
if (value.indexOf('&') != -1) {
value = value.replaceAll("&" + entry.getKey() + ";", "&" + entry.getValue() + ";");
}
}
return value;
}
}
|
package verification.timed_state_exploration.zoneProject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import lpn.parser.ExprTree;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import verification.platu.lpn.LpnTranList;
import verification.platu.stategraph.State;
import verification.platu.stategraph.StateGraph;
import verification.timed_state_exploration.zone.TimedPrjState;
/**
* This class is for storing and manipulating timing zones via difference bound matrices.
* The underlying structure is backed by a two dimensional array. A difference bound
* matrix has the form
* t0 t1 t2 t3
* t0 m00 m01 m02 m03
* t1 m10 m11 m12 m13
* t2 m20 m21 m22 m23
* t3 m30 m31 m32 m33
* where tj - ti<= mij. In particular, m0k is an upper bound for tk and -mk is a lower
* bound for tk.
*
* The timers are referred to by an index.
*
* This class also contains a public nested class DiagonalNonZeroException which extends
* java.lang.RuntimeException. This exception may be thrown if the diagonal entries of a
* zone become nonzero.
*
* @author Andrew N. Fisher
*
*/
public class Zone{
// Abstraction Function :
// The difference bound matrix is represented by int[][].
// In order to keep track of the upper and lower bounds of timers from when they are first
// enabled, the matrix will be augmented by a row and a column. The first row will contain
// the upper bounds and the first column will contain the negative of the lower bounds.
// For one timer t1 that is between 2 and 3, we might have
// lb t0 t1
// ub x 0 3
// t0 0 m m
// t1 -2 m m
// where x is not important (and will be given a zero value), 3 is the upper bound on t1
// and -2 is the negative of the lower bound. The m values represent the actual difference
// bound matrix. Also note that the column heading are not part of the stored representation
// lb stands for lower bound while ub stands for upper bound.
// This upper and lower bound information is called the Delay for a Transition object.
// Since a timer is tied directly to a Transition, the timers are index by the corresponding
// Transition's index in a LPNTranslator.
// The timers are named by an integer referred to as the index. The _indexToTimer array
// connects the index in the DBM sub-matrix to the index of the timer. For example,
// a the timer t1
// Representation invariant :
// Zones are immutable.
// Integer.MAX_VALUE is used to logically represent infinity.
// The lb and ub values for a timer should be set when the timer is enabled.
// A negative hash code indicates that the hash code has not been set.
// The index of the timer in _indexToTimer is the index in the DBM and should contain
// the zeroth timer.
// The array _indexToTimerPair should always be sorted.
// The index of the LPN should match where it is in the _lpnList, that is, if lpn is
// and LhpnFile object in _lpnList, then _lpnList[getLpnIndex()] == lpn.
/*
* Resource List :
* TODO : Create a list reference where the algorithms can be found that this class
* depends on.
*/
public static final int INFINITY = Integer.MAX_VALUE;
/* The lower and upper bounds of the times as well as the dbm. */
private int[][] _matrix;
/* Maps the index to the timer. The index is row/column of the DBM sub-matrix.
* Logically the zero timer is given index -1.
* */
//private int[] _indexToTimer;
private LPNTransitionPair[] _indexToTimerPair;
/* The hash code. */
private int _hashCode;
/* A lexicon between a transitions index and its name. */
//private static HashMap<Integer, Transition> _indexToTransition;
/* Set if a failure in the testSplit method has fired already. */
//private static boolean _FAILURE = false;
/* Hack to pass a parameter to the equals method though a variable */
//private boolean subsetting = false;
/* Records the largest zone that occurs. */
public static int ZoneSize = 0;
private void checkZoneMaxSize(){
if(dbmSize() > ZoneSize){
ZoneSize = dbmSize();
}
}
private LhpnFile[] _lpnList;
/*
* Turns on and off subsets for the zones.
* True means subset will be considered.
* False means subsets will not be considered.
*/
private static boolean _subsetFlag = true;
/*
* Turns on and off supersets for zones.
* True means that supersets will be considered.
* False means that supersets will not be considered.
*/
private static boolean _supersetFlag = true;
/**
* Gets the value of the subset flag.
* @return
* True if subsets are requested, false otherwise.
*/
public static boolean getSubsetFlag(){
return _subsetFlag;
}
/**
* Sets the value of the subset flag.
* @param useSubsets
* The value for the subset flag. Set to true if
* supersets are to be considered, false otherwise.
*/
public static void setSubsetFlag(boolean useSubsets){
_subsetFlag = useSubsets;
}
/**
* Gets the value of the superset flag.
* @return
* True if supersets are to be considered, false otherwise.
*/
public static boolean getSupersetFlag(){
return _supersetFlag;
}
/**
* Sets the superset flag.
* @param useSupersets
* The value of the superset flag. Set to true if
* supersets are to be considered, false otherwise.
*/
public static void setSupersetFlag(boolean useSupersets){
_supersetFlag = useSupersets;
}
/**
* Construct a zone that has the given timers.
* @param timers
* The ith index of the array is the index of the timer. For example,
* if timers = [1, 3, 5], then the zeroth row/column of the DBM is the
* timer of the transition with index 1, the first row/column of the
* DBM is the timer of the transition with index 3, and the 2nd
* row/column is the timer of the transition with index 5. Do not
* include the zero timer.
* @param matrix
* The DBM augmented with the lower and upper bounds of the delays for the
* transitions. For example, suppose a zone has timers [1, 3, 5] (as
* described in the timers parameters). The delay for transition 1 is
* [1, 3], the delay for transition 3 is [2,5], and the delay for
* transition 5 is [4,6]. Also suppose the DBM is
* t0 t1 t3 t5
* t0 | 0, 3, 3, 3 |
* t1 | 0, 0, 0, 0 |
* t3 | 0, 0, 0, 0 |
* t5 | 0, 0, 0, 0 |
* Then the matrix that should be passed is
* lb t0 t1 t3 t5
* ub| 0, 0, 3, 5, 6|
* t0| 0, 0, 3, 3, 3|
* t1|-1, 0, 0, 0, 0|
* t3|-2, 0, 0, 0, 0|
* t5|-4, 0, 0, 0, 0|
* The matrix should be non-null and the zero timer should always be the
* first timer, even when there are no other timers.
*/
public Zone(int[] timers, int[][] matrix)
{
// A negative number indicates that the hash code has not been set.
_hashCode = -1;
// Make a copy to reorder the timers.
// _indexToTimer = Arrays.copyOf(timers, timers.length);
// Make a copy to reorder the timers.
_indexToTimerPair = new LPNTransitionPair[timers.length];
for(int i=0; i<timers.length; i++){
_indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN,
timers[i], true);
}
// Sorting the array.
// Arrays.sort(_indexToTimer);
// Sorting the array.
Arrays.sort(_indexToTimerPair);
//if(_indexToTimer[0] != 0)
// if(_indexToTimer[0] != -1)
// // Add the zeroth timer.
// int[] newIndexToTimer = new int[_indexToTimer.length+1];
// for(int i=0; i<_indexToTimer.length; i++)
// newIndexToTimer[i+1] = _indexToTimer[i];
// _indexToTimer = newIndexToTimer;
// _indexToTimer[0] = -1;
if(_indexToTimerPair[0].get_transitionIndex() != -1){
// Add the zeroth timer.
LPNTransitionPair[] newIndexToTimerPair =
new LPNTransitionPair[_indexToTimerPair.length];
for(int i=0; i<_indexToTimerPair.length; i++){
newIndexToTimerPair[i+1] = _indexToTimerPair[i];
}
_indexToTimerPair = newIndexToTimerPair;
_indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1, true);
}
// if(_indexToTimer[0] < 0)
// // Add a zero timer.
// else if(_indexToTimer[0] > 0)
// int[] newTimerIndex = new int[_indexToTimer.length+1];
// for(int i=0; i<_indexToTimer.length; i++)
// newTimerIndex[i+1] = _indexToTimer[i];
// Map the old index of the timer to the new index of the timer.
HashMap<Integer, Integer> newIndex = new HashMap<Integer, Integer>();
// For the old index, find the new index.
for(int i=0; i<timers.length; i++)
{
// Since the zeroth timer is not included in the timers passed
// to the index in the DBM is 1 more than the index of the timer
// in the timers array.
//newIndex.put(i+1, Arrays.binarySearch(_indexToTimer, timers[i]));
LPNTransitionPair searchValue =
new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i], true);
newIndex.put(i+1, Arrays.binarySearch(_indexToTimerPair, searchValue));
}
// Add the zero timer index.
newIndex.put(0, 0);
// Initialize the matrix.
_matrix = new int[matrixSize()][matrixSize()];
// Copy the DBM
for(int i=0; i<dbmSize(); i++)
{
for(int j=0; j<dbmSize(); j++)
{
// Copy the passed in matrix to _matrix.
setDbmEntry(newIndex.get(i), newIndex.get(j),
matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]);
// In the above, changed setDBMIndex to setdbm
}
}
// Copy in the upper and lower bounds. The zero time does not have an upper or lower bound
// so the index starts at i=1, the first non-zero timer.
for(int i=1; i< dbmSize(); i++)
{
setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]);
// Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound
// and the matrix stores the negative of the lower bound. So the matrix value
// must be multiplied by -1.
setLowerBoundbydbmIndex(newIndex.get(i), -1*matrix[dbmIndexToMatrixIndex(i)][0]);
}
recononicalize();
}
/**
* Initializes a zone according to the markings of state.
* @param currentState
* The zone is initialized as if all enabled timers
* have just been enabled.
*/
public Zone(State initialState)
{
LhpnFile lpn = initialState.getLpn();
int LPNIndex = lpn.getLpnIndex();
if(_lpnList == null){
// If no LPN exists yet, create it and put lpn in it.
_lpnList = new LhpnFile[LPNIndex+1];
_lpnList[LPNIndex] = lpn;
}
else if(_lpnList.length <= LPNIndex){
// The list does not contain the lpn.
LhpnFile[] tmpList = _lpnList;
_lpnList = new LhpnFile[LPNIndex+1];
_lpnList[LPNIndex] = lpn;
// Copy any that exist already.
for(int i=0; i<_lpnList.length; i++){
_lpnList[i] = tmpList[i];
}
}
else if(_lpnList[LPNIndex] != lpn){
// This checks that the appropriate lpn is in the right spot.
// If not (which gets you in this block), then this fixes it.
_lpnList[LPNIndex] = lpn;
}
_hashCode = -1;
boolean[] enabledTran = initialState.getTranVector();
ArrayList<LPNTransitionPair> enabledTransitionsArrayList =
new ArrayList<LPNTransitionPair>();
LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1, true);
// Add the zero timer first.
enabledTransitionsArrayList.add(zeroPair);
// The index of the boolean value corresponds to the index of the Transition.
for(int i=0; i<enabledTran.length; i++){
if(enabledTran[i]){
enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i, true));
}
}
_indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);
_matrix = new int[matrixSize()][matrixSize()];
for(int i=1; i<dbmSize(); i++)
{
// Get the name for the timer in the i-th column/row of DBM
String tranName =
lpn.getTransition(_indexToTimerPair[i].get_transitionIndex()).getName();
ExprTree delay = lpn.getDelayTree(tranName);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
lpn.getAllVarsWithValuesAsString(initialState.getVector());
// Set the upper and lower bound.
int upper, lower;
if(delay.getOp().equals("uniform"))
{
ExprTree lowerDelay = delay.getLeftChild();
ExprTree upperDelay = delay.getRightChild();
lower = (int) lowerDelay.evaluateExpr(varValues);
upper = (int) upperDelay.evaluateExpr(varValues);
}
else
{
lower = (int) delay.evaluateExpr(varValues);
upper = lower;
}
setLowerBoundbydbmIndex(i, lower);
setUpperBoundbydbmIndex(i, upper);
}
// Advance the time and tighten the bounds.
advance();
recononicalize();
checkZoneMaxSize();
}
/**
* Creates a Zone based on the local states.
* @param localStates
* The current state (or initial) of the LPNs.
*/
public Zone(State[] localStates){
// Extract the local states.
//State[] localStates = tps.toStateArray();
// Initialize hash code to -1 (indicating nothing cached).
_hashCode = -1;
// Initialize the LPN list.
initialize_lpnList(localStates);
// Get the enabled transitions. This initializes the _indexTotimerPair
// which stores the relevant information.
initialize_indexToTimerPair(localStates);
// Initialize the matrix.
_matrix = new int[matrixSize()][matrixSize()];
// Set the lower bound/ upper bounds.
initializeLowerUpperBounds(getTransitionNames(), localStates);
// Advance Time
advance();
// Re-canonicalize
recononicalize();
// Check the size of the dbm.
checkZoneMaxSize();
}
/**
* Gives the names of all the transitions that are represented by the zone.
* @return
* The names of the transitions that are represented by the zone.
*/
public String[] getTransitionNames(){
String[] transitionNames = new String[_indexToTimerPair.length];
transitionNames[0] = "The zero timer.";
for(int i=1; i<transitionNames.length; i++){
LPNTransitionPair ltPair = _indexToTimerPair[i];
transitionNames[i] = _lpnList[ltPair.get_lpnIndex()]
.getTransition(ltPair.get_transitionIndex()).getName();
}
return transitionNames;
}
/**
* Initializes the _lpnList using information from the local states.
* @param localStates
* The local states.
* @return
* The enabled transitions.
*/
private void initialize_lpnList(State[] localStates){
// Create the LPN list.
_lpnList = new LhpnFile[localStates.length];
// Get the LPNs.
for(int i=0; i<localStates.length; i++){
_lpnList[i] = localStates[i].getLpn();
}
}
/**
* Initializes the _indexToTimerPair from the local states.
* @param localStates
* The local states.
* @return
* The names of the transitions stored in the _indexToTimerPair (in the same order).
*/
private void initialize_indexToTimerPair(State[] localStates){
// This list accumulates the transition pairs.
ArrayList<LPNTransitionPair> enabledTransitionsArrayList =
new ArrayList<LPNTransitionPair>();
// Put in the zero timer.
enabledTransitionsArrayList
.add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1, true));
// Get the rest of the transitions.
for(int i=0; i<localStates.length; i++){
// Extract the enabled transition vector.
boolean[] enabledTran = localStates[i].getTranVector();
// Accumulates the transition pairs for one LPN.
ArrayList<LPNTransitionPair> singleLPN = new ArrayList<LPNTransitionPair>();
// The index of the boolean value corresponds to the index of the Transition.
for(int j=0; j<enabledTran.length; j++){
if(enabledTran[j]){
// Add the transition pair.
singleLPN.add(new LPNTransitionPair(i, j, true));
}
}
// Sort the transitions for the current LPN.
Collections.sort(singleLPN);
// Add the collection to the enabledTransitionsArrayList
for(int j=0; j<singleLPN.size(); j++){
enabledTransitionsArrayList.add(singleLPN.get(j));
}
}
// Extract out the array portion of the enabledTransitionsArrayList.
_indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);
}
/**
* Sets the lower and upper bounds for the transitions.
* @param transitionNames
* The names of the transitions in _indexToTimerPair.
*/
private void initializeLowerUpperBounds(String[] transitionNames, State[] localStates){
// Traverse the entire length of the DBM submatrix except the zero row/column.
// This is the same length as the _indexToTimerPair.length-1. The DBM is used to
// match the idea of setting the value for each row.
for(int i=1; i<dbmSize(); i++){
// Get the current LPN and transition pairing.
LPNTransitionPair ltPair = _indexToTimerPair[i];
// Get the expression tree.
ExprTree delay = _lpnList[ltPair.get_lpnIndex()].getDelayTree(transitionNames[i]);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
_lpnList[ltPair.get_lpnIndex()]
.getAllVarsWithValuesAsString(localStates[ltPair.get_lpnIndex()].getVector());
// Set the upper and lower bound.
int upper, lower;
if(delay.getOp().equals("uniform"))
{
ExprTree lowerDelay = delay.getLeftChild();
ExprTree upperDelay = delay.getRightChild();
lower = (int) lowerDelay.evaluateExpr(varValues);
upper = (int) upperDelay.evaluateExpr(varValues);
}
else
{
lower = (int) delay.evaluateExpr(varValues);
upper = lower;
}
setLowerBoundbydbmIndex(i, lower);
setUpperBoundbydbmIndex(i, upper);
}
}
/**
* Zero argument constructor for use in methods that create Zones where the members
* variables will be set by the method.
*/
private Zone()
{
_matrix = new int[0][0];
_indexToTimerPair = new LPNTransitionPair[0];
_hashCode = -1;
_lpnList = new LhpnFile[0];
}
/**
* Gets the upper bound of a Transition from the zone.
* @param t
* The transition whose upper bound is wanted.
* @return
* The upper bound of Transition t.
*/
public int getUpperBoundbyTransition(Transition t)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
LPNTransitionPair ltPair =
new LPNTransitionPair(lpnIndex, transitionIndex, true);
return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));
}
/**
* Get the value of the upper bound for the delay.
* @param index
* The timer's row/column of the DBM matrix.
* @return
* The upper bound on the transitions delay.
*/
public int getUpperBoundbydbmIndex(int index)
{
return _matrix[0][dbmIndexToMatrixIndex(index)];
}
/**
* Set the value of the upper bound for the delay.
* @param t
* The transition whose upper bound is being set.
* @param value
* The value of the upper bound.
*/
public void setUpperBoundbyTransition(Transition t, int value)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);
}
/**
* Set the value of the upper bound for the delay.
* @param index
* The timer's row/column of the DBM matrix.
* @param value
* The value of the upper bound.
*/
public void setUpperBoundbydbmIndex(int index, int value)
{
_matrix[0][dbmIndexToMatrixIndex(index)] = value;
}
/**
* Sets the upper bound for a transition described by an LPNTransitionPair.
* @param ltPair
* The index of the transition and the index of the associated LPN for
* the timer to set the upper bound.
* @param value
* The value for setting the upper bound.
*/
private void setUpperBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value){
setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);
}
/**
* Gets the lower bound of a Transition from the zone.
* @param t
* The transition whose upper bound is wanted.
* @return
* The lower bound of Transition t.
*/
public int getLowerBoundbyTransition(Transition t)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
return -1*getLowerBoundbydbmIndex(
Arrays.binarySearch(_indexToTimerPair, ltPair));
}
/**
* Get the value of the lower bound for the delay.
* @param index
* The timer's row/column of the DBM matrix.
* @return
* The value of the lower bound.
*/
public int getLowerBoundbydbmIndex(int index)
{
return _matrix[dbmIndexToMatrixIndex(index)][0];
}
/**
* Set the value of the lower bound for the delay.
* @param t
* The transition whose lower bound is being set.
* @param value
* The value of the lower bound.
*/
public void setLowerBoundbyTransition(Transition t, int value)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair,ltPair), value);
}
/**
* Set the value of the upper bound for the delay.
* @param t
* The transition whose upper bound is being set.
* @param value
* The value of the upper bound.
*/
private void setLowerBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value){
setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair,ltPair), value);
}
/**
* Set the value of the lower bound for the delay.
* @param index
* The timer's row/column of the DBM matrix.
* @param value
* The value of the lower bound.
*/
public void setLowerBoundbydbmIndex(int index, int value)
{
_matrix[dbmIndexToMatrixIndex(index)][0] = -1*value;
}
/**
* Converts the index of the DBM to the index of _matrix.
* @param i
* The row/column index of the DBM.
* @return
* The row/column index of _matrix.
*/
private int dbmIndexToMatrixIndex(int i)
{
return i+1;
}
/**
* Retrieves an entry of the DBM using the DBM's addressing.
* @param i
* The row of the DBM.
* @param j
* The column of the DBM.
* @return
* The value of the (i, j) element of the DBM.
*/
public int getDbmEntry(int i, int j)
{
return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)];
}
/**
* Sets an entry of the DBM using the DBM's addressing.
* @param i
* The row of the DBM.
* @param j
* The column of the DBM.
* @param value
* The new value for the entry.
*/
private void setDbmEntry(int i, int j, int value)
{
_matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value;
}
/**
* Returns the index of the the transition in the DBM given a LPNTransitionPair pairing
* the transition index and associated LPN index.
* @param ltPair
* The pairing comprising the index of the transition and the index of the associated
* LPN.
* @return
* The row/column of the DBM associated with the ltPair.
*/
private int timerIndexToDBMIndex(LPNTransitionPair ltPair)
{
return Arrays.binarySearch(_indexToTimerPair, ltPair);
}
/**
* The matrix labeled with 'ti' where i is the transition index associated with the timer.
*/
public String toString()
{
String result = "Timer and delay.\n";
int count = 0;
// Print the timers.
for(int i=1; i<_indexToTimerPair.length; i++, count++)
{
if(_lpnList.length == 0)
{
// If no LPN's are associated with this Zone, use the index of the timer.
result += " t" + _indexToTimerPair[i].get_transitionIndex() + " : ";
}
else
{
// Get the name of the transition.
Transition tran = _lpnList[_indexToTimerPair[i].get_lpnIndex()].
getTransition(_indexToTimerPair[i].get_transitionIndex());
result += " " + tran.getName() + ":";
}
result += "[ " + -1*getLowerBoundbydbmIndex(i) + ", " + getUpperBoundbydbmIndex(i) + " ]";
if(count > 9)
{
result += "\n";
count = 0;
}
}
result += "\nDBM\n";
// Print the DBM.
for(int i=0; i<_indexToTimerPair.length; i++)
{
result += "| " + getDbmEntry(i, 0);
for(int j=1; j<_indexToTimerPair.length; j++)
{
result += ", " + getDbmEntry(i, j);
}
result += " |\n";
}
return result;
}
/**
* Tests for equality. Overrides inherited equals method.
* @return True if o is equal to this object, false otherwise.
*/
public boolean equals(Object o)
{
// Check if the reference is null.
if(o == null)
{
return false;
}
// Check that the type is correct.
if(!(o instanceof Zone))
{
return false;
}
// Check for equality using the Zone equality.
return equals((Zone) o);
}
/**
* Tests for equality.
* @param
* The Zone to compare.
* @return
* True if the zones are non-null and equal, false otherwise.
*/
public boolean equals(Zone otherZone)
{
// Check if the reference is null first.
if(otherZone == null)
{
return false;
}
// Check for reference equality.
if(this == otherZone)
{
return true;
}
// If the hash codes are different, then the objects are not equal.
if(this.hashCode() != otherZone.hashCode())
{
return false;
}
// Check if the they have the same number of timers.
if(this._indexToTimerPair.length != otherZone._indexToTimerPair.length){
return false;
}
// Check if the timers are the same.
for(int i=0; i<this._indexToTimerPair.length; i++){
if(!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))){
return false;
}
}
// Check if the matrix is the same
for(int i=0; i<_matrix.length; i++)
{
for(int j=0; j<_matrix[0].length; j++)
{
if(!(this._matrix[i][j] == otherZone._matrix[i][j]))
{
return false;
}
}
}
return true;
}
/**
* Determines if this zone is a subset of Zone otherZone.
* @param otherZone
* The zone to compare against.
* @return
* True if this is a subset of other; false otherwise.
*/
public boolean subset(Zone otherZone){
// Check if the reference is null first.
if(otherZone == null)
{
return false;
}
// Check for reference equality.
if(this == otherZone)
{
return true;
}
// Check if the the same number of timers are present.
if(this._indexToTimerPair.length != otherZone._indexToTimerPair.length){
return false;
}
// Check if the transitions are the same.
for(int i=0; i<this._indexToTimerPair.length; i++){
if(!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))){
return false;
}
}
// Check if the entries of this Zone are less than or equal to the entries
// of the other Zone.
for(int i=0; i<_matrix.length; i++)
{
for(int j=0; j<_matrix[0].length; j++)
{
if(!(this._matrix[i][j] <= otherZone._matrix[i][j])){
return false;
}
}
}
return true;
}
/**
* Determines if this zone is a superset of Zone otherZone.
* @param otherZone
* The zone to compare against.
* @return
* True if this is a subset of other; false otherwise. More specifically it
* gives the result of otherZone.subset(this). Thus it agrees with the subset method.
*/
public boolean superset(Zone otherZone){
return otherZone.subset(this);
}
/**
* Overrides the hashCode.
*/
public int hashCode()
{
// Check if the hash code has been set.
if(_hashCode <0)
{
_hashCode = createHashCode();
}
return _hashCode;
}
/**
* Creates a hash code for a Zone object.
* @return
* The hash code.
*/
private int createHashCode()
{
int newHashCode = Arrays.hashCode(_indexToTimerPair);
for(int i=0; i<_matrix.length; i++)
{
newHashCode ^= Arrays.hashCode(_matrix[i]);
}
return Math.abs(newHashCode);
}
/**
* The size of the DBM sub matrix. This is calculated using the size of _indexToTimer.
* @return
* The size of the DBM.
*/
private int dbmSize()
{
return _indexToTimerPair.length;
}
/**
* The size of the matrix.
* @return
* The size of the matrix. This is calculated using the size of _indexToTimer.
*/
private int matrixSize()
{
return _indexToTimerPair.length + 1;
}
/**
* Performs the Floyd's least pairs algorithm to reduce the DBM.
*/
private void recononicalize()
{
for(int k=0; k<dbmSize(); k++)
{
for (int i=0; i<dbmSize(); i++)
{
for(int j=0; j<dbmSize(); j++)
{
if(getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY
&& getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j))
{
setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j));
}
if( (i==j) && getDbmEntry(i, j) != 0)
{
throw new DiagonalNonZeroException("Entry (" + i + ", " + j + ")" +
" became " + getDbmEntry(i, j) + ".");
}
}
}
}
}
/**
* Determines if a timer associated with a given transitions has reached its lower bound.
* @param t
* The transition to consider.
* @return
* True if the timer has reached its lower bound, false otherwise.
*/
public boolean exceedsLowerBoundbyTransitionIndex(Transition t)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));
}
/**
* Determines if a timer has reached its lower bound.
* @param timer
* The timer's index.
* @return
* True if the timer has reached its lower bound, false otherwise.
*/
public boolean exceedsLowerBoundbydbmIndex(int index)
{
// Note : Make sure that the lower bound is stored as a negative number
// and that the inequality is correct.
return _matrix[0][dbmIndexToMatrixIndex(index)] <=
_matrix[1][dbmIndexToMatrixIndex(index)];
}
/* (non-Javadoc)
* @see verification.timed_state_exploration.zone.Zone#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State)
*/
// public Zone fireTransitionbyTransitionIndex(int timer, int[] enabledTimers,
// State state)
// // TODO: Check if finish.
// int index = Arrays.binarySearch(_indexToTimer, timer);
// //return fireTransitionbydbmIndex(Arrays.binarySearch(_indexToTimer, timer),
// //enabledTimers, state);
// // Check if the value is in this zone to fire.
// if(index < 0){
// return this;
// return fireTransitionbydbmIndex(index, enabledTimers, state);
/**
* Gives the Zone obtained by firing a given Transitions.
* @param t
* The transitions being fired.
* @param enabledTran
* The list of currently enabled Transitions.
* @param localStates
* The current local states.
* @return
* The Zone obtained by firing Transition t with enabled Transitions enabled
* enabledTran when the current state is localStates.
*/
public Zone fire(Transition t, LpnTranList enabledTran, State[] localStates){
// Create the LPNTransitionPair to check if the Transitions is in the zone and to
// find the index.
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair);
if(dbmIndex <= 0){
return this;
}
return fireTransitionbydbmIndex(dbmIndex, enabledTran, localStates);
}
/**
* Updates the Zone according to the transition firing.
* @param index
* The index of the timer.
* @return
* The updated Zone.
*/
public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers,
State[] localStates)
{
Zone newZone = new Zone();
// Copy the LPNs over.
newZone._lpnList = new LhpnFile[this._lpnList.length];
for(int i=0; i<this._lpnList.length; i++){
newZone._lpnList[i] = this._lpnList[i];
}
// Extract the pairing information for the enabled timers.
// Using the enabledTimersList should be faster than calling the get method
// several times.
newZone._indexToTimerPair = new LPNTransitionPair[enabledTimers.size() + 1];
int count = 0;
newZone._indexToTimerPair[count++] =
new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1, true);
for(Transition t : enabledTimers){
newZone._indexToTimerPair[count++] =
new LPNTransitionPair(t.getLpn().getLpnIndex(), t.getIndex(), true);
}
Arrays.sort(newZone._indexToTimerPair);
HashSet<LPNTransitionPair> newTimers = new HashSet<LPNTransitionPair>();
HashSet<LPNTransitionPair> oldTimers = new HashSet<LPNTransitionPair>();
for(int i=0; i<newZone._indexToTimerPair.length; i++)
{
// Determine if each value is a new timer or old.
if(Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i])
>= 0 )
{
// The timer was already present in the zone.
oldTimers.add(newZone._indexToTimerPair[i]);
}
else
{
// The timer is a new timer.
newTimers.add(newZone._indexToTimerPair[i]);
}
}
// Create the new matrix.
newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];
// TODO: For simplicity, make a copy of the current zone and perform the
// restriction and re-canonicalization. Later add a copy re-canonicalization
// that does the steps together.
Zone tempZone = this.clone();
tempZone.restrict(index);
tempZone.recononicalize();
// Copy the tempZone to the new zone.
for(int i=0; i<tempZone.dbmSize(); i++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[i]))
{
continue;
}
// Get the new index of for the timer.
int newIndexi = i==0 ? 0 :
Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);
for(int j=0; j<tempZone.dbmSize(); j++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[j]))
{
continue;
}
int newIndexj = j==0 ? 0 :
Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);
newZone._matrix[newZone.dbmIndexToMatrixIndex(newIndexi)]
[newZone.dbmIndexToMatrixIndex(newIndexj)]
= tempZone.getDbmEntry(i, j);
}
}
// Copy the upper and lower bounds.
for(int i=1; i<tempZone.dbmSize(); i++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[i]))
{
continue;
}
newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i],
-1*tempZone.getLowerBoundbydbmIndex(i));
// The minus sign is because _matrix stores the negative of the lower bound.
newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i],
tempZone.getUpperBoundbydbmIndex(i));
}
// Copy in the new relations for the new timers.
for(LPNTransitionPair timerNew : newTimers)
{
for(LPNTransitionPair timerOld : oldTimers)
{
newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew),
newZone.timerIndexToDBMIndex(timerOld),
tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));
// int newTimeIndex = newZone.timerIndexToDBMIndex(timerNew);
// int oldTimeIndex = newZone.timerIndexToDBMIndex(timerOld);
// int value = tempZone.getDbmEntry(0, oldTimeIndex);
newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld),
newZone.timerIndexToDBMIndex(timerNew),
tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));
}
}
// Set the upper and lower bounds for the new timers.
for(LPNTransitionPair pair : newTimers){
// Get all the upper and lower bounds for the new timers.
// Get the name for the timer in the i-th column/row of DBM
//String tranName = indexToTran.get(i).getName();
String tranName = _lpnList[pair.get_lpnIndex()]
.getTransition(pair.get_transitionIndex()).getName();
ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
_lpnList[pair.get_lpnIndex()]
.getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVector());
// Set the upper and lower bound.
int upper, lower;
if(delay.getOp().equals("uniform"))
{
ExprTree lowerDelay = delay.getLeftChild();
ExprTree upperDelay = delay.getRightChild();
lower = (int) lowerDelay.evaluateExpr(varValues);
upper = (int) upperDelay.evaluateExpr(varValues);
}
else
{
lower = (int) delay.evaluateExpr(varValues);
upper = lower;
}
newZone.setLowerBoundByLPNTransitionPair(pair, lower);
newZone.setUpperBoundByLPNTransitionPair(pair, upper);
}
newZone.advance();
newZone.recononicalize();
newZone.checkZoneMaxSize();
return newZone;
}
/**
* Advances time.
*/
private void advance()
{
for(int i=0; i<dbmSize(); i++)
{
_matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] =
getUpperBoundbydbmIndex(i);
}
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
public Zone clone()
{
// TODO: Check if finished.
Zone clonedZone = new Zone();
clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()];
for(int i=0; i<this.matrixSize(); i++)
{
for(int j=0; j<this.matrixSize(); j++)
{
clonedZone._matrix[i][j] = this._matrix[i][j];
}
}
clonedZone._indexToTimerPair = Arrays.copyOf(_indexToTimerPair, _indexToTimerPair.length);
clonedZone._hashCode = this._hashCode;
clonedZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);
return clonedZone;
}
/**
* Restricts the lower bound of a timer.
*
* @param timer
* The timer to tighten the lower bound.
*/
private void restrict(int timer)
{
//int dbmIndex = Arrays.binarySearch(_indexToTimer, timer);
_matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)]
= getLowerBoundbydbmIndex(timer);
}
/**
* The list of enabled timers.
* @return
* The list of all timers that have reached their lower bounds.
*/
public List<Transition> getEnabledTransitions()
{
ArrayList<Transition> enabledTransitions = new ArrayList<Transition>();
// Check if the timer exceeds its lower bound staring with the first nonzero
// timer.
for(int i=1; i<_indexToTimerPair.length; i++)
{
if(getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i))
{
enabledTransitions.add(_lpnList[_indexToTimerPair[i].get_lpnIndex()]
.getTransition(_indexToTimerPair[i].get_transitionIndex()));
}
}
return enabledTransitions;
}
/**
* Gives the list of enabled transitions associated with a particular LPN.
* @param LpnIndex
* The Index of the LPN the Transitions are a part of.
* @return
* A List of the Transitions that are enabled in the LPN given by the index.
*/
public List<Transition> getEnabledTransitions(int LpnIndex){
ArrayList<Transition> enabledTransitions = new ArrayList<Transition>();
// Check if the timer exceeds its lower bound staring with the first nonzero
// timer.
for(int i=1; i<_indexToTimerPair.length; i++)
{
if(getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i))
{
LPNTransitionPair ltPair = _indexToTimerPair[i];
if( ltPair.get_lpnIndex() == LpnIndex){
enabledTransitions.add(_lpnList[ltPair.get_lpnIndex()]
.getTransition(ltPair.get_transitionIndex()));
}
}
}
return enabledTransitions;
}
/* (non-Javadoc)
* @see verification.timed_state_exploration.zone.Zone#getLexicon()
*/
// public HashMap<Integer, Transition> getLexicon(){
// if(_indexToTransition == null){
// return null;
// return new HashMap<Integer, Transition>(_indexToTransition);
// public void setLexicon(HashMap<Integer, Transition> lexicon){
// _indexToTransition = lexicon;
/**
* Gives an array that maps the index of a timer in the DBM to the timer's index.
* @return
* The array that maps the index of a timer in the DBM to the timer's index.
*/
// public int[] getIndexToTimer(){
// return Arrays.copyOf(_indexToTimerPair, _indexToTimerPair.length);
/**
* Calculates a warping value needed to warp a Zone. When a zone is being warped the form
* r1*z2 - r1*z1 + r2*z1 becomes important in finding the new values of the zone. For example,
*
* @param z1
* Upper bound or negative lower bound.
* @param z2
* Relative value.
* @param r1
* First ratio.
* @param r2
* Second ratio.
* @return
* r1*z2 - r1*z1 + r2*z1
*/
public int warp(int z1, int z2, int r1, int r2){
/*
* See "Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets"
* by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda
* Section III.C for details on how this function is used and where it comes
* from.
*/
return r1*z2 - r1*z1 + r2*z1;
}
/**
* Warps a Zone.
* @return
* The warped Zone.
*/
public Zone dmbWarp(){
/*
* See "Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets"
* by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda
* Section III.C for details on how this function is used and where it comes
* from.
*/
return null;
}
/**
* The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion.
* The intention is for this exception to be thrown is a Zone has a non zero
* entry appear on the diagonal.
*
* @author Andrew N. Fisher
*
*/
public class DiagonalNonZeroException extends java.lang.RuntimeException
{
/**
* Generated serialVersionUID.
*/
private static final long serialVersionUID = -3857736741611605411L;
/**
* Creates a DiagonalNonZeroException.
* @param Message
* The message to be displayed when the exception is thrown.
*/
public DiagonalNonZeroException(String Message)
{
super(Message);
}
}
/**
* This exception is thrown when trying to merge two zones whose corresponding timers
* do not agree.
* @author Andrew N. Fisher
*
*/
// public class IncompatibleZoneException extends java.lang.RuntimeException
// // TODO : Check if this class can be removed.
// /**
// * Generated serialVersionUID
// */
// private static final long serialVersionUID = -2453680267411313227L;
// public IncompatibleZoneException(String Message)
// super(Message);
/**
* Clears out the lexicon.
*/
// public static void clearLexicon(){
// _indexToTransition = null;
}
|
package com.webimageloader.util;
import android.os.Build;
public class Android extends Build.VERSION_CODES {
/**
* Check the api level of the device we're running on
* @param level API level
* @return true if same or higher
*/
public static boolean isAPI(int level) {
return Build.VERSION.SDK_INT >= level;
}
private Android() {}
}
|
package verification.timed_state_exploration.zoneProject;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import lpn.parser.ExprTree;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import lpn.parser.Variable;
import verification.platu.lpn.DualHashMap;
import verification.platu.lpn.LpnTranList;
import verification.platu.main.Options;
import verification.platu.stategraph.State;
/**
* This class is for storing and manipulating the delay information for transitions as well as
* the values of continuous variables including rate their rates.
* A Zone represents the non-zero continuous variables and the timers for the delay in a
* Difference Bound Matrix (DBM)
*
* t0 c0 c1 t0 t1
* t0 m00 m01 m02 m03 m04
* c0 m10 m11 m12 m13 m14
* c1 m20 m21 m22 m23 m24
* t0 m30 m31 m32 m33 m34
* t1 m40 m41 m42 m43 m44
*
* For the timers, tj - ti <= m(ti,tj) where m(ti,tj) represents the element of the matrix with
* row ti and column tj. In particular, m(t0,ti) is an upper bound for ti and -m(ti,0) is a
* lower bound for ti. The continuous variables are normalized to have rate one before being
* placed in the matrix. Thus for a continuous variables ci with rate ri, the entry m(t0, ci) is
* (upper bound)/ri where 'upper bound' is the upper bound for the continuous variable and
* m(ci,t0) is -1*(lower bound)/ri where 'lower bound' is the lower bound of the continuous variable.
* When the rate is negative, dividing out by the rate switches the inequalities. For example,
* if ci is a continuous variable such that l < ci < u for some values l and u, then the normalized
* ci (that is ci/ri) is satisfies u/ri < ci/r < l/ri. Hence the m(t0,ci) is (lower bound)/ri and
* m(ci,0) is -1*(upper bound)/ri. The m(ci,cj) as well as m(ti,ci) and m(ci,ti) give the same kind
* of relational information as with just timers, but with the normalized values of the continuous
* variables. Note that a Zone with normalized continuous variables is referred to as being a 'warped'
* zone.
*
* The rate zero continuous variables are also stored in a Zone object, but they are not present in
* the zone. The Zone merely records the range of the continuous variable.
*
* The timers are referenced by the name of the transition that they are associated with and continuous
* variables are referenced by their name as well. In addition for non-zero rate continuous variables and
* the timers, several method will allow them to be referred by their index as a part of the (DMB). For
* example, c0 in the above DBM example, has index 1.
*
* A third way that the timers and variables (both rate zero and rate non-zero) can be referred to by
* an LPNTransitionPair object. These objects refer to a timer or continuous variable by providing the index
* of the corresponding transition or the index of the continuous variable as a member of an LPN and the
* index of that LPN. The LPNTransitionPair can be made more specific in the case of the continuous variables
* by using an LPNContinuousPair. These objects also provide the rate of the variable. LPNTransitionPairs
* can be used with continuous variables when they are only being used as an index only. If the rate is needed
* for the method, then LPNContinuousPairs must be used.
*
* @author Andrew N. Fisher
*
*/
public class Zone{
/*Abstraction Function :
* The difference bound matrix is stored in the _matrix member field, along with
* the upper and lower bounds of the timers and rates for continuous variables.
* The upper and lower bounds are stored when the timer becomes enabled. The upper and
* lower bounds of the rates are stored when the rate is assigned. The upper and lower
* bounds are stored in the first row and first column of the _matrix member field.
* The DBM occupies the rest of the array, that is, the sub-array formed by removing
* the first column and first row.
* For example, let t1 be a timer for a transition whose delay is between 2 and 3. Further
* let c1 be a continuous variable with rate between 4 and 5. Then _matrix would look like
* lb t0 c1 t1
* ub x 0 5 3
* t0 0 m m m
* c1 -4 m m m
* t1 -2 m m m
*
* with out the lb, ub, t0, t1, and c1.
*
* The x is does not represent anything and will most likely be zero. The upper and lower
* bounds for the zero timer (which is always present) are always 0. The m's comprise
* the DBM.
*
* For the most part, a timer or a continuous variable is referred to internally by an
* LPNTransitionPair. An LPNTransitionPair combines the index of the transition (or
* continuous variable) with the index of the LPN that the transition (or continuous
* variables) is a member of. Both continuous variables and transitions can be referred
* to by an LPNTransitionPair; however, it is better to use an LPNContinuousPair (which
* is inherited from the LPNTransitionPair) to refer to continuous variables.
* LPNContinuousPairs are used to distinguish continuous variables from transitions. They
* also store the current rate of the continuous variable.
*
* The LPNTransitionPairs are stored in the _indexToTimerPair member field. The row/column
* in the DBM for a transition is determined by the its position in this array. For example,
* suppose a transition t has an LPNTransitionPair ltTranPair that is the third element of
* the _indexToTimerPair. Then t will be the third column/row of the DBM.
*
* Continuous variables are handled slightly differently. The LPNContinuousPair for the
* continuous variables with a non-zero rate are stored in the _indexToTimerPair just as
* with the transitions. And just like with the transitions, the index in the DBM is
* determined by the index of the LPNContinuousPair in the _indexToTimerPair. However,
* rate zero continuous variables are stored in the _rateZeroContinuous member variable.
* The _rateZerContinuous pairs an LPNContinuousPair with a VariableRangePair. The
* VariableRangePair combines the variable with its upper and lower bound.
*
*/
/* Representation invariant :
* Zones are immutable.
* Integer.MAX_VALUE is used to logically represent infinity.
* The lb and ub values for a timer should be set when the timer is enabled.
* A negative hash code indicates that the hash code has not been set.
* The index of the timer in _indexToTimer is the index in the DBM and should contain
* the zeroth timer.
* The array _indexToTimerPair should always be sorted.
* The index of the LPN should match where it is in the _lpnList, that is, if lpn is
* and LhpnFile object in _lpnList, then _lpnList[getLpnIndex()] == lpn.
* The LPNTransitionPair in the _indexToTimer array should be an LPNContinuousPair
* when it stores the index to a continuous variable. Testing that the index
* is an LPNContinuousPair is used to determined if the indexing object points
* to a continuous variable. Also the LPNContinuousPair keeps track of the current rate.
*
*/
/*
* Resource List :
* TODO : Create a list reference where the algorithms can be found that this class
* depends on.
*/
public static final int INFINITY = Integer.MAX_VALUE;
/* The lower and upper bounds of the times as well as the dbm. */
private int[][] _matrix;
/* Maps the index to the timer. The index is row/column of the DBM sub-matrix.
* Logically the zero timer is given index -1.
* */
//private int[] _indexToTimer;
private LPNTransitionPair[] _indexToTimerPair;
/* The hash code. */
private int _hashCode;
/* A lexicon between a transitions index and its name. */
//private static HashMap<Integer, Transition> _indexToTransition;
/* Set if a failure in the testSplit method has fired already. */
//private static boolean _FAILURE = false;
/* Hack to pass a parameter to the equals method though a variable */
//private boolean subsetting = false;
/* Stores the continuous variables that have rate zero */
// HashMap<LPNTransitionPair, Variable> _rateZeroContinuous;
//DualHashMap<RangeAndPairing, Variable> _rateZeroContinuous;
DualHashMap<LPNContAndRate, VariableRangePair> _rateZeroContinuous;
/* Records the largest zone that occurs. */
public static int ZoneSize = 0;
/* Write a log file */
private static BufferedWriter _writeLogFile = null;
/**
* Returns the write log.
* @return
* The _writeLogfile.
*/
public static BufferedWriter get_writeLogFile(){
return _writeLogFile;
}
/**
* Sets the BufferedWriter.
* @param writeLogFile
*/
public static void set_writeLogFile(BufferedWriter writeLogFile){
_writeLogFile = writeLogFile;
}
/**
* Sets the writeLogFile to null.
*/
public static void reset_writeLogFile(){
_writeLogFile = null;
}
private void checkZoneMaxSize(){
if(dbmSize() > ZoneSize){
ZoneSize = dbmSize();
}
}
private LhpnFile[] _lpnList;
/*
* Turns on and off subsets for the zones.
* True means subset will be considered.
* False means subsets will not be considered.
*/
private static boolean _subsetFlag = true;
/*
* Turns on and off supersets for zones.
* True means that supersets will be considered.
* False means that supersets will not be considered.
*/
private static boolean _supersetFlag = true;
/**
* Gets the value of the subset flag.
* @return
* True if subsets are requested, false otherwise.
*/
public static boolean getSubsetFlag(){
return _subsetFlag;
}
/**
* Sets the value of the subset flag.
* @param useSubsets
* The value for the subset flag. Set to true if
* supersets are to be considered, false otherwise.
*/
public static void setSubsetFlag(boolean useSubsets){
_subsetFlag = useSubsets;
}
/**
* Gets the value of the superset flag.
* @return
* True if supersets are to be considered, false otherwise.
*/
public static boolean getSupersetFlag(){
return _supersetFlag;
}
/**
* Sets the superset flag.
* @param useSupersets
* The value of the superset flag. Set to true if
* supersets are to be considered, false otherwise.
*/
public static void setSupersetFlag(boolean useSupersets){
_supersetFlag = useSupersets;
}
/**
* Construct a zone that has the given timers.
* @param timers
* The ith index of the array is the index of the timer. For example,
* if timers = [1, 3, 5], then the zeroth row/column of the DBM is the
* timer of the transition with index 1, the first row/column of the
* DBM is the timer of the transition with index 3, and the 2nd
* row/column is the timer of the transition with index 5. Do not
* include the zero timer.
* @param matrix
* The DBM augmented with the lower and upper bounds of the delays for the
* transitions. For example, suppose a zone has timers [1, 3, 5] (as
* described in the timers parameters). The delay for transition 1 is
* [1, 3], the delay for transition 3 is [2,5], and the delay for
* transition 5 is [4,6]. Also suppose the DBM is
* t0 t1 t3 t5
* t0 | 0, 3, 3, 3 |
* t1 | 0, 0, 0, 0 |
* t3 | 0, 0, 0, 0 |
* t5 | 0, 0, 0, 0 |
* Then the matrix that should be passed is
* lb t0 t1 t3 t5
* ub| 0, 0, 3, 5, 6|
* t0| 0, 0, 3, 3, 3|
* t1|-1, 0, 0, 0, 0|
* t3|-2, 0, 0, 0, 0|
* t5|-4, 0, 0, 0, 0|
* The matrix should be non-null and the zero timer should always be the
* first timer, even when there are no other timers.
*/
public Zone(int[] timers, int[][] matrix)
{
// A negative number indicates that the hash code has not been set.
_hashCode = -1;
// Make a copy to reorder the timers.
// _indexToTimer = Arrays.copyOf(timers, timers.length);
// Make a copy to reorder the timers.
_indexToTimerPair = new LPNTransitionPair[timers.length];
for(int i=0; i<timers.length; i++){
// _indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN,
// timers[i], true);
_indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN,
timers[i]);
}
// Sorting the array.
// Arrays.sort(_indexToTimer);
// Sorting the array.
Arrays.sort(_indexToTimerPair);
//if(_indexToTimer[0] != 0)
// if(_indexToTimer[0] != -1)
// // Add the zeroth timer.
// int[] newIndexToTimer = new int[_indexToTimer.length+1];
// for(int i=0; i<_indexToTimer.length; i++)
// newIndexToTimer[i+1] = _indexToTimer[i];
// _indexToTimer = newIndexToTimer;
// _indexToTimer[0] = -1;
if(_indexToTimerPair[0].get_transitionIndex() != -1){
// Add the zeroth timer.
LPNTransitionPair[] newIndexToTimerPair =
new LPNTransitionPair[_indexToTimerPair.length];
for(int i=0; i<_indexToTimerPair.length; i++){
newIndexToTimerPair[i+1] = _indexToTimerPair[i];
}
_indexToTimerPair = newIndexToTimerPair;
// _indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1, true);
_indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1);
}
// if(_indexToTimer[0] < 0)
// // Add a zero timer.
// else if(_indexToTimer[0] > 0)
// int[] newTimerIndex = new int[_indexToTimer.length+1];
// for(int i=0; i<_indexToTimer.length; i++)
// newTimerIndex[i+1] = _indexToTimer[i];
// Map the old index of the timer to the new index of the timer.
HashMap<Integer, Integer> newIndex = new HashMap<Integer, Integer>();
// For the old index, find the new index.
for(int i=0; i<timers.length; i++)
{
// Since the zeroth timer is not included in the timers passed
// to the index in the DBM is 1 more than the index of the timer
// in the timers array.
//newIndex.put(i+1, Arrays.binarySearch(_indexToTimer, timers[i]));
// LPNTransitionPair searchValue =
// new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i], true);
LPNTransitionPair searchValue =
new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);
newIndex.put(i+1, Arrays.binarySearch(_indexToTimerPair, searchValue));
}
// Add the zero timer index.
newIndex.put(0, 0);
// Initialize the matrix.
_matrix = new int[matrixSize()][matrixSize()];
// Copy the DBM
for(int i=0; i<dbmSize(); i++)
{
for(int j=0; j<dbmSize(); j++)
{
// Copy the passed in matrix to _matrix.
setDbmEntry(newIndex.get(i), newIndex.get(j),
matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]);
// In the above, changed setDBMIndex to setdbm
}
}
// Copy in the upper and lower bounds. The zero time does not have an upper or lower bound
// so the index starts at i=1, the first non-zero timer.
for(int i=1; i< dbmSize(); i++)
{
setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]);
// Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound
// and the matrix stores the negative of the lower bound. So the matrix value
// must be multiplied by -1.
setLowerBoundbydbmIndex(newIndex.get(i), -1*matrix[dbmIndexToMatrixIndex(i)][0]);
}
recononicalize();
}
/**
* Initializes a zone according to the markings of state.
* @param currentState
* The zone is initialized as if all enabled timers
* have just been enabled.
*/
public Zone(State initialState)
{
// Extract the associated LPN.
LhpnFile lpn = initialState.getLpn();
int LPNIndex = lpn.getLpnIndex();
if(_lpnList == null){
// If no LPN exists yet, create it and put lpn in it.
_lpnList = new LhpnFile[LPNIndex+1];
_lpnList[LPNIndex] = lpn;
}
else if(_lpnList.length <= LPNIndex){
// The list does not contain the lpn.
LhpnFile[] tmpList = _lpnList;
_lpnList = new LhpnFile[LPNIndex+1];
_lpnList[LPNIndex] = lpn;
// Copy any that exist already.
for(int i=0; i<_lpnList.length; i++){
_lpnList[i] = tmpList[i];
}
}
else if(_lpnList[LPNIndex] != lpn){
// This checks that the appropriate lpn is in the right spot.
// If not (which gets you in this block), then this fixes it.
_lpnList[LPNIndex] = lpn;
}
// Default value for the hash code indicating that the hash code has not
// been set yet.
_hashCode = -1;
// Get the list of currently enabled Transitions by their index.
boolean[] enabledTran = initialState.getTranVector();
ArrayList<LPNTransitionPair> enabledTransitionsArrayList =
new ArrayList<LPNTransitionPair>();
// LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1);
LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER,
LPNTransitionPair.ZERO_TIMER);
// Add the zero timer first.
enabledTransitionsArrayList.add(zeroPair);
// The index of the boolean value corresponds to the index of the Transition.
for(int i=0; i<enabledTran.length; i++){
if(enabledTran[i]){
enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i));
}
}
_indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);
_matrix = new int[matrixSize()][matrixSize()];
for(int i=1; i<dbmSize(); i++)
{
// Get the name for the timer in the i-th column/row of DBM
String tranName =
lpn.getTransition(_indexToTimerPair[i].get_transitionIndex()).getLabel();
ExprTree delay = lpn.getDelayTree(tranName);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
lpn.getAllVarsWithValuesAsString(initialState.getVariableVector());
// Set the upper and lower bound.
int upper, lower;
if(delay.getOp().equals("uniform"))
{
ExprTree lowerDelay = delay.getLeftChild();
ExprTree upperDelay = delay.getRightChild();
lower = (int) lowerDelay.evaluateExpr(varValues);
upper = (int) upperDelay.evaluateExpr(varValues);
}
else
{
lower = (int) delay.evaluateExpr(varValues);
upper = lower;
}
setLowerBoundbydbmIndex(i, lower);
setUpperBoundbydbmIndex(i, upper);
}
// Advance the time and tighten the bounds.
advance();
recononicalize();
checkZoneMaxSize();
}
/**
* Creates a Zone based on the local states.
* @param localStates
* The current state (or initial) of the LPNs.
*/
public Zone(State[] localStates){
// Open the log file.
if(_writeLogFile == null && Options.get_TimingLogfile() != null){
try{
_writeLogFile =
new BufferedWriter(
new FileWriter(Options.get_TimingLogfile()));
} catch (IOException e) {
e.printStackTrace();
}finally{
}
}
// Initialize hash code to -1 (indicating nothing cached).
_hashCode = -1;
// Initialize the LPN list.
initialize_lpnList(localStates);
// Get the enabled transitions. This initializes the _indexTotimerPair
// which stores the relevant information.
// This method will also initialize the _rateZeroContinuous
initialize_indexToTimerPair(localStates);
// Initialize the matrix.
_matrix = new int[matrixSize()][matrixSize()];
// Set the lower bound/ upper bounds of the timers and the rates.
initializeLowerUpperBounds(getAllNames(), localStates);
// Initialize the row and column entries for the continuous variables.
initializeRowColumnContVar();
// Create a previous zone to the initial zone for the sake of warping.
Zone tmpZone = beforeInitialZone();
dbmWarp(tmpZone);
recononicalize();
// Advance Time
//advance();
advance(localStates);
// Re-canonicalize
recononicalize();
// Check the size of the DBM.
checkZoneMaxSize();
}
/**
* Creates a Zone based on the local states.
* @param localStates
* The current state (or initial) of the LPNs.
*/
public Zone(State[] localStates, boolean init){
// Extract the local states.
//State[] localStates = tps.toStateArray();
// Initialize hash code to -1 (indicating nothing cached).
_hashCode = -1;
// Initialize the LPN list.
initialize_lpnList(localStates);
// Get the enabled transitions. This initializes the _indexTotimerPair
// which stores the relevant information.
// This method will also initialize the _rateZeroContinuous
initialize_indexToTimerPair(localStates);
// Initialize the matrix.
_matrix = new int[matrixSize()][matrixSize()];
// Set the lower bound/ upper bounds of the timers and the rates.
initializeLowerUpperBounds(getAllNames(), localStates);
// Initialize the row and column entries for the continuous variables.
initializeRowColumnContVar();
if(init){
return;
}
// Advance Time
//advance();
advance(localStates);
// Re-canonicalize
recononicalize();
// Check the size of the DBM.
checkZoneMaxSize();
}
// /**
// * Sets ups a zone containing continuous variables only.
// * @param continuousValues
// * The values to populate the zone with.
// */
// public Zone(HashMap<LPNContinuousPair, IntervalPair> continuousValues){
// Set<LPNContinuousPair> pairSet = continuousValues.keySet();
// // Copy the LPNContinuousPairs over
// _indexToTimerPair = new LPNTransitionPair[pairSet.size()+1];
// int count = 0; // The position in the _indexToTimerPair for the next value.
// _indexToTimerPair[count++] = LPNTransitionPair.ZERO_TIMER_PAIR;
// for(LPNContinuousPair lcPair: pairSet){
// _indexToTimerPair[count++] = lcPair;
// Arrays.sort(_indexToTimerPair);
// _matrix = new int[matrixSize()][matrixSize()];
// for(int i=1; i<dbmSize(); i++){
// setDbmEntry(i, j, value)
/**
* Gives the names of all the transitions and continuous variables that
* are represented by the zone.
* @return
* The names of the transitions and continuous variables that are
* represented by the zone.
*/
public String[] getAllNames(){
// String[] transitionNames = new String[_indexToTimerPair.length];
// transitionNames[0] = "The zero timer.";
// for(int i=1; i<transitionNames.length; i++){
// LPNTransitionPair ltPair = _indexToTimerPair[i];
// transitionNames[i] = _lpnList[ltPair.get_lpnIndex()]
// .getTransition(ltPair.get_transitionIndex()).getName();
// return transitionNames;
// Get the continuous variable names.
String[] contVar = getContVarNames();
// Get the transition names.
String[] trans = getTranNames();
// Create an array large enough for all the names.
String[] names = new String[contVar.length + trans.length + 1];
// Add the zero timer.
names[0] = "The zero timer.";
// Add the continuous variables.
for(int i=0; i<contVar.length; i++){
names[i+1] = contVar[i];
}
// Add the timers.
for(int i=0; i<trans.length; i++){
// Already the zero timer has been added and the elements of contVar.
// That's a total of 'contVar.length + 1' elements. The last index was
// thus 'contVar.length' So the first index to add to is
// 'contVar.length +1'.
names[1+contVar.length + i] = trans[i];
}
return names;
}
/**
* Get the names of the continuous variables that this zone uses.
* @return
* The names of the continuous variables that are part of this zone.
*/
public String[] getContVarNames(){
// List for accumulating the names.
ArrayList<String> contNames = new ArrayList<String>();
// Find the pairs that represent the continuous variables. Loop starts at
// i=1 since the i=0 is the zero timer.
for(int i=1; i<_indexToTimerPair.length; i++){
LPNTransitionPair ltPair = _indexToTimerPair[i];
// If the isTimer value is false, then this pair represents a continuous
// variable.
//if(!ltPair.get_isTimer()){
// If pair is LPNContinuousPair.
if(ltPair instanceof LPNContinuousPair){
// Get the LPN that this pairing references and find the name of
// the continuous variable whose index is given by this pairing.
contNames.add(_lpnList[ltPair.get_lpnIndex()]
.getContVarName(ltPair.get_transitionIndex()));
}
}
return contNames.toArray(new String[0]);
}
/**
* Gets the names of the transitions that are associated with the timers in the
* zone. Does not return the zero timer.
* @return
* The names of the transitions whose timers are in the zone except the zero
* timer.
*/
public String[] getTranNames(){
// List for accumulating the names.
ArrayList<String> transitionNames = new ArrayList<String>();
// Find the pairs that represent the transition timers.
for(int i=1; i<_indexToTimerPair.length; i++){
LPNTransitionPair ltPair = _indexToTimerPair[i];
// If the isTimer value is true, then this pair represents a timer.
//if(ltPair.get_isTimer()){
// If this is an LPNTransitionPair and not an LPNContinuousPair
if(!(ltPair instanceof LPNContinuousPair)){
// Get the LPN that this pairing references and find the name of the
// transition whose index is given by this pairing.
transitionNames.add(_lpnList[ltPair.get_lpnIndex()]
.getTransition(ltPair.get_transitionIndex()).getLabel());
}
}
return transitionNames.toArray(new String[0]);
}
/**
* Initializes the _lpnList using information from the local states.
* @param localStates
* The local states.
* @return
* The enabled transitions.
*/
private void initialize_lpnList(State[] localStates){
// Create the LPN list.
_lpnList = new LhpnFile[localStates.length];
// Get the LPNs.
for(int i=0; i<localStates.length; i++){
_lpnList[i] = localStates[i].getLpn();
}
}
/**
* Initializes the _indexToTimerPair from the local states. This includes
* adding the zero timer, the continuous variables and the set of
* enabled timers.
* @param localStates
* The local states.
* @return
* The names of the transitions stored in the _indexToTimerPair (in the same order).
*/
private void initialize_indexToTimerPair(State[] localStates){
/*
* The populating of the _indexToTimerPair is done in three stages.
* The first is to add the zero timer which is at the beginning of the zone.
* The second is to add the continuous variables. And the third is to add
* the other timers. Since the continuous variables are added before the
* timers and the variables and timers are added in the order of the LPNs,
* the elements in an accumulating list (enabledTransitionsArrayList) are
* already in order up to the elements added for a particular LPN. Thus the
* only sorting that needs to take place is the sorting for a particular LPN.
* Correspondingly, elements are first found for an LPN and sort, then added
* to the main list.
*/
// This method will also initialize the _rateZeroContinuous
_rateZeroContinuous =
new DualHashMap<LPNContAndRate, VariableRangePair>();
// This list accumulates the transition pairs (ie timers) and the continuous
// variables.
ArrayList<LPNTransitionPair> enabledTransitionsArrayList =
new ArrayList<LPNTransitionPair>();
// Put in the zero timer.
// enabledTransitionsArrayList
// .add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1));
enabledTransitionsArrayList
.add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER,
LPNTransitionPair.ZERO_TIMER));
// Get the continuous variables.
for(int i=0; i<localStates.length; i++){
// Accumulates the changing continuous variables for a single LPN.
ArrayList<LPNTransitionPair> singleLPN =
new ArrayList<LPNTransitionPair>();
// Get the associated LPN.
LhpnFile lpn = localStates[i].getLpn();
// Get the continuous variables for this LPN.
String[] continuousVariables = lpn.getContVars();
// Get the variable, index map.
DualHashMap<String, Integer> variableIndex = lpn.getContinuousIndexMap();
// Find which have a nonzero rate.
for(int j=0; j<continuousVariables.length; j++){
// Get the Variables with this name.
Variable contVar = lpn.getVariable(continuousVariables[j]);
// Get the rate.
//int rate = (int) Double.parseDouble(contVar.getInitRate());
IntervalPair rate = parseRate(contVar.getInitRate());
// Get the LPN index for the variable
int lpnIndex = lpn.getLpnIndex();
// Get the index as a variable for the LPN.
int contVariableIndex = variableIndex.get(continuousVariables[j]);
// LPNTransitionPair newPair =
// new LPNTransitionPair(lpnIndex, contVariableIndex, false);
LPNContinuousPair newPair =
new LPNContinuousPair(lpnIndex, contVariableIndex,
rate.getSmallestRate());
// If the rate is non-zero, then the variables needs to be tracked
// by matrix part of the Zone.
// if(!rate.equals(new IntervalPair(0,0))){
if(newPair.getCurrentRate() != 0){
// Temporary exception guaranteeing only unit rates.
//if(rate != -1 && rate != 1){
// if(rate.get_LowerBound() != 1 && rate.get_UpperBound() != 1){
// "only supports positive unit rates. The variable " + contVar +
// " has a rate of " + rate);
// // Get the LPN index for the variable
// int lpnIndex = lpn.getLpnIndex();
// // Get the index as a variable for the LPN. This index matches
// // the index in the vector stored by platu.State.
// int contVariableIndex = variableIndex.get(continuousVariables[j]);
// The continuous variable reference.
// singleLPN.add(
// new LPNTransitionPair(lpnIndex, contVariableIndex, false));
singleLPN.add(newPair);
}
else{
// If the rate is zero, then the Zone keeps track of this variable
// in a list.
// _rateZeroContinuous.
// put(newPair, new VariableRangePair(contVar,
// parseRate(contVar.getInitValue())));
_rateZeroContinuous.
insert(new LPNContAndRate(newPair, rate),
new VariableRangePair(contVar,
parseRate(contVar.getInitValue())));
}
}
// Sort the list.
Collections.sort(singleLPN);
// Add the list to the total accumulating list.
for(int j=0; j<singleLPN.size(); j++){
enabledTransitionsArrayList.add(singleLPN.get(j));
}
}
// Get the transitions.
for(int i=0; i<localStates.length; i++){
// Extract the enabled transition vector.
boolean[] enabledTran = localStates[i].getTranVector();
// Accumulates the transition pairs for one LPN.
ArrayList<LPNTransitionPair> singleLPN = new ArrayList<LPNTransitionPair>();
// The index of the boolean value corresponds to the index of the Transition.
for(int j=0; j<enabledTran.length; j++){
if(enabledTran[j]){
// Add the transition pair.
// singleLPN.add(new LPNTransitionPair(i, j, true));
singleLPN.add(new LPNTransitionPair(i, j));
}
}
// Sort the transitions for the current LPN.
Collections.sort(singleLPN);
// Add the collection to the enabledTransitionsArrayList
for(int j=0; j<singleLPN.size(); j++){
enabledTransitionsArrayList.add(singleLPN.get(j));
}
}
// Extract out the array portion of the enabledTransitionsArrayList.
_indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);
}
/**
* Sets the lower and upper bounds for the transitions and continuous variables.
* @param varNames
* The names of the transitions in _indexToTimerPair.
*/
private void initializeLowerUpperBounds(String[] varNames, State[] localStates){
// Traverse the entire length of the DBM sub-matrix except the zero row/column.
// This is the same length as the _indexToTimerPair.length-1. The DBM is used to
// match the idea of setting the value for each row.
for(int i=1; i<dbmSize(); i++){
// Get the current LPN and transition pairing.
LPNTransitionPair ltPair = _indexToTimerPair[i];
//int upper, lower;
IntervalPair range;
// if(!ltPair.get_isTimer()){
if(ltPair instanceof LPNContinuousPair){
// If the pairing represents a continuous variable, then the
// upper and lower bound are the initial value or infinity depending
// on whether the initial rate is positive or negative.
// If the value is a constant, then assign the upper and lower bounds
// to be constant. If the value is a range then assign the upper and
// lower bounds to be a range.
Variable v = _lpnList[ltPair.get_lpnIndex()]
.getContVar(ltPair.get_transitionIndex());
// int initialRate = (int) Double.parseDouble(v.getInitRate());
// upper = initialRate;
// lower = initialRate;
String rate = v.getInitRate();
// Parse the rate. Should be in the form of [x,y] where x
// and y are integers.
//IntervalPair range = parseRate(rate);
range = parseRate(rate);
// Set the upper and lower bound (in the matrix) for the
// continuous variables.
// TODO : Check if correct.
String contValue = v.getInitValue();
IntervalPair bound = parseRate(contValue);
// Set upper bound (DBM entry (0, x) where x is the index of the variable v).
setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, bound.get_UpperBound());
// Set lower bound (DBM entry (x, 0) where x is the index of the variable v).
setDbmEntryByPair(ltPair, LPNTransitionPair.ZERO_TIMER_PAIR, -1*bound.get_LowerBound());
// lower = range.get_LowerBound();
// upper = range.get_UpperBound();
}
else{
// Get the expression tree.
ExprTree delay = _lpnList[ltPair.get_lpnIndex()].getDelayTree(varNames[i]);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
_lpnList[ltPair.get_lpnIndex()]
.getAllVarsWithValuesAsString(localStates[ltPair.get_lpnIndex()].getVariableVector());
// Set the upper and lower bound.
// Passing the zone as null since it should not be needed.
// if(delay.getOp().equals("uniform")){
// IntervalPair lowerRange = delay.getLeftChild()
// .evaluateExprBound(varValues, null);
// IntervalPair upperRange = delay.getRightChild()
// .evaluateExprBound(varValues, null);
// // The lower and upper bounds should evaluate to a single
// // value. Yell if they don't.
// if(!lowerRange.singleValue() || !upperRange.singleValue()){
// "the lower or the upper bound evaluated to a range " +
// "instead of a single value.");
// range = new IntervalPair(lowerRange.get_LowerBound(),
// upperRange.get_UpperBound());
// else{
// range = delay.evaluateExprBound(varValues, null);
range = delay.evaluateExprBound(varValues, this, null);
// int upper, lower;
// if(delay.getOp().equals("uniform"))
// ExprTree lowerDelay = delay.getLeftChild();
// ExprTree upperDelay = delay.getRightChild();
// lower = (int) lowerDelay.evaluateExpr(varValues);
// upper = (int) upperDelay.evaluateExpr(varValues);
// else
// lower = (int) delay.evaluateExpr(varValues);
// upper = lower;
}
// setLowerBoundbydbmIndex(i, lower);
// setUpperBoundbydbmIndex(i, upper);
setLowerBoundbydbmIndex(i, range.get_LowerBound());
setUpperBoundbydbmIndex(i, range.get_UpperBound());
}
}
/**
* Initialize the rows and columns for the continuous variables.
*/
private void initializeRowColumnContVar(){
/*
* TODO : Describe the idea behind the following algorithm.
*/
// for(int row=2; row<_indexToTimerPair.length; row++){
// // Note: row is indexing the row of the DBM matrix.
// LPNTransitionPair ltRowPair = _indexToTimerPair[row];
// if(ltRowPair.get_isTimer()){
// // If we reached the timers, stop.
// break;
// for(int col=1; col<row; col++){
// // Note: col is indexing the column of the DBM matrix.
// // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since
// // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower
// // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);
// int rowCol = getDbmEntry(row,0) + getDbmEntry(0, col);
// // The new (col, row) entry.
// int colRow = getDbmEntry(col, 0) + getDbmEntry(0, row);
// setDbmEntry(row, col, rowCol);
// setDbmEntry(col, row, colRow);
// The only entries that do not need to be checked are the ones where both variables
// represent timers.
for(int row=2; row<_indexToTimerPair.length; row++){
// Note: row is indexing the row of the DBM matrix.
LPNTransitionPair ltRowPair = _indexToTimerPair[row];
// if(ltRowPair.get_isTimer()){
// // If we reached the timers, stop.
// break;
for(int col=1; col<row; col++){
// Note: col is indexing the column of the DBM matrix.
LPNTransitionPair ltColPair = _indexToTimerPair[col];
// If we've reached the part of the zone involving only timers, then break out
// of this row.
// if(ltRowPair.get_isTimer() && ltColPair.get_isTimer()){
if(!(ltRowPair instanceof LPNContinuousPair) &&
!(ltColPair instanceof LPNContinuousPair)){
break;
}
// The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since
// col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower
// bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);
int rowCol = getDbmEntry(row,0) + getDbmEntry(0, col);
// The new (col, row) entry.
int colRow = getDbmEntry(col, 0) + getDbmEntry(0, row);
setDbmEntry(row, col, rowCol);
setDbmEntry(col, row, colRow);
}
}
}
/**
* Zero argument constructor for use in methods that create Zones where the members
* variables will be set by the method.
*/
private Zone()
{
_matrix = new int[0][0];
_indexToTimerPair = new LPNTransitionPair[0];
_hashCode = -1;
_lpnList = new LhpnFile[0];
_rateZeroContinuous = new DualHashMap<LPNContAndRate, VariableRangePair>();
}
/**
* Gets the upper bound of a Transition from the zone.
* @param t
* The transition whose upper bound is wanted.
* @return
* The upper bound of Transition t.
*/
public int getUpperBoundbyTransition(Transition t)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair =
// new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair =
new LPNTransitionPair(lpnIndex, transitionIndex);
return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));
}
/**
* Returns the upper bound of the continuous variable.
* @param var
* The variable of interest.
* @return
* The (0,var) entry of the zone, that is the maximum as recored by
* the zone.
*/
public int getUpperBoundbyContinuousVariable(String contVar, LhpnFile lpn){
// TODO : Finish.
// // Determine whether the variable is in the zone or rate zero.
// RangeAndPairing indexAndRange = _rateZeroContinuous.getKey(var);
// // If a RangeAndPairing is returned, then get the information from here.
// if(indexAndRange != null){
// return indexAndRange.get_range().get_UpperBound();
// // If indexAndRange is null, then try to get the value from the zone.
// int i=-1;
// for(i=0; i<_indexToTimerPair.length; i++){
// if(_indexToTimerPair[i].equals(var)){
// break;
// if(i < 0){
// + "a non-rate zero continuous variable that was not found in the "
// + "zone.");
// return getUpperBoundbydbmIndex(i);
// Extract the necessary indecies.
int lpnIndex = lpn.getLpnIndex();
//int contVarIndex = lpn.get
DualHashMap<String, Integer> variableIndecies = lpn.getContinuousIndexMap();
int contIndex = variableIndecies.get(contVar);
// Package the indecies with false indicating not a timer.
// LPNTransitionPair index = new LPNTransitionPair(lpnIndex, contIndex, false);
// Note : setting the rate is not necessary here since this is only
// being used as an index.
// LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex, 0);
LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);
//Search for the continuous variable in the rate zero variables.
VariableRangePair pairing = _rateZeroContinuous.get(index);
// If Pairing is not null, the variable was found and return the result.
if(pairing != null){
return pairing.get_range().get_UpperBound();
}
// If Pairing was null, the variable was not found. Search for the variable
// in the zone portion.
int i = Arrays.binarySearch(_indexToTimerPair, index);
// If i < 0, the search was unsuccessful, so scream.
if(i < 0){
throw new IllegalArgumentException("Atempted to find the lower bound for "
+ "a non-rate zero continuous variable that was not found in the "
+ "zone.");
}
//return getUpperBoundbydbmIndex(i);
return getDbmEntry(0, i);
}
public int getUpperBoundForRate(LPNTransitionPair contVar){
// TODO : finish.
// Check if the contVar is in the zone.
int i = Arrays.binarySearch(_indexToTimerPair, contVar);
if(i > 0){
// The continuous variable is in the zone.
// The upper and lower bounds are stored in the same
// place as the delays, so the same method of
// retrieval will work.
//return getUpperBoundbydbmIndex(contVar.get_transitionIndex());
// Grab the current rate from the LPNContinuousPair.
return ((LPNContinuousPair)_indexToTimerPair[i]).getCurrentRate();
}
// Assume the rate is zero. This covers the case if conVar
// is in the rate zero as well as if its not in the state at all.
return 0;
}
/**
* Get the value of the upper bound for the delay. If the index refers
* to a timer, otherwise get the upper bound for the continuous
* variables rate.
* @param index
* The timer's row/column of the DBM matrix.
* @return
* The upper bound on the transitions delay.
*/
public int getUpperBoundbydbmIndex(int index)
{
return _matrix[0][dbmIndexToMatrixIndex(index)];
}
/**
* Set the value of the upper bound for the delay.
* @param t
* The transition whose upper bound is being set.
* @param value
* The value of the upper bound.
*/
public void setUpperBoundbyTransition(Transition t, int value)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);
}
/**
* Set the value of the upper bound for the delay.
* @param index
* The timer's row/column of the DBM matrix.
* @param value
* The value of the upper bound.
*/
public void setUpperBoundbydbmIndex(int index, int value)
{
_matrix[0][dbmIndexToMatrixIndex(index)] = value;
}
/**
* Sets the upper bound for a transition described by an LPNTransitionPair.
* @param ltPair
* The index of the transition and the index of the associated LPN for
* the timer to set the upper bound.
* @param value
* The value for setting the upper bound.
*/
private void setUpperBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value){
setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);
}
/**
* Gets the lower bound of a Transition from the zone.
* @param t
* The transition whose upper bound is wanted.
* @return
* The lower bound of Transition t.
*/
public int getLowerBoundbyTransition(Transition t)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
return -1*getLowerBoundbydbmIndex(
Arrays.binarySearch(_indexToTimerPair, ltPair));
}
/**
* Returns the lower bound of the continuous variable.
* @param var
* The variable of interest.
* @return
* The (0,var) entry of the zone, that is the minimum as recored by
* the zone.
*/
public int getLowerBoundbyContinuousVariable(String contVar, LhpnFile lpn){
// Extract the necessary indecies.
int lpnIndex = lpn.getLpnIndex();
//int contVarIndex = lpn.get
DualHashMap<String, Integer> variableIndecies = lpn.getContinuousIndexMap();
int contIndex = variableIndecies.get(contVar);
// Package the indecies with false indicating not a timer.
// LPNTransitionPair index = new LPNTransitionPair(lpnIndex, contIndex, false);
// Note: Setting the rate is not necessary since this is only being used
// as an index.
// LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex, 0);
LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);
//Search for the continuous variable in the rate zero variables.
VariableRangePair pairing = _rateZeroContinuous.get(index);
// If Pairing is not null, the variable was found and return the result.
if(pairing != null){
return pairing.get_range().get_LowerBound();
}
// If Pairing was null, the variable was not found. Search for the variable
// in the zone portion.
int i = Arrays.binarySearch(_indexToTimerPair, index);
// If i < 0, the search was unsuccessful, so scream.
if(i < 0){
throw new IllegalArgumentException("Atempted to find the lower bound for "
+ "a non-rate zero continuous variable that was not found in the "
+ "zone.");
}
//return getLowerBoundbydbmIndex(i);
return getDbmEntry(i, 0);
}
/**
* Get the value of the lower bound for the delay if the index refers
* to a timer, otherwise get the lower bound for the continuous variables
* rate.
* @param index
* The timer's row/column of the DBM matrix.
* @return
* The value of the lower bound.
*/
public int getLowerBoundbydbmIndex(int index)
{
return _matrix[dbmIndexToMatrixIndex(index)][0];
}
public int getLowerBoundForRate(LPNTransitionPair contVar){
// TODO : finish.
// Check if the contVar is in the zone.
int i = Arrays.binarySearch(_indexToTimerPair, contVar);
if(i > 0){
// The continuous variable is in the zone.
// The upper and lower bounds are stored in the same
// place as the delays, so the same method of
// retrieval will work.
return getLowerBoundbydbmIndex(contVar.get_transitionIndex());
}
// Assume the rate is zero. This covers the case if conVar
// is in the rate zero as well as if its not in the state at all.
return 0;
}
/**
* Set the value of the lower bound for the delay.
* @param t
* The transition whose lower bound is being set.
* @param value
* The value of the lower bound.
*/
public void setLowerBoundbyTransition(Transition t, int value)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair,ltPair), value);
}
/**
* Set the value of the lower bound for the delay.
* @param t
* The transition whose upper bound is being set.
* @param value
* The value of the upper bound.
*/
private void setLowerBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value){
setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair,ltPair), value);
}
/**
* Set the value of the lower bound for the delay.
* @param index
* The timer's row/column of the DBM matrix.
* @param value
* The value of the lower bound.
*/
public void setLowerBoundbydbmIndex(int index, int value)
{
_matrix[dbmIndexToMatrixIndex(index)][0] = -1*value;
}
/**
* Give the upper and lower bounds for a continuous variable.
* @param contVar
* The variable of interest.
* @return
* The upper and lower bounds according to the Zone.
*/
public IntervalPair getContinuousBounds(String contVar, LhpnFile lpn){
/*
* Need to determine whether this is suppose to be a rate zero variable or a non-zero
* rate variable. One method is to check the rate of the passed variable. The other is
* to just check if the variable is present in either place.
*/
// Extract the necessary indecies.
int lpnIndex = lpn.getLpnIndex();
// Get the index of the continuous variable.
DualHashMap<String, Integer> variableIndecies = lpn.getContinuousIndexMap();
int contIndex = variableIndecies.get(contVar);
// Package the indecies with false indicating not a timer.
// LPNTransitionPair index = new LPNTransitionPair(lpnIndex, contIndex, false);
// Note: setting the current rate is not necessary here since the
// LPNContinuousPair is only being used as an index.
// LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex, 0);
LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);
// Search for the continuous variable in the rate zero variables.
VariableRangePair pairing = _rateZeroContinuous
.get(new LPNContAndRate(index, new IntervalPair(0,0)));
// If Pairing is not null, the variable was found and return the result.
if(pairing != null){
return pairing.get_range();
}
// If Pairing was null, the variable was not found. Search for the variable
// in the zone portion.
int i = Arrays.binarySearch(_indexToTimerPair, index);
// If i < 0, the search was unsuccessful, so scream.
if(i < 0){
throw new IllegalArgumentException("Atempted to find the bounds for "
+ "a non-rate zero continuous variable that was not found in the "
+ "zone.");
}
// Else find the upper and lower bounds.
// int lower = getLowerBoundbydbmIndex(i);
// int upper = getUpperBoundbydbmIndex(i);
int lower = (-1)*getDbmEntry(i, 0);
int upper = getDbmEntry(0, i);
return new IntervalPair(lower, upper);
}
/**
* Gets the range for the continuous variable. Values come back not
* warped.
* @param ltContPair
* The index of the variable of interest.
* @return
* The range of the continuous variable described by ltContPair.
*/
public IntervalPair getContinuousBounds(LPNContinuousPair ltContPair){
// First check in the zone.
int variableIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);
if(variableIndex < 0){
// The variable was not found in the zone. Check to see if its
// in the rate-zero varaibles. Technically I will return whatever
// is in the _rateZeroConintuous, null or not.
// return _rateZeroContinuous.get(ltContPair).get_range();
// First get an object to reference into the _rateZeroContinuous
LPNContAndRate lcr = new LPNContAndRate(ltContPair,
new IntervalPair(0,0));
return _rateZeroContinuous.get(lcr).get_range();
}
// The varaible was found in the zone. Yay.
int lower = (-1)*getDbmEntry(variableIndex, 0)
*getCurrentRate(ltContPair);
int upper = getDbmEntry(0, variableIndex)
*getCurrentRate(ltContPair);
return new IntervalPair(lower, upper);
}
/**
* Gets the range of the rate associated with a continuous variable.
* @param ltContPair
* The index of the continuous variable.
* @return
* The range of rates associated with the continuous variable indexed
* by ltContPair.
*/
public IntervalPair getRateBounds(LPNTransitionPair ltPair){
int upper;
int lower;
// Check if the ltContpair is in the zone.
int i = Arrays.binarySearch(_indexToTimerPair, ltPair);
if(i < 0){
// Then the variable is in the rate zero continuous
// variables so get the range of rates from there.
// return new IntervalPair(0,0);
// Create an object to reference into the rate zero.
LPNContAndRate lcr =
new LPNContAndRate((LPNContinuousPair) ltPair,
new IntervalPair(0,0));
// Get the old version of lcr from the rate zero since
// that contains the rate. This is quite a hack.
VariableRangePair vrp = _rateZeroContinuous.get(lcr);
lcr = _rateZeroContinuous.getKey(vrp);
return lcr.get_rateInterval();
}
upper = getUpperBoundbydbmIndex(i);
lower = -1*getLowerBoundbydbmIndex(i);
// The continuous variable is in the zone.
// The upper and lower bounds are stored in the same
// place as the delays, so the same method of
// retrieval will work.
return new IntervalPair(lower, upper);
}
/**
* Gets the lowest rate in absolute value.
* @param ltPair
* @return
*/
public int getSmallestRate(LPNTransitionPair ltPair){
int upper;
int lower;
// Check if the ltContpair is in the zone.
int i = Arrays.binarySearch(_indexToTimerPair, ltPair);
if(i < 0){
// Assume the rate is zero. This covers the case if conVar
// is in the rate zero as well as if its not in the state at all.
return 0;
}
upper = getUpperBoundbydbmIndex(i);
lower = -1*getLowerBoundbydbmIndex(i);
// If zero is a possible rate, then it is the rate to set to.
if( lower < 0 && upper > 0){
return 0;
}
// When zero is not present, use the smallest rate in absolute value.
return Math.abs(lower)<Math.abs(upper) ?
lower: upper;
}
/**
* Gets the lowerest rate in absolute value.
* @param dbmIndex
* @return
*/
public int getSmallestRate(int dbmIndex){
int lower = -1*getLowerBoundbydbmIndex(dbmIndex);
int upper = getUpperBoundbydbmIndex(dbmIndex);
if(lower < 0 && upper > 0){
return 0;
}
return Math.abs(lower)<= Math.abs(upper) ? lower : upper;
}
/**
* Sets the bounds for a continuous variable.
* @param contVar
* The continuous variable to set the bounds on.
* @param lpn
* The LhpnFile object that contains the variable.
* @param range
* The new range of the continuous variable.
*/
public void setContinuousBounds(String contVar, LhpnFile lpn,
IntervalPair range){
// Extract the necessary indecies.
int lpnIndex = lpn.getLpnIndex();
// Get the index of the continuous variable.
DualHashMap<String, Integer> variableIndecies = lpn.getContinuousIndexMap();
int contIndex = variableIndecies.get(contVar);
// Package the indecies with false indicating not a timer.
// LPNTransitionPair index = new LPNTransitionPair(lpnIndex, contIndex, false);
//Note : Setting the rate is not necessary since this only being used
// as an index.
// LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex, 0);
LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex);
// Search for the continuous variable in the rate zero variables.
VariableRangePair pairing = _rateZeroContinuous.get(index);
// If Pairing is not null, the variable was found and make the new assignment.
if(pairing != null){
pairing.set_range(range);
return;
}
// If Pairing was null, the variable was not found. Search for the variable
// in the zone portion.
int i = Arrays.binarySearch(_indexToTimerPair, index);
// If i < 0, the search was unsuccessful, so scream.
if(i < 0){
throw new IllegalArgumentException("Atempted to find the bounds for "
+ "a non-rate zero continuous variable that was not found in the "
+ "zone.");
}
// Else find the upper and lower bounds.
// setLowerBoundbydbmIndex(i, range.get_LowerBound());
// setUpperBoundbydbmIndex(i, range.get_UpperBound());
setDbmEntry(i, 0, (-1)*range.get_LowerBound());
setDbmEntry(0, i, range.get_UpperBound());
}
/**
* Converts the index of the DBM to the index of _matrix.
* @param i
* The row/column index of the DBM.
* @return
* The row/column index of _matrix.
*/
private int dbmIndexToMatrixIndex(int i)
{
return i+1;
}
/**
* Retrieves an entry of the DBM using the DBM's addressing.
* @param i
* The row of the DBM.
* @param j
* The column of the DBM.
* @return
* The value of the (i, j) element of the DBM.
*/
public int getDbmEntry(int i, int j)
{
return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)];
}
/**
* Retrieves an entry of the DBM using LPNTransitionPair indecies.
* @param iPair
* The LPNTransitionPair for the ith entry.
* @param jPair
* The LPNTransitionPair for the jth entry.
* @return
* The value of the (i,j) element of the DBM where i corresponds to the row
* for the variable iPair and j corresponds to the row for the variable jPair.
*/
public int getDbmEntryByPair(LPNTransitionPair iPair, LPNTransitionPair jPair){
int iIndex = Arrays.binarySearch(_indexToTimerPair, iPair);
int jIndex = Arrays.binarySearch(_indexToTimerPair, jPair);
return getDbmEntry(iIndex, jIndex);
}
/**
* Sets an entry of the DBM using the DBM's addressing.
* @param i
* The row of the DBM.
* @param j
* The column of the DBM.
* @param value
* The new value for the entry.
*/
private void setDbmEntry(int i, int j, int value)
{
_matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value;
}
/**
* Sets the entry in the DBM using the LPNTransitionPair indexing.
* @param row
* The LPNTransitionPair for the row.
* @param col
* The LPNTransitionPair for the column.
* @param value
* The value to set the entry to.
*/
private void setDbmEntryByPair(LPNTransitionPair row, LPNTransitionPair col, int value){
// The row index.
int i = timerIndexToDBMIndex(row);
// The column index.
int j = timerIndexToDBMIndex(col);
setDbmEntry(i, j, value);
}
/**
* Returns the index of the the transition in the DBM given a LPNTransitionPair pairing
* the transition index and associated LPN index.
* @param ltPair
* The pairing comprising the index of the transition and the index of the associated
* LPN.
* @return
* The row/column of the DBM associated with the ltPair.
*/
public int timerIndexToDBMIndex(LPNTransitionPair ltPair)
{
return Arrays.binarySearch(_indexToTimerPair, ltPair);
}
/**
* The matrix labeled with 'ti' where i is the transition index associated with the timer.
*/
public String toString()
{
// TODO : Fix the handling of continuous variables in the
// _lpnList == 0 case.
String result = "Timer and delay or continuous and ranges.\n";
int count = 0;
// Print the timers.
for(int i=1; i<_indexToTimerPair.length; i++, count++)
{
if(_lpnList.length == 0)
{
// If no LPN's are associated with this Zone, use the index of the timer.
result += " t" + _indexToTimerPair[i].get_transitionIndex() + " : ";
}
else
{
String name;
// If the current LPNTransitionPair is a timer, get the name
// from the transitions.
// if(_indexToTimerPair[i].get_isTimer()){
// If the current timer is an LPNTransitionPair and not an LPNContinuousPair
if(!(_indexToTimerPair[i] instanceof LPNContinuousPair)){
// Get the name of the transition.
Transition tran = _lpnList[_indexToTimerPair[i].get_lpnIndex()].
getTransition(_indexToTimerPair[i].get_transitionIndex());
name = tran.getLabel();
}
else{
// If the current LPNTransitionPair is not a timer, get the
// name as a continuous variable.
Variable var = _lpnList[_indexToTimerPair[i].get_lpnIndex()]
.getContVar(_indexToTimerPair[i].get_transitionIndex());
LPNContinuousPair lcPair =
(LPNContinuousPair) _indexToTimerPair[i];
name = var.getName() +
":[" + -1*getDbmEntry(i, 0)*lcPair.getCurrentRate() + ","
+ getDbmEntry(0, i)*lcPair.getCurrentRate() + "]\n" +
" Current Rate: " + lcPair.getCurrentRate() + " " +
"rate:";
}
// result += " " + tran.getName() + ":";
result += " " + name + ":";
}
result += "[ " + -1*getLowerBoundbydbmIndex(i) + ", " + getUpperBoundbydbmIndex(i) + " ]";
if(count > 9)
{
result += "\n";
count = 0;
}
}
if(!_rateZeroContinuous.isEmpty()){
result += "\nRate Zero Continuous : \n";
for (LPNContAndRate lcrPair : _rateZeroContinuous.keySet()){
result += "" + _rateZeroContinuous.get(lcrPair)
+ "Rate: " + lcrPair.get_rateInterval();
}
}
result += "\nDBM\n";
// Print the DBM.
for(int i=0; i<_indexToTimerPair.length; i++)
{
result += "| " + String.format("%3d", getDbmEntry(i, 0));
for(int j=1; j<_indexToTimerPair.length; j++)
{
result += ", " + String.format("%3d",getDbmEntry(i, j));
}
result += " |\n";
}
return result;
}
/**
* Tests for equality. Overrides inherited equals method.
* @return True if o is equal to this object, false otherwise.
*/
public boolean equals(Object o)
{
// Check if the reference is null.
if(o == null)
{
return false;
}
// Check that the type is correct.
if(!(o instanceof Zone))
{
return false;
}
// Check for equality using the Zone equality.
return equals((Zone) o);
}
/**
* Tests for equality.
* @param
* The Zone to compare.
* @return
* True if the zones are non-null and equal, false otherwise.
*/
public boolean equals(Zone otherZone)
{
// Check if the reference is null first.
if(otherZone == null)
{
return false;
}
// Check for reference equality.
if(this == otherZone)
{
return true;
}
// If the hash codes are different, then the objects are not equal.
if(this.hashCode() != otherZone.hashCode())
{
return false;
}
// Check if the they have the same number of timers.
if(this._indexToTimerPair.length != otherZone._indexToTimerPair.length){
return false;
}
// Check if the timers are the same.
for(int i=0; i<this._indexToTimerPair.length; i++){
if(!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))){
return false;
}
}
// Check if the matrix is the same
for(int i=0; i<_matrix.length; i++)
{
for(int j=0; j<_matrix[0].length; j++)
{
if(!(this._matrix[i][j] == otherZone._matrix[i][j]))
{
return false;
}
}
}
return true;
}
/**
* Determines if this zone is a subset of Zone otherZone.
* @param otherZone
* The zone to compare against.
* @return
* True if this is a subset of other; false otherwise.
*/
public boolean subset(Zone otherZone){
// Check if the reference is null first.
if(otherZone == null)
{
return false;
}
// Check for reference equality.
if(this == otherZone)
{
return true;
}
// Check if the the same number of timers are present.
if(this._indexToTimerPair.length != otherZone._indexToTimerPair.length){
return false;
}
// Check if the transitions are the same.
for(int i=0; i<this._indexToTimerPair.length; i++){
if(!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))){
return false;
}
}
// Check if the entries of this Zone are less than or equal to the entries
// of the other Zone.
for(int i=0; i<_matrix.length; i++)
{
for(int j=0; j<_matrix[0].length; j++)
{
if(!(this._matrix[i][j] <= otherZone._matrix[i][j])){
return false;
}
}
}
return true;
}
/**
* Determines if this zone is a superset of Zone otherZone.
* @param otherZone
* The zone to compare against.
* @return
* True if this is a subset of other; false otherwise. More specifically it
* gives the result of otherZone.subset(this). Thus it agrees with the subset method.
*/
public boolean superset(Zone otherZone){
return otherZone.subset(this);
}
/**
* Overrides the hashCode.
*/
public int hashCode()
{
// Check if the hash code has been set.
if(_hashCode <0)
{
_hashCode = createHashCode();
}
return _hashCode;
}
/**
* Creates a hash code for a Zone object.
* @return
* The hash code.
*/
private int createHashCode()
{
int newHashCode = Arrays.hashCode(_indexToTimerPair);
for(int i=0; i<_matrix.length; i++)
{
newHashCode ^= Arrays.hashCode(_matrix[i]);
}
return Math.abs(newHashCode);
}
/**
* The size of the DBM sub matrix. This is calculated using the size of _indexToTimer.
* @return
* The size of the DBM.
*/
private int dbmSize()
{
return _indexToTimerPair.length;
}
/**
* The size of the matrix.
* @return
* The size of the matrix. This is calculated using the size of _indexToTimer.
*/
private int matrixSize()
{
return _indexToTimerPair.length + 1;
}
/**
* Performs the Floyd's least pairs algorithm to reduce the DBM.
*/
public void recononicalize()
{
for(int k=0; k<dbmSize(); k++)
{
for (int i=0; i<dbmSize(); i++)
{
for(int j=0; j<dbmSize(); j++)
{
if(getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY
&& getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j))
{
setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j));
}
if( (i==j) && getDbmEntry(i, j) != 0)
{
throw new DiagonalNonZeroException("Entry (" + i + ", " + j + ")" +
" became " + getDbmEntry(i, j) + ".");
}
}
}
}
}
/**
* Determines if a timer associated with a given transitions has reached its lower bound.
* @param t
* The transition to consider.
* @return
* True if the timer has reached its lower bound, false otherwise.
*/
public boolean exceedsLowerBoundbyTransitionIndex(Transition t)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));
}
/**
* Determines if a timer has reached its lower bound.
* @param timer
* The timer's index.
* @return
* True if the timer has reached its lower bound, false otherwise.
*/
public boolean exceedsLowerBoundbydbmIndex(int index)
{
// Note : Make sure that the lower bound is stored as a negative number
// and that the inequality is correct.
return _matrix[0][dbmIndexToMatrixIndex(index)] <=
_matrix[1][dbmIndexToMatrixIndex(index)];
}
/* (non-Javadoc)
* @see verification.timed_state_exploration.zone.Zone#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State)
*/
// public Zone fireTransitionbyTransitionIndex(int timer, int[] enabledTimers,
// State state)
// // TODO: Check if finish.
// int index = Arrays.binarySearch(_indexToTimer, timer);
// //return fireTransitionbydbmIndex(Arrays.binarySearch(_indexToTimer, timer),
// //enabledTimers, state);
// // Check if the value is in this zone to fire.
// if(index < 0){
// return this;
// return fireTransitionbydbmIndex(index, enabledTimers, state);
/**
* Gives the Zone obtained by firing a given Transitions.
* @param t
* The transitions being fired.
* @param enabledTran
* The list of currently enabled Transitions.
* @param localStates
* The current local states.
* @return
* The Zone obtained by firing Transition t with enabled Transitions enabled
* enabledTran when the current state is localStates.
*/
// public Zone fire(Transition t, LpnTranList enabledTran, ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues,
// State[] localStates){
// public Zone fire(Transition t, LpnTranList enabledTran,
// ArrayList<UpdateContinuous> newAssignValues,
// State[] localStates){
public Zone fire(Transition t, LpnTranList enabledTran,
ContinuousRecordSet newAssignValues,
State[] localStates){
try {
if(_writeLogFile != null){
_writeLogFile.write(t.toString());
_writeLogFile.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
// Create the LPNTransitionPair to check if the Transitions is in the zone and to
// find the index.
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair);
if(dbmIndex <= 0){
return this;
}
// Get the new zone portion.
Zone newZone = fireTransitionbydbmIndexNew(dbmIndex, enabledTran, localStates,
newAssignValues);
// Update any assigned continuous variables.
//newZone.updateContinuousAssignment(newAssignValues);
// Set all the rates to their lower bound.
newZone.setAllToLowerBoundRate();
// Warp the Zone
newZone.dbmWarp(this);
// Warping can wreck the newly assigned values so correct them.
newZone.correctNewAssignemnts(newAssignValues);
newZone.recononicalize();
newZone.advance(localStates);
// Recanonicalize
newZone.recononicalize();
newZone.checkZoneMaxSize();
return newZone;
}
/**
* Updates the Zone according to the transition firing.
* @param index
* The index of the timer.
* @param newContValue
* @return
* The updated Zone.
*/
public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers,
State[] localStates,
ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues)
// public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers,
// State[] localStates,
//// ArrayList<UpdateContinuous> newAssignValues)
// public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers,
// State[] localStates,
// ContinuousRecordSet newAssignValues)
{
/*
* For the purpose of adding the newly enabled transitions and removing
* the disable transitions, the continuous variables that still have
* a nonzero rate can be treated like still enbaled timers.
*/
// Initialize the zone.
Zone newZone = new Zone();
// These sets will defferentiate between the new timers and the
// old timers, that is between the timers that are not already in the
// zone and those that are already in the zone..
HashSet<LPNTransitionPair> newTimers = new HashSet<LPNTransitionPair>();
HashSet<LPNTransitionPair> oldTimers = new HashSet<LPNTransitionPair>();
// Copy the LPNs over.
newZone._lpnList = new LhpnFile[this._lpnList.length];
for(int i=0; i<this._lpnList.length; i++){
newZone._lpnList[i] = this._lpnList[i];
}
// copyRatesNew(newZone, enabledTimers, newAssignValues);
HashMap<LPNContAndRate, IntervalPair> oldNonZero = newAssignValues.get(3);
// Add the continuous variables to the enabled timers.
for(int i=1; _indexToTimerPair[i] instanceof LPNContinuousPair; i++){
// For the purpose of addigng continuous variables to the zone
// consider an oldNonZero continuous variable as new.
if(oldNonZero.containsKey(_indexToTimerPair[i])){
continue;
}
oldTimers.add(_indexToTimerPair[i]);
}
for(int i=0; i<newZone._indexToTimerPair.length; i++)
{
// Determine if each value is a new timer or old.
if(Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i])
>= 0 )
{
// The timer was already present in the zone.
oldTimers.add(newZone._indexToTimerPair[i]);
}
else
{
// The timer is a new timer.
newTimers.add(newZone._indexToTimerPair[i]);
}
}
// Create the new matrix.
newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];
// TODO: For simplicity, make a copy of the current zone and perform the
// restriction and re-canonicalization. Later add a copy re-canonicalization
// that does the steps together.
Zone tempZone = this.clone();
tempZone.restrictTimer(index);
tempZone.recononicalize();
// Copy the tempZone to the new zone.
for(int i=0; i<tempZone.dbmSize(); i++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[i]))
{
continue;
}
// Get the new index of for the timer.
int newIndexi = i==0 ? 0 :
Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);
for(int j=0; j<tempZone.dbmSize(); j++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[j]))
{
continue;
}
int newIndexj = j==0 ? 0 :
Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);
newZone._matrix[newZone.dbmIndexToMatrixIndex(newIndexi)]
[newZone.dbmIndexToMatrixIndex(newIndexj)]
= tempZone.getDbmEntry(i, j);
}
}
// Copy the upper and lower bounds.
for(int i=1; i<tempZone.dbmSize(); i++)
{
// The block copies the upper and lower bound information from the
// old zone. Thus we do not consider anything that is not an old
// timer. Furthermore, oldNonZero represent
if(!oldTimers.contains(tempZone._indexToTimerPair[i])
&& !oldNonZero.containsKey(_indexToTimerPair[i]))
{
continue;
}
newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i],
-1*tempZone.getLowerBoundbydbmIndex(i));
// The minus sign is because _matrix stores the negative of the lower bound.
newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i],
tempZone.getUpperBoundbydbmIndex(i));
}
// Copy in the new relations for the new timers.
for(LPNTransitionPair timerNew : newTimers)
{
for(LPNTransitionPair timerOld : oldTimers)
{
newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew),
newZone.timerIndexToDBMIndex(timerOld),
tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));
newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld),
newZone.timerIndexToDBMIndex(timerNew),
tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));
}
}
// Set the upper and lower bounds for the new timers.
for(LPNTransitionPair pair : newTimers){
// Get all the upper and lower bounds for the new timers.
// Get the name for the timer in the i-th column/row of DBM
//String tranName = indexToTran.get(i).getName();
String tranName = _lpnList[pair.get_lpnIndex()]
.getTransition(pair.get_transitionIndex()).getLabel();
ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
_lpnList[pair.get_lpnIndex()]
.getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());
// Set the upper and lower bound.
int upper, lower;
if(delay.getOp().equals("uniform"))
{
IntervalPair lowerRange = delay.getLeftChild()
.evaluateExprBound(varValues, null, null);
IntervalPair upperRange = delay.getRightChild()
.evaluateExprBound(varValues, null, null);
// The lower and upper bounds should evaluate to a single
// value. Yell if they don't.
if(!lowerRange.singleValue() || !upperRange.singleValue()){
throw new IllegalStateException("When evaulating the delay, " +
"the lower or the upper bound evaluated to a range " +
"instead of a single value.");
}
lower = lowerRange.get_LowerBound();
upper = upperRange.get_UpperBound();
}
else
{
IntervalPair range = delay.evaluateExprBound(varValues, this, null);
lower = range.get_LowerBound();
upper = range.get_UpperBound();
}
newZone.setLowerBoundByLPNTransitionPair(pair, lower);
newZone.setUpperBoundByLPNTransitionPair(pair, upper);
}
//newZone.advance();
// Advance time.
// newZone.advance(localStates);
// Recanonicalize.
// newZone.recononicalize();
// newZone.checkZoneMaxSize();
return newZone;
}
public Zone fireTransitionbydbmIndexNew(int index, LpnTranList enabledTimers,
State[] localStates,
ContinuousRecordSet newAssignValues)
{
/*
* For the purpose of adding the newly enabled transitions and removing
* the disable transitions, the continuous variables that still have
* a nonzero rate can be treated like still enbaled timers.
*/
// Initialize the zone.
Zone newZone = new Zone();
// These sets will defferentiate between the new timers and the
// old timers, that is between the timers that are not already in the
// zone and those that are already in the zone..
HashSet<LPNTransitionPair> newTimers = new HashSet<LPNTransitionPair>();
HashSet<LPNTransitionPair> oldTimers = new HashSet<LPNTransitionPair>();
// Copy the LPNs over.
newZone._lpnList = new LhpnFile[this._lpnList.length];
for(int i=0; i<this._lpnList.length; i++){
newZone._lpnList[i] = this._lpnList[i];
}
copyRatesNew(newZone, enabledTimers, newAssignValues);
// HashMap<LPNContAndRate, IntervalPair> oldNonZero = newAssignValues.get(3);
// Add the continuous variables to the enabled timers.
// for(int i=1; _indexToTimerPair[i] instanceof LPNContinuousPair; i++){
// // For the purpose of addigng continuous variables to the zone
// // consider an oldNonZero continuous variable as new.
// if(oldNonZero.containsKey(_indexToTimerPair[i])){
// continue;
// oldTimers.add(_indexToTimerPair[i]);
for(int i=0; i<newZone._indexToTimerPair.length; i++)
{
// Handle the continuous variables portion.
if(newZone._indexToTimerPair[i] instanceof LPNContinuousPair){
LPNContinuousPair lcPair =
(LPNContinuousPair) newZone._indexToTimerPair[i];
// Get the record
UpdateContinuous continuousState =
newAssignValues.get(lcPair);
if(continuousState != null && (continuousState.is_newValue() ||
continuousState.newlyNonZero())){
// In the first case a new value has been assigned, so
// consider the continuous variable a 'new' variable for
// the purposes of copying relations from the previous zone.
newTimers.add(newZone._indexToTimerPair[i]);
continue;
}
// At this point, either the continuous variable was not present
// in the newAssignValues or it is in the newAssignValues and
// satisfies the following: it already had a non-zero rate, is
// being assigned another non-zero rate, and is not being assigned
// a new value. This is becuase the field _indexToTimerPair only
// deals with non-zero rates, so the variable must have a non-zero
// rate. Furthermore the if statement takes care of the cases
// when the rate changed from zero to non-zero and/or a new value
// has been assigned.
// In either of the cases, we consider the variable an 'old' variable
// for the purpose of copying the previous zone information.
oldTimers.add(newZone._indexToTimerPair[i]);
}
// At this point, the varaible represents a transition (timer).
// So determine whether this timer is new or old.
else if(Arrays.binarySearch(this._indexToTimerPair,
newZone._indexToTimerPair[i]) >= 0 )
{
// The timer was already present in the zone.
oldTimers.add(newZone._indexToTimerPair[i]);
}
else
{
// The timer is a new timer.
newTimers.add(newZone._indexToTimerPair[i]);
}
}
// Create the new matrix.
newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];
// TODO: For simplicity, make a copy of the current zone and perform the
// restriction and re-canonicalization. Later add a copy re-canonicalization
// that does the steps together.
Zone tempZone = this.clone();
tempZone.restrictTimer(index);
tempZone.recononicalize();
// Copy the tempZone to the new zone.
for(int i=0; i<tempZone.dbmSize(); i++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[i]))
{
continue;
}
// Get the new index of for the timer.
int newIndexi = i==0 ? 0 :
Arrays.binarySearch(newZone._indexToTimerPair,
tempZone._indexToTimerPair[i]);
for(int j=0; j<tempZone.dbmSize(); j++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[j]))
{
continue;
}
int newIndexj = j==0 ? 0 :
Arrays.binarySearch(newZone._indexToTimerPair,
tempZone._indexToTimerPair[j]);
newZone._matrix[newZone.dbmIndexToMatrixIndex(newIndexi)]
[newZone.dbmIndexToMatrixIndex(newIndexj)]
= tempZone.getDbmEntry(i, j);
}
}
// Copy the upper and lower bounds.
for(int i=1; i<tempZone.dbmSize(); i++)
{
// The block copies the upper and lower bound information from the
// old zone. Thus we do not consider anything that is not an old
// timer.
if(!oldTimers.contains(tempZone._indexToTimerPair[i]))
{
// A hack to ensure that the newly zero varaibles
// get the new values from the tempZone.
if(tempZone._indexToTimerPair[i] instanceof LPNContinuousPair){
LPNContinuousPair lcPair =
(LPNContinuousPair) tempZone._indexToTimerPair[i];
VariableRangePair vrp = newZone._rateZeroContinuous
.get(new LPNContAndRate(lcPair));
if(vrp != null){
// This means that the continuous varaible was non-zero
// and is now zero. Fix up the values according to
// the temp zone.
IntervalPair newRange = tempZone.getContinuousBounds(lcPair);
vrp.set_range(newRange);
}
}
continue;
}
if(_indexToTimerPair[i] instanceof LPNContinuousPair){
LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[i];
// Check if a rate assignment has occured for any continuous
// variables.
UpdateContinuous updateRecord =
newAssignValues.get(lcPair);
if(updateRecord != null){
// Since the variable is in the oldTimers, it cannot have had
// a new value assigned to it. It must have had a new rate assignment
IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();
IntervalPair values = updateRecord.get_Value();
// Copy the new rate information
newZone.setLowerBoundByLPNTransitionPair(_indexToTimerPair[i],
rates.get_LowerBound());
newZone.setUpperBoundByLPNTransitionPair(_indexToTimerPair[i],
rates.get_UpperBound());
// Copy the smallest and greatest continuous value.
// newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR,
// _indexToTimerPair[i], -1*values.get_LowerBound());
// newZone.setDbmEntryByPair(_indexToTimerPair[i],
// LPNTransitionPair.ZERO_TIMER_PAIR, values.get_UpperBound());
continue;
}
}
newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i],
-1*tempZone.getLowerBoundbydbmIndex(i));
// The minus sign is because _matrix stores the negative of the lower bound.
newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i],
tempZone.getUpperBoundbydbmIndex(i));
}
// Copy in the new relations for the new timers.
for(LPNTransitionPair timerNew : newTimers)
{
for(LPNTransitionPair timerOld : oldTimers)
{
newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew),
newZone.timerIndexToDBMIndex(timerOld),
tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));
newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld),
newZone.timerIndexToDBMIndex(timerNew),
tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));
}
}
// Set the upper and lower bounds for the new timers.
for(LPNTransitionPair pair : newTimers){
// Handle continuous case
if(pair instanceof LPNContinuousPair){
LPNContinuousPair lcPair = (LPNContinuousPair) pair;
// If a continuous variable is in the newTimers, then an assignment
// to the variable must have occurred. So get the value.
UpdateContinuous updateRecord = newAssignValues.get(lcPair);
if(updateRecord == null){
throw new IllegalStateException("The pair " + pair
+ "was not in the new assigned values but was sorted as "
+ "a new value.");
}
IntervalPair rates = updateRecord.get_lcrPair().get_rateInterval();
IntervalPair values = updateRecord.get_Value();
newZone.setLowerBoundByLPNTransitionPair(lcPair,
rates.get_LowerBound());
newZone.setUpperBoundByLPNTransitionPair(lcPair,
rates.get_UpperBound());
// Get the current rate.
int currentRate = lcPair.getCurrentRate();
if(currentRate>= 0){
// // Copy the smallest and greatest continuous value.
// newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR,
// lcPair, -1*values.get_LowerBound());
// newZone.setDbmEntryByPair(lcPair,
// LPNTransitionPair.ZERO_TIMER_PAIR,
// values.get_UpperBound());
// Copy the smallest and greatest continuous value.
newZone.setDbmEntryByPair(lcPair,
LPNTransitionPair.ZERO_TIMER_PAIR,
ContinuousUtilities.chkDiv(-1*values.get_LowerBound(),
currentRate, true));
newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR,
lcPair,
ContinuousUtilities.chkDiv(values.get_UpperBound(),
currentRate, true));
}
else{
// Copy the smallest and greatest continuous value.
// For negative rates, the upper and lower bounds need
// to be switched.
newZone.setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR,
lcPair,
ContinuousUtilities.chkDiv(-1*values.get_LowerBound(),
currentRate, true));
newZone.setDbmEntryByPair(lcPair,
LPNTransitionPair.ZERO_TIMER_PAIR,
ContinuousUtilities.chkDiv(values.get_UpperBound(),
currentRate, true));
}
continue;
}
// Get all the upper and lower bounds for the new timers.
// Get the name for the timer in the i-th column/row of DBM
String tranName = _lpnList[pair.get_lpnIndex()]
.getTransition(pair.get_transitionIndex()).getLabel();
ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
_lpnList[pair.get_lpnIndex()]
.getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());
// Set the upper and lower bound.
int upper, lower;
if(delay.getOp().equals("uniform"))
{
IntervalPair lowerRange = delay.getLeftChild()
.evaluateExprBound(varValues, null, null);
IntervalPair upperRange = delay.getRightChild()
.evaluateExprBound(varValues, null, null);
// The lower and upper bounds should evaluate to a single
// value. Yell if they don't.
if(!lowerRange.singleValue() || !upperRange.singleValue()){
throw new IllegalStateException("When evaulating the delay, " +
"the lower or the upper bound evaluated to a range " +
"instead of a single value.");
}
lower = lowerRange.get_LowerBound();
upper = upperRange.get_UpperBound();
}
else
{
IntervalPair range = delay.evaluateExprBound(varValues, this, null);
lower = range.get_LowerBound();
upper = range.get_UpperBound();
}
newZone.setLowerBoundByLPNTransitionPair(pair, lower);
newZone.setUpperBoundByLPNTransitionPair(pair, upper);
}
//Erase relationships for continuous variables that have had new values
// assigned to them or a new non-rate zero value.
for(int i = 1; i<newZone._indexToTimerPair.length &&
newZone._indexToTimerPair[i] instanceof LPNContinuousPair; i++){
LPNContinuousPair lcPair = (LPNContinuousPair) newZone._indexToTimerPair[i];
// Get the update variable.
UpdateContinuous update = newAssignValues.get(lcPair);
if(update != null && (update.is_newValue() || update.newlyNonZero())){
for(int j=1; j<newZone._indexToTimerPair.length; j++){
if (j==i){
continue;
}
else{
newZone.setDbmEntry(i, j, Zone.INFINITY);
newZone.setDbmEntry(j, i, Zone.INFINITY);
}
}
}
}
//newZone.advance();
// Advance time.
// newZone.advance(localStates);
// Recanonicalize.
// newZone.recononicalize();
// newZone.checkZoneMaxSize();
return newZone;
}
public void correctNewAssignemnts(ContinuousRecordSet newAssignValues){
//Erase relationships for continuous variables that have had new values
// assigned to them or a new non-rate zero value.
for(int i = 1; i<this._indexToTimerPair.length &&
this._indexToTimerPair[i] instanceof LPNContinuousPair; i++){
LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];
// Get the update variable.
UpdateContinuous update = newAssignValues.get(lcPair);
if(update != null && (update.is_newValue() || update.newlyNonZero())){
IntervalPair values = update.get_Value();
int currentRate = lcPair.getCurrentRate();
// Correct the upper and lower bounds.
if(lcPair.getCurrentRate()>0){
setDbmEntry(i, 0,
ContinuousUtilities.chkDiv(-1*values.get_LowerBound(),
currentRate, true));
setDbmEntry(0,i,
ContinuousUtilities.chkDiv(values.get_UpperBound(),
currentRate, true));
}
else{
setDbmEntry(i,0,
ContinuousUtilities.chkDiv(values.get_UpperBound(),
currentRate, true));
setDbmEntry(0, i,
ContinuousUtilities.chkDiv(-1*values.get_LowerBound(),
currentRate, true));
}
// Erase the relationships.
for(int j=1; j<this._indexToTimerPair.length; j++){
if (j==i){
continue;
}
else{
this.setDbmEntry(i, j, Zone.INFINITY);
this.setDbmEntry(j, i, Zone.INFINITY);
}
}
}
}
}
/**
* This fire method fires a rate change event.
*
* @param ltPair
* The index of the continuous variable whose rate needs to be changed.
* @param rate
* The new rate.
* @return
* The new zone resulting from the rate change.
*/
public Zone fire(LPNTransitionPair ltPair, int rate){
// Make a copy of the Zone.
Zone resultZone = this.clone();
// Change the current rate of the continuous variable.
setCurrentRate(ltPair, rate);
// Warp the zone.
resultZone.dbmWarp(this);
// Recanonicalize.
// resultZone.recononicalize();
// resultZone.checkZoneMaxSize();
return resultZone;
}
/**
* Handles the moving in and out of continuous variables.
* @param newContValues
*/
// private void copyRates(Zone newZone,
// HashMap<LPNContinuousPair, IntervalPair> newZeroContValues,
// HashMap<LPNContinuousPair, IntervalPair> newNonZeroContValues){
// newZone._rateZeroContinuous = new DualHashMap<LPNTransitionPair, VariableRangePair>();
// // Copy the zero rate variables over if they are still rate zero.
// for(Entry<LPNTransitionPair, VariableRangePair> entry : _rateZeroContinuous.entrySet()){
// LPNContinuousPair thePair = (LPNContinuousPair) entry.getKey();
// VariableRangePair rangeValue = entry.getValue();
// // Check if the pairing is in the newNonZeroContValues.
// IntervalPair interval = newNonZeroContValues.get(thePair);
// if(interval == null){
// // Interval being null indicates that the key was not
// // found.
// newZone._rateZeroContinuous.put(thePair, rangeValue);
/**
* Handles the moving of the continuous variables in and out of the
* _rateZeroContinuous. This includes the adding of all rate zero (new and old)
* cotninuous variables to the _rateZeroContinuous, and creating the
* _indexToTimerPair and populating it.
* @param newZone The Zone being constructed.
* @param enabled The list of enabled transitions.
* The enabled transitions.
* @param newAssignValues The list of continuous variable update information.
*/
// private void copyRates(Zone newZone, LpnTranList enabledTran,
// ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues){
// private void copyRates(Zone newZone, LpnTranList enabledTran,
// ArrayList<UpdateContinuous> newAssignValues){
private void copyRates(Zone newZone, LpnTranList enabledTran,
ContinuousRecordSet newAssignValues){
/*
* The newAssignValues is an ArrayList of four sets.
* 0. Rate zero gets zero assigned.
* 1. Rate zero gets non-zero rate assigned.
* 2. Non-zero gets zero rate assigned.
* 3. Non-zero gets non-zero rate assigned.
*/
// final int OLD_ZERO = 0; // Case 0 in description.
// final int NEW_NON_ZERO = 1; // Case 1 in description.
// final int NEW_ZERO = 2; // Case 2 in description.
// final int OLD_NON_ZERO = 3; // Case 3 in description. Isn't used.
// HashMap<LPNContAndRate, IntervalPair> oldRateZero =
// newAssignValues.get(OLD_ZERO);
// HashMap<LPNContAndRate, IntervalPair> newNonZeroRate =
// newAssignValues.get(NEW_NON_ZERO);
// HashMap<LPNContAndRate, IntervalPair> newRateZero =
// newAssignValues.get(NEW_ZERO);
// HashMap<LPNContAndRate, IntervalPair> oldNonZero =
// newAssignValues.get(OLD_NON_ZERO);
// Create new rate zero member variable.
newZone._rateZeroContinuous = new DualHashMap<LPNContAndRate,
VariableRangePair>();
// Create new _indexToTimerPair.
// First get the total number of non-zero rate continuous variables that
// are present in the old zone.
int totalContinuous = 0;
for(int i=0; i<_lpnList.length; i++){
totalContinuous += _lpnList[i].getTotalNumberOfContVars();
}
int numberNonZero = totalContinuous - _rateZeroContinuous.size();
// The size is given by
// total number of transitions
// + number of non-zero rate continuous variables previously in the zone
// + number of zero rate continuous variables that now have non-zero
// - number of non-zero rate continuous variables that are now zero
// + 1 for the zero timer.
// int newSize = enabledTran.size()
// + numberNonZero + newAssignValues.get(NEW_NON_ZERO).size()
// - newAssignValues.get(NEW_ZERO).size() + 1;
// TODO: Create an object that stores the records along with this information.
int newNonZero = 0, newZero = 0;
for(UpdateContinuous record : newAssignValues.keySet()){
if(record.newlyNonZero()){
newNonZero++;
}
if(record.newlyZero()){
newZero++;
}
}
int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;
// Create the timer array.
newZone._indexToTimerPair = new LPNTransitionPair[newSize];
// Add in the zero timer.
newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;
// Copy over the rate zero conintinuous variables.
// First copy over all the continuous variables that still have
// rate zero.
// for(LPNTransitionPair ltTranPair : _rateZeroContinuous.keySet()){
// // Cast the index.
// LPNContinuousPair ltContPair = (LPNContinuousPair) ltTranPair;
// if(newNonZeroRate.containsKey(ltContPair)){
// // The variable no longer is rate zero, so do nothing.
// continue;
// // If the value has had an assignment, use the new values instead.
// if(oldRateZero.containsKey(new LPNContAndRate(ltContPair))){
// // Create the new VariableRangePair to add.
// Variable v = _lpnList[ltContPair.get_lpnIndex()]
// .getContVar(ltContPair.get_ContinuousIndex());
// VariableRangePair vrp =
// new VariableRangePair(v, oldRateZero.get(new LPNContAndRate(ltContPair)));
// newZone._rateZeroContinuous.put(ltContPair, vrp);
// else{
// newZone._rateZeroContinuous.put(ltTranPair, _rateZeroContinuous.get(ltTranPair));
// Copy over the rate zero continuous variables.
// First copy over all the continuous variables that still have
// rate zero.
for(LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()){
// Cast the index.
LPNContinuousPair ltContPair = (LPNContinuousPair) ltTranPair.get_lcPair();
if(!newAssignValues.get(ltContPair).is_newZero()){
// The variable no longer is rate zero, so do nothing.
continue;
}
// If the value has had an assignment, use the new values instead.
// if(oldRateZero.containsKey(new LPNContAndRate(ltContPair))){
if(newAssignValues.contains(ltContPair)){
// Create the new VariableRangePair to add.
Variable v = _lpnList[ltContPair.get_lpnIndex()]
.getContVar(ltContPair.get_ContinuousIndex());
// VariableRangePair vrp =
// new VariableRangePair(v,
// oldRateZero.get(new LPNContAndRate(ltContPair)));
VariableRangePair vrp =
new VariableRangePair(v,
newAssignValues.get(ltContPair).get_Value());
newZone._rateZeroContinuous.insert(
new LPNContAndRate(ltContPair, new IntervalPair(0,0)), vrp);
}
else{
newZone._rateZeroContinuous
.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));
}
}
// Next add the values that are newly set to rate zero.
// for(LPNContAndRate ltCar : newRateZero.keySet()){
// // Exract the variable.
// Variable v = _lpnList[ltCar.get_lcPair().get_lpnIndex()].
// getContVar(ltCar.get_lcPair().get_ContinuousIndex());
// // Create a VariableRangePair.
// VariableRangePair vrp = new VariableRangePair(v, newRateZero.get(ltCar.get_lcPair()));
// // Add the value to the map.
// newZone._rateZeroContinuous.put(ltCar.get_lcPair(), vrp);
// for(LPNContAndRate ltCar : newRateZero.keySet()){
// // Exract the variable.
// Variable v = _lpnList[ltCar.get_lcPair().get_lpnIndex()].
// getContVar(ltCar.get_lcPair().get_ContinuousIndex());
// // Create a VariableRangePair.
// VariableRangePair vrp = new VariableRangePair(v, newRateZero.get(ltCar.get_lcPair()));
// // Add the value to the map.
// newZone._rateZeroContinuous.put(ltCar.get_lcPair(), vrp);
// We still need to add in the rate zero continuous variables whose rate remains zero
// since their range might have changed. We could check if the range has changed, but
// its just as easy (or easier) to simply add it anyway.
// Added the indecies for the non-zero rate continuous variables to the
// _indexToTimer array.
// Start with the values already in the old array.
// int index = 1; // Index for the next continuous index object.
// for(int i=1; this._indexToTimerPair[i] instanceof LPNContinuousPair; i++){
// // Check that the value should not be removed.
// LPNContAndRate lcar = new LPNContAndRate((LPNContinuousPair) _indexToTimerPair[i]);
// if(newRateZero.containsKey(lcar)){
// continue;
//// else if (oldNonZero.containsKey(lcar)){
//// continue;
// else if (oldRateZero.containsKey(lcar)){
// continue;
// else{
// newZone._indexToTimerPair[index++] = this._indexToTimerPair[i].clone();
// Change to the new references for the oldNonZero. This change to the
// new current rate.
// for(LPNContAndRate lcar : oldNonZero.keySet()){
// int oldIndex = Arrays.binarySearch(_indexToTimerPair, lcar.get_lcPair());
// _indexToTimerPair[oldIndex] = lcar.get_lcPair();
// Add in the indecies for the new non-zero into the old array.
// for(LPNContinuousPair ltCont : newNonZeroRate.keySet()){
// for(LPNContAndRate ltCar : newNonZeroRate.keySet()){
//// newZone._indexToTimerPair[index++] = ltCont;
// newZone._indexToTimerPair[index++] = ltCar.get_lcPair();
// Arrays.sort(newZone._indexToTimerPair);
// Copy over the new transitions.
// for(Transition t : enabledTran){
//// newZone._indexToTimerPair[index++] = ;
// int lpnIndex = t.getLpn().getLpnIndex();
// int tranIndex = t.getIndex();
// newZone._indexToTimerPair[index++] =
// new LPNTransitionPair (lpnIndex, tranIndex);
Arrays.sort(newZone._indexToTimerPair);
}
private void copyRatesNew(Zone newZone, LpnTranList enabledTran,
ContinuousRecordSet newAssignValues){
// Create new rate zero member variable.
newZone._rateZeroContinuous = new DualHashMap<LPNContAndRate,
VariableRangePair>();
// Create new _indexToTimerPair.
// First get the total number of non-zero rate continuous variables that
// are present in the old zone.
int totalContinuous = 0;
for(int i=0; i<_lpnList.length; i++){
totalContinuous += _lpnList[i].getTotalNumberOfContVars();
}
int numberNonZero = totalContinuous - _rateZeroContinuous.size();
// The size is given by
// total number of transitions
// + number of non-zero rate continuous variables previously in the zone
// + number of zero rate continuous variables that now have non-zero
// - number of non-zero rate continuous variables that are now zero
// + 1 for the zero timer.
// int newSize = enabledTran.size()
// + numberNonZero + newAssignValues.get(NEW_NON_ZERO).size()
// - newAssignValues.get(NEW_ZERO).size() + 1;
// TODO: Create an object that stores the records along with this information.
int newNonZero = 0, newZero = 0;
for(UpdateContinuous record : newAssignValues.keySet()){
if(record.newlyNonZero()){
newNonZero++;
}
if(record.newlyZero()){
newZero++;
}
}
int newSize = enabledTran.size() + numberNonZero + newNonZero - newZero + 1;
// Create the timer array.
newZone._indexToTimerPair = new LPNTransitionPair[newSize];
// Add in the zero timer.
newZone._indexToTimerPair[0] = LPNTransitionPair.ZERO_TIMER_PAIR;
int indexTimerCount = 1;
// Sort the previous rate zero continuous variables into rate zero or non-zero.
for(LPNContAndRate ltTranPair : _rateZeroContinuous.keySet()){
// Cast the index.
LPNContinuousPair ltContPair = (LPNContinuousPair) ltTranPair.get_lcPair();
// Check if the variable is a newly assigned value.
UpdateContinuous assignedLtContPair = newAssignValues.get(ltContPair);
if(assignedLtContPair != null){
if(assignedLtContPair.newlyNonZero()){
// Variable was zero and is now non-zero, so add to the the non-zero
// references.
newZone._indexToTimerPair[indexTimerCount++] =
assignedLtContPair.get_lcrPair().get_lcPair().clone();
}
else{
// Variable was zero and is still zero, but an assignment has been
// made. Simply add in the new assigned value.
VariableRangePair vrp = this._rateZeroContinuous.get(ltTranPair);
newZone._rateZeroContinuous.insert(assignedLtContPair.get_lcrPair(),
new VariableRangePair(vrp.get_variable(),
assignedLtContPair.get_Value()));
}
}
else{
newZone._rateZeroContinuous
.insert(ltTranPair, _rateZeroContinuous.get(ltTranPair));
}
}
// Sort the previous non-zero variables into the rate zero and non-zero.
for(int i=1; this._indexToTimerPair[i] instanceof LPNContinuousPair; i++){
LPNContinuousPair lcPair = (LPNContinuousPair) this._indexToTimerPair[i];
// Check if an assignment has been made.
UpdateContinuous updateRecord = newAssignValues.get(lcPair);
if(updateRecord != null){
if(updateRecord.is_newZero()){
// The continuous variable is now a rate zero variable.
LPNContinuousPair ltCar = updateRecord.get_lcrPair().get_lcPair();
Variable v = _lpnList[ltCar.get_lpnIndex()].
getContVar(ltCar.get_ContinuousIndex());
// Dewarp the upper and lower bounds.
IntervalPair values = updateRecord.get_Value();
int currentRate = getCurrentRate(ltCar);
values.set_LowerBound(
values.get_LowerBound() * currentRate);
values.set_UpperBound(
values.get_UpperBound() * currentRate);
// Create a VariableRangePair.
VariableRangePair vrp = new VariableRangePair(v,
values);
// Add the value to the map.
// newZone._rateZeroContinuous.put(ltCar, vrp);
newZone._rateZeroContinuous.insert(updateRecord.get_lcrPair(), vrp);
}
else{
// This non-zero variable still has rate non-zero, but replace
// with the newAssignValues since the rate may have changed.
newZone._indexToTimerPair[indexTimerCount++] =
updateRecord.get_lcrPair().get_lcPair();
}
}
else{
// The variable was non-zero and hasn't had an assignment.
newZone._indexToTimerPair[indexTimerCount++] =
this._indexToTimerPair[i].clone();
}
}
// Copy over the new transitions.
for(Transition t : enabledTran){
int lpnIndex = t.getLpn().getLpnIndex();
int tranIndex = t.getIndex();
newZone._indexToTimerPair[indexTimerCount++] =
new LPNTransitionPair (lpnIndex, tranIndex);
}
Arrays.sort(newZone._indexToTimerPair);
}
/**
* Advances time.
*/
private void advance()
{
for(int i=0; i<dbmSize(); i++)
{
_matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] =
getUpperBoundbydbmIndex(i);
}
}
/**
* Advances time. (This method should replace advance().)
* @param localStates
*/
public void advance(State[] localStates){
for(LPNTransitionPair ltPair : _indexToTimerPair){
if(ltPair.equals(LPNTransitionPair.ZERO_TIMER_PAIR)){
continue;
}
// Get the new value.
int newValue = 0;
// if(ltPair.get_isTimer()){
if(!(ltPair instanceof LPNContinuousPair)){
// If the pair is a timer, then simply get the stored largest value.
int index = timerIndexToDBMIndex(ltPair);
newValue = getUpperBoundbydbmIndex(index);
}
else{
// If the pair is a continuous variable, then need to find the
// possible largest bound governed by the inequalities.
newValue = ContinuousUtilities.maxAdvance(this,ltPair, localStates);
}
// In either case (timer or continuous), set the upper bound portion
// of the DBM to the new value.
setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, newValue);
}
}
/**
* Copies in the new values needed to add a set of new times.
* @param newZone
* The zone that the values are going to be copied into.
* @param tempZone
* The zone to look up current values of timers.
* @param newTimers
* A collection of the new timers.
* @param oldTimers
* A collection of the older timers.
* @param localStates
* The current state.
*/
private void copyTransitions(Zone tempZone, Collection<LPNTransitionPair> newTimers,
Collection<LPNTransitionPair> oldTimers, State[] localStates){
// Copy the tempZone to the new zone.
for(int i=0; i<tempZone.dbmSize(); i++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[i]))
{
continue;
}
// Get the new index of for the timer.
int newIndexi = i==0 ? 0 :
Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[i]);
for(int j=0; j<tempZone.dbmSize(); j++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[j]))
{
continue;
}
int newIndexj = j==0 ? 0 :
Arrays.binarySearch(_indexToTimerPair, tempZone._indexToTimerPair[j]);
_matrix[dbmIndexToMatrixIndex(newIndexi)]
[dbmIndexToMatrixIndex(newIndexj)]
= tempZone.getDbmEntry(i, j);
}
}
// Copy the upper and lower bounds.
for(int i=1; i<tempZone.dbmSize(); i++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[i]))
{
continue;
}
setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i],
-1*tempZone.getLowerBoundbydbmIndex(i));
// The minus sign is because _matrix stores the negative of the lower bound.
setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i],
tempZone.getUpperBoundbydbmIndex(i));
}
// Copy in the new relations for the new timers.
for(LPNTransitionPair timerNew : newTimers)
{
for(LPNTransitionPair timerOld : oldTimers)
{
setDbmEntry(timerIndexToDBMIndex(timerNew),
timerIndexToDBMIndex(timerOld),
tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));
setDbmEntry(timerIndexToDBMIndex(timerOld),
timerIndexToDBMIndex(timerNew),
tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));
}
}
// Set the upper and lower bounds for the new timers.
for(LPNTransitionPair pair : newTimers){
// Get all the upper and lower bounds for the new timers.
// Get the name for the timer in the i-th column/row of DBM
//String tranName = indexToTran.get(i).getName();
String tranName = _lpnList[pair.get_lpnIndex()]
.getTransition(pair.get_transitionIndex()).getLabel();
ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
_lpnList[pair.get_lpnIndex()]
.getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVariableVector());
// Set the upper and lower bound.
int upper, lower;
if(delay.getOp().equals("uniform"))
{
IntervalPair lowerRange = delay.getLeftChild()
.evaluateExprBound(varValues, null, null);
IntervalPair upperRange = delay.getRightChild()
.evaluateExprBound(varValues, null, null);
// The lower and upper bounds should evaluate to a single
// value. Yell if they don't.
if(!lowerRange.singleValue() || !upperRange.singleValue()){
throw new IllegalStateException("When evaulating the delay, " +
"the lower or the upper bound evaluated to a range " +
"instead of a single value.");
}
lower = lowerRange.get_LowerBound();
upper = upperRange.get_UpperBound();
}
else
{
IntervalPair range = delay.evaluateExprBound(varValues, this, null);
lower = range.get_LowerBound();
upper = range.get_UpperBound();
}
setLowerBoundByLPNTransitionPair(pair, lower);
setUpperBoundByLPNTransitionPair(pair, upper);
}
}
/**
* This method sets all the rate to their lower bound.
* Will not work quite right for continuous variables
* with rates that include zero.
*/
private void setAllToLowerBoundRate(){
// Loop through the continuous variables.
for(int i=1; i<_indexToTimerPair.length &&
_indexToTimerPair[i] instanceof LPNContinuousPair; i++){
LPNContinuousPair ltContPair = (LPNContinuousPair) _indexToTimerPair[i];
// For this, recall that for a continuous variable that the lower bound
// rate is stored in the zero column of the matrix.
// setCurrentRate(ltContPair,
// -1*getDbmEntry(0,
// dbmIndexToMatrixIndex(i)));
setCurrentRate(ltContPair,
-1*_matrix[dbmIndexToMatrixIndex(i)][0]);
}
}
/**
* Resets the rates of all continuous varaibles to be their
* lower bounds.
*/
public Zone resetRates(){
// Create the new zone.
Zone newZone = new Zone();
// Copy the rate zero variables.
newZone._rateZeroContinuous = this._rateZeroContinuous.clone();
// Copy the LPNs over.
newZone._lpnList = new LhpnFile[this._lpnList.length];
for(int i=0; i<this._lpnList.length; i++){
newZone._lpnList[i] = this._lpnList[i];
}
// Loop through the variables and save off those
// that are rate zero. Accumulate an array that
// indicates which are zero for faster
// copying. Save the number of continuous varaibles.
boolean[] rateZero = new boolean[this._indexToTimerPair.length]; // Is rate zero.
int zeroCount = 0;
for(int i=1; i<this._indexToTimerPair.length &&
this._indexToTimerPair[i] instanceof LPNContinuousPair; i++){
int lowerBound = -1*getLowerBoundbydbmIndex(i);
int upperBound = getUpperBoundbydbmIndex(i);
if(lowerBound <= 0 && upperBound >= 0){
// The rate zero is in the range, so this will be
// the new current rate.
rateZero[i] = true;
LPNContinuousPair lcPair =
(LPNContinuousPair) this._indexToTimerPair[i].clone();
lcPair.setCurrentRate(0);
// Save as a rate zero continuous variable.
LPNContAndRate newRateZero =
new LPNContAndRate(lcPair,
this.getRateBounds(lcPair));
VariableRangePair vcp =
new VariableRangePair(
this._lpnList[lcPair.get_lpnIndex()]
.getContVar(lcPair.get_ContinuousIndex()),
this.getContinuousBounds(lcPair));
newZone._rateZeroContinuous.insert(newRateZero, vcp);
// Update continuous variable counter.
zeroCount++;
}
}
// Save over the indexToTimer pairs.
newZone._indexToTimerPair =
new LPNTransitionPair[this._indexToTimerPair.length-zeroCount];
for(int i=0, j=0; i<newZone._indexToTimerPair.length; i++,j++){
// Ignore rate zero variables.
if(rateZero[j]){
j++;
}
newZone._indexToTimerPair[i] = this._indexToTimerPair[j].clone();
// If this is a continuous variable, set the rate to the lower bound.
if(newZone._indexToTimerPair[i] instanceof LPNContinuousPair){
((LPNContinuousPair) newZone._indexToTimerPair[i])
.setCurrentRate(this.getSmallestRate(j));
}
}
// Calculate the size of the matrix and create it.
newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];
// Copy over the old matrix for all variables except
// the rate zero variables.
for(int i=0, ioffset=0; i<newZone.matrixSize(); i++){
if(i>=1 && rateZero[i-1]){
ioffset++;
}
for(int j=1, joffset=0; j<newZone.matrixSize(); j++){
if(j>=1 && rateZero[j-1]){
joffset++;
}
newZone._matrix[i][j] = this._matrix[i+ioffset][j+joffset];
}
}
// Warp
newZone.dbmWarp(this);
newZone.recononicalize();
return newZone;
}
/**
* Finds the maximum amount that time cam advance.
* @return
* value.
* The maximum amount that time can advance before a timer expires or an inequality changes
*/
// private int maxAdvance(LPNTransitionPair contVar, State[] localStates){
// /*
// * Several comments in this function may look like C code. That's because,
// * well it is C code from atacs/src/lhpnrsg.c. In particular the
// * lhpnCheckPreds method.
// */
// // Get the continuous variable in question.
// int lpnIndex = contVar.get_lpnIndex();
// int varIndex = contVar.get_transitionIndex();
// Variable variable = _lpnList[lpnIndex].getContVar(varIndex);
//// int lhpnCheckPreds(int p,ineqList &ineqL,lhpnStateADT s,ruleADT **rules,
//// int nevents,eventADT *events)
////#ifdef __LHPN_TRACE__
////printf("lhpnCheckPreds:begin()\n");
////#endif
////int min = INFIN;
////int newMin = INFIN;
// int min = INFINITY;
// int newMin = INFINITY;
////int zoneP = getIndexZ(s->z,-2,p);
////for(unsigned i=0;i<ineqL.size();i++) {
//// if(ineqL[i]->type > 4) {
//// continue;
////#ifdef __LHPN_PRED_DEBUG__
//// printf("Zone to check...\n");
//// printZ(s->z,events,nevents,s->r);
//// printf("Checking ...");
//// printI(ineqL[i],events);
//// printf("\n");
////#endif
//// if(ineqL[i]->place == p) {
// // Get all the inequalities that reference the variable of interest.
// ArrayList<InequalityVariable> inequalities = variable.getInequalities();
// for(InequalityVariable ineq : inequalities){
//// ineq_update(ineqL[i],s,nevents);
// // Update the inequality variable.
// int ineqValue = ineq.evaluate(localStates[varIndex], this);
//// if(ineqL[i]->type <= 1) {
//// /* Working on a > or >= ineq */
// if(ineq.get_op().equals(">") || ineq.get_op().equals(">=")){
// // Working on a > or >= ineq
//// if(s->r->bound[p-nevents].current > 0) {
// // If the rate is positive.
// if(getCurrentRate(contVar) > 0){
//// if(s->m->state[ineqL[i]->signal]=='1') {
// if(ineqValue != 0){
//// if(s->z->matrix[zoneP][0] <
//// chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 1a\n");
////#endif
////#ifdef __LHPN_WARN__
//// warn("checkPreds: Impossible case 1.\n");
////#endif
//// newMin = s->z->matrix[zoneP][0];
// if(getDbmEntry(0, contVar.get_transitionIndex())
// < chkDiv(ineq.getConstant(), getCurrentRate(contVar), false)){
// // CP: case 1a.
// newMin = getDbmEntry(0, contVar.get_transitionIndex());
// System.err.println("maxAdvance: Impossible case 1.");
//// else if((-1)*s->z->matrix[0][zoneP] >
//// chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 2a\n");
////#endif
//// newMin = chkDiv(events[p]->urange,
//// s->r->bound[p-nevents].current,'F');
// else if ((-1)*getDbmEntry(contVar.get_transitionIndex(),0)
// > chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // CP : case 2a
// newMin = INFINITY;
//// else {
//// /* straddle case */
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 3a\n");
////#endif
//// newMin = chkDiv(events[p]->urange,
//// s->r->bound[p-nevents].current,'F');
// else{
// // Straddle case
// // CP : case 3a
// newMin = INFINITY;
// else{
//// else {
//// if(s->z->matrix[zoneP][0] <
//// chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 4a -- min: %d\n",chkDiv(ineqL[i]->constant,s->r->bound[p-nevents].current,'F'));
////#endif
//// newMin = chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F');
// if(getDbmEntry(contVar.get_transitionIndex(), 0)
// < chkDiv(ineq.getConstant(), getCurrentRate(contVar), false)){
// // CP: case 4a -- min
// newMin = chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false);
//// else if((-1)*s->z->matrix[0][zoneP] >
//// chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 5a\n");
////#endif
////#ifdef __LHPN_WARN__
//// warn("checkPreds: Impossible case 3.\n");
////#endif
//// newMin = s->z->matrix[zoneP][0];
// else if((-1)*getDbmEntry(contVar.get_transitionIndex(),0)
// < chkDiv(ineq.getConstant(), getCurrentRate(contVar), false)){
// // Impossible case 3.
// newMin = getDbmEntry(0, contVar.get_transitionIndex());
// System.err.print("maxAdvance : Impossible case 3.");
//// else {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 6a -- min: %d\n",s->z->matrix[zoneP][0]);
////#endif
//// /* straddle case */
//// newMin = s->z->matrix[zoneP][0];
// else{
// // CP : cas 6a
// // straddle case
// newMin = getDbmEntry(0,contVar.get_transitionIndex());
//// else {
//// /* warp <= 0 */
// else{
// // warp <= 0.
//// if(s->m->state[ineqL[i]->signal]=='1') {
// if( ineqValue != 1){
//// if(s->z->matrix[0][zoneP] <
//// (-1)*chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 7a\n");
////#endif
////#ifdef __LHPN_WARN__
//// warn("checkPreds: Impossible case 2.\n");
////#endif
//// newMin = s->z->matrix[zoneP][0];
// if(getDbmEntry(contVar.get_transitionIndex(),0)
// < (-1)*chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // CP: case 7a.
// newMin = getDbmEntry(0,contVar.get_transitionIndex());
// System.err.println("Warining: impossible case 2a found.");
//// else if((-1)*s->z->matrix[zoneP][0] >
//// (-1)*chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 8a\n");
////#endif
//// newMin = chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F');
// else if((-1)*getDbmEntry(0, contVar.get_transitionIndex())
// < (-1)*chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // Impossible case 8a.
// newMin = chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false);
//// else {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 9a\n");
////#endif
//// /* straddle case */
//// newMin = s->z->matrix[zoneP][0];
// else{
// // straddle case
// newMin = getDbmEntry(0, contVar.get_transitionIndex());
//// else {
// else{
//// if(s->z->matrix[0][zoneP] <
//// (-1)*chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 10a\n");
////#endif
//// newMin = chkDiv(events[p]->lrange,
//// s->r->bound[p-nevents].current,'F');
// if(getDbmEntry(contVar.get_transitionIndex(),0)
// < (-1)*chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // CP: case 10a.
// newMin = INFINITY;
//// else if((-1)*s->z->matrix[zoneP][0] >
//// (-1)*chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 11a\n");
//// printf("z=%d c=%d b=%d\n",
//// s->z->matrix[zoneP][0],
//// ineqL[i]->constant,
//// s->r->bound[p-nevents].current);
////#endif
////#ifdef __LHPN_WARN__
//// warn("checkPreds: Impossible case 4.\n");
////#endif
//// newMin = s->z->matrix[zoneP][0];
// else if((-1)*getDbmEntry(0, contVar.get_transitionIndex())
// < (-1)*chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // CP: case 7a.
// newMin = getDbmEntry(0,contVar.get_transitionIndex());
// System.err.println("maxAdvance : Impossible case 4.");
//// else {
//// /* straddle case */
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 12a\n");
////#endif
//// newMin = chkDiv(events[p]->lrange,
//// s->r->bound[p-nevents].current,'F');
// else{
// // straddle case
// newMin = INFINITY;
//// else {
//// /* Working on a < or <= ineq */
// else{
// // Working on a < or <= ineq
//// if(s->r->bound[p-nevents].current > 0) {
// if(getUpperBoundForRate(contVar) > 0){
//// if(s->m->state[ineqL[i]->signal]=='1') {
// if(ineqValue != 0){
//// if(s->z->matrix[zoneP][0] <
//// chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 1b -- min: %d\n",chkDiv(ineqL[i]->constant,s->r->bound[p-nevents].current,'F'));
////#endif
//// newMin = chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F');
// if(getDbmEntry(0, contVar.get_transitionIndex())
// < (-1)*chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // CP: case 1b -- min.
// newMin = chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false);
//// else if((-1)*s->z->matrix[0][zoneP] >
//// chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 2b\n");
////#endif
////#ifdef __LHPN_WARN__
//// warn("checkPreds: Impossible case 5.\n");
////#endif
//// newMin = chkDiv(events[p]->urange,
//// s->r->bound[p-nevents].current,'F');
// if((-1)*getDbmEntry(contVar.get_transitionIndex(), 0)
// < chkDiv(ineq.getConstant(), getCurrentRate(contVar),false)){
// // CP: case 2b.
// newMin = INFINITY;
// System.err.println("Warning : Impossible case 5.");
//// else {
//// /* straddle case */
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 3b -- min: %d\n",s->z->matrix[zoneP][0]);
////#endif
//// newMin = s->z->matrix[zoneP][0];
// else{
// //straddle case
// newMin = getDbmEntry(0,contVar.get_transitionIndex());
//// else {
// else{
//// if(s->z->matrix[zoneP][0] <
//// chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 4b\n");
////#endif
////#ifdef __LHPN_WARN__
//// warn("checkPreds: Impossible case 7.\n");
////#endif
//// newMin = s->z->matrix[zoneP][0];
// if(getDbmEntry(0, contVar.get_transitionIndex())
// < chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // CP: case 4b.
// newMin = getDbmEntry(0, contVar.get_transitionIndex());
// System.err.println("maxAdvance : Impossible case 7.");
//// else if((-1)*s->z->matrix[0][zoneP] >
//// chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 5b\n");
////#endif
//// newMin = chkDiv(events[p]->urange,
//// s->r->bound[p-nevents].current,'F');
// else if((-1)*getDbmEntry(contVar.get_transitionIndex(), 0)
// < chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // CP: case 5b.
// newMin = INFINITY;
//// else {
//// /* straddle case */
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 6b\n");
////#endif
//// newMin = chkDiv(events[p]->urange,
//// s->r->bound[p-nevents].current,'F');
// else{
// // straddle case
// // CP : case 6b
// newMin = INFINITY;
//// else {
//// /* warp <= 0 */
// else {
// // warp <=0
//// if(s->m->state[ineqL[i]->signal]=='1') {
// if(ineqValue != 0){
//// if(s->z->matrix[0][zoneP] <
//// (-1)*chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 7b\n");
////#endif
//// newMin = chkDiv(events[p]->lrange,
//// s->r->bound[p-nevents].current,'F');
// if(getDbmEntry(contVar.get_transitionIndex(), 0)
// < (-1)*chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // CP: case 7b.
// newMin = INFINITY;
//// else if((-1)*s->z->matrix[zoneP][0] >
//// (-1)*chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 8b\n");
////#endif
////#ifdef __LHPN_WARN__
//// warn("checkPreds: Impossible case 8.\n");
////#endif
//// newMin = s->z->matrix[zoneP][0];
// else if((-1)*getDbmEntry(0, contVar.get_transitionIndex())
// < (-1)*chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // CP: case 8b.
// newMin = getDbmEntry(0, contVar.get_transitionIndex());
// System.err.println("Warning : Impossible case 8.");
//// else {
//// /* straddle case */
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 9b\n");
////#endif
//// newMin = chkDiv(events[p]->lrange,
//// s->r->bound[p-nevents].current,'F');
// else {
// // straddle case
// // CP: case 9b.
// newMin = INFINITY;
//// else {
// else {
//// if(s->z->matrix[0][zoneP] <
//// chkDiv((-1)*ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 10b\n");
//// printf("zone: %d const: %d warp: %d chkDiv: %d\n",s->z->matrix[0][zoneP],ineqL[i]->constant,s->r->bound[p-nevents].current,chkDiv((-1)*ineqL[i]->constant,s->r->bound[p-nevents].current,'F'));
////#endif
////#ifdef __LHPN_WARN__
//// warn("checkPreds: Impossible case 6.\n");
////#endif
//// newMin = s->z->matrix[zoneP][0];
// if(getDbmEntry(contVar.get_transitionIndex(),0)
// < (-1)*chkDiv(ineq.getConstant(),
// getCurrentRate(contVar), false)){
// // CP: case 10b.
// newMin = getDbmEntry(0,contVar.get_transitionIndex());
// System.err.println("Warning : Impossible case 6");
//// else if((-1)*s->z->matrix[zoneP][0] >
//// (-1)*chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 11b\n");
////#endif
//// newMin = chkDiv(ineqL[i]->constant,
//// s->r->bound[p-nevents].current,'F');
// else if((-1)*getDbmEntry(0,contVar.get_transitionIndex())
// < (-1)*chkDiv(ineq.getConstant(),
// getCurrentRate(contVar),false)){
// // CP: case 7b.
// newMin = chkDiv(ineq.getConstant(), getCurrentRate(contVar),false);
//// else {
//// /* straddle case */
////#ifdef __LHPN_PRED_DEBUG__
//// printf("CP:case 12b\n");
////#endif
//// newMin = s->z->matrix[zoneP][0];
// else {
// // straddle case
// // CP : case 12b
// newMin = getDbmEntry(0, contVar.get_transitionIndex());
//// if(newMin < min) {
//// min = newMin;
// // Check if the value can be lowered.
// if(newMin < min){
// min = newMin;
////#ifdef __LHPN_PRED_DEBUG__
////printf("Min leaving checkPreds for %s: %d\n",events[p]->event,min);
////#endif
////return min;
// return min;
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
public Zone clone()
{
// TODO: Check if finished.
Zone clonedZone = new Zone();
clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()];
for(int i=0; i<this.matrixSize(); i++)
{
for(int j=0; j<this.matrixSize(); j++)
{
clonedZone._matrix[i][j] = this._matrix[i][j];
}
}
// clonedZone._indexToTimerPair = Arrays.copyOf(_indexToTimerPair, _indexToTimerPair.length);
clonedZone._indexToTimerPair = new LPNTransitionPair[this._indexToTimerPair.length];
for(int i=0; i<_indexToTimerPair.length; i++){
clonedZone._indexToTimerPair[i] = this._indexToTimerPair[i].clone();
}
clonedZone._hashCode = this._hashCode;
clonedZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);
clonedZone._rateZeroContinuous = this._rateZeroContinuous.clone();
return clonedZone;
}
/**
* Restricts the lower bound of a timer.
*
* @param timer
* The timer to tighten the lower bound.
*/
private void restrictTimer(int timer)
{
//int dbmIndex = Arrays.binarySearch(_indexToTimer, timer);
_matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)]
= getLowerBoundbydbmIndex(timer);
}
/**
* Restricts the lower bound of a continuous variable. Also checks fixes
* the upper bound to be at least as large if needed. This method
* is usually used as a result of an event firing.
* @param ltContPair
* The index of the continuous variable to restrict.
* @param constant
* The constant value of the inequality event that is being used to update
* the variable indexed by ltContPair.
*
*/
private boolean restrictContinuous(LPNContinuousPair ltContPair, int constant){
// It will be quicker to get the DBM index for the ltContPair one time.
int variableIndex = timerIndexToDBMIndex(ltContPair);
int zeroIndex = timerIndexToDBMIndex(LPNTransitionPair.ZERO_TIMER_PAIR);
// Set the lower bound the variable (which is the DBM[variabl][0] entry.
// Note : the lower bound in the zone is actually the negative of the lower
// bound hence the -1 on the warpValue.
setDbmEntry(variableIndex, zeroIndex, ContinuousUtilities.chkDiv(-1*constant, ltContPair.getCurrentRate(), true));
// Check if the upper bound needs to be advanced and advance it if necessary.
if(getDbmEntry(zeroIndex, variableIndex) < ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true)){
// If the upper bound in the zones is less than the new restricting value, we
// must advance it for the zone to remain consistent.
setDbmEntry(zeroIndex, variableIndex, ContinuousUtilities.chkDiv(constant, ltContPair.getCurrentRate(), true));
return true;
}
return false;
}
/**
* Restricts the continuous variables in the zone according to the inequalities in a set of events.
* @param eventSet
* A set of inequality events. Does nothing if the event set does not contian inequalities.
*/
private void restrictContinuous(EventSet eventSet){
// Check that the eventSet is a set of Inequality events.
if(!eventSet.isInequalities()){
// If the eventSet is not a set of inequalities, do nothing.
return;
}
HashSet<LPNContinuousPair> adjustedColumns = new HashSet<LPNContinuousPair>();
boolean needsAdjusting = false;
// Restrict the variables according to each of the inequalities in the eventSet.
for(Event e : eventSet){
// Get the inequality.
InequalityVariable iv = e.getInequalityVariable();
// Extract the variable. I will assume the inequality only depends on a single
// variable.
Variable x = iv.getContVariables().get(0);
// Extract the index.
int lpnIndex = iv.get_lpn().getLpnIndex();
// Extract the variable index.
// DualHashMap<String, Integer> variableIndexMap = _lpnList[lpnIndex].getVarIndexMap();
DualHashMap<String, Integer> variableIndexMap = _lpnList[lpnIndex].getContinuousIndexMap();
int variableIndex = variableIndexMap.getValue(x.getName());
// Package it up for referencing.
// LPNContinuousPair ltContPair = new LPNContinuousPair(lpnIndex, variableIndex, 0);
LPNContinuousPair ltContPair = new LPNContinuousPair(lpnIndex, variableIndex);
// Need the current rate for the varaible, grab the stored LPNContinuousPair.
int zoneIndex = Arrays.binarySearch(_indexToTimerPair, ltContPair);
if(zoneIndex > 0){
ltContPair = (LPNContinuousPair) _indexToTimerPair[zoneIndex];
}
//setDbmEntry(zoneIndex, 0, -ContinuousUtilities.chkDiv(iv.getConstant(), ltContPair.getCurrentRate(), true));
// Perform the restricting.
needsAdjusting = needsAdjusting | restrictContinuous(ltContPair, iv.getConstant());
if(needsAdjusting){
adjustedColumns.add(ltContPair);
}
}
// If one of the continuous variables has been moved forward, the other colmns
// need to be adjusted to keep a consistent zone.
if(needsAdjusting){
// At least one of the continuous variables has been moved forward,
// so se need to ajust the bounds to keep a consistent zone.
for(int i=1; i<_indexToTimerPair.length; i++){
LPNTransitionPair ltpair = _indexToTimerPair[i];
if(adjustedColumns.contains(ltpair)){
// This continuous variables already had the upper bound
// adjusted.
continue;
}
else{
// Add one to the upper bounds.
setDbmEntry(0, i, getDbmEntry(0, i)+1);
}
}
}
}
/**
* Returns a zone that is the result from resticting the this zone according to a list of firing event inequalities.
* @param eventSet
* The list of inequalities that are firing.
* @return
* The new zone that is the result of restricting this zone according to the firing of the inequalities
* in the eventSet.
*/
public Zone getContinuousRestrictedZone(EventSet eventSet, State[] localStates){
// Make a new copy of the zone.
Zone z = this.clone();
if(eventSet == null){
return z;
}
z.restrictContinuous(eventSet);
// z.advance(localStates);
// z.recononicalize();
return z;
}
/**
* The list of enabled timers.
* @return
* The list of all timers that have reached their lower bounds.
*/
public List<Transition> getEnabledTransitions()
{
ArrayList<Transition> enabledTransitions = new ArrayList<Transition>();
// Check if the timer exceeds its lower bound staring with the first nonzero
// timer.
for(int i=1; i<_indexToTimerPair.length; i++)
{
if(getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i))
{
enabledTransitions.add(_lpnList[_indexToTimerPair[i].get_lpnIndex()]
.getTransition(_indexToTimerPair[i].get_transitionIndex()));
}
}
return enabledTransitions;
}
/**
* Gives the list of enabled transitions associated with a particular LPN.
* @param LpnIndex
* The Index of the LPN the Transitions are a part of.
* @return
* A List of the Transitions that are enabled in the LPN given by the index.
*/
public List<Transition> getEnabledTransitions(int LpnIndex){
ArrayList<Transition> enabledTransitions = new ArrayList<Transition>();
// Check if the timer exceeds its lower bound staring with the first nonzero
// timer.
for(int i=1; i<_indexToTimerPair.length; i++)
{
if(getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i))
{
LPNTransitionPair ltPair = _indexToTimerPair[i];
if( ltPair.get_lpnIndex() == LpnIndex){
enabledTransitions.add(_lpnList[ltPair.get_lpnIndex()]
.getTransition(ltPair.get_transitionIndex()));
}
}
}
return enabledTransitions;
}
/**
* Find the next possible events.
*
* @param LpnIndex
* The index of the LPN that is of interest.
* @param localState
* The state associated with the LPN indexed by LpnIndex.
* @return
* LpnTranList is populated with a list of
* EventSets pertaining to the LPN with index LpnIndex. An EventSet can
* either contain a transition to
* fire or set of inequalities to change sign.
*/
public LpnTranList getPossibleEvents(int LpnIndex, State localState){
LpnTranList result = new LpnTranList();
// Look through the timers and continuous variables. For the timers
// determine if they are ready to fire. For the continuous variables,
// look up the associated inequalities and see if any of them are ready
// to fire.
// for(LPNTransitionPair ltPair : _indexToTimerPair){
// We do not need to consider the zero timer, so start the
// for loop at i=1 and not i=0.
for(int i=1; i<_indexToTimerPair.length; i++){
LPNTransitionPair ltPair = _indexToTimerPair[i];
// The enabled events are grouped with the LPN that they affect. So if
// this pair does not belong to the current LPN under consideration, skip
// processing it.
if(ltPair.get_lpnIndex() != LpnIndex){
continue;
}
// If the index refers to a timer (and not a continuous variable) and has exceeded its lower bound,
// then add the transition.
if(!(ltPair instanceof LPNContinuousPair)){
//result.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));
// The index refers to a timer. Now check if time has advanced
// far enough for the transition to fire.
if(getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)){
Event e = new Event(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));
result = addSetItem(result, e, localState);
}
}
else{
// The index refers to a continuous variable.
// First check for a rate change event.
LPNContinuousPair ltContPair =
((LPNContinuousPair) ltPair).clone();
IntervalPair ratePair = getRateBounds(ltContPair);
// if(!ratePair.singleValue()
// && (ltContPair.getCurrentRate() == ratePair.getSmallestRate())){
// // The rate represents a range of rates and no rate change
// // event has occured.
// if(ratePair.containsZero()){
// // The rate contians zero, so we need to add two rate
// // events: one for the lower bound and one for the upper
// // bound.
// LPNContinuousPair otherltContPair = ltContPair.clone();
// ltContPair.setCurrentRate(ratePair.get_LowerBound());
// otherltContPair.setCurrentRate(ratePair.get_UpperBound());
// // Create the events.
// Event lowerRateChange = new Event(ltContPair);
// Event upperRateChange = new Event(otherltContPair);
// // Add them to the result set.
// result = addSetItem(result, lowerRateChange, localState);
// result = addSetItem(result, upperRateChange, localState);
// else{
// ltContPair.setCurrentRate(ratePair.getLargestRate());
// result = addSetItem(result,
// new Event(ltContPair), localState);
result = createRateEvents(ltContPair, ratePair, result, localState);
// Check all the inequalities for inclusion.
Variable contVar = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());
if(contVar.getInequalities() != null){
for(InequalityVariable iv : contVar.getInequalities()){
// Check if the inequality can change.
if(ContinuousUtilities.inequalityCanChange(this, iv, localState)){
result = addSetItem(result, new Event(iv), localState);
}
}
}
}
}
// Check the rate zero variables for possible rate change events.
for(LPNContAndRate lcrPair : _rateZeroContinuous.keySet()){
// Get the reference object:
LPNContinuousPair ltContPair = lcrPair.get_lcPair();
// Extract the range of rates.
IntervalPair ratePair = lcrPair.get_rateInterval();
result = createRateEvents(ltContPair, ratePair, result, localState);
}
return result;
}
private LpnTranList createRateEvents(LPNContinuousPair ltContPair, IntervalPair ratePair,
LpnTranList result, State localState){
if(!ratePair.singleValue()
&& (ltContPair.getCurrentRate() == ratePair.getSmallestRate())){
// The rate represents a range of rates and no rate change
// event has occured.
// if(ratePair.containsZero()){
if(ratePair.strictlyContainsZero()){
// The rate contians zero, so we need to add two rate
// events: one for the lower bound and one for the upper
// bound.
LPNContinuousPair otherltContPair = ltContPair.clone();
ltContPair.setCurrentRate(ratePair.get_LowerBound());
otherltContPair.setCurrentRate(ratePair.get_UpperBound());
// Create the events.
Event lowerRateChange = new Event(ltContPair);
Event upperRateChange = new Event(otherltContPair);
// Add them to the result set.
result = addSetItem(result, lowerRateChange, localState);
result = addSetItem(result, upperRateChange, localState);
}
else{
ltContPair.setCurrentRate(ratePair.getLargestRate());
result = addSetItem(result,
new Event(ltContPair), localState);
}
}
return result;
}
/**
* Addes or removes items as appropriate to update the current
* lsit of possible events. Note the type LpnTranList extends
* LinkedList<Transition>. The type EventSet extends transition
* specifically so that objects of EventSet type can be place in
* this list.
* @param EventList
* The list of possible events.
*/
public LpnTranList addSetItem(LpnTranList E, Event e, State s){
// void lhpnAddSetItem(eventSets &E,lhpnEventADT e,ineqList &ineqL,lhpnZoneADT z,
// lhpnRateADT r,eventADT *events,int nevents,
// lhpnStateADT cur_state)
//int rv1l,rv1u,rv2l,rv2u,iZ,jZ;
// Note the LPNTranList plays the role of the eventSets.
int rv1l=0, rv1u=0, rv2l=0, rv2u=0, iZ, jZ;
//#ifdef __LHPN_TRACE__
//printf("lhpnAddSetItem:begin()\n");
//#endif
//#ifdef __LHPN_ADD_ACTION__
//printf("Event sets entering:\n");
//printEventSets(E,events,ineqL);
//printf("Examining event: ");
//printLhpnEvent(e,events,ineqL);
//#endif
//eventSet* eSet = new eventSet();
//eventSets* newE = new eventSets();
//bool done = false;
//bool possible = true;
//eventSets::iterator i;
// Create the new LpnTranlist for holding the events.
EventSet eSet = new EventSet();
LpnTranList newE = new LpnTranList();
boolean done = false;
boolean possible = true;
//if ((e->t == -1) && (e->ineq == -1)) {
if(e.isRate()){
//eSet->insert(e);
eSet.add(e);
//newE->push_back(*eSet);
// I believe that I should actually copy over the old list
// and then add the new event set.
newE = E.copy();
newE.addLast(eSet);
//E.clear();
//E = *newE;
// The previous two commands act to pass the changes of E
// back out of the functions. So returning the new object
// is suficient.
//#ifdef __LHPN_ADD_ACTION__
//printf("Event sets leaving:\n");
//printEventSets(E,events,ineqL);
//#endif
//#ifdef __LHPN_TRACE__
//printf("lhpnAddSetItem:end()\n");
//#endif
//return;
return newE;
}
//if (e->t == -1) {
if(e.isInequality()){
//ineq_update(ineqL[e->ineq],cur_state,nevents);
// Is this necessary, or even correct to update the inequalities.
System.out.println("Note the inequality is not being updated before in addSetItem");
// In this case the Event e represents an inequality.
InequalityVariable ineq = e.getInequalityVariable();
//rv2l = chkDiv(-1 * ineqL[e->ineq]->constant,
// r->bound[ineqL[e->ineq]->place-nevents].current,'C');
//rv2u = chkDiv(ineqL[e->ineq]->constant,
// r->bound[ineqL[e->ineq]->place-nevents].current,'C');
//iZ = getIndexZ(z,-2,ineqL[e->ineq]->place);
// Need to extract the rate.
// To do this, I'll create the indexing object.
Variable v = ineq.getContVariables().get(0);
// Find the LPN.
int lpnIndex = ineq.get_lpn().getLpnIndex();
int varIndex = _lpnList[lpnIndex].
getContinuousIndexMap().getValue(v.getName());
// Package it all up.
// LPNTransitionPair ltPair =
// new LPNTransitionPair(lpnIndex, varIndex, false);
// Note : setting the rate is not necessary since
// this is only being used as aan index.
// LPNContinuousPair ltPair =
// new LPNContinuousPair(lpnIndex, varIndex, 0);
LPNContinuousPair ltPair = new LPNContinuousPair(lpnIndex, varIndex);
rv2l = ContinuousUtilities.chkDiv(-1*ineq.getConstant(),
getCurrentRate(ltPair), true);
rv2u = ContinuousUtilities.chkDiv(ineq.getConstant(),
getCurrentRate(ltPair), true);
iZ = Arrays.binarySearch(_indexToTimerPair, ltPair);
//} else {
}
else{
//iZ = getIndexZ(z,-1,e->t);
// In this case, the event is a transition.
Transition t = e.getTransition();
int lpnIndex = t.getLpn().getLpnIndex();
int tranIndex = t.getIndex();
// Package the results.
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);
iZ = Arrays.binarySearch(_indexToTimerPair, ltPair);
}
//for(i=E.begin();i!=E.end()&&!done;i++) {
// Recall that E contains the events sets which are inherited from the Transition class
// so they can be placed in an LpnTranList. So consider each event set.
for(Transition es : E){
if(!(es instanceof EventSet)){
// This collection should contain event sets, not transitions.
throw new IllegalArgumentException("The eventSet was a Transition object not an EventSet object.");
}
EventSet eventSet = (EventSet) es;
if(done){
// Copy any remaining sets into newE.
newE.add(eventSet.clone());
break;
}
//eventSet* workSet = new eventSet();
// /* Both actions are predicate changes */
// /* Both predicates are on the same variable */
// /* Predicates are on different variables */
// /* New action is predicate change, old is transition firing (case 3) */
// /* TODO: One more ugly case, is it needed? */
// /* New action is transition firing, old is predicate change (case 4) */
// /* TODO: one more ugly case, is it needed? */
/**
* Adds a set item and explicitly sets a flag to remove the next set item
* upon firing.
* @param E
* The list of current event sets.
* @param e
* The event to add.
* @param s
* The current state.
* @param removeNext
* True if afer firing this event, the next event should be removed from the
* queue.
* @return
* The new event set.
*/
public LpnTranList addSetItem(LpnTranList E, Event e, State s,
boolean removeNext){
return null;
}
/**
* Updates the continuous variables that are set by firing a transition.
* @param firedTran
* The transition that fired.
* @param s
* The current (local) state.
*/
public void updateContinuousAssignment(Transition firedTran, State s){
// Get the LPN.
LhpnFile lpn = _lpnList[firedTran.getLpn().getLpnIndex()];
// Get the current values of the (local) state.
HashMap<String,String> currentValues =
lpn.getAllVarsWithValuesAsString(s.getVariableVector());
// Get all the continuous variable assignments.
HashMap<String, ExprTree> assignTrees = firedTran.getContAssignTrees();
for(String contVar : assignTrees.keySet()){
// Get the bounds to assign the continuous variables.
IntervalPair assignment =
assignTrees.get(contVar).evaluateExprBound(currentValues, this, null);
// Make the assignment.
setContinuousBounds(contVar, lpn, assignment);
}
}
/**
* Updates the continuous variables according to the given values.
* @param newContValues
* The new values of the continuous variables.
*/
// public void updateContinuousAssignment(ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues){
// public void updateContinuousAssignment(ArrayList<UpdateContinuous> newAssignValues){
public void updateContinuousAssignment(ContinuousRecordSet newAssignValues){
/*
* In dealing with the rates and continuous variables, there are four cases to consider. These cases
* depend on whether the the old value of the 'current rate' is zero or non-zero and whether the
* new value of the 'current rate' is zero or non-zero.
* 0. old rate is zero, new rate is zero.
* Lookup the zero rate in the _rateZeroContinuous and add any new continuous assignments.
* 1. old rate is zero, new rate is non-zero.
* Remove the rate from the _rateZeroContinuous and add the zone.
* 2. old rate is non-zero, new rate is zero.
* Add the variable with its upper and lower bounds to _rateZeroContinuous.
* 3. old rate is non-zero, new rate is non-zero.
* Get the LPNContinuousPair from the _indexToTimerPair and change the value.
*
* Note: If an assignment is made to the variable, then it should be considered as a
* new variable.
*/
// The updating of the rate-zero continuous variables is taken care of
// by the copyRates. So just need to update the values in the zone.
// This amounts to copying over the values from the old zone for
// continuous variables that haven't changed and copying in
// values for the new vlues.
// final int OLD_ZERO = 0; // Case 0 in description.
// final int NEW_NON_ZERO = 1; // Case 1 in description.
// final int NEW_ZERO = 2; // Case 2 in description.
// final int OLD_NON_ZERO = 3; // Cade 3 in description.
// HashMap<LPNContAndRate, IntervalPair> newNonZero =
// newAssignValues.get(NEW_NON_ZERO);
// HashMap<LPNContAndRate, IntervalPair> oldNonZero =
// newAssignValues.get(OLD_NON_ZERO);
// for(Entry<LPNContAndRate, IntervalPair> pair : newNonZero.entrySet()){
// // Set the lower bound.
// setDbmEntryByPair(pair.getKey()._lcPair,
// LPNTransitionPair.ZERO_TIMER_PAIR, (-1)*pair.getValue().get_LowerBound());
// // Set the upper bound.
// setDbmEntryByPair(pair.getKey().get_lcPair(),
// LPNTransitionPair.ZERO_TIMER_PAIR, pair.getValue().get_UpperBound());
// // Set the rate.
// LPNTransitionPair ltpair = pair.getKey().get_lcPair();
// int index = Arrays.binarySearch(_indexToTimerPair, ltpair);
// _matrix[dbmIndexToMatrixIndex(index)][0] = -1*pair.getKey().get_rateInterval().get_LowerBound();
// _matrix[0][dbmIndexToMatrixIndex(index)] = pair.getKey().get_rateInterval().get_UpperBound();
// for(Entry<LPNContAndRate, IntervalPair> pair : oldNonZero.entrySet()){
// // Set the lower bound.
// setDbmEntryByPair(pair.getKey().get_lcPair(),
// LPNTransitionPair.ZERO_TIMER_PAIR, (-1)*pair.getValue().get_LowerBound());
// // Set the upper bound.
// setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, pair.getKey().get_lcPair(),
// pair.getValue().get_UpperBound());
// int index = Arrays.binarySearch(_indexToTimerPair, pair.getKey().get_lcPair());
// // Set the current rate.
// LPNTransitionPair ltPair = pair.getKey().get_lcPair();
// setCurrentRate(ltPair, pair.getKey().get_lcPair().getCurrentRate());
// // Set the upper and lower bounds for the rates.
// _matrix[dbmIndexToMatrixIndex(index)][0] = -1*pair.getKey().get_rateInterval().get_LowerBound();
// _matrix[0][dbmIndexToMatrixIndex(index)] = pair.getKey().get_rateInterval().get_UpperBound();
}
/* (non-Javadoc)
* @see verification.timed_state_exploration.zone.Zone#getLexicon()
*/
// public HashMap<Integer, Transition> getLexicon(){
// if(_indexToTransition == null){
// return null;
// return new HashMap<Integer, Transition>(_indexToTransition);
// public void setLexicon(HashMap<Integer, Transition> lexicon){
// _indexToTransition = lexicon;
/**
* Gives an array that maps the index of a timer in the DBM to the timer's index.
* @return
* The array that maps the index of a timer in the DBM to the timer's index.
*/
// public int[] getIndexToTimer(){
// return Arrays.copyOf(_indexToTimerPair, _indexToTimerPair.length);
/**
* Calculates a warping value needed to warp a Zone. When a zone is being warped the form
* r1*z2 - r1*z1 + r2*z1 becomes important in finding the new values of the zone. For example,
*
* @param z1
* Upper bound or negative lower bound.
* @param z2
* Relative value.
* @param r1
* First ratio.
* @param r2
* Second ratio.
* @return
* r1*z2 - r1*z1 + r2*z1
*/
public int warp(int z1, int z2, int r1, int r2){
/*
* See "Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets"
* by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda
* Section III.C for details on how this function is used and where it comes
* from.
*/
return r1*z2 - r1*z1 + r2*z1;
}
/**
* Warps this Zone with the aid of rate infomation from the previous Zone.
*
* @param oldZone
* The previous Zone.
* @return
* The warped Zone.
*/
public void dbmWarp(Zone oldZone){
/*
* See "Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets"
* by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda
* Section III.C for details on how this function is used and where it comes
* from.
*/
// return null;
// void lhpnDbmWarp(lhpnStateADT s,eventADT *events,int nevents)
// #ifdef __LHPN_TRACE__
// printf("lhpnDbmWarp:begin()\n");
// #endif
// /* TODO: This appears to NOT work when INFIN is in the bounds?
// Should I have to worry about this case? */
// for(int i=1;i<s->z->dbmEnd;i++) {
// for(int j=i+1;j<s->z->dbmEnd;j++) {
// double iVal = 0.0;
// double jVal = 0.0;
// double iWarp = 0;
// double jWarp = 0;
// double iXDot = 0;
// double jXDot = 0;
// According to atacs comments, this appears to NOT work when
// INFIN is in the bounds.
// This portion of the code handles the warping of the relative
// parts of the zone.
for(int i=1; i< dbmSize(); i++){
for(int j=i+1; j<dbmSize(); j++){
double iVal, jVal, iWarp, jWarp, iXDot, jXDot;
// Note : the iVal and the jVal correspond to the
// alpha and beta describe in Scott Little's thesis.
// /* deal w/ the fact that we might have continuous and discrete
// places */
// #ifdef __LHPN_DEBUG_WARP__
// printf("Working on %d->%d\n",i,j);
// #endif
// if(s->z->curClocks[i].enabling == -2) {
// iVal = fabs((double)s->r->oldBound[s->z->curClocks[i].enabled-nevents].current /
// (double)s->r->bound[s->z->curClocks[i].enabled-nevents].current);
// iWarp = fabs((double)s->r->oldBound[s->z->curClocks[i].enabled-nevents].current);
// iXDot = fabs((double)s->r->bound[s->z->curClocks[i].enabled-nevents].current);
// Do some warping when dealing with the continuous variables.
if(_indexToTimerPair[i] instanceof LPNContinuousPair){
// Calcualte the alpha value.
iVal = Math.floor(Math.abs(
(double) oldZone.getCurrentRate(_indexToTimerPair[i]) /
(double) this.getCurrentRate(_indexToTimerPair[i])));
// The old rate the zone was warped by.
iWarp = Math.floor(Math.abs(
(double) oldZone.getCurrentRate(_indexToTimerPair[i])));
// The current rate rate of this continuous variable.
iXDot = Math.floor(Math.abs(
(double) this.getCurrentRate(_indexToTimerPair[i])));
// I'm not going to do any warping when the previous rate
// is zero. This statement is a break to go to next i value
// and not the next j.
if(iWarp == 0){
break;
}
}
// else {
// iVal = 1.0;
// iWarp = 1.0;
// iXDot = 1.0;
else{
// The current variable is a timer, so the new rate and old rate
// are both 1. Hence we have
iVal = 1.0;
iWarp = 1.0;
iXDot = 1.0;
}
// if(s->z->curClocks[j].enabling == -2) {
// jVal = fabs((double)s->r->oldBound[s->z->curClocks[j].enabled-nevents].current /
// (double)s->r->bound[s->z->curClocks[j].enabled-nevents].current);
// jWarp = fabs((double)s->r->oldBound[s->z->curClocks[j].enabled-nevents].current);
// jXDot = fabs((double)s->r->bound[s->z->curClocks[j].enabled-nevents].current);
// Do some warping of the second variable if it is a continuous variable.
if(_indexToTimerPair[j] instanceof LPNContinuousPair){
// Calcualte the alpha value.
jVal = Math.floor(Math.abs(
(double) oldZone.getCurrentRate(_indexToTimerPair[j]) /
(double) this.getCurrentRate(_indexToTimerPair[j])));
// The old rate the zone was warped by.
jWarp = Math.floor(Math.abs(
(double) oldZone.getCurrentRate(_indexToTimerPair[j])));
// The current rate of this continuous variable.
jXDot = Math.floor(Math.abs(
(double) this.getCurrentRate(_indexToTimerPair[j])));
// I'm not going to do any warping when the previous rate is
// zero.
if(jWarp == 0){
continue;
}
}
// else {
// jVal = 1.0;
// jWarp = 1.0;
// jXDot = 1.0;
else{
// The current variable is a timer, so the new rate and old rate
// are both 1. Hence we have
jVal = 1.0;
jWarp = 1.0;
jXDot = 1.0;
}
// #ifdef __LHPN_DEBUG_WARP__
// printf("iVal: %f, jVal: %f, iWarp: %f, jWarp: %f, iXDot: %f, jXDot: %f\n",iVal,jVal,iWarp,jWarp,iXDot,jXDot);
// /* printf("calc1- jWarp:%d * s->z->matrix[i][j]:%d / jXDot:%d + (-1 * jWarp:%d * s->z->matrix[i][0]:%d) / jXDot:%d + (iWarp:%d * s->z->matrix[i][0]:%d) / iXDot:%d = %d 1:%d 2:%d 3:%d -- %d\n", jWarp,s->z->matrix[i][j],jXDot,jWarp,s->z->matrix[i][0],jXDot,iWarp,s->z->matrix[i][0],iXDot,(chkDiv((jWarp * s->z->matrix[i][j]),jXDot,'C') + chkDiv((-1 * jWarp * s->z->matrix[i][0]),jXDot,'C') + chkDiv((iWarp * s->z->matrix[i][0]),iXDot,'C')),chkDiv((jWarp * s->z->matrix[i][j]),jXDot,'C'),chkDiv((-1 * jWarp * s->z->matrix[i][0]),jXDot,'C'),chkDiv((iWarp * s->z->matrix[i][0]),iXDot,'C'),(int)ceil(((jWarp * s->z->matrix[i][j])/jXDot) +((-1 * jWarp * s->z->matrix[i][0])/jXDot) + ((iWarp * s->z->matrix[i][0])/iXDot))); */
// /* printf("calc2-jWarp:%f * s->z->matrix[j][i]):%d/jXDot:%f) + ((-1 * jWarp:%f * s->z->matrix[0][i]:%d)/jXDot:%f) + ((iWarp:%f * s->z->matrix[0][i]):%d,iXDot:%f)) = %d 1:%f 2:%f 3:%f\n",jWarp,s->z->matrix[j][i],jXDot,jWarp,s->z->matrix[0][i],jXDot,iWarp,s->z->matrix[0][i],iXDot,(int) ceil(((jWarp * s->z->matrix[j][i])/jXDot) + ((-1 * jWarp * s->z->matrix[0][i])/jXDot) + ((iWarp * s->z->matrix[0][i]),iXDot)),((jWarp * (double)s->z->matrix[j][i])/jXDot),((-1 * jWarp * (double)s->z->matrix[0][i])/jXDot),(iWarp * (double)s->z->matrix[0][i])/iXDot); */
// #endif
// if(iVal > jVal) {
// /* s->z->matrix[i][j] = */
// /* chkDiv((jWarp * s->z->matrix[i][j]),jXDot,'C') + */
// /* chkDiv((-1 * jWarp * s->z->matrix[i][0]),jXDot,'C') + */
// /* chkDiv((iWarp * s->z->matrix[i][0]),iXDot,'C'); */
// /* s->z->matrix[j][i] = */
// /* chkDiv((jWarp * s->z->matrix[j][i]),jXDot,'C') + */
// /* chkDiv((-1 * jWarp * s->z->matrix[0][i]),jXDot,'C') + */
// /* chkDiv((iWarp * s->z->matrix[0][i]),iXDot,'C'); */
// s->z->matrix[i][j] = (int)
// ceil(((jWarp * s->z->matrix[i][j])/jXDot) +
// ((-1 * jWarp * s->z->matrix[i][0])/jXDot) +
// ((iWarp * s->z->matrix[i][0])/iXDot));
// s->z->matrix[j][i] = (int)
// ceil(((jWarp * s->z->matrix[j][i])/jXDot) +
// ((-1 * jWarp * s->z->matrix[0][i])/jXDot) +
// ((iWarp * s->z->matrix[0][i])/iXDot));
// The zone is warped differently depending on which of rate is
// larger. See Scott Little's Thesis for more details.
if(iVal > jVal){
setDbmEntry(j, i, (int)
Math.ceil(((jWarp*getDbmEntry(j, i))/jXDot) +
((-1*jWarp*getDbmEntry(0, i)/jXDot)) +
((iWarp*getDbmEntry(0, i)/iXDot))));
setDbmEntry(i, j, (int)
Math.ceil(((jWarp*getDbmEntry(i, j))/jXDot) +
((-1*jWarp*getDbmEntry(i, 0)/jXDot)) +
((iWarp*getDbmEntry(i, 0)/iXDot))));
}
// else {
// /* s->z->matrix[j][i] = */
// /* chkDiv((iWarp * s->z->matrix[j][i]),iXDot,'C') + */
// /* chkDiv((-1 * iWarp * s->z->matrix[j][0]),iXDot,'C') + */
// /* chkDiv((jWarp * s->z->matrix[j][0]),jXDot,'C'); */
// /* s->z->matrix[i][j] = */
// /* chkDiv((iWarp * s->z->matrix[i][j]),iXDot,'C') + */
// /* chkDiv((-1 * iWarp * s->z->matrix[0][j]),iXDot,'C') + */
// /* chkDiv((jWarp * s->z->matrix[0][j]),jXDot,'C'); */
// s->z->matrix[j][i] = (int)
// ceil(((iWarp * s->z->matrix[j][i])/iXDot) +
// ((-1 * iWarp * s->z->matrix[j][0])/iXDot) +
// ((jWarp * s->z->matrix[j][0])/jXDot));
// s->z->matrix[i][j] = (int)
// ceil(((iWarp * s->z->matrix[i][j])/iXDot) +
// ((-1 * iWarp * s->z->matrix[0][j])/iXDot) +
// ((jWarp * s->z->matrix[0][j])/jXDot));
else{
setDbmEntry(i, j, (int)
Math.ceil(((iWarp*getDbmEntry(i, j))/iXDot) +
((-1*iWarp*getDbmEntry(0, j)/iXDot)) +
((jWarp*getDbmEntry(0, j)/jXDot))));
setDbmEntry(j, i, (int)
Math.ceil(((iWarp*getDbmEntry(j, i))/iXDot) +
((-1*iWarp*getDbmEntry(j, 0)/iXDot)) +
((jWarp*getDbmEntry(j, 0)/jXDot))));
}
}
}
// #ifdef __LHPN_DEBUG_WARP__
// printf("After fixing up initial warp conditions.\n");
// printZ(s->z,events,nevents,s->r);
// #endif
// for(int i=1;i<s->z->dbmEnd;i++) {
// if(s->z->curClocks[i].enabling == -2) {
// Handle the warping of the bounds.
for(int i=1; i<dbmSize(); i++){
if(_indexToTimerPair[i] instanceof LPNContinuousPair){
// #ifdef __LHPN_DEBUG_WARP__
// printf("old:%d new:%d v1:%d v2:%d\n",s->r->oldBound[s->z->curClocks[i].enabled-nevents].current,s->r->bound[s->z->curClocks[i].enabled-nevents].current,s->z->matrix[0][i],s->z->matrix[i][0]);
// #endif
// if(abs(s->z->matrix[0][i]) != INFIN) {
// s->z->matrix[0][i] =
// chkDiv((abs(s->r->oldBound[s->z->curClocks[i].enabled-nevents].current)
// * s->z->matrix[0][i]),
// abs(s->r->bound[s->z->curClocks[i].enabled-nevents].current)
if(Math.abs(getDbmEntry(i, 0)) != INFINITY ){
if(oldZone.getCurrentRate(_indexToTimerPair[i]) == 0){
// If the older rate was zero, then we just need to
// divide by the new rate.
setDbmEntry(i, 0, ContinuousUtilities.chkDiv(
getDbmEntry(i,0),
Math.abs(getCurrentRate(_indexToTimerPair[i])),
true));
}
else{
// Undo the old warping and introduce the new warping.
// If the bound is infinite, then division does nothing.
setDbmEntry(i, 0, ContinuousUtilities.chkDiv(
Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i]))
* getDbmEntry(i, 0),
Math.abs(getCurrentRate(_indexToTimerPair[i])),
true));
}
}
// if(abs(s->z->matrix[i][0]) != INFIN) {
// s->z->matrix[i][0] =
// chkDiv((abs(s->r->oldBound[s->z->curClocks[i].enabled-nevents].current)
// * s->z->matrix[i][0]),
// abs(s->r->bound[s->z->curClocks[i].enabled-nevents].current)
if(Math.abs(getDbmEntry(0, i)) != INFINITY){
if(oldZone.getCurrentRate(_indexToTimerPair[i]) == 0){
setDbmEntry(0, i, ContinuousUtilities.chkDiv(
getDbmEntry(0,i),
Math.abs(getCurrentRate(_indexToTimerPair[i])),
true));
}
else{
// Undo the old warping and introduce the new warping.
// If the bound is inifite, then division does nothing.
setDbmEntry(0, i, ContinuousUtilities.chkDiv(
Math.abs(oldZone.getCurrentRate(_indexToTimerPair[i]))
* getDbmEntry(0, i),
Math.abs(getCurrentRate(_indexToTimerPair[i])),
true));
}
}
}
}
// #ifdef __LHPN_DEBUG_WARP__
// printf("After fixing up places.\n");
// printZ(s->z,events,nevents,s->r);
// #endif
// for(int i=1;i<s->z->dbmEnd;i++) {
// if(s->z->curClocks[i].enabling == -2) {
for(int i=1; i<dbmSize(); i++){
if(_indexToTimerPair[i] instanceof LPNContinuousPair){
// #ifdef __LHPN_DEBUG_WARP__
// printf("Warp: %d\n",s->r->oldBound[s->z->curClocks[i].enabled-nevents].current);
// #endif
// if(((float)s->r->oldBound[s->z->curClocks[i].enabled-nevents].current /
// (float)s->r->bound[s->z->curClocks[i].enabled-nevents].current) < 0.0) {
// /* swap */
// int temp = s->z->matrix[0][i];
// s->z->matrix[0][i] = s->z->matrix[i][0];
// s->z->matrix[i][0] = temp;
// for(int j=1;j<s->z->dbmEnd;j++) {
// /* TBD: If i & j are both changing direction do we need to
// remove the warp info? */
// if(i != j) {
// s->z->matrix[j][i] = INFIN;
// s->z->matrix[i][j] = INFIN;
// Handle the case when the warping takes us into negative space.
if((double) oldZone.getCurrentRate(_indexToTimerPair[i])/
(double) this.getCurrentRate(_indexToTimerPair[i]) < 0.0){
/* We are warping into the negative space, so swap the upper and
* lower bounds.
*/
int temp = getDbmEntry(i, 0);
setDbmEntry(i,0, getDbmEntry(0, i));
setDbmEntry(0, i, temp);
// Set the relationships to Infinity since nothing else is known.
for(int j=1; j<dbmSize(); j++){
if(i != j){
setDbmEntry(i, j, INFINITY);
setDbmEntry(j, i, INFINITY);
}
}
}
}
}
// #ifdef __LHPN_DEBUG_WARP__
// printf("After handling negative warps.\n");
// printZ(s->z,events,nevents,s->r);
// #endif
// for(int i=1;i<s->z->dbmEnd;i++) {
// if(s->z->curClocks[i].enabling == -2) {
// for(int i=1; i<dbmSize(); i++){
// if(_indexToTimerPair[i] instanceof LPNContinuousPair){
// int newCwarp = s->r->bound[s->z->curClocks[i].enabled-nevents].current;
// int newLwarp = s->r->bound[s->z->curClocks[i].enabled-nevents].lower;
// int newUwarp = s->r->bound[s->z->curClocks[i].enabled-nevents].upper;
// s->r->oldBound[s->z->curClocks[i].enabled-nevents].current = newCwarp;
// s->r->oldBound[s->z->curClocks[i].enabled-nevents].lower = newLwarp;
// s->r->oldBound[s->z->curClocks[i].enabled-nevents].upper = newUwarp;
// #ifdef __LHPN_DEBUG_WARP__
// printf("New warp for %d: %d\n",i,s->r->oldBound[s->z->curClocks[i].enabled-nevents].current);
// #endif
/* Do the nature of how I store things, I do not think I need to do
* this portion.
*/
// #ifdef __LHPN_DEBUG_WARP__
// printf("Before recanon.\n");
// printZ(s->z,events,nevents,s->r);
// #endif
// recanonZ(s->z);
// #ifdef __LHPN_DEBUG_WARP__
// printf("After recanon.\n");
// printZ(s->z,events,nevents,s->r);
// #endif
}
/**
* The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion.
* The intention is for this exception to be thrown is a Zone has a non zero
* entry appear on the diagonal.
*
* @author Andrew N. Fisher
*
*/
public class DiagonalNonZeroException extends java.lang.RuntimeException
{
/**
* Generated serialVersionUID.
*/
private static final long serialVersionUID = -3857736741611605411L;
/**
* Creates a DiagonalNonZeroException.
* @param Message
* The message to be displayed when the exception is thrown.
*/
public DiagonalNonZeroException(String Message)
{
super(Message);
}
}
/**
* This exception is thrown when trying to merge two zones whose corresponding timers
* do not agree.
* @author Andrew N. Fisher
*
*/
// public class IncompatibleZoneException extends java.lang.RuntimeException
// // TODO : Check if this class can be removed.
// /**
// * Generated serialVersionUID
// */
// private static final long serialVersionUID = -2453680267411313227L;
// public IncompatibleZoneException(String Message)
// super(Message);
/**
* Clears out the lexicon.
*/
// public static void clearLexicon(){
// _indexToTransition = null;
private IntervalPair parseRate(String rate){
String rateNoSpaces = rate.trim();
// First check if the string is a single number.
// Integer i = Integer.parseInt(rate);
// if(i != null){
// // The string is a number, so set the upper and lower bounds equal.
// return new IntervalPair(i,i);
// First check for a comma (representing an interval input).
int commaIndex = rateNoSpaces.indexOf(",");
if(commaIndex < 0){
// Assume that the string is a constant. A NumberFormatException
// will be thrown otherwise.
int i = Integer.parseInt(rate);
return new IntervalPair(i,i);
}
String lowerString = rateNoSpaces.substring(1, commaIndex).trim();
String upperString = rateNoSpaces.substring(commaIndex+1,
rateNoSpaces.length()-1).trim();
return new IntervalPair(Integer.parseInt(lowerString),
Integer.parseInt(upperString));
}
/**
* Get the list of LhpnFile objects that this Zone depends on.
* @return
* The lits of LhpnFile objects that this Zone depends on.
*/
public LhpnFile[] get_lpnList(){
return _lpnList;
}
/**
* Performs a division of two integers and either takes the ceiling or the floor. Note :
* The integers are converted to doubles for the division so the choice of ceiling or floor is
* meaningful.
* @param top
* The numerator.
* @param bottom
* The denominator.
* @param ceil
* True indicates return the ceiling and false indicates return the floor.
* @return
* Returns the ceiling of top/bottom if ceil is true and the floor of top/bottom otherwise.
*/
// public int chkDiv(int top, int bottom, Boolean ceil){
// /*
// * This method was taken from atacs/src/hpnrsg.c
// */
// int res = 0;
// if(top == INFINITY ||
// top == INFINITY * -1) {
// if(bottom < 0) {
// return top * -1;
// return top;
// if(bottom == INFINITY) {
// return 0;
// if(bottom == 0) {
// System.out.println("Warning: Divided by zero.");
// bottom = 1;
// double Dres,Dtop,Dbottom;
// Dtop = top;
// Dbottom = bottom;
// Dres = Dtop/Dbottom;
// if(ceil) {
// res = (int)Math.ceil(Dres);
// else if(!ceil) {
// res = (int)Math.floor(Dres);
// return res;
public int getCurrentRate(LPNTransitionPair contVar){
if(!(contVar instanceof LPNContinuousPair)){
// The LPNTransitionsPair does not refer to a continuous variable, so yell.
throw new IllegalArgumentException("Zone.getCurrentRate was called" +
" on an LPNTransitionPair that was not an LPNContinuousPair.");
}
LPNContinuousPair cV = (LPNContinuousPair) contVar;
// Search for the pair in the zone.
int index = Arrays.binarySearch(_indexToTimerPair, cV);
if(index >0){
// The continuous variable was found amongst the non zero rate continuous variables.
// Grab that indexing object instead since it has the rate.
cV = (LPNContinuousPair) _indexToTimerPair[index];
return cV.getCurrentRate();
}
else{
// Since the variable was not found in the non-zero rate continuous
// variables, assume the rate is zero.
return 0;
}
}
/**
* Sets the current rate for a continuous variable. It sets the rate regardless of
* whether the variable is in the rate zero portion of the Zone or not. But it
* does not move variables in and out of the zone.
* @param contVar
* The index of the variable whose rate is going to be set.
* @param currentRate
* The value of the rate.
*/
public void setCurrentRate(LPNTransitionPair contVar, int currentRate){
if(!(contVar instanceof LPNContinuousPair)){
// The LPNTransitionsPair does not refer to a continuous variable, so yell.
throw new IllegalArgumentException("Zone.getCurrentRate was called" +
" on an LPNTransitionPair that was not an LPNContinuousPair.");
}
LPNContinuousPair cV = (LPNContinuousPair) contVar;
// Check for the current variable in the rate zero variables.
VariableRangePair variableRange = _rateZeroContinuous.
getValue(new LPNContAndRate(cV, new IntervalPair(0,0)));
if(variableRange != null){
LPNContinuousPair lcPair = (LPNContinuousPair)_rateZeroContinuous.
getKey(variableRange).get_lcPair();
lcPair.setCurrentRate(currentRate);
return;
}
// Check for the current variable in the Zone varaibles.
int index = Arrays.binarySearch(_indexToTimerPair, contVar);
if(index >= 0){
// The variable was found, set the rate.
LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[index];
lcPair.setCurrentRate(currentRate);
}
}
/**
* Adds a transition to a zone.
* @param newTransitions
* The newly enabled transitions.
* @return
* The result of adding the transition.
*/
public Zone addTransition(HashSet<LPNTransitionPair> newTransitions, State[] localStates){
/*
* The zone will remain the same for all the continuous variables.
* The only thing that will change is a new transition will be added into the transitions.
*/
// Create a Zone to alter.
Zone newZone = new Zone();
// Create a copy of the LPN list.
newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);
// Copy the rate zero continuous variables.
newZone._rateZeroContinuous = this._rateZeroContinuous.clone();
// Create a copy of the current indexing pairs.
//newZone._indexToTimerPair = Arrays.copyOf(_indexToTimerPair, _indexToTimerPair.length);
newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + newTransitions.size()];
for(int i=0; i<_indexToTimerPair.length; i++){
newZone._indexToTimerPair[i] = _indexToTimerPair[i];
}
// Add the new transitions to the _indexToTimerPair list.
// for(int i=_indexToTimerPair.length; i<newZone._indexToTimerPair.length; i++){
// // Set up the index for the newTransitions list.
// int newTransitionIndex = i-_indexToTimerPair.length;
// newZone._indexToTimerPair[i] = newTransitions[newTransitionIndex];
int i = _indexToTimerPair.length;
for(LPNTransitionPair ltPair : newTransitions){
newZone._indexToTimerPair[i++] = ltPair;
}
// Sort the _indexToTimerPair list.
Arrays.sort(newZone._indexToTimerPair);
// Create matrix.
newZone._matrix = new int[newZone._indexToTimerPair.length+1][newZone._indexToTimerPair.length+1];
// Convert the current transitions to a collection of transitions.
HashSet<LPNTransitionPair> oldTransitionSet = new HashSet<LPNTransitionPair>();
for(LPNTransitionPair ltPair : _indexToTimerPair){
oldTransitionSet.add(ltPair);
}
// Copy in the new transitions.
newZone.copyTransitions(this, newTransitions, oldTransitionSet, localStates);
// newZone.advance(localStates);
// newZone.recononicalize();
return newZone;
}
/**
* This method creates a zone identical to the current zone except all the current rates are turned to 1.
* This is to provide a previous zone to the initial zone for warping.
* @return
* A zone identical to this zone with all rates set to 1.
*/
private Zone beforeInitialZone(){
Zone z = this.clone();
// for(int i=1; _indexToTimerPair[i] instanceof LPNContinuousPair; i++){
for(int i=1; i<z._indexToTimerPair.length; i++){
if(!(z._indexToTimerPair[i] instanceof LPNContinuousPair)){
break;
}
LPNContinuousPair lcPair = (LPNContinuousPair) z._indexToTimerPair[i];
lcPair.setCurrentRate(1);
}
return z;
}
/**
* Returns a new Zone that has added into the DBM portion the given
* continuous varaible that used to be in the zone.
* @param ltContPair The continuous varaible to move from the rate zero
* variables.
* @return The resulting Zone.
*/
public Zone moveOldRateZero(LPNContinuousPair ltContPair) {
// Create a Zone to alter.
Zone newZone = new Zone();
// Create a copy of the LPN list.
newZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);
// Copy the rate zero continuous variables.
newZone._rateZeroContinuous = this._rateZeroContinuous.clone();
// Extract the continuous variable from the rate zero variables.
LPNContAndRate rateZero = new LPNContAndRate(ltContPair,
new IntervalPair(0,0));
// This gets the values for the continuous variable.
VariableRangePair vrp = newZone._rateZeroContinuous.get(rateZero);
IntervalPair values = vrp.get_range();
// This replaces the rateZero with the one stored in the _rateZeroContinuous.
// The purpose of this is to obtain the stored range of rates.
rateZero = newZone._rateZeroContinuous.getKey(vrp);
// Get the range of rates.
IntervalPair rangeOfRates = rateZero.get_rateInterval();
// Remove the continuous variable.
newZone._rateZeroContinuous.delete(rateZero);
// Create a copy of the current indexing pairs.
//newZone._indexToTimerPair = Arrays.copyOf(_indexToTimerPair, _indexToTimerPair.length);
newZone._indexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length + 1];
for(int i=0; i<_indexToTimerPair.length; i++){
newZone._indexToTimerPair[i] = _indexToTimerPair[i];
}
// Add the continuous variable to the list of variables/transition in the DBM.
int numOfTransitions = _indexToTimerPair.length;
newZone._indexToTimerPair[numOfTransitions] = ltContPair;
// Sort the _indexToTimerPair list.
Arrays.sort(newZone._indexToTimerPair);
// Create matrix.
newZone._matrix = new int[newZone._indexToTimerPair.length+1][newZone._indexToTimerPair.length+1];
// Convert the current transitions to a collection of transitions.
HashSet<LPNTransitionPair> oldTransitionSet = new HashSet<LPNTransitionPair>();
for(LPNTransitionPair ltPair : _indexToTimerPair){
oldTransitionSet.add(ltPair);
}
// Copy in the new transitions.
newZone.copyTransitions(this, new HashSet<LPNTransitionPair>(),
oldTransitionSet, null);
// Get the index for the variable.
int index = Arrays.binarySearch(newZone._indexToTimerPair, ltContPair);
// Copy in the upper and lower bound of the old rate zero variable.
// newZone.setLowerBoundByLPNTransitionPair(ltContPair,
// rangeOfRates.get_LowerBound());
// newZone.setUpperBoundByLPNTransitionPair(ltContPair,
// rangeOfRates.get_UpperBound());
// Copy in the range of rates.
newZone.setLowerBoundbydbmIndex(index, rangeOfRates.get_LowerBound());
newZone.setUpperBoundbydbmIndex(index, rangeOfRates.get_UpperBound());
if(ltContPair.getCurrentRate()>0){
// Set the upper and lower bounds.
newZone.setDbmEntry(0, index,
ContinuousUtilities.chkDiv(values.get_UpperBound(),
ltContPair.getCurrentRate(), true));
newZone.setDbmEntry(index, 0,
ContinuousUtilities.chkDiv(-1*values.get_LowerBound(),
ltContPair.getCurrentRate(), true));
}
else{
// Set the upper and lower bounds. Since the rate is zero
// We swap the real upper and lower bounds.
newZone.setDbmEntry(0, index,
ContinuousUtilities.chkDiv(values.get_LowerBound(),
ltContPair.getCurrentRate(), true));
newZone.setDbmEntry(index, 0,
ContinuousUtilities.chkDiv(-1*values.get_UpperBound(),
ltContPair.getCurrentRate(), true));
}
// Set the DBM to having no relating information for how this
// variables relates to the other variables.
for(int i=1; i<newZone._indexToTimerPair.length; i++){
if(i == index){
continue;
}
else{
newZone.setDbmEntry(index, i, Zone.INFINITY);
newZone.setDbmEntry(i, index, Zone.INFINITY);
}
}
// newZone.advance(localStates);
newZone.recononicalize();
return newZone;
}
/**
* Determines whether time has advanced far enough for an inequality to change
* truth value.
* @param ineq
* The inequality to test whether its truth value can change.
* @param localState
* The state associated with the inequality.
* @return
* True if the inequality can change truth value, false otherwise.
*/
// private boolean inequalityCanChange(InequalityVariable ineq, State[] localStates){
// private boolean inequalityCanChange(InequalityVariable ineq, State localState){
// // Find the index of the continuous variable this inequality refers to.
// // I'm assuming there is a single variable.
// LhpnFile lpn = ineq.get_lpn();
// Variable contVar = ineq.getInequalities().get(0);
// DualHashMap<String, Integer> variableIndecies = lpn.getContinuousIndexMap();
// int contIndex = variableIndecies.get(contVar);
// // Package up the information into a the index. Note the current rate doesn't matter.
// LPNContinuousPair index = new LPNContinuousPair(lpn.getLpnIndex(), contIndex, 0);
// // Get the current rate.
// int currentRate = getCurrentRate(index);
// // Get the current value of the inequality. This requires looking into the current state.
//// int currentValue = localStates[lpn.getLpnIndex()].getCurrentValue(contIndex);
// int currentValue = localState.getCurrentValue(contIndex);
// // Get the Zone index of the variable.
// int zoneIndex = Arrays.binarySearch(_indexToTimerPair, index);
//// bool lhpnPredCanChange(ineqADT ineq,lhpnZoneADT z,lhpnRateADT r,
//// lhpnMarkingADT m,eventADT *events,int nevents,
//// lhpnStateADT s)
////ineq_update(ineq,s,nevents);
////#ifdef __LHPN_TRACE__
////printf("lhpnPredCanChange:begin()\n");
////#endif
////#ifdef __LHPN_PRED_DEBUG__
////printf("lhpnPredCanChange Examining: ");
////printI(ineq,events);
////printf("signal = %c, %d",s->m->state[ineq->signal],r->bound[ineq->place-nevents].current);
////printf("\n");
////if (r->bound[ineq->place-nevents].current != 0)
////printf("divRes: %d\n",chkDiv(ineq->constant,
//// r->bound[ineq->place-nevents].current,'F'));
////#endif
////
////if(ineq->type == 0 || ineq->type == 1) {
// if(ineq.get_op().contains(">")){
////int zoneP = getIndexZ(z,-2,ineq->place);
////if(zoneP == -1) {
////warn("An inequality produced a place not in the zone.");
////return false;
////if(r->bound[ineq->place-nevents].current < 0 &&
////m->state[ineq->signal] == '1') {
// // First check cases when the rate is negative.
// if(currentRate < 0 && currentValue != 0){
////if((-1)*z->matrix[zoneP][0] <=
//// (-1)*chkDiv(ineq->constant,r->bound[ineq->place-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("predCanChange:1\n");
//// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
//// return true;
// if((-1) * getDbmEntry(0, zoneIndex) <=
// (-1)*chkDiv(ineq.getConstant(), currentRate, false)){
// return true;
////} else {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("predCannotChange:1\n");
//// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
//// return false;
// else{
// return false;
////else if(r->bound[ineq->place-nevents].current > 0 &&
//// m->state[ineq->signal] == '0') {
// else if(currentRate > 0 && currentValue == 0){
////if(z->matrix[zoneP][0] >=
//// chkDiv(ineq->constant,r->bound[ineq->place-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("predCanChange:2\n");
//// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
//// return true;
// if(getDbmEntry(0, zoneIndex) <=
// chkDiv(ineq.getConstant(), currentRate, false)){
// return true;
////} else {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("predCannotChange:2\n");
//// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
////return false;
// else{
// return false;
////else {
////#ifdef __LHPN_PRED_DEBUG__
////printf("predCannotChange:3\n");
////printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
////return false;
////
////else if(ineq->type == 2 || ineq->type == 3) {
// else if(ineq.get_op().contains("<")){
////int zoneP = getIndexZ(z,-2,ineq->place);
////if(zoneP == -1) {
////warn("An inequality produced a place not in the zone.");
////return false;
////if(r->bound[ineq->place-nevents].current < 0 &&
////m->state[ineq->signal] == '0') {
// if(currentRate < 0 && currentValue == 0){
////if((-1)*z->matrix[zoneP][0] <=
//// (-1)*chkDiv(ineq->constant,r->bound[ineq->place-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("predCanChange:4\n");
//// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
//// return true;
// if((-1) * getDbmEntry(0, zoneIndex) <=
// (-1)*chkDiv(ineq.getConstant(), currentRate, false)){
// return true;
////} else {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("predCannotChange:4\n");
//// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
//// return false;
// else{
// return false;
////else if(r->bound[ineq->place-nevents].current > 0 &&
//// m->state[ineq->signal] == '1') {
// else if (currentRate > 0 &&
// currentValue != 0){
////if(z->matrix[zoneP][0] >=
//// chkDiv(ineq->constant,r->bound[ineq->place-nevents].current,'F')) {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("predCanChange:5\n");
//// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
//// return true;
// if(getDbmEntry(0, zoneIndex) >=
// chkDiv(ineq.getConstant(), currentRate, false)){
// return true;
////} else {
////#ifdef __LHPN_PRED_DEBUG__
//// printf("predCannotChange:5\n");
//// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
//// return false;
// else {
// return false;
////else {
////#ifdef __LHPN_PRED_DEBUG__
////printf("predCanChange:6\n");
////printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
////return false;
// else {
// return false;
////#ifdef __LHPN_PRED_DEBUG__
////printf("predCanChange:7\n");
////printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
//// m->state[ineq->signal]);
////#endif
////return false;
// return false;
}
|
package verification.timed_state_exploration.zoneProject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import lpn.parser.ExprTree;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import lpn.parser.Variable;
import verification.platu.lpn.DualHashMap;
import verification.platu.lpn.LpnTranList;
import verification.platu.stategraph.State;
/**
* This class is for storing and manipulating timing zones via difference bound matrices.
* The underlying structure is backed by a two dimensional array. A difference bound
* matrix has the form
* t0 t1 t2 t3
* t0 m00 m01 m02 m03
* t1 m10 m11 m12 m13
* t2 m20 m21 m22 m23
* t3 m30 m31 m32 m33
* where tj - ti<= mij. In particular, m0k is an upper bound for tk and -mk is a lower
* bound for tk.
*
* The timers are referred to by an index.
*
* This class also contains a public nested class DiagonalNonZeroException which extends
* java.lang.RuntimeException. This exception may be thrown if the diagonal entries of a
* zone become nonzero.
*
* @author Andrew N. Fisher
*
*/
public class Zone{
// Abstraction Function :
// The difference bound matrix is represented by int[][].
// In order to keep track of the upper and lower bounds of timers from when they are first
// enabled, the matrix will be augmented by a row and a column. The first row will contain
// the upper bounds and the first column will contain the negative of the lower bounds.
// For one timer t1 that is between 2 and 3, we might have
// lb t0 t1
// ub x 0 3
// t0 0 m m
// t1 -2 m m
// where x is not important (and will be given a zero value), 3 is the upper bound on t1
// and -2 is the negative of the lower bound. The m values represent the actual difference
// bound matrix. Also note that the column heading are not part of the stored representation
// lb stands for lower bound while ub stands for upper bound.
// This upper and lower bound information is called the Delay for a Transition object.
// Since a timer is tied directly to a Transition, the timers are index by the corresponding
// Transition's index in a LPNTranslator.
// The timers are named by an integer referred to as the index. The _indexToTimer array
// connects the index in the DBM sub-matrix to the index of the timer. For example,
// a the timer t1
// Representation invariant :
// Zones are immutable.
// Integer.MAX_VALUE is used to logically represent infinity.
// The lb and ub values for a timer should be set when the timer is enabled.
// A negative hash code indicates that the hash code has not been set.
// The index of the timer in _indexToTimer is the index in the DBM and should contain
// the zeroth timer.
// The array _indexToTimerPair should always be sorted.
// The index of the LPN should match where it is in the _lpnList, that is, if lpn is
// and LhpnFile object in _lpnList, then _lpnList[getLpnIndex()] == lpn.
/*
* Resource List :
* TODO : Create a list reference where the algorithms can be found that this class
* depends on.
*/
public static final int INFINITY = Integer.MAX_VALUE;
/* The lower and upper bounds of the times as well as the dbm. */
private int[][] _matrix;
/* Maps the index to the timer. The index is row/column of the DBM sub-matrix.
* Logically the zero timer is given index -1.
* */
//private int[] _indexToTimer;
private LPNTransitionPair[] _indexToTimerPair;
/* The hash code. */
private int _hashCode;
/* A lexicon between a transitions index and its name. */
//private static HashMap<Integer, Transition> _indexToTransition;
/* Set if a failure in the testSplit method has fired already. */
//private static boolean _FAILURE = false;
/* Hack to pass a parameter to the equals method though a variable */
//private boolean subsetting = false;
/* Stores the continuous variables that have rate zero */
// HashMap<LPNTransitionPair, Variable> _rateZeroContinuous;
//DualHashMap<RangeAndPairing, Variable> _rateZeroContinuous;
DualHashMap<LPNTransitionPair, VariableRangePair> _rateZeroContinuous;
/* Records the largest zone that occurs. */
public static int ZoneSize = 0;
private void checkZoneMaxSize(){
if(dbmSize() > ZoneSize){
ZoneSize = dbmSize();
}
}
private LhpnFile[] _lpnList;
/*
* Turns on and off subsets for the zones.
* True means subset will be considered.
* False means subsets will not be considered.
*/
private static boolean _subsetFlag = true;
/*
* Turns on and off supersets for zones.
* True means that supersets will be considered.
* False means that supersets will not be considered.
*/
private static boolean _supersetFlag = true;
/**
* Gets the value of the subset flag.
* @return
* True if subsets are requested, false otherwise.
*/
public static boolean getSubsetFlag(){
return _subsetFlag;
}
/**
* Sets the value of the subset flag.
* @param useSubsets
* The value for the subset flag. Set to true if
* supersets are to be considered, false otherwise.
*/
public static void setSubsetFlag(boolean useSubsets){
_subsetFlag = useSubsets;
}
/**
* Gets the value of the superset flag.
* @return
* True if supersets are to be considered, false otherwise.
*/
public static boolean getSupersetFlag(){
return _supersetFlag;
}
/**
* Sets the superset flag.
* @param useSupersets
* The value of the superset flag. Set to true if
* supersets are to be considered, false otherwise.
*/
public static void setSupersetFlag(boolean useSupersets){
_supersetFlag = useSupersets;
}
/**
* Construct a zone that has the given timers.
* @param timers
* The ith index of the array is the index of the timer. For example,
* if timers = [1, 3, 5], then the zeroth row/column of the DBM is the
* timer of the transition with index 1, the first row/column of the
* DBM is the timer of the transition with index 3, and the 2nd
* row/column is the timer of the transition with index 5. Do not
* include the zero timer.
* @param matrix
* The DBM augmented with the lower and upper bounds of the delays for the
* transitions. For example, suppose a zone has timers [1, 3, 5] (as
* described in the timers parameters). The delay for transition 1 is
* [1, 3], the delay for transition 3 is [2,5], and the delay for
* transition 5 is [4,6]. Also suppose the DBM is
* t0 t1 t3 t5
* t0 | 0, 3, 3, 3 |
* t1 | 0, 0, 0, 0 |
* t3 | 0, 0, 0, 0 |
* t5 | 0, 0, 0, 0 |
* Then the matrix that should be passed is
* lb t0 t1 t3 t5
* ub| 0, 0, 3, 5, 6|
* t0| 0, 0, 3, 3, 3|
* t1|-1, 0, 0, 0, 0|
* t3|-2, 0, 0, 0, 0|
* t5|-4, 0, 0, 0, 0|
* The matrix should be non-null and the zero timer should always be the
* first timer, even when there are no other timers.
*/
public Zone(int[] timers, int[][] matrix)
{
// A negative number indicates that the hash code has not been set.
_hashCode = -1;
// Make a copy to reorder the timers.
// _indexToTimer = Arrays.copyOf(timers, timers.length);
// Make a copy to reorder the timers.
_indexToTimerPair = new LPNTransitionPair[timers.length];
for(int i=0; i<timers.length; i++){
// _indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN,
// timers[i], true);
_indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN,
timers[i]);
}
// Sorting the array.
// Arrays.sort(_indexToTimer);
// Sorting the array.
Arrays.sort(_indexToTimerPair);
//if(_indexToTimer[0] != 0)
// if(_indexToTimer[0] != -1)
// // Add the zeroth timer.
// int[] newIndexToTimer = new int[_indexToTimer.length+1];
// for(int i=0; i<_indexToTimer.length; i++)
// newIndexToTimer[i+1] = _indexToTimer[i];
// _indexToTimer = newIndexToTimer;
// _indexToTimer[0] = -1;
if(_indexToTimerPair[0].get_transitionIndex() != -1){
// Add the zeroth timer.
LPNTransitionPair[] newIndexToTimerPair =
new LPNTransitionPair[_indexToTimerPair.length];
for(int i=0; i<_indexToTimerPair.length; i++){
newIndexToTimerPair[i+1] = _indexToTimerPair[i];
}
_indexToTimerPair = newIndexToTimerPair;
// _indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1, true);
_indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1);
}
// if(_indexToTimer[0] < 0)
// // Add a zero timer.
// else if(_indexToTimer[0] > 0)
// int[] newTimerIndex = new int[_indexToTimer.length+1];
// for(int i=0; i<_indexToTimer.length; i++)
// newTimerIndex[i+1] = _indexToTimer[i];
// Map the old index of the timer to the new index of the timer.
HashMap<Integer, Integer> newIndex = new HashMap<Integer, Integer>();
// For the old index, find the new index.
for(int i=0; i<timers.length; i++)
{
// Since the zeroth timer is not included in the timers passed
// to the index in the DBM is 1 more than the index of the timer
// in the timers array.
//newIndex.put(i+1, Arrays.binarySearch(_indexToTimer, timers[i]));
// LPNTransitionPair searchValue =
// new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i], true);
LPNTransitionPair searchValue =
new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i]);
newIndex.put(i+1, Arrays.binarySearch(_indexToTimerPair, searchValue));
}
// Add the zero timer index.
newIndex.put(0, 0);
// Initialize the matrix.
_matrix = new int[matrixSize()][matrixSize()];
// Copy the DBM
for(int i=0; i<dbmSize(); i++)
{
for(int j=0; j<dbmSize(); j++)
{
// Copy the passed in matrix to _matrix.
setDbmEntry(newIndex.get(i), newIndex.get(j),
matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]);
// In the above, changed setDBMIndex to setdbm
}
}
// Copy in the upper and lower bounds. The zero time does not have an upper or lower bound
// so the index starts at i=1, the first non-zero timer.
for(int i=1; i< dbmSize(); i++)
{
setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]);
// Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound
// and the matrix stores the negative of the lower bound. So the matrix value
// must be multiplied by -1.
setLowerBoundbydbmIndex(newIndex.get(i), -1*matrix[dbmIndexToMatrixIndex(i)][0]);
}
recononicalize();
}
/**
* Initializes a zone according to the markings of state.
* @param currentState
* The zone is initialized as if all enabled timers
* have just been enabled.
*/
public Zone(State initialState)
{
// Extract the associated LPN.
LhpnFile lpn = initialState.getLpn();
int LPNIndex = lpn.getLpnIndex();
if(_lpnList == null){
// If no LPN exists yet, create it and put lpn in it.
_lpnList = new LhpnFile[LPNIndex+1];
_lpnList[LPNIndex] = lpn;
}
else if(_lpnList.length <= LPNIndex){
// The list does not contain the lpn.
LhpnFile[] tmpList = _lpnList;
_lpnList = new LhpnFile[LPNIndex+1];
_lpnList[LPNIndex] = lpn;
// Copy any that exist already.
for(int i=0; i<_lpnList.length; i++){
_lpnList[i] = tmpList[i];
}
}
else if(_lpnList[LPNIndex] != lpn){
// This checks that the appropriate lpn is in the right spot.
// If not (which gets you in this block), then this fixes it.
_lpnList[LPNIndex] = lpn;
}
// Default value for the hash code indicating that the hash code has not
// been set yet.
_hashCode = -1;
// Get the list of currently enabled Transitions by their index.
boolean[] enabledTran = initialState.getTranVector();
ArrayList<LPNTransitionPair> enabledTransitionsArrayList =
new ArrayList<LPNTransitionPair>();
// LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1, true);
LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1);
// Add the zero timer first.
enabledTransitionsArrayList.add(zeroPair);
// The index of the boolean value corresponds to the index of the Transition.
for(int i=0; i<enabledTran.length; i++){
if(enabledTran[i]){
// enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i, true));
enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i));
}
}
_indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);
_matrix = new int[matrixSize()][matrixSize()];
for(int i=1; i<dbmSize(); i++)
{
// Get the name for the timer in the i-th column/row of DBM
String tranName =
lpn.getTransition(_indexToTimerPair[i].get_transitionIndex()).getName();
ExprTree delay = lpn.getDelayTree(tranName);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
lpn.getAllVarsWithValuesAsString(initialState.getVector());
// Set the upper and lower bound.
int upper, lower;
if(delay.getOp().equals("uniform"))
{
ExprTree lowerDelay = delay.getLeftChild();
ExprTree upperDelay = delay.getRightChild();
lower = (int) lowerDelay.evaluateExpr(varValues);
upper = (int) upperDelay.evaluateExpr(varValues);
}
else
{
lower = (int) delay.evaluateExpr(varValues);
upper = lower;
}
setLowerBoundbydbmIndex(i, lower);
setUpperBoundbydbmIndex(i, upper);
}
// Advance the time and tighten the bounds.
advance();
recononicalize();
checkZoneMaxSize();
}
/**
* Creates a Zone based on the local states.
* @param localStates
* The current state (or initial) of the LPNs.
*/
public Zone(State[] localStates){
// Extract the local states.
//State[] localStates = tps.toStateArray();
// Initialize hash code to -1 (indicating nothing cached).
_hashCode = -1;
// Initialize the LPN list.
initialize_lpnList(localStates);
// Get the enabled transitions. This initializes the _indexTotimerPair
// which stores the relevant information.
// This method will also initialize the _rateZeroContinuous
initialize_indexToTimerPair(localStates);
// Initialize the matrix.
_matrix = new int[matrixSize()][matrixSize()];
// Set the lower bound/ upper bounds of the timers and the rates.
initializeLowerUpperBounds(getAllNames(), localStates);
// Initialize the row and column entries for the continuous variables.
initializeRowColumnContVar();
// Advance Time
advance();
// Re-canonicalize
recononicalize();
// Check the size of the DBM.
checkZoneMaxSize();
}
/**
* Gives the names of all the transitions and continuous variables that
* are represented by the zone.
* @return
* The names of the transitions and continuous variables that are
* represented by the zone.
*/
public String[] getAllNames(){
// String[] transitionNames = new String[_indexToTimerPair.length];
// transitionNames[0] = "The zero timer.";
// for(int i=1; i<transitionNames.length; i++){
// LPNTransitionPair ltPair = _indexToTimerPair[i];
// transitionNames[i] = _lpnList[ltPair.get_lpnIndex()]
// .getTransition(ltPair.get_transitionIndex()).getName();
// return transitionNames;
// Get the continuous variable names.
String[] contVar = getContVarNames();
// Get the transition names.
String[] trans = getTranNames();
// Create an array large enough for all the names.
String[] names = new String[contVar.length + trans.length + 1];
// Add the zero timer.
names[0] = "The zero timer.";
// Add the continuous variables.
for(int i=0; i<contVar.length; i++){
names[i+1] = contVar[i];
}
// Add the timers.
for(int i=0; i<trans.length; i++){
// Already the zero timer has been added and the elements of contVar.
// That's a total of 'contVar.length + 1' elements. The last index was
// thus 'contVar.length' So the first index to add to is
// 'contVar.length +1'.
names[1+contVar.length + i] = trans[i];
}
return names;
}
/**
* Get the names of the continuous variables that this zone uses.
* @return
* The names of the continuous variables that are part of this zone.
*/
public String[] getContVarNames(){
// List for accumulating the names.
ArrayList<String> contNames = new ArrayList<String>();
// Find the pairs that represent the continuous variables. Loop starts at
// i=1 since the i=0 is the zero timer.
for(int i=1; i<_indexToTimerPair.length; i++){
LPNTransitionPair ltPair = _indexToTimerPair[i];
// If the isTimer value is false, then this pair represents a continuous
// variable.
//if(!ltPair.get_isTimer()){
// If pair is LPNContinuousPair.
if(ltPair instanceof LPNContinuousPair){
// Get the LPN that this pairing references and find the name of
// the continuous variable whose index is given by this pairing.
contNames.add(_lpnList[ltPair.get_lpnIndex()]
.getContVarName(ltPair.get_transitionIndex()));
}
}
return contNames.toArray(new String[0]);
}
/**
* Gets the names of the transitions that are associated with the timers in the
* zone. Does not return the zero timer.
* @return
* The names of the transitions whose timers are in the zone except the zero
* timer.
*/
public String[] getTranNames(){
// List for accumulating the names.
ArrayList<String> transitionNames = new ArrayList<String>();
// Find the pairs that represent the transition timers.
for(int i=1; i<_indexToTimerPair.length; i++){
LPNTransitionPair ltPair = _indexToTimerPair[i];
// If the isTimer value is true, then this pair represents a timer.
//if(ltPair.get_isTimer()){
// If this is an LPNTransitionPair and not an LPNContinuousPair
if(!(ltPair instanceof LPNContinuousPair)){
// Get the LPN that this pairing references and find the name of the
// transition whose index is given by this pairing.
transitionNames.add(_lpnList[ltPair.get_lpnIndex()]
.getTransition(ltPair.get_transitionIndex()).getName());
}
}
return transitionNames.toArray(new String[0]);
}
/**
* Initializes the _lpnList using information from the local states.
* @param localStates
* The local states.
* @return
* The enabled transitions.
*/
private void initialize_lpnList(State[] localStates){
// Create the LPN list.
_lpnList = new LhpnFile[localStates.length];
// Get the LPNs.
for(int i=0; i<localStates.length; i++){
_lpnList[i] = localStates[i].getLpn();
}
}
/**
* Initializes the _indexToTimerPair from the local states. (Add more detail.
* This method also initializes the rate zero variables.)
* @param localStates
* The local states.
* @return
* The names of the transitions stored in the _indexToTimerPair (in the same order).
*/
private void initialize_indexToTimerPair(State[] localStates){
/*
* The populating of the _indexToTimerPair is done in three stages.
* The first is to add the zero timer which is at the beginning of the zone.
* The second is to add the continuous variables. And the third is to add
* the other timers. Since the continuous variables are added before the
* timers and the variables and timers are added in the order of the LPNs,
* the elements in an accumulating list (enabledTransitionsArrayList) are
* already in order up to the elements added for a particular LPN. Thus the
* only sorting that needs to take place is the sorting for a particular LPN.
* Correspondingly, elements are first found for an LPN and sort, then added
* to the main list.
*/
// This method will also initialize the _rateZeroContinuous
//_rateZeroContinuous = new DualHashMap<RangeAndPairing, Variable>();
_rateZeroContinuous =
new DualHashMap<LPNTransitionPair, VariableRangePair>();
// This list accumulates the transition pairs (ie timers) and the continuous
// variables.
ArrayList<LPNTransitionPair> enabledTransitionsArrayList =
new ArrayList<LPNTransitionPair>();
// Put in the zero timer.
// enabledTransitionsArrayList
// .add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1, true));
enabledTransitionsArrayList
.add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1));
// Get the continuous variables.
for(int i=0; i<localStates.length; i++){
// Accumulates the changing continuous variables for a single LPN.
ArrayList<LPNTransitionPair> singleLPN =
new ArrayList<LPNTransitionPair>();
// Get the associated LPN.
LhpnFile lpn = localStates[i].getLpn();
// Get the continuous variables for this LPN.
String[] continuousVariables = lpn.getContVars();
// Get the variable, index map.
DualHashMap<String, Integer> variableIndex = lpn.getContinuousIndexMap();
// Find which have a nonzero rate.
for(int j=0; j<continuousVariables.length; j++){
// Get the Variables with this name.
Variable contVar = lpn.getVariable(continuousVariables[j]);
// Get the rate.
//int rate = (int) Double.parseDouble(contVar.getInitRate());
IntervalPair rate = parseRate(contVar.getInitRate());
// Get the LPN index for the variable
int lpnIndex = lpn.getLpnIndex();
// Get the index as a variable for the LPN.
int contVariableIndex = variableIndex.get(continuousVariables[j]);
// LPNTransitionPair newPair =
// new LPNTransitionPair(lpnIndex, contVariableIndex, false);
LPNContinuousPair newPair =
new LPNContinuousPair(lpnIndex, contVariableIndex,
rate.get_LowerBound());
// If the rate is non-zero, then the variables needs to be tracked
// by matrix part of the Zone.
//if(rate !=0){
if(!rate.equals(new IntervalPair(0,0))){
// Temporary exception guaranteeing only unit rates.
//if(rate != -1 && rate != 1){
if(rate.get_LowerBound() != 1 && rate.get_UpperBound() != 1){
throw new IllegalArgumentException("Current development " +
"only supports positive unit rates. The variable " + contVar +
" has a rate of " + rate);
}
// // Get the LPN index for the variable
// int lpnIndex = lpn.getLpnIndex();
// // Get the index as a variable for the LPN. This index matches
// // the index in the vector stored by platu.State.
// int contVariableIndex = variableIndex.get(continuousVariables[j]);
// The continuous variable reference.
// singleLPN.add(
// new LPNTransitionPair(lpnIndex, contVariableIndex, false));
singleLPN.add(newPair);
}
else{
// If the rate is zero, then the Zone keeps track of this variable
// in a list.
// _rateZeroContinuous.put(newPair, cpontVar);
// _rateZeroContinuous.
// put(new RangeAndPairing(newPair, parseRate(contVar.getInitValue())),
// contVar);
_rateZeroContinuous.
put(newPair, new VariableRangePair(contVar,
parseRate(contVar.getInitValue())));
}
}
// Sort the list.
Collections.sort(singleLPN);
// Add the list to the total accumulating list.
for(int j=0; j<singleLPN.size(); j++){
enabledTransitionsArrayList.add(singleLPN.get(j));
}
}
// Get the transitions.
for(int i=0; i<localStates.length; i++){
// Extract the enabled transition vector.
boolean[] enabledTran = localStates[i].getTranVector();
// Accumulates the transition pairs for one LPN.
ArrayList<LPNTransitionPair> singleLPN = new ArrayList<LPNTransitionPair>();
// The index of the boolean value corresponds to the index of the Transition.
for(int j=0; j<enabledTran.length; j++){
if(enabledTran[j]){
// Add the transition pair.
// singleLPN.add(new LPNTransitionPair(i, j, true));
singleLPN.add(new LPNTransitionPair(i, j));
}
}
// Sort the transitions for the current LPN.
Collections.sort(singleLPN);
// Add the collection to the enabledTransitionsArrayList
for(int j=0; j<singleLPN.size(); j++){
enabledTransitionsArrayList.add(singleLPN.get(j));
}
}
// Extract out the array portion of the enabledTransitionsArrayList.
_indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]);
}
/**
* Sets the lower and upper bounds for the transitions and continuous variables.
* @param varNames
* The names of the transitions in _indexToTimerPair.
*/
private void initializeLowerUpperBounds(String[] varNames, State[] localStates){
// Traverse the entire length of the DBM sub-matrix except the zero row/column.
// This is the same length as the _indexToTimerPair.length-1. The DBM is used to
// match the idea of setting the value for each row.
for(int i=1; i<dbmSize(); i++){
// Get the current LPN and transition pairing.
LPNTransitionPair ltPair = _indexToTimerPair[i];
//int upper, lower;
IntervalPair range;
// if(!ltPair.get_isTimer()){
if(ltPair instanceof LPNContinuousPair){
// If the pairing represents a continuous variable, then the
// upper and lower bound are the initial value or infinity depending
// on whether the initial rate is positive or negative.
// If the value is a constant, then assign the upper and lower bounds
// to be constant. If the value is a range then assign the upper and
// lower bounds to be a range.
Variable v = _lpnList[ltPair.get_lpnIndex()]
.getContVar(ltPair.get_transitionIndex());
// int initialRate = (int) Double.parseDouble(v.getInitRate());
// upper = initialRate;
// lower = initialRate;
String rate = v.getInitRate();
// Parse the rate. Should be in the form of [x,y] where x
// and y are integers.
//IntervalPair range = parseRate(rate);
range = parseRate(rate);
// Set the upper and lower bound (in the matrix) for the
// continuous variables.
// TODO : Check if correct.
String contValue = v.getInitValue();
IntervalPair bound = parseRate(contValue);
// Set upper bound (DBM entry (0, x) where x is the index of the variable v).
setDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, ltPair, bound.get_UpperBound());
// Set lower bound (DBM entry (x, 0) where x is the index of the variable v).
setDbmEntryByPair(ltPair, LPNTransitionPair.ZERO_TIMER_PAIR, -1*bound.get_LowerBound());
// lower = range.get_LowerBound();
// upper = range.get_UpperBound();
}
else{
// Get the expression tree.
ExprTree delay = _lpnList[ltPair.get_lpnIndex()].getDelayTree(varNames[i]);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
_lpnList[ltPair.get_lpnIndex()]
.getAllVarsWithValuesAsString(localStates[ltPair.get_lpnIndex()].getVector());
// Set the upper and lower bound.
// Passing the zone as null since it should not be needed.
// if(delay.getOp().equals("uniform")){
// IntervalPair lowerRange = delay.getLeftChild()
// .evaluateExprBound(varValues, null);
// IntervalPair upperRange = delay.getRightChild()
// .evaluateExprBound(varValues, null);
// // The lower and upper bounds should evaluate to a single
// // value. Yell if they don't.
// if(!lowerRange.singleValue() || !upperRange.singleValue()){
// "the lower or the upper bound evaluated to a range " +
// "instead of a single value.");
// range = new IntervalPair(lowerRange.get_LowerBound(),
// upperRange.get_UpperBound());
// else{
// range = delay.evaluateExprBound(varValues, null);
range = delay.evaluateExprBound(varValues, this);
// int upper, lower;
// if(delay.getOp().equals("uniform"))
// ExprTree lowerDelay = delay.getLeftChild();
// ExprTree upperDelay = delay.getRightChild();
// lower = (int) lowerDelay.evaluateExpr(varValues);
// upper = (int) upperDelay.evaluateExpr(varValues);
// else
// lower = (int) delay.evaluateExpr(varValues);
// upper = lower;
}
// setLowerBoundbydbmIndex(i, lower);
// setUpperBoundbydbmIndex(i, upper);
setLowerBoundbydbmIndex(i, range.get_LowerBound());
setUpperBoundbydbmIndex(i, range.get_UpperBound());
}
}
/**
* Initialize the rows and columns for the continuous variables.
*/
private void initializeRowColumnContVar(){
/*
* TODO : Describe the idea behind the following algorithm.
*/
// for(int row=2; row<_indexToTimerPair.length; row++){
// // Note: row is indexing the row of the DBM matrix.
// LPNTransitionPair ltRowPair = _indexToTimerPair[row];
// if(ltRowPair.get_isTimer()){
// // If we reached the timers, stop.
// break;
// for(int col=1; col<row; col++){
// // Note: col is indexing the column of the DBM matrix.
// // The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since
// // col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower
// // bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);
// int rowCol = getDbmEntry(row,0) + getDbmEntry(0, col);
// // The new (col, row) entry.
// int colRow = getDbmEntry(col, 0) + getDbmEntry(0, row);
// setDbmEntry(row, col, rowCol);
// setDbmEntry(col, row, colRow);
// The only entries that do not need to be checked are the ones where both variables
// represent timers.
for(int row=2; row<_indexToTimerPair.length; row++){
// Note: row is indexing the row of the DBM matrix.
LPNTransitionPair ltRowPair = _indexToTimerPair[row];
// if(ltRowPair.get_isTimer()){
// // If we reached the timers, stop.
// break;
for(int col=1; col<row; col++){
// Note: col is indexing the column of the DBM matrix.
LPNTransitionPair ltColPair = _indexToTimerPair[col];
// If we've reached the part of the zone involving only timers, then break out
// of this row.
// if(ltRowPair.get_isTimer() && ltColPair.get_isTimer()){
if(!(ltRowPair instanceof LPNContinuousPair) &&
!(ltColPair instanceof LPNContinuousPair)){
break;
}
// The new (row, col) entry. The entry is given by col-row<= m_(row,col). Since
// col <= m_(0,col) (its upper bound) and -row <= m_(row,0) (the negative of its lower
// bound), the entry is given by col-row <= m(0,col) + m_(row,0) = m_(row,col);
int rowCol = getDbmEntry(row,0) + getDbmEntry(0, col);
// The new (col, row) entry.
int colRow = getDbmEntry(col, 0) + getDbmEntry(0, row);
setDbmEntry(row, col, rowCol);
setDbmEntry(col, row, colRow);
}
}
}
/**
* Zero argument constructor for use in methods that create Zones where the members
* variables will be set by the method.
*/
private Zone()
{
_matrix = new int[0][0];
_indexToTimerPair = new LPNTransitionPair[0];
_hashCode = -1;
_lpnList = new LhpnFile[0];
_rateZeroContinuous = new DualHashMap<LPNTransitionPair, VariableRangePair>();
}
/**
* Gets the upper bound of a Transition from the zone.
* @param t
* The transition whose upper bound is wanted.
* @return
* The upper bound of Transition t.
*/
public int getUpperBoundbyTransition(Transition t)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair =
// new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair =
new LPNTransitionPair(lpnIndex, transitionIndex);
return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));
}
/**
* Returns the upper bound of the continuous variable.
* @param var
* The variable of interest.
* @return
* The (0,var) entry of the zone, that is the maximum as recored by
* the zone.
*/
public int getUpperBoundbyContinuousVariable(String contVar, LhpnFile lpn){
// TODO : Finish.
// // Determine whether the variable is in the zone or rate zero.
// RangeAndPairing indexAndRange = _rateZeroContinuous.getKey(var);
// // If a RangeAndPairing is returned, then get the information from here.
// if(indexAndRange != null){
// return indexAndRange.get_range().get_UpperBound();
// // If indexAndRange is null, then try to get the value from the zone.
// int i=-1;
// for(i=0; i<_indexToTimerPair.length; i++){
// if(_indexToTimerPair[i].equals(var)){
// break;
// if(i < 0){
// + "a non-rate zero continuous variable that was not found in the "
// + "zone.");
// return getUpperBoundbydbmIndex(i);
// Extract the necessary indecies.
int lpnIndex = lpn.getLpnIndex();
//int contVarIndex = lpn.get
DualHashMap<String, Integer> variableIndecies = lpn.getContinuousIndexMap();
int contIndex = variableIndecies.get(contVar);
// Package the indecies with false indicating not a timer.
// LPNTransitionPair index = new LPNTransitionPair(lpnIndex, contIndex, false);
// Note : setting the rate is not necessary here since this is only
// being used as an index.
LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex, 0);
//Search for the continuous variable in the rate zero variables.
VariableRangePair pairing = _rateZeroContinuous.get(index);
// If Pairing is not null, the variable was found and return the result.
if(pairing != null){
return pairing.get_range().get_UpperBound();
}
// If Pairing was null, the variable was not found. Search for the variable
// in the zone portion.
int i = Arrays.binarySearch(_indexToTimerPair, index);
// If i < 0, the search was unsuccessful, so scream.
if(i < 0){
throw new IllegalArgumentException("Atempted to find the lower bound for "
+ "a non-rate zero continuous variable that was not found in the "
+ "zone.");
}
//return getUpperBoundbydbmIndex(i);
return getDbmEntry(0, i);
}
public int getUpperBoundForRate(LPNTransitionPair contVar){
// TODO : finish.
// Check if the contVar is in the zone.
int i = Arrays.binarySearch(_indexToTimerPair, contVar);
if(i > 0){
// The continuous variable is in the zone.
// The upper and lower bounds are stored in the same
// place as the delays, so the same method of
// retrieval will work.
return getUpperBoundbydbmIndex(contVar.get_transitionIndex());
}
// Assume the rate is zero. This covers the case if conVar
// is in the rate zero as well as if its not in the state at all.
return 0;
}
/**
* Get the value of the upper bound for the delay. If the index refers
* to a timer, otherwise get the upper bound for the continuous
* variables rate.
* @param index
* The timer's row/column of the DBM matrix.
* @return
* The upper bound on the transitions delay.
*/
public int getUpperBoundbydbmIndex(int index)
{
return _matrix[0][dbmIndexToMatrixIndex(index)];
}
/**
* Set the value of the upper bound for the delay.
* @param t
* The transition whose upper bound is being set.
* @param value
* The value of the upper bound.
*/
public void setUpperBoundbyTransition(Transition t, int value)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);
}
/**
* Set the value of the upper bound for the delay.
* @param index
* The timer's row/column of the DBM matrix.
* @param value
* The value of the upper bound.
*/
public void setUpperBoundbydbmIndex(int index, int value)
{
_matrix[0][dbmIndexToMatrixIndex(index)] = value;
}
/**
* Sets the upper bound for a transition described by an LPNTransitionPair.
* @param ltPair
* The index of the transition and the index of the associated LPN for
* the timer to set the upper bound.
* @param value
* The value for setting the upper bound.
*/
private void setUpperBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value){
setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value);
}
/**
* Gets the lower bound of a Transition from the zone.
* @param t
* The transition whose upper bound is wanted.
* @return
* The lower bound of Transition t.
*/
public int getLowerBoundbyTransition(Transition t)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
return -1*getLowerBoundbydbmIndex(
Arrays.binarySearch(_indexToTimerPair, ltPair));
}
/**
* Returns the lower bound of the continuous variable.
* @param var
* The variable of interest.
* @return
* The (0,var) entry of the zone, that is the minimum as recored by
* the zone.
*/
public int getLowerBoundbyContinuousVariable(String contVar, LhpnFile lpn){
// Extract the necessary indecies.
int lpnIndex = lpn.getLpnIndex();
//int contVarIndex = lpn.get
DualHashMap<String, Integer> variableIndecies = lpn.getContinuousIndexMap();
int contIndex = variableIndecies.get(contVar);
// Package the indecies with false indicating not a timer.
// LPNTransitionPair index = new LPNTransitionPair(lpnIndex, contIndex, false);
// Note: Setting the rate is not necessary since this is only being used
// as an index.
LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex, 0);
//Search for the continuous variable in the rate zero variables.
VariableRangePair pairing = _rateZeroContinuous.get(index);
// If Pairing is not null, the variable was found and return the result.
if(pairing != null){
return pairing.get_range().get_LowerBound();
}
// If Pairing was null, the variable was not found. Search for the variable
// in the zone portion.
int i = Arrays.binarySearch(_indexToTimerPair, index);
// If i < 0, the search was unsuccessful, so scream.
if(i < 0){
throw new IllegalArgumentException("Atempted to find the lower bound for "
+ "a non-rate zero continuous variable that was not found in the "
+ "zone.");
}
//return getLowerBoundbydbmIndex(i);
return getDbmEntry(i, 0);
}
/**
* Get the value of the lower bound for the delay if the index refers
* to a timer, otherwise get the lower bound for the continuous variables
* rate.
* @param index
* The timer's row/column of the DBM matrix.
* @return
* The value of the lower bound.
*/
public int getLowerBoundbydbmIndex(int index)
{
return _matrix[dbmIndexToMatrixIndex(index)][0];
}
public int getLowerBoundForRate(LPNTransitionPair contVar){
// TODO : finish.
// Check if the contVar is in the zone.
int i = Arrays.binarySearch(_indexToTimerPair, contVar);
if(i > 0){
// The continuous variable is in the zone.
// The upper and lower bounds are stored in the same
// place as the delays, so the same method of
// retrieval will work.
return getLowerBoundbydbmIndex(contVar.get_transitionIndex());
}
// Assume the rate is zero. This covers the case if conVar
// is in the rate zero as well as if its not in the state at all.
return 0;
}
/**
* Set the value of the lower bound for the delay.
* @param t
* The transition whose lower bound is being set.
* @param value
* The value of the lower bound.
*/
public void setLowerBoundbyTransition(Transition t, int value)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair,ltPair), value);
}
/**
* Set the value of the upper bound for the delay.
* @param t
* The transition whose upper bound is being set.
* @param value
* The value of the upper bound.
*/
private void setLowerBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value){
setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair,ltPair), value);
}
/**
* Set the value of the lower bound for the delay.
* @param index
* The timer's row/column of the DBM matrix.
* @param value
* The value of the lower bound.
*/
public void setLowerBoundbydbmIndex(int index, int value)
{
_matrix[dbmIndexToMatrixIndex(index)][0] = -1*value;
}
/**
* Give the upper and lower bounds for a continuous variable.
* @param contVar
* The variable of interest.
* @return
* The upper and lower bounds according to the Zone.
*/
public IntervalPair getContinuousBounds(String contVar, LhpnFile lpn){
/*
* Need to determine whether this is suppose to be a rate zero variable or a non-zero
* rate variable. One method is to check the rate of the passed variable. The other is
* to just check if the variable is present in either place.
*/
// Extract the necessary indecies.
int lpnIndex = lpn.getLpnIndex();
// Get the index of the continuous variable.
DualHashMap<String, Integer> variableIndecies = lpn.getContinuousIndexMap();
int contIndex = variableIndecies.get(contVar);
// Package the indecies with false indicating not a timer.
// LPNTransitionPair index = new LPNTransitionPair(lpnIndex, contIndex, false);
// Note: setting the current rate is not necessary here since the
// LPNContinuousPair is only being used as an index.
LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex, 0);
// Search for the continuous variable in the rate zero variables.
VariableRangePair pairing = _rateZeroContinuous.get(index);
// If Pairing is not null, the variable was found and return the result.
if(pairing != null){
return pairing.get_range();
}
// If Pairing was null, the variable was not found. Search for the variable
// in the zone portion.
int i = Arrays.binarySearch(_indexToTimerPair, index);
// If i < 0, the search was unsuccessful, so scream.
if(i < 0){
throw new IllegalArgumentException("Atempted to find the bounds for "
+ "a non-rate zero continuous variable that was not found in the "
+ "zone.");
}
// Else find the upper and lower bounds.
// int lower = getLowerBoundbydbmIndex(i);
// int upper = getUpperBoundbydbmIndex(i);
int lower = (-1)*getDbmEntry(i, 0);
int upper = getDbmEntry(0, i);
return new IntervalPair(lower, upper);
}
/**
* Sets the bounds for a continuous variable.
* @param contVar
* The continuous variable to set the bounds on.
* @param lpn
* The LhpnFile object that contains the variable.
* @param range
* The new range of the continuous variable.
*/
public void setContinuousBounds(String contVar, LhpnFile lpn,
IntervalPair range){
// Extract the necessary indecies.
int lpnIndex = lpn.getLpnIndex();
// Get the index of the continuous variable.
DualHashMap<String, Integer> variableIndecies = lpn.getContinuousIndexMap();
int contIndex = variableIndecies.get(contVar);
// Package the indecies with false indicating not a timer.
// LPNTransitionPair index = new LPNTransitionPair(lpnIndex, contIndex, false);
//Note : Setting the rate is not necessary since this only being used
// as an index.
LPNContinuousPair index = new LPNContinuousPair(lpnIndex, contIndex, 0);
// Search for the continuous variable in the rate zero variables.
VariableRangePair pairing = _rateZeroContinuous.get(index);
// If Pairing is not null, the variable was found and make the new assignment.
if(pairing != null){
pairing.set_range(range);
return;
}
// If Pairing was null, the variable was not found. Search for the variable
// in the zone portion.
int i = Arrays.binarySearch(_indexToTimerPair, index);
// If i < 0, the search was unsuccessful, so scream.
if(i < 0){
throw new IllegalArgumentException("Atempted to find the bounds for "
+ "a non-rate zero continuous variable that was not found in the "
+ "zone.");
}
// Else find the upper and lower bounds.
// setLowerBoundbydbmIndex(i, range.get_LowerBound());
// setUpperBoundbydbmIndex(i, range.get_UpperBound());
setDbmEntry(i, 0, (-1)*range.get_LowerBound());
setDbmEntry(0, i, range.get_UpperBound());
}
/**
* Converts the index of the DBM to the index of _matrix.
* @param i
* The row/column index of the DBM.
* @return
* The row/column index of _matrix.
*/
private int dbmIndexToMatrixIndex(int i)
{
return i+1;
}
/**
* Retrieves an entry of the DBM using the DBM's addressing.
* @param i
* The row of the DBM.
* @param j
* The column of the DBM.
* @return
* The value of the (i, j) element of the DBM.
*/
public int getDbmEntry(int i, int j)
{
return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)];
}
/**
* Sets an entry of the DBM using the DBM's addressing.
* @param i
* The row of the DBM.
* @param j
* The column of the DBM.
* @param value
* The new value for the entry.
*/
private void setDbmEntry(int i, int j, int value)
{
_matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value;
}
/**
* Sets the entry in the DBM using the LPNTransitionPair indexing.
* @param row
* The LPNTransitionPair for the row.
* @param col
* The LPNTransitionPair for the column.
* @param value
* The value to set the entry to.
*/
private void setDbmEntryByPair(LPNTransitionPair row, LPNTransitionPair col, int value){
// The row index.
int i = timerIndexToDBMIndex(row);
// The column index.
int j = timerIndexToDBMIndex(col);
setDbmEntry(i, j, value);
}
/**
* Returns the index of the the transition in the DBM given a LPNTransitionPair pairing
* the transition index and associated LPN index.
* @param ltPair
* The pairing comprising the index of the transition and the index of the associated
* LPN.
* @return
* The row/column of the DBM associated with the ltPair.
*/
private int timerIndexToDBMIndex(LPNTransitionPair ltPair)
{
return Arrays.binarySearch(_indexToTimerPair, ltPair);
}
/**
* The matrix labeled with 'ti' where i is the transition index associated with the timer.
*/
public String toString()
{
// TODO : Fix the handling of continuous variables in the
// _lpnList == 0 case.
String result = "Timer and delay or continuous and ranges.\n";
int count = 0;
// Print the timers.
for(int i=1; i<_indexToTimerPair.length; i++, count++)
{
if(_lpnList.length == 0)
{
// If no LPN's are associated with this Zone, use the index of the timer.
result += " t" + _indexToTimerPair[i].get_transitionIndex() + " : ";
}
else
{
String name;
// If the current LPNTransitionPair is a timer, get the name
// from the transitions.
// if(_indexToTimerPair[i].get_isTimer()){
// If the current timer is an LPNTransitionPair and not an LPNContinuousPair
if(!(_indexToTimerPair[i] instanceof LPNContinuousPair)){
// Get the name of the transition.
Transition tran = _lpnList[_indexToTimerPair[i].get_lpnIndex()].
getTransition(_indexToTimerPair[i].get_transitionIndex());
name = tran.getName();
}
else{
// If the current LPNTransitionPair is not a timer, get the
// name as a continuous variable.
Variable var = _lpnList[_indexToTimerPair[i].get_lpnIndex()]
.getContVar(_indexToTimerPair[i].get_transitionIndex());
name = var.getName() +
":[" + -1*getDbmEntry(0, i) + "," + getDbmEntry(i, 0) +
"rate:";
}
// result += " " + tran.getName() + ":";
result += " " + name + ":";
}
result += "[ " + -1*getLowerBoundbydbmIndex(i) + ", " + getUpperBoundbydbmIndex(i) + " ]";
if(count > 9)
{
result += "\n";
count = 0;
}
}
if(!_rateZeroContinuous.isEmpty()){
result += "Rate Zero Continuous : \n";
for (LPNTransitionPair ltPair : _rateZeroContinuous.keySet()){
result += "" + _rateZeroContinuous.get(ltPair);
}
}
result += "\nDBM\n";
// Print the DBM.
for(int i=0; i<_indexToTimerPair.length; i++)
{
result += "| " + getDbmEntry(i, 0);
for(int j=1; j<_indexToTimerPair.length; j++)
{
result += ", " + getDbmEntry(i, j);
}
result += " |\n";
}
return result;
}
/**
* Tests for equality. Overrides inherited equals method.
* @return True if o is equal to this object, false otherwise.
*/
public boolean equals(Object o)
{
// Check if the reference is null.
if(o == null)
{
return false;
}
// Check that the type is correct.
if(!(o instanceof Zone))
{
return false;
}
// Check for equality using the Zone equality.
return equals((Zone) o);
}
/**
* Tests for equality.
* @param
* The Zone to compare.
* @return
* True if the zones are non-null and equal, false otherwise.
*/
public boolean equals(Zone otherZone)
{
// Check if the reference is null first.
if(otherZone == null)
{
return false;
}
// Check for reference equality.
if(this == otherZone)
{
return true;
}
// If the hash codes are different, then the objects are not equal.
if(this.hashCode() != otherZone.hashCode())
{
return false;
}
// Check if the they have the same number of timers.
if(this._indexToTimerPair.length != otherZone._indexToTimerPair.length){
return false;
}
// Check if the timers are the same.
for(int i=0; i<this._indexToTimerPair.length; i++){
if(!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))){
return false;
}
}
// Check if the matrix is the same
for(int i=0; i<_matrix.length; i++)
{
for(int j=0; j<_matrix[0].length; j++)
{
if(!(this._matrix[i][j] == otherZone._matrix[i][j]))
{
return false;
}
}
}
return true;
}
/**
* Determines if this zone is a subset of Zone otherZone.
* @param otherZone
* The zone to compare against.
* @return
* True if this is a subset of other; false otherwise.
*/
public boolean subset(Zone otherZone){
// Check if the reference is null first.
if(otherZone == null)
{
return false;
}
// Check for reference equality.
if(this == otherZone)
{
return true;
}
// Check if the the same number of timers are present.
if(this._indexToTimerPair.length != otherZone._indexToTimerPair.length){
return false;
}
// Check if the transitions are the same.
for(int i=0; i<this._indexToTimerPair.length; i++){
if(!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))){
return false;
}
}
// Check if the entries of this Zone are less than or equal to the entries
// of the other Zone.
for(int i=0; i<_matrix.length; i++)
{
for(int j=0; j<_matrix[0].length; j++)
{
if(!(this._matrix[i][j] <= otherZone._matrix[i][j])){
return false;
}
}
}
return true;
}
/**
* Determines if this zone is a superset of Zone otherZone.
* @param otherZone
* The zone to compare against.
* @return
* True if this is a subset of other; false otherwise. More specifically it
* gives the result of otherZone.subset(this). Thus it agrees with the subset method.
*/
public boolean superset(Zone otherZone){
return otherZone.subset(this);
}
/**
* Overrides the hashCode.
*/
public int hashCode()
{
// Check if the hash code has been set.
if(_hashCode <0)
{
_hashCode = createHashCode();
}
return _hashCode;
}
/**
* Creates a hash code for a Zone object.
* @return
* The hash code.
*/
private int createHashCode()
{
int newHashCode = Arrays.hashCode(_indexToTimerPair);
for(int i=0; i<_matrix.length; i++)
{
newHashCode ^= Arrays.hashCode(_matrix[i]);
}
return Math.abs(newHashCode);
}
/**
* The size of the DBM sub matrix. This is calculated using the size of _indexToTimer.
* @return
* The size of the DBM.
*/
private int dbmSize()
{
return _indexToTimerPair.length;
}
/**
* The size of the matrix.
* @return
* The size of the matrix. This is calculated using the size of _indexToTimer.
*/
private int matrixSize()
{
return _indexToTimerPair.length + 1;
}
/**
* Performs the Floyd's least pairs algorithm to reduce the DBM.
*/
private void recononicalize()
{
for(int k=0; k<dbmSize(); k++)
{
for (int i=0; i<dbmSize(); i++)
{
for(int j=0; j<dbmSize(); j++)
{
if(getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY
&& getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j))
{
setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j));
}
if( (i==j) && getDbmEntry(i, j) != 0)
{
throw new DiagonalNonZeroException("Entry (" + i + ", " + j + ")" +
" became " + getDbmEntry(i, j) + ".");
}
}
}
}
}
/**
* Determines if a timer associated with a given transitions has reached its lower bound.
* @param t
* The transition to consider.
* @return
* True if the timer has reached its lower bound, false otherwise.
*/
public boolean exceedsLowerBoundbyTransitionIndex(Transition t)
{
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair));
}
/**
* Determines if a timer has reached its lower bound.
* @param timer
* The timer's index.
* @return
* True if the timer has reached its lower bound, false otherwise.
*/
public boolean exceedsLowerBoundbydbmIndex(int index)
{
// Note : Make sure that the lower bound is stored as a negative number
// and that the inequality is correct.
return _matrix[0][dbmIndexToMatrixIndex(index)] <=
_matrix[1][dbmIndexToMatrixIndex(index)];
}
/* (non-Javadoc)
* @see verification.timed_state_exploration.zone.Zone#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State)
*/
// public Zone fireTransitionbyTransitionIndex(int timer, int[] enabledTimers,
// State state)
// // TODO: Check if finish.
// int index = Arrays.binarySearch(_indexToTimer, timer);
// //return fireTransitionbydbmIndex(Arrays.binarySearch(_indexToTimer, timer),
// //enabledTimers, state);
// // Check if the value is in this zone to fire.
// if(index < 0){
// return this;
// return fireTransitionbydbmIndex(index, enabledTimers, state);
/**
* Gives the Zone obtained by firing a given Transitions.
* @param t
* The transitions being fired.
* @param enabledTran
* The list of currently enabled Transitions.
* @param localStates
* The current local states.
* @return
* The Zone obtained by firing Transition t with enabled Transitions enabled
* enabledTran when the current state is localStates.
*/
public Zone fire(Transition t, LpnTranList enabledTran, State[] localStates){
// Create the LPNTransitionPair to check if the Transitions is in the zone and to
// find the index.
LhpnFile lpn = t.getLpn();
int lpnIndex = lpn.getLpnIndex();
int transitionIndex = t.getIndex();
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair);
if(dbmIndex <= 0){
return this;
}
// Get the new zone portion.
Zone newZone = fireTransitionbydbmIndex(dbmIndex, enabledTran, localStates);
// Update any assigned continuous variables.
newZone.updateContinuousAssignment(t, localStates[lpnIndex]);
//return fireTransitionbydbmIndex(dbmIndex, enabledTran, localStates);
return newZone;
}
/**
* Updates the Zone according to the transition firing.
* @param index
* The index of the timer.
* @return
* The updated Zone.
*/
public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers,
State[] localStates)
{
Zone newZone = new Zone();
// Copy the LPNs over.
newZone._lpnList = new LhpnFile[this._lpnList.length];
for(int i=0; i<this._lpnList.length; i++){
newZone._lpnList[i] = this._lpnList[i];
}
// Copy the continuous variables over.
newZone._rateZeroContinuous = this._rateZeroContinuous.clone();
// Extract the pairing information for the enabled timers.
// Using the enabledTimersList should be faster than calling the get method
// several times.
newZone._indexToTimerPair = new LPNTransitionPair[enabledTimers.size() + 1];
int count = 0;
// newZone._indexToTimerPair[count++] =
// new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1, true);
newZone._indexToTimerPair[count++] =
new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1);
for(Transition t : enabledTimers){
// newZone._indexToTimerPair[count++] =
// new LPNTransitionPair(t.getLpn().getLpnIndex(), t.getIndex(), true);
newZone._indexToTimerPair[count++] =
new LPNTransitionPair(t.getLpn().getLpnIndex(), t.getIndex());
}
Arrays.sort(newZone._indexToTimerPair);
HashSet<LPNTransitionPair> newTimers = new HashSet<LPNTransitionPair>();
HashSet<LPNTransitionPair> oldTimers = new HashSet<LPNTransitionPair>();
for(int i=0; i<newZone._indexToTimerPair.length; i++)
{
// Determine if each value is a new timer or old.
if(Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i])
>= 0 )
{
// The timer was already present in the zone.
oldTimers.add(newZone._indexToTimerPair[i]);
}
else
{
// The timer is a new timer.
newTimers.add(newZone._indexToTimerPair[i]);
}
}
// Create the new matrix.
newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()];
// TODO: For simplicity, make a copy of the current zone and perform the
// restriction and re-canonicalization. Later add a copy re-canonicalization
// that does the steps together.
Zone tempZone = this.clone();
tempZone.restrict(index);
tempZone.recononicalize();
// Copy the tempZone to the new zone.
for(int i=0; i<tempZone.dbmSize(); i++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[i]))
{
continue;
}
// Get the new index of for the timer.
int newIndexi = i==0 ? 0 :
Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]);
for(int j=0; j<tempZone.dbmSize(); j++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[j]))
{
continue;
}
int newIndexj = j==0 ? 0 :
Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]);
newZone._matrix[newZone.dbmIndexToMatrixIndex(newIndexi)]
[newZone.dbmIndexToMatrixIndex(newIndexj)]
= tempZone.getDbmEntry(i, j);
}
}
// Copy the upper and lower bounds.
for(int i=1; i<tempZone.dbmSize(); i++)
{
if(!oldTimers.contains(tempZone._indexToTimerPair[i]))
{
continue;
}
newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i],
-1*tempZone.getLowerBoundbydbmIndex(i));
// The minus sign is because _matrix stores the negative of the lower bound.
newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i],
tempZone.getUpperBoundbydbmIndex(i));
}
// Copy in the new relations for the new timers.
for(LPNTransitionPair timerNew : newTimers)
{
for(LPNTransitionPair timerOld : oldTimers)
{
newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew),
newZone.timerIndexToDBMIndex(timerOld),
tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld)));
// int newTimeIndex = newZone.timerIndexToDBMIndex(timerNew);
// int oldTimeIndex = newZone.timerIndexToDBMIndex(timerOld);
// int value = tempZone.getDbmEntry(0, oldTimeIndex);
newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld),
newZone.timerIndexToDBMIndex(timerNew),
tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0));
}
}
// Set the upper and lower bounds for the new timers.
for(LPNTransitionPair pair : newTimers){
// Get all the upper and lower bounds for the new timers.
// Get the name for the timer in the i-th column/row of DBM
//String tranName = indexToTran.get(i).getName();
String tranName = _lpnList[pair.get_lpnIndex()]
.getTransition(pair.get_transitionIndex()).getName();
ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName);
// Get the values of the variables for evaluating the ExprTree.
HashMap<String, String> varValues =
_lpnList[pair.get_lpnIndex()]
.getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVector());
// Set the upper and lower bound.
int upper, lower;
if(delay.getOp().equals("uniform"))
{
// ExprTree lowerDelay = delay.getLeftChild();
// ExprTree upperDelay = delay.getRightChild();
// lower = (int) lowerDelay.evaluateExpr(varValues);
// upper = (int) upperDelay.evaluateExpr(varValues);
IntervalPair lowerRange = delay.getLeftChild()
.evaluateExprBound(varValues, null);
IntervalPair upperRange = delay.getRightChild()
.evaluateExprBound(varValues, null);
// The lower and upper bounds should evaluate to a single
// value. Yell if they don't.
if(!lowerRange.singleValue() || !upperRange.singleValue()){
throw new IllegalStateException("When evaulating the delay, " +
"the lower or the upper bound evaluated to a range " +
"instead of a single value.");
}
lower = lowerRange.get_LowerBound();
upper = upperRange.get_UpperBound();
}
else
{
// lower = (int) delay.evaluateExpr(varValues);
// upper = lower;
IntervalPair range = delay.evaluateExprBound(varValues, this);
lower = range.get_LowerBound();
upper = range.get_UpperBound();
}
newZone.setLowerBoundByLPNTransitionPair(pair, lower);
newZone.setUpperBoundByLPNTransitionPair(pair, upper);
}
newZone.advance();
newZone.recononicalize();
newZone.checkZoneMaxSize();
return newZone;
}
/**
* Advances time.
*/
private void advance()
{
for(int i=0; i<dbmSize(); i++)
{
_matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] =
getUpperBoundbydbmIndex(i);
}
}
/**
* Advances time. (This method should replace advance().)
* @param localStates
*/
private void advance(State[] localStates){
for(LPNTransitionPair ltPair : _indexToTimerPair){
// For ease, extract the index.
int index = ltPair.get_transitionIndex();
// Get the new value.
int newValue = 0;
// if(ltPair.get_isTimer()){
if(ltPair instanceof LPNContinuousPair){
// If the pair is a timer, then simply get the stored largest value.
newValue = getUpperBoundbydbmIndex(index);
}
else{
// I fthe pair is a continuous variable, then need to find the
// possible largest bound governed by the inequalities.
newValue = maxAdvance(ltPair, localStates);
}
// In either case (timer or continuous), set the upper bound portion
// of the DBM to the new value.
setDbmEntryByPair(ltPair, LPNTransitionPair.ZERO_TIMER_PAIR, newValue);
}
}
/**
* Finds the maximum amount that time cam advance.
* @return
* value.
* The maximum amount that time can advance before a timer expires or an inequality changes
*/
private int maxAdvance(LPNTransitionPair contVar, State[] localStates){
/*
* Several comments in this function may look like C code. That's because,
* well it is C code from atacs/src/lhpnrsg.c. In particular the
* lhpnCheckPreds method.
*/
// Get the continuous variable in question.
int lpnIndex = contVar.get_lpnIndex();
int varIndex = contVar.get_transitionIndex();
Variable variable = _lpnList[lpnIndex].getContVar(varIndex);
// int lhpnCheckPreds(int p,ineqList &ineqL,lhpnStateADT s,ruleADT **rules,
// int nevents,eventADT *events)
//#ifdef __LHPN_TRACE__
//printf("lhpnCheckPreds:begin()\n");
//#endif
//int min = INFIN;
//int newMin = INFIN;
int min = INFINITY;
int newMin = INFINITY;
//int zoneP = getIndexZ(s->z,-2,p);
//for(unsigned i=0;i<ineqL.size();i++) {
// if(ineqL[i]->type > 4) {
// continue;
//#ifdef __LHPN_PRED_DEBUG__
// printf("Zone to check...\n");
// printZ(s->z,events,nevents,s->r);
// printf("Checking ...");
// printI(ineqL[i],events);
// printf("\n");
//#endif
// if(ineqL[i]->place == p) {
// Get all the inequalities that reference the variable of interest.
ArrayList<InequalityVariable> inequalities = variable.getInequalities();
for(InequalityVariable ineq : inequalities){
// ineq_update(ineqL[i],s,nevents);
// Update the inequality variable.
int ineqValue = ineq.evaluate(localStates[varIndex], this);
// if(ineqL[i]->type <= 1) {
// /* Working on a > or >= ineq */
if(ineq.get_op().equals(">") || ineq.get_op().equals(">=")){
// Working on a > or >= ineq
// if(s->r->bound[p-nevents].current > 0) {
// If the rate is positive.
if(getCurrentRate(contVar) > 0){
// if(s->m->state[ineqL[i]->signal]=='1') {
if(ineqValue != 0){
// if(s->z->matrix[zoneP][0] <
// chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 1a\n");
//#endif
//#ifdef __LHPN_WARN__
// warn("checkPreds: Impossible case 1.\n");
//#endif
// newMin = s->z->matrix[zoneP][0];
if(getDbmEntry(0, contVar.get_transitionIndex())
< chkDiv(ineq.getConstant(), getCurrentRate(contVar), false)){
// CP: case 1a.
newMin = getDbmEntry(0, contVar.get_transitionIndex());
System.err.println("maxAdvance: Impossible case 1.");
}
// else if((-1)*s->z->matrix[0][zoneP] >
// chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 2a\n");
//#endif
// newMin = chkDiv(events[p]->urange,
// s->r->bound[p-nevents].current,'F');
else if ((-1)*getDbmEntry(contVar.get_transitionIndex(),0)
> chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// CP : case 2a
newMin = INFINITY;
}
// else {
// /* straddle case */
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 3a\n");
//#endif
// newMin = chkDiv(events[p]->urange,
// s->r->bound[p-nevents].current,'F');
else{
// Straddle case
// CP : case 3a
newMin = INFINITY;
}
}
else{
// else {
// if(s->z->matrix[zoneP][0] <
// chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 4a -- min: %d\n",chkDiv(ineqL[i]->constant,s->r->bound[p-nevents].current,'F'));
//#endif
// newMin = chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F');
if(getDbmEntry(contVar.get_transitionIndex(), 0)
< chkDiv(ineq.getConstant(), getCurrentRate(contVar), false)){
// CP: case 4a -- min
newMin = chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false);
}
// else if((-1)*s->z->matrix[0][zoneP] >
// chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 5a\n");
//#endif
//#ifdef __LHPN_WARN__
// warn("checkPreds: Impossible case 3.\n");
//#endif
// newMin = s->z->matrix[zoneP][0];
else if((-1)*getDbmEntry(contVar.get_transitionIndex(),0)
< chkDiv(ineq.getConstant(), getCurrentRate(contVar), false)){
// Impossible case 3.
newMin = getDbmEntry(0, contVar.get_transitionIndex());
System.err.print("maxAdvance : Impossible case 3.");
}
// else {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 6a -- min: %d\n",s->z->matrix[zoneP][0]);
//#endif
// /* straddle case */
// newMin = s->z->matrix[zoneP][0];
else{
// CP : cas 6a
// straddle case
newMin = getDbmEntry(0,contVar.get_transitionIndex());
}
}
}
// else {
// /* warp <= 0 */
else{
// warp <= 0.
// if(s->m->state[ineqL[i]->signal]=='1') {
if( ineqValue != 1){
// if(s->z->matrix[0][zoneP] <
// (-1)*chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 7a\n");
//#endif
//#ifdef __LHPN_WARN__
// warn("checkPreds: Impossible case 2.\n");
//#endif
// newMin = s->z->matrix[zoneP][0];
if(getDbmEntry(contVar.get_transitionIndex(),0)
< (-1)*chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// CP: case 7a.
newMin = getDbmEntry(0,contVar.get_transitionIndex());
System.err.println("Warining: impossible case 2a found.");
}
// else if((-1)*s->z->matrix[zoneP][0] >
// (-1)*chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 8a\n");
//#endif
// newMin = chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F');
else if((-1)*getDbmEntry(0, contVar.get_transitionIndex())
< (-1)*chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// Impossible case 8a.
newMin = chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false);
}
// else {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 9a\n");
//#endif
// /* straddle case */
// newMin = s->z->matrix[zoneP][0];
else{
// straddle case
newMin = getDbmEntry(0, contVar.get_transitionIndex());
}
}
// else {
else{
// if(s->z->matrix[0][zoneP] <
// (-1)*chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 10a\n");
//#endif
// newMin = chkDiv(events[p]->lrange,
// s->r->bound[p-nevents].current,'F');
if(getDbmEntry(contVar.get_transitionIndex(),0)
< (-1)*chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// CP: case 10a.
newMin = INFINITY;
}
// else if((-1)*s->z->matrix[zoneP][0] >
// (-1)*chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 11a\n");
// printf("z=%d c=%d b=%d\n",
// s->z->matrix[zoneP][0],
// ineqL[i]->constant,
// s->r->bound[p-nevents].current);
//#endif
//#ifdef __LHPN_WARN__
// warn("checkPreds: Impossible case 4.\n");
//#endif
// newMin = s->z->matrix[zoneP][0];
else if((-1)*getDbmEntry(0, contVar.get_transitionIndex())
< (-1)*chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// CP: case 7a.
newMin = getDbmEntry(0,contVar.get_transitionIndex());
System.err.println("maxAdvance : Impossible case 4.");
}
// else {
// /* straddle case */
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 12a\n");
//#endif
// newMin = chkDiv(events[p]->lrange,
// s->r->bound[p-nevents].current,'F');
else{
// straddle case
newMin = INFINITY;
}
}
}
}
// else {
// /* Working on a < or <= ineq */
else{
// Working on a < or <= ineq
// if(s->r->bound[p-nevents].current > 0) {
if(getUpperBoundForRate(contVar) > 0){
// if(s->m->state[ineqL[i]->signal]=='1') {
if(ineqValue != 0){
// if(s->z->matrix[zoneP][0] <
// chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 1b -- min: %d\n",chkDiv(ineqL[i]->constant,s->r->bound[p-nevents].current,'F'));
//#endif
// newMin = chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F');
if(getDbmEntry(0, contVar.get_transitionIndex())
< (-1)*chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// CP: case 1b -- min.
newMin = chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false);
}
// else if((-1)*s->z->matrix[0][zoneP] >
// chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 2b\n");
//#endif
//#ifdef __LHPN_WARN__
// warn("checkPreds: Impossible case 5.\n");
//#endif
// newMin = chkDiv(events[p]->urange,
// s->r->bound[p-nevents].current,'F');
if((-1)*getDbmEntry(contVar.get_transitionIndex(), 0)
< chkDiv(ineq.getConstant(), getCurrentRate(contVar),false)){
// CP: case 2b.
newMin = INFINITY;
System.err.println("Warning : Impossible case 5.");
}
// else {
// /* straddle case */
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 3b -- min: %d\n",s->z->matrix[zoneP][0]);
//#endif
// newMin = s->z->matrix[zoneP][0];
else{
//straddle case
newMin = getDbmEntry(0,contVar.get_transitionIndex());
}
}
// else {
else{
// if(s->z->matrix[zoneP][0] <
// chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 4b\n");
//#endif
//#ifdef __LHPN_WARN__
// warn("checkPreds: Impossible case 7.\n");
//#endif
// newMin = s->z->matrix[zoneP][0];
if(getDbmEntry(0, contVar.get_transitionIndex())
< chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// CP: case 4b.
newMin = getDbmEntry(0, contVar.get_transitionIndex());
System.err.println("maxAdvance : Impossible case 7.");
}
// else if((-1)*s->z->matrix[0][zoneP] >
// chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 5b\n");
//#endif
// newMin = chkDiv(events[p]->urange,
// s->r->bound[p-nevents].current,'F');
else if((-1)*getDbmEntry(contVar.get_transitionIndex(), 0)
< chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// CP: case 5b.
newMin = INFINITY;
}
// else {
// /* straddle case */
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 6b\n");
//#endif
// newMin = chkDiv(events[p]->urange,
// s->r->bound[p-nevents].current,'F');
else{
// straddle case
// CP : case 6b
newMin = INFINITY;
}
}
}
// else {
// /* warp <= 0 */
else {
// warp <=0
// if(s->m->state[ineqL[i]->signal]=='1') {
if(ineqValue != 0){
// if(s->z->matrix[0][zoneP] <
// (-1)*chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 7b\n");
//#endif
// newMin = chkDiv(events[p]->lrange,
// s->r->bound[p-nevents].current,'F');
if(getDbmEntry(contVar.get_transitionIndex(), 0)
< (-1)*chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// CP: case 7b.
newMin = INFINITY;
}
// else if((-1)*s->z->matrix[zoneP][0] >
// (-1)*chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 8b\n");
//#endif
//#ifdef __LHPN_WARN__
// warn("checkPreds: Impossible case 8.\n");
//#endif
// newMin = s->z->matrix[zoneP][0];
else if((-1)*getDbmEntry(0, contVar.get_transitionIndex())
< (-1)*chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// CP: case 8b.
newMin = getDbmEntry(0, contVar.get_transitionIndex());
System.err.println("Warning : Impossible case 8.");
}
// else {
// /* straddle case */
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 9b\n");
//#endif
// newMin = chkDiv(events[p]->lrange,
// s->r->bound[p-nevents].current,'F');
else {
// straddle case
// CP: case 9b.
newMin = INFINITY;
}
}
// else {
else {
// if(s->z->matrix[0][zoneP] <
// chkDiv((-1)*ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 10b\n");
// printf("zone: %d const: %d warp: %d chkDiv: %d\n",s->z->matrix[0][zoneP],ineqL[i]->constant,s->r->bound[p-nevents].current,chkDiv((-1)*ineqL[i]->constant,s->r->bound[p-nevents].current,'F'));
//#endif
//#ifdef __LHPN_WARN__
// warn("checkPreds: Impossible case 6.\n");
//#endif
// newMin = s->z->matrix[zoneP][0];
if(getDbmEntry(contVar.get_transitionIndex(),0)
< (-1)*chkDiv(ineq.getConstant(),
getCurrentRate(contVar), false)){
// CP: case 10b.
newMin = getDbmEntry(0,contVar.get_transitionIndex());
System.err.println("Warning : Impossible case 6");
}
// else if((-1)*s->z->matrix[zoneP][0] >
// (-1)*chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 11b\n");
//#endif
// newMin = chkDiv(ineqL[i]->constant,
// s->r->bound[p-nevents].current,'F');
else if((-1)*getDbmEntry(0,contVar.get_transitionIndex())
< (-1)*chkDiv(ineq.getConstant(),
getCurrentRate(contVar),false)){
// CP: case 7b.
newMin = chkDiv(ineq.getConstant(), getCurrentRate(contVar),false);
}
// else {
// /* straddle case */
//#ifdef __LHPN_PRED_DEBUG__
// printf("CP:case 12b\n");
//#endif
// newMin = s->z->matrix[zoneP][0];
else {
// straddle case
// CP : case 12b
newMin = getDbmEntry(0, contVar.get_transitionIndex());
}
// if(newMin < min) {
// min = newMin;
}
}
}
// Check if the value can be lowered.
if(newMin < min){
min = newMin;
}
}
//#ifdef __LHPN_PRED_DEBUG__
//printf("Min leaving checkPreds for %s: %d\n",events[p]->event,min);
//#endif
//return min;
return min;
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
public Zone clone()
{
// TODO: Check if finished.
Zone clonedZone = new Zone();
clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()];
for(int i=0; i<this.matrixSize(); i++)
{
for(int j=0; j<this.matrixSize(); j++)
{
clonedZone._matrix[i][j] = this._matrix[i][j];
}
}
clonedZone._indexToTimerPair = Arrays.copyOf(_indexToTimerPair, _indexToTimerPair.length);
clonedZone._hashCode = this._hashCode;
clonedZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length);
clonedZone._rateZeroContinuous = this._rateZeroContinuous.clone();
return clonedZone;
}
/**
* Restricts the lower bound of a timer.
*
* @param timer
* The timer to tighten the lower bound.
*/
private void restrict(int timer)
{
//int dbmIndex = Arrays.binarySearch(_indexToTimer, timer);
_matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)]
= getLowerBoundbydbmIndex(timer);
}
/**
* The list of enabled timers.
* @return
* The list of all timers that have reached their lower bounds.
*/
public List<Transition> getEnabledTransitions()
{
ArrayList<Transition> enabledTransitions = new ArrayList<Transition>();
// Check if the timer exceeds its lower bound staring with the first nonzero
// timer.
for(int i=1; i<_indexToTimerPair.length; i++)
{
if(getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i))
{
enabledTransitions.add(_lpnList[_indexToTimerPair[i].get_lpnIndex()]
.getTransition(_indexToTimerPair[i].get_transitionIndex()));
}
}
return enabledTransitions;
}
/**
* Gives the list of enabled transitions associated with a particular LPN.
* @param LpnIndex
* The Index of the LPN the Transitions are a part of.
* @return
* A List of the Transitions that are enabled in the LPN given by the index.
*/
public List<Transition> getEnabledTransitions(int LpnIndex){
ArrayList<Transition> enabledTransitions = new ArrayList<Transition>();
// Check if the timer exceeds its lower bound staring with the first nonzero
// timer.
for(int i=1; i<_indexToTimerPair.length; i++)
{
if(getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i))
{
LPNTransitionPair ltPair = _indexToTimerPair[i];
if( ltPair.get_lpnIndex() == LpnIndex){
enabledTransitions.add(_lpnList[ltPair.get_lpnIndex()]
.getTransition(ltPair.get_transitionIndex()));
}
}
}
return enabledTransitions;
}
/**
* Find the next possible events.
*
* @param LpnIndex
* The index of the LPN that is of interest.
* @param localState
* The state associated with the LPN indexed by LpnIndex.
* @return
* LpnTranList is populated with a list of
* EventSets pertaining to the LPN with index LpnIndex. An EventSet can
* either contain a transition to
* fire or set of inequalities to change sign.
*/
public LpnTranList getPossibleEvents(int LpnIndex, State localState){
LpnTranList result = new LpnTranList();
// Look through the timers and continuous variables. For the timers
// determine if they are ready to fire. For the continuous variables,
// look up the associated inequalities and see if any of them are ready
// to fire.
// for(LPNTransitionPair ltPair : _indexToTimerPair){
for(int i=0; i<_indexToTimerPair.length; i++){
LPNTransitionPair ltPair = _indexToTimerPair[i];
// The enabled events are grouped with the LPN that they affect. So if
// this pair does not belong to the current LPN under consideration, skip
// processing it.
if(ltPair.get_lpnIndex() != LpnIndex){
continue;
}
// If the index refers to a timer (and not a continuous variable) and has exceeded its lower bound,
// then add the transition.
if(!(ltPair instanceof LPNContinuousPair) && getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)){
//result.add(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));
Event e = new Event(_lpnList[ltPair.get_lpnIndex()].getTransition(ltPair.get_transitionIndex()));
addSetItem(result, e, localState);
}
else{
// The index refers to a continuous variable. So check all the inequalities for inclusion.
Variable contVar = _lpnList[ltPair.get_lpnIndex()].getContVar(ltPair.get_transitionIndex());
for(InequalityVariable iv : contVar.getInequalities()){
addSetItem(result, new Event(iv), localState);
}
}
}
return result;
}
/**
* Addes or removes items as appropriate to update the current
* lsit of possible events. Note the type LpnTranList extends
* LinkedList<Transition>. The type EventSet extends transition
* specifically so that objects of EventSet type can be place in
* this list.
* @param EventList
* The list of possible events.
*/
private LpnTranList addSetItem(LpnTranList E, Event e, State s){
// void lhpnAddSetItem(eventSets &E,lhpnEventADT e,ineqList &ineqL,lhpnZoneADT z,
// lhpnRateADT r,eventADT *events,int nevents,
// lhpnStateADT cur_state)
//int rv1l,rv1u,rv2l,rv2u,iZ,jZ;
// Note the LPNTranList plays the role of the eventSets.
int rv1l=0, rv1u=0, rv2l=0, rv2u=0, iZ, jZ;
//#ifdef __LHPN_TRACE__
//printf("lhpnAddSetItem:begin()\n");
//#endif
//#ifdef __LHPN_ADD_ACTION__
//printf("Event sets entering:\n");
//printEventSets(E,events,ineqL);
//printf("Examining event: ");
//printLhpnEvent(e,events,ineqL);
//#endif
//eventSet* eSet = new eventSet();
//eventSets* newE = new eventSets();
//bool done = false;
//bool possible = true;
//eventSets::iterator i;
// Create the new LpnTranlist for holding the events.
EventSet eSet = new EventSet();
LpnTranList newE = new LpnTranList();
boolean done = false;
boolean possible = true;
//if ((e->t == -1) && (e->ineq == -1)) {
if(e.isRate()){
//eSet->insert(e);
eSet.add(e);
//newE->push_back(*eSet);
newE.addLast(eSet);
//E.clear();
//E = *newE;
// The previous two commands act to pass the changes of E
// back out of the functions. So returning the new object
// is suficient.
//#ifdef __LHPN_ADD_ACTION__
//printf("Event sets leaving:\n");
//printEventSets(E,events,ineqL);
//#endif
//#ifdef __LHPN_TRACE__
//printf("lhpnAddSetItem:end()\n");
//#endif
//return;
return newE;
}
//if (e->t == -1) {
if(e.isInequality()){
//ineq_update(ineqL[e->ineq],cur_state,nevents);
// Is this necessary, or even correct to update the inequalities.
System.out.println("Note the inequality is not being updated before in addSetItem");
// In this case the Event e represents an inequality.
InequalityVariable ineq = e.getInequalityVariable();
//rv2l = chkDiv(-1 * ineqL[e->ineq]->constant,
// r->bound[ineqL[e->ineq]->place-nevents].current,'C');
//rv2u = chkDiv(ineqL[e->ineq]->constant,
// r->bound[ineqL[e->ineq]->place-nevents].current,'C');
//iZ = getIndexZ(z,-2,ineqL[e->ineq]->place);
// Need to extract the rate.
// To do this, I'll create the indexing object.
Variable v = ineq.getContVariables().get(0);
// Find the LPN.
int lpnIndex = ineq.get_lpn().getLpnIndex();
int varIndex = _lpnList[lpnIndex].
getContinuousIndexMap().getValue(v.getName());
// Package it all up.
// LPNTransitionPair ltPair =
// new LPNTransitionPair(lpnIndex, varIndex, false);
// Note : setting the rate is not necessary since
// this is only being used as aan index.
LPNContinuousPair ltPair =
new LPNContinuousPair(lpnIndex, varIndex, 0);
rv2l = chkDiv(-1*ineq.getConstant(), getCurrentRate(ltPair), true);
rv2u = chkDiv(ineq.getConstant(), getCurrentRate(ltPair), true);
iZ = Arrays.binarySearch(_indexToTimerPair, ltPair);
//} else {
}
else{
//iZ = getIndexZ(z,-1,e->t);
// In this case, the event is a transition.
Transition t = e.getTransition();
int lpnIndex = t.getLpn().getLpnIndex();
int tranIndex = t.getIndex();
// Package the results.
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex, true);
LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, tranIndex);
iZ = Arrays.binarySearch(_indexToTimerPair, ltPair);
}
//for(i=E.begin();i!=E.end()&&!done;i++) {
for(Transition es : E){
if(!(es instanceof EventSet)){
// This collection should contain event sets, not transitions.
throw new IllegalArgumentException("The eventSet was a Transition object not an EventSet object.");
}
EventSet eventSet = (EventSet) es;
//eventSet* workSet = new eventSet();
// /* Both actions are predicate changes */
// /* Both predicates are on the same variable */
// /* Predicates are on different variables */
// /* New action is predicate change, old is transition firing (case 3) */
// /* TODO: One more ugly case, is it needed? */
// /* New action is transition firing, old is predicate change (case 4) */
// /* TODO: one more ugly case, is it needed? */
/**
* Updates the continuous variables that are set by firing a transition.
* @param firedTran
* The transition that fired.
* @param s
* The current (local) state.
*/
public void updateContinuousAssignment(Transition firedTran, State s){
// Get the LPN.
LhpnFile lpn = _lpnList[firedTran.getLpn().getLpnIndex()];
// Get the current values of the (local) state.
HashMap<String,String> currentValues =
lpn.getAllVarsWithValuesAsString(s.getVector());
// Get all the continuous variable assignments.
HashMap<String, ExprTree> assignTrees = firedTran.getContAssignTrees();
for(String contVar : assignTrees.keySet()){
// Get the bounds to assign the continuous variables.
IntervalPair assignment =
assignTrees.get(contVar).evaluateExprBound(currentValues, this);
// Make the assignment.
setContinuousBounds(contVar, lpn, assignment);
}
}
/* (non-Javadoc)
* @see verification.timed_state_exploration.zone.Zone#getLexicon()
*/
// public HashMap<Integer, Transition> getLexicon(){
// if(_indexToTransition == null){
// return null;
// return new HashMap<Integer, Transition>(_indexToTransition);
// public void setLexicon(HashMap<Integer, Transition> lexicon){
// _indexToTransition = lexicon;
/**
* Gives an array that maps the index of a timer in the DBM to the timer's index.
* @return
* The array that maps the index of a timer in the DBM to the timer's index.
*/
// public int[] getIndexToTimer(){
// return Arrays.copyOf(_indexToTimerPair, _indexToTimerPair.length);
/**
* Calculates a warping value needed to warp a Zone. When a zone is being warped the form
* r1*z2 - r1*z1 + r2*z1 becomes important in finding the new values of the zone. For example,
*
* @param z1
* Upper bound or negative lower bound.
* @param z2
* Relative value.
* @param r1
* First ratio.
* @param r2
* Second ratio.
* @return
* r1*z2 - r1*z1 + r2*z1
*/
public int warp(int z1, int z2, int r1, int r2){
/*
* See "Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets"
* by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda
* Section III.C for details on how this function is used and where it comes
* from.
*/
return r1*z2 - r1*z1 + r2*z1;
}
/**
* Warps a Zone.
* @return
* The warped Zone.
*/
public Zone dmbWarp(){
/*
* See "Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets"
* by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda
* Section III.C for details on how this function is used and where it comes
* from.
*/
return null;
}
/**
* The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion.
* The intention is for this exception to be thrown is a Zone has a non zero
* entry appear on the diagonal.
*
* @author Andrew N. Fisher
*
*/
public class DiagonalNonZeroException extends java.lang.RuntimeException
{
/**
* Generated serialVersionUID.
*/
private static final long serialVersionUID = -3857736741611605411L;
/**
* Creates a DiagonalNonZeroException.
* @param Message
* The message to be displayed when the exception is thrown.
*/
public DiagonalNonZeroException(String Message)
{
super(Message);
}
}
/**
* This exception is thrown when trying to merge two zones whose corresponding timers
* do not agree.
* @author Andrew N. Fisher
*
*/
// public class IncompatibleZoneException extends java.lang.RuntimeException
// // TODO : Check if this class can be removed.
// /**
// * Generated serialVersionUID
// */
// private static final long serialVersionUID = -2453680267411313227L;
// public IncompatibleZoneException(String Message)
// super(Message);
/**
* Clears out the lexicon.
*/
// public static void clearLexicon(){
// _indexToTransition = null;
private IntervalPair parseRate(String rate){
String rateNoSpaces = rate.trim();
// First check if the string is a single number.
// Integer i = Integer.parseInt(rate);
// if(i != null){
// // The string is a number, so set the upper and lower bounds equal.
// return new IntervalPair(i,i);
// First check for a comma (representing an interval input).
int commaIndex = rateNoSpaces.indexOf(",");
if(commaIndex < 0){
// Assume that the string is a constant. A NumberFormatException
// will be thrown otherwise.
int i = Integer.parseInt(rate);
return new IntervalPair(i,i);
}
String lowerString = rateNoSpaces.substring(1, commaIndex).trim();
String upperString = rateNoSpaces.substring(commaIndex+1,
rateNoSpaces.length()-1).trim();
return new IntervalPair(Integer.parseInt(lowerString),
Integer.parseInt(upperString));
}
/**
* Get the list of LhpnFile objects that this Zone depends on.
* @return
* The lits of LhpnFile objects that this Zone depends on.
*/
public LhpnFile[] get_lpnList(){
return _lpnList;
}
/**
* Performs a division of two integers and either takes the ceiling or the floor. Note :
* The integers are converted to doubles for the division so the choice of ceiling or floor is
* meaningful.
* @param top
* The numerator.
* @param bottom
* The denominator.
* @param ceil
* True indicates return the ceiling and false indicates return the floor.
* @return
* Returns the ceiling of top/bottom if ceil is true and the floor of top/bottom otherwise.
*/
public int chkDiv(int top, int bottom, Boolean ceil){
/*
* This method was taken from atacs/src/hpnrsg.c
*/
int res = 0;
if(top == INFINITY ||
top == INFINITY * -1) {
if(bottom < 0) {
return top * -1;
}
return top;
}
if(bottom == INFINITY) {
return 0;
}
if(bottom == 0) {
System.out.println("Warning: Divided by zero.");
bottom = 1;
}
double Dres,Dtop,Dbottom;
Dtop = top;
Dbottom = bottom;
Dres = Dtop/Dbottom;
if(ceil) {
res = (int)Math.ceil(Dres);
}
else if(!ceil) {
res = (int)Math.floor(Dres);
}
return res;
}
public int getCurrentRate(LPNTransitionPair contVar){
if(!(contVar instanceof LPNContinuousPair)){
// The LPNTransitionsPair does not refer to a continuous variable, so yell.
throw new IllegalArgumentException("Zone.getCurrentRate was called" +
" on an LPNTransitionPair that was not an LPNContinuousPair.");
}
LPNContinuousPair cV = (LPNContinuousPair) contVar;
return cV.getCurrentRate();
}
/**
* Sets the current rate for a continuous variable. It sets the rate regardless of
* whether the variable is in the rate zero portion of the Zone or not.
* @param contVar
* The index of the variable whose rate is going to be set.
* @param currentRate
* The value of the rate.
*/
public void setCurrentRate(LPNTransitionPair contVar, int currentRate){
if(!(contVar instanceof LPNContinuousPair)){
// The LPNTransitionsPair does not refer to a continuous variable, so yell.
throw new IllegalArgumentException("Zone.getCurrentRate was called" +
" on an LPNTransitionPair that was not an LPNContinuousPair.");
}
LPNContinuousPair cV = (LPNContinuousPair) contVar;
// Check for the current variable in the rate zero variables.
VariableRangePair variableRange = _rateZeroContinuous.getValue(contVar);
if(variableRange != null){
LPNContinuousPair lcPair = (LPNContinuousPair)_rateZeroContinuous.getKey(variableRange);
lcPair.setCurrentRate(currentRate);
return;
}
// Check for the current variable in the Zone varaibles.
int index = Arrays.binarySearch(_indexToTimerPair, contVar);
if(index >= 0){
// The variable was found, set the rate.
LPNContinuousPair lcPair = (LPNContinuousPair) _indexToTimerPair[index];
lcPair.setCurrentRate(currentRate);
}
}
private boolean inequalityCanChange(InequalityVariable ineq, State[] localStates){
// Find the index of the continuous variable this inequality refers to.
// I'm assuming there is a single variable.
LhpnFile lpn = ineq.get_lpn();
Variable contVar = ineq.getInequalities().get(0);
DualHashMap<String, Integer> variableIndecies = lpn.getContinuousIndexMap();
int contIndex = variableIndecies.get(contVar);
// Package up the information into a the index. Note the current rate doesn't matter.
LPNContinuousPair index = new LPNContinuousPair(lpn.getLpnIndex(), contIndex, 0);
// Get the current rate.
int currentRate = getCurrentRate(index);
// Get the current value of the inequality. This requires looking into the current state.
int currentValue = localStates[lpn.getLpnIndex()].getCurrentValue(contIndex);
// Get the Zone index of the variable.
int zoneIndex = Arrays.binarySearch(_indexToTimerPair, index);
// bool lhpnPredCanChange(ineqADT ineq,lhpnZoneADT z,lhpnRateADT r,
// lhpnMarkingADT m,eventADT *events,int nevents,
// lhpnStateADT s)
//ineq_update(ineq,s,nevents);
//#ifdef __LHPN_TRACE__
//printf("lhpnPredCanChange:begin()\n");
//#endif
//#ifdef __LHPN_PRED_DEBUG__
//printf("lhpnPredCanChange Examining: ");
//printI(ineq,events);
//printf("signal = %c, %d",s->m->state[ineq->signal],r->bound[ineq->place-nevents].current);
//printf("\n");
//if (r->bound[ineq->place-nevents].current != 0)
//printf("divRes: %d\n",chkDiv(ineq->constant,
// r->bound[ineq->place-nevents].current,'F'));
//#endif
//
//if(ineq->type == 0 || ineq->type == 1) {
if(ineq.get_op().contains(">")){
//int zoneP = getIndexZ(z,-2,ineq->place);
//if(zoneP == -1) {
//warn("An inequality produced a place not in the zone.");
//return false;
//if(r->bound[ineq->place-nevents].current < 0 &&
//m->state[ineq->signal] == '1') {
// First check cases when the rate is negative.
if(currentRate < 0 && currentValue != 0){
//if((-1)*z->matrix[zoneP][0] <=
// (-1)*chkDiv(ineq->constant,r->bound[ineq->place-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("predCanChange:1\n");
// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
// return true;
if((-1) * getDbmEntry(0, zoneIndex) <=
(-1)*chkDiv(ineq.getConstant(), currentRate, false)){
return true;
}
//} else {
//#ifdef __LHPN_PRED_DEBUG__
// printf("predCannotChange:1\n");
// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
// return false;
else{
return false;
}
}
//else if(r->bound[ineq->place-nevents].current > 0 &&
// m->state[ineq->signal] == '0') {
else if(currentRate > 0 && currentValue == 0){
//if(z->matrix[zoneP][0] >=
// chkDiv(ineq->constant,r->bound[ineq->place-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("predCanChange:2\n");
// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
// return true;
if(getDbmEntry(0, zoneIndex) <=
chkDiv(ineq.getConstant(), currentRate, false)){
return true;
}
//} else {
//#ifdef __LHPN_PRED_DEBUG__
// printf("predCannotChange:2\n");
// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
//return false;
else{
return false;
}
}
//else {
//#ifdef __LHPN_PRED_DEBUG__
//printf("predCannotChange:3\n");
//printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
//return false;
}
//
//else if(ineq->type == 2 || ineq->type == 3) {
else if(ineq.get_op().contains("<")){
//int zoneP = getIndexZ(z,-2,ineq->place);
//if(zoneP == -1) {
//warn("An inequality produced a place not in the zone.");
//return false;
//if(r->bound[ineq->place-nevents].current < 0 &&
//m->state[ineq->signal] == '0') {
if(currentRate < 0 && currentValue == 0){
//if((-1)*z->matrix[zoneP][0] <=
// (-1)*chkDiv(ineq->constant,r->bound[ineq->place-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("predCanChange:4\n");
// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
// return true;
if((-1) * getDbmEntry(0, zoneIndex) <=
(-1)*chkDiv(ineq.getConstant(), currentRate, false)){
return true;
}
//} else {
//#ifdef __LHPN_PRED_DEBUG__
// printf("predCannotChange:4\n");
// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
// return false;
else{
return false;
}
}
//else if(r->bound[ineq->place-nevents].current > 0 &&
// m->state[ineq->signal] == '1') {
else if (currentRate > 0 &&
currentValue != 0){
//if(z->matrix[zoneP][0] >=
// chkDiv(ineq->constant,r->bound[ineq->place-nevents].current,'F')) {
//#ifdef __LHPN_PRED_DEBUG__
// printf("predCanChange:5\n");
// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
// return true;
if(getDbmEntry(0, zoneIndex) >=
chkDiv(ineq.getConstant(), currentRate, false)){
return true;
}
//} else {
//#ifdef __LHPN_PRED_DEBUG__
// printf("predCannotChange:5\n");
// printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
// return false;
else {
return false;
}
}
//else {
//#ifdef __LHPN_PRED_DEBUG__
//printf("predCanChange:6\n");
//printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
//return false;
else {
return false;
}
}
//#ifdef __LHPN_PRED_DEBUG__
//printf("predCanChange:7\n");
//printf("rate: %d state: %c\n",r->bound[ineq->place-nevents].current,
// m->state[ineq->signal]);
//#endif
//return false;
return false;
}
/**
* Gives the Zone obtained by firing a given Transitions.
* @param t
* The transitions being fired.
* @param enabledTran
* The list of currently enabled Transitions.
* @param localStates
* The current local states.
* @return
* The Zone obtained by firing Transition t with enabled Transitions enabled
* enabledTran when the current state is localStates.
*/
public Zone fire(EventSet eventset, LpnTranList enabledTran, State[] localStates){
// // Create the LPNTransitionPair to check if the Transitions is in the zone and to
// // find the index.
// LhpnFile lpn = t.getLpn();
// int lpnIndex = lpn.getLpnIndex();
// int transitionIndex = t.getIndex();
//// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true);
// LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex);
// int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair);
// if(dbmIndex <= 0){
// return this;
// // Get the new zone portion.
// Zone newZone = fireTransitionbydbmIndex(dbmIndex, enabledTran, localStates);
// // Update any assigned continuous variables.
// newZone.updateContinuousAssignment(t, localStates[lpnIndex]);
// //return fireTransitionbydbmIndex(dbmIndex, enabledTran, localStates);
// return newZone;
// Determine whether the event set is a set of inequalities or a transition.
if(eventset.isInequalities()){
}
return null;
}
}
|
package hex.tree.xgboost;
import hex.*;
import hex.genmodel.utils.DistributionFamily;
import hex.glm.GLMTask;
import hex.tree.xgboost.rabit.RabitTrackerH2O;
import ml.dmlc.xgboost4j.java.Booster;
import ml.dmlc.xgboost4j.java.DMatrix;
import ml.dmlc.xgboost4j.java.XGBoostError;
import water.*;
import ml.dmlc.xgboost4j.java.*;
import water.exceptions.H2OIllegalArgumentException;
import water.exceptions.H2OModelBuilderIllegalArgumentException;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.*;
import water.util.Timer;
import java.io.*;
import java.util.*;
import static hex.tree.SharedTree.createModelSummaryTable;
import static hex.tree.SharedTree.createScoringHistoryTable;
import static water.H2O.technote;
/** Gradient Boosted Trees
*
* Based on "Elements of Statistical Learning, Second Edition, page 387"
*/
public class XGBoost extends ModelBuilder<XGBoostModel,XGBoostModel.XGBoostParameters,XGBoostOutput> {
private static final double FILL_RATIO_THRESHOLD = 0.25D;
@Override public boolean haveMojo() { return true; }
@Override public BuilderVisibility builderVisibility() {
if(ExtensionManager.getInstance().isCoreExtensionsEnabled(XGBoostExtension.NAME)){
return BuilderVisibility.Stable;
} else {
return BuilderVisibility.Experimental;
}
}
@Override public ModelCategory[] can_build() {
return new ModelCategory[]{
ModelCategory.Regression,
ModelCategory.Binomial,
ModelCategory.Multinomial,
};
}
// Called from an http request
public XGBoost(XGBoostModel.XGBoostParameters parms ) { super(parms ); init(false); }
public XGBoost(XGBoostModel.XGBoostParameters parms, Key<XGBoostModel> key) { super(parms, key); init(false); }
public XGBoost(boolean startup_once) { super(new XGBoostModel.XGBoostParameters(),startup_once); }
public boolean isSupervised(){return true;}
/** Start the XGBoost training Job on an F/J thread. */
@Override protected XGBoostDriver trainModelImpl() {
return new XGBoostDriver();
}
/** Initialize the ModelBuilder, validating all arguments and preparing the
* training frame. This call is expected to be overridden in the subclasses
* and each subclass will start with "super.init();". This call is made
* by the front-end whenever the GUI is clicked, and needs to be fast;
* heavy-weight prep needs to wait for the trainModel() call.
*
* Validate the learning rate and distribution family. */
@Override public void init(boolean expensive) {
super.init(expensive);
if (H2O.CLOUD.size() > 1) {
if(H2O.SELF.getSecurityManager().securityEnabled) {
throw new H2OIllegalArgumentException("Cannot run XGBoost on an SSL enabled cluster larger than 1 node. XGBoost does not support SSL encryption.");
}
}
if (expensive) {
if (_response.naCnt() > 0) {
error("_response_column", "Response contains missing values (NAs) - not supported by XGBoost.");
}
if(!new XGBoostExtensionCheck().doAllNodes().enabled) {
error("XGBoost", "XGBoost is not available on all nodes!");
}
}
// Initialize response based on given distribution family.
// Regression: initially predict the response mean
// Binomial: just class 0 (class 1 in the exact inverse prediction)
// Multinomial: Class distribution which is not a single value.
// However there is this weird tension on the initial value for
// classification: If you guess 0's (no class is favored over another),
// then with your first GBM tree you'll typically move towards the correct
// answer a little bit (assuming you have decent predictors) - and
// immediately the Confusion Matrix shows good results which gradually
// improve... BUT the Means Squared Error will suck for unbalanced sets,
// even as the CM is good. That's because we want the predictions for the
// common class to be large and positive, and the rare class to be negative
// and instead they start around 0. Guessing initial zero's means the MSE
// is so bad, that the R^2 metric is typically negative (usually it's
// between 0 and 1).
// If instead you guess the mean (reversed through the loss function), then
// the zero-tree XGBoost model reports an MSE equal to the response variance -
// and an initial R^2 of zero. More trees gradually improves the R^2 as
// expected. However, all the minority classes have large guesses in the
// wrong direction, and it takes a long time (lotsa trees) to correct that
// - so your CM sucks for a long time.
if (expensive) {
if (error_count() > 0)
throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(XGBoost.this);
if (hasOffsetCol()) {
error("_offset_column", "Offset is not supported for XGBoost.");
}
}
if ( _parms._backend == XGBoostModel.XGBoostParameters.Backend.gpu) {
if (! hasGPU(_parms._gpu_id))
error("_backend", "GPU backend (gpu_id: " + _parms._gpu_id + ") is not functional. Check CUDA_PATH and/or GPU installation.");
if (H2O.getCloudSize() > 1)
error("_backend", "GPU backend is not supported in distributed mode.");
Map<String, Object> incompats = _parms.gpuIncompatibleParams();
if (! incompats.isEmpty())
for (Map.Entry<String, Object> incompat : incompats.entrySet())
error("_backend", "GPU backend is not available for parameter setting '" + incompat.getKey() + " = " + incompat.getValue() + "'. Use CPU backend instead.");
}
if (_parms._distribution == DistributionFamily.quasibinomial)
error("_distribution", "Quasibinomial is not supported for XGBoost in current H2O.");
switch( _parms._distribution) {
case bernoulli:
if( _nclass != 2 /*&& !couldBeBool(_response)*/)
error("_distribution", technote(2, "Binomial requires the response to be a 2-class categorical"));
break;
case modified_huber:
if( _nclass != 2 /*&& !couldBeBool(_response)*/)
error("_distribution", technote(2, "Modified Huber requires the response to be a 2-class categorical."));
break;
case multinomial:
if (!isClassifier()) error("_distribution", technote(2, "Multinomial requires an categorical response."));
break;
case huber:
if (isClassifier()) error("_distribution", technote(2, "Huber requires the response to be numeric."));
break;
case poisson:
if (isClassifier()) error("_distribution", technote(2, "Poisson requires the response to be numeric."));
break;
case gamma:
if (isClassifier()) error("_distribution", technote(2, "Gamma requires the response to be numeric."));
break;
case tweedie:
if (isClassifier()) error("_distribution", technote(2, "Tweedie requires the response to be numeric."));
break;
case gaussian:
if (isClassifier()) error("_distribution", technote(2, "Gaussian requires the response to be numeric."));
break;
case laplace:
if (isClassifier()) error("_distribution", technote(2, "Laplace requires the response to be numeric."));
break;
case quantile:
if (isClassifier()) error("_distribution", technote(2, "Quantile requires the response to be numeric."));
break;
case AUTO:
break;
default:
error("_distribution","Invalid distribution: " + _parms._distribution);
}
if( !(0. < _parms._learn_rate && _parms._learn_rate <= 1.0) )
error("_learn_rate", "learn_rate must be between 0 and 1");
if( !(0. < _parms._col_sample_rate && _parms._col_sample_rate <= 1.0) )
error("_col_sample_rate", "col_sample_rate must be between 0 and 1");
if (_parms._grow_policy== XGBoostModel.XGBoostParameters.GrowPolicy.lossguide && _parms._tree_method!= XGBoostModel.XGBoostParameters.TreeMethod.hist)
error("_grow_policy", "must use tree_method=hist for grow_policy=lossguide");
if ((_train != null) && (_parms._monotone_constraints != null)) {
// we check that there are no duplicate definitions and constraints are defined only for numerical columns
Set<String> constrained = new HashSet<>();
for (KeyValue constraint : _parms._monotone_constraints) {
if (constrained.contains(constraint.getKey())) {
error("_monotone_constraints", "Feature '" + constraint.getKey() + "' has multiple constraints.");
continue;
}
constrained.add(constraint.getKey());
Vec v = _train.vec(constraint.getKey());
if (v == null) {
error("_monotone_constraints", "Invalid constraint - there is no column '" + constraint.getKey() + "' in the training frame.");
} else if (v.get_type() != Vec.T_NUM) {
error("_monotone_constraints", "Invalid constraint - column '" + constraint.getKey() +
"' has type " + v.get_type_str() + ". Only numeric columns can have monotonic constraints.");
}
}
}
}
static DataInfo makeDataInfo(Frame train, Frame valid, XGBoostModel.XGBoostParameters parms, int nClasses) {
DataInfo dinfo = new DataInfo(
train,
valid,
1, //nResponses
true, //all factor levels
DataInfo.TransformType.NONE, //do not standardize
DataInfo.TransformType.NONE, //do not standardize response
parms._missing_values_handling == XGBoostModel.XGBoostParameters.MissingValuesHandling.Skip, //whether to skip missing
false, // do not replace NAs in numeric cols with mean
true, // always add a bucket for missing values
parms._weights_column != null, // observation weights
parms._offset_column != null,
parms._fold_column != null
);
// Checks and adjustments:
// 1) observation weights (adjust mean/sigmas for predictors and response)
// 2) NAs (check that there's enough rows left)
GLMTask.YMUTask ymt = new GLMTask.YMUTask(dinfo, nClasses,nClasses == 1, parms._missing_values_handling == XGBoostModel.XGBoostParameters.MissingValuesHandling.Skip, true, true).doAll(dinfo._adaptedFrame);
if (ymt.wsum() == 0 && parms._missing_values_handling == XGBoostModel.XGBoostParameters.MissingValuesHandling.Skip)
throw new H2OIllegalArgumentException("No rows left in the dataset after filtering out rows with missing values. Ignore columns with many NAs or set missing_values_handling to 'MeanImputation'.");
if (parms._weights_column != null && parms._offset_column != null) {
Log.warn("Combination of offset and weights can lead to slight differences because Rollupstats aren't weighted - need to re-calculate weighted mean/sigma of the response including offset terms.");
}
if (parms._weights_column != null && parms._offset_column == null /*FIXME: offset not yet implemented*/) {
dinfo.updateWeightedSigmaAndMean(ymt.predictorSDs(), ymt.predictorMeans());
if (nClasses == 1)
dinfo.updateWeightedSigmaAndMeanForResponse(ymt.responseSDs(), ymt.responseMeans());
}
dinfo.coefNames(); // cache the coefficient names
assert dinfo._coefNames != null;
return dinfo;
}
public static byte[] getRawArray(Booster booster) {
if(null == booster) {
return null;
}
byte[] rawBooster;
try {
Map<String, String> localRabitEnv = new HashMap<>();
Rabit.init(localRabitEnv);
rawBooster = booster.toByteArray();
Rabit.shutdown();
} catch (XGBoostError xgBoostError) {
throw new IllegalStateException("Failed to initialize Rabit or serialize the booster.", xgBoostError);
}
return rawBooster;
}
class XGBoostDriver extends Driver {
// Per driver instance
final private String featureMapFileName = "featureMap" + UUID.randomUUID().toString() + ".txt";
// Shared file to write list of features
private String featureMapFileAbsolutePath = null;
@Override
public void computeImpl() {
init(true); //this can change the seed if it was set to -1
// Something goes wrong
if (error_count() > 0)
throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(XGBoost.this);
buildModel();
}
final void buildModel() {
if ((XGBoostModel.XGBoostParameters.Backend.auto.equals(_parms._backend) || XGBoostModel.XGBoostParameters.Backend.gpu.equals(_parms._backend)) &&
hasGPU(_parms._gpu_id) && H2O.getCloudSize() == 1 && _parms.gpuIncompatibleParams().isEmpty()) {
synchronized (XGBoostGPULock.lock(_parms._gpu_id)) {
buildModelImpl();
}
} else {
buildModelImpl();
}
}
final void buildModelImpl() {
XGBoostModel model = new XGBoostModel(_result, _parms, new XGBoostOutput(XGBoost.this), _train, _valid);
model.write_lock(_job);
if (_parms._dmatrix_type == XGBoostModel.XGBoostParameters.DMatrixType.sparse) {
model._output._sparse = true;
} else if (_parms._dmatrix_type == XGBoostModel.XGBoostParameters.DMatrixType.dense) {
model._output._sparse = false;
} else {
model._output._sparse = isTrainDatasetSparse();
}
// Single Rabit tracker per job. Manages the node graph for Rabit.
final IRabitTracker rt;
XGBoostSetupTask setupTask = null;
try {
XGBoostSetupTask.FrameNodes trainFrameNodes = XGBoostSetupTask.findFrameNodes(_train);
// Prepare Rabit tracker for this job
// This cannot be H2O.getCloudSize() as a frame might not be distributed on all the nodes
// In such a case we'll perform training only on a subset of nodes while XGBoost/Rabit would keep waiting
// for H2O.getCloudSize() number of requests/responses.
rt = new RabitTrackerH2O(trainFrameNodes.getNumNodes());
if (!startRabitTracker(rt)) {
throw new IllegalArgumentException("Cannot start XGboost rabit tracker, please, "
+ "make sure you have python installed!");
}
// Create a "feature map" and store in a temporary file (for Variable Importance, MOJO, ...)
DataInfo dataInfo = model.model_info().dataInfo();
assert dataInfo != null;
String featureMap = XGBoostUtils.makeFeatureMap(_train, dataInfo);
model.model_info().setFeatureMap(featureMap);
featureMapFileAbsolutePath = createFeatureMapFile(featureMap);
BoosterParms boosterParms = XGBoostModel.createParams(_parms, model._output.nclasses(), dataInfo.coefNames());
model._output._native_parameters = boosterParms.toTwoDimTable();
setupTask = new XGBoostSetupTask(model, _parms, boosterParms, getWorkerEnvs(rt), trainFrameNodes).run();
try {
// initial iteration
XGBoostUpdateTask nullModelTask = new XGBoostUpdateTask(setupTask, 0).run();
BoosterProvider boosterProvider = new BoosterProvider(model.model_info(), nullModelTask);
// train the model
scoreAndBuildTrees(setupTask, boosterProvider, model);
// shutdown rabit & XGB native resources
XGBoostCleanupTask.cleanUp(setupTask);
setupTask = null;
waitOnRabitWorkers(rt);
} finally {
stopRabitTracker(rt);
}
} catch (XGBoostError xgBoostError) {
xgBoostError.printStackTrace();
throw new RuntimeException("XGBoost failure", xgBoostError);
} finally {
if (setupTask != null) {
try {
XGBoostCleanupTask.cleanUp(setupTask);
} catch (Exception e) {
Log.err("XGBoost clean-up failed - this could leak memory!", e);
}
}
// Unlock & save results
model.unlock(_job);
}
}
/**
* @return True if train dataset is sparse, otherwise false.
*/
private boolean isTrainDatasetSparse() {
long nonZeroCount = 0;
int nonCategoricalColumns = 0;
long oneHotEncodedColumns = 0;
for (int i = 0; i < _train.numCols(); ++i) {
if (_train.name(i).equals(_parms._response_column)) continue;
if (_train.name(i).equals(_parms._weights_column)) continue;
if (_train.name(i).equals(_parms._fold_column)) continue;
if (_train.name(i).equals(_parms._offset_column)) continue;
final Vec vector = _train.vec(i);
if (vector.isCategorical()) {
nonZeroCount += _train.numRows();
} else {
nonZeroCount += vector.nzCnt();
}
if (vector.isCategorical()) {
oneHotEncodedColumns += vector.cardinality();
} else {
nonCategoricalColumns++;
}
}
final long totalColumns = oneHotEncodedColumns + nonCategoricalColumns;
final double denominator = (double) totalColumns * _train.numRows();
final double fillRatio = (double) nonZeroCount / denominator;
Log.info("fill ratio: " + fillRatio);
return fillRatio < FILL_RATIO_THRESHOLD
|| ((_train.numRows() * totalColumns) > Integer.MAX_VALUE);
}
// For feature importances - write out column info
private String createFeatureMapFile(String featureMap) {
OutputStream os = null;
try {
File tmpModelDir = java.nio.file.Files.createTempDirectory("xgboost-model-" + _result.toString()).toFile();
File fmFile = new File(tmpModelDir, featureMapFileName);
os = new FileOutputStream(fmFile);
os.write(featureMap.getBytes());
os.close();
return fmFile.getAbsolutePath();
} catch (IOException e) {
throw new RuntimeException("Cannot generate feature map file " + featureMapFileName, e);
} finally {
FileUtils.close(os);
}
}
private void scoreAndBuildTrees(final XGBoostSetupTask setupTask, final BoosterProvider boosterProvider,
final XGBoostModel model) throws XGBoostError {
for( int tid=0; tid< _parms._ntrees; tid++) {
// During first iteration model contains 0 trees, then 1-tree, ...
boolean scored = doScoring(model, boosterProvider, false);
if (scored && ScoreKeeper.stopEarly(model._output.scoreKeepers(), _parms._stopping_rounds, _nclass > 1, _parms._stopping_metric, _parms._stopping_tolerance, "model's last", true)) {
Log.info("Early stopping triggered - stopping XGBoost training");
break;
}
Timer kb_timer = new Timer();
XGBoostUpdateTask t = new XGBoostUpdateTask(setupTask, tid).run();
boosterProvider.reset(t);
Log.info((tid + 1) + ". tree was built in " + kb_timer.toString());
_job.update(1);
model._output._ntrees++;
model._output._scored_train = ArrayUtils.copyAndFillOf(model._output._scored_train, model._output._ntrees+1, new ScoreKeeper());
model._output._scored_valid = model._output._scored_valid != null ? ArrayUtils.copyAndFillOf(model._output._scored_valid, model._output._ntrees+1, new ScoreKeeper()) : null;
model._output._training_time_ms = ArrayUtils.copyAndFillOf(model._output._training_time_ms, model._output._ntrees+1, System.currentTimeMillis());
if (stop_requested() && !timeout()) throw new Job.JobCancelledException();
if (timeout()) {
Log.info("Stopping XGBoost training because of timeout");
break;
}
}
_job.update(0, "Scoring the final model");
// Final scoring
doScoring(model, boosterProvider, true);
// Finish remaining work (if stopped early)
_job.update(_parms._ntrees-model._output._ntrees);
}
// Don't start the tracker for 1 node clouds -> the GPU plugin fails in such a case
private boolean startRabitTracker(IRabitTracker rt) {
if (H2O.CLOUD.size() > 1) {
return rt.start(0);
}
return true;
}
// RT should not be started for 1 node clouds
private void waitOnRabitWorkers(IRabitTracker rt) {
if(H2O.CLOUD.size() > 1) {
rt.waitFor(0);
}
}
/**
*
* @param rt Rabit tracker to stop
*/
private void stopRabitTracker(IRabitTracker rt){
if(H2O.CLOUD.size() > 1) {
rt.stop();
}
}
// XGBoost seems to manipulate its frames in case of a 1 node distributed version in a way the GPU plugin can't handle
// Therefore don't use RabitTracker envs for 1 node
private Map<String, String> getWorkerEnvs(IRabitTracker rt) {
if(H2O.CLOUD.size() > 1) {
return rt.getWorkerEnvs();
} else {
return new HashMap<>();
}
}
long _firstScore = 0;
long _timeLastScoreStart = 0;
long _timeLastScoreEnd = 0;
private boolean doScoring(XGBoostModel model,
BoosterProvider boosterProvider,
boolean finalScoring) throws XGBoostError {
boolean scored = false;
long now = System.currentTimeMillis();
if (_firstScore == 0) _firstScore = now;
long sinceLastScore = now - _timeLastScoreStart;
_job.update(0, "Built " + model._output._ntrees + " trees so far (out of " + _parms._ntrees + ").");
boolean timeToScore = (now - _firstScore < _parms._initial_score_interval) || // Score every time for 4 secs
// Throttle scoring to keep the cost sane; limit to a 10% duty cycle & every 4 secs
(sinceLastScore > _parms._score_interval && // Limit scoring updates to every 4sec
(double) (_timeLastScoreEnd - _timeLastScoreStart) / sinceLastScore < 0.1); //10% duty cycle
boolean manualInterval = _parms._score_tree_interval > 0 && model._output._ntrees % _parms._score_tree_interval == 0;
// Now model already contains tid-trees in serialized form
if (_parms._score_each_iteration || finalScoring || // always score under these circumstances
(timeToScore && _parms._score_tree_interval == 0) || // use time-based duty-cycle heuristic only if the user didn't specify _score_tree_interval
manualInterval) {
_timeLastScoreStart = now;
boosterProvider.updateBooster(); // retrieve booster, expensive!
model.doScoring(_train, _parms.train(), _valid, _parms.valid());
_timeLastScoreEnd = System.currentTimeMillis();
XGBoostOutput out = model._output;
final Map<String, Integer> varimp;
Booster booster = null;
try {
booster = model.model_info().deserializeBooster();
varimp = BoosterHelper.doWithLocalRabit(new BoosterHelper.BoosterOp<Map<String, Integer>>() {
@Override
public Map<String, Integer> apply(Booster booster) throws XGBoostError {
return booster.getFeatureScore(featureMapFileAbsolutePath);
}
}, booster);
} finally {
if (booster != null)
BoosterHelper.dispose(booster);
}
out._varimp = model.computeVarImp(varimp);
out._model_summary = createModelSummaryTable(out._ntrees, null);
out._scoring_history = createScoringHistoryTable(out, model._output._scored_train, out._scored_valid, _job, out._training_time_ms, _parms._custom_metric_func != null);
out._variable_importances = hex.ModelMetrics.calcVarImp(out._varimp);
model.update(_job);
Log.info(model);
scored = true;
}
return scored;
}
}
private static final class BoosterProvider {
XGBoostModelInfo _modelInfo;
XGBoostUpdateTask _updateTask;
BoosterProvider(XGBoostModelInfo modelInfo, XGBoostUpdateTask updateTask) {
_modelInfo = modelInfo;
_updateTask = updateTask;
_modelInfo.setBoosterBytes(_updateTask.getBoosterBytes());
}
final void reset(XGBoostUpdateTask updateTask) {
_updateTask = updateTask;
}
final void updateBooster() {
if (_updateTask == null) {
throw new IllegalStateException("Booster can be retrieved only once!");
}
final byte[] boosterBytes = _updateTask.getBoosterBytes();
_modelInfo.setBoosterBytes(boosterBytes);
}
}
private static Set<Integer> GPUS = new HashSet<>();
static boolean hasGPU(H2ONode node, int gpu_id) {
final boolean hasGPU;
if (H2O.SELF.equals(node)) {
hasGPU = hasGPU(gpu_id);
} else {
HasGPUTask t = new HasGPUTask(gpu_id);
new RPC<>(node, t).call().get();
hasGPU = t._hasGPU;
}
Log.debug("Availability of GPU (id=" + gpu_id + ") on node " + node + ": " + hasGPU);
return hasGPU;
}
private static class HasGPUTask extends DTask<HasGPUTask> {
private final int _gpu_id;
// OUT
private boolean _hasGPU;
private HasGPUTask(int gpu_id) { _gpu_id = gpu_id; }
@Override
public void compute2() {
_hasGPU = hasGPU(_gpu_id);
tryComplete();
}
}
// helper
static synchronized boolean hasGPU(int gpu_id) {
if (! XGBoostExtension.isGpuSupportEnabled()) {
return false;
}
if(GPUS.contains(gpu_id)) {
return true;
}
DMatrix trainMat;
try {
trainMat = new DMatrix(new float[]{1,2,1,2},2,2);
trainMat.setLabel(new float[]{1,0});
} catch (XGBoostError xgBoostError) {
throw new IllegalStateException("Couldn't prepare training matrix for XGBoost.", xgBoostError);
}
HashMap<String, Object> params = new HashMap<>();
params.put("updater", "grow_gpu_hist");
params.put("silent", 1);
params.put("gpu_id", gpu_id);
HashMap<String, DMatrix> watches = new HashMap<>();
watches.put("train", trainMat);
try {
Map<String, String> localRabitEnv = new HashMap<>();
Rabit.init(localRabitEnv);
ml.dmlc.xgboost4j.java.XGBoost.train(trainMat, params, 1, watches, null, null);
GPUS.add(gpu_id);
return true;
} catch (XGBoostError xgBoostError) {
return false;
} finally {
try {
Rabit.shutdown();
} catch (XGBoostError e) {
Log.warn("Cannot shutdown XGBoost Rabit for current thread.");
}
}
}
@Override public void cv_computeAndSetOptimalParameters(ModelBuilder<XGBoostModel,XGBoostModel.XGBoostParameters,XGBoostOutput>[] cvModelBuilders) {
if( _parms._stopping_rounds == 0 && _parms._max_runtime_secs == 0) return; // No exciting changes to stopping conditions
// Extract stopping conditions from each CV model, and compute the best stopping answer
_parms._stopping_rounds = 0;
_parms._max_runtime_secs = 0;
int sum = 0;
for (ModelBuilder mb : cvModelBuilders)
sum += ((XGBoostOutput) DKV.<Model>getGet(mb.dest())._output)._ntrees;
_parms._ntrees = (int)((double)sum/cvModelBuilders.length);
warn("_ntrees", "Setting optimal _ntrees to " + _parms._ntrees + " for cross-validation main model based on early stopping of cross-validation models.");
warn("_stopping_rounds", "Disabling convergence-based early stopping for cross-validation main model.");
warn("_max_runtime_secs", "Disabling maximum allowed runtime for cross-validation main model.");
}
}
|
package org.corpus_tools.annis.gui.admin.reflinks;
import static com.github.mvysny.kaributesting.v8.LocatorJ._click;
import static com.github.mvysny.kaributesting.v8.LocatorJ._get;
import static com.github.mvysny.kaributesting.v8.LocatorJ._setValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.github.mvysny.kaributesting.v8.GridKt;
import com.github.mvysny.kaributesting.v8.MockVaadin;
import com.vaadin.shared.data.sort.SortDirection;
import com.vaadin.spring.internal.UIScopeImpl;
import com.vaadin.ui.Button;
import com.vaadin.ui.Grid;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TextField;
import java.io.IOException;
import java.net.URI;
import java.util.UUID;
import net.jcip.annotations.NotThreadSafe;
import org.corpus_tools.annis.gui.AnnisUI;
import org.corpus_tools.annis.gui.SingletonBeanStoreRetrievalStrategy;
import org.corpus_tools.annis.gui.query_references.UrlShortener;
import org.corpus_tools.annis.gui.query_references.UrlShortenerEntry;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.web.WebAppConfiguration;
@SpringBootTest
@ActiveProfiles({"desktop", "test", "headless"})
@WebAppConfiguration
@NotThreadSafe
class ReferenceLinkEditorTest {
@Autowired
private BeanFactory beanFactory;
private AnnisUI ui;
private ReferenceLinkEditor panel;
private UrlShortenerEntry entry1;
private UrlShortenerEntry entry2;
@BeforeEach
void setup() throws IOException {
UIScopeImpl.setBeanStoreRetrievalStrategy(new SingletonBeanStoreRetrievalStrategy());
this.ui = beanFactory.getBean(AnnisUI.class);
MockVaadin.setup(() -> ui);
_click(_get(Button.class, spec -> spec.withCaption("Administration")));
TabSheet tab = _get(TabSheet.class);
panel = _get(ReferenceLinkEditor.class);
tab.setSelectedTab(panel);
// Add some example entries
ui.getUrlShortener().getRepo().deleteAll();
UrlShortener urlShortener = this.ui.getUrlShortener();
entry1 = new UrlShortenerEntry();
entry1.setId(UUID.fromString("4366b0a5-6b27-40fe-ac5d-08e75c9eef51"));
entry1.setUrl(URI.create("/test1"));
urlShortener.getRepo().save(entry1);
entry2 = new UrlShortenerEntry();
entry2.setId(UUID.fromString("b1912b10-93f3-4018-84e8-6bf7572ee163"));
entry2.setUrl(URI.create("/test2"));
entry2.setTemporaryUrl(URI.create("/temp2"));
urlShortener.getRepo().save(entry2);
}
@AfterEach
void cleanup() {
ui.getUrlShortener().getRepo().deleteAll();
}
@Test
void testShowAndSortEntries() {
@SuppressWarnings("unchecked")
Grid<UrlShortenerEntry> grid = _get(panel, Grid.class);
assertEquals(2, GridKt._size(grid));
assertEquals(entry1, GridKt._get(grid, 0));
assertEquals(entry2, GridKt._get(grid, 1));
// Sort by the "Temporary URL" column
grid.sort(grid.getColumns().get(3), SortDirection.ASCENDING);
assertEquals(entry1, GridKt._get(grid, 0));
assertEquals(entry2, GridKt._get(grid, 1));
grid.sort(grid.getColumns().get(3), SortDirection.DESCENDING);
assertEquals(entry2, GridKt._get(grid, 0));
assertEquals(entry1, GridKt._get(grid, 1));
}
@Test
void testFilterByUUID() {
@SuppressWarnings("unchecked")
Grid<UrlShortenerEntry> grid = _get(panel, Grid.class);
TextField filter = _get(grid, TextField.class);
// Set an existing UUID
_setValue(filter, "4366b0a5-6b27-40fe-ac5d-08e75c9eef51");
assertEquals(1, GridKt._size(grid));
// Set an invalid UUID, this should not apply the filter
_setValue(filter, "4366b0a5-");
assertEquals(2, GridKt._size(grid));
// Set to a non-existing but valid UUID, this should hide all entries
_setValue(filter, "8307fbb6-f426-433d-9b11-71244b970e0d");
assertEquals(0, GridKt._size(grid));
// Create a lot of UUIDs with the filter active
for (int i = 0; i < 10000; i++) {
UrlShortenerEntry e = new UrlShortenerEntry();
e.setId(UUID.randomUUID());
e.setUrl(URI.create("/doesnotexist"));
ui.getUrlShortener().getRepo().save(e);
}
// Since the UUID is not included, the grid should be still empty
assertEquals(0, GridKt._size(grid));
// Create a new entry for the missing UUID with an existing filter active
UrlShortenerEntry e = new UrlShortenerEntry();
e.setId(UUID.fromString("8307fbb6-f426-433d-9b11-71244b970e0d"));
e.setUrl(URI.create("/"));
ui.getUrlShortener().getRepo().save(e);
assertEquals(1, GridKt._size(grid));
}
@Test
void testManyEntriesAscending() {
@SuppressWarnings("unchecked")
Grid<UrlShortenerEntry> grid = _get(panel, Grid.class);
grid.sort(grid.getColumns().get(4), SortDirection.ASCENDING);
// Add random UUIDs
for (int i = 0; i < 10000; i++) {
UrlShortenerEntry e = new UrlShortenerEntry();
e.setId(UUID.randomUUID());
e.setUrl(URI.create("/doesnotexist"));
ui.getUrlShortener().getRepo().save(e);
}
assertEquals(10002, GridKt._size(grid));
// Add a single UUID which will be shown at the beginning of the grid when sorted
UrlShortenerEntry firstEntry = new UrlShortenerEntry();
firstEntry.setId(UUID.randomUUID());
firstEntry.setUrl(URI.create("/"));
ui.getUrlShortener().getRepo().save(firstEntry);
assertEquals(firstEntry, GridKt._get(grid, 0));
}
@Test
void testManyEntriesDescending() {
@SuppressWarnings("unchecked")
Grid<UrlShortenerEntry> grid = _get(panel, Grid.class);
grid.sort(grid.getColumns().get(4), SortDirection.DESCENDING);
// Add random UUIDs
for (int i = 0; i < 10000; i++) {
UrlShortenerEntry e = new UrlShortenerEntry();
e.setId(UUID.randomUUID());
e.setUrl(URI.create("/doesnotexist"));
ui.getUrlShortener().getRepo().save(e);
}
assertEquals(10002, GridKt._size(grid));
// Add a single UUID which will be shown at the end of the grid when sorted
UrlShortenerEntry lastEntry = new UrlShortenerEntry();
lastEntry.setId(UUID.randomUUID());
lastEntry.setUrl(URI.create("/"));
ui.getUrlShortener().getRepo().save(lastEntry);
assertEquals(lastEntry, GridKt._get(grid, 10002));
}
}
|
package edu.northwestern.bioinformatics.studycalendar.dao;
import edu.northwestern.bioinformatics.studycalendar.domain.PlannedEvent;
/**
* @author Rhett Sutphin
*/
public class PlannedEventDaoTest extends ContextDaoTestCase<PlannedEventDao> {
public void testGetById() throws Exception {
PlannedEvent loaded = getDao().getById(-12);
assertEquals("Wrong id", -12, (int) loaded.getId());
assertEquals("Wrong day number", new Integer(4), loaded.getDay());
assertNotNull("Period not loaded", loaded.getPeriod());
assertEquals("Wrong period", -300L, (long) loaded.getPeriod().getId());
assertNotNull("Activity not loaded", loaded.getActivity());
assertEquals("Wrong activity", -200L, (long) loaded.getActivity().getId());
}
public void testPeriodBidirectional() throws Exception {
PlannedEvent loaded = getDao().getById(-12);
assertTrue(loaded.getPeriod().getPlannedEvents().contains(loaded));
}
public void testSaveDetached() throws Exception {
Integer id;
{
PlannedEvent plannedEvent = new PlannedEvent();
plannedEvent.setDay(5);
plannedEvent.setActivity(getDao().getById(-12).getActivity());
getDao().save(plannedEvent);
assertNotNull("not saved", plannedEvent.getId());
id = plannedEvent.getId();
}
interruptSession();
PlannedEvent loaded = getDao().getById(id);
assertNotNull("Could not reload", loaded);
assertEquals("Wrong event loaded", 5, (int) loaded.getDay());
}
}
|
package org.sakaiproject.gradebookng.tool.panels;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.extensions.markup.html.form.DateTextField;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.sakaiproject.gradebookng.business.GradebookNgBusinessService;
import org.sakaiproject.service.gradebook.shared.Assignment;
import org.sakaiproject.service.gradebook.shared.CategoryDefinition;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
/**
* The panel for the add grade item window
* @author Steve Swinsburg (steve.swinsburg@gmail.com)
*
*/
public class AddGradeItemPanelContent extends Panel {
private static final long serialVersionUID = 1L;
@SpringBean(name="org.sakaiproject.gradebookng.business.GradebookNgBusinessService")
protected GradebookNgBusinessService businessService;
public AddGradeItemPanelContent(String id, Model<Assignment> assignment) {
super(id, assignment);
add(new TextField<String>("title", new PropertyModel<String>(assignment, "name")));
add(new TextField<Double>("points", new PropertyModel<Double>(assignment, "points")));
add(new DateTextField("duedate", new PropertyModel<Date>(assignment, "dueDate"), "MM/dd/yyyy")); //TODO needs to come from i18n
List<CategoryDefinition> categories = businessService.getGradebookCategories();
final Map<Long, String> categoryMap = new HashMap<>();
for (CategoryDefinition category : categories) {
categoryMap.put(category.getId(), category.getName());
}
DropDownChoice<Long> categoryDropDown = new DropDownChoice<Long>("category", new PropertyModel<Long>(assignment, "categoryId"), new ArrayList<Long>(categoryMap.keySet()), new IChoiceRenderer<Long>() {
private static final long serialVersionUID = 1L;
public Object getDisplayValue(Long value) {
return categoryMap.get(value);
}
public String getIdValue(Long object, int index) {
return object.toString();
}
});
categoryDropDown.setNullValid(true);
add(categoryDropDown);
add(new CheckBox("extraCredit", new PropertyModel<Boolean>(assignment, "extraCredit")));
final AjaxCheckBox released = new AjaxCheckBox("released", new PropertyModel<Boolean>(assignment, "released")) {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(AjaxRequestTarget target) {
//nothing required
}
};
released.setOutputMarkupId(true);
add(released);
//if checked, release must also be checked and then disabled
final AjaxCheckBox counted = new AjaxCheckBox("counted", new PropertyModel<Boolean>(assignment, "counted")) {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(AjaxRequestTarget target) {
if(this.getModelObject()) {
released.setModelObject(true);
released.setEnabled(false);
} else {
released.setEnabled(true);
}
target.add(released);
}
};
add(counted);
}
}
|
package org.zstack.header.host;
import org.zstack.header.query.APIQueryReply;
import org.zstack.header.rest.RestResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@RestResponse(allTo = "inventories")
public class APIQueryHostReply extends APIQueryReply {
private List<HostInventory> inventories;
public List<HostInventory> getInventories() {
return inventories;
}
public void setInventories(List<HostInventory> inventories) {
this.inventories = inventories;
}
public static APIQueryHostReply __example__() {
APIQueryHostReply reply = new APIQueryHostReply();
HostInventory hi = new HostInventory ();
hi.setAvailableCpuCapacity(2L);
hi.setAvailableMemoryCapacity(4L);
hi.setClusterUuid(uuid());
hi.setManagementIp("192.168.0.1");
hi.setName("example");
hi.setState(HostState.Enabled.toString());
hi.setStatus(HostStatus.Connected.toString());
hi.setClusterUuid(uuid());
hi.setZoneUuid(uuid());
hi.setUuid(uuid());
hi.setTotalCpuCapacity(4L);
hi.setTotalMemoryCapacity(4L);
hi.setHypervisorType("KVM");
hi.setDescription("example");
reply.setInventories(Arrays.asList(hi));
return reply;
}
}
|
package io.github.ihongs.action;
import io.github.ihongs.Cnst;
import io.github.ihongs.Core;
import io.github.ihongs.CoreConfig;
import io.github.ihongs.CoreLocale;
import io.github.ihongs.CoreLogger;
import io.github.ihongs.HongsExemption;
import io.github.ihongs.util.Data;
import io.github.ihongs.util.Synt;
import io.github.ihongs.util.Tool;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;
import javax.servlet.http.Part;
/**
*
*
* <p>
* Servlet,Filter Core ;
* Filter web.xml,
* Servlet,Filter Core .
* </p>
*
* <h3>:</h3>
* <pre>
* server.id ID
* core.language.probing
* core.language.default
* core.timezone.probing
* core.timezone.default
* </pre>
*
* @author Hong
*/
public class ActionDriver extends HttpServlet implements Servlet, Filter {
/**
* , true
*/
private boolean INIT = false;
/**
* , true ,
*/
private boolean SHUT = false;
/**
* Filter
* @param conf
* @throws ServletException
*/
@Override
public void init( FilterConfig conf) throws ServletException {
this.init(conf.getServletContext());
}
/**
* Servlet
* @param conf
* @throws ServletException
*/
@Override
public void init(ServletConfig conf) throws ServletException {
super.init(conf /*call super init*/);
this.init(conf.getServletContext());
}
/**
*
* @param cont
* @throws ServletException
*/
synchronized final void init(ServletContext cont) throws ServletException {
if (Core.ENVIR != 1) {
Core.ENVIR = 1;
} else {
return;
}
INIT= true;
if (Core.BASE_HREF == null) {
SHUT= true;
System.setProperty("file.encoding", "UTF-8");
Core.DEBUG = Synt.declare(cont.getInitParameter("debug"), (byte) 0);
Core.BASE_HREF = cont.getContextPath();
Core.BASE_PATH = cont.getRealPath("" );
Core.BASE_PATH = Core.BASE_PATH.replaceFirst("[/\\\\]$", "");
Core.CORE_PATH = Core.BASE_PATH + File.separator + "WEB-INF";
File cp = new File(Core.CORE_PATH );
if (!cp.exists()) {
Core.CORE_PATH = cp.getParent();
}
Core.CONF_PATH = Core.CORE_PATH + File.separator + "etc";
Core.DATA_PATH = Core.CORE_PATH + File.separator + "var";
/
CoreConfig cnf = CoreConfig.getInstance("defines");
Core.SERVER_ID = cnf.getProperty("server.id", "0");
Map m = new HashMap();
m.put("SERVER_ID", Core.SERVER_ID);
m.put("BASE_PATH", Core.BASE_PATH);
m.put("CORE_PATH", Core.CORE_PATH);
m.put("CONF_PATH", Core.CONF_PATH);
m.put("DATA_PATH", Core.DATA_PATH);
for(Map.Entry et : cnf.entrySet()) {
String k = (String) et.getKey ();
String v = (String) et.getValue();
if (k.startsWith("envir.")) {
k = k.substring(6 );
v = Tool.inject(v,m);
System.setProperty(k,v);
}
}
if (0 < Core.DEBUG && 8 != (8 & Core.DEBUG)) {
for(Map.Entry et : cnf.entrySet()) {
String k = (String) et.getKey ();
String v = (String) et.getValue();
if (k.startsWith("debug.")) {
k = k.substring(6 );
v = Tool.inject(v,m);
System.setProperty(k,v);
}
}
}
cnf = CoreConfig.getInstance("default");
Core.ACTION_LANG.set(cnf.getProperty("core.language.default", "zh_CN"));
Core.ACTION_ZONE.set(cnf.getProperty("core.timezone.default", "GMT-8"));
}
ActionRunner.getActions();
Core.GLOBAL_CORE.clear ();
long time = Long.parseLong(
System.getProperty("core.global.cleans.period", "600000"));
if ( time > 0 ) {
new Timer ("core.global.cleans", true).schedule(
new TimerTask() {
@Override
public void run() {
if (0 != Core.DEBUG && 8 != (8 & Core.DEBUG) ) {
CoreLogger.debug( "Global core objects: "
+ Core.GLOBAL_CORE.toString( )
);
}
Core.GLOBAL_CORE.clean();
}
} , time, time);
}
if (0 != Core.DEBUG && 8 != (8 & Core.DEBUG)) {
CoreLogger.debug(new StringBuilder("...")
.append("\r\n\tDEBUG : ").append(Core.DEBUG)
.append("\r\n\tSERVER_ID : ").append(Core.SERVER_ID)
.append("\r\n\tBASE_HREF : ").append(Core.BASE_HREF)
.append("\r\n\tBASE_PATH : ").append(Core.BASE_PATH)
.append("\r\n\tCORE_PATH : ").append(Core.CORE_PATH)
.append("\r\n\tCONF_PATH : ").append(Core.CONF_PATH)
.append("\r\n\tDATA_PATH : ").append(Core.DATA_PATH)
.toString());
}
}
@Override
public void destroy () {
if (! INIT) {
return;
}
if (0 != Core.DEBUG && 8 != (8 & Core.DEBUG)) {
Core core = Core.GLOBAL_CORE;
long time = System.currentTimeMillis() - Core.STARTS_TIME;
CoreLogger.debug(new StringBuilder("...")
.append("\r\n\tSERVER_ID : ").append(Core.SERVER_ID)
.append("\r\n\tObjects : ").append(core.toString())
.append("\r\n\tRuntime : ").append(Tool.humanTime(time))
.toString());
}
if (! SHUT) {
return;
}
try {
Core.GLOBAL_CORE.close();
} catch ( Throwable e) {
CoreLogger.error(e);
}
}
@Override
public void service (ServletRequest rep, ServletResponse rsp)
throws ServletException, IOException {
doDriver(rep, rsp, new DriverProxy() {
@Override
public void doDriver(Core core, ActionHelper hlpr)
throws ServletException, IOException {
doAction(core, hlpr);
}
});
}
@Override
public void doFilter(ServletRequest rep, ServletResponse rsp, final FilterChain chn)
throws ServletException, IOException {
doDriver(rep, rsp, new DriverProxy() {
@Override
public void doDriver(Core core, ActionHelper hlpr)
throws ServletException, IOException {
doFilter(core, hlpr, chn);
}
});
}
final void doDriver(ServletRequest rep, ServletResponse rsp, final DriverProxy agt)
throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest ) rep;
HttpServletResponse rsq = (HttpServletResponse) rsp;
ActionHelper hlpr;
Core core = (Core) req.getAttribute(Core.class.getName());
if ( core == null) {
core = Core.getInstance( );
req.setAttribute ( Core.class.getName(), core );
hlpr = new ActionHelper( req, rsq );
core.put ( ActionHelper.class.getName(), hlpr );
try {
doLaunch(core, hlpr, req, rsq );
agt.doDriver ( core, hlpr);
doCommit(core, hlpr, req, rsq );
} catch (IOException ex) {
CoreLogger.error(ex);
} catch (ServletException ex ) {
CoreLogger.error(ex);
} catch (RuntimeException ex ) {
CoreLogger.error(ex);
} catch (Error er) {
CoreLogger.error(er);
} finally {
doFinish(core, hlpr, req );
}
} else {
Core.THREAD_CORE.set(core);
hlpr = core.get(ActionHelper.class);
hlpr.updateHelper( req, rsq );
agt.doDriver(core, hlpr);
}
}
private void doCommit(Core core, ActionHelper hlpr, HttpServletRequest req, HttpServletResponse rsp)
throws ServletException {
Map dat = hlpr.getResponseData();
if (dat != null) {
req .setAttribute(Cnst.RESPON_ATTR, dat);
hlpr.updateHelper( req, rsp );
hlpr.responed();
}
}
private void doLaunch(Core core, ActionHelper hlpr, HttpServletRequest req, HttpServletResponse rsp)
throws ServletException {
Core.ACTION_TIME.set(System.currentTimeMillis( ));
Core.CLIENT_ADDR.set(getClientAddr(req)/*Remote IP*/);
Core.ACTION_NAME.set(getOriginPath(req).substring(1));
CoreConfig conf = core.get(CoreConfig.class);
Core.ACTION_ZONE.set(conf.getProperty("core.timezone.default","GMT+8"));
if (conf.getProperty("core.timezone.probing", false)) {
/**
* Session/Cookies
*/
String sess = conf.getProperty("core.timezone.session", "zone");
String zone = (String) hlpr.getSessibute(sess);
if (zone == null || zone.length() == 0) {
zone = (String) hlpr.getCookibute(sess);
if (zone == null || zone.length() == 0) {
zone = req.getHeader(/*Cur*/"Timezone");
}
}
if (zone != null) {
zone = TimeZone.getTimeZone(zone).getID();
// if (zone != null) {
Core.ACTION_ZONE.set(zone);
}
}
Core.ACTION_LANG.set(conf.getProperty("core.language.default","zh_CN"));
if (conf.getProperty("core.language.probing", false)) {
/**
* Session/Cookies
*/
String sess = conf.getProperty("core.language.session", "lang");
String lang = (String) hlpr.getSessibute(sess);
if (lang == null || lang.length() == 0) {
lang = (String) hlpr.getCookibute(sess);
if (lang == null || lang.length() == 0) {
lang = req.getHeader("Accept-Language");
}
}
if (lang != null) {
lang = CoreLocale.getAcceptLanguage(lang);
if (lang != null) {
Core.ACTION_LANG.set(lang);
}
}
}
if (! hlpr.getResponse().isCommitted()) {
String pb;
pb = conf.getProperty("core.powered.by");
if (pb != null && pb.length() != 0) {
rsp.setHeader("X-Powered-By", pb);
}
pb = conf.getProperty("core.service.by");
if (pb != null && pb.length() != 0) {
rsp.setHeader( "Server" , pb);
}
}
}
private void doFinish(Core core, ActionHelper hlpr, HttpServletRequest req) {
try {
if (0 < Core.DEBUG && 8 != (8 & Core.DEBUG)) {
req = hlpr.getRequest();
HttpSession ses = req .getSession(false);
Object uid = hlpr.getSessibute(Cnst.UID_SES);
String mem;
String tim;
if (uid != null) {
mem = uid.toString( );
} else
if (ses != null) {
mem = "$"+ses.getId();
} else {
mem = "-";
}
tim = Tool.humanTime ( System.currentTimeMillis() - Core.ACTION_TIME.get() );
StringBuilder sb = new StringBuilder("...");
sb.append("\r\n\tACTION_NAME : ").append(Core.ACTION_NAME.get())
.append("\r\n\tACTION_TIME : ").append(Core.ACTION_TIME.get())
.append("\r\n\tACTION_LANG : ").append(Core.ACTION_LANG.get())
.append("\r\n\tACTION_ZONE : ").append(Core.ACTION_ZONE.get())
.append("\r\n\tMethod : ").append(req.getMethod())
.append("\r\n\tMember : ").append(mem)
.append("\r\n\tThread : ").append(Thread.currentThread().getName())
.append("\r\n\tRuntime : ").append(tim)
.append("\r\n\tObjects : ").append(core.toString());
CoreConfig cf = CoreConfig.getInstance();
if (cf.getProperty("core.debug.action.request", false)) {
Map rd = null;
try {
rd = hlpr.getRequestData();
} catch ( HongsExemption ex ) {
CoreLogger.debug(ex.getMessage());
}
if (rd != null && !rd.isEmpty()) {
sb.append("\r\n\tRequest : ")
.append(Tool.indent(Data.toString(rd)).substring(1));
}
}
if (cf.getProperty("core.debug.action.results", false)) {
Map xd = hlpr.getResponseData();
if (xd == null) {
xd = (Map) req.getAttribute(Cnst.RESPON_ATTR);
}
if (xd != null && !xd.isEmpty()) {
sb.append("\r\n\tResults : ")
.append(Tool.indent(Data.toString(xd)).substring(1));
}
}
if (cf.getProperty("core.debug.action.session", false) && ses != null) {
Map map = new HashMap();
Enumeration<String> nms = ses.getAttributeNames();
while (nms.hasMoreElements()) {
String nme = nms.nextElement();
map.put(nme , ses.getAttribute(nme));
}
if (!map.isEmpty()) {
sb.append("\r\n\tSession : ")
.append(Tool.indent(Data.toString(map)).substring(1));
}
}
if (cf.getProperty("core.debug.action.context", false)) {
Map map = new HashMap();
Enumeration<String> nms = req.getAttributeNames();
while (nms.hasMoreElements()) {
String nme = nms.nextElement();
map.put(nme , req.getAttribute(nme));
}
if (!map.isEmpty()) {
sb.append("\r\n\tContext : ")
.append(Tool.indent(Data.toString(map)).substring(1));
}
}
if (cf.getProperty("core.debug.action.headers", false)) {
Map map = new HashMap();
Enumeration<String> nms = req.getHeaderNames();
while (nms.hasMoreElements()) {
String nme = nms.nextElement();
map.put(nme , req.getHeader(nme));
}
if (!map.isEmpty()) {
sb.append("\r\n\tHeaders : ")
.append(Tool.indent(Data.toString(map)).substring(1));
}
}
if (cf.getProperty("core.debug.action.cookies", false)) {
Map map = new HashMap();
Cookie[] cks = req.getCookies();
for (Cookie cke : cks) {
map.put(cke.getName( ), cke.getValue( ));
}
if (!map.isEmpty()) {
sb.append("\r\n\tCookies : ")
.append(Tool.indent(Data.toString(map)).substring(1));
}
}
CoreLogger.debug(sb.toString());
}
Map<String, List<Part>> ud = Synt.asMap(hlpr.getAttribute(Cnst.UPLOAD_ATTR));
if (ud != null) {
for(List<Part> pa : ud.values()) {
for (Part pr : pa) {
try {
pr.delete();
} catch (IOException ex) {
CoreLogger.error(ex);
}
}
}
}
} finally {
try {
core.close( );
} catch (Error e) {
CoreLogger.error( e );
} catch (Exception e) {
CoreLogger.error( e );
}
req.removeAttribute(Core.class.getName());
Core.THREAD_CORE.remove();
Core.ACTION_TIME.remove();
Core.ACTION_ZONE.remove();
Core.ACTION_LANG.remove();
Core.ACTION_NAME.remove();
}
}
/**
*
*
* @param core
* @param hlpr
* @param chn
* @throws ServletException
* @throws IOException
*/
protected void doFilter(Core core, ActionHelper hlpr, FilterChain chn)
throws ServletException, IOException {
chn.doFilter(hlpr.getRequest(), hlpr.getResponse());
}
/**
*
*
* @param core
* @param hlpr
* @throws ServletException
* @throws IOException
*/
protected void doAction(Core core, ActionHelper hlpr)
throws ServletException, IOException {
service( hlpr.getRequest(), hlpr.getResponse());
}
/
/**
* Core
* @param req
* @return
*/
public static final Core getActualCore(HttpServletRequest req) {
Core core = (Core) req.getAttribute(Core.class.getName());
if (core == null) {
core = Core.GLOBAL_CORE ;
} else {
Core.THREAD_CORE.set(core);
}
return core;
}
/**
*
* @param req
* @return
*/
public static final String getSchemeHost(HttpServletRequest req) {
String link = req.getScheme() + ":
+ req.getServerName();
int port = req.getServerPort();
if ( port != 80 && port != 443 ) {
link += ":" + port ;
}
return link ;
}
/**
* ServletPath
* @param req
* @return
*/
public static final String getRecentPath(HttpServletRequest req) {
String uri = (String) req.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
String suf = (String) req.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
if (uri == null) {
uri = req.getServletPath();
suf = req.getPathInfo();
}
if (suf != null) {
uri += suf;
}
return uri;
}
/**
* ServletPath
* @param req
* @return
*/
public static final String getOriginPath(HttpServletRequest req) {
String uri = (String) req.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH);
String suf = (String) req.getAttribute(RequestDispatcher.FORWARD_PATH_INFO);
if (uri == null) {
uri = req.getServletPath();
suf = req.getPathInfo();
}
if (suf != null) {
uri += suf;
}
return uri;
}
/**
* IP
* @param req
* @return
*/
public static final String getClientAddr(HttpServletRequest req) {
String ip = (String)req.getAttribute(Cnst.CLIENT_ATTR);
if (null != ip) {
return ip;
}
// RFC 7239,
String h_0 = req.getHeader("Forwarded");
if ( h_0 != null && h_0.length() != 0 ) {
int e_0,b_0 = 0;
String h_1;
while (true) {
e_0 = h_0.indexOf(',' , b_0);
if (e_0 != -1) {
h_1 = h_0.substring(b_0, e_0);
b_0 = e_0 + 1;
} else
if (b_0 != 0) {
h_1 = h_0.substring(b_0);
} else
{
h_1 = h_0;
}
int e_1,b_1 = 0;
String h_2;
while (true) {
e_1 = h_1.indexOf(';' , b_1);
if (e_1 != -1) {
h_2 = h_1.substring(b_1, e_1);
b_1 = e_1 + 1;
} else
if (b_1 != 0) {
h_2 = h_1.substring(b_1);
} else
{
h_2 = h_1;
}
int e_2 = h_2.indexOf ('=');
if (e_2 != -1) {
String key = h_2.substring(0 , e_2).trim();
String val = h_2.substring(1 + e_2).trim();
key = key.toLowerCase( );
if ( "for" .equals(key )
&& ! "unknown".equals(val )) {
/**
*
* IPv4 X.X.X.X:PORT
* IPv6 "[X:X:X:X:X]:PORT"
*
*/
if (val.startsWith("\"")
&& val. endsWith("\"")) {
val = val.substring(1 , val.length() - 1);
}
if (val.startsWith("[" )) {
e_2 = val.indexOf("]" );
if (e_2 != -1) {
val = val.substring(1 , e_2);
}
} else {
e_2 = val.indexOf(":" );
if (e_2 != -1) {
val = val.substring(0 , e_2);
}
}
return val;
}
}
if (e_1 == -1) {
break;
}
}
if (e_0 == -1) {
break;
}
}
}
for (String key : new String[] {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP"} ) {
String val = req.getHeader(key);
if (val != null && val.length( ) != 0 ) {
int pos = val.indexOf (',');
if (pos > 0) {
val = val.substring(0, pos);
} val = val.trim();
if (!"unknown".equalsIgnoreCase(val)) {
return val;
}
}
}
return req.getRemoteAddr( );
}
public static interface DriverProxy {
public void doDriver(Core core, ActionHelper hlpr) throws ServletException, IOException;
}
}
|
package com.thoughtworks.xstream.core;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import java.security.AccessControlException;
public class JVM {
private ReflectionProvider reflectionProvider;
private static final float majorJavaVersion = getMajorJavaVersion(System.getProperty("java.version"));
static final float DEFAULT_JAVA_VERSION = 1.3f;
/**
* Parses the java version system property to determine the major java version,
* ie 1.x
*
* @param javaVersion the system property 'java.version'
* @return A float of the form 1.x
*/
static final float getMajorJavaVersion(String javaVersion) {
try {
return Float.parseFloat(javaVersion.substring(0, 3));
} catch ( NumberFormatException e ){
// Some JVMs may not conform to the x.y.z java.version format
return DEFAULT_JAVA_VERSION;
}
}
public static boolean is14() {
return majorJavaVersion >= 1.4f;
}
public static boolean is15() {
return majorJavaVersion >= 1.5f;
}
private static boolean isSun() {
return System.getProperty("java.vm.vendor").indexOf("Sun") != -1;
}
private static boolean isApple() {
return System.getProperty("java.vm.vendor").indexOf("Apple") != -1;
}
private static boolean isHPUX() {
return System.getProperty("java.vm.vendor").indexOf("Hewlett-Packard Company") != -1;
}
private static boolean isIBM() {
return System.getProperty("java.vm.vendor").indexOf("IBM") != -1;
}
private static boolean isBlackdown() {
return System.getProperty("java.vm.vendor").indexOf("Blackdown") != -1;
}
public Class loadClass(String name) {
try {
return Class.forName(name, false, getClass().getClassLoader());
} catch (ClassNotFoundException e) {
return null;
}
}
public synchronized ReflectionProvider bestReflectionProvider() {
if (reflectionProvider == null) {
try {
if ( canUseSun14ReflectionProvider() ) {
String cls = "com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider";
reflectionProvider = (ReflectionProvider) loadClass(cls).newInstance();
} else {
reflectionProvider = new PureJavaReflectionProvider();
}
} catch (InstantiationException e) {
reflectionProvider = new PureJavaReflectionProvider();
} catch (IllegalAccessException e) {
reflectionProvider = new PureJavaReflectionProvider();
} catch (AccessControlException e) {
// thrown when trying to access sun.misc package in Applet context.
reflectionProvider = new PureJavaReflectionProvider();
}
}
return reflectionProvider;
}
private boolean canUseSun14ReflectionProvider() {
return (isSun() || isApple() || isHPUX() || isIBM() || isBlackdown()) && is14() && loadClass("sun.misc.Unsafe") != null;
}
}
|
package org.inaturalist.android;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.Layout;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import com.flurry.android.FlurryAgent;
import com.koushikdutta.urlimageviewhelper.UrlImageViewCallback;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class UserProfile extends AppCompatActivity implements TabHost.OnTabChangeListener, AppBarLayout.OnOffsetChangedListener {
private final static String VIEW_TYPE_OBSERVATIONS = "observations";
private final static String VIEW_TYPE_SPECIES = "species";
private final static String VIEW_TYPE_IDENTIFICATIONS = "identifications";
private String mViewType;
private INaturalistApp mApp;
private BetterJSONObject mUser;
private TabHost mTabHost;
private ActivityHelper mHelper;
private ListView mObservationsList;
private UserObservationAdapter mObservationsListAdapter;
private ProgressBar mLoadingObservationsList;
private ViewGroup mObservationsContainer;
private TextView mObservationsListEmpty;
private ListView mSpeciesList;
private UserSpeciesAdapter mSpeciesListAdapter;
private ProgressBar mLoadingSpeciesList;
private ViewGroup mSpeciesContainer;
private TextView mSpeciesListEmpty;
private ListView mIdentificationsList;
private UserIdentificationsAdapter mIdentificationsListAdapter;
private ProgressBar mLoadingIdentificationsList;
private ViewGroup mIdentificationsContainer;
private TextView mIdentificationsListEmpty;
private ArrayList<JSONObject> mObservations;
private ArrayList<JSONObject> mSpecies;
private ArrayList<JSONObject> mIdentifications;
private UserDetailsReceiver mUserDetailsReceiver;
private int mTotalObservations;
private int mTotalSpecies;
private int mTotalIdentifications;
private AppBarLayout mAppBarLayout;
private boolean mUserPicHidden;
private ViewGroup mUserPicContainer;
private TextView mUserName;
private TextView mUserBio;
private int mObservationListIndex;
private int mObservationListOffset;
private int mSpeciesListIndex;
private int mSpeciesListOffset;
private int mIdentificationsListIndex;
private int mIdentificationsListOffset;
@Override
protected void onStart()
{
super.onStart();
FlurryAgent.onStartSession(this, INaturalistApp.getAppContext().getString(R.string.flurry_api_key));
FlurryAgent.logEvent(this.getClass().getSimpleName());
}
@Override
protected void onStop()
{
super.onStop();
FlurryAgent.onEndSession(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
this.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHelper = new ActivityHelper(this);
final Intent intent = getIntent();
setContentView(R.layout.user_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
mAppBarLayout = (AppBarLayout) findViewById(R.id.user_top_bar);
mAppBarLayout.addOnOffsetChangedListener(this);
mLoadingObservationsList = (ProgressBar) findViewById(R.id.loading_observations_list);
mObservationsListEmpty = (TextView) findViewById(R.id.observations_list_empty);
mObservationsList = (ListView) findViewById(R.id.observations_list);
mObservationsContainer = (ViewGroup) findViewById(R.id.observations_container);
mLoadingSpeciesList = (ProgressBar) findViewById(R.id.loading_species_list);
mSpeciesListEmpty = (TextView) findViewById(R.id.species_list_empty);
mSpeciesList = (ListView) findViewById(R.id.species_list);
mSpeciesContainer = (ViewGroup) findViewById(R.id.species_container);
mSpeciesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
JSONObject item = (JSONObject) view.getTag();
Intent intent = new Intent(UserProfile.this, TaxonActivity.class);
intent.putExtra(TaxonActivity.TAXON, new BetterJSONObject(item));
intent.putExtra(TaxonActivity.DOWNLOAD_TAXON, true);
startActivity(intent);
}
});
mLoadingIdentificationsList = (ProgressBar) findViewById(R.id.loading_identifications_list);
mIdentificationsListEmpty = (TextView) findViewById(R.id.identifications_list_empty);
mIdentificationsList = (ListView) findViewById(R.id.identifications_list);
mIdentificationsContainer = (ViewGroup) findViewById(R.id.identifications_container);
mObservationsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
JSONObject item = (JSONObject) view.getTag();
Intent intent = new Intent(UserProfile.this, ObservationViewerActivity.class);
intent.putExtra("observation", item.toString());
intent.putExtra("read_only", true);
intent.putExtra("reload", true);
startActivity(intent);
}
});
ViewCompat.setNestedScrollingEnabled(mObservationsList, true);
ViewCompat.setNestedScrollingEnabled(mIdentificationsList, true);
ViewCompat.setNestedScrollingEnabled(mSpeciesList, true);
if (mApp == null) {
mApp = (INaturalistApp)getApplicationContext();
}
if (savedInstanceState == null) {
mUser = (BetterJSONObject) intent.getSerializableExtra("user");
mTotalObservations = mUser.getJSONObject().optInt("observations_count", 0);
mTotalIdentifications = mUser.getJSONObject().optInt("identifications_count", 0);
mViewType = VIEW_TYPE_OBSERVATIONS;
mObservationsContainer.setVisibility(View.VISIBLE);
mSpeciesContainer.setVisibility(View.GONE);
mIdentificationsContainer.setVisibility(View.GONE);
} else {
mUser = (BetterJSONObject) savedInstanceState.getSerializable("user");
mViewType = savedInstanceState.getString("mViewType");
mObservationListIndex = savedInstanceState.getInt("mObservationListIndex");
mObservationListOffset = savedInstanceState.getInt("mObservationListOffset");
mSpeciesListIndex = savedInstanceState.getInt("mSpeciesListIndex");
mSpeciesListOffset = savedInstanceState.getInt("mSpeciesListOffset");
mIdentificationsListIndex = savedInstanceState.getInt("mIdentificationsListIndex");
mIdentificationsListOffset = savedInstanceState.getInt("IdentificationsmListOffset");
mObservations = loadListFromBundle(savedInstanceState, "mObservations");
mSpecies = loadListFromBundle(savedInstanceState, "mSpecies");
mIdentifications = loadListFromBundle(savedInstanceState, "mIdentifications");
mTotalIdentifications = savedInstanceState.getInt("mTotalIdentifications");
mTotalObservations = savedInstanceState.getInt("mTotalObservations");
mTotalSpecies = savedInstanceState.getInt("mTotalSpecies");
}
// Tab Initialization
initialiseTabHost();
refreshViewState();
refreshViewType();
if (mUser == null) {
finish();
return;
}
mUserName = (TextView) findViewById(R.id.user_name);
mUserBio = (TextView) findViewById(R.id.user_bio);
mUserPicContainer = (ViewGroup) findViewById(R.id.user_pic_container);
refreshUserDetails();
}
private void saveListToBundle(Bundle outState, ArrayList<JSONObject> list, String key) {
if (list != null) {
JSONArray arr = new JSONArray(list);
outState.putString(key, arr.toString());
}
}
private ArrayList<JSONObject> loadListFromBundle(Bundle savedInstanceState, String key) {
ArrayList<JSONObject> results = new ArrayList<JSONObject>();
String obsString = savedInstanceState.getString(key);
if (obsString != null) {
try {
JSONArray arr = new JSONArray(obsString);
for (int i = 0; i < arr.length(); i++) {
results.add(arr.getJSONObject(i));
}
return results;
} catch (JSONException exc) {
exc.printStackTrace();
return null;
}
} else {
return null;
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable("user", mUser);
outState.putString("mViewType", mViewType);
saveListToBundle(outState, mObservations, "mObservations");
saveListToBundle(outState, mSpecies, "mSpecies");
saveListToBundle(outState, mIdentifications, "mIdentifications");
outState.putInt("mTotalIdentifications", mTotalIdentifications);
outState.putInt("mTotalObservations", mTotalObservations);
outState.putInt("mTotalSpecies", mTotalSpecies);
if (mViewType.equals(VIEW_TYPE_OBSERVATIONS)) {
View firstVisibleRow = mObservationsList.getChildAt(0);
if (firstVisibleRow != null && mObservationsList != null) {
mObservationListOffset = firstVisibleRow.getTop() - mObservationsList.getPaddingTop();
mObservationListIndex = mObservationsList.getFirstVisiblePosition();
outState.putInt("mObservationListIndex", mObservationListIndex);
outState.putInt("mObservationListOffset", mObservationListOffset);
}
} else if (mViewType.equals(VIEW_TYPE_SPECIES)) {
View firstVisibleRow = mSpeciesList.getChildAt(0);
if (firstVisibleRow != null && mSpeciesList != null) {
mSpeciesListOffset = firstVisibleRow.getTop() - mSpeciesList.getPaddingTop();
mSpeciesListIndex = mSpeciesList.getFirstVisiblePosition();
outState.putInt("mSpeciesListIndex", mSpeciesListIndex);
outState.putInt("mSpeciesListOffset", mSpeciesListOffset);
}
} else if (mViewType.equals(VIEW_TYPE_IDENTIFICATIONS)) {
View firstVisibleRow = mIdentificationsList.getChildAt(0);
if (firstVisibleRow != null && mIdentificationsList != null) {
mIdentificationsListOffset = firstVisibleRow.getTop() - mIdentificationsList.getPaddingTop();
mIdentificationsListIndex = mIdentificationsList.getFirstVisiblePosition();
outState.putInt("mIdentificationsListIndex", mIdentificationsListIndex);
outState.putInt("mIdentificationsListOffset", mIdentificationsListOffset);
}
}
super.onSaveInstanceState(outState);
}
@Override
protected void onPause() {
super.onPause();
BaseFragmentActivity.safeUnregisterReceiver(mUserDetailsReceiver, this);
}
@Override
protected void onResume() {
super.onResume();
if (mApp == null) {
mApp = (INaturalistApp) getApplicationContext();
}
mUserDetailsReceiver = new UserDetailsReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(INaturalistService.USER_DETAILS_RESULT);
filter.addAction(INaturalistService.SPECIES_COUNT_RESULT);
filter.addAction(INaturalistService.USER_OBSERVATIONS_RESULT);
filter.addAction(INaturalistService.IDENTIFICATIONS_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mUserDetailsReceiver, filter, this);
if ((mUser == null) || (mUser.getInt("observations_count") == null) || (mUser.getString("description") == null)) getUserDetails(INaturalistService.ACTION_GET_SPECIFIC_USER_DETAILS);
if (mSpecies == null) getUserDetails(INaturalistService.ACTION_GET_USER_SPECIES_COUNT);
if (mObservations == null) getUserDetails(INaturalistService.ACTION_GET_USER_OBSERVATIONS);
if (mIdentifications == null) getUserDetails(INaturalistService.ACTION_GET_USER_IDENTIFICATIONS);
refreshViewState();
if (mViewType.equals(VIEW_TYPE_OBSERVATIONS)) {
mObservationsList.setSelectionFromTop(mObservationListIndex, mObservationListOffset);
} else if (mViewType.equals(VIEW_TYPE_SPECIES)) {
mObservationsList.setSelectionFromTop(mSpeciesListIndex, mSpeciesListOffset);
} else if (mViewType.equals(VIEW_TYPE_IDENTIFICATIONS)) {
mObservationsList.setSelectionFromTop(mIdentificationsListIndex, mIdentificationsListOffset);
}
}
// Method to add a TabHost
private static void AddTab(UserProfile activity, TabHost tabHost, TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
mViewType = tag;
refreshViewType();
}
private void refreshViewType() {
runOnUiThread(new Runnable() {
@Override
public void run() {
mObservationsContainer.setVisibility(View.GONE);
mSpeciesContainer.setVisibility(View.GONE);
mIdentificationsContainer.setVisibility(View.GONE);
}
});
TabWidget tabWidget = mTabHost.getTabWidget();
for (int i = 0; i < tabWidget.getChildCount(); i++) {
View tab = tabWidget.getChildAt(i);
TextView tabNameText = (TextView) tab.findViewById(R.id.tab_name);
View bottomLine = tab.findViewById(R.id.bottom_line);
tabNameText.setTypeface(null, Typeface.NORMAL);
tabNameText.setTextColor(Color.parseColor("#ACACAC"));
bottomLine.setVisibility(View.GONE);
}
int selectedTab = 0;
ViewGroup container = null;
if (mViewType.equals(VIEW_TYPE_OBSERVATIONS)) {
selectedTab = 0;
container = mObservationsContainer;
} else if (mViewType.equals(VIEW_TYPE_SPECIES)) {
selectedTab = 1;
container = mSpeciesContainer;
} else if (mViewType.equals(VIEW_TYPE_IDENTIFICATIONS)) {
selectedTab = 2;
container = mIdentificationsContainer;
}
// Hack to fix annoying issue (#541) where the layouts initially received a height of 0px
container.setVisibility(View.VISIBLE);
ViewGroup.LayoutParams params = container.getLayoutParams();
params.height = 1;
container.setLayoutParams(params);
container.requestLayout();
final ViewGroup finalContainer = container;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
ViewGroup.LayoutParams params = finalContainer.getLayoutParams();
params.height = ViewGroup.LayoutParams.MATCH_PARENT;
finalContainer.setLayoutParams(params);
finalContainer.requestLayout();
}
}, 1);
mTabHost.setCurrentTab(selectedTab);
View tab = tabWidget.getChildAt(selectedTab);
TextView tabNameText = (TextView) tab.findViewById(R.id.tab_name);
View bottomLine = tab.findViewById(R.id.bottom_line);
tabNameText.setTypeface(null, Typeface.BOLD);
tabNameText.setTextColor(Color.parseColor("#000000"));
bottomLine.setVisibility(View.VISIBLE);
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
UserProfile.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec(VIEW_TYPE_OBSERVATIONS).setIndicator(
createTabContent(getString(R.string.project_observations), 1000)));
UserProfile.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec(VIEW_TYPE_SPECIES).setIndicator(
createTabContent(getString(R.string.project_species), 2000)));
UserProfile.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec(VIEW_TYPE_IDENTIFICATIONS).setIndicator(
createTabContent(getString(R.string.identifications), 3000)));
mTabHost.getTabWidget().setDividerDrawable(null);
mTabHost.setOnTabChangedListener(this);
}
private View createTabContent(String tabName, int count) {
View view = LayoutInflater.from(this).inflate(R.layout.user_profile_tab, null);
TextView countText = (TextView) view.findViewById(R.id.count);
TextView tabNameText = (TextView) view.findViewById(R.id.tab_name);
DecimalFormat formatter = new DecimalFormat("
countText.setText(formatter.format(count));
tabNameText.setText(tabName);
return view;
}
private boolean isLoggedIn() {
SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE);
return prefs.getString("username", null) != null;
}
private void getUserDetails(String action) {
Intent serviceIntent = new Intent(action, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.USERNAME, mUser.getString("login"));
startService(serviceIntent);
}
private class UserDetailsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String error = extras.getString("error");
if (error != null) {
mHelper.alert(String.format(getString(R.string.couldnt_load_user_details), error));
return;
}
String username = intent.getStringExtra(INaturalistService.USERNAME);
if ((username == null) || (!username.toLowerCase().equals(mUser.getString("login").toLowerCase()))) {
// Results not for the current user name
return;
}
boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false);
Object object = null;
BetterJSONObject resultsObject;
JSONArray results = null;
if (isSharedOnApp) {
object = mApp.getServiceResult(intent.getAction());
} else {
object = intent.getSerializableExtra(actionToResultsParam(intent.getAction()));
}
int totalResults = 0;
if (object == null) {
refreshViewState();
return;
}
if (intent.getAction().equals(INaturalistService.USER_DETAILS_RESULT)) {
// Extended user details
mUser = (BetterJSONObject) object;
refreshUserDetails();
mTotalObservations = mUser.getInt("observations_count");
mTotalIdentifications = mUser.getInt("identifications_count");
return;
} else if (intent.getAction().equals(INaturalistService.SPECIES_COUNT_RESULT)) {
// Life list result (species)
resultsObject = (BetterJSONObject) object;
totalResults = resultsObject.getInt("total_results");
results = resultsObject.getJSONArray("results").getJSONArray();
} else {
// Observations / Identifications result
results = ((SerializableJSONArray) object).getJSONArray();
totalResults = results.length();
}
ArrayList<JSONObject> resultsArray = new ArrayList<JSONObject>();
if (results == null) {
refreshViewState();
return;
}
for (int i = 0; i < results.length(); i++) {
try {
JSONObject item = results.getJSONObject(i);
resultsArray.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (intent.getAction().equals(INaturalistService.USER_OBSERVATIONS_RESULT)) {
mObservations = resultsArray;
} else if (intent.getAction().equals(INaturalistService.SPECIES_COUNT_RESULT)) {
mSpecies = resultsArray;
mTotalSpecies = totalResults;
} else if (intent.getAction().equals(INaturalistService.IDENTIFICATIONS_RESULT)) {
mIdentifications = resultsArray;
}
refreshViewState();
}
private String actionToResultsParam(String action) {
if (action.equals(INaturalistService.USER_DETAILS_RESULT)) {
return INaturalistService.USER;
} else if (action.equals(INaturalistService.SPECIES_COUNT_RESULT)) {
return INaturalistService.SPECIES_COUNT_RESULT;
} else if (action.equals(INaturalistService.USER_OBSERVATIONS_RESULT)) {
return INaturalistService.OBSERVATIONS;
} else if (action.equals(INaturalistService.IDENTIFICATIONS_RESULT)) {
return INaturalistService.IDENTIFICATIONS;
} else {
return null;
}
}
}
private void refreshViewState() {
TabWidget tabWidget = mTabHost.getTabWidget();
DecimalFormat formatter = new DecimalFormat("
if (mObservations == null) {
((TextView)tabWidget.getChildAt(0).findViewById(R.id.count)).setVisibility(View.GONE);
((ProgressBar)tabWidget.getChildAt(0).findViewById(R.id.loading)).setVisibility(View.VISIBLE);
mLoadingObservationsList.setVisibility(View.VISIBLE);
mObservationsList.setVisibility(View.GONE);
mObservationsListEmpty.setVisibility(View.GONE);
} else {
((TextView)tabWidget.getChildAt(0).findViewById(R.id.count)).setVisibility(View.VISIBLE);
((ProgressBar)tabWidget.getChildAt(0).findViewById(R.id.loading)).setVisibility(View.GONE);
((TextView)tabWidget.getChildAt(0).findViewById(R.id.count)).setText(formatter.format(mTotalObservations));
mLoadingObservationsList.setVisibility(View.GONE);
if (mObservations.size() == 0) {
mObservationsListEmpty.setVisibility(View.VISIBLE);
} else {
mObservationsListEmpty.setVisibility(View.GONE);
}
if (mObservationsList.getAdapter() == null) {
mObservationsListAdapter = new UserObservationAdapter(UserProfile.this, mObservations);
mObservationsList.setAdapter(mObservationsListAdapter);
}
mObservationsList.setVisibility(View.VISIBLE);
}
if (mSpecies == null) {
((TextView)tabWidget.getChildAt(1).findViewById(R.id.count)).setVisibility(View.GONE);
((ProgressBar)tabWidget.getChildAt(1).findViewById(R.id.loading)).setVisibility(View.VISIBLE);
mLoadingSpeciesList.setVisibility(View.VISIBLE);
mSpeciesListEmpty.setVisibility(View.GONE);
mSpeciesList.setVisibility(View.GONE);
} else {
((TextView)tabWidget.getChildAt(1).findViewById(R.id.count)).setVisibility(View.VISIBLE);
((ProgressBar)tabWidget.getChildAt(1).findViewById(R.id.loading)).setVisibility(View.GONE);
((TextView)tabWidget.getChildAt(1).findViewById(R.id.count)).setText(formatter.format(mTotalSpecies));
mLoadingSpeciesList.setVisibility(View.GONE);
if (mSpecies.size() == 0) {
mSpeciesListEmpty.setVisibility(View.VISIBLE);
} else {
mSpeciesListEmpty.setVisibility(View.GONE);
}
if (mSpeciesList.getAdapter() == null) {
mSpeciesListAdapter = new UserSpeciesAdapter(UserProfile.this, mSpecies);
mSpeciesList.setAdapter(mSpeciesListAdapter);
mSpeciesList.setVisibility(View.VISIBLE);
}
}
if (mIdentifications == null) {
((TextView)tabWidget.getChildAt(2).findViewById(R.id.count)).setVisibility(View.GONE);
((ProgressBar)tabWidget.getChildAt(2).findViewById(R.id.loading)).setVisibility(View.VISIBLE);
mLoadingIdentificationsList.setVisibility(View.VISIBLE);
mIdentificationsListEmpty.setVisibility(View.GONE);
mIdentificationsList.setVisibility(View.GONE);
} else {
((TextView)tabWidget.getChildAt(2).findViewById(R.id.count)).setVisibility(View.VISIBLE);
((ProgressBar)tabWidget.getChildAt(2).findViewById(R.id.loading)).setVisibility(View.GONE);
((TextView)tabWidget.getChildAt(2).findViewById(R.id.count)).setText(formatter.format(mTotalIdentifications));
mLoadingIdentificationsList.setVisibility(View.GONE);
if (mIdentifications.size() == 0) {
mIdentificationsListEmpty.setVisibility(View.VISIBLE);
} else {
mIdentificationsListEmpty.setVisibility(View.GONE);
}
if (mIdentificationsList.getAdapter() == null) {
mIdentificationsListAdapter = new UserIdentificationsAdapter(UserProfile.this, mIdentifications, mUser.getString("login"));
mIdentificationsList.setAdapter(mIdentificationsListAdapter);
mIdentificationsList.setVisibility(View.VISIBLE);
// Make sure the images get loaded only when the user stops scrolling
mIdentificationsList.setOnScrollListener(mIdentificationsListAdapter);
mIdentificationsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
JSONObject item = (JSONObject) view.getTag();
Intent intent = new Intent(UserProfile.this, ObservationViewerActivity.class);
intent.putExtra("observation", item.optJSONObject("observation").toString());
intent.putExtra("read_only", true);
intent.putExtra("reload", true);
startActivity(intent);
}
});
}
}
}
public void onOffsetChanged(AppBarLayout appBarLayout, int offset) {
int maxScroll = appBarLayout.getTotalScrollRange();
float percentage = (float) Math.abs(offset) / (float) maxScroll;
if (percentage >= 0.9f) {
if (!mUserPicHidden) {
startAlphaAnimation(mUserPicContainer, 100, View.INVISIBLE);
mUserPicHidden = true;
}
} else {
if (mUserPicHidden) {
startAlphaAnimation(mUserPicContainer, 100, View.VISIBLE);
mUserPicHidden = false;
}
}
}
public static void startAlphaAnimation (View v, long duration, int visibility) {
AlphaAnimation alphaAnimation = (visibility == View.VISIBLE)
? new AlphaAnimation(0f, 1f)
: new AlphaAnimation(1f, 0f);
alphaAnimation.setDuration(duration);
alphaAnimation.setFillAfter(true);
v.startAnimation(alphaAnimation);
}
private void refreshUserDetails() {
mUserName.setText(mUser.getString("login"));
CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
String fullName = mUser.getString("name");
if ((fullName == null) || (fullName.length() == 0)) {
// No full name - use username instead
collapsingToolbar.setTitle(mUser.getString("login"));
mUserName.setVisibility(View.INVISIBLE);
} else {
collapsingToolbar.setTitle(fullName);
mUserName.setVisibility(View.VISIBLE);
}
final String bio = mUser.getString("description");
mUserBio.setOnClickListener(null);
final View.OnClickListener onBio = new View.OnClickListener() {
@Override
public void onClick(View view) {
String bio = mUser.getString("description");
if ((bio == null) || (bio.length() == 0)) {
// No bio
return;
}
String title;
String fullName = mUser.getString("name");
if ((fullName == null) || (fullName.length() == 0)) {
title = mUser.getString("login");
} else {
title = fullName;
}
mHelper.alert(title, mUser.getString("description"));
}
};
if ((bio == null) || (bio.length() == 0)) {
mUserBio.setVisibility(View.GONE);
} else {
mUserBio.setVisibility(View.VISIBLE);
mUserBio.setText(Html.fromHtml(bio));
ViewTreeObserver vto = mUserBio.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < 16) {
mUserBio.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
mUserBio.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
Layout l = mUserBio.getLayout();
if (l != null) {
int lines = l.getLineCount();
if (lines > 0) {
if (l.getEllipsisCount(lines - 1) > 0) {
// Bio is ellipsized - Trim the bio text to show the more link
String newBio = bio.substring(0, l.getLineStart(lines - 1) + l.getEllipsisStart(lines - 1) - 8) + "... " + getString(R.string.more_bio);
mUserBio.setText(Html.fromHtml(newBio));
// Show the full bio when the shortened bio is clicked
mUserBio.setOnClickListener(onBio);
}
}
}
}
});
}
final ImageView userPic = (ImageView) findViewById(R.id.user_pic);
String iconUrl = mUser.getString("medium_user_icon_url");
if (iconUrl == null) iconUrl = mUser.getString("user_icon_url");
if (iconUrl == null) iconUrl = mUser.getString("icon_url");
if ((iconUrl != null) && (iconUrl.length() > 0)) {
UrlImageViewHelper.setUrlDrawable(userPic, iconUrl, new UrlImageViewCallback() {
@Override
public void onLoaded(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) {
findViewById(R.id.no_user_pic).setVisibility(View.GONE);
userPic.setVisibility(View.VISIBLE);
}
@Override
public Bitmap onPreSetBitmap(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) {
Bitmap centerCrop = ImageUtils.centerCropBitmap(loadedBitmap);
return ImageUtils.getCircleBitmap(centerCrop);
}
});
UrlImageViewHelper.setUrlDrawable((ImageView) findViewById(R.id.user_bg), iconUrl + "?bg=1", new UrlImageViewCallback() {
@Override
public void onLoaded(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) {
if (loadedBitmap != null) {
imageView.setImageBitmap(ImageUtils.blur(UserProfile.this, ImageUtils.centerCropBitmap(loadedBitmap.copy(loadedBitmap.getConfig(), true))));
}
}
@Override
public Bitmap onPreSetBitmap(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) {
return loadedBitmap;
}
});
userPic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Only show the photo viewer if a large enough image exists
if ((mUser.getString("original_user_icon_url") != null) || (mUser.getString("medium_user_icon_url") != null) || (mUser.getString("icon_url") != null)) {
Intent intent = new Intent(UserProfile.this, ProfilePhotoViewer.class);
intent.putExtra(ProfilePhotoViewer.USER, mUser.getJSONObject().toString());
startActivity(intent);
}
}
});
} else {
userPic.setVisibility(View.GONE);
findViewById(R.id.no_user_pic).setVisibility(View.VISIBLE);
}
}
}
|
package eu.itesla_project.ucte.network;
import eu.itesla_project.commons.ConverterBaseTest;
import eu.itesla_project.ucte.network.io.UcteReader;
import eu.itesla_project.ucte.network.io.UcteWriter;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* @author Christian Biasuzzi <christian.biasuzzi@techrain.it>
* @author Mathieu Bague <mathieu.bague@rte-france.com>
*/
public class UcteFileReadWriteTest extends ConverterBaseTest {
private static final String REFERENCE = "/20170322_1844_SN3_FR2.uct";
private static UcteNetwork create() {
try (BufferedReader br = new BufferedReader(new InputStreamReader(UcteFileReadWriteTest.class.getResourceAsStream(REFERENCE)))) {
return new UcteReader().read(br);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static void write(UcteNetwork network, Path file) {
try (BufferedWriter bw = Files.newBufferedWriter(file)) {
new UcteWriter(network).write(bw);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static UcteNetwork read(Path file) {
try (BufferedReader br = Files.newBufferedReader(file)) {
return new UcteReader().read(br);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Test
public void roundTripTest() throws IOException {
roundTripTest(create(), UcteFileReadWriteTest::write, UcteFileReadWriteTest::read, REFERENCE);
}
}
|
package imagej.ui.swing.commands.debug;
import imagej.command.Command;
import imagej.plugin.Parameter;
import imagej.plugin.Plugin;
import imagej.ui.DialogPrompt;
import imagej.ui.UIService;
/**
* A demonstration of ImageJ's UI-agnostic dialog prompt capabilities.
*
* @author Grant Harris
* @author Curtis Rueden
*/
@Plugin(menuPath = "Plugins>Sandbox>Dialog Prompt Demo")
public class DialogPromptDemo implements Command {
@Parameter
private UIService uiService;
@Override
public void run() {
final DialogPrompt.Result result =
uiService.showDialog("Do you like green eggs and ham?", "Sam I Am",
DialogPrompt.MessageType.QUESTION_MESSAGE,
DialogPrompt.OptionType.YES_NO_OPTION);
boolean yes = result == DialogPrompt.Result.YES_OPTION;
uiService.showDialog(yes ? "Good for you!" : "Why not?");
}
}
|
package com.dlucci.widdlewidget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Button;
import android.widget.RemoteViews;
import android.hardware.Camera.Parameters;
import android.hardware.Camera;
import android.provider.Settings;
import java.lang.System;
public class WiddleWidget extends AppWidgetProvider{
private static final String TAG = "WiddleWidget";
private static final String WIFI_ACTION = "com.dlucci.widdlewidget.wifi";
private static final String AIRPLANE_ACTION = "com.dlucci.widdlewidget.airplane";
private static final String FLASHLIGHT_ACTION = "com.dlucci.widdlewidget.flashlight";
private Button wifi, airplane, flashlight;
private static boolean flashOn = false;
private static Camera cam;
@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.d(TAG, "onUpdate");
for(int i = 0; i < appWidgetIds.length; i++) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widdlewidget_layout);
Intent btnAction = new Intent(context, this.getClass());
btnAction.setAction(WIFI_ACTION);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, btnAction, 0);
Log.d(TAG, "finishing up onUpdate");
views.setOnClickPendingIntent(R.id.wifi, pi);
appWidgetManager.updateAppWidget(appWidgetIds[i], views);
btnAction.setAction(FLASHLIGHT_ACTION);
pi = PendingIntent.getBroadcast(context, 0, btnAction, 0);
views.setOnClickPendingIntent(R.id.light, pi);
appWidgetManager.updateAppWidget(appWidgetIds[i], views);
btnAction.setAction(AIRPLANE_ACTION);
pi = PendingIntent.getBroadcast(context, 0, btnAction, 0);
views.setOnClickPendingIntent(R.id.airplane, pi);
appWidgetManager.updateAppWidget(appWidgetIds[i], views);
}
}
@Override public void onReceive(Context context, Intent i){
Log.d(TAG, "onReceive");
String action = i.getAction();
Log.d(TAG, "Action is " + action);
if(action.equals(WIFI_ACTION)){
WifiManager manager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
if(manager.isWifiEnabled())
manager.setWifiEnabled(false);
else
manager.setWifiEnabled(true);
} else if(action.equals(FLASHLIGHT_ACTION)){
if(flashOn){
cam.stopPreview();
cam.unlock();
cam.release();
flashOn = false;
} else {
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
cam.lock();
flashOn = true;
}
} else if(action.equals(AIRPLANE_ACTION)){
boolean isEnabled = Settings.System.getInt(
context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 1;
Settings.System.putInt(
context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);
}
super.onReceive(context, i);
}
}
|
package com.example.jacek.streamthegame;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import com.example.jacek.streamthegame.GameObjects.GameObject;
import java.util.EventObject;
import java.util.HashSet;
public class Grid {
private AnimationFinishedListener animationFinishedListener;
private int nRows, nCols;
private int cellWidth, cellHeight;
// currentLayout maps all cells with object that are placed on them
// from item number to coordinates:
// int col = i / this.nCols;
// int row = i % this.nCols;
// from coordinates to element in the array:
// int i = row*this.nCols + col;
private GameObject[] currentLayout;
private GameObjectFactory gameObjectFactory;
public Grid(Context context, LevelDefinition level, int canvasHeight, int canvasWidth) {
this.nRows = level.getHeight();
this.nCols = level.getWidth();
this.cellHeight = canvasHeight/this.nRows;
this.cellWidth = canvasWidth/this.nCols;
this.gameObjectFactory = new GameObjectFactory(context, this.cellWidth, this.cellHeight);
this.currentLayout = new GameObject[this.nRows*this.nCols];
this.addLevelObjects(level);
}
public void draw(Canvas canvas) {
HashSet<GameObject> drawn = new HashSet<>();
for (int i = 0; i < this.nRows * this.nCols; ++i) {
GameObject item = currentLayout[i];
if (item != null && !drawn.contains(item)) {
int row = i / this.nCols;
int col = i % this.nCols;
// draw Object
canvas.drawBitmap(
item.getImage(),
this.cellWidth * col,
this.cellHeight * row,
null);
drawn.add(item);
}
}
}
public int getCellWidth() {
return this.cellWidth;
}
public int getCellHeight() {
return this.cellHeight;
}
public GameObject getObjectFromCoords(int row, int col) {
return this.currentLayout[row*this.nCols + col];
}
public void rotateObjAt(int row, int col) {
GameObject obj = this.getObjectFromCoords(row, col);
if (obj != null) {
Point startCoords = this.getStartCoords(row, col);
if (this.isRotationSave(startCoords.x, startCoords.y)) {
this.removeObject(obj);
obj.rotate();
this.addToLayout(obj, startCoords.x, startCoords.y);
}
}
}
/**
* @param row: row coordinate of the object to move.
* @param col: col coordinate of the object to move.
* @param drow: movement in y-axis: + row down, - row up
* @param dcol: movement in x-axis: + col right, - col left
* @return true if move was successful
* */
public boolean moveObjAt(int row, int col, int drow, int dcol) {
GameObject obj = this.getObjectFromCoords(row, col);
if (obj != null) {
Point startCoords = this.getStartCoords(row, col);
if (!this.checkObjCollision(startCoords.x, startCoords.y, drow, dcol)) {
this.removeObject(obj);
this.addToLayout(obj, startCoords.x + drow, startCoords.y + dcol);
return true;
}
}
return false;
}
public void removeObject(GameObject obj) {
for (int i = 0; i < this.nRows * this.nCols; ++i) {
if(this.currentLayout[i] == obj) {
this.currentLayout[i] = null;
}
}
}
public void addLevelObjects(LevelDefinition level) {
for(GameObjectDefinition objDef : level.getObjects()) {
GameObject obj = this.gameObjectFactory.getObject(objDef.getSprite());
obj.rotate(objDef.getRotations());
this.addToLayout(obj, objDef.getInsertionRow(), objDef.getInsertionCol());
}
}
public void update() {
for (int i = 0; i < this.nRows * this.nCols; ++i) {
GameObject obj = this.currentLayout[i];
if (obj != null) {
if (obj.getType() == Sprite.enter && obj.finishedAnimating()) {
this.animationFinished(true);
break;
}
if (obj.isAnimating()) {
this.updateAnimations(obj, i);
break;
}
}
}
}
public synchronized void registerAnimationFinishedHandler(AnimationFinishedListener listener) {
this.animationFinishedListener = listener;
}
private void updateAnimations(GameObject obj, int pos) {
obj.update();
if (obj.finishedAnimating()) {
this.startPairedAnimation(obj, pos);
}
}
private void startPairedAnimation(GameObject obj, int pos) {
//find another object in chain to start animation on it
Exit exit = obj.getAnimationEndExit();
Point cornerCoords = obj.getCoordsFromCorner(exit.getCorner());
int oldRow = pos / this.nCols + cornerCoords.x;
int oldCol = pos % this.nCols + cornerCoords.y;
int newRow = this.getPairedRow(exit.getDir(), oldRow);
int newCol = this.getPairedCol(exit.getDir(), oldCol);
if (this.hasPairedExit(newRow, newCol, exit.getDir())) {
GameObject newObj = this.getObjectFromCoords(newRow, newCol);
//if (!newObj.finishedAnimating()) {
newObj.startAnimation(this.getPairedExit(newRow, newCol, exit.getDir()));
} else {
//this.startFailLevelAnimation(newRow, newCol, exit.getDir()); // todo maybe in the futute, for now just reset animations
this.resetAnimations();
this.animationFinished(false);
}
}
private int getPairedRow(Direction dir, int row) {
switch(dir) {
case UP:
row
break;
case DOWN:
row++;
break;
}
return row;
}
private int getPairedCol(Direction dir, int col) {
switch(dir) {
case LEFT:
col
break;
case RIGHT:
col++;
break;
}
return col;
}
private boolean hasPairedExit(int row, int col, Direction dir) {
if (row < 0 || row > this.nRows) return false;
if (col < 0 || col > this.nCols) return false;
GameObject obj = this.getObjectFromCoords(row, col);
if(obj == null) return false;
Point startCoords = this.getStartCoords(row, col);
return obj.hasExitAt(row - startCoords.x, col - startCoords.y, dir.opposite());
}
private Exit getPairedExit(int row, int col, Direction dir) {
GameObject obj = this.getObjectFromCoords(row, col);
Point startCoords = this.getStartCoords(row, col);
return obj.getExitAt(row - startCoords.x, col - startCoords.y, dir.opposite());
}
/** Performs add to layout without any collision and boundary checks.
* Assumes that checks for save insert was performed prior to calling this function.
* @param object: object to add to layout.
* @param row: x coordinate of the upper left corner of the object.
* @param col: y coordinate of the upper left corner of the object.
* */
private void addToLayout(GameObject object, int row, int col) {
int width = object.getWidthCells();
int height = object.getHeightCells();
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int pos = (row + i)*this.nCols + (col+j);
this.currentLayout[pos] = object;
}
}
}
/**
* return upper left corner coordinates of an object from row and col
* @return Point object: x = row, y = col
* */
private Point getStartCoords(int row, int col) {
GameObject obj = this.getObjectFromCoords(row, col);
if(obj == null) return new Point(row, col);
// first check up
for(int r = row - 1; r >= 0; --r) {
if (this.getObjectFromCoords(r, col) == obj) {
row = r;
} else break;
}
// then check left
for(int c = col - 1; c >= 0; --c) {
if (this.getObjectFromCoords(row, c) == obj) {
col = c;
} else break;
}
return new Point(row, col);
}
/**
* Important note: assumes that srow and scol are coordinates
* of the upper left corner of an object
*
* @param srow: start (upper left) row
* @param scol: start (upper left) col
* @param drow: movement in y-axis: + row down, - row up
* @param dcol: movement in x-axis: + col right, - col left
* @returns:
* true = collision detected
* false = collision not detected
* */
private boolean checkObjCollision(int srow, int scol, int drow, int dcol) {
GameObject obj = this.getObjectFromCoords(srow, scol);
int width = obj.getWidthCells();
int height = obj.getHeightCells();
int row = srow + drow; // new insertion row
int col = scol + dcol; // new insertion col
// check boundaries
if (row < 0 || row + height > this.nRows) return true;
if (col < 0 || col + width > this.nCols) return true;
// check if all cells occupied by object are empty
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int pos = (row + i)*this.nCols + (col+j);
if (this.currentLayout[pos] != null && this.currentLayout[pos] != obj) {
return true;
}
}
}
// if checks above didn't find a collision there is none
return false;
}
/**
* checks if object rotation is not colliding with other object and screen end
* @param srow: start (upper left) row of an object
* @param scol: start (upper left) col of an object
* */
private boolean isRotationSave(int srow, int scol) {
GameObject obj = this.getObjectFromCoords(srow, scol);
// after rotation objects dimensions will swap
int height = obj.getWidthCells();
int width = obj.getHeightCells();
if (srow + height > this.nRows) return false;
if (scol + width > this.nCols) return false;
// check if all new cells occupied by object are empty
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int pos = (srow + i)*this.nCols + (scol+j);
if (this.currentLayout[pos] != null && this.currentLayout[pos] != obj) {
return false;
}
}
}
return true;
}
private synchronized void resetAnimations() {
HashSet<GameObject> visited = new HashSet<>();
for (GameObject obj : this.currentLayout) {
if (obj != null && !visited.contains(obj)) {
obj.resetAnimation();
visited.add(obj);
}
}
}
private synchronized void animationFinished (boolean isSuccess) {
AnimationFinishedEvent event = new AnimationFinishedEvent(this, isSuccess);
if(this.animationFinishedListener != null){
this.animationFinishedListener.animationFinished(event);
}
}
private void startFailLevelAnimation(int row, int col, Direction dir) {
// todo
}
private void clearLayout() {
for (GameObject obj : this.currentLayout) {
obj = null;
}
}
}
|
package com.expidev.gcmapp.http;
import static com.expidev.gcmapp.Constants.PREFS_SETTINGS;
import static com.expidev.gcmapp.Constants.PREF_CURRENT_ASSIGNMENT;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import com.expidev.gcmapp.BuildConfig;
import com.expidev.gcmapp.http.GmaApiClient.Session;
import com.expidev.gcmapp.json.MeasurementsJsonParser;
import com.expidev.gcmapp.json.MinistryJsonParser;
import com.expidev.gcmapp.model.Assignment;
import com.expidev.gcmapp.model.Church;
import com.expidev.gcmapp.model.Ministry;
import com.expidev.gcmapp.model.measurement.MeasurementDetails;
import com.expidev.gcmapp.model.Training;
import com.expidev.gcmapp.service.MinistriesService;
import org.ccci.gto.android.common.api.AbstractApi.Request.MediaType;
import org.ccci.gto.android.common.api.AbstractApi.Request.Method;
import org.ccci.gto.android.common.api.AbstractTheKeyApi;
import org.ccci.gto.android.common.api.ApiException;
import org.ccci.gto.android.common.api.ApiSocketException;
import org.ccci.gto.android.common.util.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import me.thekey.android.TheKey;
import me.thekey.android.TheKeySocketException;
import me.thekey.android.lib.TheKeyImpl;
import static com.expidev.gcmapp.BuildConfig.THEKEY_CLIENTID;
public final class GmaApiClient extends AbstractTheKeyApi<AbstractTheKeyApi.Request<Session>, Session> {
private final String TAG = getClass().getSimpleName();
private static final String ASSIGNMENTS = "assignments";
private static final String CHURCHES = "churches";
private static final String MEASUREMENTS = "measurements";
private static final String MINISTRIES = "ministries";
private static final String TOKEN = "token";
private static final String TRAINING = "training";
private static final Object LOCK_INSTANCE = new Object();
private static GmaApiClient INSTANCE;
// XXX: temporary until mContext from AbstractApi is visible
private final Context mContext;
private final SharedPreferences mPrefs;
private GmaApiClient(final Context context) {
super(context, TheKeyImpl.getInstance(context, THEKEY_CLIENTID), BuildConfig.GCM_BASE_URI, "gcm_api_sessions");
mContext = context;
mPrefs = mContext.getSharedPreferences(PREFS_SETTINGS, Context.MODE_PRIVATE);
}
public static GmaApiClient getInstance(final Context context) {
synchronized (LOCK_INSTANCE) {
if(INSTANCE == null) {
INSTANCE = new GmaApiClient(context.getApplicationContext());
}
}
return INSTANCE;
}
@Nullable
@Override
protected String getDefaultService() {
return mBaseUri.buildUpon().appendPath(TOKEN).toString();
}
@Override
protected Session loadSession(@NonNull final SharedPreferences prefs, @NonNull final Request request) {
return new Session(prefs, request.guid);
}
@Nullable
@Override
protected Session establishSession(@NonNull final Request<Session> request) throws ApiException {
HttpURLConnection conn = null;
try {
final String service = getService();
if (service != null) {
// issue request only if we get a ticket for the user making this request
final TheKey.TicketAttributesPair ticket = mTheKey.getTicketAndAttributes(service);
assert request.guid != null;
if (ticket != null && request.guid.equals(ticket.attributes.getGuid())) {
// issue getToken request
conn = this.getToken(ticket.ticket, false);
// parse valid responses
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// extract cookies
// XXX: this won't be needed once Jon removes the cookie requirement from the API
final Set<String> cookies = this.extractCookies(conn);
// parse response JSON
final JSONObject json = new JSONObject(IOUtils.readString(conn.getInputStream()));
// save the returned associated ministries
// XXX: this isn't ideal and crosses logical components, but I can't think of a cleaner way to do it currently -DF
MinistriesService
.saveAssociatedMinistriesFromServer(mContext, json.optJSONArray("assignments"));
// create session object
return new Session(json.optString("session_ticket", null), cookies,
ticket.attributes.getGuid());
} else {
// authentication with the ticket failed, let's clear the cached service in case that caused the issue
if (service.equals(getCachedService())) {
setCachedService(null);
}
}
}
}
} catch (final TheKeySocketException | IOException e) {
throw new ApiSocketException(e);
} catch (final JSONException e) {
Log.i(TAG, "invalid json for getToken", e);
} finally {
IOUtils.closeQuietly(conn);
}
// unable to get a session
return null;
}
@NonNull
private Set<String> extractCookies(@NonNull final HttpURLConnection conn) {
final Set<String> cookies = new HashSet<>();
for (final Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
final String key = header.getKey();
if ("Set-Cookie".equalsIgnoreCase(key) || "Set-Cookie2".equals(key)) {
for (final String value : header.getValue()) {
for (final HttpCookie cookie : HttpCookie.parse(value)) {
if (cookie != null) {
cookies.add(cookie.toString());
}
}
}
}
}
return cookies;
}
@Override
protected void onPrepareUri(@NonNull final Uri.Builder uri, @NonNull final Request<Session> request)
throws ApiException {
super.onPrepareUri(uri, request);
// append the session_token when using the session
if (request.useSession && request.session != null) {
uri.appendQueryParameter("token", request.session.id);
}
}
@Override
protected void onPrepareRequest(@NonNull final HttpURLConnection conn, @NonNull final Request<Session> request)
throws ApiException, IOException {
super.onPrepareRequest(conn, request);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
// attach cookies when using the session
// XXX: this should go away once we remove the cookie requirement on the API
if (request.useSession && request.session != null) {
conn.addRequestProperty("Cookie", TextUtils.join("; ", request.session.cookies));
}
}
/* API methods */
@NonNull
private HttpURLConnection getToken(@NonNull final String ticket, final boolean refresh) throws ApiException {
// build login request
final Request<Session> login = new Request<>(TOKEN);
login.accept = MediaType.APPLICATION_JSON;
login.params.add(param("st", ticket));
login.params.add(param("refresh", refresh));
login.useSession = false;
// send request (tickets are one time use only, so we can't retry)
return this.sendRequest(login, 0);
}
@Nullable
public List<Ministry> getAllMinistries() throws ApiException {
return this.getAllMinistries(false);
}
@Nullable
public List<Ministry> getAllMinistries(final boolean refresh) throws ApiException {
// build request
final Request<Session> request = new Request<>(MINISTRIES);
request.params.add(param("refresh", refresh));
// process request
HttpURLConnection conn = null;
try
{
conn = this.sendRequest(request);
Log.i(TAG, "response code: " + Integer.toString(conn.getResponseCode()));
// is this a successful response?
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
final JSONArray json = new JSONArray(IOUtils.readString(conn.getInputStream()));
return MinistryJsonParser.parseMinistriesJson(json);
}
} catch (final JSONException e) {
Log.e(TAG, "error parsing getAllMinistries response", e);
} catch (final IOException e) {
throw new ApiSocketException(e);
} finally {
IOUtils.closeQuietly(conn);
}
return null;
}
/* BEGIN church methods */
@Nullable
public List<Church> getChurches(@NonNull final String ministryId) throws ApiException {
// build request
final Request<Session> request = new Request<>(CHURCHES);
request.accept = MediaType.APPLICATION_JSON;
request.params.add(param("ministry_id", ministryId));
// process request
HttpURLConnection conn = null;
try {
conn = this.sendRequest(request);
// is this a successful response?
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return Church.listFromJson(new JSONArray(IOUtils.readString(conn.getInputStream())));
}
} catch (final JSONException e) {
Log.e(TAG, "error parsing getChurches response", e);
} catch (final IOException e) {
throw new ApiSocketException(e);
} finally {
IOUtils.closeQuietly(conn);
}
return null;
}
public boolean createChurch(@NonNull final Church church) throws ApiException, JSONException {
return this.createChurch(church.toJson());
}
public boolean createChurch(@NonNull final JSONObject church) throws ApiException {
// build request
final Request<Session> request = new Request<>(CHURCHES);
request.method = Method.POST;
request.setContent(church);
// process request
HttpURLConnection conn = null;
try {
conn = this.sendRequest(request);
// is this a successful response?
return conn.getResponseCode() == HttpURLConnection.HTTP_CREATED;
} catch (final IOException e) {
throw new ApiSocketException(e);
} finally {
IOUtils.closeQuietly(conn);
}
}
public boolean updateChurch(@NonNull final Church church) throws ApiException, JSONException {
return this.updateChurch(church.getId(), church.toJson());
}
public boolean updateChurch(final long id, @NonNull final JSONObject church) throws ApiException {
// short-circuit if we are trying to update an invalid church
if (id == Church.INVALID_ID) {
return false;
}
// build request
final Request<Session> request = new Request<>(CHURCHES + "/" + id);
request.method = Method.PUT;
request.setContent(church);
// process request
HttpURLConnection conn = null;
try {
conn = this.sendRequest(request);
// is this a successful response?
return conn.getResponseCode() == HttpURLConnection.HTTP_CREATED;
} catch (final IOException e) {
throw new ApiSocketException(e);
} finally {
IOUtils.closeQuietly(conn);
}
}
/* END church methods */
@Nullable
public JSONArray searchMeasurements(@NonNull final String ministryId, @NonNull final String mcc,
@Nullable final String period) throws ApiException {
// build request
final Request<Session> request = new Request<>(MEASUREMENTS);
request.params.add(param("ministry_id", ministryId));
request.params.add(param("mcc", mcc));
if (period != null) {
request.params.add(param("period", period));
}
// process request
HttpURLConnection conn = null;
try {
conn = this.sendRequest(request);
// is this a successful response?
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return new JSONArray(IOUtils.readString(conn.getInputStream()));
}
} catch (final JSONException e) {
Log.e(TAG, "error parsing getAllMinistries response", e);
} catch (final IOException e) {
throw new ApiSocketException(e);
} finally {
IOUtils.closeQuietly(conn);
}
return null;
}
@Nullable
public JSONObject getDetailsForMeasurement(@NonNull final String measurementId, @NonNull final String ministryId,
@NonNull final String mcc, @Nullable final String period)
throws ApiException {
// build request
final Request<Session> request = new Request<>(MEASUREMENTS + "/" + measurementId);
request.params.add(param("ministry_id", ministryId));
request.params.add(param("mcc", mcc.toLowerCase()));
if (period != null) {
request.params.add(param("period", period));
}
// process request
HttpURLConnection conn = null;
try {
conn = this.sendRequest(request);
// is this a successful response?
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return new JSONObject(IOUtils.readString(conn.getInputStream()));
}
} catch (final JSONException e) {
Log.e(TAG, "error parsing getAllMinistries response", e);
} catch (final IOException e) {
throw new ApiSocketException(e);
} finally {
IOUtils.closeQuietly(conn);
}
return null;
}
public boolean updateMeasurementDetails(List<MeasurementDetails> measurementDetailsList)
throws JSONException, ApiException
{
String assignmentId = mPrefs.getString(PREF_CURRENT_ASSIGNMENT, null);
List<JSONObject> data = new ArrayList<>();
for(MeasurementDetails measurementDetails : measurementDetailsList)
{
// Can be positive or negative
if(measurementDetails.getLocalValue() != 0)
{
data.add(MeasurementsJsonParser.createJsonForMeasurementDetails(measurementDetails, "local", assignmentId));
}
if(measurementDetails.getPersonalValue() != 0)
{
data.add(MeasurementsJsonParser.createJsonForMeasurementDetails(measurementDetails, "personal", assignmentId));
}
}
return updateMeasurementDetails(MeasurementsJsonParser.createPostJsonForMeasurementDetails(data));
}
public boolean updateMeasurementDetails(JSONArray data) throws ApiException
{
// build request
final Request<Session> request = new Request<>(MEASUREMENTS);
request.method = Method.POST;
request.setContent(data);
// process request
HttpURLConnection conn = null;
try
{
conn = this.sendRequest(request);
Log.i(TAG, "Response Code: " + conn.getResponseCode());
Log.i(TAG, "Data POSTed: " + data.toString());
// is this a successful response?
return conn.getResponseCode() == HttpURLConnection.HTTP_CREATED;
}
catch (final IOException e)
{
throw new ApiSocketException(e);
}
finally
{
IOUtils.closeQuietly(conn);
}
}
@Nullable
public JSONArray getAssignments() throws ApiException {
return this.getAssignments(false);
}
@Nullable
public JSONArray getAssignments(final boolean refresh) throws ApiException {
// build request
final Request<Session> request = new Request<>(ASSIGNMENTS);
request.params.add(param("refresh", refresh));
// process request
HttpURLConnection conn = null;
try {
conn = this.sendRequest(request);
// is this a successful response?
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return new JSONArray(IOUtils.readString(conn.getInputStream()));
}
} catch (final JSONException e) {
Log.e(TAG, "error parsing getAllMinistries response", e);
} catch (final IOException e) {
throw new ApiSocketException(e);
} finally {
IOUtils.closeQuietly(conn);
}
return null;
}
@Nullable
public JSONObject createAssignment(@NonNull final String userEmail, @NonNull final String ministryId,
@NonNull final Assignment.Role role) throws ApiException {
// build request
final Request<Session> request = new Request<>(ASSIGNMENTS);
request.method = Method.POST;
// generate POST data
final Map<String, Object> data = new HashMap<>();
data.put("username", userEmail);
data.put("ministry_id", ministryId);
data.put("team_role", role.raw);
request.setContent(new JSONObject(data));
// issue request and process response
HttpURLConnection conn = null;
try {
conn = this.sendRequest(request);
// if successful return parsed response
if (conn.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
return new JSONObject(IOUtils.readString(conn.getInputStream()));
}
} catch (final IOException e) {
throw new ApiSocketException(e);
} catch (final JSONException e) {
Log.i(TAG, "invalid response json for createAssignment", e);
} finally {
IOUtils.closeQuietly(conn);
}
return null;
}
@Nullable
public JSONArray searchTraining(@NonNull final String ministryId, @NonNull final String mcc) throws ApiException {
// build request
final Request<Session> request = new Request<>(TRAINING);
request.params.add(param("ministry_id", ministryId));
request.params.add(param("mcc", mcc));
// process request
HttpURLConnection conn = null;
try
{
conn = this.sendRequest(request);
// is this a successful response?
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return new JSONArray(IOUtils.readString(conn.getInputStream()));
}
} catch (final JSONException e) {
Log.e(TAG, "error parsing searchTraining response", e);
} catch (final IOException e) {
throw new ApiSocketException(e);
} finally {
IOUtils.closeQuietly(conn);
}
return null;
}
public boolean updateTraining(final long id, @NonNull final JSONObject training) throws ApiException
{
if (id == Training.INVALID_ID) return false;
final Request<Session> request = new Request<>(TRAINING + "/" + id);
request.method = Method.PUT;
request.setContent(training);
HttpURLConnection connn = null;
try
{
connn = this.sendRequest(request);
return connn.getResponseCode() == HttpURLConnection.HTTP_CREATED;
} catch (final IOException e)
{
throw new ApiSocketException(e);
}
finally
{
IOUtils.closeQuietly(connn);
}
}
protected static class Session extends AbstractTheKeyApi.Session {
@NonNull
final Set<String> cookies;
Session(@Nullable final String id, @Nullable final Collection<String> cookies, @NonNull final String guid) {
super(id, guid);
this.cookies = Collections.unmodifiableSet(new HashSet<>(cookies));
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
Session(@NonNull final SharedPreferences prefs, @NonNull final String guid) {
super(prefs, guid);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
this.cookies = Collections.unmodifiableSet(new HashSet<>(
prefs.getStringSet(this.getPrefAttrName("cookies"), Collections.<String>emptySet())));
} else {
// work around missing getStringSet
final Set<String> cookies = new HashSet<>();
try {
final JSONArray json =
new JSONArray(prefs.getString(this.getPrefAttrName("cookies"), null));
for (int i = 0; i < json.length(); i++) {
cookies.add(json.getString(i));
}
} catch (final JSONException ignored) {
}
this.cookies = Collections.unmodifiableSet(cookies);
}
}
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void save(@NonNull final SharedPreferences.Editor prefs) {
super.save(prefs);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
prefs.putStringSet(this.getPrefAttrName("cookies"), this.cookies);
} else {
// work around missing putStringSet
prefs.putString(this.getPrefAttrName("cookies"), new JSONArray(this.cookies).toString());
}
}
@Override
protected void delete(@NonNull SharedPreferences.Editor prefs) {
super.delete(prefs);
prefs.remove(this.getPrefAttrName("cookies"));
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Session that = (Session) o;
return super.equals(o) && this.cookies.equals(that.cookies);
}
@Override
protected boolean isValid() {
return super.isValid() && this.cookies.size() > 0;
}
}
}
|
package org.archive.wayback.proxy;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Properties;
import org.archive.wayback.ResultURIConverter;
import org.archive.wayback.WaybackConstants;
import org.archive.wayback.core.PropertyConfiguration;
import org.archive.wayback.exception.ConfigurationException;
/**
*
*
* @author brad
* @version $Date$, $Revision$
*/
public class RedirectResultURIConverter implements ResultURIConverter {
private static final String REDIRECT_PATH_PROPERTY = "proxy.redirectpath";
private String redirectURI = null;
public void init(Properties p) throws ConfigurationException {
PropertyConfiguration pc = new PropertyConfiguration(p);
redirectURI = pc.getString(REDIRECT_PATH_PROPERTY);
}
/* (non-Javadoc)
* @see org.archive.wayback.ResultURIConverter#makeReplayURI(java.lang.String, java.lang.String)
*/
public String makeReplayURI(String datespec, String url) {
String res = null;
if(!url.startsWith(WaybackConstants.HTTP_URL_PREFIX)) {
url = WaybackConstants.HTTP_URL_PREFIX + url;
}
try {
res = redirectURI + "?url=" + URLEncoder.encode(url, "UTF-8") +
"&time=" + URLEncoder.encode(datespec, "UTF-8");
} catch (UnsupportedEncodingException e) {
// should not be able to happen -- with hard-coded UTF-8, anyways..
e.printStackTrace();
}
return res;
}
/**
* @param redirectURI the redirectURI to set
*/
public void setRedirectURI(String redirectURI) {
this.redirectURI = redirectURI;
}
}
|
package org.pcap4j.packet;
import static org.pcap4j.util.ByteArrays.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.pcap4j.packet.factory.PacketFactories;
import org.pcap4j.packet.namednumber.EtherType;
import org.pcap4j.util.ByteArrays;
import org.pcap4j.util.MacAddress;
/**
* This Class handles from DA to data.
* Both preamble, SFD, and FCS are not contained.
*
* @author Kaito Yamada
* @since pcap4j 0.9.1
*/
public final class EthernetPacket extends AbstractPacket {
private static final long serialVersionUID = 3461432646404254300L;
private static final int MIN_ETHERNET_PAYLOAD_LENGTH = 46; // [bytes]
//private static final int MAX_ETHERNET_PAYLOAD_LENGTH = 1500; // [bytes]
private final EthernetHeader header;
private final Packet payload;
// Ethernet frame must be at least 60 bytes except FCS.
// If it's less than 60 bytes, it's padded with this field.
// Although this class handles pad, it's actually responsibility of NIF.
private final byte[] pad;
public static EthernetPacket newPacket(
byte[] rawData, int offset, int length
) throws IllegalRawDataException {
ByteArrays.validateBounds(rawData, offset, length);
return new EthernetPacket(rawData, offset, length);
}
private EthernetPacket(byte[] rawData, int offset, int length) throws IllegalRawDataException {
this.header = new EthernetHeader(rawData, offset, length);
int payloadAndPadLength = length - header.length();
if (payloadAndPadLength > 0) {
int payloadOffset = offset + header.length();
this.payload
= PacketFactories.getFactory(Packet.class, EtherType.class)
.newInstance(rawData, payloadOffset, payloadAndPadLength, header.getType());
int padLength = payloadAndPadLength - payload.length();
if (padLength > 0) {
this.pad
= ByteArrays.getSubArray(
rawData, payloadOffset + payload.length(), padLength
);
}
else {
this.pad = new byte[0];
}
}
else {
this.payload = null;
this.pad = new byte[0];
}
}
private EthernetPacket(Builder builder) {
if (
builder == null
|| builder.dstAddr == null
|| builder.srcAddr == null
|| builder.type == null
) {
StringBuilder sb = new StringBuilder();
sb.append("builder: ").append(builder)
.append(" builder.dstAddr: ").append(builder.dstAddr)
.append(" builder.srcAddr: ").append(builder.srcAddr)
.append(" builder.type: ").append(builder.type);
throw new NullPointerException(sb.toString());
}
if (!builder.paddingAtBuild && builder.pad == null) {
throw new NullPointerException(
"builder.pad must not be null"
+ " if builder.paddingAtBuild is false"
);
}
this.payload = builder.payloadBuilder != null ? builder.payloadBuilder.build() : null;
this.header = new EthernetHeader(builder);
int payloadLength = payload != null ? payload.length() : 0;
if (builder.paddingAtBuild) {
if (payloadLength < MIN_ETHERNET_PAYLOAD_LENGTH) {
this.pad = new byte[MIN_ETHERNET_PAYLOAD_LENGTH - payloadLength];
}
else {
this.pad = new byte[0];
}
}
else {
this.pad = new byte[builder.pad.length];
System.arraycopy(
builder.pad, 0, this.pad, 0, builder.pad.length
);
}
}
@Override
public EthernetHeader getHeader() {
return header;
}
@Override
public Packet getPayload() {
return payload;
}
/**
*
* @return pad
*/
public byte[] getPad() {
byte[] copy = new byte[pad.length];
System.arraycopy(pad, 0, copy, 0, pad.length);
return copy;
}
@Override
protected int calcLength() {
int length = super.calcLength();
length += pad.length;
return length;
}
@Override
protected byte[] buildRawData() {
byte[] rawData = super.buildRawData();
if (pad.length != 0) {
System.arraycopy(
pad, 0, rawData, rawData.length - pad.length, pad.length
);
}
return rawData;
}
@Override
protected String buildString() {
StringBuilder sb = new StringBuilder();
sb.append(header.toString());
if (payload != null) {
sb.append(payload.toString());
}
if (pad.length != 0) {
String ls = System.getProperty("line.separator");
sb.append("[Ethernet Pad (")
.append(pad.length)
.append(" bytes)]")
.append(ls)
.append(" Hex stream: ")
.append(ByteArrays.toHexString(pad, " "))
.append(ls);
}
return sb.toString();
}
@Override
public Builder getBuilder() {
return new Builder(this);
}
@Override
public boolean equals(Object obj) {
if (super.equals(obj)) {
EthernetPacket other = (EthernetPacket)obj;
return Arrays.equals(pad, other.pad);
}
else {
return false;
}
}
@Override
protected int calcHashCode() {
return 31 * super.calcHashCode() + Arrays.hashCode(pad);
}
/**
* @author Kaito Yamada
* @since pcap4j 0.9.1
*/
public static final class Builder extends AbstractBuilder {
private MacAddress dstAddr;
private MacAddress srcAddr;
private EtherType type;
private Packet.Builder payloadBuilder;
private byte[] pad;
private boolean paddingAtBuild;
public Builder() {}
private Builder(EthernetPacket packet) {
this.dstAddr = packet.header.dstAddr;
this.srcAddr = packet.header.srcAddr;
this.type = packet.header.type;
this.payloadBuilder = packet.payload != null ? packet.payload.getBuilder() : null;
this.pad = packet.pad;
}
/**
*
* @param dstAddr
* @return this Builder object for method chaining.
*/
public Builder dstAddr(MacAddress dstAddr) {
this.dstAddr = dstAddr;
return this;
}
/**
*
* @param srcAddr
* @return this Builder object for method chaining.
*/
public Builder srcAddr(MacAddress srcAddr) {
this.srcAddr = srcAddr;
return this;
}
/**
*
* @param type
* @return this Builder object for method chaining.
*/
public Builder type(EtherType type) {
this.type = type;
return this;
}
@Override
public Builder payloadBuilder(Packet.Builder payloadBuilder) {
this.payloadBuilder = payloadBuilder;
return this;
}
@Override
public Packet.Builder getPayloadBuilder() {
return payloadBuilder;
}
/**
*
* @param pad
* @return this Builder object for method chaining.
*/
public Builder pad(byte[] pad) {
this.pad = pad;
return this;
}
/**
*
* @param paddingAtBuild
* @return this Builder object for method chaining.
*/
public Builder paddingAtBuild(boolean paddingAtBuild) {
this.paddingAtBuild = paddingAtBuild;
return this;
}
@Override
public EthernetPacket build() {
return new EthernetPacket(this);
}
}
/**
* @author Kaito Yamada
* @since pcap4j 0.9.1
*/
public static final class EthernetHeader extends AbstractHeader {
/*
* 0 15
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Dst Hardware Address |
* + +
* | |
* + +
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Src Hardware Address |
* + +
* | |
* + +
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
private static final long serialVersionUID = -8271269099161190389L;
private static final int DST_ADDR_OFFSET = 0;
private static final int DST_ADDR_SIZE = MacAddress.SIZE_IN_BYTES;
private static final int SRC_ADDR_OFFSET = DST_ADDR_OFFSET + DST_ADDR_SIZE;
private static final int SRC_ADDR_SIZE = MacAddress.SIZE_IN_BYTES;
private static final int TYPE_OFFSET = SRC_ADDR_OFFSET + SRC_ADDR_SIZE;
private static final int TYPE_SIZE = SHORT_SIZE_IN_BYTES;
private static final int ETHERNET_HEADER_SIZE = TYPE_OFFSET + TYPE_SIZE;
private final MacAddress dstAddr;
private final MacAddress srcAddr;
private final EtherType type;
private EthernetHeader(byte[] rawData, int offset, int length) throws IllegalRawDataException {
if (length < ETHERNET_HEADER_SIZE) {
StringBuilder sb = new StringBuilder(100);
sb.append("The data is too short to build an Ethernet header(")
.append(ETHERNET_HEADER_SIZE)
.append(" bytes). data: ")
.append(ByteArrays.toHexString(rawData, " "))
.append(", offset: ")
.append(offset)
.append(", length: ")
.append(length);
throw new IllegalRawDataException(sb.toString());
}
this.dstAddr = ByteArrays.getMacAddress(rawData, DST_ADDR_OFFSET + offset);
this.srcAddr = ByteArrays.getMacAddress(rawData, SRC_ADDR_OFFSET + offset);
this.type = EtherType.getInstance(ByteArrays.getShort(rawData, TYPE_OFFSET + offset));
}
private EthernetHeader(Builder builder) {
this.dstAddr = builder.dstAddr;
this.srcAddr = builder.srcAddr;
this.type = builder.type;
}
/**
*
* @return dstAddr
*/
public MacAddress getDstAddr() {
return dstAddr;
}
/**
*
* @return srcAddr
*/
public MacAddress getSrcAddr() {
return srcAddr;
}
/**
*
* @return type
*/
public EtherType getType() {
return type;
}
@Override
protected List<byte[]> getRawFields() {
List<byte[]> rawFields = new ArrayList<byte[]>();
rawFields.add(ByteArrays.toByteArray(dstAddr));
rawFields.add(ByteArrays.toByteArray(srcAddr));
rawFields.add(ByteArrays.toByteArray(type.value()));
return rawFields;
}
@Override
public int length() {
return ETHERNET_HEADER_SIZE;
}
@Override
protected String buildString() {
StringBuilder sb = new StringBuilder();
String ls = System.getProperty("line.separator");
sb.append("[Ethernet Header (")
.append(length())
.append(" bytes)]")
.append(ls);
sb.append(" Destination address: ")
.append(dstAddr)
.append(ls);
sb.append(" Source address: ")
.append(srcAddr)
.append(ls);
sb.append(" Type: ")
.append(type)
.append(ls);
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (obj == this) { return true; }
if (!this.getClass().isInstance(obj)) { return false; }
EthernetHeader other = (EthernetHeader)obj;
return
dstAddr.equals(other.dstAddr)
&& srcAddr.equals(other.srcAddr)
&& type.equals(other.type);
}
@Override
protected int calcHashCode() {
int result = 17;
result = 31 * result + dstAddr.hashCode();
result = 31 * result + srcAddr.hashCode();
result = 31 * result + type.hashCode();
return result;
}
}
}
|
package org.devgateway.ocds.web.rest.controller;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.apache.commons.lang3.ArrayUtils;
import org.devgateway.ocds.persistence.mongo.Award;
import org.devgateway.ocds.persistence.mongo.Tender;
import org.devgateway.ocds.persistence.mongo.constants.MongoConstants;
import org.devgateway.ocds.web.rest.controller.request.DefaultFilterPagingRequest;
import org.devgateway.ocds.web.rest.controller.request.GroupingFilterPagingRequest;
import org.devgateway.ocds.web.rest.controller.request.YearFilterPagingRequest;
import org.devgateway.toolkit.persistence.mongo.aggregate.CustomSortingOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.Fields;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.aggregation.ProjectionOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.TextCriteria;
import org.springframework.util.ObjectUtils;
import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.FLAGS_TOTAL_FLAGGED;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.query.Criteria.where;
/**
* @author mpostelnicu
*/
public abstract class GenericOCDSController {
private static final int LAST_MONTH_ZERO = 11;
public static final int BIGDECIMAL_SCALE = 15;
public static final int DAY_MS = 86400000;
public static final BigDecimal ONE_HUNDRED = new BigDecimal(100);
protected Map<String, Object> filterProjectMap;
protected final Logger logger = LoggerFactory.getLogger(GenericOCDSController.class);
@Autowired
protected MongoTemplate mongoTemplate;
/**
* Gets the date of the first day of the year (01.01.year)
*
* @param year
* @return
*/
protected Date getStartDate(final int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_YEAR, 1);
Date start = cal.getTime();
return start;
}
protected <Z> List<Z> releaseAgg(Aggregation agg, AggregationOptions options, Class<Z> clazz) {
return mongoTemplate.aggregate(agg.withOptions(options), "release", clazz)
.getMappedResults();
}
protected List<DBObject> releaseAgg(Aggregation agg) {
return releaseAgg(agg, DBObject.class);
}
protected List<DBObject> releaseAgg(Aggregation agg, AggregationOptions options) {
return releaseAgg(agg, options, DBObject.class);
}
protected <Z> List<Z> releaseAgg(Aggregation agg, Class<Z> clazz) {
return releaseAgg(agg, Aggregation.newAggregationOptions().allowDiskUse(true).build(), clazz);
}
/**
* Creates a mongo $cond that calculates percentage of expression1/expression2.
* Checks for division by zero.
*
* @param expression1
* @param expression2
* @return
*/
protected DBObject getPercentageMongoOp(String expression1, String expression2) {
return new BasicDBObject(
"$cond",
Arrays.asList(new BasicDBObject("$eq", Arrays.asList(
ref(expression2),
0
)), new BasicDBObject("$literal", 0),
new BasicDBObject(
"$multiply",
Arrays.asList(new BasicDBObject(
"$divide",
Arrays.asList(
ref(expression1),
ref(expression2)
)
), 100)
)
)
);
}
/**
* This is used to build the start date filter query when a monthly filter is used.
*
* @param year
* @param month
* @return
*/
protected Date getMonthStartDate(final int year, final int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date start = cal.getTime();
return start;
}
/**
* This is used to build the end date filter query when a monthly filter is used.
*
* @param year
* @param month
* @return
*/
protected Date getMonthEndDate(final int year, final int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
Date end = cal.getTime();
return end;
}
/**
* Gets the date of the last date of the year (31.12.year)
*
* @param year
* @return
*/
protected Date getEndDate(final int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, LAST_MONTH_ZERO);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
Date end = cal.getTime();
return end;
}
protected String ref(String field) {
return "$" + field;
}
/**
* Appends the procuring bid type id for this filter, this will fitler based
* on tender.items.classification._id
*
* @param filter
* @return the {@link Criteria} for this filter
*/
protected Criteria getBidTypeIdFilterCriteria(final DefaultFilterPagingRequest filter) {
return createFilterCriteria("tender.items.classification._id", filter.getBidTypeId(), filter);
}
protected Criteria getTotalFlaggedCriteria(final DefaultFilterPagingRequest filter) {
return createFilterCriteria(FLAGS_TOTAL_FLAGGED, filter.getTotalFlagged(), filter);
}
/**
* Appends flags.flaggedStats.type filter
*/
protected Criteria getFlagTypeFilterCriteria(final DefaultFilterPagingRequest filter) {
return createFilterCriteria("flags.flaggedStats.type", filter.getFlagType(), filter);
}
protected Criteria getAwardStatusFilterCriteria(final DefaultFilterPagingRequest filter) {
return createFilterCriteria(MongoConstants.FieldNames.AWARDS_STATUS, filter.getAwardStatus(), filter);
}
/**
* Adds monthly projection operation, when needed, if the
* {@link YearFilterPagingRequest#getMonthly()}
*
* @param filter
* @param project
* @param field
*/
protected void addYearlyMonthlyProjection(YearFilterPagingRequest filter, DBObject project, String field) {
project.put("year", new BasicDBObject("$year", field));
if (filter.getMonthly()) {
project.put(("month"), new BasicDBObject("$month", field));
}
}
protected CustomSortingOperation getSortByYearMonth(YearFilterPagingRequest filter) {
DBObject sort = new BasicDBObject();
if (filter.getMonthly()) {
sort.put("_id.year", 1);
sort.put("_id.month", 1);
} else {
sort.put("year", 1);
}
return new CustomSortingOperation(sort);
}
/**
* Similar to {@link #getSortByYearMonth(YearFilterPagingRequest)} but it can be used
* if additional grouping elements are present, besides month and year
*
* @param filter
* @return
*/
protected CustomSortingOperation getSortByYearMonthWhenOtherGroups(YearFilterPagingRequest filter,
String... otherSort) {
DBObject sort = new BasicDBObject();
if (filter.getMonthly()) {
sort.put("_id.year", 1);
sort.put("_id.month", 1);
} else {
sort.put("_id.year", 1);
}
if (otherSort != null) {
Arrays.asList(otherSort).forEach(s -> sort.put(s, 1));
}
return new CustomSortingOperation(sort);
}
protected void addYearlyMonthlyReferenceToGroup(YearFilterPagingRequest filter, DBObject group) {
if (filter.getMonthly()) {
group.put(Fields.UNDERSCORE_ID, new BasicDBObject("year", "$year").append("month", "$month"));
} else {
group.put(Fields.UNDERSCORE_ID, "$year");
}
}
/**
* Returns the grouping fields based on the {@link YearFilterPagingRequest#getMonthly()} setting
*
* @param filter
* @return
*/
protected String[] getYearlyMonthlyGroupingFields(YearFilterPagingRequest filter) {
if (filter.getMonthly()) {
return new String[]{"$year", "$month"};
} else {
return new String[]{"$year"};
}
}
/**
* @param filter
* @param extraGroups adds extra groups
* @return
* @see #getYearlyMonthlyGroupingFields(YearFilterPagingRequest)
*/
protected String[] getYearlyMonthlyGroupingFields(YearFilterPagingRequest filter, String... extraGroups) {
return ArrayUtils.addAll(getYearlyMonthlyGroupingFields(filter), extraGroups);
}
protected GroupOperation getYearlyMonthlyGroupingOperation(YearFilterPagingRequest filter) {
return group(getYearlyMonthlyGroupingFields(filter));
}
protected ProjectionOperation transformYearlyGrouping(YearFilterPagingRequest filter) {
if (filter.getMonthly()) {
return project();
} else {
return project(Fields.from(
Fields.field("year", org.springframework.data
.mongodb.core.aggregation.Fields.UNDERSCORE_ID_REF)))
.andExclude(Fields.UNDERSCORE_ID);
}
}
protected void addYearlyMonthlyGroupingOperationFirst(YearFilterPagingRequest filter, DBObject group) {
group.put("year", new BasicDBObject("$first", "$year"));
if (filter.getMonthly()) {
group.put("month", new BasicDBObject("$first", "$month"));
}
}
protected Criteria getNotBidTypeIdFilterCriteria(final DefaultFilterPagingRequest filter) {
return createNotFilterCriteria("tender.items.classification._id", filter.getNotBidTypeId(), filter);
}
/**
* Appends the tender.items.deliveryLocation._id
*
* @param filter
* @return the {@link Criteria} for this filter
*/
protected Criteria getByTenderDeliveryLocationIdentifier(final DefaultFilterPagingRequest filter) {
return createFilterCriteria("tender.items.deliveryLocation._id",
filter.getTenderLoc(), filter
);
}
/**
* Creates a search criteria filter based on tender.value.amount and uses
* {@link DefaultFilterPagingRequest#getMinTenderValue()} and
* {@link DefaultFilterPagingRequest#getMaxTenderValue()} to create
* interval search
*
* @param filter
* @return
*/
protected Criteria getByTenderAmountIntervalCriteria(final DefaultFilterPagingRequest filter) {
if (filter.getMaxTenderValue() == null && filter.getMinTenderValue() == null) {
return new Criteria();
}
Criteria criteria = where(MongoConstants.FieldNames.TENDER_VALUE_AMOUNT);
if (filter.getMinTenderValue() != null) {
criteria = criteria.gte(filter.getMinTenderValue().doubleValue());
}
if (filter.getMaxTenderValue() != null) {
criteria = criteria.lte(filter.getMaxTenderValue().doubleValue());
}
return criteria;
}
/**
* Creates a search criteria filter based on awards.value.amount and uses
* {@link DefaultFilterPagingRequest#getMinAwardValue()} and
* {@link DefaultFilterPagingRequest#getMaxAwardValue()} to create
* interval search
*
* @param filter
* @return
*/
protected Criteria getByAwardAmountIntervalCriteria(final DefaultFilterPagingRequest filter) {
if (filter.getMaxAwardValue() == null && filter.getMinAwardValue() == null) {
return new Criteria();
}
Criteria elem = where("value.amount");
if (filter.getMinAwardValue() != null) {
elem = elem.gte(filter.getMinAwardValue().doubleValue());
}
if (filter.getMaxAwardValue() != null) {
elem = elem.lte(filter.getMaxAwardValue().doubleValue());
}
return where("awards").elemMatch(elem);
}
private <S> Criteria createFilterCriteria(final String filterName, final Set<S> filterValues,
final DefaultFilterPagingRequest filter) {
if (filterValues == null) {
return new Criteria();
}
return where(filterName).in(filterValues.toArray());
}
private <S> Criteria createNotFilterCriteria(final String filterName, final Set<S> filterValues,
final DefaultFilterPagingRequest filter) {
if (filterValues == null) {
return new Criteria();
}
return where(filterName).not().in(filterValues.toArray());
}
/**
* Appends the procuring entity id for this filter, this will fitler based
* on tender.procuringEntity._id
*
* @param filter
* @return the {@link Criteria} for this filter
*/
protected Criteria getProcuringEntityIdCriteria(final DefaultFilterPagingRequest filter) {
return createFilterCriteria(
MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID, filter.getProcuringEntityId(), filter);
}
protected CriteriaDefinition getTextCriteria(DefaultFilterPagingRequest filter) {
if (ObjectUtils.isEmpty(filter.getText()) || filter.getAwardFiltering()) {
return new Criteria();
} else {
return TextCriteria.forLanguage(MongoConstants.MONGO_LANGUAGE).matchingAny(filter.getText());
}
}
/**
* Adds the filter by electronic submission criteria for tender.submissionMethod.
*
* @param filter
* @return
*/
protected Criteria getElectronicSubmissionCriteria(final DefaultFilterPagingRequest filter) {
if (filter.getElectronicSubmission() != null && filter.getElectronicSubmission()) {
return where(MongoConstants.FieldNames.TENDER_SUBMISSION_METHOD).is(
Tender.SubmissionMethod.electronicSubmission.toString());
}
return new Criteria();
}
/**
* Add the filter by flagged
*
* @param filter
* @return
*/
protected Criteria getFlaggedCriteria(final DefaultFilterPagingRequest filter) {
if (filter.getFlagged() != null && filter.getFlagged()) {
return where("flags.flaggedStats.0").exists(true);
}
return new Criteria();
}
protected Criteria getNotProcuringEntityIdCriteria(final DefaultFilterPagingRequest filter) {
return createNotFilterCriteria(
MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID, filter.getNotProcuringEntityId(), filter);
}
/**
* Appends the supplier entity id for this filter, this will fitler based
* on tender.procuringEntity._id
*
* @param filter
* @return the {@link Criteria} for this filter
*/
protected Criteria getSupplierIdCriteria(final DefaultFilterPagingRequest filter) {
if (filter.getAwardFiltering()) {
return createFilterCriteria(MongoConstants.FieldNames.AWARDS_SUPPLIERS_ID, filter.getSupplierId(), filter);
}
if (filter.getSupplierId() == null) {
return new Criteria();
}
return where("awards").elemMatch(
where("status").is(Award.Status.active.toString()).and("suppliers._id").in(filter.getSupplierId()));
}
protected Criteria getBidderIdCriteria(final DefaultFilterPagingRequest filter) {
return createFilterCriteria("bids.details.tenderers._id", filter.getBidderId(), filter);
}
/**
* Appends the procurement method for this filter, this will fitler based
* on tender.procurementMethod
*
* @param filter
* @return the {@link Criteria} for this filter
*/
protected Criteria getProcurementMethodCriteria(final DefaultFilterPagingRequest filter) {
return createFilterCriteria(
MongoConstants.FieldNames.TENDER_PROC_METHOD, filter.getProcurementMethod(), filter);
}
@PostConstruct
protected void init() {
Map<String, Object> tmpMap = new HashMap<>();
tmpMap.put(MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID, 1);
tmpMap.put(MongoConstants.FieldNames.TENDER_PROC_METHOD, 1);
tmpMap.put(MongoConstants.FieldNames.TENDER_SUBMISSION_METHOD, 1);
tmpMap.put(MongoConstants.FieldNames.AWARDS_SUPPLIERS_ID, 1);
tmpMap.put("tender.items.classification._id", 1);
tmpMap.put("tender.items.deliveryLocation._id", 1);
tmpMap.put(MongoConstants.FieldNames.TENDER_VALUE_AMOUNT, 1);
tmpMap.put(MongoConstants.FieldNames.AWARDS_VALUE_AMOUNT, 1);
filterProjectMap = Collections.unmodifiableMap(tmpMap);
}
protected Criteria getYearFilterCriteria(final YearFilterPagingRequest filter, final String dateProperty) {
Criteria[] yearCriteria = null;
Criteria criteria = new Criteria();
if (filter.getYear() == null) {
yearCriteria = new Criteria[1];
yearCriteria[0] = new Criteria();
} else {
yearCriteria = new Criteria[filter.getYear().size()];
Integer[] yearArray = filter.getYear().toArray(new Integer[0]);
for (int i = 0; i < yearArray.length; i++) {
yearCriteria[i] = where(dateProperty).gte(getStartDate(yearArray[i]))
.lte(getEndDate(yearArray[i]));
}
criteria = criteria.orOperator(yearCriteria);
if (filter.getMonth() != null && filter.getYear().size() == 1) {
Integer[] monthArray = filter.getMonth().toArray(new Integer[0]);
criteria = new Criteria(); //we reset the criteria because we use only one year
Criteria[] monthCriteria = new Criteria[filter.getMonth().size()];
for (int i = 0; i < monthArray.length; i++) {
monthCriteria[i] = where(dateProperty).gte(getMonthStartDate(
yearArray[0],
monthArray[i]
))
.lte(getMonthEndDate(
yearArray[0],
monthArray[i]
));
}
criteria = criteria.orOperator(monthCriteria);
}
}
// logger.info("Criteria=" + criteria.getCriteriaObject());
return criteria;
}
protected Map<String, CriteriaDefinition> createDefaultFilterCriteriaMap(final DefaultFilterPagingRequest filter) {
HashMap<String, CriteriaDefinition> map = new HashMap<>();
map.put(MongoConstants.Filters.BID_TYPE_ID, getBidTypeIdFilterCriteria(filter));
map.put(MongoConstants.Filters.NOT_BID_TYPE_ID, getNotBidTypeIdFilterCriteria(filter));
map.put(MongoConstants.Filters.PROCURING_ENTITY_ID, getProcuringEntityIdCriteria(filter));
map.put(MongoConstants.Filters.NOT_PROCURING_ENTITY_ID, getNotProcuringEntityIdCriteria(filter));
map.put(MongoConstants.Filters.SUPPLIER_ID, getSupplierIdCriteria(filter));
map.put(MongoConstants.Filters.PROCUREMENT_METHOD, getProcurementMethodCriteria(filter));
map.put(MongoConstants.Filters.TENDER_LOC, getByTenderDeliveryLocationIdentifier(filter));
map.put(MongoConstants.Filters.TENDER_VALUE, getByTenderAmountIntervalCriteria(filter));
map.put(MongoConstants.Filters.AWARD_VALUE, getByAwardAmountIntervalCriteria(filter));
map.put(MongoConstants.Filters.FLAGGED, getFlaggedCriteria(filter));
map.put(MongoConstants.Filters.FLAG_TYPE, getFlagTypeFilterCriteria(filter));
map.put(MongoConstants.Filters.ELECTRONIC_SUBMISSION, getElectronicSubmissionCriteria(filter));
map.put(MongoConstants.Filters.AWARD_STATUS, getAwardStatusFilterCriteria(filter));
map.put(MongoConstants.Filters.BIDDER_ID, getBidderIdCriteria(filter));
map.put(MongoConstants.Filters.TOTAL_FLAGGED, getTotalFlaggedCriteria(filter));
map.put(MongoConstants.Filters.TEXT, getTextCriteria(filter));
return map;
}
/**
* Removes {@link Criteria} objects that were generated empty because they are not needed and they seem to slow
* down the mongodb query engine by a lot.
*
* @param values
* @return
*/
protected CriteriaDefinition[] getEmptyFilteredCriteria(Collection<CriteriaDefinition> values) {
return values.stream().distinct().toArray(CriteriaDefinition[]::new);
}
/**
* We ensure {@link TextCriteria} is always returned first before {@link Criteria}
*
* @param criteria
* @return
* @see Criteria#createCriteriaList(Criteria[])
*/
private BasicDBList createTextSearchFriendlyCriteriaList(CriteriaDefinition[] criteria) {
BasicDBList bsonList = new BasicDBList();
Arrays.stream(criteria).sorted((c1, c2) -> c2.getClass().getSimpleName()
.compareTo(c1.getClass().getSimpleName()))
.map(CriteriaDefinition::getCriteriaObject).collect(Collectors.toCollection(() -> bsonList));
return bsonList;
}
protected Criteria getDefaultFilterCriteria(final DefaultFilterPagingRequest filter,
Map<String, CriteriaDefinition> map) {
return getAndOperatorCriteriaDefinition(map.values());
}
/**
* For some reason the mongodb spring team did not add support for this, probably because the $text
* criteria has some limitations, has to be always first in a list of criteria, etc...
*
* @param criteriaDefinitions
* @return
*/
protected Criteria getAndOperatorCriteriaDefinition(Collection<CriteriaDefinition> criteriaDefinitions) {
return new Criteria("$and").is(createTextSearchFriendlyCriteriaList(getEmptyFilteredCriteria(
criteriaDefinitions)));
}
protected Criteria getDefaultFilterCriteria(final DefaultFilterPagingRequest filter) {
return getDefaultFilterCriteria(filter, createDefaultFilterCriteriaMap(filter));
}
protected Criteria getYearDefaultFilterCriteria(final YearFilterPagingRequest filter, final String dateProperty) {
return getYearDefaultFilterCriteria(filter, createDefaultFilterCriteriaMap(filter), dateProperty);
}
protected Criteria getYearDefaultFilterCriteria(final YearFilterPagingRequest filter,
Map<String, CriteriaDefinition> map,
final String dateProperty) {
map.put(MongoConstants.Filters.YEAR, getYearFilterCriteria(filter, dateProperty));
return getAndOperatorCriteriaDefinition(map.values());
}
protected MatchOperation getMatchDefaultFilterOperation(final DefaultFilterPagingRequest filter) {
return match(getDefaultFilterCriteria(filter));
}
protected MatchOperation getMatchYearDefaultFilterOperation(final YearFilterPagingRequest filter,
final String dateProperty) {
return match(getYearDefaultFilterCriteria(filter, dateProperty));
}
/**
* Creates a groupby expression that takes into account the filter. It will
* only use one of the filter options as groupby and ignores the rest.
*
* @param filter
* @param existingGroupBy
* @return
*/
protected GroupOperation getTopXFilterOperation(final GroupingFilterPagingRequest filter,
final String... existingGroupBy) {
List<String> groupBy = new ArrayList<>();
if (filter.getGroupByCategory() == null) {
groupBy.addAll(Arrays.asList(existingGroupBy));
}
if (filter.getGroupByCategory() != null) {
groupBy.add(getGroupByCategory(filter));
}
return group(groupBy.toArray(new String[0]));
}
private String getGroupByCategory(final GroupingFilterPagingRequest filter) {
if ("bidTypeId".equals(filter.getGroupByCategory())) {
return "tender.items.classification._id".replace(".", "");
} else if ("procuringEntityId".equals(filter.getGroupByCategory())) {
return MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID.replace(".", "");
}
return null;
}
}
|
package com.yahoo.zookeeper.test;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import org.junit.After;
import org.junit.Before;
import com.yahoo.zookeeper.server.ZooLog;
import com.yahoo.zookeeper.server.quorum.QuorumPeer;
import com.yahoo.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import junit.framework.TestCase;
public class QuorumTest extends ClientTest {
static File baseTest = new File(System.getProperty("build.test.dir", "build"));
File s1dir, s2dir, s3dir, s4dir, s5dir;
QuorumPeer s1, s2, s3, s4, s5;
@Before
protected void setUp() throws Exception {
s1dir = File.createTempFile("test", ".junit", baseTest);
s1dir = new File(s1dir + ".dir");
s1dir.mkdirs();
s2dir = File.createTempFile("test", ".junit", baseTest);
s2dir = new File(s2dir + ".dir");
s2dir.mkdirs();
s3dir = File.createTempFile("test", ".junit", baseTest);
s3dir = new File(s3dir + ".dir");
s3dir.mkdirs();
s4dir = File.createTempFile("test", ".junit", baseTest);
s4dir = new File(s4dir + ".dir");
s4dir.mkdirs();
s5dir = File.createTempFile("test", ".junit", baseTest);
s5dir = new File(s5dir + ".dir");
s5dir.mkdirs();
startServers();
ZooLog.logWarn("Setup finished");
}
void startServers() throws IOException, InterruptedException {
int tickTime = 2000;
int initLimit = 3;
int syncLimit = 3;
ArrayList<QuorumServer> peers = new ArrayList<QuorumServer>();
hostPort = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183,127.0.0.1:2184,127.0.0.1:2185";
peers.add(new QuorumServer(1, new InetSocketAddress("127.0.0.1", 3181)));
peers.add(new QuorumServer(2, new InetSocketAddress("127.0.0.1", 3182)));
peers.add(new QuorumServer(3, new InetSocketAddress("127.0.0.1", 3183)));
peers.add(new QuorumServer(4, new InetSocketAddress("127.0.0.1", 3184)));
peers.add(new QuorumServer(5, new InetSocketAddress("127.0.0.1", 3185)));
ZooLog.logWarn("creating QuorumPeer 1");
s1 = new QuorumPeer(peers, s1dir, s1dir, 2181, 0, 1, tickTime, initLimit, syncLimit);
ZooLog.logWarn("creating QuorumPeer 2");
s2 = new QuorumPeer(peers, s2dir, s2dir, 2182, 0, 2, tickTime, initLimit, syncLimit);
ZooLog.logWarn("creating QuorumPeer 3");
s3 = new QuorumPeer(peers, s3dir, s3dir, 2183, 0, 3, tickTime, initLimit, syncLimit);
ZooLog.logWarn("creating QuorumPeer 4");
s4 = new QuorumPeer(peers, s4dir, s4dir, 2184, 0, 4, tickTime, initLimit, syncLimit);
ZooLog.logWarn("creating QuorumPeer 5");
s5 = new QuorumPeer(peers, s5dir, s5dir, 2185, 0, 5, tickTime, initLimit, syncLimit);
ZooLog.logWarn("start QuorumPeer 1");
s1.start();
ZooLog.logWarn("start QuorumPeer 2");
s2.start();
ZooLog.logWarn("start QuorumPeer 3");
s3.start();
ZooLog.logWarn("start QuorumPeer 4");
s4.start();
ZooLog.logWarn("start QuorumPeer 5");
s5.start();
ZooLog.logWarn("started QuorumPeer 5");
Thread.sleep(5000);
}
@After
protected void tearDown() throws Exception {
ZooLog.logWarn("TearDown started");
s1.shutdown();
s2.shutdown();
s3.shutdown();
s4.shutdown();
s5.shutdown();
Thread.sleep(5000);
}
}
|
package com.karambit.bookie.helper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.karambit.bookie.model.Message;
import com.karambit.bookie.model.User;
import java.util.ArrayList;
import java.util.Calendar;
public class DBHandler extends SQLiteOpenHelper {
public static final String TAG = DBHandler.class.getSimpleName();
private static final String DATABASE_NAME = "Bookie.db";
private static final String USER_TABLE_NAME = "user";
private static final String USER_COLUMN_ID = "id";
private static final String USER_COLUMN_NAME = "name";
private static final String USER_COLUMN_IMAGE_URL = "image_url";
private static final String USER_COLUMN_THUMBNAIL_URL = "thumbnail_url";
private static final String USER_COLUMN_LATITUDE = "latitude";
private static final String USER_COLUMN_LONGITUDE = "longitude";
private static final String USER_COLUMN_PASSWORD = "password";
private static final String USER_COLUMN_EMAIL = "email";
private static final String USER_COLUMN_VERIFIED = "verified";
private static final String USER_COLUMN_BIO = "bio";
private static final String USER_COLUMN_BOOK_COUNTER = "book_counter";
private static final String USER_COLUMN_POINT = "point";
private static final String LG_TABLE_NAME = "loved_genre";
private static final String LG_COLUMN_ID = "loved_genre_id";
private static final String LG_COLUMN_USER_ID = "user_id";
private static final String LG_COLUMN_GENRE_CODE = "genre_code";
private static final String MESSAGE_TABLE_NAME = "message";
private static final String MESSAGE_COLUMN_ID = "message_id";
private static final String MESSAGE_COLUMN_TEXT = "text";
private static final String MESSAGE_COLUMN_FROM_USER_ID = "from_user_id";
private static final String MESSAGE_COLUMN_TO_USER_ID = "to_user_id";
private static final String MESSAGE_COLUMN_IS_DELETED = "is_deleted";
private static final String MESSAGE_COLUMN_STATE = "state";
private static final String MESSAGE_COLUMN_CREATED_AT = "created_at";
private static final String MESSAGE_USER_TABLE_NAME = "message_user";
private static final String MESSAGE_USER_COLUMN_ID = "user_id";
private static final String MESSAGE_USER_COLUMN_NAME = "name";
private static final String MESSAGE_USER_COLUMN_IMAGE_URL = "image_url";
private static final String MESSAGE_USER_COLUMN_THUMBNAIL_URL = "thumbnail_url";
private static final String MESSAGE_USER_COLUMN_LATITUDE = "latitude";
private static final String MESSAGE_USER_COLUMN_LONGITUDE = "longitude";
private final Context mContext;
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"CREATE TABLE " + USER_TABLE_NAME + " (" +
USER_COLUMN_ID + " INTEGER PRIMERY KEY, " +
USER_COLUMN_NAME + " TEXT NOT NULL, " +
USER_COLUMN_IMAGE_URL + " TEXT, " +
USER_COLUMN_THUMBNAIL_URL + " TEXT, " +
USER_COLUMN_LATITUDE + " DOUBLE, " +
USER_COLUMN_LONGITUDE + " DOUBLE, " +
USER_COLUMN_PASSWORD + " TEXT NOT NULL, " +
USER_COLUMN_EMAIL + " TEXT NOT NULL, " +
USER_COLUMN_VERIFIED + " BIT NOT NULL, " +
USER_COLUMN_BIO + " TEXT, " +
USER_COLUMN_BOOK_COUNTER + " INTEGER NOT NULL, " +
USER_COLUMN_POINT + " INTEGER NOT NULL)"
);
db.execSQL(
"CREATE TABLE " + LG_TABLE_NAME + " (" +
LG_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
LG_COLUMN_USER_ID + " INTEGER NOT NULL, " +
LG_COLUMN_GENRE_CODE + " INTEGER NOT NULL)"
);
db.execSQL(
"CREATE TABLE " + MESSAGE_TABLE_NAME + " (" +
MESSAGE_COLUMN_ID + " INTEGER PRIMARY KEY NOT NULL, " +
MESSAGE_COLUMN_TEXT + " TEXT NOT NULL, " +
MESSAGE_COLUMN_FROM_USER_ID + " INTEGER NOT NULL, " +
MESSAGE_COLUMN_TO_USER_ID + " INTEGER NOT NULL, " +
MESSAGE_COLUMN_IS_DELETED + " INTEGER NOT NULL DEFAULT 0, " +
MESSAGE_COLUMN_STATE + " INTEGER NOT NULL, " +
MESSAGE_COLUMN_CREATED_AT + " LONG NOT NULL)"
);
db.execSQL(
"CREATE TABLE " + MESSAGE_USER_TABLE_NAME + " (" +
MESSAGE_USER_COLUMN_ID + " INTEGER PRIMARY KEY NOT NULL, " +
MESSAGE_USER_COLUMN_NAME + " TEXT NOT NULL, " +
MESSAGE_USER_COLUMN_IMAGE_URL + " TEXT, " +
MESSAGE_USER_COLUMN_THUMBNAIL_URL + " TEXT, " +
MESSAGE_USER_COLUMN_LATITUDE + " DOUBLE, " +
MESSAGE_USER_COLUMN_LONGITUDE + " DOUBLE)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + LG_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + MESSAGE_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + MESSAGE_USER_TABLE_NAME);
onCreate(db);
}
public boolean insertCurrentUser(int id, String name, String imageURL, String thumbnailURL, double latitude, double longitude,
String password, String email, boolean verified, String bio, int bookCounter, int point) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(USER_COLUMN_ID, id);
contentValues.put(USER_COLUMN_NAME, name);
contentValues.put(USER_COLUMN_IMAGE_URL, imageURL);
contentValues.put(USER_COLUMN_THUMBNAIL_URL, thumbnailURL);
contentValues.put(USER_COLUMN_LATITUDE, latitude);
contentValues.put(USER_COLUMN_LONGITUDE, longitude);
contentValues.put(USER_COLUMN_PASSWORD, password);
contentValues.put(USER_COLUMN_EMAIL, email);
contentValues.put(USER_COLUMN_VERIFIED, verified);
contentValues.put(USER_COLUMN_BIO, bio);
contentValues.put(USER_COLUMN_BOOK_COUNTER, bookCounter);
contentValues.put(USER_COLUMN_POINT, point);
boolean result = db.insert(USER_TABLE_NAME, null, contentValues) > 0;
if (db.isOpen()){
db.close();
}
if (result) {
return true;
} else {
return false;
}
}
public boolean insertCurrentUser(User.Details user) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
ContentValues contentValues = new ContentValues();
contentValues.put(USER_COLUMN_ID, user.getUser().getID());
contentValues.put(USER_COLUMN_NAME, user.getUser().getName());
contentValues.put(USER_COLUMN_IMAGE_URL, user.getUser().getImageUrl());
contentValues.put(USER_COLUMN_THUMBNAIL_URL, user.getUser().getThumbnailUrl());
contentValues.put(USER_COLUMN_LATITUDE, user.getUser().getLatitude());
contentValues.put(USER_COLUMN_LONGITUDE, user.getUser().getLongitude());
contentValues.put(USER_COLUMN_PASSWORD, user.getPassword());
contentValues.put(USER_COLUMN_EMAIL, user.getEmail());
contentValues.put(USER_COLUMN_VERIFIED, user.isVerified());
contentValues.put(USER_COLUMN_BIO, user.getBio());
contentValues.put(USER_COLUMN_BOOK_COUNTER, user.getBookCounter());
contentValues.put(USER_COLUMN_POINT, user.getPoint());
boolean result = db.insert(USER_TABLE_NAME, null, contentValues) > 0;
db.setTransactionSuccessful();
db.endTransaction();
if (db.isOpen()){
db.close();
}
if (result) {
return true;
} else {
return false;
}
}
public User getCurrentUser() {
SQLiteDatabase db = this.getReadableDatabase();
db.beginTransaction();
Cursor res = db.rawQuery("SELECT * FROM " + USER_TABLE_NAME, null);
res.moveToFirst();
User user = new User(res.getInt(res.getColumnIndex(USER_COLUMN_ID)),
res.getString(res.getColumnIndex(USER_COLUMN_NAME)),
res.getString(res.getColumnIndex(USER_COLUMN_IMAGE_URL)),
res.getString(res.getColumnIndex(USER_COLUMN_THUMBNAIL_URL)),
res.getDouble(res.getColumnIndex(USER_COLUMN_LATITUDE)),
res.getDouble(res.getColumnIndex(USER_COLUMN_LONGITUDE)));
res.close();
db.setTransactionSuccessful();
db.endTransaction();
if (db.isOpen()){
db.close();
}
return user;
}
public User.Details getCurrentUserDetails() {
SQLiteDatabase db = this.getReadableDatabase();
db.beginTransaction();
Cursor res = db.rawQuery("SELECT * FROM " + USER_TABLE_NAME, null);
res.moveToFirst();
User user = new User(res.getInt(res.getColumnIndex(USER_COLUMN_ID)),
res.getString(res.getColumnIndex(USER_COLUMN_NAME)),
res.getString(res.getColumnIndex(USER_COLUMN_IMAGE_URL)),
res.getString(res.getColumnIndex(USER_COLUMN_THUMBNAIL_URL)),
res.getDouble(res.getColumnIndex(USER_COLUMN_LATITUDE)),
res.getDouble(res.getColumnIndex(USER_COLUMN_LONGITUDE)));
User.Details details = user.new Details(res.getString(res.getColumnIndex(USER_COLUMN_PASSWORD)),
res.getString(res.getColumnIndex(USER_COLUMN_EMAIL)),
res.getInt(res.getColumnIndex(USER_COLUMN_VERIFIED)) > 0,
res.getString(res.getColumnIndex(USER_COLUMN_BIO)),
res.getInt(res.getColumnIndex(USER_COLUMN_BOOK_COUNTER)),
res.getInt(res.getColumnIndex(USER_COLUMN_POINT)));
res.close();
db.setTransactionSuccessful();
db.endTransaction();
if (db.isOpen()){
db.close();
}
return details;
}
public void updateCurrentUserLocation(double latitude, double longitude){
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
ContentValues cv = new ContentValues();
cv.put(USER_COLUMN_LATITUDE, latitude);
cv.put(USER_COLUMN_LONGITUDE, longitude);
// getCurrentUser in this class fetch user from database. getCurrentUser in SessionManager fetch user from static User field
db.update(USER_TABLE_NAME, cv, USER_COLUMN_ID + "=" + SessionManager.getCurrentUser(mContext.getApplicationContext()).getID(), null);
db.setTransactionSuccessful();
db.endTransaction();
if (db.isOpen()){
db.close();
}
}
public int deleteCurrentUser() {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
int result = db.delete(USER_TABLE_NAME, null, null);
db.setTransactionSuccessful();
db.endTransaction();
if (db.isOpen()){
db.close();
}
return result;
}
public boolean insertLovedGenres(User user, Integer[] lovedGenreCodes) {
SQLiteDatabase db = this.getWritableDatabase();
// db.beginTransaction();
Cursor cursor = db.rawQuery("SELECT * FROM " + LG_TABLE_NAME +
" WHERE " + LG_COLUMN_USER_ID + " = " + user.getID(), null);
if (cursor.getCount() > 0) {
resetLovedGenres(user);
}
cursor.close();
for (Integer lovedGenreCode : lovedGenreCodes) {
ContentValues contentValues = new ContentValues();
contentValues.put(LG_COLUMN_USER_ID, user.getID());
contentValues.put(LG_COLUMN_GENRE_CODE, lovedGenreCode);
if (db.insert(LG_TABLE_NAME, null, contentValues) <= 0) {
return false;
}
}
// db.setTransactionSuccessful();
// db.endTransaction();
if (db.isOpen()){
db.close();
}
Log.i(TAG, "Loved Genres inserted");
return true;
}
public int[] getLovedGenres(User user) {
SQLiteDatabase db = this.getReadableDatabase();
db.beginTransaction();
Cursor res = db.rawQuery("SELECT * FROM " + LG_TABLE_NAME +
" WHERE " + LG_COLUMN_USER_ID + " = " + user.getID(), null);
res.moveToFirst();
int[] lovedGenres = new int[res.getCount()];
int i = 0;
try {
if (res.getCount() > 0) {
do {
lovedGenres[i++] = res.getInt(res.getColumnIndex(LG_COLUMN_GENRE_CODE));
} while (res.moveToNext());
}
} finally {
res.close();
db.setTransactionSuccessful();
db.endTransaction();
if (db.isOpen()){
db.close();
}
}
return lovedGenres;
}
public Integer[] getLovedGenresAsInt(User user) {
int[] lovedGenres = getLovedGenres(user);
Integer[] selectedGenres = new Integer[lovedGenres.length];
int i = 0;
for (int value : lovedGenres) {
selectedGenres[i++] = value;
}
return selectedGenres;
}
public void resetLovedGenres(User user) {
SQLiteDatabase db = this.getReadableDatabase();
db.beginTransaction();
db.delete(LG_TABLE_NAME, LG_COLUMN_USER_ID + " = " + user.getID(), null);
Log.i(TAG, "Loved Genres reset");
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
public boolean isLovedGenresSelected(User user) {
Cursor cursor = null;
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
String countQuery = "SELECT * FROM " + LG_TABLE_NAME + " WHERE " + LG_COLUMN_USER_ID + " = " + user.getID();
cursor = db.rawQuery(countQuery, null);
return cursor.getCount() > 0;
} finally {
if (cursor != null) {
cursor.close();
}
if (db != null && db.isOpen()) {
db.close();
}
}
}
public boolean insertMessage(Message message) {
SQLiteDatabase db = null;
boolean result = false;
try {
db = this.getWritableDatabase();
db.beginTransaction();
ContentValues contentValues = new ContentValues();
contentValues.put(MESSAGE_COLUMN_TEXT, message.getText());
contentValues.put(MESSAGE_COLUMN_FROM_USER_ID, message.getSender().getID());
contentValues.put(MESSAGE_COLUMN_TO_USER_ID, message.getReceiver().getID());
contentValues.put(MESSAGE_COLUMN_IS_DELETED, 0);
contentValues.put(MESSAGE_COLUMN_CREATED_AT, message.getCreatedAt().getTimeInMillis());
contentValues.put(MESSAGE_COLUMN_STATE, message.getState().ordinal());
result = db.insert(MESSAGE_TABLE_NAME, null, contentValues) > 0;
}finally {
if (db != null && db.isOpen()){
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
return result;
}
public ArrayList<Message> getConversationMessages (User anotherUser, User currentUser) {
SQLiteDatabase db = null;
Cursor res = null;
ArrayList<Message> messages = new ArrayList<>();
try {
db = this.getReadableDatabase();
db.beginTransaction();
String deletedString = "1";
res = db.rawQuery("SELECT * FROM " + MESSAGE_TABLE_NAME +
" WHERE (" + MESSAGE_COLUMN_FROM_USER_ID + " = " + anotherUser.getID() + " OR " + MESSAGE_COLUMN_TO_USER_ID +
" = " + anotherUser.getID() + ") AND " + MESSAGE_COLUMN_IS_DELETED + " <> " + deletedString + " ORDER BY " + MESSAGE_COLUMN_CREATED_AT + " DESC", null);
res.moveToFirst();
if (res.getCount() > 0) {
do {
Calendar calendar = Calendar.getInstance();
long time = res.getLong(res.getColumnIndex(MESSAGE_COLUMN_CREATED_AT)); //replace 4 with the column index
calendar.setTimeInMillis(time);
Message message;
if (res.getInt(res.getColumnIndex(MESSAGE_COLUMN_FROM_USER_ID)) == SessionManager.getCurrentUser(mContext.getApplicationContext()).getID()) {
message = new Message(res.getInt(res.getColumnIndex(MESSAGE_COLUMN_ID)),
res.getString(res.getColumnIndex(MESSAGE_COLUMN_TEXT)),
currentUser,
anotherUser,
calendar,
Message.State.values()[res.getInt(res.getColumnIndex(MESSAGE_COLUMN_STATE))]);
} else {
message = new Message(res.getInt(res.getColumnIndex(MESSAGE_COLUMN_ID)),
res.getString(res.getColumnIndex(MESSAGE_COLUMN_TEXT)),
anotherUser,
currentUser,
calendar,
Message.State.values()[res.getInt(res.getColumnIndex(MESSAGE_COLUMN_STATE))]);
}
messages.add(message);
} while (res.moveToNext());
}
} finally {
if (res != null){
res.close();
}
if (db != null && db.isOpen()){
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
return messages;
}
public void deleteMessage(Integer messageID) {
SQLiteDatabase db = null;
try{
db = this.getWritableDatabase();
db.beginTransaction();
String deletedString = "1";
ContentValues cv = new ContentValues();
cv.put(MESSAGE_COLUMN_IS_DELETED, deletedString);
db.update(MESSAGE_TABLE_NAME, cv, MESSAGE_COLUMN_ID + "=" + messageID, null);
}finally {
if (db != null && db.isOpen()){
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
}
public void deleteMessage(Message message) {
deleteMessage(message.getID());
}
public Message getLastMessage (User anotherUser, User currentUser) {
SQLiteDatabase db = null;
Cursor res = null;
Message message;
try {
db = this.getReadableDatabase();
db.beginTransaction();
String deletedString = "1";
res = db.rawQuery("SELECT * FROM " + MESSAGE_TABLE_NAME +
" WHERE (" + MESSAGE_COLUMN_FROM_USER_ID + " = " + anotherUser.getID() + " OR " + MESSAGE_COLUMN_TO_USER_ID +
" = " + anotherUser.getID() + ") AND " + MESSAGE_COLUMN_IS_DELETED + " <> " + deletedString + " ORDER BY " + MESSAGE_COLUMN_CREATED_AT + " DESC "
+ "LIMIT 1", null);
res.moveToFirst();
Calendar calendar = Calendar.getInstance();
long time = res.getLong(res.getColumnIndex(MESSAGE_COLUMN_CREATED_AT)); //replace 4 with the column index
calendar.setTimeInMillis(time);
if (res.getInt(res.getColumnIndex(MESSAGE_COLUMN_FROM_USER_ID)) == SessionManager.getCurrentUser(mContext.getApplicationContext()).getID()){
message = new Message(res.getInt(res.getColumnIndex(MESSAGE_COLUMN_ID)),
res.getString(res.getColumnIndex(MESSAGE_COLUMN_TEXT)),
currentUser,
anotherUser,
calendar,
Message.State.values()[res.getInt(res.getColumnIndex(MESSAGE_COLUMN_STATE))]);
}else{
message = new Message(res.getInt(res.getColumnIndex(MESSAGE_COLUMN_ID)),
res.getString(res.getColumnIndex(MESSAGE_COLUMN_TEXT)),
anotherUser,
currentUser,
calendar,
Message.State.values()[res.getInt(res.getColumnIndex(MESSAGE_COLUMN_STATE))]);
}
}finally {
if (res != null) {
res.close();
}
if (db != null && db.isOpen()){
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
return message;
}
public ArrayList<Message> getLastMessages (ArrayList<User> users, User currentUser) {
ArrayList<Message> messages = new ArrayList<>();
for (User user : users){
messages.add(getLastMessage(user,currentUser));
}
return messages;
}
public boolean insertMessageUser(User user) {
SQLiteDatabase db = null;
boolean result = false;
try{
db = this.getWritableDatabase();
db.beginTransaction();
ContentValues contentValues = new ContentValues();
contentValues.put(MESSAGE_USER_COLUMN_ID, user.getID());
contentValues.put(MESSAGE_USER_COLUMN_NAME, user.getName());
contentValues.put(MESSAGE_USER_COLUMN_IMAGE_URL, user.getImageUrl());
contentValues.put(MESSAGE_USER_COLUMN_THUMBNAIL_URL, user.getThumbnailUrl());
contentValues.put(MESSAGE_USER_COLUMN_LATITUDE, user.getLatitude());
contentValues.put(MESSAGE_USER_COLUMN_LONGITUDE, user.getLongitude());
result = db.insert(MESSAGE_USER_TABLE_NAME, null, contentValues) > 0;
}finally {
if (db != null && db.isOpen()){
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
return result;
}
public ArrayList<User> getMessageUsers() {
SQLiteDatabase db = null;
Cursor res = null;
ArrayList<User> users = new ArrayList<>();
try {
db = this.getReadableDatabase();
db.beginTransaction();
res = db.rawQuery("SELECT * FROM " + MESSAGE_USER_TABLE_NAME, null);
res.moveToFirst();
if (res.getCount() > 0) {
do {
User user = new User(res.getInt(res.getColumnIndex(MESSAGE_USER_COLUMN_ID)),
res.getString(res.getColumnIndex(MESSAGE_USER_COLUMN_NAME)),
res.getString(res.getColumnIndex(MESSAGE_USER_COLUMN_IMAGE_URL)),
res.getString(res.getColumnIndex(MESSAGE_USER_COLUMN_THUMBNAIL_URL)),
res.getDouble(res.getColumnIndex(MESSAGE_USER_COLUMN_LATITUDE)),
res.getDouble(res.getColumnIndex(MESSAGE_USER_COLUMN_LONGITUDE)));
users.add(user);
} while (res.moveToNext());
}
}finally {
if (res != null) {
res.close();
}
if (db != null && db.isOpen()){
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
return users;
}
public int deleteMessageUser(Integer userID) {
SQLiteDatabase db = null;
int result;
try{
db = this.getWritableDatabase();
db.beginTransaction();
result = db.delete(MESSAGE_USER_TABLE_NAME, MESSAGE_USER_COLUMN_ID + " = ?", new String[] { userID.toString() });
}finally {
if (db != null && db.isOpen()){
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
return result;
}
public int deleteMessageUser(User user) {
return deleteMessageUser(user.getID());
}
public void deleteAllMessages() {
SQLiteDatabase db = null;
try{
db = this.getWritableDatabase();
db.beginTransaction();
db.delete(MESSAGE_USER_TABLE_NAME, null, null);
db.delete(MESSAGE_TABLE_NAME, null, null);
} finally {
if (db != null && db.isOpen()){
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
}
public boolean isMessageUserExists(int userID) {
SQLiteDatabase db = null;
Cursor res = null;
try {
db = this.getReadableDatabase();
db.beginTransaction();
res = db.rawQuery("SELECT * FROM " + MESSAGE_USER_TABLE_NAME + " WHERE " + USER_COLUMN_ID + " = " + userID, null);
res.moveToFirst();
return res.getCount() > 0;
}finally {
if (res != null) {
res.close();
}
if (db != null && db.isOpen()){
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
}
public boolean isMessageUserExists(User user) {
return isMessageUserExists(user.getID());
}
}
|
package com.intellij.usages.impl;
import com.intellij.ide.*;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Factory;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.Navigatable;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SmartExpander;
import com.intellij.ui.content.Content;
import com.intellij.usages.*;
import com.intellij.usages.rules.*;
import com.intellij.util.Alarm;
import com.intellij.util.EditSourceOnDoubleClickHandler;
import com.intellij.util.Processor;
import com.intellij.util.ui.tree.TreeUtil;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.*;
import java.util.List;
public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTrackerListener {
private UsageNodeTreeBuilder myBuilder;
private MyPanel myRootPanel;
private JTree myTree = new JTree();
private Content myContent;
private UsageViewPresentation myPresentation;
private UsageTarget[] myTargets;
private Factory<UsageSearcher> myUsageSearcherFactory;
private Project myProject;
private TreeExpander myTreeExpander;
private boolean mySearchInProgress = true;
private ExporterToTextFile myTextFileExporter;
private Alarm myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
private Alarm myFlushAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
private UsageModelTracker myModelTracker;
private Map<Usage, UsageNode> myUsageNodes = new HashMap<Usage, UsageNode>();
private ButtonPanel myButtonPanel = new ButtonPanel();
private boolean myChangesDetected = false;
private List<Usage> myUsagesToFlush = new ArrayList<Usage>();
private Factory<ProgressIndicator> myIndicatorFactory;
public UsageViewImpl(UsageViewPresentation presentation,
UsageTarget[] targets,
Factory<UsageSearcher> usageSearcherFactory,
Project project) {
myPresentation = presentation;
myTargets = targets;
myUsageSearcherFactory = usageSearcherFactory;
myProject = project;
myRootPanel = new MyPanel(myTree);
UsageViewTreeModelBuilder model = new UsageViewTreeModelBuilder(myPresentation, targets);
myBuilder = new UsageNodeTreeBuilder(getActiveGroupingRules(project), getActiveFilteringRules(project), (GroupNode)model.getRoot());
myTree.setModel(model);
myRootPanel.setLayout(new BorderLayout());
JPanel centralPanel = new JPanel();
centralPanel.setLayout(new BorderLayout());
myRootPanel.add(centralPanel, BorderLayout.CENTER);
JPanel toolbarPanel = new JPanel(new BorderLayout());
toolbarPanel.add(createToolbar(), BorderLayout.WEST);
toolbarPanel.add(createFiltersToolbar(), BorderLayout.CENTER);
myRootPanel.add(toolbarPanel, BorderLayout.WEST);
centralPanel.add(ScrollPaneFactory.createScrollPane(myTree), BorderLayout.CENTER);
centralPanel.add(myButtonPanel, BorderLayout.SOUTH);
initTree();
myTree.setCellRenderer(new UsageViewTreeCellRenderer(this));
collapseAll();
myModelTracker = new UsageModelTracker(project);
myModelTracker.addListener(this);
if (myPresentation.isShowCancelButton()) {
addButtonToLowerPane(new Runnable() {
public void run() {
close();
}
}, "Cancel", 'C');
}
}
private static UsageFilteringRule[] getActiveFilteringRules(final Project project) {
final UsageFilteringRuleProvider[] providers = ApplicationManager.getApplication().getComponents(UsageFilteringRuleProvider.class);
List<UsageFilteringRule> list = new ArrayList<UsageFilteringRule>();
for (int i = 0; i < providers.length; i++) {
list.addAll(Arrays.asList(providers[i].getActiveRules(project)));
}
return list.toArray(new UsageFilteringRule[list.size()]);
}
private static UsageGroupingRule[] getActiveGroupingRules(final Project project) {
final UsageGroupingRuleProvider[] providers = ApplicationManager.getApplication().getComponents(UsageGroupingRuleProvider.class);
List<UsageGroupingRule> list = new ArrayList<UsageGroupingRule>();
for (int i = 0; i < providers.length; i++) {
list.addAll(Arrays.asList(providers[i].getActiveRules(project)));
}
return list.toArray(new UsageGroupingRule[list.size()]);
}
public void modelChanged(boolean isPropertyChange) {
if (!isPropertyChange) {
myChangesDetected = true;
}
updateLater();
}
private void initTree() {
myTree.setRootVisible(false);
myTree.setShowsRootHandles(true);
SmartExpander.installOn(myTree);
TreeUtil.installActions(myTree);
EditSourceOnDoubleClickHandler.install(myTree);
myTree.addKeyListener(
new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (KeyEvent.VK_ENTER == e.getKeyCode()) {
TreePath leadSelectionPath = myTree.getLeadSelectionPath();
if (leadSelectionPath == null) return;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)leadSelectionPath.getLastPathComponent();
if (node instanceof UsageNode) {
final Usage usage = ((UsageNode)node).getUsage();
usage.navigate(false);
usage.highlightInEditor();
}
else if (node.isLeaf()) {
Navigatable navigatable = getNavigatableForNode(node);
if (navigatable != null && navigatable.canNavigate()) {
navigatable.navigate(false);
}
}
}
}
}
);
PopupHandler.installPopupHandler(myTree, IdeActions.GROUP_USAGE_VIEW_POPUP, ActionPlaces.USAGE_VIEW_POPUP);
//TODO: install speed search. Not in openapi though. It makes sense to create a common TreeEnchancer service.
}
private JComponent createToolbar() {
DefaultActionGroup group = new DefaultActionGroup() {
public void update(AnActionEvent e) {
super.update(e);
myButtonPanel.update(e);
}
};
AnAction[] actions = createActions();
for (int i = 0; i < actions.length; i++) {
AnAction action = actions[i];
if (action != null) group.add(action);
}
ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.USAGE_VIEW_TOOLBAR,
group, false);
return actionToolbar.getComponent();
}
private JComponent createFiltersToolbar() {
final DefaultActionGroup group = new DefaultActionGroup();
final AnAction[] groupingActions = createGroupingActions();
for (int i = 0; i < groupingActions.length; i++) {
group.add(groupingActions[i]);
}
group.add(new MergeDupLines());
final AnAction[] filteringActions = createFilteringActions();
for (int i = 0; i < filteringActions.length; i++) {
group.add(filteringActions[i]);
}
ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.USAGE_VIEW_TOOLBAR,
group, false);
return actionToolbar.getComponent();
}
private AnAction[] createActions() {
myTreeExpander = new TreeExpander() {
public void expandAll() {
UsageViewImpl.this.expandAll();
}
public boolean canExpand() {
return true;
}
public void collapseAll() {
UsageViewImpl.this.collapseAll();
}
public boolean canCollapse() {
return true;
}
};
CommonActionsManager actionsManager = CommonActionsManager.getInstance();
myTextFileExporter = new ExporterToTextFile(this);
return new AnAction[]{
canPerformReRun() ? new ReRunAction() : null,
new CloseAction(),
actionsManager.createCollapseAllAction(myTreeExpander),
actionsManager.createExpandAllAction(myTreeExpander),
actionsManager.createPrevOccurenceAction(myRootPanel),
actionsManager.createNextOccurenceAction(myRootPanel),
actionsManager.installAutoscrollToSourceHandler(myProject, myTree, new MyAutoScrollToSourceOptionProvider()),
actionsManager.createExportToTextFileAction(myTextFileExporter),
actionsManager.createHelpAction(null)
};
}
private AnAction[] createGroupingActions() {
final UsageGroupingRuleProvider[] providers = ApplicationManager.getApplication().getComponents(UsageGroupingRuleProvider.class);
List<AnAction> list = new ArrayList<AnAction>();
for (int i = 0; i < providers.length; i++) {
list.addAll(Arrays.asList(providers[i].createGroupingActions(this)));
}
return list.toArray(new AnAction[list.size()]);
}
private AnAction[] createFilteringActions() {
final UsageFilteringRuleProvider[] providers = ApplicationManager.getApplication().getComponents(UsageFilteringRuleProvider.class);
List<AnAction> list = new ArrayList<AnAction>();
for (int i = 0; i < providers.length; i++) {
list.addAll(Arrays.asList(providers[i].createFilteringActions(this)));
}
return list.toArray(new AnAction[list.size()]);
}
public void rulesChanged() {
final ArrayList<UsageState> states = new ArrayList<UsageState>();
captureUsagesExpandState(new TreePath(myTree.getModel().getRoot()), states);
Collection<Usage> allUsages = myUsageNodes.keySet();
reset();
myBuilder.setGroupingRules(getActiveGroupingRules(myProject));
myBuilder.setFilteringRules(getActiveFilteringRules(myProject));
for (Iterator<Usage> i = allUsages.iterator(); i.hasNext();) {
Usage usage = i.next();
if (!usage.isValid()) {
i.remove();
continue;
}
if (usage instanceof MergeableUsage) {
((MergeableUsage)usage).reset();
}
appendUsage(usage);
}
restoreUsageExpandState(states);
}
private void captureUsagesExpandState(TreePath pathFrom, final Collection<UsageState> states) {
if (!myTree.isExpanded(pathFrom)) {
return;
}
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)pathFrom.getLastPathComponent();
final int childCount = node.getChildCount();
for (int idx = 0; idx < childCount; idx++) {
final TreeNode child = node.getChildAt(idx);
if (child instanceof UsageNode) {
final Usage usage = ((UsageNode)child).getUsage();
if (usage != null) {
states.add(new UsageState(usage, myTree.getSelectionModel().isPathSelected(pathFrom.pathByAddingChild(child))));
}
}
else {
captureUsagesExpandState(pathFrom.pathByAddingChild(child), states);
}
}
}
private void restoreUsageExpandState(final Collection<UsageState> states) {
//always expand the last level group
final DefaultMutableTreeNode root = (DefaultMutableTreeNode)myTree.getModel().getRoot();
for (int i = root.getChildCount() - 1; i >= 0; i
final DefaultMutableTreeNode child = (DefaultMutableTreeNode)root.getChildAt(i);
if (child instanceof GroupNode){
final TreePath treePath = new TreePath(child.getPath());
myTree.expandPath(treePath);
}
}
myTree.getSelectionModel().clearSelection();
for (Iterator<UsageState> it = states.iterator(); it.hasNext();) {
final UsageState usageState = it.next();
usageState.restore();
}
}
private void expandAll() {
TreeUtil.expandAll(myTree);
}
private void collapseAll() {
TreeUtil.collapseAll(myTree, 3);
TreeUtil.expand(myTree, 2);
}
public DefaultMutableTreeNode getModelRoot() {
return (DefaultMutableTreeNode)myTree.getModel().getRoot();
}
private class CloseAction extends AnAction {
private CloseAction() {
super("Close", null, IconLoader.getIcon("/actions/cancel.png"));
}
public void update(AnActionEvent e) {
super.update(e);
e.getPresentation().setVisible(myContent != null);
}
public void actionPerformed(AnActionEvent e) {
close();
}
}
private class MergeDupLines extends RuleAction {
public MergeDupLines() {
super(UsageViewImpl.this, "Merge usages from the same line", IconLoader.getIcon("/toolbar/filterdups.png"));
}
protected boolean getOptionValue() {
return UsageViewSettings.getInstance().IS_FILTER_DUPLICATED_LINE;
}
protected void setOptionValue(boolean value) {
UsageViewSettings.getInstance().IS_FILTER_DUPLICATED_LINE = value;
}
}
private class ReRunAction extends AnAction {
public ReRunAction() {
super("Rerun", "Rerun search", IconLoader.getIcon("/actions/refreshUsages.png"));
registerCustomShortcutSet(CommonShortcuts.getRerun(), myRootPanel);
}
public void actionPerformed(AnActionEvent e) {
refreshUsages();
}
public void update(AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
presentation.setEnabled(allTargetsAreValid());
}
}
private void refreshUsages() {
reset();
doReRun();
}
private void doReRun() {
final Application application = ApplicationManager.getApplication();
final Runnable process = new Runnable() {
public void run() {
setSearchInProgress(true);
myChangesDetected = false;
UsageSearcher usageSearcher = myUsageSearcherFactory.create();
usageSearcher.generate(new Processor<Usage>() {
public boolean process(final Usage usage) {
appendUsageLater(usage);
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
return indicator != null ? !indicator.isCanceled() : true;
}
});
setSearchInProgress(false);
}
};
if (myIndicatorFactory!=null) {
UsageViewImplUtil.runProcessWithProgress(myIndicatorFactory.create(), process, new Runnable() {
public void run() {}
});
} else {
application.runProcessWithProgressSynchronously(
process, UsageViewManagerImpl.getProgressTitle(myPresentation), true, myProject
);
}
}
private void reset() {
myUsageNodes = new HashMap<Usage, UsageNode>();
myIsFirstVisibleUsageFound = false;
((UsageViewTreeModelBuilder)myTree.getModel()).reset();
TreeUtil.expand(myTree, 2);
}
public void appendUsageLater(final Usage usage) {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
myFlushAlarm.cancelAllRequests();
myFlushAlarm.addRequest(new Runnable() {
public void run() {
flush();
}
}, 300, indicator.getModalityState());
}
synchronized (myUsagesToFlush) {
myUsagesToFlush.add(usage);
if (myUsagesToFlush.size() > 50) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
flush();
}
});
}
}
}
private void flush() {
synchronized (myUsagesToFlush) {
for (int i = 0; i < myUsagesToFlush.size(); i++) {
Usage usage = myUsagesToFlush.get(i);
appendUsage(usage);
}
myUsagesToFlush.clear();
}
}
private boolean myIsFirstVisibleUsageFound = false;
public void appendUsage(Usage usage) {
final UsageNode node = myBuilder.appendUsage(usage);
myUsageNodes.put(usage, node);
if (!myIsFirstVisibleUsageFound && node != null) { //first visible usage found;
showNode(node);
myIsFirstVisibleUsageFound = true;
}
}
public void includeUsages(Usage[] usages) {
for (int i = 0; i < usages.length; i++) {
final UsageNode node = myUsageNodes.get(usages[i]);
if (node != null) {
node.setUsageExcluded(false);
}
}
updateImmediately();
}
public void excludeUsages(Usage[] usages) {
for (int i = 0; i < usages.length; i++) {
final UsageNode node = myUsageNodes.get(usages[i]);
if (node != null) {
node.setUsageExcluded(true);
}
}
updateImmediately();
}
public JComponent getComponent() {
return myRootPanel;
}
public void setContent(Content content) {
myContent = content;
content.setDisposer(this);
}
private void updateImmediately() {
checkNodeValidity((DefaultMutableTreeNode)myTree.getModel().getRoot());
}
private void checkNodeValidity(DefaultMutableTreeNode node) {
Enumeration enumeration = node.children();
while (enumeration.hasMoreElements()) {
checkNodeValidity((DefaultMutableTreeNode)enumeration.nextElement());
}
if (node instanceof Node && node != getModelRoot()) ((Node)node).update();
}
private void updateLater() {
myUpdateAlarm.cancelAllRequests();
myUpdateAlarm.addRequest(
new Runnable() {
public void run() {
updateImmediately();
}
},
300
);
}
public void close() {
com.intellij.usageView.UsageViewManager.getInstance(myProject).closeContent(myContent);
}
public void dispose() {
myModelTracker.removeListener(this);
myModelTracker.dispose();
myUpdateAlarm.cancelAllRequests();
}
public boolean isSearchInProgress() {
return mySearchInProgress;
}
public void setSearchInProgress(boolean searchInProgress) {
mySearchInProgress = searchInProgress;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
flush();
final UsageNode firstUsageNode = ((UsageViewTreeModelBuilder)myTree.getModel()).getFirstUsageNode();
if (firstUsageNode != null) { //first usage;
showNode(firstUsageNode);
}
}
});
}
private void showNode(final UsageNode node) {
TreePath usagePath = new TreePath(node.getPath());
myTree.expandPath(usagePath.getParentPath());
myTree.setSelectionPath(usagePath);
}
public void addButtonToLowerPane(final Runnable runnable, String text, char mnemonic) {
int index = myButtonPanel.getComponentCount();
if (index > 0 && myPresentation.isShowCancelButton()) index
myButtonPanel.add(
index,
runnable,
text,
mnemonic
);
}
public void addPerformOperationAction(final Runnable processRunnable,
final String commandName,
final String cannotMakeString,
String shortDescription,
char mnemonic) {
addButtonToLowerPane(
new Runnable() {
public void run() {
checkReadonlyUsages();
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
if (cannotMakeString != null && myChangesDetected) {
if (canPerformReRun() && allTargetsAreValid()) {
int answer = Messages.showYesNoDialog(
myProject,
cannotMakeString + "\nWould you like to rerun the search now?",
"Error",
Messages.getErrorIcon()
);
if (answer == 0) {
refreshUsages();
}
}
else {
Messages.showMessageDialog(
myProject,
cannotMakeString,
"Error",
Messages.getErrorIcon()
);
//todo[myakovlev] request focus to tree
//myUsageView.getTree().requestFocus();
}
return;
}
close();
CommandProcessor.getInstance().executeCommand(
myProject, new Runnable() {
public void run() {
processRunnable.run();
}
},
commandName,
null
);
}
}, shortDescription, mnemonic);
}
private boolean allTargetsAreValid() {
for (int i = 0; i < myTargets.length; i++) {
UsageTarget target = myTargets[i];
if (!target.isValid()) {
return false;
}
}
return true;
}
public UsageViewPresentation getPresentation() {
return myPresentation;
}
private boolean canPerformReRun() {
return myUsageSearcherFactory != null;
}
private void checkReadonlyUsages() {
final Set<VirtualFile> readOnlyUsages = getReadOnlyUsagesFiles();
if (!readOnlyUsages.isEmpty()) {
ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(readOnlyUsages.toArray(new VirtualFile[readOnlyUsages.size()]));
}
}
private Set<Usage> getReadOnlyUsages() {
final Set<Usage> result = new HashSet<Usage>();
final Set<Map.Entry<Usage,UsageNode>> usages = myUsageNodes.entrySet();
for (Iterator<Map.Entry<Usage,UsageNode>> i = usages.iterator(); i.hasNext();) {
Map.Entry<Usage,UsageNode> entry = i.next();
Usage usage = entry.getKey();
UsageNode node = entry.getValue();
if (!node.isExcluded() && usage.isReadOnly()) {
result.add(usage);
}
}
return result;
}
private Set<VirtualFile> getReadOnlyUsagesFiles() {
Set<Usage> usages = getReadOnlyUsages();
Set<VirtualFile> result = new HashSet<VirtualFile>();
for (Iterator<Usage> i = usages.iterator(); i.hasNext();) {
Usage usage = i.next();
if (usage instanceof UsageInFile) {
UsageInFile usageInFile = (UsageInFile)usage;
result.add(usageInFile.getFile());
}
if (usage instanceof UsageInFiles) {
UsageInFiles usageInFiles = (UsageInFiles)usage;
result.addAll(Arrays.asList(usageInFiles.getFiles()));
}
}
return result;
}
public Set<Usage> getExcludedUsages() {
Set<Usage> result = new HashSet<Usage>();
Collection<UsageNode> usageNodes = myUsageNodes.values();
for (Iterator<UsageNode> i = usageNodes.iterator(); i.hasNext();) {
final UsageNode node = i.next();
if (node == null) {
continue;
}
if (node.isExcluded()) {
result.add(node.getUsage());
}
}
return result;
}
public Node getSelectedNode() {
TreePath leadSelectionPath = myTree.getLeadSelectionPath();
if (leadSelectionPath == null) return null;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)leadSelectionPath.getLastPathComponent();
return node instanceof Node ? (Node)node : null;
}
private Usage[] getSelectedUsages() {
TreePath[] selectionPaths = myTree.getSelectionPaths();
if (selectionPaths == null) return null;
Set<Usage> usages = new HashSet<Usage>();
for (int i = 0; i < selectionPaths.length; i++) {
TreePath selectionPath = selectionPaths[i];
DefaultMutableTreeNode node = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
collectUsages(node, usages);
}
return usages.toArray(new Usage[usages.size()]);
}
private void collectUsages(DefaultMutableTreeNode node, Set<Usage> usages) {
if (node instanceof UsageNode) {
UsageNode usageNode = (UsageNode)node;
final Usage usage = usageNode.getUsage();
if (usage != null && usage.isValid()) {
usages.add(usage);
}
}
Enumeration enumeration = node.children();
while (enumeration.hasMoreElements()) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)enumeration.nextElement();
collectUsages(child, usages);
}
}
private UsageTarget[] getSelectedUsageTargets() {
TreePath[] selectionPaths = myTree.getSelectionPaths();
if (selectionPaths == null) return null;
Set<UsageTarget> targets = new HashSet<UsageTarget>();
for (int i = 0; i < selectionPaths.length; i++) {
TreePath selectionPath = selectionPaths[i];
Object lastPathComponent = selectionPath.getLastPathComponent();
if (lastPathComponent instanceof UsageTargetNode) {
UsageTargetNode usageTargetNode = (UsageTargetNode)lastPathComponent;
UsageTarget target = usageTargetNode.getTarget();
if (target != null && target.isValid()) {
targets.add(target);
}
}
}
return targets.size() > 0 ? targets.toArray(new UsageTarget[targets.size()]) : null;
}
private static Navigatable getNavigatableForNode(DefaultMutableTreeNode node) {
if (node == null) {
return null;
}
Object userObject = node.getUserObject();
if (userObject instanceof Navigatable) {
final Navigatable navigatable = (Navigatable)userObject;
return navigatable.canNavigate() ? navigatable : null;
}
return null;
}
public boolean areTargetsValid() {
return ((UsageViewTreeModelBuilder)myTree.getModel()).areTargetsValid();
}
private class MyPanel extends JPanel implements DataProvider, OccurenceNavigator {
private OccurenceNavigatorSupport mySupport;
public MyPanel(JTree tree) {
mySupport = new OccurenceNavigatorSupport(tree) {
protected Navigatable createDescriptorForNode(DefaultMutableTreeNode node) {
if (node.getChildCount() > 0) return null;
if (!((Node)node).isValid()) return null;
return getNavigatableForNode(node);
}
public String getNextOccurenceActionName() {
return "Next Occurence";
}
public String getPreviousOccurenceActionName() {
return "Previous Occurence";
}
};
}
public boolean hasNextOccurence() {
return mySupport.hasNextOccurence();
}
public boolean hasPreviousOccurence() {
return mySupport.hasPreviousOccurence();
}
public OccurenceInfo goNextOccurence() {
return mySupport.goNextOccurence();
}
public OccurenceInfo goPreviousOccurence() {
return mySupport.goPreviousOccurence();
}
public String getNextOccurenceActionName() {
return mySupport.getNextOccurenceActionName();
}
public String getPreviousOccurenceActionName() {
return mySupport.getPreviousOccurenceActionName();
}
public Object getData(String dataId) {
Node node = getSelectedNode();
if (dataId.equals(USAGE_VIEW)) {
return UsageViewImpl.this;
}
if (dataId.equals(DataConstants.NAVIGATABLE)) {
return getNavigatableForNode(node);
}
if (dataId.equals(DataConstants.EXPORTER_TO_TEXT_FILE)) {
return myTextFileExporter;
}
if (dataId.equals(USAGES)) {
return getSelectedUsages();
}
if (dataId.equals(USAGE_TARGETS)) {
Object selectedUsageTargets = getSelectedUsageTargets();
if (selectedUsageTargets != null) return selectedUsageTargets;
}
if (node != null) {
Object userObject = node.getUserObject();
if (userObject instanceof DataProvider) {
DataProvider dataProvider = (DataProvider)userObject;
return dataProvider.getData(dataId);
}
}
return null;
}
}
private static class MyAutoScrollToSourceOptionProvider implements AutoScrollToSourceOptionProvider {
public boolean isAutoScrollMode() {
return UsageViewSettings.getInstance().IS_AUTOSCROLL_TO_SOURCE;
}
public void setAutoScrollMode(boolean state) {
UsageViewSettings.getInstance().IS_AUTOSCROLL_TO_SOURCE = state;
}
}
private final class ButtonPanel extends JPanel {
public ButtonPanel() {
setLayout(new FlowLayout(FlowLayout.LEFT, 8, 0));
}
public void add(int index, final Runnable runnable, String text, char mnemonic) {
final JButton button = new JButton(text);
button.setFocusable(false);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
runnable.run();
}
});
button.setMnemonic(mnemonic);
add(button, index);
invalidate();
if (getParent() != null) {
getParent().validate();
}
}
void update(AnActionEvent e) {
for (int i = 0; i < getComponentCount(); ++i) {
Component component = getComponent(i);
if (component instanceof JButton) {
final JButton button = (JButton)component;
button.setEnabled(!isSearchInProgress());
}
}
}
}
private class UsageState {
private final Usage myUsage;
private final boolean mySelected;
public UsageState(final Usage usage) {
this(usage, false);
}
public UsageState(final Usage usage, boolean isSelected) {
myUsage = usage;
mySelected = isSelected;
}
public void restore() {
final UsageNode node = myUsageNodes.get(myUsage);
if (node == null) {
return;
}
final DefaultMutableTreeNode parentGroupingNode = (DefaultMutableTreeNode)node.getParent();
if (parentGroupingNode != null) {
final TreePath treePath = new TreePath(parentGroupingNode.getPath());
myTree.expandPath(treePath);
if (mySelected) {
myTree.addSelectionPath(treePath.pathByAddingChild(node));
}
}
}
}
public void setProgressIndicatorFactory(final Factory<ProgressIndicator> indicatorFactory) {
myIndicatorFactory = indicatorFactory;
}
}
|
package com.samourai.wallet.segwit;
import android.content.Context;
import android.widget.Toast;
import com.samourai.wallet.SamouraiWallet;
import com.samourai.wallet.hd.HD_Address;
import com.samourai.wallet.hd.HD_Wallet;
import com.samourai.wallet.hd.HD_WalletFactory;
import org.bitcoinj.crypto.MnemonicException;
import java.io.IOException;
public class BIP49Util {
private static HD_Wallet wallet = null;
private static Context context = null;
private static BIP49Util instance = null;
private BIP49Util() { ; }
public static BIP49Util getInstance(Context ctx) {
context = ctx;
if(instance == null || wallet == null) {
try {
wallet = HD_WalletFactory.getInstance(context).getBIP49();
}
catch (IOException ioe) {
ioe.printStackTrace();
Toast.makeText(context, "HD wallet error", Toast.LENGTH_SHORT).show();
}
catch (MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
Toast.makeText(context, "HD wallet error", Toast.LENGTH_SHORT).show();
}
instance = new BIP49Util();
}
return instance;
}
public void reset() {
wallet = null;
}
public HD_Wallet getWallet() {
return wallet;
}
public P2SH_P2WPKH getAddressAt(int chain, int idx) {
HD_Address addr = getWallet().getAccount(0).getChain(chain).getAddressAt(idx);
P2SH_P2WPKH p2shp2wpkh = new P2SH_P2WPKH(addr.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
return p2shp2wpkh;
}
}
|
package won.cryptography.rdfsign;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import de.uni_koblenz.aggrimm.icp.crypto.sign.graph.*;
import de.uni_koblenz.aggrimm.icp.crypto.sign.ontology.Ontology;
import won.protocol.util.RdfUtils;
import won.protocol.util.WonRdfUtils;
import won.protocol.vocabulary.WONMSG;
import java.util.ArrayList;
import java.util.LinkedList;
public class WonAssembler
{
private static final String SIG_GRAPH_NAME_TEMP = "<http://localhost:8080/won/SIG-GRAPH-PLACEHOLDER-TEMP>";
private static final String SIG_BNODE_NAME = "_:sig-1";
/**
* Assumes that namedSignedGraph is GraphCollection containing exactly one named graph
* that is part of the Dataset graphOrigin, and that for this named graph the signature
* is already calculated inside the GraphCollection internally (i.e. an Algorithm's
* methods canonicalize(namedSignedGraph), postCanonicalize(namedSignedGraph),
* hash(namedSignedGraph, envHashAlgorithm), postHash(namedSignedGraph),
* sign(namedSignedGraph, privateKey) have already been applied.
*
* The method assembles the signature from provided GraphCollection into the origin Dataset
* by putting signature triples inside the default graph of the Dataset. Intended for the
* use by WonSigner.
*
* @param namedSignedGraph GraphCollection containing one named graph with its calculated signature
* @param graphOrigin Dataset that contains the graph that has was used to construct the namedSignedGraph
* @throws Exception
*/
@Deprecated
public static void assemble(GraphCollection namedSignedGraph,
Dataset graphOrigin)
throws Exception {
Ontology o = prepareSignatureOntology(namedSignedGraph);
verifyGraphCollectionContainsExactlyOneNamedGraph(namedSignedGraph);
addSignatureTriplesToOrigin(namedSignedGraph, o, graphOrigin);
}
/**
* Assumes that namedSignedGraph is GraphCollection containing exactly one named graph
* that is part of the Dataset graphOrigin, and that for this named graph the signature
* is already calculated inside the GraphCollection internally (i.e. an Algorithm's
* methods canonicalize(namedSignedGraph), postCanonicalize(namedSignedGraph),
* hash(namedSignedGraph, envHashAlgorithm), postHash(namedSignedGraph),
* sign(namedSignedGraph, privateKey) have already been applied.
*
* The method assembles the signature from provided GraphCollection into the origin Dataset
* by putting signature triples inside the named graph of the Dataset. Intended for the
* use by WonSigner.
*
* @param namedSignedGraph GraphCollection containing one named graph with its calculated signature
* @param graphOrigin Dataset that contains the graph that has was used to construct the namedSignedGraph
* @param sigGraphURI the name (URI) of the graph that should be assigned to the signature graph
* @throws Exception
*/
public static void assemble(GraphCollection namedSignedGraph,
Dataset graphOrigin,
String sigGraphURI)
throws Exception {
Ontology o = prepareSignatureOntology(namedSignedGraph);
verifyGraphCollectionContainsExactlyOneNamedGraph(namedSignedGraph);
addSignatureAsNamedGraphToOrigin(namedSignedGraph, o, graphOrigin, sigGraphURI);
}
/**
* Removes signature graphs from the Dataset. Can be useful to use after
* verification is done, when the signatures are no longer required for
* further actions on the signed data of the Dataset.
*
* @param dataset from which graphs representing signatures have to be removed
*/
public static void removeSignatureGraphs(Dataset dataset) {
for (String name : RdfUtils.getModelNames(dataset)) {
if (WonRdfUtils.SignatureUtils.isSignatureGraph(name, dataset.getNamedModel(name))) {
dataset.removeNamedModel(name);
}
}
}
private static void verifyGraphCollectionContainsExactlyOneNamedGraph(GraphCollection gc) {
LinkedList<NamedGraph> graphs = gc.getGraphs();
if (graphs.size() == 1 && !graphs.get(0).getName().isEmpty()) {
// it's OK
} else if (graphs.size() == 2
&& graphs.get(0).getName().isEmpty() || graphs.get(1).getName().isEmpty()) {
// it's OK
} else {
// it's not OK
throw new IllegalArgumentException(WonAssembler.class.getName() +
" expects exactly one named graph, found " + (graphs.size() - 1));
}
}
private static Ontology prepareSignatureOntology(GraphCollection gc) {
//Get Signature Data
SignatureData sigData = gc.getSignature();
//Prepare Ontology
Ontology o = new Ontology(sigData);
//Choose an unused prefix for signatures to avoid prefix collisions
//Add number to default prefix in case it is used in graph already with other IRI
String sigPrefix = o.getSigPrefix(); //Get signature prefix from Ontology
String sigIri = Ontology.getSigIri(); //Get signature IRI from Ontology
String sigPre = sigPrefix;
for (int prefixCounter = 2; true; prefixCounter++) {
//Find equal prefix with different IRI
boolean prefixUsed = false;
for (Prefix p : gc.getPrefixes()) {
if (p.getPrefix().equals(sigPre)) {
if (!p.getIri().equals("<" + sigIri + ">")) {
//Found!
prefixUsed = true;
break;
}
}
}
if (prefixUsed) {
//Prefix is used with different IRI! Try again with another one (add higher number)!
sigPre = sigPrefix + prefixCounter;
} else {
//Prefix is not used with a different IRI! Continue!
break;
}
}
o.setSigPrefix(sigPre);
return o;
}
private static NamedGraph getSignatureAsGraph(GraphCollection gc, Ontology o) {
gc.addPrefix(new Prefix(o.getSigPrefix() + ":", "<" + Ontology.getSigIri() + ">"));
String name = gc.getGraphs().get(0).getName();
if (name.isEmpty()) {
name = gc.getGraphs().get(1).getName();
}
NamedGraph sigGraph = new NamedGraph(SIG_GRAPH_NAME_TEMP, 0, null);
ArrayList<Triple> sigGraphTriples = sigGraph.getTriples();
// this graph is signed by the signature
sigGraphTriples.add(new Triple(SIG_BNODE_NAME, "<" + WONMSG.HAS_SIGNED_GRAPH_PROPERTY + ">", name));
for (Triple t : o.getTriples()) {
String subj = t.getSubject();
sigGraphTriples.add(new Triple(subj, t.getPredicate(), t.getObject()));
}
gc.addGraph(sigGraph);
return sigGraph;
}
private static NamedGraph getSignatureAsGraph(GraphCollection gc, String sigGraphURI, Ontology o) {
gc.addPrefix(new Prefix(o.getSigPrefix() + ":", "<" + Ontology.getSigIri() + ">"));
// the signed graph
String name = gc.getGraphs().get(0).getName();
if (name.isEmpty()) {
name = gc.getGraphs().get(1).getName();
}
NamedGraph sigGraph = new NamedGraph(SIG_GRAPH_NAME_TEMP, 0, null);
ArrayList<Triple> sigGraphTriples = sigGraph.getTriples();
// this graph is signed by the signature
sigGraphTriples.add(new Triple("<" + sigGraphURI + ">", "<" + WONMSG.HAS_SIGNED_GRAPH_PROPERTY + ">", name));
for (Triple t : o.getTriples()) {
String subj = t.getSubject();
if (subj.equals(SIG_BNODE_NAME)) {
// this graph represents the signature and contains the signature triples
subj = "<" + sigGraphURI + ">";
}
sigGraphTriples.add(new Triple(subj, t.getPredicate(), t.getObject()));
}
gc.addGraph(sigGraph);
return sigGraph;
}
private static void addSignatureAsNamedGraphToOrigin(
GraphCollection namedSignedGraph, Ontology o,
Dataset graphOrigin, String sigGraphURI) throws Exception {
NamedGraph signatureAsGraph = getSignatureAsGraph(namedSignedGraph, sigGraphURI, o);
Model signatureAsModel = ModelConverter.namedGraphToModel(signatureAsGraph.getName(), namedSignedGraph);
graphOrigin.addNamedModel(sigGraphURI, signatureAsModel);
addPrefixesToDefaultGraph(signatureAsModel, graphOrigin);
}
private static void addSignatureTriplesToOrigin(
GraphCollection namedSignedGraph, Ontology o,
Dataset graphOrigin) throws Exception {
NamedGraph signatureAsGraph = getSignatureAsGraph(namedSignedGraph, o);
Model signatureAsModel = ModelConverter.namedGraphToModel(signatureAsGraph.getName(), namedSignedGraph);
graphOrigin.getDefaultModel().add(signatureAsModel);
addPrefixesToDefaultGraph(signatureAsModel, graphOrigin);
}
private static void addPrefixesToDefaultGraph(final Model signatureAsModel, final Dataset graphOrigin) {
for (String prefix : signatureAsModel.getNsPrefixMap().keySet()) {
graphOrigin.getDefaultModel().setNsPrefix(prefix, signatureAsModel.getNsPrefixMap().get(prefix));
}
graphOrigin.getDefaultModel().getNsPrefixMap().putAll(signatureAsModel.getNsPrefixMap());
}
}
|
package com.sjn.stamp.ui.item;
import android.animation.Animator;
import android.support.annotation.NonNull;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.sjn.stamp.R;
import com.sjn.stamp.media.provider.ProviderType;
import java.util.List;
import eu.davidea.flexibleadapter.FlexibleAdapter;
import eu.davidea.flexibleadapter.helpers.AnimatorHelper;
/**
* Item dedicated to display which Layout is currently displayed.
* This item is a Scrollable Header.
*/
public class QueueTitleItem extends AbstractItem<QueueTitleItem.LayoutViewHolder> {
private ProviderType mProviderType;
private String mProviderValue;
public QueueTitleItem(ProviderType providerType, String providerValue) {
super(providerType.name() + providerValue);
mProviderType = providerType;
mProviderValue = providerValue;
}
@Override
public int getLayoutRes() {
return R.layout.recycler_queue_title_item;
}
@Override
public LayoutViewHolder createViewHolder(FlexibleAdapter adapter, LayoutInflater inflater, ViewGroup parent) {
return new LayoutViewHolder(inflater.inflate(getLayoutRes(), parent, false), adapter);
}
@Override
public void bindViewHolder(FlexibleAdapter adapter, LayoutViewHolder holder, int position, List payloads) {
if (mProviderType != null) {
holder.mTitle.setText(mProviderType.name());
if (mProviderValue == null || mProviderValue.isEmpty()) {
holder.mSubtitle.setVisibility(View.GONE);
} else {
holder.mSubtitle.setVisibility(View.VISIBLE);
holder.mSubtitle.setText(mProviderValue);
}
}
//Support for StaggeredGridLayoutManager
if (holder.itemView.getLayoutParams() instanceof StaggeredGridLayoutManager.LayoutParams) {
((StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams()).setFullSpan(true);
Log.d("ScrollableLayoutItem", "LayoutItem configured fullSpan for StaggeredGridLayout");
}
}
static class LayoutViewHolder extends LongClickDisableViewHolder {
public TextView mTitle;
TextView mSubtitle;
LayoutViewHolder(View view, FlexibleAdapter adapter) {
super(view, adapter, true);
mTitle = (TextView) view.findViewById(R.id.title);
mSubtitle = (TextView) view.findViewById(R.id.subtitle);
}
@Override
public void scrollAnimators(@NonNull List<Animator> animators, int position, boolean isForward) {
AnimatorHelper.slideInFromTopAnimator(animators, itemView, mAdapter.getRecyclerView());
}
}
@Override
public String toString() {
return "ScrollableLayoutItem[" + super.toString() + "]";
}
}
|
package mdn.vtvpluspro.fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import mdn.vtvplus.R;
import mdn.vtvpluspro.adapter.LiveScoreAdapter;
import mdn.vtvpluspro.common.DialogManager;
import mdn.vtvpluspro.common.ExpandableHeightListView;
import mdn.vtvpluspro.common.ParserManager;
import mdn.vtvpluspro.network.ApiManager;
import mdn.vtvpluspro.network.IApiCallback;
import mdn.vtvpluspro.object.MatchScheduleModel;
import java.util.ArrayList;
import java.util.List;
public class LiveScoreFragment extends BaseFragment {
private View rootView;
private ScrollView fragment_list_live_score_root;
private ExpandableHeightListView fragment_live_score_current_list;
private ExpandableHeightListView fragment_live_score_result_list;
private ExpandableHeightListView fragment_live_score_future_list;
private LiveScoreAdapter lvOfCurrentAdapter;
private LiveScoreAdapter lvOfResultAdapter;
private LiveScoreAdapter lvOfFutureAdapter;
private List<MatchScheduleModel> mListOfCurrent;
private List<MatchScheduleModel> mListOfResult;
private List<MatchScheduleModel> mListOfFuture;
private Handler handler;
private boolean isTheFirstTime;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mListOfCurrent = new ArrayList<MatchScheduleModel>();
mListOfResult = new ArrayList<MatchScheduleModel>();
mListOfFuture = new ArrayList<MatchScheduleModel>();
handler = new Handler();
isTheFirstTime = true;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_list_live_score, null);
fragment_list_live_score_root = (ScrollView) rootView
.findViewById(R.id.fragment_list_live_score_root);
fragment_live_score_current_list = (ExpandableHeightListView) rootView
.findViewById(R.id.fragment_live_score_current_list);
fragment_live_score_result_list = (ExpandableHeightListView) rootView
.findViewById(R.id.fragment_live_score_result_list);
fragment_live_score_future_list = (ExpandableHeightListView) rootView
.findViewById(R.id.fragment_live_score_future_list);
fragment_live_score_current_list.setExpanded(true);
fragment_live_score_result_list.setExpanded(true);
fragment_live_score_future_list.setExpanded(true);
requestData();
return rootView;
}
private void requestData() {
if(isTheFirstTime) {
DialogManager.showSimpleProgressDialog(baseSlideMenuActivity);
}
ApiManager.callListLiveScore(baseSlideMenuActivity, new IApiCallback() {
@Override
public void responseSuccess(String response) {
// TODO Auto-generated method stub
parserLiveScoreData(response);
}
@Override
public void responseFailWithCode(int statusCode) {
DialogManager.alert(baseSlideMenuActivity,
getString(R.string.network_fail));
DialogManager.closeProgressDialog();
}
});
}
private void parserLiveScoreData(String response) {
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... strings) {
if (null == mListOfCurrent) {
mListOfCurrent = new ArrayList<MatchScheduleModel>();
} else {
mListOfCurrent.clear();
}
if (null == mListOfResult) {
mListOfResult = new ArrayList<MatchScheduleModel>();
} else {
mListOfResult.clear();
}
if (null == mListOfFuture) {
mListOfFuture = new ArrayList<MatchScheduleModel>();
} else {
mListOfFuture.clear();
}
ParserManager.parserListLiveScoreData(strings[0], mListOfCurrent, mListOfResult,
mListOfFuture);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
updateView();
if(null != handler){
if(isTheFirstTime) {
DialogManager.closeProgressDialog();
isTheFirstTime = false;
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
requestData();
}
}, 30000);
}
}
}.execute(response);
}
private void updateView() {
lvOfCurrentAdapter = new LiveScoreAdapter(getActivity(), mListOfCurrent);
lvOfResultAdapter = new LiveScoreAdapter(getActivity(), mListOfResult);
lvOfFutureAdapter = new LiveScoreAdapter(getActivity(), mListOfFuture);
fragment_live_score_current_list.setAdapter(lvOfCurrentAdapter);
fragment_live_score_result_list.setAdapter(lvOfResultAdapter);
fragment_live_score_future_list.setAdapter(lvOfFutureAdapter);
fragment_list_live_score_root.smoothScrollTo(0, 0);
}
}
|
package edu.wustl.catissuecore.flex.dag;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import edu.common.dynamicextensions.domaininterface.AssociationInterface;
import edu.common.dynamicextensions.domaininterface.AttributeInterface;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException;
import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException;
import edu.wustl.cab2b.client.ui.dag.PathLink;
import edu.wustl.cab2b.client.ui.dag.ambiguityresolver.AmbiguityObject;
import edu.wustl.cab2b.client.ui.query.ClientQueryBuilder;
import edu.wustl.cab2b.client.ui.query.IClientQueryBuilderInterface;
import edu.wustl.cab2b.client.ui.query.IPathFinder;
import edu.wustl.cab2b.server.cache.EntityCache;
import edu.wustl.catissuecore.applet.AppletConstants;
import edu.wustl.catissuecore.bizlogic.querysuite.CreateQueryObjectBizLogic;
import edu.wustl.catissuecore.bizlogic.querysuite.GenerateHtmlForAddLimitsBizLogic;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.querysuite.QueryModuleError;
import edu.wustl.catissuecore.util.querysuite.QueryModuleUtil;
import edu.wustl.common.querysuite.exceptions.CyclicException;
import edu.wustl.common.querysuite.factory.QueryObjectFactory;
import edu.wustl.common.querysuite.metadata.associations.IAssociation;
import edu.wustl.common.querysuite.metadata.associations.IIntraModelAssociation;
import edu.wustl.common.querysuite.metadata.path.IPath;
import edu.wustl.common.querysuite.queryobject.ICondition;
import edu.wustl.common.querysuite.queryobject.IConstraints;
import edu.wustl.common.querysuite.queryobject.IExpression;
import edu.wustl.common.querysuite.queryobject.IExpressionId;
import edu.wustl.common.querysuite.queryobject.IJoinGraph;
import edu.wustl.common.querysuite.queryobject.IQuery;
import edu.wustl.common.querysuite.queryobject.IQueryEntity;
import edu.wustl.common.querysuite.queryobject.LogicalOperator;
import edu.wustl.common.querysuite.queryobject.impl.Expression;
import edu.wustl.common.querysuite.queryobject.impl.ExpressionId;
import edu.wustl.common.querysuite.queryobject.impl.JoinGraph;
import edu.wustl.common.querysuite.queryobject.impl.Rule;
import edu.wustl.common.querysuite.queryobject.locator.Position;
import edu.wustl.common.querysuite.queryobject.locator.QueryNodeLocator;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.common.util.logger.Logger;
/**
*The class is responsibel controlling all activities of Flex DAG
*
*@author aniket_pandit
*/
public class DAGPanel {
private IClientQueryBuilderInterface m_queryObject;
private IPathFinder m_pathFinder;
private IExpression expression;
private HashMap<String,IPath> m_pathMap = new HashMap<String, IPath>();
private Map<IExpressionId, Position> positionMap;
public DAGPanel(IPathFinder pathFinder)
{
m_pathFinder =pathFinder;
}
/**
*
* @param expressionId
* @param isOutputView
* @return
*/
private DAGNode createNode(IExpressionId expressionId,boolean isOutputView)
{
IExpression expression = m_queryObject.getQuery().getConstraints().getExpression(expressionId);
IQueryEntity constraintEntity = expression.getQueryEntity();
DAGNode dagNode = new DAGNode();
dagNode.setNodeName(edu.wustl.cab2b.common.util.Utility.getOnlyEntityName(constraintEntity.getDynamicExtensionsEntity()));
dagNode.setExpressionId(expression.getExpressionId().getInt());
if(isOutputView)
{
dagNode.setNodeType(DAGConstant.VIEW_ONLY_NODE);
}
else
{
dagNode.setToolTip(expression);
}
return dagNode;
}
/**
*
* @param strToCreateQueryObject
* @param entityName
* @param mode
* @return
*/
@SuppressWarnings("unchecked")
public DAGNode createQueryObject(String strToCreateQueryObject,String entityName,String mode)
{
Map ruleDetailsMap = null;
IExpressionId expressionId = null;
DAGNode node = null;
HttpServletRequest request = flex.messaging.FlexContext.getHttpRequest();
HttpSession session = request.getSession();
IQuery query = (IQuery)session.getAttribute(DAGConstant.QUERY_OBJECT);// Get existing Query object from server
if(query != null)
{
m_queryObject.setQuery(query);
}
else
{
query = m_queryObject.getQuery();
}
session.setAttribute(DAGConstant.QUERY_OBJECT, query);
try {
Long entityId = Long.parseLong(entityName);
EntityInterface entity =EntityCache.getCache().getEntityById(entityId);
CreateQueryObjectBizLogic queryBizLogic = new CreateQueryObjectBizLogic();
if (!strToCreateQueryObject.equalsIgnoreCase("")) {
ruleDetailsMap = queryBizLogic.getRuleDetailsMap(strToCreateQueryObject, entity);
List<AttributeInterface> attributes = (List<AttributeInterface>) ruleDetailsMap.get(AppletConstants.ATTRIBUTES);
List<String> attributeOperators = (List<String>) ruleDetailsMap.get(AppletConstants.ATTRIBUTE_OPERATORS);
List<List<String>> conditionValues = (List<List<String>>) ruleDetailsMap.get(AppletConstants.ATTR_VALUES);
String errMsg = (String)ruleDetailsMap.get(AppletConstants.ERROR_MESSAGE);
if(errMsg.equals(""))
{
if(mode.equals("Edit"))
{
Rule rule = ((Rule) (expression.getOperand(0)));
rule.removeAllConditions();
List<ICondition> conditionsList = ((ClientQueryBuilder)m_queryObject).getConditions(attributes, attributeOperators,conditionValues);
for (ICondition condition : conditionsList)
{
rule.addCondition(condition);
}
expressionId = expression.getExpressionId();
node = createNode(expressionId,false);
}
else
{
expressionId = m_queryObject.addRule(attributes, attributeOperators, conditionValues,entity);
node = createNode(expressionId,false);
}
node.setErrorMsg(errMsg);
}else
{
node= new DAGNode();
node.setErrorMsg(errMsg);
}
}
} catch (DynamicExtensionsSystemException e) {
e.printStackTrace();
} catch (DynamicExtensionsApplicationException e) {
e.printStackTrace();
}
return node;
}
/**
* Sets ClientQueryBuilder object
* @param queryObject
*/
public void setQueryObject(IClientQueryBuilderInterface queryObject) {
m_queryObject = queryObject;
}
/**
* Sets Expression
* @param expression
*/
public void setExpression(IExpression expression)
{
this.expression = expression;
}
/**
* Links two nodes
* @param sourceNode
* @param destNode
* @param paths
*/
public List<DAGPath> linkNode(final DAGNode sourceNode, final DAGNode destNode,List<IPath> paths) {
List<DAGPath> dagPathList = null;
if (paths != null && !paths.isEmpty()) {
dagPathList = new ArrayList<DAGPath>();
IExpressionId sourceExpressionId = new ExpressionId(sourceNode.getExpressionId());
IExpressionId destExpressionId = new ExpressionId(destNode.getExpressionId());
if (!m_queryObject.isPathCreatesCyclicGraph(sourceExpressionId, destExpressionId,
paths.get(0))) {
for (int i = 0; i < paths.size(); i++) {
IPath path = paths.get(i);
LinkTwoNode(sourceNode, destNode, paths.get(i), new ArrayList<IExpressionId>());
String pathStr = new Long(path.getPathId()).toString();
DAGPath dagPath = new DAGPath();
dagPath.setToolTip(getPathDisplayString(path));
dagPath.setId(pathStr);
dagPath.setSourceExpId(sourceNode.getExpressionId());
dagPath.setDestinationExpId(destNode.getExpressionId());
dagPathList.add(dagPath);
String key =pathStr+"_"+sourceNode.getExpressionId()+"_"+destNode.getExpressionId();
m_pathMap.put(key,path);
}
}
}
return dagPathList;
}
/**
* Gets list of paths between two nodes
* @param sourceNode
* @param destNode
* @return
*/
public List<IPath> getPaths(DAGNode sourceNode, DAGNode destNode) {
Map<AmbiguityObject, List<IPath>> map = null;
AmbiguityObject ambiguityObject = null;
try {
IQuery query = m_queryObject.getQuery();
IConstraints constraints = query.getConstraints();
IExpressionId expressionId = new ExpressionId(sourceNode.getExpressionId());
IExpression expression = constraints
.getExpression(expressionId);
IQueryEntity sourceEntity = expression
.getQueryEntity();
expressionId = new ExpressionId(destNode.getExpressionId());
expression = constraints.getExpression(expressionId);
IQueryEntity destinationEntity = expression
.getQueryEntity();
ambiguityObject = new AmbiguityObject(
sourceEntity.getDynamicExtensionsEntity(),
destinationEntity.getDynamicExtensionsEntity());
// ResolveAmbiguity resolveAmbigity = new ResolveAmbiguity(
// ambiguityObject, m_pathFinder);
DAGResolveAmbiguity resolveAmbigity = new DAGResolveAmbiguity(ambiguityObject, m_pathFinder);
map = resolveAmbigity.getPathsForAllAmbiguities();
} catch (Exception e) {
e.printStackTrace();
}
return map.get(ambiguityObject);
}
/**
* Link 2 nodes
* @param sourceNode
* @param destNode
* @param path
* @param intermediateExpressions
*/
private void LinkTwoNode(final DAGNode sourceNode, final DAGNode destNode, final IPath path,
List<IExpressionId> intermediateExpressions) {
IExpressionId sourceexpressionId = null;
IExpressionId destexpressionId = null;
try {
sourceexpressionId = new ExpressionId(sourceNode
.getExpressionId());
destexpressionId = new ExpressionId(destNode
.getExpressionId());
intermediateExpressions = m_queryObject.addPath(sourceexpressionId,
destexpressionId, path);
} catch (CyclicException e) {
// JOptionPane.showMessageDialog(this, "Cannot connect nodes as it creates cycle in graph",
// "Connect Nodes warning", JOptionPane.WARNING_MESSAGE);
e.printStackTrace();
}
//DAGPath dagpath
PathLink link = new PathLink();
link.setAssociationExpressions(intermediateExpressions);
link.setDestinationExpressionId(destexpressionId);
link.setSourceExpressionId(sourceexpressionId);
link.setPath(path);
//// if (assPosition == 0) {
//// updateQueryObject(link, sourceNode, destNode, null);
//// } else {
updateQueryObject(link,sourceNode, destNode);
}
/**
* Updates query object
* @param link
* @param sourceNode
* @param destNode
*/
private void updateQueryObject(PathLink link, DAGNode sourceNode, DAGNode destNode) {
//TODO required to modify code logic will not work for multiple association
IExpressionId sourceexpressionId = new ExpressionId(sourceNode
.getExpressionId());
//IExpressionId destexpressionId = new ExpressionId(destNode
//.getExpressionId());
// If the first association is added, put operator between attribute condition and association
String operator = null;
// if (sourcePort == null) {
operator = sourceNode.getOperatorBetweenAttrAndAssociation();
//} else { // Get the logical operator associated with previous association
// operator = sourceNode.getLogicalOperator(sourcePort);
// Get the expressionId between which to add logical operator
IExpressionId destId = link.getLogicalConnectorExpressionId();
m_queryObject.setLogicalConnector(sourceexpressionId, destId,
edu.wustl.cab2b.client.ui.query.Utility.getLogicalOperator(operator), false);
// Put appropriate parenthesis
// The code is required for multiple associations
//if (sourcePort != null) {
//IExpressionId previousExpId = link.getLogicalConnectorExpressionId();
//m_queryObject.addParantheses(sourceexpressionId, previousExpId, destId);
}
/**
* Gets display path string
* @param path
* @return
*/
public static String getPathDisplayString(IPath path) {
String text = "";
List<IAssociation> pathList = path.getIntermediateAssociations();
text = text.concat(edu.wustl.cab2b.common.util.Utility.getOnlyEntityName(path.getSourceEntity()));
for (int i = 0; i < pathList.size(); i++) {
text = text.concat(">>");
IAssociation association = pathList.get(i);
if (association instanceof IIntraModelAssociation)
{
IIntraModelAssociation iAssociation = (IIntraModelAssociation)association;
AssociationInterface dynamicExtensionsAssociation = iAssociation.getDynamicExtensionsAssociation();
String role = "("+dynamicExtensionsAssociation.getTargetRole().getName()+")";
text = text.concat(role+">>");
}
text = text.concat(edu.wustl.cab2b.common.util.Utility.getOnlyEntityName(association.getTargetEntity()));
}
Logger.out.debug(text );
return text;
}
/**
* Generates sql query
* @return
*/
public int search()
{
QueryModuleError status = QueryModuleError.SUCCESS;
IQuery query = m_queryObject.getQuery();
HttpServletRequest request = flex.messaging.FlexContext.getHttpRequest();
boolean isRulePresentInDag = QueryModuleUtil.checkIfRulePresentInDag(query) ;
if (isRulePresentInDag)
{
status=QueryModuleUtil.searchQuery(request, query,null);
}
else
{
status = QueryModuleError.EMPTY_DAG;
}
return status.getErrorCode();
}
/**
* Repaints DAG
* @return
*/
public List<DAGNode> repaintDAG()
{
List<DAGNode> nodeList = new ArrayList<DAGNode>();
HttpServletRequest request = flex.messaging.FlexContext.getHttpRequest();
HttpSession session = request.getSession();
IQuery query =(IQuery)session.getAttribute(DAGConstant.QUERY_OBJECT);
m_queryObject.setQuery(query);
IConstraints constraints = query.getConstraints();
positionMap = new QueryNodeLocator(400,query).getPositionMap();
HashSet<IExpressionId> visibleExpression = new HashSet<IExpressionId>();
Enumeration<IExpressionId> expressionIds = constraints.getExpressionIds();
while(expressionIds.hasMoreElements())
{
IExpressionId id = expressionIds.nextElement();
IExpression expression = constraints.getExpression(id);
if(expression.isVisible())
{
visibleExpression.add(id);
}
}
for(IExpressionId expressionId:visibleExpression){
IExpression exp = constraints.getExpression(expressionId);
IQueryEntity constraintEntity = exp.getQueryEntity();
String nodeDisplayName = edu.wustl.cab2b.common.util.Utility.getOnlyEntityName(constraintEntity.getDynamicExtensionsEntity());
DAGNode dagNode = new DAGNode();
dagNode.setExpressionId(exp.getExpressionId().getInt());
dagNode.setNodeName(nodeDisplayName);
dagNode.setToolTip(exp);
Position position = positionMap.get(exp.getExpressionId());
if (position!=null)
{
dagNode.setX(position.getX());
dagNode.setY(position.getY());
}
if(!exp.containsRule())
{
dagNode.setNodeType(DAGConstant.VIEW_ONLY_NODE);
}
if(!exp.isInView())
{
dagNode.setNodeType(DAGConstant.CONSTRAINT_ONLY_NODE);
}
nodeform(expressionId,dagNode,constraints,new ArrayList<IIntraModelAssociation>());
int numOperands = exp.numberOfOperands();
int numOperator = numOperands-1;
for(int i=0;i<numOperator;i++)
{
String operator = exp.getConnector(i, i+1).getOperator().toString();
dagNode.setOperatorList(operator.toUpperCase());
}
nodeList.add(dagNode);
}
return nodeList;
}
/**
*
* @param expressionId
* @param node
* @param constraints
* @param path
*/
private void nodeform(IExpressionId expressionId,DAGNode node,IConstraints constraints,List<IIntraModelAssociation> intraModelAssociationList)
{
IJoinGraph graph = constraints.getJoinGraph();
List childList = graph.getChildrenList(expressionId);
for(int i=0;i<childList.size();i++)
{
IExpressionId newExpId = (IExpressionId)childList.get(i);
IExpression exp = constraints.getExpression(newExpId);
IQueryEntity constraintEntity = exp.getQueryEntity();
/* Code to get IPath Object*/
IIntraModelAssociation association =(IIntraModelAssociation)(graph.getAssociation(expressionId,newExpId));
intraModelAssociationList.add(association);
if(exp.isVisible())
{
IPath pathObj = (IPath)m_pathFinder.getPathForAssociations(intraModelAssociationList);
long pathId =pathObj.getPathId();
DAGNode dagNode = new DAGNode();
dagNode.setExpressionId(exp.getExpressionId().getInt());
dagNode.setNodeName(edu.wustl.cab2b.common.util.Utility.getOnlyEntityName(constraintEntity.getDynamicExtensionsEntity()));
dagNode.setToolTip(exp);
/* Adding Dag Path in each visible list which have childrens*/
String pathStr =new Long(pathId).toString();
DAGPath dagPath = new DAGPath();
dagPath.setToolTip(getPathDisplayString(pathObj));
dagPath.setId(pathStr);
dagPath.setSourceExpId(node.getExpressionId());
dagPath.setDestinationExpId(dagNode.getExpressionId());
String key =pathStr+"_"+node.getExpressionId()+"_"+dagNode.getExpressionId();
m_pathMap.put(key,pathObj);
node.setDagpathList(dagPath);
node.setAssociationList(dagNode);
intraModelAssociationList.clear();
}
else
{
nodeform(newExpId,node,constraints,intraModelAssociationList);
}
}
}
/**
*
* @param parentExpId
* @param parentIndex
* @param operator
*/
public void updateLogicalOperator(int parentExpId,int parentIndex,String operator )
{
IExpressionId parentExpressionId = new ExpressionId(parentExpId);
IQuery query = m_queryObject.getQuery();
IExpression parentExpression = query.getConstraints().getExpression(parentExpressionId);
LogicalOperator logicOperator = edu.wustl.cab2b.client.ui.query.Utility.getLogicalOperator(operator);
int childIndex = parentIndex +1;
parentExpression.setConnector(parentIndex, childIndex,QueryObjectFactory.createLogicalConnector(logicOperator));
m_queryObject.setQuery(query);
}
/**
*
* @param expId
* @return
*/
public Map editAddLimitUI(int expId)
{
Map<String, Object> map = new HashMap<String,Object>();
IExpressionId expressionId = new ExpressionId(expId);
IExpression expression = m_queryObject.getQuery().getConstraints().getExpression(expressionId);
EntityInterface entity = expression.getQueryEntity().getDynamicExtensionsEntity();
GenerateHtmlForAddLimitsBizLogic generateHTMLBizLogic = new GenerateHtmlForAddLimitsBizLogic();
Rule rule = ((Rule) (expression.getOperand(0)));
List<ICondition> conditions = rule.getConditions();
String html = generateHTMLBizLogic.generateHTML(entity, conditions);
map.put(DAGConstant.HTML_STR, html);
map.put(DAGConstant.EXPRESSION, expression);
return map;
}
/**
*
* @param nodesStr
* @return
*/
public DAGNode addNodeToOutPutView(String id)
{
DAGNode node = null;
if (!id.equalsIgnoreCase(""))
{
Long entityId = Long.parseLong(id);
EntityInterface entity =EntityCache.getCache().getEntityById(entityId);
IExpressionId expressionId = ((ClientQueryBuilder)m_queryObject).addExpression(entity);
node = createNode(expressionId,true);
}
return node;
}
public void restoreQueryObject()
{
HttpServletRequest request = flex.messaging.FlexContext.getHttpRequest();
HttpSession session = request.getSession();
IQuery query = (IQuery) session.getAttribute(DAGConstant.QUERY_OBJECT);
m_queryObject.setQuery(query);
}
/**
*
* @param expId
*/
public void deleteExpression(int expId)
{
IExpressionId expressionId = new ExpressionId(expId);
m_queryObject.removeExpression(expressionId);
}
/**
*
* @param expId
*/
public void addExpressionToView(int expId) {
IExpressionId expressionId = new ExpressionId(expId);
Expression expression = (Expression) m_queryObject.getQuery().getConstraints().getExpression(expressionId);
expression.setInView(true);
}
/**
*
* @param expId
*/
public void deleteExpressionFormView(int expId)
{
IExpressionId expressionId = new ExpressionId(expId);
Expression expression = (Expression) m_queryObject.getQuery().getConstraints().getExpression(expressionId);
expression.setInView(false);
}
/**
*
* @param path
* @param linkedNodeList
*/
public void deletePath(String pathName,List<DAGNode>linkedNodeList)
{
IPath path = m_pathMap.remove(pathName);
IExpressionId sourceexpressionId = new ExpressionId(linkedNodeList.get(0)
.getExpressionId());
IExpressionId destexpressionId = new ExpressionId(linkedNodeList.get(1)
.getExpressionId());
List<IAssociation> associations =path.getIntermediateAssociations();
JoinGraph graph =(JoinGraph)m_queryObject.getQuery().getConstraints().getJoinGraph();
List<IExpressionId> expressionIds = graph.getIntermediateExpressions(sourceexpressionId, destexpressionId, associations);
// If the association is direct association, remove the respective association
if (0 == expressionIds.size()) {
m_queryObject.removeAssociation(sourceexpressionId, destexpressionId);
} else {
for (int i = 0; i < expressionIds.size(); i++) {
m_queryObject.removeExpression(expressionIds.get(i));
}
}
}
}
|
package de.gebatzens.ggvertretungsplan;
import android.annotation.TargetApi;
import android.app.Application;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import java.util.HashMap;
import de.gebatzens.ggvertretungsplan.data.Exams;
import de.gebatzens.ggvertretungsplan.data.Filter;
import de.gebatzens.ggvertretungsplan.data.GGPlan;
import de.gebatzens.ggvertretungsplan.data.Mensa;
import de.gebatzens.ggvertretungsplan.data.News;
import de.gebatzens.ggvertretungsplan.fragment.RemoteDataFragment;
import de.gebatzens.ggvertretungsplan.provider.GGProvider;
import de.gebatzens.ggvertretungsplan.provider.SWSProvider;
import de.gebatzens.ggvertretungsplan.provider.VPProvider;
public class GGApp extends Application {
public GGPlan.GGPlans plans = null;
public News news;
public Mensa mensa;
public MainActivity activity;
public VPProvider provider;
public Exams exams;
public static final int UPDATE_DISABLE = 0, UPDATE_WLAN = 1, UPDATE_ALL = 2;
private SharedPreferences preferences;
public static GGApp GG_APP;
private HashMap<String, Class<? extends VPProvider>> mProviderList = new HashMap<String, Class<? extends VPProvider>>();
public Filter.FilterList filters = new Filter.FilterList();
@Override
public void onCreate() {
super.onCreate();
GG_APP = this;
registerProviders();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
GGBroadcast.createAlarm(this);
recreateProvider();
filters = FilterActivity.loadFilter();
}
public RemoteDataFragment.RemoteData getDataForFragment(FragmentType type) {
switch(type) {
case PLAN:
return plans;
case NEWS:
return news;
case MENSA:
return mensa;
case EXAMS:
return exams;
default:
return null;
}
}
public void registerProviders() {
mProviderList.clear();
mProviderList.put("gg", GGProvider.class);
mProviderList.put("sws", SWSProvider.class);
}
public void createNotification(int icon, String title, String message, Intent intent, int id, String... strings) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(message);
if(strings.length > 1) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(strings[0]);
boolean b = true;
for(String s : strings) {
if(!b) {
inboxStyle.addLine(s);
}
b = false;
}
mBuilder.setStyle(inboxStyle);
}
mBuilder.setColor(GGApp.GG_APP.provider.getDarkColor());
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(id, mBuilder.build());
}
public String getSelectedProvider() {
return preferences.getString("schule", "gg");
}
public boolean notificationsEnabled() {
return preferences.getBoolean("benachrichtigungen", true);
}
public void showToast(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
public void recreateProvider() {
createProvider(getSelectedProvider());
if(provider instanceof GGProvider)
startService(new Intent(this, MQTTService.class));
}
public void createProvider(String id) {
Log.w("ggvp", "createProvider " + id);
Class<? extends VPProvider> clas = mProviderList.get(id);
if(clas == null)
throw new RuntimeException("Provider for " + id + " not found");
try {
provider = (VPProvider) clas.getConstructors()[0].newInstance(this, id);
} catch (Exception e) {
e.printStackTrace();
}
}
public int translateUpdateType(String s) {
if(s.equals("disable"))
return UPDATE_DISABLE;
else if(s.equals("wifi"))
return UPDATE_WLAN;
else if(s.equals("all"))
return UPDATE_ALL;
return UPDATE_DISABLE;
}
public String translateUpdateType(int i) {
String[] s = getResources().getStringArray(R.array.appupdatesArray);
return s[i];
}
public int getUpdateType() {
return translateUpdateType(preferences.getString("appupdates", "wifi"));
}
public FragmentType getFragmentType() {
return FragmentType.valueOf(preferences.getString("fragtype", "PLAN"));
}
public void setFragmentType(FragmentType type) {
preferences.edit().putString("fragtype", type.toString()).apply();
}
public boolean appUpdatesEnabled() {
return preferences.getBoolean("autoappupdates", true);
}
public void refreshAsync(final Runnable finished, final boolean updateFragments, final FragmentType type) {
Log.w("ggvp", "refreshAsync " + type + " " + provider);
new Thread() {
@Override
public void run() {
boolean update = updateFragments;
switch(type) {
case PLAN:
GGPlan.GGPlans nplans = provider.getPlans(updateFragments);
//if(plans != null)
// update = update && !(nplans[0].equals(plans[0]) && nplans[1].equals(plans[1]));
plans = nplans;
break;
case NEWS:
news = provider.getNews();
break;
case MENSA:
mensa = provider.getMensa();
break;
case EXAMS:
exams = provider.getExams();
break;
}
if(update)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
activity.mContent.updateFragment();
}
});
if(finished != null)
activity.runOnUiThread(finished);
}
}.start();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void setStatusBarColor(Window w) {
w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
w.setStatusBarColor(GGApp.GG_APP.provider.getDarkColor());
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void setStatusBarColorTransparent(Window w) {
w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
w.setStatusBarColor(getResources().getColor(R.color.transparent));
}
public static enum FragmentType {
PLAN, NEWS, MENSA, EXAMS
}
}
|
package ru.job4j.chess.figure;
import ru.job4j.chess.Cell;
import ru.job4j.chess.exception.ImpossibleMoveException;
import java.util.Arrays;
public class Bishop extends Figure {
private Cell position;
public Bishop(Cell position) {
super(position);
this.position = position;
}
public Figure clone(Cell dist) {
return new Bishop(dist);
}
@Override
public Cell[] way(Cell dest) throws ImpossibleMoveException {
Cell[] result;
if (Math.abs(this.position.getX() - dest.getX()) == Math.abs(this.position.getY() - dest.getY())) {
result = super.way(dest);
} else {
throw new ImpossibleMoveException("This move is impossible");
}
return result;
}
}
|
package com.thoughtworks.xstream.converters.extended;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Convenient converter for classes with natural string representation.
*
* Converter for classes that adopt the following convention:
* - a constructor that takes a single string parameter
* - a toString() that is overloaded to issue a string that is meaningful
*
* @author Paul Hammant
*/
public class ToStringConverter extends AbstractSingleValueConverter {
private final Class clazz;
private final Constructor ctor;
public ToStringConverter(Class clazz) throws NoSuchMethodException {
this.clazz = clazz;
ctor = clazz.getConstructor(new Class[] {String.class});
}
public boolean canConvert(Class type) {
return type.equals(clazz);
}
public String toString(Object obj) {
return obj == null ? null : obj.toString();
}
public Object fromString(String str) {
try {
return ctor.newInstance(new Object[] {str});
} catch (InstantiationException e) {
throw new ConversionException("Unable to instantiate single String param constructor", e);
} catch (IllegalAccessException e) {
throw new ConversionException("Unable to access single String param constructor", e);
} catch (InvocationTargetException e) {
throw new ConversionException("Unable to target single String param constructor", e.getTargetException());
}
}
}
|
package org.bouncycastle.tls;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import org.bouncycastle.tls.crypto.TlsCipher;
import org.bouncycastle.tls.crypto.TlsDecodeResult;
import org.bouncycastle.tls.crypto.TlsEncodeResult;
import org.bouncycastle.tls.crypto.TlsNullNullCipher;
/**
* An implementation of the TLS 1.0/1.1/1.2 record layer.
*/
class RecordStream
{
private static int DEFAULT_PLAINTEXT_LIMIT = (1 << 14);
private final Record inputRecord = new Record();
private final SequenceNumber readSeqNo = new SequenceNumber(), writeSeqNo = new SequenceNumber();
private TlsProtocol handler;
private InputStream input;
private OutputStream output;
private TlsCipher pendingCipher = null;
private TlsCipher readCipher = TlsNullNullCipher.INSTANCE;
private TlsCipher readCipherDeferred = null;
private TlsCipher writeCipher = TlsNullNullCipher.INSTANCE;
private ProtocolVersion writeVersion = null;
private int plaintextLimit = DEFAULT_PLAINTEXT_LIMIT;
private int ciphertextLimit = DEFAULT_PLAINTEXT_LIMIT;
private boolean ignoreChangeCipherSpec = false;
RecordStream(TlsProtocol handler, InputStream input, OutputStream output)
{
this.handler = handler;
this.input = input;
this.output = output;
}
int getPlaintextLimit()
{
return plaintextLimit;
}
void setPlaintextLimit(int plaintextLimit)
{
this.plaintextLimit = plaintextLimit;
this.ciphertextLimit = readCipher.getCiphertextDecodeLimit(plaintextLimit);
}
void setWriteVersion(ProtocolVersion writeVersion)
{
this.writeVersion = writeVersion;
}
void setIgnoreChangeCipherSpec(boolean ignoreChangeCipherSpec)
{
this.ignoreChangeCipherSpec = ignoreChangeCipherSpec;
}
void setPendingCipher(TlsCipher tlsCipher)
{
this.pendingCipher = tlsCipher;
}
void notifyChangeCipherSpecReceived()
throws IOException
{
if (pendingCipher == null)
{
throw new TlsFatalAlert(AlertDescription.unexpected_message, "No pending cipher");
}
enablePendingCipherRead(false);
}
void enablePendingCipherRead(boolean deferred)
throws IOException
{
if (pendingCipher == null)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
if (readCipherDeferred != null)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
if (deferred)
{
this.readCipherDeferred = pendingCipher;
}
else
{
this.readCipher = pendingCipher;
this.ciphertextLimit = readCipher.getCiphertextDecodeLimit(plaintextLimit);
readSeqNo.reset();
}
}
void enablePendingCipherWrite()
throws IOException
{
if (pendingCipher == null)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
this.writeCipher = this.pendingCipher;
writeSeqNo.reset();
}
void finaliseHandshake()
throws IOException
{
if (readCipher != pendingCipher || writeCipher != pendingCipher)
{
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
this.pendingCipher = null;
}
boolean needsKeyUpdate()
{
return writeSeqNo.currentValue() >= (1L << 20);
}
void notifyKeyUpdateReceived() throws IOException
{
readCipher.rekeyDecoder();
readSeqNo.reset();
}
void notifyKeyUpdateSent() throws IOException
{
writeCipher.rekeyEncoder();
writeSeqNo.reset();
}
RecordPreview previewRecordHeader(byte[] recordHeader) throws IOException
{
short recordType = checkRecordType(recordHeader, RecordFormat.TYPE_OFFSET);
// ProtocolVersion recordVersion = TlsUtils.readVersion(recordHeader, RecordFormat.VERSION_OFFSET);
int length = TlsUtils.readUint16(recordHeader, RecordFormat.LENGTH_OFFSET);
checkLength(length, ciphertextLimit, AlertDescription.record_overflow);
int recordSize = RecordFormat.FRAGMENT_OFFSET + length;
int applicationDataLimit = 0;
// NOTE: For TLS 1.3, this only MIGHT be application data
if (ContentType.application_data == recordType && handler.isApplicationDataReady())
{
applicationDataLimit = Math.max(0, Math.min(plaintextLimit, readCipher.getPlaintextLimit(length)));
}
return new RecordPreview(recordSize, applicationDataLimit);
}
RecordPreview previewOutputRecord(int contentLength)
{
int contentLimit = Math.max(0, Math.min(plaintextLimit, contentLength));
int recordSize = previewOutputRecordSize(contentLimit);
return new RecordPreview(recordSize, contentLimit);
}
int previewOutputRecordSize(int contentLength)
{
// assert contentLength <= plaintextLimit
return RecordFormat.FRAGMENT_OFFSET + writeCipher.getCiphertextEncodeLimit(contentLength, plaintextLimit);
}
boolean readFullRecord(byte[] input, int inputOff, int inputLen)
throws IOException
{
if (inputLen < RecordFormat.FRAGMENT_OFFSET)
{
return false;
}
int length = TlsUtils.readUint16(input, inputOff + RecordFormat.LENGTH_OFFSET);
if (inputLen != (RecordFormat.FRAGMENT_OFFSET + length))
{
return false;
}
short recordType = checkRecordType(input, inputOff + RecordFormat.TYPE_OFFSET);
ProtocolVersion recordVersion = TlsUtils.readVersion(input, inputOff + RecordFormat.VERSION_OFFSET);
checkLength(length, ciphertextLimit, AlertDescription.record_overflow);
if (ignoreChangeCipherSpec && ContentType.change_cipher_spec == recordType)
{
checkChangeCipherSpec(input, inputOff + RecordFormat.FRAGMENT_OFFSET, length);
return true;
}
TlsDecodeResult decoded = decodeAndVerify(recordType, recordVersion, input,
inputOff + RecordFormat.FRAGMENT_OFFSET, length);
handler.processRecord(decoded.contentType, decoded.buf, decoded.off, decoded.len);
return true;
}
boolean readRecord()
throws IOException
{
if (!inputRecord.readHeader(input))
{
return false;
}
short recordType = checkRecordType(inputRecord.buf, RecordFormat.TYPE_OFFSET);
ProtocolVersion recordVersion = TlsUtils.readVersion(inputRecord.buf, RecordFormat.VERSION_OFFSET);
int length = TlsUtils.readUint16(inputRecord.buf, RecordFormat.LENGTH_OFFSET);
checkLength(length, ciphertextLimit, AlertDescription.record_overflow);
inputRecord.readFragment(input, length);
TlsDecodeResult decoded;
try
{
if (ignoreChangeCipherSpec && ContentType.change_cipher_spec == recordType)
{
checkChangeCipherSpec(inputRecord.buf, RecordFormat.FRAGMENT_OFFSET, length);
return true;
}
decoded = decodeAndVerify(recordType, recordVersion, inputRecord.buf, RecordFormat.FRAGMENT_OFFSET, length);
}
finally
{
inputRecord.reset();
}
handler.processRecord(decoded.contentType, decoded.buf, decoded.off, decoded.len);
return true;
}
TlsDecodeResult decodeAndVerify(short recordType, ProtocolVersion recordVersion, byte[] ciphertext, int off, int len)
throws IOException
{
long seqNo = readSeqNo.nextValue(AlertDescription.unexpected_message);
TlsDecodeResult decoded = readCipher.decodeCiphertext(seqNo, recordType, recordVersion, ciphertext, off, len);
checkLength(decoded.len, plaintextLimit, AlertDescription.record_overflow);
/*
* RFC 5246 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert,
* or ChangeCipherSpec content types.
*/
if (decoded.len < 1 && decoded.contentType != ContentType.application_data)
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
return decoded;
}
void writeRecord(short contentType, byte[] plaintext, int plaintextOffset, int plaintextLength)
throws IOException
{
// Never send anything until a valid ClientHello has been received
if (writeVersion == null)
{
return;
}
/*
* RFC 5246 6.2.1 The length should not exceed 2^14.
*/
checkLength(plaintextLength, plaintextLimit, AlertDescription.internal_error);
/*
* RFC 5246 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert,
* or ChangeCipherSpec content types.
*/
if (plaintextLength < 1 && contentType != ContentType.application_data)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
long seqNo = writeSeqNo.nextValue(AlertDescription.internal_error);
ProtocolVersion recordVersion = writeVersion;
TlsEncodeResult encoded = writeCipher.encodePlaintext(seqNo, contentType, recordVersion,
RecordFormat.FRAGMENT_OFFSET, plaintext, plaintextOffset, plaintextLength);
int ciphertextLength = encoded.len - RecordFormat.FRAGMENT_OFFSET;
TlsUtils.checkUint16(ciphertextLength);
TlsUtils.writeUint8(encoded.recordType, encoded.buf, encoded.off + RecordFormat.TYPE_OFFSET);
TlsUtils.writeVersion(recordVersion, encoded.buf, encoded.off + RecordFormat.VERSION_OFFSET);
TlsUtils.writeUint16(ciphertextLength, encoded.buf, encoded.off + RecordFormat.LENGTH_OFFSET);
try
{
output.write(encoded.buf, encoded.off, encoded.len);
}
catch (InterruptedIOException e)
{
throw new TlsFatalAlert(AlertDescription.internal_error, e);
}
output.flush();
}
void close() throws IOException
{
inputRecord.reset();
IOException io = null;
try
{
input.close();
}
catch (IOException e)
{
io = e;
}
try
{
output.close();
}
catch (IOException e)
{
if (io == null)
{
io = e;
}
else
{
// TODO[tls] Available from JDK 7
// io.addSuppressed(e);
}
}
if (io != null)
{
throw io;
}
}
private void checkChangeCipherSpec(byte[] buf, int off, int len)
throws IOException
{
if (1 != len || (byte)ChangeCipherSpec.change_cipher_spec != buf[off])
{
throw new TlsFatalAlert(AlertDescription.unexpected_message,
"Malformed " + ContentType.getText(ContentType.change_cipher_spec));
}
}
private short checkRecordType(byte[] buf, int off)
throws IOException
{
short recordType = TlsUtils.readUint8(buf, off);
if (null != readCipherDeferred && recordType == ContentType.application_data)
{
this.readCipher = readCipherDeferred;
this.readCipherDeferred = null;
this.ciphertextLimit = readCipher.getCiphertextDecodeLimit(plaintextLimit);
readSeqNo.reset();
}
else if (readCipher.usesOpaqueRecordType())
{
if (ContentType.application_data != recordType)
{
if (ignoreChangeCipherSpec && ContentType.change_cipher_spec == recordType)
{
// See RFC 8446 D.4.
}
else
{
throw new TlsFatalAlert(AlertDescription.unexpected_message,
"Opaque " + ContentType.getText(recordType));
}
}
}
else
{
switch (recordType)
{
case ContentType.application_data:
{
if (!handler.isApplicationDataReady())
{
throw new TlsFatalAlert(AlertDescription.unexpected_message,
"Not ready for " + ContentType.getText(ContentType.application_data));
}
break;
}
case ContentType.alert:
case ContentType.change_cipher_spec:
case ContentType.handshake:
// case ContentType.heartbeat:
break;
default:
throw new TlsFatalAlert(AlertDescription.unexpected_message,
"Unsupported " + ContentType.getText(recordType));
}
}
return recordType;
}
private static void checkLength(int length, int limit, short alertDescription)
throws IOException
{
if (length > limit)
{
throw new TlsFatalAlert(alertDescription);
}
}
private static class Record
{
private final byte[] header = new byte[RecordFormat.FRAGMENT_OFFSET];
volatile byte[] buf = header;
volatile int pos = 0;
void fillTo(InputStream input, int length) throws IOException
{
while (pos < length)
{
try
{
int numRead = input.read(buf, pos, length - pos);
if (numRead < 0)
{
break;
}
pos += numRead;
}
catch (InterruptedIOException e)
{
/*
* Although modifying the bytesTransferred doesn't seem ideal, it's the simplest
* way to make sure we don't break client code that depends on the exact type,
* e.g. in Apache's httpcomponents-core-4.4.9, BHttpConnectionBase.isStale
* depends on the exception type being SocketTimeoutException (or a subclass).
*
* We can set to 0 here because the only relevant callstack (via
* TlsProtocol.readApplicationData) only ever processes one non-empty record (so
* interruption after partial output cannot occur).
*/
pos += e.bytesTransferred;
e.bytesTransferred = 0;
throw e;
}
}
}
void readFragment(InputStream input, int fragmentLength) throws IOException
{
int recordLength = RecordFormat.FRAGMENT_OFFSET + fragmentLength;
resize(recordLength);
fillTo(input, recordLength);
if (pos < recordLength)
{
throw new EOFException();
}
}
boolean readHeader(InputStream input) throws IOException
{
fillTo(input, RecordFormat.FRAGMENT_OFFSET);
if (pos == 0)
{
return false;
}
if (pos < RecordFormat.FRAGMENT_OFFSET)
{
throw new EOFException();
}
return true;
}
void reset()
{
buf = header;
pos = 0;
}
private void resize(int length)
{
if (buf.length < length)
{
byte[] tmp = new byte[length];
System.arraycopy(buf, 0, tmp, 0, pos);
buf = tmp;
}
}
}
private static class SequenceNumber
{
private long value = 0L;
private boolean exhausted = false;
synchronized long currentValue()
{
return value;
}
synchronized long nextValue(short alertDescription) throws TlsFatalAlert
{
if (exhausted)
{
throw new TlsFatalAlert(alertDescription, "Sequence numbers exhausted");
}
long result = value;
if (++value == 0)
{
exhausted = true;
}
return result;
}
synchronized void reset()
{
this.value = 0L;
this.exhausted = false;
}
}
}
|
package me.devsaki.hentoid.json;
import androidx.annotation.NonNull;
import java.util.HashMap;
import java.util.Map;
public class JsonSettings {
private Map<String, Object> settings = new HashMap<>();
public JsonSettings() {
// Nothing special do to here
}
public Map<String, Object> getSettings() {
return settings;
}
public void setSettings(@NonNull Map<String, Object> settings) {
this.settings = settings;
}
}
|
package h2o.common.util.security;
import h2o.common.exception.ExceptionUtil;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAUtil {
private static final String KEY_ALGORITHM = "RSA";
private static final String SIGN_ALGORITHM = "SHA256withRSA";
private static byte[] decryptBASE64(String key) {
return new Base64Util().decode(key);
}
public static byte[] decryptByPrivateKey(byte[] data, String key) {
try {
byte[] keyBytes = decryptBASE64(key);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (Exception e) {
throw ExceptionUtil.toRuntimeException(e);
}
}
public static byte[] encryptByPublicKey(byte[] data, String key) {
try {
byte[] keyBytes = decryptBASE64(key);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (Exception e) {
throw ExceptionUtil.toRuntimeException(e);
}
}
public static byte[] signBySHA256WithRSA( byte[] content, String privateKey) {
try {
byte[] keyBytes = decryptBASE64(privateKey);
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(keyBytes);
PrivateKey priKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(priPKCS8);
Signature signature = Signature.getInstance(SIGN_ALGORITHM);
signature.initSign(priKey);
signature.update(content);
return signature.sign();
} catch (Exception e) {
throw ExceptionUtil.toRuntimeException(e);
}
}
public static boolean verifyBySHA256WithRSA( byte[] content, String publicKey , byte[] sign ) {
try {
byte[] keyBytes = decryptBASE64(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
PublicKey pubKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGN_ALGORITHM);
signature.initVerify(pubKey);
signature.update(content);
return signature.verify(sign);
} catch (Exception e) {
throw ExceptionUtil.toRuntimeException(e);
}
}
public static KeyPair makeKey(int keysize) {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(keysize);
KeyPair keyPair = keyPairGen.generateKeyPair();
// String pubkey = new Base64Util().encode( keyPair.getPublic().getEncoded() );//
// String prikey = new Base64Util().encode( keyPair.getPrivate().getEncoded() );//
return keyPair;
} catch (Exception e) {
throw ExceptionUtil.toRuntimeException(e);
}
}
}
|
package org.intermine.web.struts;
import java.util.Set;
/**
* Helper class to pass to JSP from TableController. (Was a static member of TableController but
* Tomcat 6 failed to access the get methods).
*
* @author Matthew Wakeling
*/
public class DisplayLookup
{
private int matches;
private Set<String> unresolved, duplicates, translated;
/**
* Create a new DisplayLookup object.
*
* @param matches the number of identifiers that matched useful objects
* @param unresolved a Set of the identifiers that did not match anything useful
* @param duplicates a Set of the identifiers that matched multiple useful objects
* @param translated a Set of the identifiers that only matched objects of the wrong type
*/
public DisplayLookup(int matches, Set<String> unresolved, Set<String> duplicates,
Set<String> translated) {
this.matches = matches;
this.unresolved = unresolved;
this.duplicates = duplicates;
this.translated = translated;
}
/**
* Returns the number of identifiers that matched useful objects.
*
* @return an int
*/
public int getMatches() {
return matches;
}
/**
* Returns a Set of the identifiers that did not match anything useful.
*
* @return a Set of Strings
*/
public Set<String> getUnresolved() {
return unresolved;
}
/**
* Returns a Set of the identifiers that matched more than one useful object.
*
* @return a Set of Strings
*/
public Set<String> getDuplicates() {
return duplicates;
}
/**
* Returns a Set of the identifiers that matched only objects of the wrong type.
*
* @return a Set of Strings
*/
public Set<String> getTranslated() {
return translated;
}
}
|
package ru.job4j.tracker;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
*
* @author Yury Vlasov
* @since 20.04.2017
* @version 1.0
*/
public class TrackerTest {
/**
* Test add.
*/
@Test
public void whenAddNewItemThenTrackerHasSameItem() {
Tracker tracker = new Tracker();
Item item = new Item("test1", "testDescription", 123L);
tracker.add(item);
assertThat(tracker.getAll()[0],is(item));
}
/**
* Test Delete.
*/
@Test
public void whenDeleteItemThenTrackerHasSameItem() {
Tracker tracker = new Tracker();
Item item1 = new Item("test1", "testDescription1", 1L);
Item item2 = new Item("test2", "testDescription2", 2L);
tracker.add(item1);
tracker.add(item2);
tracker.delete(item2.getId());
assertThat(tracker.getAll()[0],is(item1));
}
}
|
package be.kuleuven.cs.distrinet.rejuse.tree;
import java.util.List;
import be.kuleuven.cs.distrinet.rejuse.action.Action;
import be.kuleuven.cs.distrinet.rejuse.predicate.TypePredicate;
import be.kuleuven.cs.distrinet.rejuse.predicate.UniversalPredicate;
/**
* A TreeStructure provides a tree view on a data structure. The data structure itself
* can be anything, including a data structure with a different tree layout.
*
* By using this class, you sacrifice design for performance. In a purely object-oriented
* style, each node in the tree structure would have a reference to the object in the underlying data structure.
* Let us call such a tree structure a StatefulTreeStructure.
* This would have two advantages. First, we don't have to provide the data structure object
* as a parameter with each method. This makes it easier to use. Second, since not all
* tree structure objects in the tree may be of the same class, care must be taken that
* the data structure objects that is passed as an argument actually corresponds to
* that TreeStructure object. With a StatefulTreeStructure, nothing can go wrong since we don't
* have to pass the data structure object as an argument in the first place.
*
* But creating a StatefulTreeStructure object for each object in your data structure is
* more expensive than having a single (or a few) TreeStructure objects. When the
* data structure objects themselves keep a reference to the tree structure,
* this overhead may be tolerable. This could be the case when that particular tree structure
* is inherently present in the data structure. An example is the inheritance tree in a graph of
* persons. In other cases, however, we would either have to synchronize the StatefulTreeStructure
* objects with the underlying data structure, or create new StatefulTreeStructure objects on each use.
* For large data structures, this may become problematic.
*
*
* @author Marko van Dooren
*
* @param <T> The type of the node in the tree.
*/
public abstract class TreeStructure<T> {
/**
* Return the parent of the given node.
*
* @param node The node of which the parent is requested.
*/
/*@
@ public behavior
@
@ pre node != null;
@*/
public abstract T parent(T node);
public abstract List<? extends T> children(T element);
public abstract TreeStructure<T> tree(T element);
public <X extends T, E extends Exception> X nearestAncestor(T element, UniversalPredicate<X,E> predicate) throws E {
T el = parent(element);
while ((el != null) && (! predicate.eval((T)el))) {
el = tree(el).parent(el);
}
return (X) el;
}
public <X extends T, E extends Exception> X nearestAncestorOrSelf(T element, UniversalPredicate<X, E> predicate) throws E {
T el = element;
while ((el != null) && (! predicate.eval((T)el))) {
el = tree(el).parent(el);
}
return (X) el;
}
public <X extends T> X nearestAncestorOrSelf(T element, Class<X> c) {
T el = element;
while ((el != null) && (! c.isInstance(el))){
el = tree(el).parent(el);
}
return (X) el;
}
public boolean hasAncestorOrSelf(T element, T ancestor) {
T el = element;
while ((el != null) && (el != ancestor)){
el = tree(el).parent(el);
}
return el == ancestor;
}
public final <X extends T> List<X> descendants(T element, Class<X> c) {
List<X> result = children(element, c);
for (T e : children(element)) {
result.addAll(tree(e).descendants(e,c));
}
return result;
}
public final <X extends T> List<X> children(T element, Class<X> c) {
return new TypePredicate<X>(c).downCastedList(children(element));
}
public final <X extends T, E extends Exception> void apply(T element, Action<X,E> action) throws E {
if(action.type().isInstance(element)) {
action.perform((T)element);
}
for (T e : children(element)) {
tree(e).apply(e,action);
}
}
}
|
package io.hawt.web.auth;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.security.auth.Subject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import io.hawt.system.AuthHelpers;
import io.hawt.system.AuthenticateResult;
import io.hawt.system.Authenticator;
import io.hawt.system.ConfigManager;
import io.hawt.web.ServletHelpers;
import org.jolokia.converter.Converters;
import org.jolokia.converter.json.JsonConvertOptions;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Login servlet
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 187076436862364207L;
private static final transient Logger LOG = LoggerFactory.getLogger(LoginServlet.class);
private static final int DEFAULT_SESSION_TIMEOUT = 1800; // 30 mins
private Integer timeout = DEFAULT_SESSION_TIMEOUT;
private AuthenticationConfiguration authConfiguration;
private Converters converters = new Converters();
private JsonConvertOptions options = JsonConvertOptions.DEFAULT;
@Override
public void init() {
authConfiguration = AuthenticationConfiguration.getConfiguration(getServletContext());
setupSessionTimeout();
LOG.info("hawtio login is using {} HttpSession timeout", timeout != null ? timeout + " sec." : "default");
}
private void setupSessionTimeout() {
ConfigManager configManager = (ConfigManager) getServletContext().getAttribute("ConfigManager");
if (configManager == null) {
return;
}
String timeoutStr = configManager.get("sessionTimeout", Integer.toString(DEFAULT_SESSION_TIMEOUT));
if (timeoutStr == null) {
return;
}
try {
timeout = Integer.valueOf(timeoutStr);
// timeout of 0 means default timeout
if (timeout == 0) {
timeout = DEFAULT_SESSION_TIMEOUT;
}
} catch (Exception e) {
// ignore and use our own default of 1/2 hour
timeout = DEFAULT_SESSION_TIMEOUT;
}
}
/**
* GET simply returns login.html
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (authConfiguration.isKeycloakEnabled()) {
response.sendRedirect(request.getContextPath() + "/");
} else {
request.getRequestDispatcher("/login.html").forward(request, response);
}
}
/**
* POST with username/password tries authentication and returns result as JSON
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
clearSession(request);
JSONObject json = ServletHelpers.readObject(request.getReader());
String username = (String) json.get("username");
String password = (String) json.get("password");
AuthenticateResult result = Authenticator.authenticate(
authConfiguration, request, username, password,
subject -> {
setupSession(request, subject, username);
sendResponse(response, subject);
});
switch (result) {
case AUTHORIZED:
// response was sent using the authenticated subject, nothing more to do
break;
case NOT_AUTHORIZED:
case NO_CREDENTIALS:
ServletHelpers.doForbidden(response);
break;
}
}
private void clearSession(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
Subject subject = (Subject) session.getAttribute("subject");
if (subject != null) {
LOG.info("Logging out existing user: {}", AuthHelpers.getUsername(subject));
Authenticator.logout(authConfiguration, subject);
session.invalidate();
}
}
private void setupSession(HttpServletRequest request, Subject subject, String username) {
HttpSession session = request.getSession(true);
session.setAttribute("subject", subject);
session.setAttribute("user", username);
session.setAttribute("org.osgi.service.http.authentication.remote.user", username);
session.setAttribute("org.osgi.service.http.authentication.type", HttpServletRequest.BASIC_AUTH);
session.setAttribute("loginTime", GregorianCalendar.getInstance().getTimeInMillis());
if (timeout != null) {
session.setMaxInactiveInterval(timeout);
}
LOG.debug("Http session timeout for user {} is {} sec.", username, session.getMaxInactiveInterval());
}
private void sendResponse(HttpServletResponse response, Subject subject) {
response.setContentType("application/json");
try (PrintWriter out = response.getWriter()) {
Map<String, Object> answer = new HashMap<>();
List<Object> principals = new ArrayList<>();
for (Principal principal : subject.getPrincipals()) {
Map<String, String> data = new HashMap<>();
data.put("type", principal.getClass().getName());
data.put("name", principal.getName());
principals.add(data);
}
List<Object> credentials = new ArrayList<>();
for (Object credential : subject.getPublicCredentials()) {
Map<String, Object> data = new HashMap<>();
data.put("type", credential.getClass().getName());
data.put("credential", credential);
credentials.add(data);
}
answer.put("principals", principals);
answer.put("credentials", credentials);
ServletHelpers.writeObject(converters, options, out, answer);
} catch (IOException e) {
LOG.error("Failed to send response", e);
}
}
}
|
package org.intermine.web.struts;
import java.util.NoSuchElementException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.tiles.ComponentContext;
import org.intermine.api.InterMineAPI;
import org.intermine.api.bag.BagManager;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebResults;
import org.intermine.api.template.TemplateManager;
import org.intermine.api.template.TemplatePopulator;
import org.intermine.model.InterMineObject;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.template.TemplatePopulatorException;
import org.intermine.template.TemplateQuery;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.ReportObject;
import org.intermine.web.logic.results.ReportObjectFactory;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.template.TemplateHelper;
/**
* Action to handle events related to displaying inline templates.
*
* @author Mark Woodbridge
*/
public class ModifyDetails extends DispatchAction
{
private static final Logger LOG = Logger.getLogger(ModifyDetails.class);
/**
* Show in table for inline template queries.
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws an exception
*/
public ActionForward runTemplate(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
String name = request.getParameter("name");
String scope = request.getParameter("scope");
String bagName = request.getParameter("bagName");
String idForLookup = request.getParameter("idForLookup");
Profile profile = SessionMethods.getProfile(session);
TemplateManager templateManager = im.getTemplateManager();
TemplateQuery template = templateManager.getTemplate(profile, name, scope);
BagManager bagManager = im.getBagManager();
InterMineBag bag = bagManager.getUserOrGlobalBag(profile, bagName);
TemplateQuery populatedTemplate;
try {
if (idForLookup != null && idForLookup.length() != 0) {
Integer objectId = new Integer(idForLookup);
ObjectStore os = im.getObjectStore();
InterMineObject object = os.getObjectById(objectId);
template = TemplateHelper.removeDirectAttributesFromView(template);
populatedTemplate = TemplatePopulator.populateTemplateWithObject(template, object);
} else {
populatedTemplate = TemplatePopulator.populateTemplateWithBag(template, bag);
}
} catch (TemplatePopulatorException e) {
LOG.error("Error running up template '" + template.getName() + "' from report page for"
+ ((idForLookup == null) ? " bag " + bagName
: " object " + idForLookup) + ".", e);
throw new RuntimeException("Error running up template '" + template.getName()
+ "' from report page for" + ((idForLookup == null) ? " bag " + bagName
: " object " + idForLookup) + ".", e);
}
String identifier = "itt." + populatedTemplate.getName() + "." + idForLookup;
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
WebResults webResults = executor.execute(populatedTemplate);
PagedTable pagedResults = new PagedTable(webResults, 10);
SessionMethods.setResultsTable(session, identifier, pagedResults);
// add results table to trail
String trail = request.getParameter("trail");
if (trail != null) {
trail += "|results." + identifier;
} else {
trail = "|results." + identifier;
}
return new ForwardParameters(mapping.findForward("results"))
.addParameter("templateQueryTitle", template.getTitle())
.addParameter("templateQueryDescription",
(template.getDescription() != null) ? template.getDescription() : "")
.addParameter("table", identifier).addParameter("trail", trail).forward();
}
/**
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws an exception
* @deprecated ajaxVerbosify is used instead
*/
@Deprecated
public ActionForward verbosify(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
if (session == null) {
return null;
}
//String fieldName = request.getParameter("field");
String trail = request.getParameter("trail");
//String placement = request.getParameter("placement");
ReportObject object = getReportObject(session, request.getParameter("id"));
if (object != null) {
//object.setVerbosity(placement + "_" + fieldName, true);
}
return forwardToReport(mapping, request.getParameter("id"), trail);
}
/**
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws an exception
* @deprecated ajaxVerbosify is used instead
*/
@Deprecated
public ActionForward unverbosify(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
//HttpSession session = request.getSession();
//String fieldName = request.getParameter("field");
String trail = request.getParameter("trail");
//String placement = request.getParameter("placement");
//ReportObject object = getReportObject(session, request.getParameter("id"));
//object.setVerbosity(placement + "_" + fieldName, false);
return forwardToReport(mapping, request.getParameter("id"), trail);
}
/**
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws an exception
*/
public ActionForward ajaxVerbosify(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String fieldName = request.getParameter("field");
String trail = request.getParameter("trail");
//String placement = request.getParameter("placement");
ReportObject object = getReportObject(session, request.getParameter("id"));
Object collection = object.getRefsAndCollections().get(fieldName);
//String key = placement + "_" + fieldName;
//object.setVerbosity(key, !object.isVerbose(key));
request.setAttribute("object", object);
request.setAttribute("trail", trail);
request.setAttribute("collection", collection);
request.setAttribute("fieldName", fieldName);
//if (object.isVerbose(key)) {
// return mapping.findForward("reportCollectionTable");
return null;
}
/**
* Count number of results for a template for inline templates
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws an exception
*/
public ActionForward ajaxTemplateCount(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
String type = request.getParameter("type");
String id = request.getParameter("id");
String templateName = request.getParameter("template");
String detailsType = request.getParameter("detailsType");
ObjectStore os = im.getObjectStore();
TemplateManager templateManager = im.getTemplateManager();
TemplateQuery tq = templateManager.getTemplate(profile, templateName, type);
ComponentContext cc = new ComponentContext();
if ("object".equals(detailsType)) {
InterMineObject o = os.getObjectById(new Integer(id));
ReportObjectFactory reportObjects = SessionMethods.getReportObjects(session);
ReportObject obj = reportObjects.get(o);
cc.putAttribute("reportObject", obj);
cc.putAttribute("templateQuery", tq);
cc.putAttribute("placement", request.getParameter("placement"));
try {
new ReportTemplateController().execute(cc, mapping, form, request, response);
} catch (NoSuchElementException e) {
// TODO: happening on metabolicMine im:aspect:Pathways_Gene_Pathway
}
request.setAttribute("org.apache.struts.taglib.tiles.CompContext", cc);
return mapping.findForward("reportTemplateTable");
}
BagManager bagManager = im.getBagManager();
InterMineBag interMineBag = bagManager.getUserOrGlobalBag(profile, id);
cc.putAttribute("interMineIdBag", interMineBag);
cc.putAttribute("templateQuery", tq);
cc.putAttribute("placement", request.getParameter("placement"));
new ReportTemplateController().execute(cc, mapping, form, request, response);
request.setAttribute("org.apache.struts.taglib.tiles.CompContext", cc);
return mapping.findForward("reportTemplateTable");
}
/**
* Construct an ActionForward to the object details page.
*/
private ActionForward forwardToReport(ActionMapping mapping, String id, String trail) {
ForwardParameters forward = new ForwardParameters(mapping.findForward("report"));
forward.addParameter("id", id);
forward.addParameter("trail", trail);
return forward.forward();
}
/**
* Get a ReportObject from the session given the object id as a string.
*
* @param session the current http session
* @param idString intermine object id
* @return ReportObject for the intermine object
*/
protected ReportObject getReportObject(HttpSession session, String idString) {
ObjectStore os = SessionMethods.getInterMineAPI(session).getObjectStore();
InterMineObject obj = null;
try {
obj = os.getObjectById(new Integer(idString));
} catch (ObjectStoreException e) {
LOG.error("Exception while fetching object with id " + idString, e);
}
if (obj == null) {
LOG.error("Could not find object with id " + idString);
return null;
}
ReportObjectFactory reportObjects = SessionMethods.getReportObjects(session);
ReportObject retval = reportObjects.get(obj);
if (retval == null) {
LOG.error("Could not find ReportObject on session for id " + idString);
}
return retval;
}
}
|
package com.groupon.seleniumgridextras.tasks;
import com.google.gson.JsonObject;
import com.groupon.seleniumgridextras.OSChecker;
import com.groupon.seleniumgridextras.os.LinuxSystemInfo;
import com.groupon.seleniumgridextras.os.MacSystemInfo;
import com.groupon.seleniumgridextras.os.OSInfo;
import com.groupon.seleniumgridextras.os.WindowsSystemInfo;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class SystemInfo extends ExecuteOSTask {
public SystemInfo() {
setEndpoint("/system");
setDescription("Returns system details about the current node");
JsonObject params = new JsonObject();
setAcceptedParams(params);
setRequestType("GET");
setResponseType("json");
setClassname(this.getClass().getCanonicalName().toString());
setCssClass("btn-info");
setButtonText("System Info");
setEnabledInGui(true);
addResponseDescription("drives", "Hash of all mounted drives and their info");
addResponseDescription("processor", "Info about processors on machine");
addResponseDescription("ram", "Info in bytes on how much RAM machine has/uses");
addResponseDescription("uptime", "System uptime since last reboot in seconds");
addResponseDescription("hostname", "Host name");
addResponseDescription("ip", "Host ip");
}
@Override
public JsonObject execute() {
try {
OSInfo info;
if (OSChecker.isWindows()) {
info = new WindowsSystemInfo();
} else if (OSChecker.isMac()) {
info = new MacSystemInfo();
} else {
info = new LinuxSystemInfo();
}
getJsonResponse().addListOfHashes("drives", info.getDiskInfo());
getJsonResponse().addKeyValues("processor", info.getProcessorInfo());
getJsonResponse().addKeyValues("ram", info.getMemoryInfo());
getJsonResponse().addKeyValues("uptime", info.getSystemUptime());
} catch (Exception e) {
getJsonResponse().addKeyValues("error", e.toString());
}
List<String> hostNetworking = getComputerNetworkInfo();
getJsonResponse().addKeyValues("hostname", hostNetworking.get(0));
getJsonResponse().addKeyValues("ip", hostNetworking.get(1));
return getJsonResponse().getJson();
}
@Override
public JsonObject execute(Map<String, String> parameter) {
return execute();
}
private List<String> getComputerNetworkInfo() {
List<String> host = new LinkedList<String>();
try {
InetAddress addr;
addr = InetAddress.getLocalHost();
host.add(addr.getHostName());
host.add(addr.getHostAddress());
} catch (UnknownHostException ex) {
System.out.println("Hostname can not be resolved");
host.add("N/A");
host.add("N/A");
}
return host;
}
}
|
package ch.unizh.ini.jaer.projects.npp;
import com.jogamp.opengl.GLAutoDrawable;
import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ProgressMonitor;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.util.avioutput.DvsSliceAviWriter;
/**
* Incremental Roshambo learning demo
*
* @author Tobi Delbruck/Iulia Lungu
*/
@Description("Incremental learning demo for Roshambo + other finger gestures; subclass of DavisDeepLearnCnnProcessor")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class RoShamBoIncremental extends RoShamBoCNN {
private DvsSliceAviWriter aviWriter = null;
private Path lastSymbolsPath = Paths.get(getString("lastSymbolsPath", ""));
// private DatagramChannel channel = null;
private DatagramSocket sendToSocket = null, listenOnSocket = null;
private InetSocketAddress client = null;
private String host = getString("hostname", "localhost");
public static final int DEFAULT_SENDTO_PORT = 14334;
public static final int DEFAULT_LISTENON_PORT = 14335;
private int portSendTo = getInt("portSendTo", DEFAULT_SENDTO_PORT);
private int portListenOn = getInt("portListenOn", DEFAULT_LISTENON_PORT);
private static final String CMD_NEW_SYMBOL_AVAILABLE = "newsymbol", CMD_PROGRESS = "progress", CMD_LOAD_NETWORK = "loadnetwork", CMD_CANCEL = "cancel";
private Thread portListenerThread = null;
private ProgressMonitor progressMonitor = null;
private String lastNewClassName=getString("lastNewClassName","");
public RoShamBoIncremental(AEChip chip) {
super(chip);
String learn = "0. Incremental learning";
setPropertyTooltip(learn, "LearnNewClass", "Toggle collecting symbol data");
setPropertyTooltip(learn, "ChooseSamplesFolder", "Choose a folder to store the symbol AVI data files");
setPropertyTooltip(learn, "hostname", "learning host name (IP or DNS)");
setPropertyTooltip(learn, "portSendTo", "learning host port number that we send to");
setPropertyTooltip(learn, "portListenOn", "local port number we listen on to get message back from learning server");
aviWriter = new DvsSliceAviWriter(chip);
aviWriter.setEnclosed(true, this);
aviWriter.setFrameRate(60);
aviWriter.getDvsFrame().setOutputImageHeight(64);
aviWriter.getDvsFrame().setOutputImageWidth(64);
getEnclosedFilterChain().add(aviWriter);
}
public void doChooseSamplesFolder() {
JFileChooser c = new JFileChooser(lastSymbolsPath.toFile());
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.setDialogTitle("Choose folder to store symbol AVIs");
c.setApproveButtonText("Select");
c.setApproveButtonToolTipText("Selects a folder to store AVIs");
int ret = c.showOpenDialog(chip.getFilterFrame());
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastSymbolsPath = Paths.get(c.getSelectedFile().toString());
putString("lastSymbolsPath", lastSymbolsPath.toString());
}
private void closeSymbolFileAndSendMessage() {
log.info("stopping sample recording, starting training");
aviWriter.doCloseFile(); // saves tmpfile.avi
String newname=JOptionPane.showInputDialog(chip.getFilterFrame(), "Class name for this sample (e.g. thumbsup or peace)?", lastNewClassName);
if(newname==null){
try {
// user canceled, delete the file
Files.delete(aviWriter.getFile().toPath());
} catch (IOException ex) {
log.warning("could not delete the AVI file "+aviWriter.getFile()+": "+ex.toString());
}
return;
}
Path source=aviWriter.getFile().toPath(), dest=source.resolveSibling(newname+".avi");
try {
Files.move(source, dest);
sendUDPMessage(CMD_NEW_SYMBOL_AVAILABLE + " " + dest.toString());
} catch (IOException ex) {
Logger.getLogger(RoShamBoIncremental.class.getName()).log(Level.WARNING, null, ex);
}
}
private void openSymbolFileAndStartRecording(String prefix) {
log.info("recording symbol");
aviWriter.openAVIOutputStream(lastSymbolsPath.resolve(prefix + ".avi").toFile(), new String[]{"# " + prefix});
}
public void doToggleOnLearnNewClass() {
openSymbolFileAndStartRecording("tmpfile");
}
public void doToggleOffLearnNewClass() {
closeSymbolFileAndSendMessage();
}
public String getHostname() {
return host;
}
/**
* You need to setHost before this will send events.
*
* @param host the host
*/
synchronized public void setHostname(String host) {
this.host = host;
// if ( checkClient() ){
putString("hostname", host);
// }else{
// log.warning("checkClient() returned false, not storing "+host+" in preferences");
}
public int getPortSendTo() {
return portSendTo;
}
/**
* You set the port to say which port the packet will be sent to.
*
* @param portSendTo the UDP port number.
*/
public void setPortSendTo(int portSendTo) {
this.portSendTo = portSendTo;
putInt("portSendTo", portSendTo);
}
/**
* @return the listenOnPort
*/
public int getPortListenOn() {
return portListenOn;
}
/**
* @param portListenOn the listenOnPort to set
*/
public void setPortListenOn(int portListenOn) {
this.portListenOn = portListenOn;
putInt("portListenOn", portListenOn);
}
private void parseMessage(String msg) {
log.info("parsing message \"" + msg + "\"");
if (msg == null) {
log.warning("got null message");
return;
}
StringTokenizer tokenizer = new StringTokenizer(msg);
switch (tokenizer.nextToken()) {
case CMD_NEW_SYMBOL_AVAILABLE:
log.warning("learning server should not send this message; it is for us to send");
return;
case CMD_LOAD_NETWORK:
String networkFilename = tokenizer.nextToken();
if (networkFilename == null || networkFilename.isEmpty()) {
log.warning("null filename supplied for new network");
return;
}
synchronized (RoShamBoIncremental.this) { // sync on outter class, not thread we are running in
try {
log.info("loading new CNN from " + networkFilename);
loadNetwork(new File(networkFilename));
} catch (Exception e) {
log.log(Level.SEVERE, "Exception loading new network", e);
}
}
break;
case CMD_PROGRESS:
try {
int progress = Integer.parseInt(tokenizer.nextToken());
if (progressMonitor == null || progressMonitor.isCanceled()) {
progressMonitor = new ProgressMonitor(chip.getFilterFrame(), "Training", "note", 0, 100);
}
progressMonitor.setProgress(progress);
progressMonitor.setNote(String.format("%d%%", progress));
if (progress >= 100) {
synchronized (RoShamBoIncremental.this) {// sync on outter class, not thread we are running in
// we progressMonitor this in annotate (running in EDT thread) to see we should send cancel message
progressMonitor = null;
}
}
} catch (Exception e) {
log.warning("exception updating progress monitor: " + e.toString());
}
break;
default:
log.warning("unknown token or comamnd in message \"" + msg + "\"");
}
}
synchronized private void sendUDPMessage(String string) { // sync for thread safety on multiple senders
if (portListenerThread == null || !portListenerThread.isAlive() || listenOnSocket == null) { // start a thread to get messages from client
log.info("starting thread to listen for UDP datagram messages on port " + portListenOn);
portListenerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
listenOnSocket = new DatagramSocket(portListenOn);
} catch (SocketException ex) {
log.warning("could not open local port for listening for learning server messages on port " + portListenOn + ": " + ex.toString());
return;
}
while (true) {
try {
byte[] buf = new byte[1024];
DatagramPacket datagram = new DatagramPacket(buf, buf.length);
listenOnSocket.receive(datagram);
String msg = new String(datagram.getData());
log.info("got message:" + msg);
parseMessage(msg);
} catch (IOException ex) {
log.warning("stopping thread; exception in recieving message: " + ex.toString());
break;
}
}
}
}, "RoShamBoIncremental Listener");
portListenerThread.start();
}
log.info(String.format("sending message to host=%s port=%s string=\"%s\"", host, portSendTo, string));
if (sendToSocket == null) {
try {
log.info("opening socket to send datagrams from");
client = new InetSocketAddress(host, portSendTo); // get address for remote client
sendToSocket = new DatagramSocket(); // make a local socket using any port, will be used to send datagrams to the host/sendToPort
} catch (IOException ex) {
log.warning(String.format("cannot open socket to send to host=%s port=%d, got exception %s", host, portSendTo, ex.toString()));
return;
}
}
try {
byte[] buf = string.getBytes();
DatagramPacket datagram = new DatagramPacket(buf, buf.length, client.getAddress(), portSendTo); // construct datagram to send to host/sendToPort
sendToSocket.send(datagram);
} catch (IOException ex) {
log.warning("cannot send message " + ex.toString());
return;
}
}
@Override
public void annotate(GLAutoDrawable drawable) {
super.annotate(drawable);
synchronized (this) {
if (progressMonitor != null && progressMonitor.isCanceled()) {
sendUDPMessage(CMD_CANCEL);
}
}
}
}
|
package io.spine.client;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Message;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.protobuf.util.FieldMaskUtil.fromStringList;
import static io.spine.client.FilterFactory.all;
import static io.spine.client.Targets.composeTarget;
import static java.util.Arrays.asList;
import static java.util.Collections.singleton;
/**
* An abstract base for builders that create {@link com.google.protobuf.Message Message instances}
* which have a {@link Target} and a {@link FieldMask} as attributes.
*
* <p>The {@link Target} matching the builder configuration is created with {@link #buildTarget()},
* while the {@link FieldMask} is composed with {@link #composeMask()}.
*
* <p>The public API of this class is inspired by the SQL syntax.
* <pre>
* {@code
* select(Customer.class) // returning <AbstractTargetBuilder> descendant instance
* .byId(getWestCoastCustomerIds())
* .withMask("name", "address", "email")
* .where(eq("type", "permanent"),
* eq("discountPercent", 10),
* eq("companySize", Company.Size.SMALL))
* }
* </pre>
*
* <p>Calling any of the builder methods overrides the previous call of the given method or
* any of its overloads. For example, calling sequentially
* <pre>
* {@code
* builder.withMask(mask1)
* .withMask(mask2)
* // optionally some other invocations
* .withMask(mask3)
* .build();
* }
* </pre>
* is equivalent to calling
* <pre>
* {@code
* builder.withMask(mask3)
* .build();
* }
* </pre>
*
* @param <T>
* a type of the message which is returned by the implementations {@link #build()}
* @param <B>
* a type of the builder implementations
*/
abstract class AbstractTargetBuilder<T extends Message, B extends AbstractTargetBuilder> {
private final Class<? extends Message> targetType;
/*
All the optional fields are initialized only when and if set.
The empty collections make effectively no influence, but null values allow us to create
the query `Target` more efficiently.
*/
private @Nullable Set<?> ids;
private @Nullable Set<CompositeFilter> columns;
private @Nullable Set<String> fieldMask;
AbstractTargetBuilder(Class<? extends Message> targetType) {
this.targetType = checkNotNull(targetType);
}
/**
* Creates a new {@link io.spine.client.Target Target} based on the current builder
* configuration.
*
* @return a new {@link io.spine.client.Query Query} or {@link io.spine.client.Topic Topic}
* target
*/
Target buildTarget() {
return composeTarget(targetType, ids, columns);
}
@Nullable FieldMask composeMask() {
if (fieldMask == null || fieldMask.isEmpty()) {
return null;
}
FieldMask mask = fromStringList(null, ImmutableList.copyOf(fieldMask));
return mask;
}
/**
* Sets the ID predicate to the {@link io.spine.client.Query}.
*
* <p>Though it's not prohibited at compile-time, please make sure to pass instances of the
* same type to the argument of this method. Moreover, the instances must be of the type of
* the query target type identifier.
*
* <p>This method or any of its overloads do not check these
* constrains an assume they are followed by the caller.
*
* <p>If there are no IDs (i.e. and empty {@link Iterable} is passed), the query retrieves all
* the records regardless their IDs.
*
* @param ids
* the values of the IDs to look up
* @return self for method chaining
*/
public B byId(Iterable<?> ids) {
checkNotNull(ids);
this.ids = ImmutableSet.copyOf(ids);
return self();
}
/**
* Sets the ID predicate to the {@link io.spine.client.Query}.
*
* @param ids
* the values of the IDs to look up
* @return self for method chaining
* @see #byId(Iterable)
*/
public B byId(Message... ids) {
this.ids = ImmutableSet.copyOf(ids);
return self();
}
/**
* Sets the ID predicate to the {@link io.spine.client.Query}.
*
* @param ids
* the values of the IDs to look up
* @return self for method chaining
* @see #byId(Iterable)
*/
public B byId(String... ids) {
this.ids = ImmutableSet.copyOf(ids);
return self();
}
/**
* Sets the ID predicate to the {@link io.spine.client.Query}.
*
* @param ids
* the values of the IDs to look up
* @return self for method chaining
* @see #byId(Iterable)
*/
public B byId(Integer... ids) {
this.ids = ImmutableSet.copyOf(ids);
return self();
}
/**
* Sets the ID predicate to the {@link io.spine.client.Query}.
*
* @param ids
* the values of the IDs to look up
* @return self for method chaining
* @see #byId(Iterable)
*/
public B byId(Long... ids) {
this.ids = ImmutableSet.copyOf(ids);
return self();
}
/**
* Sets the Entity Column predicate to the {@link io.spine.client.Query}.
*
* <p>If there are no {@link io.spine.client.Filter}s (i.e. the passed array is empty),
* all
* the records will be retrieved regardless the Entity Columns values.
*
* <p>The multiple parameters passed into this method are considered to be joined in
* a conjunction ({@link io.spine.client.CompositeFilter.CompositeOperator#ALL ALL}
* operator), i.e.
* a record matches this query only if it matches all of these parameters.
*
* @param predicate
* the {@link io.spine.client.Filter}s to filter the requested entities by
* @return self for method chaining
* @see io.spine.client.Filters for a convenient way to create {@link io.spine.client.Filter}
* instances
* @see #where(io.spine.client.CompositeFilter...)
*/
public B where(Filter... predicate) {
CompositeFilter aggregatingFilter = all(asList(predicate));
columns = singleton(aggregatingFilter);
return self();
}
/**
* Sets the Entity Column predicate to the {@link io.spine.client.Query}.
*
* <p>If there are no {@link io.spine.client.Filter}s (i.e. the passed array is empty),
* all the records will be retrieved regardless the Entity Columns values.
*
* <p>The input values represent groups of {@linkplain io.spine.client.Filter column
* filters} joined with
* a {@linkplain io.spine.client.CompositeFilter.CompositeOperator composite operator}.
*
* <p>The input filter groups are effectively joined between each other by
* {@link io.spine.client.CompositeFilter.CompositeOperator#ALL ALL} operator, i.e. a
* record matches
* this query if it matches all the composite filters.
*
* <p>Example of usage:
* <pre>
* {@code
* factory.select(Customer.class)
* // Possibly other parameters
* .where(all(ge("companySize", 50), le("companySize", 1000)),
* either(gt("establishedTime", twoYearsAgo), eq("country", "Germany")))
* .build();
* }
* </pre>
*
* <p>In the example above, the {@code Customer} records match the built query if they
* represent
* companies that have their company size between 50 and 1000 employees and either have been
* established less than two years ago, or originate from Germany.
*
* <p>Note that the filters which belong to different {@link io.spine.client.FilterFactory#all
* all(...)} groups
* may be represented as a single {@link io.spine.client.FilterFactory#all all(...)} group. For
* example, two
* following queries would be identical:
* <pre>
* {@code
* // Option 1
* factory.select(Customer.class)
* .where(all(
* eq("country", "Germany")),
* all(
* ge("companySize", 50),
* le("companySize", 100)))
* .build();
*
* // Option 2 (identical)
* factory.select(Customer.class)
* .where(all(
* eq("country", "Germany"),
* ge("companySize", 50),
* le("companySize", 100)))
* .build();
* }
* </pre>
*
* <p>The {@code Option 1} is recommended in this case, since the filters are grouped
* logically,
* though both builders produce effectively the same {@link io.spine.client.Query} instances.
* Note, that
* those instances may not be equal in terms of {@link Object#equals(Object)} method.
*
* @param predicate
* a number of {@link io.spine.client.CompositeFilter} instances forming the query
* predicate
* @return self for method chaining
* @see io.spine.client.Filters for a convinient way to create {@link
* io.spine.client.CompositeFilter} instances
*/
public B where(CompositeFilter... predicate) {
columns = ImmutableSet.copyOf(predicate);
return self();
}
/**
* Sets the entity fields to retrieve.
*
* <p>The names of the fields must be formatted according to the {@link FieldMask}
* specification.
*
* <p>If there are no fields (i.e. an empty {@link Iterable} is passed), all the fields will
* be retrieved.
*
* @param fieldNames
* the fields to query
* @return self for method chaining
*/
public B withMask(Iterable<String> fieldNames) {
checkNotNull(fieldNames);
this.fieldMask = ImmutableSet.copyOf(fieldNames);
return self();
}
/**
* Sets the entity fields to retrieve.
*
* <p>The names of the fields must be formatted according to the {@link FieldMask}
* specification.
*
* <p>If there are no fields (i.e. an empty array is passed), all the fields will
* be retrieved.
*
* @param fieldNames
* the fields to query
* @return self for method chaining
*/
public B withMask(String... fieldNames) {
this.fieldMask = ImmutableSet.<String>builder()
.add(fieldNames)
.build();
return self();
}
public abstract T build();
@Override
public String toString() {
return queryString();
}
@SuppressWarnings("MethodWithMoreThanThreeNegations")
// OK for this method as it's used primarily for debugging
private String queryString() {
String valueSeparator = "; ";
StringBuilder sb = new StringBuilder();
Class<? extends AbstractTargetBuilder> builderCls = self().getClass();
sb.append(builderCls.getSimpleName())
.append('(')
.append("SELECT ")
.append(fieldMask == null || fieldMask.isEmpty() ? '*' : fieldMask)
.append(" FROM ")
.append(targetType.getSimpleName())
.append(" WHERE (");
if (ids != null && !ids.isEmpty()) {
sb.append("id IN ")
.append(ids)
.append(valueSeparator);
}
if (columns != null && !columns.isEmpty()) {
sb.append("AND columns: ")
.append(columns);
}
sb.append(");");
return sb.toString();
}
/**
* A typed instance of current Builder.
*
* @return {@code this} with the required compile-time type
*/
abstract B self();
}
|
package de.codecentric.selenium;
import static org.junit.Assert.assertTrue;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
@Ignore
public class OpenSpaceSessionsPageTest extends AbstractPageTest {
private String pageLink = "/allSessions";
@Test
public void openPageAndValidateTitle() {
open(pageLink);
assertTrue("Page title does not match", PAGE_TITLE.equalsIgnoreCase(driver.getTitle()));
}
@Test
public void openCurrentSessionsPage() {
open(pageLink);
WebElement title = driver.findElement(By.id("title"));
assertTrue(title.isDisplayed());
}
}
|
package com.thoughtworks.acceptance;
import com.thoughtworks.acceptance.someobjects.X;
import com.thoughtworks.xstream.alias.CannotResolveClassException;
/**
* @author Paul Hammant
*/
public class AliasTest extends AbstractAcceptanceTest {
public void testBarfsIfAliasDoesNotExist() {
String xml = "" +
"<X-array>\n" +
" <X>\n" +
" <anInt>0</anInt>\n" +
" </X>\n" +
"</X-array>";
// now change the alias
xstream.alias("Xxxxxxxx", X.class);
try {
xstream.fromXML(xml);
fail("ShouldCannotResolveClassException expected");
} catch (CannotResolveClassException expectedException) {
// expected
}
}
public void testAliasWithUnderscore() {
String xml = "" +
"<X_alias>\n" +
" <anInt>0</anInt>\n" +
"</X_alias>";
// now change the alias
xstream.alias("X_alias", X.class);
X x = new X(0);
try {
assertBothWays(x, xml);
fail("CannotResolveClassException expected");
} catch (CannotResolveClassException e) {
//expected - marshalling works but not unmarshalling
}
}
}
|
package com.thoughtworks.acceptance;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
public class SwingTest extends AbstractAcceptanceTest {
// JTable is one of the nastiest components to serialize. If this works, we're in good shape :)
public void testJTable() {
// Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
JTable original = new JTable();
String originalXml = xstream.toXML(original);
JTable deserialized = (JTable) xstream.fromXML(originalXml);
String deserializedXml = xstream.toXML(deserialized);
assertEquals(originalXml, deserializedXml);
}
public void testDefaultListModel() {
final DefaultListModel original = new DefaultListModel();
final JList list = new JList();
list.setModel(original);
String originalXml = xstream.toXML(original);
DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
String deserializedXml = xstream.toXML(deserialized);
assertEquals(originalXml, deserializedXml);
list.setModel(deserialized);
}
}
|
package ru.stqa.pft.sandbox;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PointTests {
@Test
public void test1(){
Point p1 = new Point(0,0);
Point p2 = new Point(0,0);
Assert.assertEquals(p1.distance(p2),0.0);
}
@Test
public void test2(){
Point p1 = new Point(0,1);
Point p2 = new Point(0,4);
Assert.assertEquals(p1.distance(p2),4.0);
}
@Test
public void test3(){
Point p1 = new Point(1,1);
Point p2 = new Point(-1,-1);
Assert.assertEquals(p1.distance(p2),2.8284271247461903);
}
@Test
public void test4(){
Point p1 = new Point(-1,1);
Point p2 = new Point(1,-1);
Assert.assertEquals(p1.distance(p2),2.8284271247461903);
}
@Test
public void test5(){
Point p1 = new Point(-7,-7);
Point p2 = new Point(0,0);
Assert.assertEquals(p1.distance(p2),9.899494936611665);
}
}
|
package org.jetel.ctl.extensions;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.jetel.ctl.Stack;
import org.jetel.ctl.TransformLangExecutorRuntimeException;
import org.jetel.ctl.data.DateFieldEnum;
import org.jetel.util.DataGenerator;
import org.jetel.util.MiscUtils;
import org.jetel.util.date.DateFormatter;
import org.jetel.util.date.DateFormatterFactory;
public class DateLib extends TLFunctionLibrary {
@Override
public TLFunctionPrototype getExecutable(String functionName) {
final TLFunctionPrototype ret =
"dateDiff".equals(functionName) ? new DateDiffFunction() :
"dateAdd".equals(functionName) ? new DateAddFunction() :
"today".equals(functionName) ? new TodayFunction() :
"zeroDate".equals(functionName) ? new ZeroDateFunction() :
"extractDate".equals(functionName) ? new ExtractDateFunction() :
"extractTime".equals(functionName) ? new ExtractTimeFunction() :
"trunc".equals(functionName) ? new TruncFunction() :
"truncDate".equals(functionName)? new TruncDateFunction() :
"randomDate".equals(functionName) ? new RandomDateFunction() : null;
if (ret == null) {
throw new IllegalArgumentException("Unknown function '" + functionName + "'");
}
return ret;
}
@TLFunctionAnnotation("Returns current date and time.")
public static final Date today(TLFunctionCallContext context) {
return new Date();
}
// TODAY
class TodayFunction implements TLFunctionPrototype {
public void init(TLFunctionCallContext context) {
}
public void execute(Stack stack, TLFunctionCallContext context) {
stack.push(today(context));
}
}
// DATEADD
class DateAddFunction implements TLFunctionPrototype {
public void init(TLFunctionCallContext context) {
dateAddInit(context);
}
public void execute(Stack stack, TLFunctionCallContext context) {
final DateFieldEnum unit = (DateFieldEnum)stack.pop();
final Integer shift = stack.popInt();
final Date lhs = stack.popDate();
stack.push(dateAdd(context, lhs,shift,unit));
}
}
@TLFunctionInitAnnotation
public static final void dateAddInit(TLFunctionCallContext context) {
context.setCache(new TLCalendarCache());
}
@TLFunctionAnnotation("Adds to a component of a date (e.g. month)")
public static final Date dateAdd(TLFunctionCallContext context, Date lhs, Integer shift, DateFieldEnum unit) {
Calendar c = ((TLCalendarCache)context.getCache()).getCalendar();
c.setTime(lhs);
c.add(unit.asCalendarField(),shift);
return c.getTime();
}
// DATEDIFF
class DateDiffFunction implements TLFunctionPrototype {
public void init(TLFunctionCallContext context) {
dateDiffInit(context);
}
public void execute(Stack stack, TLFunctionCallContext context) {
final DateFieldEnum unit = (DateFieldEnum)stack.pop();
final Date rhs = stack.popDate();
final Date lhs = stack.popDate();
stack.push(dateDiff(context, lhs, rhs, unit));
}
}
@TLFunctionInitAnnotation
public static final void dateDiffInit(TLFunctionCallContext context) {
context.setCache(new TLCalendarCache());
}
@TLFunctionAnnotation("Returns the difference between dates")
public static final Integer dateDiff(TLFunctionCallContext context, Date lhs, Date rhs, DateFieldEnum unit) {
long diffSec = (lhs.getTime() - rhs.getTime()) / 1000L;
int diff = 0;
Calendar cal = null;
switch (unit) {
case SECOND:
// we have the difference in seconds
diff = (int) diffSec;
break;
case MINUTE:
// how many minutes'
diff = (int) (diffSec / 60L);
break;
case HOUR:
diff = (int) (diffSec / 3600L);
break;
case DAY:
// how many days is the difference
diff = (int) (diffSec / 86400L);
break;
case WEEK:
// how many weeks
diff = (int) (diffSec / 604800L);
break;
case MONTH:
cal = ((TLCalendarCache)context.getCache()).getCalendar();
cal.setTime(lhs);
diff = cal.get(Calendar.MONTH) + cal.get(Calendar.YEAR) * 12;
cal.setTime(rhs);
diff -= cal.get(Calendar.MONTH) + cal.get(Calendar.YEAR) * 12;
break;
case YEAR:
cal = ((TLCalendarCache)context.getCache()).getCalendar();
cal.setTime(lhs);
diff = cal.get(Calendar.YEAR);
cal.setTime(rhs);
diff -= cal.get(Calendar.YEAR);
break;
default:
throw new TransformLangExecutorRuntimeException("Unknown time unit " + unit);
}
return diff;
}
@TLFunctionAnnotation("Returns 1.1.1970 date.")
public static final Date zeroDate(TLFunctionCallContext context) {
return new Date(0L);
}
class ZeroDateFunction implements TLFunctionPrototype {
public void init(TLFunctionCallContext context) {
}
public void execute(Stack stack, TLFunctionCallContext context) {
stack.push(zeroDate(context));
}
}
// extractDate
// TODO: add test case
class ExtractDateFunction implements TLFunctionPrototype {
public void init(TLFunctionCallContext context) {
extractDateInit(context);
}
public void execute(Stack stack, TLFunctionCallContext context) {
stack.push(extractDate(context, stack.popDate()));
}
}
@TLFunctionInitAnnotation
public static final void extractDateInit(TLFunctionCallContext context) {
context.setCache(new TLCalendarCache());
}
@TLFunctionAnnotation("Extracts only date portion from date-time value, setting all time fields to zero.")
public static final Date extractDate(TLFunctionCallContext context, Date d) {
// this hardcore code is necessary, subtracting milliseconds
// or using Calendar.clear() does not seem to handle light-saving correctly
Calendar cal = ((TLCalendarCache)context.getCache()).getCalendar();
cal.setTime(d);
int[] portion = new int[]{cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)};
cal.clear();
cal.set(Calendar.DAY_OF_MONTH, portion[0]);
cal.set(Calendar.MONTH, portion[1]);
cal.set(Calendar.YEAR, portion[2]);
return cal.getTime();
}
// extractTime
// TODO: add test case
class ExtractTimeFunction implements TLFunctionPrototype {
public void init(TLFunctionCallContext context) {
extractTimeInit(context);
}
public void execute(Stack stack, TLFunctionCallContext context) {
stack.push(extractTime(context, stack.popDate()));
}
}
@TLFunctionInitAnnotation
public void extractTimeInit(TLFunctionCallContext context) {
context.setCache(new TLCalendarCache());
}
@TLFunctionAnnotation("Extracts only time portion from date-time value, clearing all date fields.")
public static final Date extractTime(TLFunctionCallContext context, Date d) {
// this hardcore code is necessary, subtracting milliseconds
// or using Calendar.clear() does not seem to handle light-saving correctly
Calendar cal = ((TLCalendarCache)context.getCache()).getCalendar();
cal.setTime(d);
int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)};
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, portion[0]);
cal.set(Calendar.MINUTE, portion[1]);
cal.set(Calendar.SECOND, portion[2]);
cal.set(Calendar.MILLISECOND, portion[3]);
return cal.getTime();
}
//Trunc
class TruncFunction implements TLFunctionPrototype {
public void init(TLFunctionCallContext context) {
truncInit(context);
}
public void execute(Stack stack, TLFunctionCallContext context) {
if(context.getParams()[0].isDecimal()) {
stack.push(trunc(context, stack.popDecimal()));
} else if (context.getParams()[0].isDouble()) {
stack.push(trunc(context, stack.popDouble()));
} else if (context.getParams()[0].isDate()) {
stack.push(trunc(context, stack.popDate()));
} else if (context.getParams()[0].isMap()) {
stack.push(trunc(context, stack.popMap()));
} else {
stack.push(trunc(context, stack.popList()));
}
}
}
@TLFunctionInitAnnotation
public static final void truncInit(TLFunctionCallContext context) {
context.setCache(new TLCalendarCache());
}
@TLFunctionAnnotation("Truncates BigDecimal - returns long part of number, decimal part is discarded.")
public static final Long trunc(TLFunctionCallContext context, BigDecimal value) {
return value.longValue();
}
@TLFunctionAnnotation("Truncates Double - returns long part of double, decimal part is discarded.")
public static final Long trunc(TLFunctionCallContext context, Double value) {
return value.longValue();
}
@TLFunctionAnnotation("Returns date with the same year,month and day, but hour, minute, second and millisecond are set to zero values.")
public static final Date trunc(TLFunctionCallContext context, Date value) {
Calendar cal = ((TLCalendarCache)context.getCache()).getCalendar();
cal.setTime(value);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE , 0);
cal.set(Calendar.SECOND , 0);
cal.set(Calendar.MILLISECOND , 0);
value.setTime(cal.getTimeInMillis());
return value;
}
@TLFunctionAnnotation("Emptyes the passed List and returns null.")
public static final <E> List<E> trunc(TLFunctionCallContext context, List<E> value) {
value.clear();
return null;
}
@TLFunctionAnnotation("Emptyes the passed Map and returns null.")
public static final <E, F> Map<E, F> trunc(TLFunctionCallContext context, Map<E, F> value) {
value.clear();
return null;
}
//Trunc date
class TruncDateFunction implements TLFunctionPrototype {
public void init(TLFunctionCallContext context) {
truncDateInit(context);
}
public void execute(Stack stack, TLFunctionCallContext context) {
stack.push(truncDate(context, stack.popDate()));
}
}
@TLFunctionInitAnnotation
public static final void truncDateInit(TLFunctionCallContext context) {
context.setCache(new TLCalendarCache());
}
@TLFunctionAnnotation("Returns the date with the same hour, minute, second and millisecond, but year, month and day are set to zero values.")
public static final Date truncDate(TLFunctionCallContext context, Date date) {
Calendar cal = ((TLCalendarCache)context.getCache()).getCalendar();
cal.setTime(date);
cal.set(Calendar.YEAR,0);
cal.set(Calendar.MONTH,0);
cal.set(Calendar.DAY_OF_MONTH,1);
date.setTime(cal.getTimeInMillis());
return date;
}
//Random date
class RandomDateFunction implements TLFunctionPrototype {
public void init(TLFunctionCallContext context) {
randomDateInit(context);
}
public void execute(Stack stack, TLFunctionCallContext context) {
Long randomSeed = null;
String locale = null;
String format;
if (context.getParams().length > 3) {
if (context.getParams().length > 4) {
randomSeed = stack.popLong();
}
if (context.getParams().length > 3) {
if (context.getParams()[3].isLong() || context.getParams()[3].isInteger()) {
randomSeed = stack.popLong();
} else {
locale = stack.popString();
}
}
format = stack.popString();
String to = stack.popString();
String from = stack.popString();
if (randomSeed == null) {
stack.push(randomDate(context, from, to, format, locale));
} else {
stack.push(randomDate(context, from, to, format, locale, randomSeed));
}
} else if (context.getParams().length > 2){
if (context.getParams()[2].isLong() || context.getParams()[2].isInteger()) {
randomSeed = stack.popLong();
if (context.getParams()[1].isDate()) {
Date to = stack.popDate();
Date from = stack.popDate();
stack.push(randomDate(context, from, to, randomSeed));
} else {
Long to = stack.popLong();
Long from = stack.popLong();
stack.push(randomDate(context, from, to, randomSeed));
}
} else {
format = stack.popString();
String to = stack.popString();
String from = stack.popString();
stack.push(randomDate(context, from, to, format));
}
} else {
if (context.getParams()[1].isDate()) {
Date to = stack.popDate();
Date from = stack.popDate();
stack.push(randomDate(context, from, to));
} else {
Long to = stack.popLong();
Long from = stack.popLong();
stack.push(randomDate(context, from, to));
}
}
}
}
@TLFunctionInitAnnotation
public static final void randomDateInit(TLFunctionCallContext context) {
context.setCache(new TLMultiCache(new TLCache[] {
new TLDateFormatLocaleCache(context, 2, 3),
new TLDataGeneratorCache()
} ));
}
@TLFunctionAnnotation("Generates a random date from interval specified by two dates.")
public static final Date randomDate(TLFunctionCallContext context, Date from, Date to) {
return randomDate(context, from.getTime(), to.getTime());
}
@TLFunctionAnnotation("Generates a random date from interval specified by Long representation of dates. Allows changing seed.")
public static final Date randomDate(TLFunctionCallContext context, Long from, Long to) {
if (from > to) {
throw new TransformLangExecutorRuntimeException("randomDate - fromDate is greater than toDate");
}
return new Date(((TLDataGeneratorCache)((TLMultiCache)context.getCache()).getCaches()[1]).getDataGenerator().nextLong(from, to));
}
@TLFunctionAnnotation("Generates a random date from interval specified by two dates. Allows changing seed.")
public static final Date randomDate(TLFunctionCallContext context, Date from, Date to, Long randomSeed) {
return randomDate(context, from.getTime(), to.getTime(), randomSeed);
}
@TLFunctionAnnotation("Generates a random date from interval specified by Long representation of dates. Allows changing seed.")
public static final Date randomDate(TLFunctionCallContext context, Long from, Long to, Long randomSeed) {
if (from > to) {
throw new TransformLangExecutorRuntimeException("randomDate - fromDate is greater than toDate");
}
DataGenerator generator = ((TLDataGeneratorCache)((TLMultiCache)context.getCache()).getCaches()[1]).getDataGenerator();
generator.setSeed(randomSeed);
return new Date(generator.nextLong(from, to));
}
@TLFunctionAnnotation("Generates a random date from interval specified by string representation of dates in given format.")
public static final Date randomDate(TLFunctionCallContext context, String from, String to, String format) {
DateFormatter df = ((TLDateFormatLocaleCache)((TLMultiCache)context.getCache()).getCaches()[0]).getCachedLocaleFormatter(context, format, null, 1, 2);
return randomDate(context, from, to, df);
}
@TLFunctionAnnotation("Generates a random from interval specified by string representation of dates in given format and locale.")
public static final Date randomDate(TLFunctionCallContext context, String from, String to, String format, String locale) {
DateFormatter df = DateFormatterFactory.createFormatter(format, MiscUtils.createLocale(locale));
return randomDate(context, from, to, df);
}
@TLFunctionAnnotation("Generates a random date from interval specified by string representation of dates in given format. Allows changing seed.")
public static final Date randomDate(TLFunctionCallContext context, String from, String to, String format, Long randomSeed) {
DateFormatter df = DateFormatterFactory.createFormatter(format);
return randomDate(context, from, to, randomSeed, df);
}
@TLFunctionAnnotation("Generates a random date from interval specified by string representation of dates in given format and locale. Allows changing seed.")
public static final Date randomDate(TLFunctionCallContext context, String from, String to, String format, String locale, Long randomSeed) {
DateFormatter df = DateFormatterFactory.createFormatter(format, MiscUtils.createLocale(locale));
return randomDate(context, from, to, randomSeed, df);
}
private static final Date randomDate(TLFunctionCallContext context, String from, String to, DateFormatter formatter) {
try {
long fromTime = formatter.parseMillis(from);
long toTime = formatter.parseMillis(to);
return randomDate(context, fromTime, toTime);
} catch (IllegalArgumentException e) {
throw new TransformLangExecutorRuntimeException("randomDate - " + e.getMessage());
}
}
private static final Date randomDate(TLFunctionCallContext context, String from, String to, Long randomSeed, DateFormatter formatter) {
try {
long fromTime = formatter.parseMillis(from);
long toTime = formatter.parseMillis(to);
return randomDate(context, fromTime, toTime, randomSeed);
} catch (IllegalArgumentException e) {
throw new TransformLangExecutorRuntimeException("randomDate - " + e.getMessage());
}
}
}
|
package ti.modules.titanium.analytics;
import java.util.HashMap;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiContext;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiPlatformHelper;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.appcelerator.analytics.APSAnalytics;
import com.appcelerator.analytics.APSAnalyticsEvent;
@Kroll.module
public class AnalyticsModule extends KrollModule
{
private static final String TAG = "AnalyticsModule";
protected static final String PROPERTY_APP_NAV = "app.nav";
protected static final String PROPERTY_APP_TIMED = "app.timed";
protected static final String PROPERTY_APP_FEATURE = "app.feature";
protected static final String PROPERTY_APP_SETTINGS = "app.settings";
protected static final String PROPERTY_APP_USER = "app.user";
private APSAnalytics analytics = APSAnalytics.getInstance();
public AnalyticsModule()
{
super();
}
public AnalyticsModule(TiContext tiContext)
{
this();
}
@Kroll.method
public void navEvent(String from, String to,
@Kroll.argument(optional=true) String event,
@Kroll.argument(optional=true) KrollDict data)
{
if (TiApplication.getInstance().isAnalyticsEnabled()) {
// Preserve legacy behavior allowing the argument to be optional. We set it to be an empty string now
// instead of "null".
if (event == null) {
event = "";
}
if (data instanceof HashMap) {
analytics.sendAppNavEvent(from, to, event, TiConvert.toJSON(data));
} else if (data != null) {
try {
analytics.sendAppNavEvent(from, to, event, new JSONObject(data.toString()));
} catch (JSONException e) {
Log.e(TAG, "Cannot convert data into JSON");
}
} else {
analytics.sendAppNavEvent(from, to, event, null);
}
} else {
Log.e(TAG, "Analytics is disabled. To enable, please update the <analytics></analytics> node in your tiapp.xml");
}
}
@Kroll.method
public void featureEvent(String event, @Kroll.argument(optional = true) KrollDict data)
{
if (TiApplication.getInstance().isAnalyticsEnabled()) {
if (data instanceof HashMap) {
analytics.sendAppFeatureEvent(event, TiConvert.toJSON(data));
} else if (data != null) {
try {
analytics.sendAppFeatureEvent(event, new JSONObject(data.toString()));
} catch (JSONException e) {
Log.e(TAG, "Cannot convert data into JSON");
}
} else {
analytics.sendAppFeatureEvent(event, null);
}
} else {
Log.e(TAG, "Analytics is disabled. To enable, please update the <analytics></analytics> node in your tiapp.xml");
}
}
@Kroll.getProperty @Kroll.method
public String getLastEvent()
{
if (TiApplication.getInstance().isAnalyticsEnabled()) {
TiPlatformHelper platformHelper = TiPlatformHelper.getInstance();
APSAnalyticsEvent event = platformHelper.getLastEvent();
if (event != null) {
try {
JSONObject json = new JSONObject();
json.put("ver", platformHelper.getDBVersion());
json.put("id", platformHelper.getLastEventID());
json.put("event", event.getEventType());
json.put("ts", event.getEventTimestamp());
json.put("mid", event.getEventMid());
json.put("sid", event.getEventSid());
json.put("aguid", event.getEventAppGuid());
json.put("seq", event.getEventSeq());
if (event.mustExpandPayload()) {
json.put("data", new JSONObject(event.getEventPayload()));
} else {
json.put("data", event.getEventPayload());
}
return json.toString();
} catch (JSONException e) {
Log.e(TAG, "Error generating last event.", e);
}
}
} else {
Log.e(TAG, "Analytics is disabled. To enable, please update the <analytics></analytics> node in your tiapp.xml");
}
return null;
}
@Override
public String getApiName()
{
return "Ti.Analytics";
}
}
|
package com.planetmayo.debrief.satc.util;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPoint;
import com.vividsolutions.jts.geom.Polygon;
/** utility class providing geospatial support
*
* @author ian
*
*/
public class GeoSupport
{
private static GeometryFactory _factory;
private static GeoPlotter _plotter;
public static interface GeoPlotter
{
/** plot the indicated line
*
* @param title title of the line
* @param coords coords to plot
*/
void showGeometry(String title, Coordinate[] coords);
/** clear the plot
*
*/
void clear();
}
public static void setPlotter(GeoPlotter plotter)
{
_plotter = plotter;
}
/** get our geometry factory
*
* @return
*/
public static GeometryFactory getFactory()
{
if(_factory == null)
_factory = new GeometryFactory();
return _factory;
}
public static double m2deg(double metres)
{
return metres / 111200d;
}
public static double deg2m(double degs)
{
return degs * 111200d;
}
public static double kts2MSec(double kts)
{
return kts * 0.514444444;
}
public static double MSec2kts(double m_sec)
{
return m_sec / 0.514444444;
}
public static void clearOutput()
{
if(_plotter != null)
_plotter.clear();
}
public static void writeGeometry(String title, Geometry geo)
{
if(geo == null)
return;
if(geo instanceof LineString)
{
LineString ring = (LineString) geo;
Coordinate[] coords = ring.getCoordinates();
writeGeometry(title, coords);
}
else if(geo instanceof Polygon)
{
Polygon poly = (Polygon) geo;
writeGeometry(title + " edge " ,poly.getBoundary());
}
else if(geo instanceof MultiLineString)
{
MultiLineString lineS = (MultiLineString) geo;
int n = lineS.getNumGeometries();
for(int i=0;i<n;i++)
{
Geometry thisGeo = lineS.getGeometryN(i);
writeGeometry(title + " geo:" + i, thisGeo);
}
}
else if(geo instanceof MultiPoint)
{
MultiPoint mp = (MultiPoint) geo;
Coordinate[] coords = mp.getCoordinates();
writeGeometry(title, coords);
}
}
private static void showGeometry(String title, Coordinate[] coords)
{
if(_plotter != null)
{
_plotter.showGeometry(title, coords);
}
}
private static void writeGeometry(String title, Coordinate[] coords)
{
System.out.println("== " + title + " ==");
for (int i = 0; i < coords.length; i++)
{
Coordinate coordinate = coords[i];
System.out.println(coordinate.x + ", " + coordinate.y);
}
// and try to show it
showGeometry(title, coords);
}
}
|
package app.hongs.action.serv;
import app.hongs.Cnst;
import app.hongs.Core;
import app.hongs.HongsError;
import app.hongs.action.ActionDriver;
import app.hongs.action.ActionHelper;
import app.hongs.action.ActionRunner;
import app.hongs.action.anno.Action;
import app.hongs.action.anno.CustomReplies;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.Set;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*
* <h3>(init-param):</h3>
* <pre>
* action-path
* layout-path
* ignore-urls URL, ",", "*"
* </pre>
* <p>
* :
* action-path, layout-path filter-mapping url-pattern ,
*
* </p>
*
* @author Hongs
*/
public class AutoFilter extends ActionDriver {
private String action;
private String layout;
private FilterCheck ignore = null;
private Set<String> layset = null;
private Set<String> actset = null;
private Set<String> cstset = null;
// private Map<String, String> cstmap = null; // inlucde
// private Map<String, String> cxtmap = null; // forward
@Override
public void init(FilterConfig cnf) throws ServletException {
super.init(cnf);
action = cnf.getInitParameter("action-path");
layout = cnf.getInitParameter("layout-path");
if (action == null) {
action ="/common/pages";
}
if (layout == null) {
layout = action;
}
// URL
this.ignore = new FilterCheck(
cnf.getInitParameter("ignore-urls"),
cnf.getInitParameter("attend-urls")
);
}
@Override
public void destroy() {
actset = null;
layset = null;
}
@Override
public void doFilter(Core core, ActionHelper hlpr, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse rsp = hlpr.getResponse();
HttpServletRequest req = hlpr.getRequest( );
String url = ActionDriver.getCurrPath( req );
if (ignore != null && ignore.ignore(url)) {
chain.doFilter(req , rsp);
return;
}
if (url.endsWith(".api")) {
} else
if (url.endsWith(".act")) {
String act, ext;
String src, met;
String uri;
int pos;
try {
pos = url.lastIndexOf('.');
ext = url.substring( pos);
act = url.substring(1,pos);
pos = act.lastIndexOf('/');
met = act.substring(1+pos);
src = act.substring(0,pos);
} catch (IndexOutOfBoundsException ex) {
chain.doFilter ( req, rsp);
return;
}
uri = "/"+ src +"/@"+ met +".jsp";
if (new File(Core.BASE_PATH+ uri).exists()) {
include ( req, rsp, url, uri);
return;
}
uri = "/"+ src +"/#"+ met +".jsp";
if (new File(Core.BASE_PATH+ uri).exists()) {
forward ( req, rsp, url, uri);
return;
}
if (!ActionRunner.getActions().containsKey(act)) {
/*
getlays();
for(Map.Entry<String, String> et : cstmap.entrySet()) {
met = et.getKey ( );
uri = et.getValue( );
if (act.endsWith(met)) {
include(req,rsp, url, layout + uri);
return;
}
}
for(Map.Entry<String, String> et : cxtmap.entrySet()) {
met = et.getKey ( );
uri = et.getValue( );
if (act.endsWith(met)) {
forward(req,rsp, url, layout + uri);
return;
}
}
*/
for(String axt: getacts()) {
if (act.endsWith(axt)) {
if (cstset.contains(axt)) {
forward(req, rsp, url, action + axt + ext);
} else {
include(req, rsp, url, action + axt + ext);
}
return;
}
}
}
} else {
// default.html
if ( url.endsWith("/") ) {
url = url + "default.html";
}
File urf = new File(Core.BASE_PATH+ url);
if (!urf.exists( )) {
boolean jsp = url.endsWith (".jsp" );
boolean htm = url.endsWith (".htm" )
|| url.endsWith (".html");
int pos = url.lastIndexOf( "." );
String uxl = pos == -1 ? url: url.substring(0, pos);
for(String uri: getlays()) {
if (url.endsWith(uri)) {
forward(req, rsp, url, layout + uri);
return;
}
if (jsp) {
continue;
}
if (htm) {
// xxx.htm => xxx.jsp
if ((uxl + ".jsp").endsWith(uri)) {
forward(req, rsp, url, layout + uri);
return;
}
} else {
// xxx.xxx => xxx.xxx.jsp
if ((url + ".jsp").endsWith(uri)) {
forward(req, rsp, url, layout + uri);
return;
}
}
}
}
}
chain.doFilter(req, rsp);
}
private void include(ServletRequest req, ServletResponse rsp, String url, String uri)
throws ServletException, IOException {
req.setAttribute(Cnst.PATH_ATTR, url);
req.getRequestDispatcher(uri).include(req, rsp);
}
private void forward(ServletRequest req, ServletResponse rsp, String url, String uri)
throws ServletException, IOException {
req.setAttribute(Cnst.PATH_ATTR, url);
req.getRequestDispatcher(uri).forward(req, rsp);
}
private Set<String> getacts() {
if (null != actset) {
return actset;
}
// search class
// search search
Class cls;
try {
cls = ActionRunner.getActions()
.get(action.substring(1) + "/search")
.getMclass( );
} catch ( NullPointerException ex ) {
throw new HongsError(0x3e,
"Auto action '" + action.substring(1) + "/search' is not exists", ex);
}
cstset = new HashSet();
actset = new TreeSet(new Comparator<String>( ) {
@Override
public int compare( String o1, String o2 ) {
int i, c1 = 0, c2 = 0;
i = 0;
while ((i = o1.indexOf('/', i)) != -1) {
i ++;
c1 ++;
}
i = 0;
while ((i = o2.indexOf('/', i)) != -1) {
i ++;
c2 ++;
}
return Integer.compare(c2, c1);
}
});
for (Method mtd : cls.getMethods( )) {
Action ann = mtd.getAnnotation(Action.class);
if (null != ann) {
String uri;
if (!"".equals(ann.value())) {
uri = "/"+ ann.value( );
} else {
uri = "/"+ mtd.getName();
}
if (mtd.isAnnotationPresent(CustomReplies.class)) {
cstset.add(uri);
}
actset.add(uri);
}
}
return actset;
}
private Set<String> getlays() {
if (null != layset) {
return layset;
}
File dir = new File(Core.BASE_PATH + layout);
if (!dir.exists( )) {
throw new HongsError(0x3f,
"Auto layout '" + layout.substring(1) + "' is not exists");
}
if (!dir.isDirectory()) {
throw new HongsError(0x3f,
"Auto layout '" + layout.substring(1) + "' is not a directory");
}
layset = new LinkedHashSet();
// cstmap = new LinkedHashMap();
// cxtmap = new LinkedHashMap();
getlays(layset, dir, "/");
return layset;
}
private void getlays(Set layset, File dx, String dn) {
File[] fs = dx.listFiles( );
if (null == fs) {
return;
}
for ( File fx : fs ) {
String fn = fx.getName();
if (fn.startsWith (".")
|| fn.startsWith ("_")) {
continue;
}
if (fx.isDirectory( )) {
getlays(layset, fx, dn + fn + "/");
}
/**
* @,#
* @ include, # forward
*/
// if (fn.startsWith ("@")) {
// int l = fn.lastIndexOf(".");
// String ln = fn.substring(1 , l);
// cstmap.put( dn + ln , dn + fn );
// } else
// if (fn.startsWith ("
// int l = fn.lastIndexOf(".");
// String ln = fn.substring(1 , l);
// cxtmap.put( dn + ln , dn + fn );
// } else
layset.add( dn + fn);
}
}
}
|
package com.alcoapps.actionbarextras;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.kroll.common.Log;
import android.app.Activity;
import android.app.ActionBar;
import android.view.ViewConfiguration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
@Kroll.module(name="Actionbarextras", id="com.alcoapps.actionbarextras")
public class ActionbarextrasModule extends KrollModule
{
// Standard Debugging variables
private static final String TAG = "ActionbarextrasModule";
// You can define constants with @Kroll.constant, for example:
// @Kroll.constant public static final String EXTERNAL_NAME = value;
public ActionbarextrasModule()
{
super();
}
@Kroll.onAppCreate
public static void onAppCreate(TiApplication app)
{
Log.d(TAG, "inside onAppCreate");
// put module init code that needs to run when the application is created
try {
ViewConfiguration config = ViewConfiguration.get(app);
java.lang.reflect.Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ex) {
// Ignore
}
}
// Methods
@Kroll.method
public void setExtras(KrollDict args)
{
Log.d(TAG, "called the setextras method");
// declare stuff
TiApplication appContext = TiApplication.getInstance();
Activity activity = appContext.getCurrentActivity();
ActionBar actionBar = activity.getActionBar();
if (!TiApplication.isUIThread()) {
if (args.containsKey("title")){
actionBar.setTitle((String) args.get("title"));
}
if (args.containsKey("subtitle")){
actionBar.setSubtitle((String) args.get("subtitle"));
}
if (args.containsKey("backgroundColor")) {
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor((String) args.get("backgroundColor"))));
}
}
}
}
|
package com.buschmais.cdo.impl;
import com.buschmais.cdo.api.CdoException;
import com.buschmais.cdo.api.CdoTransaction;
import com.buschmais.cdo.api.CompositeObject;
import com.buschmais.cdo.impl.cache.TransactionalCache;
import com.buschmais.cdo.impl.interceptor.InterceptorFactory;
import com.buschmais.cdo.impl.interceptor.InterceptorInvocationHandler;
import com.buschmais.cdo.impl.proxy.ProxyMethodService;
import com.buschmais.cdo.impl.proxy.instance.EntityProxyMethodService;
import com.buschmais.cdo.impl.proxy.instance.InstanceInvocationHandler;
import com.buschmais.cdo.spi.datastore.DatastoreSession;
import com.buschmais.cdo.spi.datastore.TypeMetadataSet;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
public class InstanceManager<EntityId, Entity> {
private final MetadataProvider metadataProvider;
private final DatastoreSession<EntityId, Entity, ?, ?, ?, ?> datastoreSession;
private final ClassLoader classLoader;
private final TransactionalCache cache;
private final ProxyMethodService<Entity, ?> proxyMethodService;
private final InterceptorFactory interceptorFactory;
public InstanceManager(MetadataProvider metadataProvider, DatastoreSession<EntityId, Entity, ?, ?, ?, ?> datastoreSession, ClassLoader classLoader, CdoTransaction cdoTransaction, TransactionalCache cache, InterceptorFactory interceptorFactory) {
this.metadataProvider = metadataProvider;
this.datastoreSession = datastoreSession;
this.classLoader = classLoader;
this.cache = cache;
PropertyManager propertyManager = new PropertyManager(datastoreSession);
this.interceptorFactory = interceptorFactory;
proxyMethodService = new EntityProxyMethodService(metadataProvider, this, propertyManager, cdoTransaction, interceptorFactory, datastoreSession);
}
public <T> T getInstance(Entity entity) {
Set<?> discriminators = datastoreSession.getDiscriminators(entity);
if (discriminators == null || discriminators.isEmpty()) {
throw new CdoException("Cannot determine type discriminators for entity '" + entity + "'");
}
TypeMetadataSet<?> types = metadataProvider.getTypes(discriminators);
EntityId id = datastoreSession.getId(entity);
Object instance = cache.get(id);
if (instance == null) {
InstanceInvocationHandler invocationHandler = new InstanceInvocationHandler(entity, proxyMethodService);
instance = createInstance(invocationHandler, types.toClasses(), CompositeObject.class);
cache.put(id, instance);
}
return (T) instance;
}
public <Instance> Instance createInstance(InvocationHandler invocationHandler, Set<Class<?>> types, Class<?>... baseTypes) {
List<Class<?>> effectiveTypes = new ArrayList<>(types.size() + baseTypes.length);
effectiveTypes.addAll(types);
effectiveTypes.addAll(Arrays.asList(baseTypes));
return (Instance) createProxyInstance(invocationHandler, effectiveTypes);
}
public <Instance> void removeInstance(Instance instance) {
Entity entity = getEntity(instance);
EntityId id = datastoreSession.getId(entity);
cache.remove(id);
}
public <Instance> void destroyInstance(Instance instance) {
getInvocationHandler(instance).close();
}
public <Instance> boolean isEntity(Instance instance) {
return CompositeObject.class.isAssignableFrom(instance.getClass());
}
public <Instance> Entity getEntity(Instance instance) {
InstanceInvocationHandler<Entity> invocationHandler = getInvocationHandler(instance);
return invocationHandler.getEntity();
}
public void close() {
for (Object instance : cache.values()) {
destroyInstance(instance);
}
cache.clear();
}
private Object createProxyInstance(InvocationHandler invocationHandler, List<Class<?>> effectiveTypes) {
Object instance = Proxy.newProxyInstance(classLoader, effectiveTypes.toArray(new Class<?>[effectiveTypes.size()]), invocationHandler);
return interceptorFactory.addInterceptor(instance);
}
private <Instance> InstanceInvocationHandler<Entity> getInvocationHandler(Instance instance) {
InvocationHandler invocationHandler = Proxy.getInvocationHandler(interceptorFactory.removeInterceptor(instance));
if (!(invocationHandler instanceof InstanceInvocationHandler)) {
throw new CdoException("Instance " + instance + " implementing " + Arrays.asList(instance.getClass().getInterfaces()) + " is not a " + InstanceInvocationHandler.class.getName());
}
return (InstanceInvocationHandler<Entity>) invocationHandler;
}
}
|
package org.eclipse.jetty.io.ssl;
import java.io.IOException;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.util.Arrays;
import java.util.concurrent.Executor;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import org.eclipse.jetty.io.AbstractConnection;
import org.eclipse.jetty.io.AbstractEndPoint;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.io.FillInterest;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.io.SelectChannelEndPoint;
import org.eclipse.jetty.io.SocketBased;
import org.eclipse.jetty.io.WriteFlusher;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* A Connection that acts as an interceptor between an EndPoint providing SSL encrypted data
* and another consumer of an EndPoint (typically an {@link Connection} like HttpConnection) that
* wants unencrypted data.
* <p>
* The connector uses an {@link EndPoint} (typically {@link SelectChannelEndPoint}) as
* it's source/sink of encrypted data. It then provides an endpoint via {@link #getDecryptedEndPoint()} to
* expose a source/sink of unencrypted data to another connection (eg HttpConnection).
* <p>
* The design of this class is based on a clear separation between the passive methods, which do not block nor schedule any
* asynchronous callbacks, and active methods that do schedule asynchronous callbacks.
* <p>
* The passive methods are {@link DecryptedEndPoint#fill(ByteBuffer)} and {@link DecryptedEndPoint#flush(ByteBuffer...)}. They make best
* effort attempts to progress the connection using only calls to the encrypted {@link EndPoint#fill(ByteBuffer)} and {@link EndPoint#flush(ByteBuffer...)}
* methods. They will never block nor schedule any readInterest or write callbacks. If a fill/flush cannot progress either because
* of network congestion or waiting for an SSL handshake message, then the fill/flush will simply return with zero bytes filled/flushed.
* Specifically, if a flush cannot proceed because it needs to receive a handshake message, then the flush will attempt to fill bytes from the
* encrypted endpoint, but if insufficient bytes are read it will NOT call {@link EndPoint#fillInterested(Object, Callback)}.
* <p>
* It is only the active methods : {@link DecryptedEndPoint#fillInterested(Object, Callback)} and
* {@link DecryptedEndPoint#write(Object, Callback, ByteBuffer...)} that may schedule callbacks by calling the encrypted
* {@link EndPoint#fillInterested(Object, Callback)} and {@link EndPoint#write(Object, Callback, ByteBuffer...)}
* methods. For normal data handling, the decrypted fillInterest method will result in an encrypted fillInterest and a decrypted
* write will result in an encrypted write. However, due to SSL handshaking requirements, it is also possible for a decrypted fill
* to call the encrypted write and for the decrypted flush to call the encrypted fillInterested methods.
* <p>
* MOST IMPORTANTLY, the encrypted callbacks from the active methods (#onFillable() and WriteFlusher#completeWrite()) do no filling or flushing
* themselves. Instead they simple make the callbacks to the decrypted callbacks, so that the passive encrypted fill/flush will
* be called again and make another best effort attempt to progress the connection.
*
*/
public class SslConnection extends AbstractConnection
{
private static final Logger LOG = Log.getLogger(SslConnection.class);
private static final boolean DEBUG = LOG.isDebugEnabled(); // Easy for the compiler to remove the code if DEBUG==false
private static final ByteBuffer __FILL_CALLED_FLUSH= BufferUtil.allocate(0);
private static final ByteBuffer __FLUSH_CALLED_FILL= BufferUtil.allocate(0);
private final ByteBufferPool _bufferPool;
private final SSLEngine _sslEngine;
private final DecryptedEndPoint _decryptedEndPoint;
private ByteBuffer _decryptedInput;
private ByteBuffer _encryptedInput;
private ByteBuffer _encryptedOutput;
private final boolean _encryptedDirectBuffers = false;
private final boolean _decryptedDirectBuffers = false;
private final Runnable _runCompletWrite = new Runnable()
{
@Override
public void run()
{
_decryptedEndPoint.getWriteFlusher().completeWrite();
}
};
private final Runnable _runWriteEmpty = new Runnable()
{
@Override
public void run()
{
_decryptedEndPoint.write(null, new Callback.Empty<>(), BufferUtil.EMPTY_BUFFER);
}
};
public SslConnection(ByteBufferPool byteBufferPool, Executor executor, EndPoint endPoint, SSLEngine sslEngine)
{
super(endPoint, executor);
this._bufferPool = byteBufferPool;
this._sslEngine = sslEngine;
this._decryptedEndPoint = new DecryptedEndPoint();
if (endPoint instanceof SocketBased)
{
try
{
((SocketBased) endPoint).getSocket().setSoLinger(true,30000);
}
catch (SocketException e)
{
throw new RuntimeIOException(e);
}
}
}
public SSLEngine getSSLEngine()
{
return _sslEngine;
}
public DecryptedEndPoint getDecryptedEndPoint()
{
return _decryptedEndPoint;
}
@Override
public void onOpen()
{
try
{
// Begin the handshake
_sslEngine.beginHandshake();
super.onOpen();
}
catch (SSLException x)
{
getEndPoint().close();
throw new RuntimeIOException(x);
}
}
@Override
public void onClose()
{
_decryptedEndPoint.getConnection().onClose();
super.onClose();
}
@Override
public int getMessagesIn()
{
return _decryptedEndPoint.getConnection().getMessagesIn();
}
@Override
public int getMessagesOut()
{
return _decryptedEndPoint.getConnection().getMessagesOut();
}
@Override
public void close()
{
getDecryptedEndPoint().getConnection().close();
}
@Override
public void onFillable()
{
// onFillable means that there are encrypted bytes ready to be filled.
// however we do not fill them here on this callback, but instead wakeup
// the decrypted readInterest and/or writeFlusher so that they will attempt
// to do the fill and/or flush again and these calls will do the actually
// filling.
if (DEBUG)
LOG.debug("onFillable enter {}", getEndPoint());
// wake up whoever is doing the fill or the flush so they can
// do all the filling, unwrapping, wrapping and flushing
_decryptedEndPoint.getFillInterest().fillable();
// If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read
synchronized(_decryptedEndPoint)
{
if (_decryptedEndPoint._flushRequiresFillToProgress)
{
_decryptedEndPoint._flushRequiresFillToProgress = false;
getExecutor().execute(_runCompletWrite);
}
}
if (DEBUG)
LOG.debug("onFillable exit {}", getEndPoint());
}
@Override
public void onFillInterestedFailed(Throwable cause)
{
// this means that the fill interest in encrypted bytes has failed.
// However we do not handle that here on this callback, but instead wakeup
// the decrypted readInterest and/or writeFlusher so that they will attempt
// to do the fill and/or flush again and these calls will do the actually
// handle the cause.
super.onFillInterestedFailed(cause);
synchronized(_decryptedEndPoint)
{
_decryptedEndPoint.getFillInterest().onFail(cause);
if (_decryptedEndPoint._flushRequiresFillToProgress)
{
_decryptedEndPoint._flushRequiresFillToProgress = false;
_decryptedEndPoint.getWriteFlusher().onFail(cause);
}
}
}
@Override
public String toString()
{
ByteBuffer b = _encryptedInput;
int ei=b==null?-1:b.remaining();
b = _encryptedOutput;
int eo=b==null?-1:b.remaining();
b = _decryptedInput;
int di=b==null?-1:b.remaining();
return String.format("SslConnection@%x{%s,eio=%d/%d,di=%d} -> %s",
hashCode(),
_sslEngine.getHandshakeStatus(),
ei,eo,di,
_decryptedEndPoint.getConnection());
}
public class DecryptedEndPoint extends AbstractEndPoint
{
private boolean _fillRequiresFlushToProgress;
private boolean _flushRequiresFillToProgress;
private boolean _cannotAcceptMoreAppDataToFlush;
private boolean _underFlown;
private final Callback<Void> _writeCallback = new Callback<Void>()
{
@Override
public void completed(Void context)
{
// This means that a write of encrypted data has completed. Writes are done
// only if there is a pending writeflusher or a read needed to write
// data. In either case the appropriate callback is passed on.
synchronized (DecryptedEndPoint.this)
{
if (DEBUG)
LOG.debug("write.complete {}", SslConnection.this.getEndPoint());
releaseEncryptedOutputBuffer();
_cannotAcceptMoreAppDataToFlush = false;
if (_fillRequiresFlushToProgress)
{
_fillRequiresFlushToProgress = false;
getFillInterest().fillable();
}
getExecutor().execute(_runCompletWrite);
}
}
@Override
public void failed(Void context, Throwable x)
{
// This means that a write of data has failed. Writes are done
// only if there is an active writeflusher or a read needed to write
// data. In either case the appropriate callback is passed on.
synchronized (DecryptedEndPoint.this)
{
if (DEBUG)
LOG.debug("{} write.failed", SslConnection.this, x);
if (_encryptedOutput != null)
BufferUtil.clear(_encryptedOutput);
releaseEncryptedOutputBuffer();
_cannotAcceptMoreAppDataToFlush = false;
if (_fillRequiresFlushToProgress)
{
_fillRequiresFlushToProgress = false;
getFillInterest().onFail(x);
}
getWriteFlusher().onFail(x);
// TODO release all buffers??? or may in onClose
}
}
};
public DecryptedEndPoint()
{
// TODO does this need idle timeouts
super(null,getEndPoint().getLocalAddress(), getEndPoint().getRemoteAddress());
}
public EndPoint getEncryptedEndPoint()
{
return getEndPoint();
}
@Override
protected FillInterest getFillInterest()
{
return super.getFillInterest();
}
@Override
protected WriteFlusher getWriteFlusher()
{
return super.getWriteFlusher();
}
@Override
protected void onIncompleteFlush()
{
// This means that the decrypted endpoint write method was called and not
// all data could be wrapped. So either we need to write some encrypted data,
// OR if we are handshaking we need to read some encrypted data OR
// if neither then we should just try the flush again.
synchronized (DecryptedEndPoint.this)
{
if (DEBUG)
LOG.debug("onIncompleteFlush {}", getEndPoint());
// If we have pending output data,
if (BufferUtil.hasContent(_encryptedOutput))
{
// write it
_cannotAcceptMoreAppDataToFlush = true;
getEndPoint().write(null, _writeCallback, _encryptedOutput);
}
// TODO: use _fillRequiresFlushToProgress ?
else if (_sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP)
{
// we are actually read blocked in order to write
_flushRequiresFillToProgress=true;
SslConnection.this.fillInterested();
}
else if (isOutputShutdown())
{
getWriteFlusher().onClose();
}
else
{
// try the flush again
getWriteFlusher().completeWrite();
}
}
}
@Override
protected boolean needsFill() throws IOException
{
// This means that the decrypted data consumer has called the fillInterested
// method on the DecryptedEndPoint, so we have to work out if there is
// decrypted data to be filled or what callbacks to setup to be told when there
// might be more encrypted data available to attempt another call to fill
synchronized (DecryptedEndPoint.this)
{
// Do we already have some app data, then app can fill now so return true
if (BufferUtil.hasContent(_decryptedInput))
return true;
// If we have no encrypted data to decrypt OR we have some, but it is not enough
if (BufferUtil.isEmpty(_encryptedInput) || _underFlown)
{
// We are not ready to read data
// Are we actually write blocked?
if (_fillRequiresFlushToProgress)
{
// we must be blocked trying to write before we can read
// Do we have data to write
if (BufferUtil.hasContent(_encryptedOutput))
{
// write it
_cannotAcceptMoreAppDataToFlush = true;
getEndPoint().write(null, _writeCallback, _encryptedOutput);
}
else
{
// we have already written the net data
// pretend we are readable so the wrap is done by next readable callback
_fillRequiresFlushToProgress = false;
return true;
}
}
else
// Normal readable callback
// Get called back on onfillable when then is more data to fill
SslConnection.this.fillInterested();
return false;
}
else
{
// We are ready to read data
return true;
}
}
}
@Override
public void setConnection(Connection connection)
{
if (connection instanceof AbstractConnection)
{
AbstractConnection a = (AbstractConnection)connection;
if (a.getInputBufferSize()<_sslEngine.getSession().getApplicationBufferSize())
a.setInputBufferSize(_sslEngine.getSession().getApplicationBufferSize());
}
super.setConnection(connection);
}
public SslConnection getSslConnection()
{
return SslConnection.this;
}
@Override
public synchronized int fill(ByteBuffer buffer) throws IOException
{
if (DEBUG)
LOG.debug("{} fill enter", SslConnection.this);
try
{
// Do we already have some decrypted data?
if (BufferUtil.hasContent(_decryptedInput))
return BufferUtil.flipPutFlip(_decryptedInput, buffer);
// We will need a network buffer
if (_encryptedInput == null)
_encryptedInput = _bufferPool.acquire(_sslEngine.getSession().getPacketBufferSize(), _encryptedDirectBuffers);
else
BufferUtil.compact(_encryptedInput);
// We also need an app buffer, but can use the passed buffer if it is big enough
ByteBuffer app_in;
if (BufferUtil.space(buffer) > _sslEngine.getSession().getApplicationBufferSize())
app_in = buffer;
else if (_decryptedInput == null)
app_in = _decryptedInput = _bufferPool.acquire(_sslEngine.getSession().getApplicationBufferSize(), _decryptedDirectBuffers);
else
app_in = _decryptedInput;
// loop filling and unwrapping until we have something
while (true)
{
// Let's try reading some encrypted data... even if we have some already.
int net_filled = getEndPoint().fill(_encryptedInput);
if (DEBUG)
LOG.debug("{} filled {} encrypted bytes", SslConnection.this, net_filled);
if (net_filled > 0)
_underFlown = false;
// Let's try the SSL thang even if we have no net data because in that
// case we want to fall through to the handshake handling
int pos = BufferUtil.flipToFill(app_in);
SSLEngineResult unwrapResult = _sslEngine.unwrap(_encryptedInput, app_in);
BufferUtil.flipToFlush(app_in, pos);
if (DEBUG)
LOG.debug("{} unwrap {}", SslConnection.this, unwrapResult);
// and deal with the results
switch (unwrapResult.getStatus())
{
case BUFFER_OVERFLOW:
throw new IllegalStateException();
case CLOSED:
// Dang! we have to care about the handshake state specially for close
switch (_sslEngine.getHandshakeStatus())
{
case NOT_HANDSHAKING:
// We were not handshaking, so just tell the app we are closed
return -1;
case NEED_TASK:
// run the task
_sslEngine.getDelegatedTask().run();
continue;
case NEED_WRAP:
// we need to send some handshake data (probably to send a close handshake).
// If we were called from flush,
if (buffer==__FLUSH_CALLED_FILL)
return -1; // it can deal with the close handshake
// We need to call flush to cause the wrap to happen
_fillRequiresFlushToProgress = true;
try
{
// flushing an empty buffer will invoke the wrap mechanisms
flush(__FILL_CALLED_FLUSH);
// If encrypted output is all written, we can proceed with close
if (BufferUtil.isEmpty(_encryptedOutput))
{
_fillRequiresFlushToProgress = false;
return -1;
}
// Otherwise return as if a normal fill and let a subsequent call
// return -1 to the caller.
return unwrapResult.bytesProduced();
}
catch (IOException e)
{
LOG.debug(e);
// The flush failed, oh well nothing more to do than tell the app
// that the connection is closed.
return -1;
}
}
throw new IllegalStateException();
default:
if (unwrapResult.getStatus()==Status.BUFFER_UNDERFLOW)
_underFlown=true;
// if we produced bytes, we don't care about the handshake state for now and it can be dealt with on another call to fill or flush
if (unwrapResult.bytesProduced() > 0)
{
if (app_in == buffer)
return unwrapResult.bytesProduced();
return BufferUtil.flipPutFlip(_decryptedInput, buffer);
}
// Dang! we have to care about the handshake state
switch (_sslEngine.getHandshakeStatus())
{
case NOT_HANDSHAKING:
// we just didn't read anything.
if (net_filled < 0)
_sslEngine.closeInbound();
// TODO: do we need to check if there is something pending to write ?
// getWriteFlusher().completeWrite();
return 0;
case NEED_TASK:
// run the task
_sslEngine.getDelegatedTask().run();
continue;
case NEED_WRAP:
// we need to send some handshake data
// if we are called from flush
if (buffer==__FLUSH_CALLED_FILL)
return 0; // let it do the wrapping
_fillRequiresFlushToProgress = true;
flush(__FILL_CALLED_FLUSH);
if (BufferUtil.isEmpty(_encryptedOutput))
{
// the flush completed so continue
_fillRequiresFlushToProgress = false;
continue;
}
return 0;
case NEED_UNWRAP:
// if we just filled some net data
if (net_filled < 0)
{
// If we call closeInbound() before having read the SSL close
// message an exception will be thrown (truncation attack).
// The TLS specification says that the sender of the SSL close
// message may just close and avoid to read the response.
// If that is the case, we avoid calling closeInbound() because
// will throw the truncation attack exception for nothing.
if (isOpen())
_sslEngine.closeInbound();
}
else if (net_filled > 0)
{
// maybe we will fill some more on a retry
continue;
}
// we need to wait for more net data
return 0;
case FINISHED:
throw new IllegalStateException();
}
}
}
}
catch (SSLException e)
{
getEndPoint().close();
throw new EofException(e);
}
catch (Exception e)
{
getEndPoint().close();
throw e;
}
finally
{
// If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read
if (_decryptedEndPoint._flushRequiresFillToProgress)
{
_decryptedEndPoint._flushRequiresFillToProgress = false;
getExecutor().execute(_runCompletWrite);
}
if (_encryptedInput != null && !_encryptedInput.hasRemaining())
{
_bufferPool.release(_encryptedInput);
_encryptedInput = null;
}
if (_decryptedInput != null && !_decryptedInput.hasRemaining())
{
_bufferPool.release(_decryptedInput);
_decryptedInput = null;
}
if (DEBUG)
LOG.debug("{} fill exit", SslConnection.this);
}
}
@Override
public synchronized boolean flush(ByteBuffer... appOuts) throws IOException
{
// The contract for flush does not require that all appOuts bytes are written
// or even that any appOut bytes are written! If the connection is write block
// or busy handshaking, then zero bytes may be taken from appOuts and this method
// will return 0 (even if some handshake bytes were flushed and filled).
// it is the applications responsibility to call flush again - either in a busy loop
// or better yet by using EndPoint#write to do the flushing.
if (DEBUG)
LOG.debug("{} flush enter {}", SslConnection.this, Arrays.toString(appOuts));
int consumed=0;
try
{
if (_cannotAcceptMoreAppDataToFlush)
{
if (_sslEngine.isOutboundDone())
throw new EofException(new ClosedChannelException());
return false;
}
// We will need a network buffer
if (_encryptedOutput == null)
_encryptedOutput = _bufferPool.acquire(_sslEngine.getSession().getPacketBufferSize() * 2, _encryptedDirectBuffers);
while (true)
{
// do the funky SSL thang!
// We call sslEngine.wrap to try to take bytes from appOut buffers and encrypt them into the _netOut buffer
BufferUtil.compact(_encryptedOutput);
int pos = BufferUtil.flipToFill(_encryptedOutput);
SSLEngineResult wrapResult = _sslEngine.wrap(appOuts, _encryptedOutput);
if (DEBUG)
LOG.debug("{} wrap {}", SslConnection.this, wrapResult);
BufferUtil.flipToFlush(_encryptedOutput, pos);
if (wrapResult.bytesConsumed()>0)
consumed+=wrapResult.bytesConsumed();
boolean all_consumed=true;
// clear empty buffers to prevent position creeping up the buffer
for (ByteBuffer b : appOuts)
{
if (BufferUtil.isEmpty(b))
BufferUtil.clear(b);
else
all_consumed=false;
}
// and deal with the results returned from the sslEngineWrap
switch (wrapResult.getStatus())
{
case CLOSED:
// The SSL engine has close, but there may be close handshake that needs to be written
if (BufferUtil.hasContent(_encryptedOutput))
{
_cannotAcceptMoreAppDataToFlush = true;
getEndPoint().flush(_encryptedOutput);
// If we failed to flush the close handshake then we will just pretend that
// the write has progressed normally and let a subsequent call to flush (or WriteFlusher#onIncompleteFlushed)
// to finish writing the close handshake. The caller will find out about the close on a subsequent flush or fill.
if (BufferUtil.hasContent(_encryptedOutput))
return false;
}
// otherwise we have written, and the caller will close the underlying connection
return all_consumed;
case BUFFER_UNDERFLOW:
throw new IllegalStateException();
default:
if (DEBUG)
LOG.debug("{} {} {}", this, wrapResult.getStatus(), BufferUtil.toDetailString(_encryptedOutput));
// if we have net bytes, let's try to flush them
if (BufferUtil.hasContent(_encryptedOutput))
getEndPoint().flush(_encryptedOutput);
// But we also might have more to do for the handshaking state.
switch (_sslEngine.getHandshakeStatus())
{
case NOT_HANDSHAKING:
// Return with the number of bytes consumed (which may be 0)
return all_consumed&&BufferUtil.isEmpty(_encryptedOutput);
case NEED_TASK:
// run the task and continue
_sslEngine.getDelegatedTask().run();
continue;
case NEED_WRAP:
// Hey we just wrapped! Oh well who knows what the sslEngine is thinking, so continue and we will wrap again
continue;
case NEED_UNWRAP:
// Ah we need to fill some data so we can write.
// So if we were not called from fill and the app is not reading anyway
if (appOuts[0]!=__FILL_CALLED_FLUSH && !getFillInterest().isInterested())
{
// Tell the onFillable method that there might be a write to complete
_flushRequiresFillToProgress = true;
fill(__FLUSH_CALLED_FILL);
}
return all_consumed&&BufferUtil.isEmpty(_encryptedOutput);
case FINISHED:
throw new IllegalStateException();
}
}
}
}
catch (Exception e)
{
getEndPoint().close();
throw e;
}
finally
{
if (DEBUG)
LOG.debug("{} flush exit, consumed {}", SslConnection.this, consumed);
releaseEncryptedOutputBuffer();
}
}
private void releaseEncryptedOutputBuffer()
{
if (_encryptedOutput != null && !_encryptedOutput.hasRemaining())
{
_bufferPool.release(_encryptedOutput);
_encryptedOutput = null;
if (_sslEngine.isOutboundDone())
getEndPoint().shutdownOutput();
}
}
@Override
public void shutdownOutput()
{
_sslEngine.closeOutbound();
try
{
flush(BufferUtil.EMPTY_BUFFER);
}
catch (IOException e)
{
LOG.ignore(e);
getEndPoint().close();
}
}
@Override
public boolean isOutputShutdown()
{
return _sslEngine.isOutboundDone() || getEndPoint().isOutputShutdown();
}
@Override
public void close()
{
getEndPoint().close();
}
@Override
public boolean isOpen()
{
return getEndPoint().isOpen();
}
@Override
public Object getTransport()
{
return getEndPoint();
}
@Override
public boolean isInputShutdown()
{
return _sslEngine.isInboundDone();
}
@Override
public String toString()
{
return super.toString()+"->"+getEndPoint().toString();
}
}
}
|
package com.williamfiset.algorithms.graphtheory.networkflow;
import static java.lang.Math.*;
import java.util.*;
public class Dinics {
static final long INF = 987654321L;
// Inputs: n = number of nodes, s = source, t = sink
private final int n, s, t;
// Internal
private boolean solved;
private int[] level;
// Outputs
private long maxFlow;
private boolean[] minCut;
private List<List<Edge>> graph;
static class Edge {
int to;
Edge residual;
long flow, capacity;
public Edge(int to, long capacity) {
this.to = to;
this.capacity = capacity;
}
}
/**
* Creates an instance of a flow network solver. Use the {@link #addEdge(int, int, int)}
* method to add edges to the graph.
*
* @param n - The number of nodes in the graph including source and sink nodes.
* @param s - The index of the source node, 0 <= source < n
* @param t - The index of the sink node, 0 <= sink < n
*/
public Dinics(int n, int s, int t) {
this.n = n; this.s = s; this.t = t;
level = new int[n];
initializeGraph();
}
// Construct an empty graph with n nodes including the source and sink nodes.
private void initializeGraph() {
graph = new ArrayList<>(n);
for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
}
/**
* Adds a directed edge (and residual edge) to the flow graph.
*
* @param from - The index of the node the directed edge starts at.
* @param to - The index of the node the directed edge ends at.
* @param capacity - The capacity of the edge.
*/
public void addEdge(int from, int to, int capacity) {
Edge e1 = new Edge(to, capacity);
Edge e2 = new Edge(from, 0);
e1.residual = e2;
e2.residual = e1;
graph.get(from).add(e1);
graph.get(to).add(e2);
}
public List<List<Edge>> getGraph() {
solve();
return graph;
}
// Returns the maximum flow from the source to the sink.
public long getMaxFlow() {
solve();
return maxFlow;
}
// Returns the min-cut of this flow network where the nodes on the "left side"
// of the cut with the source are marked as true and those on the "right side"
// of the cut with the sink are marked as false.
public boolean[] getMinCut() {
solve();
return minCut;
}
// Do a BFS from source to sink and compute the depth/level of each node
// which is the minimum number of edges from that node to the source.
private boolean bfs() {
Arrays.fill(level, -1);
level[s] = 0;
Deque<Integer> q = new ArrayDeque<>(n);
q.offer(s);
while(!q.isEmpty()) {
int node = q.poll();
for (Edge edge : graph.get(node)) {
if (edge.flow < edge.capacity && level[edge.to] == -1) {
level[edge.to] = level[node] + 1;
q.offer(edge.to);
}
}
}
return level[t] != -1;
}
private long dfs(int at, int[] p, long flow) {
if (at == t) return flow;
final int sz = graph.get(at).size();
for (;p[at] < sz; p[at]++) {
Edge edge = graph.get(at).get(p[at]);
if (edge.flow < edge.capacity && level[edge.to] == level[at] + 1) {
long bottleNeck = dfs(edge.to, p, min(flow, edge.capacity - edge.flow));
if (bottleNeck > 0) {
Edge res = edge.residual;
edge.flow += bottleNeck;
res.flow -= bottleNeck;
return bottleNeck;
}
}
}
return 0;
}
public void solve() {
if (solved) return;
// p[i] indicates the next unused edge index in the adjacency list for node i
int[] p = new int[n];
while(bfs()) {
Arrays.fill(p, 0);
for (long flow = dfs(s, p, INF); flow != 0; flow = dfs(s, p, INF)) {
maxFlow += flow;
}
}
minCut = new boolean[n];
for (int i = 0; i < n; i++)
if (level[i] != -1)
minCut[i] = true;
solved = true;
}
}
|
package com.eclipserunner.ui.menus;
import static com.eclipserunner.utils.SelectionUtils.selectionAsList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.expressions.EvaluationContext;
import org.eclipse.core.expressions.Expression;
import org.eclipse.core.expressions.IEvaluationContext;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.internal.ui.DebugUIPlugin;
import org.eclipse.debug.internal.ui.actions.LaunchShortcutAction;
import org.eclipse.debug.internal.ui.launchConfigurations.LaunchShortcutExtension;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.events.MenuAdapter;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.activities.WorkbenchActivityHelper;
/**
* TODO LWA: under development
*
* @author vachacz
*/
@SuppressWarnings("restriction")
public class BookmarkPopupMenuAction implements IObjectActionDelegate, IMenuCreator {
private IStructuredSelection selection;
private boolean rebuildMenu = true;
private IAction delegateAction;
public Menu getMenu(Menu parent) {
Menu menu = new Menu(parent);
menu.addMenuListener(new MenuAdapter() {
@Override
public void menuShown(MenuEvent event) {
if (rebuildMenu) {
Menu menu = (Menu) event.widget;
disposeMenuItems(menu);
if (selection != null) {
fillMenu(menu);
}
rebuildMenu = false;
}
}
});
return menu;
}
public void selectionChanged(IAction action, ISelection iSelection) {
if (iSelection instanceof IStructuredSelection) {
selection = (IStructuredSelection) iSelection;
rebuildMenu = true;
if (delegateAction != action) {
delegateAction = action;
delegateAction.setMenuCreator(this);
}
action.setEnabled(true);
} else {
action.setEnabled(false);
}
}
protected void fillMenu(Menu menu) {
List<LaunchShortcutExtension> applicableShortcuts = getApplicableShortcuts();
Iterator<LaunchShortcutExtension> iterator = applicableShortcuts.iterator();
while (iterator.hasNext()) {
LaunchShortcutExtension launchShortcut = iterator.next();
if (launchShortcut.getModes().contains(ILaunchManager.RUN_MODE)) {
populateMenuItem(ILaunchManager.RUN_MODE, launchShortcut, menu);
}
}
}
@SuppressWarnings("unchecked")
private List<LaunchShortcutExtension> getApplicableShortcuts() {
IEvaluationContext context = createContext();
List<LaunchShortcutExtension> applicableShortcuts = new ArrayList<LaunchShortcutExtension>();
Iterator iterator = getLaunchShortcuts().iterator();
while (iterator.hasNext()) {
LaunchShortcutExtension launchShortcut = (LaunchShortcutExtension) iterator.next();
if (isApplicable(launchShortcut, context)) {
applicableShortcuts.add(launchShortcut);
}
}
return applicableShortcuts;
}
private IEvaluationContext createContext() {
IEvaluationContext context = new EvaluationContext(null, selectionAsList(selection));
context.setAllowPluginActivation(true);
context.addVariable("selection", selection);
return context;
}
private boolean isApplicable(LaunchShortcutExtension launchShortcut, IEvaluationContext context) {
try {
Expression expr = launchShortcut.getContextualLaunchEnablementExpression();
return !WorkbenchActivityHelper.filterItem(launchShortcut)
&& launchShortcut.evalEnablementExpression(context, expr);
} catch (CoreException e) {
return false;
}
}
private void populateMenuItem(String mode, LaunchShortcutExtension launchShortcut, Menu menu) {
Action action = new LaunchShortcutAction(mode, launchShortcut);
action.setActionDefinitionId(launchShortcut.getId() + "." + mode);
// replace default action label with context label if specified.
String contextLabel = launchShortcut.getContextLabel(mode);
action.setText(contextLabel != null ? contextLabel : action.getText());
new ActionContributionItem(action).fill(menu, -1);
}
public void setActivePart(IAction arg0, IWorkbenchPart arg1) {
// not needed
}
public void run(IAction action) {
// action provides sub menu and does not handle any action
}
public Menu getMenu(Control control) {
// never called
return null;
}
public void dispose() {
// nothing to do
}
@SuppressWarnings("unchecked")
private List getLaunchShortcuts() {
return DebugUIPlugin.getDefault().getLaunchConfigurationManager().getLaunchShortcuts();
}
private void disposeMenuItems(Menu menu) {
MenuItem[] menuItems = menu.getItems();
for (int i = 0; i < menuItems.length; i++) {
menuItems[i].dispose();
}
}
}
|
package com.haxademic.app.haxmapper.textures;
import com.haxademic.core.app.P;
import com.haxademic.core.math.MathUtil;
public class TextureEQGrid
extends BaseTexture {
protected float _cols = 32;
protected float _rows = 32;
protected float _spectrumInterval = 512f / (_cols * _rows); // 256 keeps it in the bottom half of the spectrum since the high ends is so overrun
protected float _cellW;
protected float _cellH;
protected boolean _boxesGrow = false;
public TextureEQGrid( int width, int height ) {
super();
buildGraphics( width, height );
_cellW = P.ceil( _texture.width/_cols );
_cellH = P.ceil( _texture.height/_rows );
}
public void newLineMode() {
_boxesGrow = MathUtil.randBoolean(P.p);
}
public void update() {
super.update();
_texture.beginDraw();
_texture.clear();
// draw grid
float startX = 0;
float startY = 0;
int spectrumIndex = 0;
_texture.noStroke();
for (int i = 0; i < _cols; i++) {
for (int j = 0; j < _rows; j++) {
if( _boxesGrow ) {
float scaleVal = P.constrain( 0.1f * P.p.audioIn.getEqBand( P.floor(_spectrumInterval * spectrumIndex) ), 0, 1 );
_texture.fill( _colorEase.colorInt() );
_texture.rect(
startX + i*_cellW + _cellW * 0.5f - (_cellW * scaleVal * 0.5f),
startY + j*_cellH + _cellH * 0.5f - (_cellH * scaleVal * 0.5f),
_cellW * scaleVal,
_cellH * scaleVal
);
spectrumIndex++;
} else {
float alphaVal = P.p.audioIn.getEqBand( P.floor(_spectrumInterval * spectrumIndex) );
_texture.fill( _colorEase.colorInt(), P.constrain( alphaVal * 255f, 0, 255 ) );
_texture.rect( startX + i*_cellW, startY + j*_cellH, _cellW, _cellH );
spectrumIndex++;
}
}
}
_texture.endDraw();
}
}
|
package com.mebigfatguy.fbcontrib.detect;
import java.util.ArrayDeque;
import java.util.BitSet;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.AnnotationEntry;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.GETFIELD;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.INVOKEVIRTUAL;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReferenceType;
import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.SignatureUtils;
import com.mebigfatguy.fbcontrib.utils.ToString;
import com.mebigfatguy.fbcontrib.utils.Values;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.FieldAnnotation;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.BasicBlock.InstructionIterator;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.CFGBuilderException;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.Edge;
/**
* finds fields that are used in a locals only fashion, specifically private fields that are accessed first in each method with a store vs. a load.
*/
public class FieldCouldBeLocal extends BytecodeScanningDetector {
private final BugReporter bugReporter;
private ClassContext clsContext;
private Map<String, FieldInfo> localizableFields;
private CFG cfg;
private ConstantPoolGen cpg;
private BitSet visitedBlocks;
private Map<String, Set<String>> methodFieldModifiers;
private String clsName;
private String clsSig;
/**
* constructs a FCBL detector given the reporter to report bugs on.
*
* @param bugReporter
* the sync of bug reports
*/
public FieldCouldBeLocal(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
/**
* overrides the visitor to collect localizable fields, and then report those that survive all method checks.
*
* @param classContext
* the context object that holds the JavaClass parsed
*/
@Override
public void visitClassContext(ClassContext classContext) {
try {
localizableFields = new HashMap<>();
visitedBlocks = new BitSet();
clsContext = classContext;
clsName = clsContext.getJavaClass().getClassName();
clsSig = SignatureUtils.classToSignature(clsName);
JavaClass cls = classContext.getJavaClass();
Field[] fields = cls.getFields();
ConstantPool cp = classContext.getConstantPoolGen().getConstantPool();
for (Field f : fields) {
if (!f.isStatic() && !f.isVolatile() && (f.getName().indexOf('$') < 0) && f.isPrivate()) {
FieldAnnotation fa = new FieldAnnotation(cls.getClassName(), f.getName(), f.getSignature(), false);
boolean hasExternalAnnotation = false;
for (AnnotationEntry entry : f.getAnnotationEntries()) {
ConstantUtf8 cutf = (ConstantUtf8) cp.getConstant(entry.getTypeIndex());
if (!cutf.getBytes().startsWith("java")) {
hasExternalAnnotation = true;
break;
}
}
localizableFields.put(f.getName(), new FieldInfo(fa, hasExternalAnnotation));
}
}
if (localizableFields.size() > 0) {
buildMethodFieldModifiers(classContext);
super.visitClassContext(classContext);
for (FieldInfo fi : localizableFields.values()) {
FieldAnnotation fa = fi.getFieldAnnotation();
SourceLineAnnotation sla = fi.getSrcLineAnnotation();
BugInstance bug = new BugInstance(this, BugType.FCBL_FIELD_COULD_BE_LOCAL.name(), NORMAL_PRIORITY).addClass(this).addField(fa);
if (sla != null) {
bug.addSourceLine(sla);
}
bugReporter.reportBug(bug);
}
}
} finally {
localizableFields = null;
visitedBlocks = null;
clsContext = null;
methodFieldModifiers = null;
}
}
/**
* overrides the visitor to navigate basic blocks looking for all first usages of fields, removing those that are read from first.
*
* @param obj
* the context object of the currently parsed method
*/
@Override
public void visitMethod(Method obj) {
if (localizableFields.isEmpty()) {
return;
}
try {
cfg = clsContext.getCFG(obj);
cpg = cfg.getMethodGen().getConstantPool();
BasicBlock bb = cfg.getEntry();
Set<String> uncheckedFields = new HashSet<>(localizableFields.keySet());
visitedBlocks.clear();
checkBlock(bb, uncheckedFields);
} catch (CFGBuilderException cbe) {
localizableFields.clear();
} finally {
cfg = null;
cpg = null;
}
}
/**
* looks for methods that contain a GETFIELD or PUTFIELD opcodes
*
* @param method
* the context object of the current method
* @return if the class uses GETFIELD or PUTFIELD
*/
private boolean prescreen(Method method) {
BitSet bytecodeSet = getClassContext().getBytecodeSet(method);
return (bytecodeSet != null) && (bytecodeSet.get(Constants.PUTFIELD) || bytecodeSet.get(Constants.GETFIELD));
}
/**
* implements the visitor to pass through constructors and static initializers to the byte code scanning code. These methods are not reported, but are used
* to build SourceLineAnnotations for fields, if accessed.
*
* @param obj
* the context object of the currently parsed code attribute
*/
@Override
public void visitCode(Code obj) {
Method m = getMethod();
if (prescreen(m)) {
String methodName = m.getName();
if ("<clinit".equals(methodName) || Values.CONSTRUCTOR.equals(methodName)) {
super.visitCode(obj);
}
}
}
/**
* implements the visitor to add SourceLineAnnotations for fields in constructors and static initializers.
*
* @param seen
* the opcode of the currently visited instruction
*/
@Override
public void sawOpcode(int seen) {
if ((seen == GETFIELD) || (seen == PUTFIELD)) {
String fieldName = getNameConstantOperand();
FieldInfo fi = localizableFields.get(fieldName);
if (fi != null) {
SourceLineAnnotation sla = SourceLineAnnotation.fromVisitedInstruction(this);
fi.setSrcLineAnnotation(sla);
}
}
}
/**
* looks in this basic block for the first access to the fields in uncheckedFields. Once found the item is removed from uncheckedFields, and removed from
* localizableFields if the access is a GETFIELD. If any unchecked fields remain, this method is recursively called on all outgoing edges of this basic
* block.
*
* @param bb
* this basic block
* @param uncheckedFields
* the list of fields to look for
*/
private void checkBlock(BasicBlock bb, Set<String> uncheckedFields) {
Deque<BlockState> toBeProcessed = new ArrayDeque<>();
toBeProcessed.addLast(new BlockState(bb, uncheckedFields));
visitedBlocks.set(bb.getLabel());
while (!toBeProcessed.isEmpty()) {
if (localizableFields.isEmpty()) {
return;
}
BlockState bState = toBeProcessed.removeFirst();
bb = bState.getBasicBlock();
InstructionIterator ii = bb.instructionIterator();
while ((bState.getUncheckedFieldSize() > 0) && ii.hasNext()) {
InstructionHandle ih = ii.next();
Instruction ins = ih.getInstruction();
if (ins instanceof FieldInstruction) {
FieldInstruction fi = (FieldInstruction) ins;
if (fi.getReferenceType(cpg).getSignature().equals(clsSig)) {
String fieldName = fi.getFieldName(cpg);
FieldInfo finfo = localizableFields.get(fieldName);
if ((finfo != null) && localizableFields.get(fieldName).hasAnnotation()) {
localizableFields.remove(fieldName);
} else {
boolean justRemoved = bState.removeUncheckedField(fieldName);
if (ins instanceof GETFIELD) {
if (justRemoved) {
localizableFields.remove(fieldName);
if (localizableFields.isEmpty()) {
return;
}
}
} else if (finfo != null) {
finfo.setSrcLineAnnotation(SourceLineAnnotation.fromVisitedInstruction(clsContext, this, ih.getPosition()));
}
}
}
} else if (ins instanceof INVOKESPECIAL) {
INVOKESPECIAL is = (INVOKESPECIAL) ins;
ReferenceType rt = is.getReferenceType(cpg);
if (Values.CONSTRUCTOR.equals(is.getMethodName(cpg))
&& ((rt instanceof ObjectType) && ((ObjectType) rt).getClassName().startsWith(clsContext.getJavaClass().getClassName() + '$'))) {
localizableFields.clear();
}
} else if (ins instanceof INVOKEVIRTUAL) {
INVOKEVIRTUAL is = (INVOKEVIRTUAL) ins;
ReferenceType rt = is.getReferenceType(cpg);
if ((rt instanceof ObjectType) && ((ObjectType) rt).getClassName().equals(clsName)) {
String methodDesc = is.getName(cpg) + is.getSignature(cpg);
Set<String> fields = methodFieldModifiers.get(methodDesc);
if (fields != null) {
localizableFields.keySet().removeAll(fields);
}
}
}
}
if (bState.getUncheckedFieldSize() > 0) {
Iterator<Edge> oei = cfg.outgoingEdgeIterator(bb);
while (oei.hasNext()) {
Edge e = oei.next();
BasicBlock cb = e.getTarget();
int label = cb.getLabel();
if (!visitedBlocks.get(label)) {
toBeProcessed.addLast(new BlockState(cb, bState));
visitedBlocks.set(label);
}
}
}
}
}
/**
* builds up the method to field map of what method write to which fields this is one recursively so that if method A calls method B, and method B writes to
* field C, then A modifies F.
*
* @param classContext
* the context object of the currently parsed class
*/
private void buildMethodFieldModifiers(ClassContext classContext) {
FieldModifier fm = new FieldModifier();
fm.visitClassContext(classContext);
methodFieldModifiers = fm.getMethodFieldModifiers();
}
/**
* holds information about a field and it's first usage
*/
private static class FieldInfo {
private final FieldAnnotation fieldAnnotation;
private SourceLineAnnotation srcLineAnnotation;
private final boolean hasAnnotation;
/**
* creates a FieldInfo from an annotation, and assumes no source line information
*
* @param fa
* the field annotation for this field
* @param hasExternalAnnotation
* the field has a non java based annotation
*/
FieldInfo(final FieldAnnotation fa, boolean hasExternalAnnotation) {
fieldAnnotation = fa;
srcLineAnnotation = null;
hasAnnotation = hasExternalAnnotation;
}
/**
* set the source line annotation of first use for this field
*
* @param sla
* the source line annotation
*/
void setSrcLineAnnotation(final SourceLineAnnotation sla) {
if (srcLineAnnotation == null) {
srcLineAnnotation = sla;
}
}
/**
* get the field annotation for this field
*
* @return the field annotation
*/
FieldAnnotation getFieldAnnotation() {
return fieldAnnotation;
}
/**
* get the source line annotation for the first use of this field
*
* @return the source line annotation
*/
SourceLineAnnotation getSrcLineAnnotation() {
return srcLineAnnotation;
}
/**
* gets whether the field has a non java annotation
*
* @return if the field has a non java annotation
*/
boolean hasAnnotation() {
return hasAnnotation;
}
@Override
public String toString() {
return ToString.build(this);
}
}
private static class BlockState {
private final BasicBlock basicBlock;
private Set<String> uncheckedFields;
private boolean fieldsAreSharedWithParent;
/**
* creates a BlockState consisting of the next basic block to parse, and what fields are to be checked
*
* @param bb
* the basic block to parse
* @param fields
* the fields to look for first use
*/
public BlockState(final BasicBlock bb, final Set<String> fields) {
basicBlock = bb;
uncheckedFields = fields;
fieldsAreSharedWithParent = true;
}
/**
* creates a BlockState consisting of the next basic block to parse, and what fields are to be checked
*
* @param bb
* the basic block to parse
* @param parentBlockState
* the basic block to copy from
*/
public BlockState(final BasicBlock bb, BlockState parentBlockState) {
basicBlock = bb;
uncheckedFields = parentBlockState.uncheckedFields;
fieldsAreSharedWithParent = true;
}
/**
* get the basic block to parse
*
* @return the basic block
*/
public BasicBlock getBasicBlock() {
return basicBlock;
}
/**
* returns the number of unchecked fields
*
* @return the number of unchecked fields
*/
public int getUncheckedFieldSize() {
return (uncheckedFields == null) ? 0 : uncheckedFields.size();
}
/**
* return the field from the set of unchecked fields if this occurs make a copy of the set on write to reduce memory usage
*
* @param field
* the field to be removed
*
* @return whether the object was removed.
*/
public boolean removeUncheckedField(String field) {
if ((uncheckedFields == null) || !uncheckedFields.contains(field)) {
return false;
}
if (uncheckedFields.size() == 1) {
uncheckedFields = null;
fieldsAreSharedWithParent = false;
return true;
}
if (fieldsAreSharedWithParent) {
uncheckedFields = new HashSet<>(uncheckedFields);
fieldsAreSharedWithParent = false;
uncheckedFields.remove(field);
} else {
uncheckedFields.remove(field);
}
return true;
}
@Override
public String toString() {
return ToString.build(this);
}
}
private static class FieldModifier extends BytecodeScanningDetector {
private final Map<String, Set<String>> methodCallChain = new HashMap<>();
private final Map<String, Set<String>> mfModifiers = new HashMap<>();
private String clsName;
public Map<String, Set<String>> getMethodFieldModifiers() {
Map<String, Set<String>> modifiers = new HashMap<>(mfModifiers.size());
modifiers.putAll(mfModifiers);
for (Entry<String, Set<String>> method : modifiers.entrySet()) {
modifiers.put(method.getKey(), new HashSet<>(method.getValue()));
}
boolean modified = true;
while (modified) {
modified = false;
for (Map.Entry<String, Set<String>> entry : methodCallChain.entrySet()) {
String methodDesc = entry.getKey();
Set<String> calledMethods = entry.getValue();
for (String calledMethodDesc : calledMethods) {
Set<String> fields = mfModifiers.get(calledMethodDesc);
if (fields != null) {
Set<String> flds = modifiers.get(methodDesc);
if (flds == null) {
flds = new HashSet<>();
modifiers.put(methodDesc, flds);
}
if (flds.addAll(fields)) {
modified = true;
}
}
}
}
}
return modifiers;
}
@Override
public void visitClassContext(ClassContext context) {
clsName = context.getJavaClass().getClassName();
super.visitClassContext(context);
}
@Override
public void sawOpcode(int seen) {
if (seen == PUTFIELD) {
if (clsName.equals(getClassConstantOperand())) {
String methodDesc = getMethodName() + getMethodSig();
Set<String> fields = mfModifiers.get(methodDesc);
if (fields == null) {
fields = new HashSet<>();
mfModifiers.put(methodDesc, fields);
}
fields.add(getNameConstantOperand());
}
} else if ((seen == INVOKEVIRTUAL) && clsName.equals(getClassConstantOperand())) {
String methodDesc = getMethodName() + getMethodSig();
Set<String> methods = methodCallChain.get(methodDesc);
if (methods == null) {
methods = new HashSet<>();
methodCallChain.put(methodDesc, methods);
}
methods.add(getNameConstantOperand() + getSigConstantOperand());
}
}
@Override
public String toString() {
return ToString.build(this);
}
}
}
|
package com.pensioenpage.jynx.ods2csv.tests;
import com.pensioenpage.jynx.ods2csv.Converter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import static org.junit.Assert.*;
import org.junit.Test;
public class ConverterTests {
// Methods
@Test
public void testConverter() throws Exception {
// Make sure constructor does not accept null arguments
Converter converter = new Converter();
try {
converter.convert(null, null);
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException e) {
// as expected
}
try {
converter.convert(new ByteArrayInputStream("Test".getBytes()), null);
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException e) {
// as expected
}
try {
converter.convert(null, new ByteArrayOutputStream());
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException e) {
// as expected
}
// Test with actual input files, compare with expected output
boolean finished = false;
int i = 0;
do {
InputStream ods = getClass().getResourceAsStream("test" + i + ".ods");
InputStream csv = getClass().getResourceAsStream("test" + i + ".csv");
if (ods == null || csv == null) {
finished = true;
} else {
doTest(ods, csv);
}
} while (! finished);
}
private void doTest(InputStream ods, InputStream csv) throws Exception {
Converter converter = new Converter();
ByteArrayOutputStream actual = new ByteArrayOutputStream();
converter.convert(ods, actual);
}
}
|
package com.redhat.ceylon.common.config;
import java.io.File;
import java.net.Proxy;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.redhat.ceylon.common.Constants;
import com.redhat.ceylon.common.FileUtil;
public class DefaultToolOptions {
public final static String DEFAULTS_ENCODING = "defaults.encoding";
public final static String DEFAULTS_OFFLINE = "defaults.offline";
public final static String DEFAULTS_TIMEOUT = "defaults.timeout";
// BACKWARDS-COMPAT
public final static String DEFAULTS_MAVENOVERRIDES = "defaults.mavenoverrides";
public final static String DEFAULTS_OVERRIDES = "defaults.overrides";
public final static String DEFAULTS_FLAT_CLASSPATH = "defaults.flatclasspath";
public final static String DEFAULTS_AUTO_EPORT_MAVEN_DEPENDENCIES = "defaults.autoexportmavendependencies";
public final static String COMPILER_SOURCE = "compiler.source";
public final static String COMPILER_RESOURCE = "compiler.resource";
public final static String COMPILER_RESOURCE_ROOT = "compiler.resourceroot";
public final static String COMPILER_SCRIPT = "compiler.script";
public final static String COMPILER_DOC = "compiler.doc";
public final static String COMPILER_SUPPRESSWARNING = "compiler.suppresswarning";
public final static String COMPILER_NOOSGI = "compiler.noosgi";
public final static String COMPILER_OSGIPROVIDEDBUNDLES = "compiler.osgiprovidedbundles";
public final static String COMPILER_NOPOM = "compiler.nopom";
public final static String COMPILER_PACK200 = "compiler.pack200";
public final static String RUNTOOL_COMPILE = "runtool.compile";
public final static String TESTTOOL_COMPILE = "testtool.compile";
private DefaultToolOptions() {
}
public static String getDefaultEncoding() {
return getDefaultEncoding(CeylonConfig.get());
}
public static String getDefaultEncoding(CeylonConfig config) {
return config.getOption(DEFAULTS_ENCODING);
}
public static boolean getDefaultOffline() {
return getDefaultOffline(CeylonConfig.get());
}
public static boolean getDefaultOffline(CeylonConfig config) {
return config.getBoolOption(DEFAULTS_OFFLINE, false);
}
public static long getDefaultTimeout() {
return getDefaultTimeout(CeylonConfig.get());
}
public static long getDefaultTimeout(CeylonConfig config) {
return timeoutFromString(config.getOption(DEFAULTS_TIMEOUT), Constants.DEFAULT_TIMEOUT);
}
public static int timeoutFromString(String num, int defaultTimeout) {
if (num != null) {
int fact = 1000;
if (num.endsWith("ms")) {
num = num.substring(0, num.length() - 2);
fact = 1;
}
return Integer.parseInt(num) * fact;
} else {
return defaultTimeout;
}
}
public static Proxy getDefaultProxy() {
return getDefaultProxy(CeylonConfig.get());
}
public static Proxy getDefaultProxy(CeylonConfig config) {
Authentication auth = Authentication.fromConfig(config);
return auth.getProxy();
}
public static String getDefaultOverrides() {
return getDefaultOverrides(CeylonConfig.get());
}
public static String getDefaultOverrides(CeylonConfig config) {
String ov = config.getOption(DEFAULTS_OVERRIDES);
if(ov != null)
return ov;
// backwards compat
return config.getOption(DEFAULTS_MAVENOVERRIDES);
}
public static boolean getDefaultFlatClasspath() {
return getDefaultFlatClasspath(CeylonConfig.get());
}
public static boolean getDefaultFlatClasspath(CeylonConfig config) {
return config.getBoolOption(DEFAULTS_FLAT_CLASSPATH, false);
}
public static boolean getDefaultAutoExportMavenDependencies() {
return getDefaultAutoExportMavenDependencies(CeylonConfig.get());
}
public static boolean getDefaultAutoExportMavenDependencies(CeylonConfig config) {
return config.getBoolOption(DEFAULTS_AUTO_EPORT_MAVEN_DEPENDENCIES, false);
}
public static List<File> getCompilerSourceDirs() {
return getCompilerSourceDirs(CeylonConfig.get());
}
public static List<File> getCompilerSourceDirs(CeylonConfig config) {
String[] dirs = config.getOptionValues(COMPILER_SOURCE);
if (dirs != null) {
return Arrays.asList(FileUtil.pathsToFileArray(dirs));
} else {
return Collections.singletonList(new File(Constants.DEFAULT_SOURCE_DIR));
}
}
public static List<File> getCompilerResourceDirs() {
return getCompilerResourceDirs(CeylonConfig.get());
}
public static List<File> getCompilerResourceDirs(CeylonConfig config) {
String[] dirs = config.getOptionValues(COMPILER_RESOURCE);
if (dirs != null) {
return Arrays.asList(FileUtil.pathsToFileArray(dirs));
} else {
return Collections.singletonList(new File(Constants.DEFAULT_RESOURCE_DIR));
}
}
public static List<File> getCompilerScriptDirs() {
return getCompilerScriptDirs(CeylonConfig.get());
}
public static List<File> getCompilerScriptDirs(CeylonConfig config) {
String[] dirs = config.getOptionValues(COMPILER_SCRIPT);
if (dirs != null) {
return Arrays.asList(FileUtil.pathsToFileArray(dirs));
} else {
return Collections.singletonList(new File(Constants.DEFAULT_SCRIPT_DIR));
}
}
public static String getCompilerResourceRootName() {
return getCompilerResourceRootName(CeylonConfig.get());
}
public static String getCompilerResourceRootName(CeylonConfig config) {
return config.getOption(COMPILER_RESOURCE_ROOT, Constants.DEFAULT_RESOURCE_ROOT);
}
public static List<File> getCompilerDocDirs() {
return getCompilerDocDirs(CeylonConfig.get());
}
public static List<File> getCompilerDocDirs(CeylonConfig config) {
String[] dirs = config.getOptionValues(COMPILER_DOC);
if (dirs != null) {
return Arrays.asList(FileUtil.pathsToFileArray(dirs));
} else {
return Collections.singletonList(new File(Constants.DEFAULT_DOC_DIR));
}
}
public static String getCompilerOutputRepo() {
return getCompilerOutputRepo(CeylonConfig.get());
}
public static String getCompilerOutputRepo(CeylonConfig config) {
return Repositories.withConfig(config).getOutputRepository().getUrl();
}
public static List<String> getCompilerSuppressWarnings() {
return getCompilerSuppressWarnings(CeylonConfig.get());
}
public static List<String> getCompilerSuppressWarnings(CeylonConfig config) {
String[] warnings = config.getOptionValues(COMPILER_SUPPRESSWARNING);
if (warnings != null) {
return Arrays.asList(warnings);
} else {
return null;
}
}
public static boolean getCompilerNoOsgi() {
return getCompilerNoOsgi(CeylonConfig.get());
}
public static boolean getCompilerNoOsgi(CeylonConfig config) {
return config.getBoolOption(COMPILER_NOOSGI, false);
}
public static String getCompilerOsgiProvidedBundles() {
return getCompilerOsgiProvidedBundles(CeylonConfig.get());
}
public static String getCompilerOsgiProvidedBundles(CeylonConfig config) {
return config.getOption(COMPILER_OSGIPROVIDEDBUNDLES, "");
}
public static boolean getCompilerNoPom() {
return getCompilerNoPom(CeylonConfig.get());
}
public static boolean getCompilerNoPom(CeylonConfig config) {
return config.getBoolOption(COMPILER_NOPOM, false);
}
public static boolean getCompilerPack200() {
return getCompilerPack200(CeylonConfig.get());
}
public static boolean getCompilerPack200(CeylonConfig config) {
return config.getBoolOption(COMPILER_PACK200, false);
}
public static String getRunToolCompileFlags() {
return getRunToolCompileFlags(CeylonConfig.get());
}
public static String getRunToolCompileFlags(CeylonConfig config) {
return config.getOption(RUNTOOL_COMPILE, Constants.DEFAULT_RUNTOOL_COMPILATION_FLAGS);
}
public static String getTestToolCompileFlags() {
return getTestToolCompileFlags(CeylonConfig.get());
}
public static String getTestToolCompileFlags(CeylonConfig config) {
return config.getOption(TESTTOOL_COMPILE, Constants.DEFAULT_TESTTOOL_COMPILATION_FLAGS);
}
}
|
package com.intuit.karate.core;
import com.intuit.karate.PerfHook;
import com.intuit.karate.Runner;
import com.intuit.karate.http.HttpRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.intuit.karate.match.Match;
import com.intuit.karate.match.MatchResult;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author pthomas3
*/
class PerfHookTest {
static final Logger logger = LoggerFactory.getLogger(PerfHookTest.class);
static MockServer server;
@BeforeAll
static void beforeAll() {
server = MockServer
.feature("classpath:com/intuit/karate/core/perf-mock.feature")
.http(0).build();
System.setProperty("karate.server.port", server.getPort() + "");
}
@BeforeEach
void beforeEach() {
eventName = null;
featureResult = null;
}
@AfterAll
static void afterAll() {
server.stop();
}
@Test
void testPerfHook1() {
// Run a passing scenario
List<String> tags = Collections.singletonList("@name=pass");
String bar = UUID.randomUUID().toString().replaceAll("-", "");
Map<String, Object> arg = Collections.singletonMap("bar", bar);
Runner.callAsync("classpath:com/intuit/karate/core/perf.feature", tags, arg, perfHook);
assertEquals(eventName, "http://localhost:" + server.getPort() + "/hello?foo=" + bar);
assertNotNull(featureResult);
assertFalse(featureResult.isEmpty());
assertFalse(featureResult.isFailed());
assertEquals(featureResult.getScenarioCount(), 1);
assertEquals(featureResult.getPassedCount(), 1);
assertEquals(featureResult.getFailedCount(), 0);
match(featureResult.getVariables(), "{ bar: '" + bar + "', responseHeaders: { content-type: ['application/json'], content-length: [
}
@Test
void testPerfHook2() {
// Run a scenario which fails the status check
List<String> tags = Collections.singletonList("@name=failStatus");
String bar = UUID.randomUUID().toString().replaceAll("-", "");
Map<String, Object> arg = Collections.singletonMap("bar", bar);
Runner.callAsync("classpath:com/intuit/karate/core/perf.feature", tags, arg, perfHook);
assertEquals(eventName, "http://localhost:" + server.getPort() + "/hello?foo=" + bar);
assertNotNull(featureResult);
assertFalse(featureResult.isEmpty());
assertTrue(featureResult.isFailed());
assertEquals(featureResult.getScenarioCount(), 1);
assertEquals(featureResult.getPassedCount(), 0);
assertEquals(featureResult.getFailedCount(), 1);
match(featureResult.getVariables(), "{ bar: '" + bar + "', responseHeaders: { content-type: ['application/json'], content-length: [
}
@Test
void testPerfHook3() {
// Run a scenario which fails the response match
List<String> tags = Collections.singletonList("@name=failResponse");
String bar = UUID.randomUUID().toString().replaceAll("-", "");
Map<String, Object> arg = Collections.singletonMap("bar", bar);
Runner.callAsync("classpath:com/intuit/karate/core/perf.feature", tags, arg, perfHook);
assertEquals(eventName, "http://localhost:" + server.getPort() + "/hello?foo=" + bar);
assertNotNull(featureResult);
assertFalse(featureResult.isEmpty());
assertTrue(featureResult.isFailed());
assertEquals(featureResult.getScenarioCount(), 1);
assertEquals(featureResult.getPassedCount(), 0);
assertEquals(featureResult.getFailedCount(), 1);
match(featureResult.getVariables(), "{ bar: '" + bar + "', responseHeaders: { content-type: ['application/json'], content-length: [
}
@Test
void testPerfHook4() {
// Run a scenario without passing a required argument
List<String> tags = Collections.singletonList("@name=pass");
Map<String, Object> arg = Collections.emptyMap();
Runner.callAsync("classpath:com/intuit/karate/core/perf.feature", tags, arg, perfHook);
assertNull(eventName);
assertNotNull(featureResult);
assertFalse(featureResult.isEmpty());
assertTrue(featureResult.isFailed());
assertEquals(featureResult.getScenarioCount(), 1);
assertEquals(featureResult.getPassedCount(), 0);
assertEquals(featureResult.getFailedCount(), 1);
match(featureResult.getVariables(), "{ configSource: 'normal' }");
}
@Test
void testPerfHook5() {
// Run a scenario which doesn't exist
List<String> tags = Collections.singletonList("@name=doesntExist");
Map<String, Object> arg = Collections.emptyMap();
Runner.callAsync("classpath:com/intuit/karate/core/perf.feature", tags, arg, perfHook);
assertNull(eventName);
assertNotNull(featureResult);
assertTrue(featureResult.isEmpty());
assertFalse(featureResult.isFailed());
assertEquals(featureResult.getScenarioCount(), 0);
assertEquals(featureResult.getPassedCount(), 0);
assertEquals(featureResult.getFailedCount(), 0);
assertNull(featureResult.getVariables());
}
@Test
void testPerfHook6() {
// Run a feature which doesn't exist
List<String> tags = Collections.emptyList();
Map<String, Object> arg = Collections.emptyMap();
String feature = "com/intuit/karate/core/doesntExist.feature";
try {
Runner.callAsync("classpath:" + feature, tags, arg, perfHook);
fail("we expected execution to fail");
} catch (RuntimeException e) {
assertEquals(e.getMessage(), "not found: " + feature);
}
assertNull(eventName);
assertNull(featureResult);
}
private void match(Object actual, Object expected) {
MatchResult mr = Match.that(actual).isEqualTo(expected);
assertTrue(mr.pass, mr.message);
}
String eventName;
FeatureResult featureResult;
PerfHook perfHook = new PerfHook() {
@Override
public String getPerfEventName(HttpRequest request, ScenarioRuntime sr) {
return request.getUrl();
}
@Override
public void reportPerfEvent(PerfEvent event) {
eventName = event.getName();
logger.debug("perf event: {}", eventName);
}
@Override
public void submit(Runnable runnable) {
logger.debug("submit called");
runnable.run();
}
@Override
public void afterFeature(FeatureResult fr) {
featureResult = fr;
logger.debug("afterFeature called");
}
};
}
|
package org.pdxfinder.utilities;
import org.apache.commons.cli.Option;
import org.pdxfinder.dao.*;
import org.pdxfinder.repositories.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.time.Instant;
import java.util.Collection;
import java.util.Date;
import java.util.Set;
/**
* The hope was to put a lot of reused repository actions into one place ie find
* or create a node or create a node with that requires a number of 'child'
* nodes that are terms
*
* @author sbn
*/
@Component
public class LoaderUtils {
public static Option loadAll = new Option("LoadAll", false, "Load all PDX Finder data");
private TumorTypeRepository tumorTypeRepository;
private BackgroundStrainRepository backgroundStrainRepository;
private ImplantationTypeRepository implantationTypeRepository;
private ImplantationSiteRepository implantationSiteRepository;
private ExternalDataSourceRepository externalDataSourceRepository;
private PatientRepository patientRepository;
private ModelCreationRepository modelCreationRepository;
private TissueRepository tissueRepository;
private PatientSnapshotRepository patientSnapshotRepository;
private SampleRepository sampleRepository;
private MarkerRepository markerRepository;
private MarkerAssociationRepository markerAssociationRepository;
private MolecularCharacterizationRepository molecularCharacterizationRepository;
private PdxPassageRepository pdxPassageRepository;
private QualityAssuranceRepository qualityAssuranceRepository;
private OntologyTermRepository ontologyTermRepository;
private SpecimenRepository specimenRepository;
private PlatformRepository platformRepository;
private PlatformAssociationRepository platformAssociationRepository;
private final static Logger log = LoggerFactory.getLogger(LoaderUtils.class);
public LoaderUtils(TumorTypeRepository tumorTypeRepository,
BackgroundStrainRepository backgroundStrainRepository,
ImplantationTypeRepository implantationTypeRepository,
ImplantationSiteRepository implantationSiteRepository,
ExternalDataSourceRepository externalDataSourceRepository,
PatientRepository patientRepository,
ModelCreationRepository modelCreationRepository,
TissueRepository tissueRepository,
PatientSnapshotRepository patientSnapshotRepository,
SampleRepository sampleRepository,
MarkerRepository markerRepository,
MarkerAssociationRepository markerAssociationRepository,
MolecularCharacterizationRepository molecularCharacterizationRepository,
PdxPassageRepository pdxPassageRepository,
QualityAssuranceRepository qualityAssuranceRepository,
OntologyTermRepository ontologyTermRepository,
SpecimenRepository specimenRepository,
PlatformRepository platformRepository,
PlatformAssociationRepository platformAssociationRepository) {
Assert.notNull(tumorTypeRepository, "tumorTypeRepository cannot be null");
Assert.notNull(backgroundStrainRepository, "backgroundStrainRepository cannot be null");
Assert.notNull(implantationTypeRepository, "implantationTypeRepository cannot be null");
Assert.notNull(implantationSiteRepository, "implantationSiteRepository cannot be null");
Assert.notNull(externalDataSourceRepository, "externalDataSourceRepository cannot be null");
Assert.notNull(patientRepository, "patientRepository cannot be null");
Assert.notNull(modelCreationRepository, "modelCreationRepository cannot be null");
Assert.notNull(tissueRepository, "tissueRepository cannot be null");
Assert.notNull(patientSnapshotRepository, "patientSnapshotRepository cannot be null");
Assert.notNull(sampleRepository, "sampleRepository cannot be null");
Assert.notNull(markerRepository, "markerRepository cannot be null");
Assert.notNull(markerAssociationRepository, "markerAssociationRepository cannot be null");
Assert.notNull(molecularCharacterizationRepository, "molecularCharacterizationRepository cannot be null");
this.tumorTypeRepository = tumorTypeRepository;
this.backgroundStrainRepository = backgroundStrainRepository;
this.implantationTypeRepository = implantationTypeRepository;
this.implantationSiteRepository = implantationSiteRepository;
this.externalDataSourceRepository = externalDataSourceRepository;
this.patientRepository = patientRepository;
this.modelCreationRepository = modelCreationRepository;
this.tissueRepository = tissueRepository;
this.patientSnapshotRepository = patientSnapshotRepository;
this.sampleRepository = sampleRepository;
this.markerRepository = markerRepository;
this.markerAssociationRepository = markerAssociationRepository;
this.molecularCharacterizationRepository = molecularCharacterizationRepository;
this.pdxPassageRepository = pdxPassageRepository;
this.qualityAssuranceRepository = qualityAssuranceRepository;
this.ontologyTermRepository = ontologyTermRepository;
this.specimenRepository = specimenRepository;
this.platformRepository = platformRepository;
this.platformAssociationRepository = platformAssociationRepository;
}
public ExternalDataSource getExternalDataSource(String abbr, String name, String description) {
ExternalDataSource eDS = externalDataSourceRepository.findByAbbreviation(abbr);
if (eDS == null) {
log.info("External data source '{}' not found. Creating", abbr);
eDS = new ExternalDataSource(
name,
abbr,
description,
Date.from(Instant.now()));
externalDataSourceRepository.save(eDS);
}
return eDS;
}
public ModelCreation createModelCreation(String pdxId, ImplantationSite implantationSite, ImplantationType implantationType, Sample sample, BackgroundStrain backgroundStrain, QualityAssurance qa) {
ModelCreation modelCreation = modelCreationRepository.findBySourcePdxId(pdxId);
if (modelCreation != null) {
log.info("Deleting existing ModelCreation " + pdxId);
modelCreationRepository.delete(modelCreation);
}
modelCreation = new ModelCreation(pdxId, implantationSite, implantationType, sample, backgroundStrain, qa);
modelCreationRepository.save(modelCreation);
return modelCreation;
}
public ModelCreation createModelCreation(String pdxId, String implantationSiteStr, String implantationTypeStr, Sample sample, BackgroundStrain backgroundStrain, QualityAssurance qa) {
ImplantationSite implantationSite = this.getImplantationSite(implantationSiteStr);
ImplantationType implantationType = this.getImplantationType(implantationTypeStr);
ModelCreation modelCreation = modelCreationRepository.findBySourcePdxId(pdxId);
if (modelCreation != null) {
log.info("Deleting existing ModelCreation " + pdxId);
modelCreationRepository.delete(modelCreation);
}
modelCreation = new ModelCreation(pdxId, implantationSite, implantationType, sample, backgroundStrain, qa);
modelCreationRepository.save(modelCreation);
return modelCreation;
}
public PatientSnapshot getPatientSnapshot(String externalId, String sex, String race, String ethnicity, String age, ExternalDataSource externalDataSource) {
Patient patient = patientRepository.findByExternalId(externalId);
PatientSnapshot patientSnapshot = null;
if (patient == null) {
log.info("Patient '{}' not found. Creating", externalId);
patient = this.getPatient(externalId, sex, race, ethnicity, externalDataSource);
patientSnapshot = new PatientSnapshot(patient, age);
patientSnapshotRepository.save(patientSnapshot);
} else {
patientSnapshot = this.getPatientSnapshot(patient, age);
}
return patientSnapshot;
}
public PatientSnapshot getPatientSnapshot(Patient patient, String age) {
PatientSnapshot patientSnapshot = null;
Set<PatientSnapshot> pSnaps = patientSnapshotRepository.findByPatient(patient.getExternalId());
loop:
for (PatientSnapshot ps : pSnaps) {
if (ps.getAge().equals(age)) {
patientSnapshot = ps;
break loop;
}
}
if (patientSnapshot == null) {
log.info("PatientSnapshot for patient '{}' at age '{}' not found. Creating", patient.getExternalId(), age);
patientSnapshot = new PatientSnapshot(patient, age);
patientSnapshotRepository.save(patientSnapshot);
}
return patientSnapshot;
}
public Patient getPatient(String externalId, String sex, String race, String ethnicity, ExternalDataSource externalDataSource) {
Patient patient = patientRepository.findByExternalId(externalId);
if (patient == null) {
log.info("Patient '{}' not found. Creating", externalId);
patient = new Patient(externalId, sex, race, ethnicity, externalDataSource);
patientRepository.save(patient);
}
return patient;
}
public Sample getSample(String sourceSampleId, String typeStr, String diagnosis, String originStr, String sampleSiteStr, String extractionMethod, String classification, Boolean normalTissue, ExternalDataSource externalDataSource) {
TumorType type = this.getTumorType(typeStr);
Tissue origin = this.getTissue(originStr);
Tissue sampleSite = this.getTissue(sampleSiteStr);
Sample sample = sampleRepository.findBySourceSampleId(sourceSampleId);
if (sample == null) {
sample = new Sample(sourceSampleId, type, diagnosis, origin, sampleSite, extractionMethod, classification, normalTissue, externalDataSource);
sampleRepository.save(sample);
}
return sample;
}
public Sample getSampleBySourceSampleId(String sourceSampleId){
Sample sample = sampleRepository.findBySourceSampleId(sourceSampleId);
return sample;
}
public Sample getSampleBySourcePdxId(String pdxId){
return sampleRepository.findBySourcePdxId(pdxId);
}
public void saveSample(Sample sample){
sampleRepository.save(sample);
}
public ImplantationSite getImplantationSite(String iSite) {
ImplantationSite site = implantationSiteRepository.findByName(iSite);
if (site == null) {
log.info("Implantation Site '{}' not found. Creating.", iSite);
site = new ImplantationSite(iSite);
implantationSiteRepository.save(site);
}
return site;
}
public ImplantationType getImplantationType(String iType) {
ImplantationType type = implantationTypeRepository.findByName(iType);
if (type == null) {
log.info("Implantation Site '{}' not found. Creating.", iType);
type = new ImplantationType(iType);
implantationTypeRepository.save(type);
}
return type;
}
public Tissue getTissue(String t) {
Tissue tissue = tissueRepository.findByName(t);
if (tissue == null) {
log.info("Tissue '{}' not found. Creating.", t);
tissue = new Tissue(t);
tissueRepository.save(tissue);
}
return tissue;
}
public TumorType getTumorType(String name) {
TumorType tumorType = tumorTypeRepository.findByName(name);
if (tumorType == null) {
log.info("TumorType '{}' not found. Creating.", name);
tumorType = new TumorType(name);
tumorTypeRepository.save(tumorType);
}
return tumorType;
}
public BackgroundStrain getBackgroundStrain(String symbol, String name, String description, String url) {
BackgroundStrain bgStrain = backgroundStrainRepository.findByName(name);
if (bgStrain == null) {
log.info("Background Strain '{}' not found. Creating", name);
bgStrain = new BackgroundStrain(symbol, name, description, url);
backgroundStrainRepository.save(bgStrain);
}
return bgStrain;
}
// is this bad? ... probably..
public Marker getMarker(String symbol) {
return this.getMarker(symbol, symbol);
}
public Marker getMarker(String symbol, String name) {
Marker marker = markerRepository.findByName(name);
if (marker == null && symbol != null) {
marker = markerRepository.findBySymbol(symbol);
}
if (marker == null) {
log.info("Marker '{}' not found. Creating", name);
marker = new Marker(symbol, name);
marker = markerRepository.save(marker);
}
return marker;
}
public Marker getMarkerByEnsemblId(String id){
Marker marker = markerRepository.findByEnsemblId(id);
if (marker == null) {
log.info("Marker '{}' not found. Creating ensemble", id);
marker = new Marker();
marker.setEnsemblId(id);
marker = markerRepository.save(marker);
}
return marker;
}
public MarkerAssociation getMarkerAssociation(String type, String markerSymbol, String markerName) {
Marker m = this.getMarker(markerSymbol, markerName);
MarkerAssociation ma = markerAssociationRepository.findByTypeAndMarkerName(type, m.getName());
if (ma == null && m.getSymbol() != null) {
ma = markerAssociationRepository.findByTypeAndMarkerSymbol(type, m.getSymbol());
}
if (ma == null) {
ma = new MarkerAssociation(type, m);
markerAssociationRepository.save(ma);
}
return ma;
}
// wow this is misleading it doesn't do anyting!
public void deleteAllByEDSName(String edsName) throws Exception {
throw new Exception("Nothing deleted. Method not implemented!");
}
public void savePatientSnapshot(PatientSnapshot ps) {
patientSnapshotRepository.save(ps);
}
public void saveMolecularCharacterization(MolecularCharacterization mc) {
molecularCharacterizationRepository.save(mc);
}
public void saveQualityAssurance(QualityAssurance qa) {
if (qa != null) {
if (null == qualityAssuranceRepository.findFirstByTechnologyAndDescriptionAndValidationTechniques(qa.getTechnology(), qa.getDescription(), qa.getValidationTechniques())) {
qualityAssuranceRepository.save(qa);
}
}
}
public void savePdxPassage(PdxPassage pdxPassage){
pdxPassageRepository.save(pdxPassage);
}
public Specimen getSpecimen(String id){
Specimen specimen = specimenRepository.findByExternalId(id);
if(specimen == null){
specimen = new Specimen();
specimen.setExternalId(id);
}
return specimen;
}
public void saveSpecimen(Specimen specimen){
specimenRepository.save(specimen);
}
public OntologyTerm getOntologyTerm(String url, String label){
OntologyTerm ot = ontologyTermRepository.findByUrl(url);
if(ot == null){
ot = new OntologyTerm(url, label);
ontologyTermRepository.save(ot);
}
return ot;
}
public OntologyTerm getOntologyTerm(String url){
OntologyTerm ot = ontologyTermRepository.findByUrl(url);
return ot;
}
public OntologyTerm getOntologyTermByLabel(String label){
OntologyTerm ot = ontologyTermRepository.findByLabel(label);
return ot;
}
public Collection<OntologyTerm> getAllOntologyTerms() {
Collection<OntologyTerm> ot = ontologyTermRepository.findAll();
return ot;
}
public int getIndirectMappingNumber(String label) {
return ontologyTermRepository.getIndirectMappingNumber(label);
}
public int getDirectMappingNumber(String label) {
Set<OntologyTerm> otset = ontologyTermRepository.getDistinctSubTreeNodes(label);
int mapNum = 0;
for (OntologyTerm ot : otset) {
mapNum += ot.getDirectMappedSamplesNumber();
}
return mapNum;
}
public void saveOntologyTerm(OntologyTerm ot){
ontologyTermRepository.save(ot);
}
public void saveMarker(Marker marker) {
markerRepository.save(marker);
}
public Collection<Marker> getAllMarkers() {
return markerRepository.findAllMarkers();
}
public Collection<Marker> getAllHumanMarkers() {
return markerRepository.findAllHumanMarkers();
}
public Platform getPlatform(String name, ExternalDataSource eds) {
Platform p = platformRepository.findByNameAndDataSource(name, eds.getName());
if (p == null) {
p = new Platform();
p.setName(name);
p.setExternalDataSource(eds);
platformRepository.save(p);
}
return p;
}
public PlatformAssociation createPlatformAssociation(Platform p, Marker m) {
if (platformAssociationRepository == null) {
System.out.println("PAR is null");
}
if (p == null) {
System.out.println("Platform is null");
}
if (p.getExternalDataSource() == null) {
System.out.println("P.EDS is null");
}
if (m == null) {
System.out.println("Marker is null");
}
PlatformAssociation pa = platformAssociationRepository.findByPlatformAndMarker(p.getName(), p.getExternalDataSource().getName(), m.getSymbol());
if (pa == null) {
pa = new PlatformAssociation();
pa.setPlatform(p);
pa.setMarker(m);
platformAssociationRepository.save(pa);
}
return pa;
}
}
|
package net.sourceforge.stripes.util;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Queue;
import java.util.LinkedList;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Arrays;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* Common utilty methods that are useful when working with reflection.
*
* @author Tim Fennell
*/
public class ReflectUtil {
/** Static helper class, shouldn't be constructed. */
private ReflectUtil() {}
/**
* Holds a map of commonly used interface types (mostly collections) to a class that
* implements the interface and will, by default, be instantiated when an instance
* of the iterface is needed.
*/
protected static final Map<Class,Class> interfaceImplementations = new HashMap<Class,Class>();
static {
interfaceImplementations.put(Collection.class, ArrayList.class);
interfaceImplementations.put(List.class, ArrayList.class);
interfaceImplementations.put(Set.class, HashSet.class);
interfaceImplementations.put(SortedSet.class, TreeSet.class);
interfaceImplementations.put(Queue.class, LinkedList.class);
interfaceImplementations.put(Map.class, HashMap.class);
interfaceImplementations.put(SortedMap.class, TreeMap.class);
}
/**
* The set of method that annotation classes inherit, and should be avoided when
* toString()ing an annotation class.
*/
private static final Set<String> INHERITED_ANNOTATION_METHODS =
Literal.set("toString", "equals", "hashCode", "annotationType");
/**
* Looks up the default implementing type for the supplied interface. This is done
* based on a static map of known common interface types and implementing classes.
*
* @param iface an interface for which an implementing class is needed
* @return a Class object representing the implementing type, or null if one is
* not found
*/
public static Class getImplementingClass(Class iface) {
return interfaceImplementations.get(iface);
}
public static <T> T getInterfaceInstance(Class<T> interfaceType)
throws InstantiationException, IllegalAccessException {
Class impl = getImplementingClass(interfaceType);
if (impl == null) {
throw new InstantiationException(
"Stripes needed to instantiate a property who's declared type as an " +
"interface (which obviously cannot be instantiated. The interface is not " +
"one that Stripes is aware of, so no implementing class was known. The " +
"interface type was: '" + interfaceType.getName() + "'. To fix this " +
"you'll need to do one of three things. 1) Change the getter/setter methods " +
"to use a concrete type so that Stripes can instantiate it. 2) in the bean's " +
"setContext() method pre-instantiate the property so Stripes doesn't have to. " +
"3) Bug the Stripes author ;) If the interface is a JDK type it can easily be " +
"fixed. If not, if enough people ask, a generic way to handle the problem " +
"might get implemented.");
}
else {
return (T) impl.newInstance();
}
}
/**
* Utility method used to load a class. Any time that Stripes needs to load of find a
* class by name it uses this method. As a result any time the classloading strategy
* needs to change it can be done in one place! Currently uses
* {@code Thread.currentThread().getContextClassLoader().loadClass(String)}.
*
* @param name the fully qualified (binary) name of the class to find or load
* @return the Class object representing the class
* @throws ClassNotFoundException if the class cannot be loaded
*/
public static Class findClass(String name) throws ClassNotFoundException {
return Thread.currentThread().getContextClassLoader().loadClass(name);
}
/**
* <p>A better (more concise) toString method for annotation types that yields a String
* that should look more like the actual usage of the annotation in a class. The String produced
* is similar to that produced by calling toString() on the annotation directly, with the
* following differences:</p>
*
* <ul>
* <li>Uses the classes simple name instead of it's fully qualified name.</li>
* <li>Only outputs attributes that are set to non-default values.</li>
*
* <p>If, for some unforseen reason, an exception is thrown within this method it will be
* caught and the return value will be {@code ann.toString()}.
*
* @param ann the annotation to convert to a human readable String
* @return a human readable String form of the annotation and it's attributes
*/
public static String toString(Annotation ann) {
try {
Class<? extends Annotation> type = ann.annotationType();
StringBuilder builder = new StringBuilder(128);
builder.append("@");
builder.append(type.getSimpleName());
boolean appendedAnyParameters = false;
Method[] methods = type.getMethods();
for (Method method : methods) {
if (!INHERITED_ANNOTATION_METHODS.contains(method.getName())) {
Object defaultValue = method.getDefaultValue();
Object actualValue = method.invoke(ann);
// If we have arrays, they have to be treated a little differently
Object[] defaultArray = null, actualArray = null;
if ( Object[].class.isAssignableFrom(method.getReturnType()) ) {
defaultArray = (Object[]) defaultValue;
actualArray = (Object[]) actualValue;
}
// Only print an attribute if it isn't set to the default value
if ( (defaultArray != null && !Arrays.equals(defaultArray, actualArray)) ||
(defaultArray == null && !actualValue.equals(defaultValue)) ) {
if (appendedAnyParameters) {
builder.append(", ");
}
else {
builder.append("(");
}
builder.append(method.getName());
builder.append("=");
if (actualArray != null) {
builder.append( Arrays.toString(actualArray) );
}
else {
builder.append(actualValue);
}
appendedAnyParameters = true;
}
}
}
if (appendedAnyParameters) {
builder.append(")");
}
return builder.toString();
}
catch (Exception e) {
return ann.toString();
}
}
}
|
package com.cloud.migration;
import java.io.File;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import org.apache.log4j.xml.DOMConfigurator;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.ResourceCountVO;
import com.cloud.configuration.dao.ResourceCountDao;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.user.Account;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.vm.InstanceGroupVMMapVO;
import com.cloud.vm.InstanceGroupVO;
import com.cloud.vm.dao.InstanceGroupDao;
import com.cloud.vm.dao.InstanceGroupVMMapDao;
public class Db21to22MigrationUtil {
private AccountDao _accountDao;
private DomainDao _domainDao;
private ResourceCountDao _resourceCountDao;
private InstanceGroupDao _vmGroupDao;
private InstanceGroupVMMapDao _groupVMMapDao;
private void doMigration() {
setupComponents();
migrateResourceCounts();
setupInstanceGroups();
System.out.println("Migration done");
}
private void migrateResourceCounts() {
System.out.println("migrating resource counts");
SearchBuilder<ResourceCountVO> sb = _resourceCountDao.createSearchBuilder();
sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
for (ResourceType type : ResourceType.values()) {
SearchCriteria<ResourceCountVO> sc = sb.create();
sc.setParameters("type", type);
List<ResourceCountVO> resourceCounts = _resourceCountDao.search(sc, null);
for (ResourceCountVO resourceCount : resourceCounts) {
if (resourceCount.getAccountId() != null) {
Account acct = _accountDao.findById(resourceCount.getAccountId());
Long domainId = acct.getDomainId();
while (domainId != null) {
_resourceCountDao.updateDomainCount(domainId, type, true, resourceCount.getCount());
DomainVO domain = _domainDao.findById(domainId);
domainId = domain.getParent();
}
}
}
}
System.out.println("done migrating resource counts");
}
private void setupComponents() {
ComponentLocator.getLocator("migration", "migration-components.xml", "log4j-cloud.xml");
ComponentLocator locator = ComponentLocator.getCurrentLocator();
_accountDao = locator.getDao(AccountDao.class);
_domainDao = locator.getDao(DomainDao.class);
_resourceCountDao = locator.getDao(ResourceCountDao.class);
_vmGroupDao = locator.getDao(InstanceGroupDao.class);
_groupVMMapDao = locator.getDao(InstanceGroupVMMapDao.class);
}
private void setupInstanceGroups() {
System.out.println("setting up vm instance groups");
//Search for all the vms that have not null groups
long vmId = 0;
long accountId = 0;
String groupName;
Transaction txn = Transaction.open(Transaction.CLOUD_DB);
txn.start();
try {
String request = "SELECT vm.id, uservm.account_id, vm.group from vm_instance vm, user_vm uservm where vm.group is not null and vm.removed is null and vm.id=uservm.id order by id";
PreparedStatement statement = txn.prepareAutoCloseStatement(request);
ResultSet result = statement.executeQuery();
while (result.next()) {
vmId = result.getLong(1);
accountId = result.getLong(2);
groupName = result.getString(3);
InstanceGroupVO group = _vmGroupDao.findByAccountAndName(vmId, groupName);
//Create vm group if the group doesn't exist for this account
if (group == null) {
group = new InstanceGroupVO(groupName, accountId);
group = _vmGroupDao.persist(group);
}
if (group != null) {
InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(group.getId(), vmId);
_groupVMMapDao.persist(groupVmMapVO);
}
}
statement.close();
txn.commit();
} catch (Exception e) {
System.out.println("Unhandled exception: " + e);
} finally {
txn.close();
}
}
public static void main(String[] args) {
File file = PropertiesUtil.findConfigFile("log4j-cloud.xml");
if (file != null) {
System.out.println("Log4j configuration from : " + file.getAbsolutePath());
DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
} else {
System.out.println("Configure log4j with default properties");
}
new Db21to22MigrationUtil().doMigration();
System.exit(0);
}
}
|
package org.kie.scanner;
import org.drools.kproject.models.KieModuleModelImpl;
import org.kie.builder.ReleaseId;
import org.kie.builder.KieModule;
import org.kie.builder.KieScanner;
import org.kie.builder.Message;
import org.kie.builder.impl.InternalKieModule;
import org.kie.builder.impl.InternalKieScanner;
import org.kie.builder.impl.MemoryKieModule;
import org.kie.builder.impl.ResultsImpl;
import org.kie.builder.impl.ZipKieModule;
import org.kie.builder.model.KieModuleModel;
import org.kie.runtime.KieContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.aether.artifact.Artifact;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static org.kie.scanner.ArtifactResolver.getResolverFor;
import static org.kie.builder.impl.KieBuilderImpl.buildKieModule;
public class KieRepositoryScannerImpl implements InternalKieScanner {
private Timer timer;
private static final Logger log = LoggerFactory.getLogger(KieScanner.class);
private KieContainer kieContainer;
private final Set<DependencyDescriptor> usedDependencies = new HashSet<DependencyDescriptor>();
private ArtifactResolver artifactResolver;
public void setKieContainer(KieContainer kieContainer) {
this.kieContainer = kieContainer;
ReleaseId releaseId = kieContainer.getReleaseId();
if (releaseId == null) {
throw new RuntimeException("The KieContainer's ReleaseId cannot be null. Are you using a KieClasspathContainer?");
}
DependencyDescriptor projectDescr = new DependencyDescriptor(releaseId);
if (!projectDescr.isFixedVersion()) {
usedDependencies.add(projectDescr);
}
artifactResolver = getResolverFor(kieContainer.getReleaseId(), true);
init();
}
private ArtifactResolver getArtifactResolver() {
if (artifactResolver == null) {
artifactResolver = new ArtifactResolver();
}
return artifactResolver;
}
private void init() {
Collection<Artifact> artifacts = findKJarAtifacts();
log.info("Artifacts containing a kjar: " + artifacts);
if (artifacts.isEmpty()) {
log.info("There's no artifacts containing a kjar: shutdown the scanner");
return;
}
indexAtifacts(artifacts);
}
public KieModule loadArtifact(ReleaseId releaseId) {
return loadArtifact(releaseId, null);
}
public KieModule loadArtifact(ReleaseId releaseId, InputStream pomXml) {
String artifactName = releaseId.toString();
ArtifactResolver resolver = pomXml != null ? ArtifactResolver.getResolverFor(pomXml) : getArtifactResolver();
Artifact artifact = resolver.resolveArtifact(artifactName);
return artifact != null ? buildArtifact(releaseId, artifact, resolver) : loadPomArtifact(releaseId);
}
private KieModule loadPomArtifact(ReleaseId releaseId) {
ArtifactResolver resolver = getResolverFor(releaseId, false);
if (resolver == null) {
return null;
}
MemoryKieModule kieModule = new MemoryKieModule(releaseId);
addDependencies(kieModule, resolver, resolver.getPomDirectDependencies());
build(kieModule);
return kieModule;
}
private InternalKieModule buildArtifact(ReleaseId releaseId, Artifact artifact, ArtifactResolver resolver) {
ZipKieModule kieModule = createZipKieModule(releaseId, artifact.getFile());
if (kieModule != null) {
addDependencies(kieModule, resolver, resolver.getArtifactDependecies(new DependencyDescriptor(artifact).toString()));
build(kieModule);
}
return kieModule;
}
private void addDependencies(InternalKieModule kieModule, ArtifactResolver resolver, List<DependencyDescriptor> dependencies) {
for (DependencyDescriptor dep : dependencies) {
Artifact depArtifact = resolver.resolveArtifact(dep.toString());
if (isKJar(depArtifact.getFile())) {
ReleaseId depReleaseId = new DependencyDescriptor(depArtifact).getGav();
ZipKieModule zipKieModule = createZipKieModule(depReleaseId, depArtifact.getFile());
if (zipKieModule != null) {
kieModule.addDependency(zipKieModule);
}
}
}
}
private static ZipKieModule createZipKieModule(ReleaseId releaseId, File jar) {
KieModuleModel kieModuleModel = getKieModuleModelFromJar(jar);
return kieModuleModel != null ? new ZipKieModule(releaseId, kieModuleModel, jar) : null;
}
private static KieModuleModel getKieModuleModelFromJar(File jar) {
ZipFile zipFile = null;
try {
zipFile = new ZipFile( jar );
ZipEntry zipEntry = zipFile.getEntry(KieModuleModelImpl.KMODULE_JAR_PATH);
return KieModuleModelImpl.fromXML(zipFile.getInputStream(zipEntry));
} catch ( Exception e ) {
} finally {
try {
zipFile.close();
} catch ( IOException e ) { }
}
return null;
}
private ResultsImpl build(InternalKieModule kieModule) {
ResultsImpl messages = new ResultsImpl();
buildKieModule(kieModule, messages);
return messages;
}
public void start(long pollingInterval) {
if (pollingInterval <= 0) {
throw new IllegalArgumentException("pollingInterval must be positive");
}
if (timer != null) {
throw new IllegalStateException("The scanner is already running");
}
startScanTask(pollingInterval);
}
public void stop() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
private void startScanTask(long pollingInterval) {
timer = new Timer(true);
timer.schedule(new ScanTask(), pollingInterval, pollingInterval);
}
private class ScanTask extends TimerTask {
public void run() {
scanNow();
}
}
public void scanNow() {
Collection<Artifact> updatedArtifacts = scanForUpdates(usedDependencies);
if (updatedArtifacts.isEmpty()) {
return;
}
for (Artifact artifact : updatedArtifacts) {
DependencyDescriptor depDescr = new DependencyDescriptor(artifact);
usedDependencies.remove(depDescr);
usedDependencies.add(depDescr);
updateKieModule(artifact, depDescr.getGav());
}
log.info("The following artifacts have been updated: " + updatedArtifacts);
}
private void updateKieModule(Artifact artifact, ReleaseId releaseId) {
ZipKieModule kieModule = createZipKieModule(releaseId, artifact.getFile());
if (kieModule != null) {
ResultsImpl messages = build(kieModule);
if ( messages.filterMessages(Message.Level.ERROR).isEmpty()) {
kieContainer.updateToVersion(releaseId);
}
}
}
private Collection<Artifact> scanForUpdates(Collection<DependencyDescriptor> dependencies) {
List<Artifact> newArtifacts = new ArrayList<Artifact>();
for (DependencyDescriptor dependency : dependencies) {
Artifact newArtifact = getArtifactResolver().resolveArtifact(dependency.toResolvableString());
if (newArtifact == null) {
continue;
}
DependencyDescriptor resolvedDep = new DependencyDescriptor(newArtifact);
if (resolvedDep.isNewerThan(dependency)) {
newArtifacts.add(newArtifact);
}
}
return newArtifacts;
}
private void indexAtifacts(Collection<Artifact> artifacts) {
for (Artifact artifact : artifacts) {
usedDependencies.add(new DependencyDescriptor(artifact));
}
}
private Collection<Artifact> findKJarAtifacts() {
Collection<DependencyDescriptor> deps = getArtifactResolver().getAllDependecies();
deps = filterNonFixedDependecies(deps);
Collection<Artifact> artifacts = resolveArtifacts(deps);
return filterKJarArtifacts(artifacts);
}
private Collection<DependencyDescriptor> filterNonFixedDependecies(Collection<DependencyDescriptor> dependencies) {
List<DependencyDescriptor> nonFixedDeps = new ArrayList<DependencyDescriptor>();
for (DependencyDescriptor dep : dependencies) {
if (!dep.isFixedVersion()) {
nonFixedDeps.add(dep);
}
}
return nonFixedDeps;
}
private List<Artifact> resolveArtifacts(Collection<DependencyDescriptor> dependencies) {
List<Artifact> artifacts = new ArrayList<Artifact>();
for (DependencyDescriptor dep : dependencies) {
Artifact artifact = getArtifactResolver().resolveArtifact(dep.toString());
artifacts.add(artifact);
log.debug( artifact + " resolved to " + artifact.getFile() );
}
return artifacts;
}
private Collection<Artifact> filterKJarArtifacts(Collection<Artifact> artifacts) {
List<Artifact> kJarArtifacts = new ArrayList<Artifact>();
for (Artifact artifact : artifacts) {
if (isKJar(artifact.getFile())) {
kJarArtifacts.add(artifact);
}
}
return kJarArtifacts;
}
private boolean isKJar(File jar) {
ZipFile zipFile;
try {
zipFile = new ZipFile( jar );
} catch (IOException e) {
throw new RuntimeException(e);
}
ZipEntry zipEntry = zipFile.getEntry( KieModuleModelImpl.KMODULE_JAR_PATH );
return zipEntry != null;
}
}
|
package org.intermine.pathquery;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.metadata.AttributeDescriptor;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.CollectionDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.util.StringUtil;
import org.intermine.util.TypeUtil;
import org.intermine.util.Util;
/**
* Object to represent a path through an InterMine model. Construction from
* a String validates against model.
* @author Richard Smith
*/
public class Path
{
protected static final Logger LOG = Logger.getLogger(Path.class);
private ClassDescriptor startCld;
private List<String> elements;
private FieldDescriptor endFld;
private final Model model;
private String path;
private boolean containsCollections = false;
private boolean containsReferences = false;
private final Map<String, String> subClassConstraintPaths;
private List<ClassDescriptor> elementClassDescriptors;
private final List<Boolean> outers;
/**
* Create a new Path object. The Path must start with a class name.
* @param model the Model used to check ClassDescriptors and FieldDescriptors
* @param path a String of the form "Department.manager.name" or
* "Department.employees[Manager].seniority"
* @throws PathException thrown if there is a problem resolving the path eg. a reference doesn't
* exist in the model
*/
public Path(Model model, String path) throws PathException {
if (model == null) {
throw new IllegalArgumentException("model argument is null");
}
this.model = model;
if (path == null) {
throw new IllegalArgumentException("path argument is null");
}
if (StringUtils.isBlank(path)) {
throw new IllegalArgumentException("path argument is blank");
}
subClassConstraintPaths = new HashMap<String, String>();
Pattern p = Pattern.compile("([^\\[\\]]+)\\[(.*)\\]");
List<String> newPathBits = new ArrayList<String>();
List<Boolean> newPathOuters = new ArrayList<Boolean>();
StringTokenizer bits = new StringTokenizer(". " + path, ".:", true);
boolean notFirst = false;
while (bits.hasMoreTokens()) {
String separator = bits.nextToken();
String thisBit = bits.nextToken();
if (notFirst) {
newPathOuters.add(Boolean.valueOf(":".equals(separator)));
} else {
thisBit = thisBit.substring(1);
notFirst = true;
}
Matcher m = p.matcher(thisBit);
if (m.matches()) {
String pathBit = m.group(1);
String className = m.group(2);
newPathBits.add(pathBit);
subClassConstraintPaths.put(StringUtil.join(newPathBits, "."), className);
} else {
newPathBits.add(thisBit);
}
}
this.path = StringUtil.join(newPathBits, ".");
this.outers = newPathOuters;
initialise();
}
/**
* Create a Path object using class constraints from a Map. Unlike the other constructor, the
* stringPath cannot contain class constraint annotation. Either call the other constructor
* like this: new Path(model, "Department.employees[Manager].seniority") or call this
* constructor like this: new Path(model, "Department.employees.seniority", map) where the
* map contains: key "Department.employees" -> value: "Manager"
*
* @param model the Model used to check ClassDescriptors and FieldDescriptors
* @param stringPath a String of the form "Department.manager.name"
* @param constraintMap a Map from paths as string to class names - use when parts of the path
* are constrained to be sub-classes
* @throws PathException thrown if there is a problem resolving the path eg. a reference doesn't
* exist in the model
*/
public Path(Model model, String stringPath, Map<String, String> constraintMap)
throws PathException {
this.model = model;
if (stringPath == null) {
throw new IllegalArgumentException("path argument is null");
}
if (StringUtils.isBlank(stringPath)) {
throw new IllegalArgumentException("path argument is blank");
}
this.path = stringPath;
this.subClassConstraintPaths = new HashMap<String, String>(constraintMap);
// validatePath(constraintMap, stringPath);
for (String constaintPath: subClassConstraintPaths.keySet()) {
if (constaintPath.indexOf(':') != -1) {
throw new IllegalArgumentException("illegal character (':') in constraint map");
}
}
if (path.indexOf("[") != -1) {
throw new IllegalArgumentException("path: " + stringPath
+ " contains illegal character '['");
}
List<String> newPathBits = new ArrayList<String>();
List<Boolean> newPathOuters = new ArrayList<Boolean>();
StringTokenizer bits = new StringTokenizer(". " + path, ".:", true);
boolean notFirst = false;
while (bits.hasMoreTokens()) {
String separator = bits.nextToken();
String thisBit = bits.nextToken();
if (notFirst) {
newPathOuters.add(Boolean.valueOf(":".equals(separator)));
} else {
thisBit = thisBit.substring(1);
notFirst = true;
}
newPathBits.add(thisBit);
}
this.path = StringUtil.join(newPathBits, ".");
this.outers = newPathOuters;
initialise();
}
// /**
// * Method checks if there isn't incompatible join, when for example department is once joined
// * in constraint as inner join and in other constraint as outer join.
// * @param constraintMap
// * @param stringPath
// */
// private void validatePath(Map<String, String> constraintMap, String stringPath) {
// Set<String> paths = new HashSet<String>(constraintMap.keySet());
// paths.add(stringPath);
// for (String constraint : paths) {
// String[] parts = constraint.split(":");
// String prefix = "";
// for (int i = 0; i < parts.length - 1; i++) {
// String part = parts[i];
// prefix += part + ".";
// for (String checkedString : paths) {
// if (checkedString.startsWith(prefix)) {
// + constraint + ", " + checkedString);
private void initialise() throws PathException {
elements = new ArrayList<String>();
elementClassDescriptors = new ArrayList<ClassDescriptor>();
String[] parts = path.split("[.]");
String clsName = parts[0];
ClassDescriptor cld = null;
if (!("".equals(clsName))) {
cld = model.getClassDescriptorByName(model.getPackageName() + "." + clsName);
if (cld == null) {
throw new PathException("Unable to resolve path '" + path + "': class '" + clsName
+ "' not found in model '" + model.getName() + "'", path);
}
this.startCld = cld;
elementClassDescriptors.add(cld);
} else {
LOG.error("First part is empty. Path is \"" + path + "\"");
}
StringBuffer currentPath = new StringBuffer(parts[0]);
for (int i = 1; i < parts.length; i++) {
currentPath.append(".");
String thisPart = parts[i];
currentPath.append(thisPart);
elements.add(thisPart);
if (!("".equals(clsName))) {
FieldDescriptor fld = cld.getFieldDescriptorByName(thisPart);
if (fld == null) {
throw new PathException("Unable to resolve path '" + path + "': field '"
+ thisPart + "' of class '" + cld.getName()
+ "' not found in model '" + model.getName() + "'", path);
}
// if this is a collection then mark the whole path as containing collections
if (fld.isCollection()) {
this.containsCollections = true;
}
if (fld.isReference()) {
this.containsReferences = true;
}
if (i < parts.length - 1) {
// check if attribute and not at end of path
if (fld.isAttribute()) {
throw new PathException("Unable to resolve path '" + path + "': field '"
+ thisPart + "' of class '" + cld.getName()
+ "' is not a reference/collection field in the model '"
+ model.getName() + "'", path);
}
} else {
this.endFld = fld;
}
if (!fld.isAttribute()) {
String constrainedClassName =
subClassConstraintPaths.get(currentPath.toString());
if (constrainedClassName == null) {
// the class of this reference/collection is not constrained so get the
// class name from the model
cld = ((ReferenceDescriptor) fld).getReferencedClassDescriptor();
} else {
String qualifiedClassName = model.getPackageName() + "."
+ constrainedClassName;
cld = model.getClassDescriptorByName(qualifiedClassName);
if (cld == null) {
throw new PathException("Unable to resolve path '" + path + "': class '"
+ qualifiedClassName + "' not found in model '"
+ model.getName() + "'", path);
}
}
elementClassDescriptors.add(cld);
}
}
}
}
/**
* Returns a list of paths, each corresponding to one step further along the path. Starts with
* the root path, and ends in the current path, ie:
*
* Company.departments.manager.name
* decomposes to:
* Company, Company.departments, Company.departments.manager, Company.departments.manager.name
*
* @return the list of composing paths.
*/
public List<Path> decomposePath() {
List<Path> pathList = new ArrayList<Path>();
pathList.add(this);
Path currentPath = this;
while (!currentPath.isRootPath()) {
Path nextPath = currentPath.getPrefix();
pathList.add(nextPath);
currentPath = nextPath;
}
Collections.reverse(pathList);
return pathList;
}
/**
* Return true if and only if any part of the path is a collection.
* @return the collections flag
*/
public boolean containsCollections() {
return containsCollections;
}
/**
* Return true if and only if any part of the path is a reference.
* @return the references flag
*/
public boolean containsReferences() {
return containsReferences;
}
/**
* Return true if the Path does not contain references or collections
* @return a boolean
*/
public boolean isOnlyAttribute() {
return (!containsReferences && !containsCollections);
}
/**
* Return true if and only if the end of the path is an attribute.
* @return the end-is-attribute flag
*/
public boolean endIsAttribute() {
if (endFld == null) {
return false;
}
return endFld.isAttribute();
}
/**
* Return true if and only if the end of the path is a collection.
* @return the end-is-collection flag
*/
public boolean endIsCollection() {
if (endFld == null) {
return false;
}
return endFld.isCollection();
}
/**
* Return true if and only if the end of the path is a reference .
* @return the end-is-reference flag
*/
public boolean endIsReference() {
if (endFld == null) {
return false;
}
return endFld.isReference();
}
/**
* Return the ClassDescriptor of the first element in the path. eg. for Department.name,
* return the Department descriptor.
* @return the starting ClassDescriptor
*/
public ClassDescriptor getStartClassDescriptor() {
return startCld;
}
/**
* Return the FieldDescriptor of the last element in the path or null if the path has just one
* element. eg. for "Employee.department.name", return the Department.name descriptor but
* for "Employee" return null.
* @return the end FieldDescriptor
*/
public FieldDescriptor getEndFieldDescriptor() {
return endFld;
}
/**
* If the last element in the path is a reference or collection return the ClassDescriptor that
* the reference or collection references. If the path has one element (eg. "Employee"),
* return its ClassDescriptor. If the last element in the path is an attribute, return null.
* @return the ClassDescriptor
*/
public ClassDescriptor getEndClassDescriptor() {
if (getEndFieldDescriptor() == null) {
return getStartClassDescriptor();
}
if (!getEndFieldDescriptor().isAttribute()) {
if (getEndFieldDescriptor().isCollection()) {
CollectionDescriptor collDesc = (CollectionDescriptor) getEndFieldDescriptor();
return collDesc.getReferencedClassDescriptor();
}
if (getEndFieldDescriptor().isReference()) {
ReferenceDescriptor refDesc = (ReferenceDescriptor) getEndFieldDescriptor();
return refDesc.getReferencedClassDescriptor();
}
}
return null;
}
/**
* Return a Path object that represents the prefix of this path, ie this Path without the
* last element. If the Path contains only the root class, an exception is thrown.
*
* @return the prefix Path
*/
public Path getPrefix() {
if (isRootPath()) {
throw new RuntimeException("path (" + this + ") has only one element");
}
String pathString = toString();
int lastDotIndex = pathString.lastIndexOf('.');
int lastIndex = pathString.lastIndexOf(':');
if (lastDotIndex > lastIndex) {
lastIndex = lastDotIndex;
}
try {
return new Path(model, pathString.substring(0, lastIndex));
} catch (PathException e) {
// Should not happen
throw new Error("There must be a bug", e);
}
}
/**
* Return new Path that has this Path as its prefix and has fieldName as the last element.
*
* @param fieldName the field name
* @return the new Path
* @throws PathException if the resulting Path is not valid
*/
public Path append(String fieldName) throws PathException {
return new Path(model, toString() + "." + fieldName);
}
/**
* Return the type of the last element in the path, regardless of whether it is an attribute
* or a class.
* @return the Class of the last element
*/
public Class<?> getEndType() {
Class<?> retval = null;
if (endFld != null && endFld.isAttribute()) {
retval = Util.getClassFromString(((AttributeDescriptor) endFld).getType());
} else {
retval = getLastClassDescriptor().getType();
}
return retval;
}
public ClassDescriptor getLastClassDescriptor() {
List<ClassDescriptor> l = getElementClassDescriptors();
return l.get(l.size() - 1);
}
/**
* Returns the second to last ClassDescriptor in the path. That is, the one before the one
* returned by getLastClassDescriptor.
*
* @return the ClassDescriptor
*/
public ClassDescriptor getSecondLastClassDescriptor() {
List<ClassDescriptor> l = getElementClassDescriptors();
return l.get(l.size() - 2);
}
/**
* Return the last string element of this path, throw an exception of there is only one element,
* i.e. for 'Company.departments.manager' return 'manager'.
* @return the last string element of the path
*/
public String getLastElement() {
if (isRootPath()) {
throw new RuntimeException("path (" + this + ") has only one element");
}
return elements.get(elements.size() - 1);
}
/**
* Return true if this path represents just the starting class, e.g. 'Department'. Returns
* false of there are further elements, e.g. 'Department.manager'
* @return true if this is a root path
*/
public boolean isRootPath() {
if (getElements().size() == 0) {
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override public boolean equals(Object o) {
if (o instanceof Path) {
Path p = (Path) o;
return (p.startCld.equals(this.startCld)
&& p.elements.equals(this.elements));
}
return false;
}
/**
* Returns a representation of the Path as a String, with class constraint markers. eg.
* "Department.employees[Manager].seniority"
* {@inheritDoc}
*/
@Override public String toString() {
String cdUnqualifiedName = getStartClassDescriptor().getUnqualifiedName();
StringBuffer returnStringBuffer = new StringBuffer(cdUnqualifiedName);
// the path without class constraints
StringBuffer simplePath = new StringBuffer(cdUnqualifiedName);
for (int i = 0; i < elements.size(); i++) {
returnStringBuffer.append(outers.get(i).booleanValue() ? ":" : ".");
simplePath.append(".");
String fieldName = elements.get(i);
returnStringBuffer.append(fieldName);
simplePath.append(fieldName);
String constraintClassName =
subClassConstraintPaths.get(simplePath.toString());
if (constraintClassName != null) {
if (startCld != null) {
FieldDescriptor fieldDescriptor = elementClassDescriptors.get(i)
.getFieldDescriptorByName(fieldName);
if (fieldDescriptor.isReference() || fieldDescriptor.isCollection()) {
String referencedClassName =
((ReferenceDescriptor) fieldDescriptor).getReferencedClassName();
if (!TypeUtil.unqualifiedName(referencedClassName)
.equals(constraintClassName)) {
returnStringBuffer.append('[');
returnStringBuffer.append(constraintClassName);
returnStringBuffer.append(']');
}
}
} else {
returnStringBuffer.append('[')
.append(constraintClassName)
.append(']');
}
}
}
return returnStringBuffer.toString();
}
/**
* {@inheritDoc}
*/
@Override public int hashCode() {
return 0;
}
/**
* Return a list of field names, one per path element (except for the first, which is a
* class). To clarify, this does not include the root class of the path.
*
* @return a list of field names
*/
public List<String> getElements() {
return elements;
}
/**
* Return a List of the ClassDescriptor objects for each element of the path.
* @return the ClassDescriptors
*/
public List<ClassDescriptor> getElementClassDescriptors() {
return elementClassDescriptors;
}
/**
* Returns a representation of the Path as a String, with no class constraint markers. eg.
* "Department.employees.seniority"
* @return a String version of the Path
*/
public String toStringNoConstraints() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < elements.size(); i++) {
sb.append(outers.get(i).booleanValue() ? ":" : ".");
sb.append(elements.get(i));
}
return getStartClassDescriptor().getUnqualifiedName() + sb.toString();
}
/**
* Required for jsp
* @return a String version of the Path
*/
public String getNoConstraintsString() {
return toStringNoConstraints();
}
/**
* Returns a Map from simplified path string (with dots instead of colons, and no constraints)
* to constraint class name.
*
* @return subClassConstraintPaths
*/
public Map<String, String> getSubClassConstraintPaths() {
return subClassConstraintPaths;
}
/**
* Return the model that this path is created for.
* @return the model
*/
public Model getModel() {
return model;
}
}
|
package org.glob3.mobile.generated;
// GL.cpp
// Glob3 Mobile
// GL.hpp
// Glob3 Mobile
public class GL
{
private final INativeGL _gl;
private MutableMatrix44D _modelView = new MutableMatrix44D();
// stack of ModelView matrices
private java.util.LinkedList<MutableMatrix44D> _matrixStack = new java.util.LinkedList<MutableMatrix44D>();
private java.util.LinkedList<Integer> _texturesIdBag = new java.util.LinkedList<Integer>();
private int _texturesIdCounter;
// state handling
private boolean _enableTextures;
private boolean _enableTexture2D;
private boolean _enableVertexColor;
private boolean _enableVertexNormal;
private boolean _enableVerticesPosition;
private boolean _enableFlatColor;
private boolean _enableDepthTest;
private boolean _enableBlend;
private boolean _enableCullFace;
private GLCullFace _cullFace_face = GLCullFace.Back;
//C++ TO JAVA CONVERTER NOTE: This was formerly a static local variable declaration (not allowed in Java):
private float[] loadModelView_M = new float[16];
private void loadModelView()
{
//C++ TO JAVA CONVERTER NOTE: This static local variable declaration (not allowed in Java) has been moved just prior to the method:
// static float M[16];
_modelView.copyToFloatMatrix(loadModelView_M);
_gl.uniformMatrix4fv(GlobalMembersGL.Uniforms.Modelview, 1, false, loadModelView_M);
}
private int getTextureID()
{
if (_texturesIdBag.size() == 0)
{
final int bugdetSize = 256;
System.out.printf("= Creating %d texturesIds...\n", bugdetSize);
final java.util.ArrayList<Integer> ids = _gl.genTextures(bugdetSize);
for (int i = 0; i < bugdetSize; i++)
{
_texturesIdBag.addLast(ids.get(i));
}
_texturesIdCounter += bugdetSize;
System.out.printf("= Created %d texturesIds (accumulated %ld).\n", bugdetSize, _texturesIdCounter);
}
int result = _texturesIdBag.getLast();
_texturesIdBag.removeLast();
// printf(" - Assigning 1 texturesId from bag (bag size=%ld).\n", _texturesIdBag.size());
return result;
}
public GL(INativeGL gl)
{
_gl = gl;
_enableTextures = false;
_enableTexture2D = false;
_enableVertexColor = false;
_enableVertexNormal = false;
_enableVerticesPosition = false;
_enableFlatColor = false;
_enableBlend = false;
_enableDepthTest = false;
_enableCullFace = false;
_cullFace_face = GLCullFace.Back;
_texturesIdCounter = 0;
}
public void dispose()
{
}
public final void enableVerticesPosition()
{
if (!_enableVerticesPosition)
{
_gl.enableVertexAttribArray(GlobalMembersGL.Attributes.Position);
_enableVerticesPosition = true;
}
}
// state handling
public final void enableTextures()
{
if (!_enableTextures)
{
_gl.enableVertexAttribArray(GlobalMembersGL.Attributes.TextureCoord);
_enableTextures = true;
}
}
//C++ TO JAVA CONVERTER TODO TASK: The implementation of the following method could not be found:
// void verticesColors(boolean v);
public final void enableTexture2D()
{
if (!_enableTexture2D)
{
_gl.uniform1i(GlobalMembersGL.Uniforms.EnableTexture, 1);
_enableTexture2D = true;
}
}
public final void enableVertexFlatColor(float r, float g, float b, float a, float intensity)
{
if (!_enableFlatColor)
{
_gl.uniform1i(GlobalMembersGL.Uniforms.EnableFlatColor, 1);
_enableFlatColor = true;
}
_gl.uniform4f(GlobalMembersGL.Uniforms.FlatColor, r, g, b, a);
_gl.uniform1f(GlobalMembersGL.Uniforms.FlatColorIntensity, intensity);
}
public final void disableVertexFlatColor()
{
if (_enableFlatColor)
{
_gl.uniform1i(GlobalMembersGL.Uniforms.EnableFlatColor, 0);
_enableFlatColor = false;
}
}
public final void disableTexture2D()
{
if (_enableTexture2D)
{
_gl.uniform1i(GlobalMembersGL.Uniforms.EnableTexture, 0);
_enableTexture2D = false;
}
}
public final void disableVerticesPosition()
{
if (_enableVerticesPosition)
{
_gl.disableVertexAttribArray(GlobalMembersGL.Attributes.Position);
_enableVerticesPosition = false;
}
}
public final void disableTextures()
{
if (_enableTextures)
{
_gl.disableVertexAttribArray(GlobalMembersGL.Attributes.TextureCoord);
_enableTextures = false;
}
}
public final void clearScreen(float r, float g, float b, float a)
{
_gl.clearColor(r, g, b, a);
GLBufferType[] buffers = { ColorBuffer, DepthBuffer };
_gl.clear(2, buffers);
}
public final void color(float r, float g, float b, float a)
{
_gl.uniform4f(GlobalMembersGL.Uniforms.FlatColor, r, g, b, a);
}
public final void enableVertexColor(float[] colors, float intensity)
{
if (!_enableVertexColor)
{
_gl.uniform1i(GlobalMembersGL.Uniforms.EnableColorPerVertex, 1);
_gl.enableVertexAttribArray(GlobalMembersGL.Attributes.Color);
_gl.vertexAttribPointer(GlobalMembersGL.Attributes.Color, 4, Float, 0, 0, colors);
_gl.uniform1f(GlobalMembersGL.Uniforms.ColorPerVertexIntensity, intensity);
_enableVertexColor = true;
}
}
public final void disableVertexColor()
{
if (_enableVertexColor)
{
_gl.disableVertexAttribArray(GlobalMembersGL.Attributes.Color);
_gl.uniform1i(GlobalMembersGL.Uniforms.EnableColorPerVertex, 0);
_enableVertexColor = false;
}
}
public final void enableVertexNormal(float[] normals)
{
// if (normals != NULL) {
if (!_enableVertexNormal)
{
_gl.enableVertexAttribArray(GlobalMembersGL.Attributes.Normal);
_gl.vertexAttribPointer(GlobalMembersGL.Attributes.Normal, 3, Float, 0, 0, normals);
_enableVertexNormal = true;
}
}
public final void disableVertexNormal()
{
if (_enableVertexNormal)
{
_gl.disableVertexAttribArray(GlobalMembersGL.Attributes.Normal);
_enableVertexNormal = false;
}
}
public final void pushMatrix()
{
_matrixStack.addLast(_modelView);
}
public final void popMatrix()
{
_modelView = _matrixStack.getLast();
_matrixStack.removeLast();
loadModelView();
}
public final void loadMatrixf(MutableMatrix44D modelView)
{
_modelView = modelView;
loadModelView();
}
public final void multMatrixf(MutableMatrix44D m)
{
_modelView = _modelView.multiply(m);
loadModelView();
}
public final void vertexPointer(int size, int stride, float[] vertex)
{
_gl.vertexAttribPointer(GlobalMembersGL.Attributes.Position, size, Float, 0, stride, (Object) vertex);
}
public final void drawTriangleStrip(int n, int[] i)
{
_gl.drawElements(TriangleStrip, n, UnsignedInt, i);
}
public final void drawLines(int n, int[] i)
{
_gl.drawElements(Lines, n, UnsignedInt, i);
}
public final void drawLineLoop(int n, int[] i)
{
_gl.drawElements(LineLoop, n, UnsignedInt, i);
}
public final void drawPoints(int n, int[] i)
{
_gl.drawElements(Points, n, UnsignedInt, i);
}
//C++ TO JAVA CONVERTER NOTE: This was formerly a static local variable declaration (not allowed in Java):
private float[] setProjection_M = new float[16];
public final void setProjection(MutableMatrix44D projection)
{
//C++ TO JAVA CONVERTER NOTE: This static local variable declaration (not allowed in Java) has been moved just prior to the method:
// static float M[16];
projection.copyToFloatMatrix(setProjection_M);
_gl.uniformMatrix4fv(GlobalMembersGL.Uniforms.Projection, 1, false, setProjection_M);
}
public final void useProgram(int program)
{
// set shaders
_gl.useProgram(program);
// Extract the handles to attributes
GlobalMembersGL.Attributes.Position = _gl.getAttribLocation(program, "Position");
GlobalMembersGL.Attributes.TextureCoord = _gl.getAttribLocation(program, "TextureCoord");
GlobalMembersGL.Attributes.Color = _gl.getAttribLocation(program, "Color");
GlobalMembersGL.Attributes.Normal = _gl.getAttribLocation(program, "Normal");
// Extract the handles to uniforms
GlobalMembersGL.Uniforms.Projection = _gl.getUniformLocation(program, "Projection");
GlobalMembersGL.Uniforms.Modelview = _gl.getUniformLocation(program, "Modelview");
GlobalMembersGL.Uniforms.Sampler = _gl.getUniformLocation(program, "Sampler");
GlobalMembersGL.Uniforms.EnableTexture = _gl.getUniformLocation(program, "EnableTexture");
GlobalMembersGL.Uniforms.FlatColor = _gl.getUniformLocation(program, "FlatColor");
GlobalMembersGL.Uniforms.TranslationTexCoord = _gl.getUniformLocation(program, "TranslationTexCoord");
GlobalMembersGL.Uniforms.ScaleTexCoord = _gl.getUniformLocation(program, "ScaleTexCoord");
GlobalMembersGL.Uniforms.PointSize = _gl.getUniformLocation(program, "PointSize");
// default values
_gl.uniform2f(GlobalMembersGL.Uniforms.TranslationTexCoord, 0, 0);
_gl.uniform2f(GlobalMembersGL.Uniforms.ScaleTexCoord, 1, 1);
_gl.uniform1f(GlobalMembersGL.Uniforms.PointSize, (float) 1.0);
//BILLBOARDS
GlobalMembersGL.Uniforms.BillBoard = _gl.getUniformLocation(program, "BillBoard");
GlobalMembersGL.Uniforms.ViewPortRatio = _gl.getUniformLocation(program, "ViewPortRatio");
_gl.uniform1i(GlobalMembersGL.Uniforms.BillBoard, 0); //NOT DRAWING BILLBOARD
//FOR FLAT COLOR MIXING
GlobalMembersGL.Uniforms.FlatColorIntensity = _gl.getUniformLocation(program, "FlatColorIntensity");
GlobalMembersGL.Uniforms.ColorPerVertexIntensity = _gl.getUniformLocation(program, "ColorPerVertexIntensity");
GlobalMembersGL.Uniforms.EnableColorPerVertex = _gl.getUniformLocation(program, "EnableColorPerVertex");
GlobalMembersGL.Uniforms.EnableFlatColor = _gl.getUniformLocation(program, "EnableFlatColor");
}
public final void enablePolygonOffset(float factor, float units)
{
_gl.enable(PolygonOffsetFill);
_gl.polygonOffset(factor, units);
}
public final void disablePolygonOffset()
{
_gl.disable(PolygonOffsetFill);
}
public final void lineWidth(float width)
{
_gl.lineWidth(width);
}
public final void pointSize(float size)
{
_gl.uniform1f(GlobalMembersGL.Uniforms.PointSize, size);
}
public final int getError()
{
return _gl.getError();
}
public final int uploadTexture(IImage image, int textureWidth, int textureHeight)
{
byte[] imageData = new byte[textureWidth * textureHeight * 4];
image.fillWithRGBA(imageData, textureWidth, textureHeight);
_gl.blendFunc(SrcAlpha, OneMinusSrcAlpha);
_gl.pixelStorei(Unpack, 1);
int texID = getTextureID();
_gl.bindTexture(Texture2D, texID);
_gl.texParameteri(Texture2D, MinFilter, Linear);
_gl.texParameteri(Texture2D, MagFilter, Linear);
_gl.texParameteri(Texture2D, WrapS, ClampToEdge);
_gl.texParameteri(Texture2D, WrapT, ClampToEdge);
_gl.texImage2D(Texture2D, 0, RGBA, textureWidth, textureHeight, 0, RGBA, UnsignedByte, imageData);
return texID;
}
public final void setTextureCoordinates(int size, int stride, float[] texcoord)
{
_gl.vertexAttribPointer(GlobalMembersGL.Attributes.TextureCoord, size, Float, 0, stride, (Object) texcoord);
}
public final void bindTexture(int n)
{
_gl.bindTexture(Texture2D, n);
}
public final void enableDepthTest()
{
if (!_enableDepthTest)
{
_gl.enable(DepthTest);
_enableDepthTest = true;
}
}
public final void disableDepthTest()
{
if (_enableDepthTest)
{
_gl.disable(DepthTest);
_enableDepthTest = false;
}
}
public final void enableBlend()
{
if (!_enableBlend)
{
_gl.enable(Blend);
_enableBlend = true;
}
}
public final void disableBlend()
{
if (_enableBlend)
{
_gl.disable(Blend);
_enableBlend = false;
}
}
public final void drawBillBoard(int textureId, Vector3D pos, float viewPortRatio)
{
float[] vertex = { (float) pos.x(), (float) pos.y(), (float) pos.z(), (float) pos.x(), (float) pos.y(), (float) pos.z(), (float) pos.x(), (float) pos.y(), (float) pos.z(), (float) pos.x(), (float) pos.y(), (float) pos.z() };
float[] texcoord = { 1, 1, 1, 0, 0, 1, 0, 0 };
_gl.uniform1i(GlobalMembersGL.Uniforms.BillBoard, 1);
_gl.uniform1f(GlobalMembersGL.Uniforms.ViewPortRatio, viewPortRatio);
disableDepthTest();
enableTexture2D();
color(1, 1, 1, 1);
bindTexture(textureId);
vertexPointer(3, 0, vertex);
setTextureCoordinates(2, 0, texcoord);
_gl.drawArrays(TriangleStrip, 0, 4);
enableDepthTest();
_gl.uniform1i(GlobalMembersGL.Uniforms.BillBoard, 0);
}
public final void deleteTexture(int glTextureId)
{
int[] textures = { glTextureId };
_gl.deleteTextures(1, textures);
_texturesIdBag.addLast(glTextureId);
// printf(" - Delete 1 texturesId (bag size=%ld).\n", _texturesIdBag.size());
}
public final void enableCullFace(GLCullFace face)
{
if (!_enableCullFace)
{
_gl.enable(CullFacing);
_enableCullFace = true;
}
if (_cullFace_face != face)
{
_gl.cullFace(face);
_cullFace_face = face;
}
}
public final void disableCullFace()
{
if (_enableCullFace)
{
_gl.disable(CullFacing);
_enableCullFace = false;
}
}
public final void transformTexCoords(Vector2D scale, Vector2D translation)
{
_gl.uniform2f(GlobalMembersGL.Uniforms.ScaleTexCoord, (float) scale.x(), (float) scale.y());
_gl.uniform2f(GlobalMembersGL.Uniforms.TranslationTexCoord, (float) translation.x(), (float) translation.y());
}
public final void color(Color col)
{
color(col.getRed(), col.getGreen(), col.getBlue(), col.getAlpha());
}
public final void clearScreen(Color col)
{
clearScreen(col.getRed(), col.getGreen(), col.getBlue(), col.getAlpha());
}
public final void enableVertexFlatColor(Color c, float intensity)
{
enableVertexFlatColor(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha(), intensity);
}
}
|
package com.thewizardplusplus.diaryofcalories;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.app.AlarmManager;
import android.content.Context;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
label1 = (TextView)findViewById(R.id.label1);
current_day_calories = (TextView)findViewById(
R.id.current_day_calories
);
current_day_calories_unit = (TextView)findViewById(
R.id.current_day_calories_unit
);
maximum_calories = (TextView)findViewById(R.id.maximum_calories);
label3 = (TextView)findViewById(R.id.label3);
label4 = (TextView)findViewById(R.id.label4);
remaining_calories = (TextView)findViewById(R.id.remaining_calories);
remaining_calories_unit = (TextView)findViewById(
R.id.remaining_calories_unit
);
weight_edit = (EditText)findViewById(R.id.weight_edit);
calories_edit = (EditText)findViewById(R.id.calories_edit);
cancel_button = (ImageButton)findViewById(R.id.cancel_button);
Intent intent = new Intent(this, MainActivity.class);
Utils.showNotification(
this,
ONGOING_NOTIFICATION_ID,
R.drawable.icon,
getString(R.string.application_name),
"",
intent,
NotificationType.ONGOING,
0
);
updateUi();
setWidgetUpdateAlarm();
}
@Override
public void onResume() {
super.onResume();
updateUi();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.backup:
backupHistory();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void addData(View view) {
String weight = weight_edit.getText().toString();
String calories = calories_edit.getText().toString();
if (weight.length() != 0 && calories.length() != 0) {
DataAccessor data_accessor = DataAccessor.getInstance(this);
data_accessor.addData(
Float.parseFloat(weight),
Float.parseFloat(calories)
);
updateUi();
updateWidget();
weight_edit.setText("");
calories_edit.setText("");
weight_edit.requestFocus();
}
}
public void undoTheLast(View view) {
DataAccessor data_accessor = DataAccessor.getInstance(this);
data_accessor.undoTheLast();
updateUi();
updateWidget();
weight_edit.requestFocus();
}
public void showHistory(View view) {
Intent intent = new Intent(this, HistoryActivity.class);
startActivity(intent);
}
public void showSettings(View view) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
public void showAbout(View view) {
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
}
private static final String BACKUP_DIRECTORY = "#diary-of-calories";
private static final long NOTIFICATION_HIDE_DELAY = 5000;
private static final int ONGOING_NOTIFICATION_ID = -1;
private TextView label1;
private TextView current_day_calories;
private TextView current_day_calories_unit;
private TextView maximum_calories;
private TextView label3;
private TextView label4;
private TextView remaining_calories;
private TextView remaining_calories_unit;
private EditText weight_edit;
private EditText calories_edit;
private ImageButton cancel_button;
private void updateUi() {
DataAccessor data_accessor = DataAccessor.getInstance(this);
DayData current_day_data = data_accessor.getCurrentDayData();
double current_day_calories = current_day_data.calories;
label1.setText(
String.format(getString(R.string.label1),
Utils.convertDateToLocaleFormat(current_day_data.date))
);
this.current_day_calories.setText(
Utils.convertNumberToLocaleFormat(current_day_calories)
);
float soft_limit = data_accessor
.getSettings()
.soft_limit;
float hard_limit = data_accessor
.getSettings()
.hard_limit;
double maximum_calories = 0.0;
double difference = 0.0;
if (current_day_calories <= hard_limit) {
label3.setVisibility(View.VISIBLE);
label4.setVisibility(View.GONE);
if (current_day_calories <= soft_limit) {
maximum_calories = soft_limit;
this.current_day_calories.setTextColor(Color.rgb(0, 0xc0, 0));
this.current_day_calories_unit.setTextColor(Color.rgb(0, 0xc0, 0));
this.remaining_calories.setTextColor(Color.rgb(0, 0xc0, 0));
this.remaining_calories_unit.setTextColor(Color.rgb(0, 0xc0, 0));
} else {
maximum_calories = hard_limit;
this.current_day_calories.setTextColor(Color.rgb(0xc0, 0xc0, 0));
this.current_day_calories_unit.setTextColor(Color.rgb(0xc0, 0xc0, 0));
this.remaining_calories.setTextColor(Color.rgb(0xc0, 0xc0, 0));
this.remaining_calories_unit.setTextColor(Color.rgb(0xc0, 0xc0, 0));
}
difference = maximum_calories - current_day_calories;
} else {
maximum_calories = hard_limit;
difference = current_day_calories - maximum_calories;
label3.setVisibility(View.GONE);
label4.setVisibility(View.VISIBLE);
this.current_day_calories.setTextColor(Color.rgb(0xc0, 0, 0));
this.current_day_calories_unit.setTextColor(Color.rgb(0xc0, 0, 0));
this.remaining_calories.setTextColor(Color.rgb(0xc0, 0, 0));
this.remaining_calories_unit.setTextColor(Color.rgb(0xc0, 0, 0));
}
this.maximum_calories.setText(
Utils.convertNumberToLocaleFormat(maximum_calories)
);
this.remaining_calories.setText(
Utils.convertNumberToLocaleFormat(difference)
);
cancel_button.setEnabled(data_accessor.getNumberOfCurrentDayData() > 0);
}
private void setWidgetUpdateAlarm() {
Intent intent = new Intent(this, WidgetUpdateAlarm.class);
PendingIntent pending_intent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
AlarmManager alarm_manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm_manager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending_intent);
}
private void updateWidget() {
RemoteViews views = Widget.getUpdatedViews(this);
ComponentName widget = new ComponentName(this, Widget.class);
AppWidgetManager.getInstance(this).updateAppWidget(widget, views);
}
private void backupHistory() {
String storage_state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(storage_state)) {
Utils.showAlertDialog(
this,
getString(R.string.error_message_box_title),
getString(R.string.external_storage_error_message)
);
return;
}
File directory = new File(
Environment.getExternalStorageDirectory(),
BACKUP_DIRECTORY
);
if (!directory.exists()) {
boolean result = directory.mkdir();
if (!result) {
Utils.showAlertDialog(
this,
getString(R.string.error_message_box_title),
getString(R.string.directory_error_message)
);
return;
}
}
Date current_date = new Date();
SimpleDateFormat file_suffix_format = new SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss"
);
String file_suffix = file_suffix_format.format(current_date);
File backup_file = new File(
directory,
"database_dump_" + file_suffix + ".xml"
);
OutputStream out = null;
try {
try {
out = new BufferedOutputStream(
new FileOutputStream(backup_file)
);
DataAccessor data_accessor = DataAccessor.getInstance(this);
String xml = data_accessor.getAllDataInXml();
out.write(xml.getBytes());
} finally {
if (out != null) {
out.close();
}
}
} catch (IOException exception) {
Utils.showAlertDialog(
this,
getString(R.string.error_message_box_title),
getString(R.string.backup_file_error_message)
);
return;
}
SimpleDateFormat notification_timestamp_format = new SimpleDateFormat(
"dd.MM.yyyy HH:mm:ss"
);
String notification_timestamp = notification_timestamp_format.format(current_date);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(backup_file), "text/xml");
Utils.showNotification(
this,
0,
R.drawable.icon,
getString(R.string.application_name),
String.format(
getString(R.string.backup_saved_notification),
notification_timestamp
),
intent,
NotificationType.HIDDING,
NOTIFICATION_HIDE_DELAY
);
}
}
|
package com.akiban.server.test.pt;
import com.akiban.server.test.ApiTestBase;
import com.akiban.ais.model.TableIndex;
import com.akiban.server.expression.Expression;
import com.akiban.server.expression.ExpressionComposer;
import com.akiban.qp.expression.IndexBound;
import com.akiban.qp.expression.IndexKeyRange;
import com.akiban.qp.expression.RowBasedUnboundExpressions;
import com.akiban.qp.operator.API;
import com.akiban.qp.operator.Cursor;
import com.akiban.qp.operator.Operator;
import com.akiban.qp.operator.QueryContext;
import com.akiban.qp.persistitadapter.PersistitAdapter;
import com.akiban.qp.row.Row;
import com.akiban.qp.rowtype.IndexRowType;
import com.akiban.qp.rowtype.RowType;
import com.akiban.qp.rowtype.Schema;
import com.akiban.server.api.dml.SetColumnSelector;
import com.akiban.server.expression.std.Expressions;
import com.akiban.server.expression.std.FieldExpression;
import com.akiban.server.service.functions.FunctionsRegistry;
import com.akiban.server.service.functions.FunctionsRegistryImpl;
import com.akiban.qp.operator.OperatorExecutionBase;
import com.akiban.qp.row.ValuesHolderRow;
import com.akiban.qp.rowtype.DerivedTypesSchema;
import com.akiban.server.types.AkType;
import com.akiban.server.types.ValueSource;
import com.akiban.server.types.util.ValueHolder;
import com.persistit.Exchange;
import com.persistit.Key;
import com.persistit.exception.PersistitException;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
public class AggregatePT extends ApiTestBase {
public static final int ROW_COUNT = 100000;
public static final int WARMUPS = 100, REPEATS = 10;
public AggregatePT() {
super("PT");
}
private TableIndex index;
@Before
public void loadData() {
int t = createTable("user", "t",
"id INT NOT NULL PRIMARY KEY",
"gid INT",
"flag BOOLEAN",
"sval VARCHAR(20) NOT NULL",
"n1 INT",
"n2 INT",
"k INT");
Random rand = new Random(69);
for (int i = 0; i < ROW_COUNT; i++) {
writeRow(t, i,
rand.nextInt(10),
(rand.nextInt(100) < 80) ? 0 : 1,
randString(rand, 20),
rand.nextInt(100),
rand.nextInt(1000),
rand.nextInt());
}
index = createIndex("user", "t", "t_i",
"gid", "sval", "flag", "k", "n1", "n2", "id");
}
private String randString(Random rand, int size) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < size; i++) {
str.append((char)('A' + rand.nextInt(26)));
}
return str.toString();
}
@Test
public void normalOperators() {
Schema schema = new Schema(rowDefCache().ais());
IndexRowType indexType = schema.indexRowType(index);
IndexKeyRange keyRange = IndexKeyRange.unbounded(indexType);
API.Ordering ordering = new API.Ordering();
ordering.append(new FieldExpression(indexType, 0), true);
Operator plan = API.indexScan_Default(indexType, keyRange, ordering);
RowType rowType = indexType;
plan = spa(plan, rowType);
PersistitAdapter adapter = persistitAdapter(schema);
QueryContext queryContext = queryContext(adapter);
System.out.println("NORMAL OPERATORS");
double time = 0.0;
for (int i = 0; i < WARMUPS+REPEATS; i++) {
long start = System.nanoTime();
Cursor cursor = API.cursor(plan, queryContext);
cursor.open();
while (true) {
Row row = cursor.next();
if (row == null) break;
if (i == 0) System.out.println(row);
}
cursor.close();
long end = System.nanoTime();
if (i >= WARMUPS)
time += (end - start) / 1.0e6;
}
System.out.println(String.format("%g ms", time / REPEATS));
}
private Operator spa(Operator plan, RowType rowType) {
FunctionsRegistry functions = new FunctionsRegistryImpl();
ExpressionComposer and = functions.composer("and");
Expression pred1 = functions.composer("greaterOrEquals")
.compose(Arrays.asList(Expressions.field(rowType, 1),
Expressions.literal("M")));
Expression pred2 = functions.composer("lessOrEquals")
.compose(Arrays.asList(Expressions.field(rowType, 1),
Expressions.literal("Y")));
Expression pred = and.compose(Arrays.asList(pred1, pred2));
pred2 = functions.composer("notEquals")
.compose(Arrays.asList(Expressions.field(rowType, 2),
Expressions.literal(1L)));
pred = and.compose(Arrays.asList(pred, pred2));
plan = API.select_HKeyOrdered(plan, rowType, pred);
plan = API.project_Default(plan, rowType,
Arrays.asList(Expressions.field(rowType, 0),
Expressions.field(rowType, 3),
Expressions.field(rowType, 4),
Expressions.field(rowType, 5)));
rowType = plan.rowType();
plan = API.aggregate_Partial(plan, rowType,
1, functions,
Arrays.asList("count", "sum", "sum"));
return plan;
}
@Test
public void bespokeOperator() {
Schema schema = new Schema(rowDefCache().ais());
IndexRowType indexType = schema.indexRowType(index);
IndexKeyRange keyRange = IndexKeyRange.unbounded(indexType);
API.Ordering ordering = new API.Ordering();
ordering.append(new FieldExpression(indexType, 0), true);
Operator plan = API.indexScan_Default(indexType, keyRange, ordering);
RowType rowType = indexType;
plan = new BespokeOperator(plan);
PersistitAdapter adapter = persistitAdapter(schema);
QueryContext queryContext = queryContext(adapter);
System.out.println("BESPOKE OPERATOR");
double time = 0.0;
for (int i = 0; i < WARMUPS+REPEATS; i++) {
long start = System.nanoTime();
Cursor cursor = API.cursor(plan, queryContext);
cursor.open();
while (true) {
Row row = cursor.next();
if (row == null) break;
if (i == 0) System.out.println(row);
}
cursor.close();
long end = System.nanoTime();
if (i >= WARMUPS)
time += (end - start) / 1.0e6;
}
System.out.println(String.format("%g ms", time / REPEATS));
}
@Test
public void pojoAggregator() throws PersistitException {
System.out.println("POJO");
double time = 0.0;
for (int i = 0; i < WARMUPS+REPEATS; i++) {
long start = System.nanoTime();
POJOAggregator aggregator = new POJOAggregator(i == 0);
Exchange exchange = persistitStore().getExchange(session(), index);
exchange.clear();
exchange.append(Key.BEFORE);
while (exchange.traverse(Key.GT, true)) {
Key key = exchange.getKey();
aggregator.aggregate(key);
}
aggregator.emit();
persistitStore().releaseExchange(session(), exchange);
long end = System.nanoTime();
if (i >= WARMUPS)
time += (end - start) / 1.0e6;
}
System.out.println(String.format("%g ms", time / REPEATS));
}
static class BespokeOperator extends Operator {
private Operator inputOperator;
private RowType outputType;
public BespokeOperator(Operator inputOperator) {
this.inputOperator = inputOperator;
outputType = new BespokeRowType();
}
@Override
protected Cursor cursor(QueryContext context) {
return new BespokeCursor(context, API.cursor(inputOperator, context), outputType);
}
@Override
public void findDerivedTypes(Set<RowType> derivedTypes) {
inputOperator.findDerivedTypes(derivedTypes);
derivedTypes.add(outputType);
}
@Override
public List<Operator> getInputOperators() {
return Collections.singletonList(inputOperator);
}
@Override
public RowType rowType() {
return outputType;
}
}
static class BespokeCursor extends OperatorExecutionBase implements Cursor {
private Cursor inputCursor;
private RowType outputType;
private ValuesHolderRow outputRow;
private BespokeAggregator aggregator;
public BespokeCursor(QueryContext context, Cursor inputCursor, RowType outputType) {
super(context);
this.inputCursor = inputCursor;
this.outputType = outputType;
}
@Override
public void open() {
inputCursor.open();
outputRow = new ValuesHolderRow(outputType);
aggregator = new BespokeAggregator();
}
@Override
public void close() {
inputCursor.close();
aggregator = null;
}
@Override
public void destroy() {
close();
inputCursor = null;
}
@Override
public boolean isIdle() {
return ((inputCursor != null) && (aggregator == null));
}
@Override
public boolean isActive() {
return ((inputCursor != null) && (aggregator != null));
}
@Override
public boolean isDestroyed() {
return (inputCursor == null);
}
@Override
public Row next() {
if (aggregator == null)
return null;
while (true) {
Row inputRow = inputCursor.next();
if (inputRow == null) {
if (aggregator.isEmpty()) {
close();
return null;
}
aggregator.fill(outputRow);
close();
return outputRow;
}
if (aggregator.aggregate(inputRow, outputRow)) {
return outputRow;
}
}
}
}
static final AkType[] TYPES = {
AkType.LONG, AkType.LONG, AkType.LONG, AkType.LONG
};
static class BespokeRowType extends RowType {
public BespokeRowType() {
super(-1);
}
@Override
public DerivedTypesSchema schema() {
return null;
}
public int nFields() {
return TYPES.length;
}
public AkType typeAt(int index) {
return TYPES[index];
}
}
static class BespokeAggregator {
private boolean key_init;
private long key;
private long count1;
private boolean sum1_init;
private long sum1;
private boolean sum2_init;
private long sum2;
public boolean isEmpty() {
return !key_init;
}
public boolean aggregate(Row inputRow, ValuesHolderRow outputRow) {
// The select part.
String sval = inputRow.eval(1).getString();
if (("M".compareTo(sval) > 0) ||
("Y".compareTo(sval) < 0))
return false;
long flag = inputRow.eval(2).getInt();
if (flag == 1)
return false;
// The actual aggregate part.
boolean emit = false, reset = false;
long nextKey = inputRow.eval(0).getInt();
if (!key_init) {
key_init = reset = true;
key = nextKey;
}
else if (key != nextKey) {
fill(outputRow);
emit = reset = true;
key = nextKey;
}
if (reset) {
sum1_init = sum2_init = false;
count1 = sum1 = sum2 = 0;
}
ValueSource value = inputRow.eval(3);
if (!value.isNull()) {
count1++;
}
value = inputRow.eval(4);
if (!value.isNull()) {
if (!sum1_init)
sum1_init = true;
sum1 += value.getInt();
}
value = inputRow.eval(5);
if (!value.isNull()) {
if (!sum2_init)
sum2_init = true;
sum2 += value.getInt();
}
return emit;
}
public void fill(ValuesHolderRow row) {
row.holderAt(0).putLong(key);
row.holderAt(1).putLong(count1);
row.holderAt(2).putLong(sum1);
row.holderAt(3).putLong(sum2);
}
@Override
public String toString() {
return String.format("%d: [%d %d %d]", key, count1, sum1, sum2);
}
}
static class POJOAggregator {
private boolean key_init;
private long key;
private long count1;
private boolean sum1_init;
private long sum1;
private boolean sum2_init;
private long sum2;
private final boolean doPrint;
public POJOAggregator(boolean doPrint) {
this.doPrint = doPrint;
}
public void aggregate(Key row) {
row.indexTo(1);
String sval = row.decodeString();
if (("M".compareTo(sval) > 0) ||
("Y".compareTo(sval) < 0))
return;
row.indexTo(2);
long flag = row.decodeLong();
if (flag == 1)
return;
row.indexTo(0);
boolean reset = false;
long nextKey = row.decodeLong();
if (!key_init) {
key_init = reset = true;
key = nextKey;
}
else if (key != nextKey) {
emit();
reset = true;
key = nextKey;
}
if (reset) {
sum1_init = sum2_init = false;
count1 = sum1 = sum2 = 0;
}
row.indexTo(3);
if (!row.isNull()) {
count1++;
}
row.indexTo(4);
if (!row.isNull()) {
if (!sum1_init)
sum1_init = true;
sum1 += row.decodeLong();
}
row.indexTo(5);
if (!row.isNull()) {
if (!sum2_init)
sum2_init = true;
sum2 += row.decodeLong();
}
}
public void emit() {
if (doPrint)
System.out.println(this);
}
@Override
public String toString() {
return String.format("%d: [%d %d %d]", key, count1, sum1, sum2);
}
}
@Test
public void sorted() {
Schema schema = new Schema(rowDefCache().ais());
IndexRowType indexType = schema.indexRowType(index);
IndexKeyRange keyRange = IndexKeyRange.unbounded(indexType);
API.Ordering ordering = new API.Ordering();
ordering.append(new FieldExpression(indexType, 0), true);
Operator plan = API.indexScan_Default(indexType, keyRange, ordering);
RowType rowType = indexType;
plan = spa(plan, rowType);
rowType = plan.rowType();
ordering = new API.Ordering();
ordering.append(new FieldExpression(rowType, 2), true);
plan = API.sort_InsertionLimited(plan, rowType, ordering,
API.SortOption.PRESERVE_DUPLICATES, 100);
PersistitAdapter adapter = persistitAdapter(schema);
QueryContext queryContext = queryContext(adapter);
System.out.println("SORTED");
double time = 0.0;
for (int i = 0; i < WARMUPS+REPEATS; i++) {
long start = System.nanoTime();
Cursor cursor = API.cursor(plan, queryContext);
cursor.open();
while (true) {
Row row = cursor.next();
if (row == null) break;
if (i == 0) System.out.println(row);
}
cursor.close();
long end = System.nanoTime();
if (i >= WARMUPS)
time += (end - start) / 1.0e6;
}
System.out.println(String.format("%g ms", time / REPEATS));
}
}
|
package com.vmware.vim25.mo.samples.ovf;
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.ComputeResource;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.HttpNfcLease;
import com.vmware.vim25.mo.ResourcePool;
import com.vmware.vim25.mo.ServiceInstance;
public class ImportLocalOvfVApp
{
private static final int CHUCK_LEN = 64 * 1024;
public static LeaseProgressUpdater leaseUpdater;
public static void main(String[] args) throws Exception
{
if (args.length < 6)
{
System.out.println(
"java ImportLocalOvfVApp <targetURL> <username> <password> <hostip> <OVFFile LocalPath> <NewVMName>");
System.out.println(
"java ImportLocalOvfVApp https://10.20.140.47/sdk Administrator password 10.17.204.115 E:/Downloads/Nostalgia.ovf NewVM");
return;
}
ServiceInstance si = new ServiceInstance(new URL(args[0]), args[1], args[2], true);
String ovfLocal = args[4];
String hostip = args[3];
String newVmName = args[5];
HostSystem host = (HostSystem) si.getSearchIndex().findByIp(null, hostip, false);
System.out.println("Host Name : " + host.getName());
System.out.println("Network : " + host.getNetworks()[0].getName());
System.out.println("Datastore : " + host.getDatastores()[0].getName());
Folder vmFolder = (Folder) host.getVms()[0].getParent();
OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
importSpecParams.setHostSystem(host.getMOR());
importSpecParams.setLocale("US");
importSpecParams.setEntityName(newVmName);
importSpecParams.setDeploymentOption("");
OvfNetworkMapping networkMapping = new OvfNetworkMapping();
networkMapping.setName("Network 1");
networkMapping.setNetwork(host.getNetworks()[0].getMOR()); // network);
importSpecParams.setNetworkMapping(new OvfNetworkMapping[] { networkMapping });
importSpecParams.setPropertyMapping(null);
String ovfDescriptor = readOvfContent(ovfLocal);
if (ovfDescriptor == null)
{
si.getServerConnection().logout();
return;
}
ovfDescriptor = escapeSpecialChars(ovfDescriptor);
System.out.println("ovfDesc:" + ovfDescriptor);
ResourcePool rp = ((ComputeResource)host.getParent()).getResourcePool();
OvfCreateImportSpecResult ovfImportResult = si.getOvfManager().createImportSpec(
ovfDescriptor, rp, host.getDatastores()[0], importSpecParams);
if(ovfImportResult==null)
{
si.getServerConnection().logout();
return;
}
long totalBytes = addTotalBytes(ovfImportResult);
System.out.println("Total bytes: " + totalBytes);
HttpNfcLease httpNfcLease = null;
httpNfcLease = rp.importVApp(ovfImportResult.getImportSpec(), vmFolder, host);
// Wait until the HttpNfcLeaseState is ready
HttpNfcLeaseState hls;
for(;;)
{
hls = httpNfcLease.getState();
if(hls == HttpNfcLeaseState.ready || hls == HttpNfcLeaseState.error)
{
break;
}
}
if (hls.equals(HttpNfcLeaseState.ready))
{
System.out.println("HttpNfcLeaseState: ready ");
HttpNfcLeaseInfo httpNfcLeaseInfo = (HttpNfcLeaseInfo) httpNfcLease.getInfo();
printHttpNfcLeaseInfo(httpNfcLeaseInfo);
leaseUpdater = new LeaseProgressUpdater(httpNfcLease, 5000);
leaseUpdater.start();
HttpNfcLeaseDeviceUrl[] deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
long bytesAlreadyWritten = 0;
for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls)
{
String deviceKey = deviceUrl.getImportKey();
for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem())
{
if (deviceKey.equals(ovfFileItem.getDeviceId()))
{
System.out.println("Import key==OvfFileItem device id: " + deviceKey);
String absoluteFile = new File(ovfLocal).getParent() + File.separator + ovfFileItem.getPath();
String urlToPost = deviceUrl.getUrl().replace("*", hostip);
uploadVmdkFile(ovfFileItem.isCreate(), absoluteFile, urlToPost, bytesAlreadyWritten, totalBytes);
bytesAlreadyWritten += ovfFileItem.getSize();
System.out.println("Completed uploading the VMDK file:" + absoluteFile);
}
}
}
leaseUpdater.interrupt();
httpNfcLease.httpNfcLeaseProgress(100);
httpNfcLease.httpNfcLeaseComplete();
}
si.getServerConnection().logout();
}
public static long addTotalBytes(OvfCreateImportSpecResult ovfImportResult)
{
OvfFileItem[] fileItemArr = ovfImportResult.getFileItem();
long totalBytes = 0;
if (fileItemArr != null)
{
for (OvfFileItem fi : fileItemArr)
{
printOvfFileItem(fi);
totalBytes += fi.getSize();
}
}
return totalBytes;
}
private static void uploadVmdkFile(boolean put, String diskFilePath, String urlStr,
long bytesAlreadyWritten, long totalBytes) throws IOException
{
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
return true;
}
});
HttpsURLConnection conn = (HttpsURLConnection) new URL(urlStr).openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setChunkedStreamingMode(CHUCK_LEN);
conn.setRequestMethod(put? "PUT" : "POST"); // Use a post method to write the file.
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/x-vnd.vmware-streamVmdk");
conn.setRequestProperty("Content-Length", Long.toString(new File(diskFilePath).length()));
BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());
BufferedInputStream diskis = new BufferedInputStream(new FileInputStream(diskFilePath));
int bytesAvailable = diskis.available();
int bufferSize = Math.min(bytesAvailable, CHUCK_LEN);
byte[] buffer = new byte[bufferSize];
long totalBytesWritten = 0;
while (true)
{
int bytesRead = diskis.read(buffer, 0, bufferSize);
if (bytesRead == -1)
{
System.out.println("Total bytes written: " + totalBytesWritten);
break;
}
totalBytesWritten += bytesRead;
bos.write(buffer, 0, bufferSize);
bos.flush();
System.out.println("Total bytes written: " + totalBytesWritten);
int progressPercent = (int) (((bytesAlreadyWritten + totalBytesWritten) * 100) / totalBytes);
leaseUpdater.setPercent(progressPercent);
}
diskis.close();
bos.flush();
bos.close();
conn.disconnect();
}
public static String readOvfContent(String ovfFilePath) throws IOException
{
StringBuffer strContent = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(ovfFilePath)));
String lineStr;
while ((lineStr = in.readLine()) != null)
{
strContent.append(lineStr);
}
in.close();
return strContent.toString();
}
private static void printHttpNfcLeaseInfo(HttpNfcLeaseInfo info)
{
System.out.println("================ HttpNfcLeaseInfo ================");
HttpNfcLeaseDeviceUrl[] deviceUrlArr = info.getDeviceUrl();
for (HttpNfcLeaseDeviceUrl durl : deviceUrlArr)
{
System.out.println("Device URL Import Key: " + durl.getImportKey());
System.out.println("Device URL Key: " + durl.getKey());
System.out.println("Device URL : " + durl.getUrl());
System.out.println("Updated device URL: " + durl.getUrl());
}
System.out.println("Lease Timeout: " + info.getLeaseTimeout());
System.out.println("Total Disk capacity: " + info.getTotalDiskCapacityInKB());
System.out.println("==================================================");
}
private static void printOvfFileItem(OvfFileItem fi)
{
System.out.println("================ OvfFileItem ================");
System.out.println("chunkSize: " + fi.getChunkSize());
System.out.println("create: " + fi.isCreate());
System.out.println("deviceId: " + fi.getDeviceId());
System.out.println("path: " + fi.getPath());
System.out.println("size: " + fi.getSize());
System.out.println("==============================================");
}
public static String escapeSpecialChars(String str)
{
str = str.replaceAll("<", "<");
return str.replaceAll(">", ">"); // do not escape "&" -> "&", "\"" -> """
}
}
|
package io.spacedog.client.file;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.common.collect.Sets;
import io.spacedog.client.data.DataObjectBase;
import io.spacedog.client.http.WebPath;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = Visibility.ANY,
getterVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE)
public class SpaceFile extends DataObjectBase {
private String path;
private String key;
private String name;
private long length;
private String contentType;
private String hash;
private String encryption;
private boolean snapshot;
private Set<String> tags = Sets.newLinkedHashSet();
public SpaceFile() {
}
public SpaceFile(String path) {
this.path = path;
}
public String getPath() {
return path;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public Set<String> getTags() {
return tags;
}
public void setTags(Set<String> tags) {
this.tags = tags;
}
public String getEncryption() {
return encryption;
}
public void setEncryption(String Encryption) {
this.encryption = Encryption;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public boolean getSnapshot() {
return snapshot;
}
public void setSnapshot(boolean snapshot) {
this.snapshot = snapshot;
}
public String getEscapedPath() {
return WebPath.parse(path).toEscapedString();
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = Visibility.PUBLIC_ONLY,
getterVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE)
public static class FileList {
public long total;
public List<SpaceFile> files;
public String next;
}
public static String flatPath(String path) {
if (path.charAt(0) == '/')
path = path.substring(1);
path = path.replace('/', '-');
return path;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof SpaceFile))
return false;
SpaceFile file = (SpaceFile) obj;
return Objects.equals(path, file.path);
}
@Override
public int hashCode() {
return Objects.hashCode(path);
}
@Override
public String toString() {
return String.format("SpaceFile[%s]", path);
}
}
|
package com.akiban.util;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import static org.junit.Assert.*;
public final class FilteringIteratorTest {
@Test
public void correctUsageBasic() {
ArrayList<Integer> list = list(1, 2, 3, 4, 5, 6);
List<Integer> filtered = dump( onlyEvens(list) );
assertEquals("filtered list", list(2, 4, 6), filtered);
}
// have to filter out more than one in a row
@Test
public void correctUsageBasicSparse() {
ArrayList<Integer> list = list(1, 27, 31, 11, 2, 3, 4, 5, 6);
List<Integer> filtered = dump( onlyEvens(list) );
assertEquals("filtered list", list(2, 4, 6), filtered);
}
@Test
public void correctUsageEmptyList() {
List<Integer> filtered = dump( onlyEvens() );
assertEquals("filtered list", list(), filtered);
}
@Test
public void correctUsageEmptyAfterFilter() {
List<Integer> filtered = dump( onlyEvens(1, 3, 7) );
assertEquals("filtered list", list(), filtered);
}
@Test
public void correctUsageRemove() {
ArrayList<Integer> list = list(1, 2, 3, 4, 5, 6);
Iterator<Integer> iterator = onlyEvens(list, true);
List<Integer> removed = new ArrayList<Integer>();
while (iterator.hasNext()) {
removed.add( iterator.next() );
iterator.remove();
}
assertEquals("removed", list(2, 4, 6), removed);
assertEquals("left", list(1, 3, 5), list);
}
@Test(expected=NoSuchElementException.class)
public void nextOnEmpty() {
Iterator<Integer> iterator = onlyEvens();
iterator.next();
}
@Test(expected=NoSuchElementException.class)
public void nextOnEmptyAfterFilter() {
Iterator<Integer> iterator = onlyEvens(1);
iterator.next();
}
@Test
public void nextTwice() {
Iterator<Integer> iterator = onlyEvens(1, 2, 3, 4, 5);
assertEquals("first", 2, iterator.next().intValue());
assertEquals("second", 4, iterator.next().intValue());
assertFalse("hasNext() == true", iterator.hasNext());
}
@Test(expected=IllegalStateException.class)
public void removeTwice() {
Iterator<Integer> iterator = SafeAction.of(new SafeAction.Get<Iterator<Integer>>() {
@Override
public Iterator<Integer> get() {
Iterator<Integer> iterator = onlyEvens(1, 2);
assertTrue("hasNext == false", iterator.hasNext());
assertEquals("next()", 2, iterator.next().intValue());
iterator.remove();
return iterator;
}
});
iterator.remove();
}
@Test(expected=UnsupportedOperationException.class)
public void removeDisallowedByIterator() {
Iterator<Integer> iterator = SafeAction.of(new SafeAction.Get<Iterator<Integer>>() {
@Override
public Iterator<Integer> get() {
Iterator<Integer> iterator = onlyEvens(list(2), false);
assertTrue("hasNext == false", iterator.hasNext());
assertEquals("next()", 2, iterator.next().intValue());
return iterator;
}
});
iterator.remove();
}
@Test(expected=UnsupportedOperationException.class)
public void removeDisallowedByDelegate() {
Iterator<Integer> iterator = SafeAction.of(new SafeAction.Get<Iterator<Integer>>() {
@Override
public Iterator<Integer> get() {
Iterator<Integer> iterator = onlyEvens(Collections.unmodifiableList(list(2)), false);
assertTrue("hasNext == false", iterator.hasNext());
assertEquals("next()", 2, iterator.next().intValue());
return iterator;
}
});
iterator.remove();
}
@Test
public void hasNextTwice() {
Iterator<Integer> iterator = onlyEvens(1, 2, 3);
assertTrue("hasNext 1", iterator.hasNext());
assertTrue("hasNext 2", iterator.hasNext());
assertEquals("next", 2, iterator.next().intValue());
assertFalse("hasNext 3", iterator.hasNext());
}
private static Iterator<Integer> onlyEvens(int... integers) {
return onlyEvens(list(integers));
}
private static Iterator<Integer> onlyEvens(Iterable<Integer> iterable) {
return onlyEvens(iterable, true);
}
private static Iterator<Integer> onlyEvens(Iterable<Integer> iterable, boolean mutable) {
return new FilteringIterator<Integer>(iterable.iterator(), mutable) {
@Override
protected boolean allow(Integer item) {
return (item % 2) == 0;
}
};
}
private static List<Integer> dump(Iterator<Integer> iterator) {
ArrayList<Integer> list = new ArrayList<Integer>();
while (iterator.hasNext()) {
list.add(iterator.next());
}
return list;
}
private static ArrayList<Integer> list(int... values) {
ArrayList<Integer> list = new ArrayList<Integer>(values.length);
for (int value : values) {
list.add(value);
}
return list;
}
}
|
package com.wb.nextgenlibrary.widget;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.Formatter;
import java.util.Locale;
import android.widget.SeekBar.OnSeekBarChangeListener;
import com.wb.nextgenlibrary.R;
public class CustomMediaController extends MediaController {
private static final String TAG = "CustomMediaController";
private MediaPlayerControl mPlayer;
private Context mContext;
private View mAnchor;
private View mRoot;
private ProgressBar mProgress;
private TextView mEndTime, mCurrentTime;
private boolean mShowing;
private boolean mDragging;
private static final int sDefaultTimeout = 3000;
private static final int FADE_OUT = 1;
private static final int SHOW_PROGRESS = 2;
private boolean mUseFullscreenToggle;
private boolean mUseFastForward;
private boolean mFromXml;
private boolean mListenersSet;
private View.OnClickListener mNextListener, mPrevListener;
StringBuilder mFormatBuilder;
Formatter mFormatter;
private ImageButton mPauseButton;
private ImageButton mFfwdButton;
private ImageButton mRewButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private ImageButton mFullscreenButton;
private Handler mHandler = new MessageHandler(this);
private boolean mIsFullScreen = false;
private MediaControllerVisibilityChangeListener mVisibilityListenter;
public static interface MediaControllerVisibilityChangeListener{
void onVisibilityChange(boolean bShow);
}
public CustomMediaController(Context context, AttributeSet attrs) {
super(context, attrs);
mRoot = null;
mContext = context;
mUseFastForward = true;
mUseFullscreenToggle = true;
mFromXml = true;
Log.i(TAG, TAG);
}
public CustomMediaController(Context context, boolean useFastForward, boolean useFullscreenToggle) {
super(context);
mContext = context;
mUseFastForward = useFastForward;
mUseFullscreenToggle = useFullscreenToggle;
Log.i(TAG, TAG);
}
public CustomMediaController(Context context) {
this(context, true, true);
Log.i(TAG, TAG);
}
public void setVisibilityChangeListener(MediaControllerVisibilityChangeListener listener){
mVisibilityListenter = listener;
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
if (mRoot != null)
initControllerView(mRoot);
}
public void setMediaPlayer(MediaPlayerControl player) {
mPlayer = player;
updatePausePlay();
updateFullScreen();
}
public void setIsFullScreen(boolean bFullScreen){
mIsFullScreen = bFullScreen;
}
/**
* Set the view that acts as the anchor for the control view.
* This can for example be a VideoView, or your Activity's main view.
* @param view The view to which to anchor the controller when it is visible.
*/
@Override
public void setAnchorView(View view) {
if (mAnchor != null) {
mAnchor.removeOnLayoutChangeListener(mLayoutChangeListener);
}
mAnchor = view;
if (mAnchor != null) {
mAnchor.addOnLayoutChangeListener(mLayoutChangeListener);
}
FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
removeAllViews();
View v = makeControllerView();
addView(v);
}
// This is called whenever mAnchor's layout bound changes
private final OnLayoutChangeListener mLayoutChangeListener =
new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight,
int oldBottom) {
mRoot.getHeight();
mRoot.getWidth();
}
};
/**
* Create the view that holds the widgets that control playback.
* Derived classes can override this to create their own.
* @return The controller view.
* @hide This doesn't work as advertised
*/
protected View makeControllerView() {
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRoot = inflate.inflate(R.layout.custom_media_controller, null);
initControllerView(mRoot);
return mRoot;
}
private void initControllerView(View v) {
mPauseButton = (ImageButton) v.findViewById(R.id.custom_playpause);
if (mPauseButton != null) {
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
}
mFullscreenButton = (ImageButton) v.findViewById(R.id.fullscreen);
if (mFullscreenButton != null) {
mFullscreenButton.requestFocus();
mFullscreenButton.setOnClickListener(mFullscreenListener);
if (!mFromXml){
mFullscreenButton.setVisibility(mUseFullscreenToggle ? VISIBLE: GONE);
}
}
mFfwdButton = (ImageButton) v.findViewById(R.id.ffwd);
if (mFfwdButton != null) {
mFfwdButton.setOnClickListener(mFfwdListener);
if (!mFromXml) {
mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
}
}
mRewButton = (ImageButton) v.findViewById(R.id.rew);
if (mRewButton != null) {
mRewButton.setOnClickListener(mRewListener);
if (!mFromXml) {
mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
}
}
// By default these are hidden. They will be enabled when setPrevNextListeners() is called
mNextButton = (ImageButton) v.findViewById(R.id.next);
if (mNextButton != null && !mFromXml && !mListenersSet) {
mNextButton.setVisibility(View.GONE);
}
mPrevButton = (ImageButton) v.findViewById(R.id.prev);
if (mPrevButton != null && !mFromXml && !mListenersSet) {
mPrevButton.setVisibility(View.GONE);
}
mProgress = (SeekBar) v.findViewById(R.id.mediacontroller_progress);
if (mProgress != null) {
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
}
mEndTime = (TextView) v.findViewById(R.id.time);
mCurrentTime = (TextView) v.findViewById(R.id.time_current);
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
installPrevNextListeners();
}
/**
* Show the controller on screen. It will go away
* automatically after 3 seconds of inactivity.
*/
public void show() {
show(sDefaultTimeout);
}
/**
* Disable pause or seek buttons if the stream cannot be paused or seeked.
* This requires the control interface to be a MediaPlayerControlExt
*/
private void disableUnsupportedButtons() {
if (mPlayer == null) {
return;
}
try {
if (mPauseButton != null && !mPlayer.canPause()) {
mPauseButton.setEnabled(false);
}
if (mRewButton != null && !mPlayer.canSeekBackward()) {
mRewButton.setEnabled(false);
}
if (mFfwdButton != null && !mPlayer.canSeekForward()) {
mFfwdButton.setEnabled(false);
}
} catch (IncompatibleClassChangeError ex) {
// We were given an old version of the interface, that doesn't have
// the canPause/canSeekXYZ methods. This is OK, it just means we
// assume the media can be paused and seeked, and so we don't disable
// the buttons.
}
}
/**
* Show the controller on screen. It will go away
* automatically after 'timeout' milliseconds of inactivity.
* @param timeout The timeout in milliseconds. Use 0 to show
* the controller until hide() is called.
*/
public void show(int timeout) {
if (!mShowing && mAnchor != null) {
if (mVisibilityListenter != null)
mVisibilityListenter.onVisibilityChange(true);
setProgress();
if (mPauseButton != null) {
mPauseButton.requestFocus();
}
disableUnsupportedButtons();
FrameLayout.LayoutParams tlp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM
);
if (this.getParent() != null){
((ViewGroup)this.getParent()).removeView(this);
}
if (this.getParent() == null && mAnchor.getParent() != null)
((ViewGroup)mAnchor.getParent()).addView(this, tlp);
mShowing = true;
}
updatePausePlay();
updateFullScreen();
// cause the progress bar to be updated even if mShowing
// was already true. This happens, for example, if we're
// paused with the progress bar showing the user hits play.
mHandler.sendEmptyMessage(SHOW_PROGRESS);
Message msg = mHandler.obtainMessage(FADE_OUT);
if (timeout != 0) {
mHandler.removeMessages(FADE_OUT);
mHandler.sendMessageDelayed(msg, timeout);
}
}
public boolean isShowing() {
return mShowing;
}
/**
* Remove the controller from the screen.
*/
public void hide() {
if (mAnchor == null) {
return;
}
if (mVisibilityListenter != null)
mVisibilityListenter.onVisibilityChange(false);
if (mAnchor.getParent() != null) {
try {
((ViewGroup) (mAnchor.getParent())).removeView(this);
mHandler.removeMessages(SHOW_PROGRESS);
} catch (IllegalArgumentException ex) {
Log.w("MediaController", "already removed");
}
}
mShowing = false;
}
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private int setProgress() {
if (mPlayer == null || mDragging) {
return 0;
}
int position = mPlayer.getCurrentPosition();
int duration = mPlayer.getDuration();
if (mProgress != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
mProgress.setProgress( (int) pos);
}
int percent = mPlayer.getBufferPercentage();
mProgress.setSecondaryProgress(percent * 10);
}
if (mEndTime != null)
mEndTime.setText(stringForTime(duration));
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime(position));
return position;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
show(sDefaultTimeout);
return false;
}
@Override
public boolean onTrackballEvent(MotionEvent ev) {
show(sDefaultTimeout);
return false;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (mPlayer == null) {
return true;
}
int keyCode = event.getKeyCode();
final boolean uniqueDown = event.getRepeatCount() == 0
&& event.getAction() == KeyEvent.ACTION_DOWN;
if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK
|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keyCode == KeyEvent.KEYCODE_SPACE) {
if (uniqueDown) {
doPauseResume();
show(sDefaultTimeout);
if (mPauseButton != null) {
mPauseButton.requestFocus();
}
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
if (uniqueDown && !mPlayer.isPlaying()) {
mPlayer.start();
updatePausePlay();
show(sDefaultTimeout);
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
|| keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
if (uniqueDown && mPlayer.isPlaying()) {
mPlayer.pause();
updatePausePlay();
show(sDefaultTimeout);
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
|| keyCode == KeyEvent.KEYCODE_VOLUME_UP
|| keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
// don't show the controls for volume adjustment
return super.dispatchKeyEvent(event);
} else if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) {
if (uniqueDown) {
hide();
}
return true;
}
show(sDefaultTimeout);
return super.dispatchKeyEvent(event);
}
private View.OnClickListener mPauseListener = new View.OnClickListener() {
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private View.OnClickListener mFullscreenListener = new View.OnClickListener() {
public void onClick(View v) {
doToggleFullscreen();
mIsFullScreen = !mIsFullScreen;
show(sDefaultTimeout);
}
};
public void updatePausePlay() {
if (mRoot == null || mPauseButton == null || mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) {
mPauseButton.setImageResource(android.R.drawable.ic_media_pause);
} else {
mPauseButton.setImageResource(android.R.drawable.ic_media_play);
}
}
public void reset(){
setProgress();
}
public void updateFullScreen() {
if (mRoot == null || mFullscreenButton == null || mPlayer == null) {
return;
}
if (mIsFullScreen) {
mFullscreenButton.setImageResource(R.drawable.icon_player_minimize);
}
else {
mFullscreenButton.setImageResource(R.drawable.icon_player_maximize);
}
}
private void doPauseResume() {
if (mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) {
mPlayer.pause();
} else {
mPlayer.start();
}
updatePausePlay();
}
private void doToggleFullscreen() {
if (mPlayer == null) {
return;
}
requestToggleFullScreen();
}
protected void requestToggleFullScreen(){
}
// There are two scenarios that can trigger the seekbar listener to trigger:
// The first is the user using the touchpad to adjust the posititon of the
// seekbar's thumb. In this case onStartTrackingTouch is called followed by
// a number of onProgressChanged notifications, concluded by onStopTrackingTouch.
// We're setting the field "mDragging" to true for the duration of the dragging
// session to avoid jumps in the position in case of ongoing playback.
// The second scenario involves the user operating the scroll ball, in this
// case there WON'T BE onStartTrackingTouch/onStopTrackingTouch notifications,
// we will simply apply the updated position without suspending regular updates.
private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
public void onStartTrackingTouch(SeekBar bar) {
show(3600000);
mDragging = true;
// By removing these pending progress messages we make sure
// that a) we won't update the progress while the user adjusts
// the seekbar and b) once the user is done dragging the thumb
// we will post one of these messages to the queue again and
// this ensures that there will be exactly one message queued up.
mHandler.removeMessages(SHOW_PROGRESS);
}
public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
if (mPlayer == null) {
return;
}
if (!fromuser) {
// We're not interested in programmatically generated changes to
// the progress bar's position.
return;
}
long duration = mPlayer.getDuration();
long newposition = (duration * progress) / 1000L;
mPlayer.seekTo( (int) newposition);
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime( (int) newposition));
}
public void onStopTrackingTouch(SeekBar bar) {
mDragging = false;
setProgress();
updatePausePlay();
show(sDefaultTimeout);
// Ensure that progress is properly updated in the future,
// the call to show() does not guarantee this because it is a
// no-op if we are already showing.
mHandler.sendEmptyMessage(SHOW_PROGRESS);
}
};
@Override
public void setEnabled(boolean enabled) {
if (mPauseButton != null) {
mPauseButton.setEnabled(enabled);
}
if (mFfwdButton != null) {
mFfwdButton.setEnabled(enabled);
}
if (mRewButton != null) {
mRewButton.setEnabled(enabled);
}
if (mNextButton != null) {
mNextButton.setEnabled(enabled && mNextListener != null);
}
if (mPrevButton != null) {
mPrevButton.setEnabled(enabled && mPrevListener != null);
}
if (mProgress != null) {
mProgress.setEnabled(enabled);
}
disableUnsupportedButtons();
super.setEnabled(enabled);
}
private View.OnClickListener mRewListener = new View.OnClickListener() {
public void onClick(View v) {
if (mPlayer == null) {
return;
}
int pos = mPlayer.getCurrentPosition();
pos -= 5000; // milliseconds
mPlayer.seekTo(pos);
setProgress();
show(sDefaultTimeout);
}
};
private View.OnClickListener mFfwdListener = new View.OnClickListener() {
public void onClick(View v) {
if (mPlayer == null) {
return;
}
int pos = mPlayer.getCurrentPosition();
pos += 15000; // milliseconds
mPlayer.seekTo(pos);
setProgress();
show(sDefaultTimeout);
}
};
private void installPrevNextListeners() {
if (mNextButton != null) {
mNextButton.setOnClickListener(mNextListener);
mNextButton.setEnabled(mNextListener != null);
}
if (mPrevButton != null) {
mPrevButton.setOnClickListener(mPrevListener);
mPrevButton.setEnabled(mPrevListener != null);
}
}
public void setPrevNextListeners(View.OnClickListener next, View.OnClickListener prev) {
mNextListener = next;
mPrevListener = prev;
mListenersSet = true;
if (mRoot != null) {
installPrevNextListeners();
if (mNextButton != null && !mFromXml) {
mNextButton.setVisibility(View.VISIBLE);
}
if (mPrevButton != null && !mFromXml) {
mPrevButton.setVisibility(View.VISIBLE);
}
}
}
private static class MessageHandler extends Handler {
private final WeakReference<CustomMediaController> mView;
MessageHandler(CustomMediaController view) {
mView = new WeakReference<CustomMediaController>(view);
}
@Override
public void handleMessage(Message msg) {
CustomMediaController view = mView.get();
if (view == null || view.mPlayer == null) {
return;
}
int pos;
switch (msg.what) {
case FADE_OUT:
view.hide();
break;
case SHOW_PROGRESS:
pos = view.setProgress();
if (!view.mDragging && view.mShowing && view.mPlayer.isPlaying()) {
msg = obtainMessage(SHOW_PROGRESS);
sendMessageDelayed(msg, 1000 - (pos % 1000));
}
break;
}
}
}
}
|
package org.spine3.base;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.protobuf.InvalidProtocolBufferException;
import io.grpc.Metadata;
import io.grpc.Metadata.Key;
import org.spine3.annotations.Internal;
import org.spine3.util.Exceptions;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.grpc.Metadata.BINARY_BYTE_MARSHALLER;
/**
* Serves as converter from {@link Error} to {@link Metadata} and vice versa.
*
* @author Dmytro Grankin
*/
@Internal
public class MetadataConverter {
private static final String ERROR_KEY_NAME = "Spine-Error-bin";
/**
* The {@link Metadata.Key} to store and get an {@link Error} from a {@link Metadata}.
*/
@VisibleForTesting
static final Key<byte[]> KEY = Key.of(ERROR_KEY_NAME, BINARY_BYTE_MARSHALLER);
// Prevent instantiation of this utility class.
private MetadataConverter() {
}
/**
* Returns the {@link Metadata}, containing the {@link Error} as a byte array.
*
* @param error the error to convert
* @return the metadata containing error
*/
public static Metadata toMetadata(Error error) {
checkNotNull(error);
final Metadata metadata = new Metadata();
metadata.put(KEY, error.toByteArray());
return metadata;
}
/**
* Returns the {@link Error} extracted from the {@link Metadata}.
*
* @param metadata the metadata to convert
* @return the error extracted from the metadata or {@code Optional.absent()}
* if there is no error.
*/
public static Optional<Error> toError(Metadata metadata) {
checkNotNull(metadata);
final byte[] bytes = metadata.get(KEY);
if (bytes == null) {
return Optional.absent();
}
try {
final Error error = Error.parseFrom(bytes);
return Optional.of(error);
} catch (InvalidProtocolBufferException e) {
throw Exceptions.wrappedCause(e);
}
}
}
|
package com.nurkiewicz.java8;
import org.junit.Test;
import org.mockito.InOrder;
import java.util.Date;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongConsumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.data.Offset.offset;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
/**
* - Use explicit Function, Predicate, Supplier, Consuner (like Guava)
* - Change Encrypter to class taking Function<Byte, Byte>
* - Turning Function, Supplier and Producer into lambda
* - Method references (method, static method, constructor)
* - Higher order functions - returning lambdas
*/
public class J03_FunctionTest {
@Test
public void shouldPrependHello() {
final Function<Integer, String> fun = null;
assertThat(fun.apply(42)).isEqualTo("Answer is 42");
}
@Test
public void shouldProduceAnser() {
final Supplier<Integer> answerFun = null;
assertThat(answerFun.get()).isEqualTo(42);
}
@Test
public void shouldDecideIfNegative() {
final Predicate<Double> isNegative = null;
assertThat(isNegative.test(3.0)).isFalse();
assertThat(isNegative.test(0.0)).isFalse();
assertThat(isNegative.test(-1.1)).isTrue();
}
@Test
public void shouldCallOtherClassInConsumer() {
final Date dateMock = mock(Date.class);
final Consumer<Long> consumer = null;
consumer.accept(1000L);
consumer.accept(2000L);
final InOrder order = inOrder(dateMock);
order.verify(dateMock).setTime(1000L);
order.verify(dateMock).setTime(2000L);
}
@Test
public void shouldCallOtherClassInPrimitiveConsumer() {
final Date dateMock = mock(Date.class);
final LongConsumer consumer = null;
consumer.accept(1000L);
consumer.accept(2000L);
final InOrder order = inOrder(dateMock);
order.verify(dateMock).setTime(1000L);
order.verify(dateMock).setTime(2000L);
}
@Test
public void shouldInvokeReturnedLambdas() throws Exception {
//given
final Function<String, Integer> strLenFun = createStringLenFunction();
final Function<Integer, Double> tripleFun = multiplyFun(3.0);
final String input = "abcd";
//when
final int strLen = strLenFun.apply(input);
final double tripled = tripleFun.apply(4);
//then
assertThat(strLen).isEqualTo(4);
assertThat(tripled).isEqualTo(4 * 3.0, offset(0.01));
}
@Test
public void shouldComposeFunctionsInVariousWays() throws Exception {
//given
final Function<String, Integer> strLenFun = createStringLenFunction();
final Function<Integer, Double> tripleFun = multiplyFun(3.0);
final Function<String, Double> andThenFun = strLenFun.andThen(tripleFun);
final Function<String, Double> composeFun = tripleFun.compose(strLenFun);
final String input = "abcd";
//when
final double naiveResult = tripleFun.apply(strLenFun.apply(input));
final double andThenResult = andThenFun.apply(input);
final double composeResult = composeFun.apply(input);
//then
assertThat(naiveResult).isEqualTo(4 * 3.0, offset(0.01));
assertThat(andThenResult).isEqualTo(4 * 3.0, offset(0.01));
assertThat(composeResult).isEqualTo(4 * 3.0, offset(0.01));
}
private Function<Integer, Double> multiplyFun(double times) {
throw new UnsupportedOperationException("multiplyFun()");
}
private Function<String, Integer> createStringLenFunction() {
throw new UnsupportedOperationException("createStringLenFunction()");
}
}
|
package javasearch;
import org.junit.Test;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
public class SearchResultTest {
public SearchResultTest() {
}
@Test
public final void testSingleLineSearchResult() {
final Pattern pattern = Pattern.compile("Search");
final SearchFile searchFile = new SearchFile("~/src/git/xsearch/csharp/CsSearch/CsSearch",
"Searcher.cs", FileType.TEXT);
final int lineNum = 10;
final int matchStartIndex = 15;
final int matchEndIndex = 23;
final String line = "\tpublic class Searcher\n";
final SearchResult searchResult = new SearchResult(pattern, searchFile, lineNum,
matchStartIndex, matchEndIndex, line);
final String expectedPath = "~/src/git/xsearch/csharp/CsSearch/CsSearch" + File.separator + "Searcher.cs";
final String expectedOutput = String.format("%s: %d: [%d:%d]: %s", expectedPath,
lineNum, matchStartIndex, matchEndIndex, line.trim());
assertEquals(searchResult.toString(), expectedOutput);
}
@Test
public final void testBinaryFileSearchResult() {
final Pattern pattern = Pattern.compile("Search");
final SearchFile searchFile = new SearchFile("~/src/git/xsearch/csharp/CsSearch/CsSearch",
"Searcher.exe", FileType.BINARY);
final int lineNum = 0;
final int matchStartIndex = 0;
final int matchEndIndex = 0;
final SearchResult searchResult = new SearchResult(pattern, searchFile, lineNum,
matchStartIndex, matchEndIndex, null);
final String expectedPath = "~/src/git/xsearch/csharp/CsSearch/CsSearch" + File.separator + "Searcher.exe";
final String expectedOutput = String.format("%s matches at [0:0]", expectedPath);
assertEquals(searchResult.toString(), expectedOutput);
}
@Test
public final void testMultiLineSearchResult() {
final Pattern pattern = Pattern.compile("Search");
final SearchFile searchFile = new SearchFile("~/src/git/xsearch/csharp/CsSearch/CsSearch",
"Searcher.cs", FileType.TEXT);
final int lineNum = 10;
final int matchStartIndex = 15;
final int matchEndIndex = 23;
final String line = "\tpublic class Searcher\n";
final List<String> linesBefore = Arrays.asList("namespace CsSearch\n", "{\n");
final List<String> linesAfter = Arrays.asList("\t{\n", "\t\tprivate readonly FileTypes _fileTypes;\n");
final SearchResult searchResult = new SearchResult(pattern, searchFile, lineNum,
matchStartIndex, matchEndIndex, line, linesBefore, linesAfter);
final String expectedPath = "~/src/git/xsearch/csharp/CsSearch/CsSearch" + File.separator + "Searcher.cs";
final String expectedOutput = String.format(
"================================================================================\n" +
"%s: %d: [%d:%d]\n" +
"
" 8 | namespace CsSearch\n" +
" 9 | {\n" +
"> 10 | \tpublic class Searcher\n" +
" 11 | \t{\n" +
" 12 | \t\tprivate readonly FileTypes _fileTypes;\n",
expectedPath, lineNum, matchStartIndex, matchEndIndex);
assertEquals(searchResult.toString(), expectedOutput);
}
}
|
package com.pengrad.telegrambot;
import com.pengrad.telegrambot.checks.AnimationCheck;
import com.pengrad.telegrambot.checks.AudioTest;
import com.pengrad.telegrambot.checks.ChatMemberTest;
import com.pengrad.telegrambot.checks.ChatTest;
import com.pengrad.telegrambot.checks.DocumentTest;
import com.pengrad.telegrambot.checks.FileTest;
import com.pengrad.telegrambot.checks.GameHighScoreTest;
import com.pengrad.telegrambot.checks.GameTest;
import com.pengrad.telegrambot.checks.MessageTest;
import com.pengrad.telegrambot.checks.PhotoSizeTest;
import com.pengrad.telegrambot.checks.StickerTest;
import com.pengrad.telegrambot.checks.UpdateTest;
import com.pengrad.telegrambot.checks.UserTest;
import com.pengrad.telegrambot.checks.VideoNoteCheck;
import com.pengrad.telegrambot.checks.VideoTest;
import com.pengrad.telegrambot.checks.VoiceTest;
import com.pengrad.telegrambot.checks.WebhookInfoTest;
import com.pengrad.telegrambot.impl.TelegramBotClient;
import com.pengrad.telegrambot.model.*;
import com.pengrad.telegrambot.model.request.ChatAction;
import com.pengrad.telegrambot.model.request.ForceReply;
import com.pengrad.telegrambot.model.request.InlineKeyboardButton;
import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup;
import com.pengrad.telegrambot.model.request.InlineQueryResult;
import com.pengrad.telegrambot.model.request.InlineQueryResultArticle;
import com.pengrad.telegrambot.model.request.InlineQueryResultAudio;
import com.pengrad.telegrambot.model.request.InlineQueryResultCachedAudio;
import com.pengrad.telegrambot.model.request.InlineQueryResultCachedDocument;
import com.pengrad.telegrambot.model.request.InlineQueryResultCachedGif;
import com.pengrad.telegrambot.model.request.InlineQueryResultCachedMpeg4Gif;
import com.pengrad.telegrambot.model.request.InlineQueryResultCachedPhoto;
import com.pengrad.telegrambot.model.request.InlineQueryResultCachedSticker;
import com.pengrad.telegrambot.model.request.InlineQueryResultCachedVideo;
import com.pengrad.telegrambot.model.request.InlineQueryResultCachedVoice;
import com.pengrad.telegrambot.model.request.InlineQueryResultContact;
import com.pengrad.telegrambot.model.request.InlineQueryResultDocument;
import com.pengrad.telegrambot.model.request.InlineQueryResultGame;
import com.pengrad.telegrambot.model.request.InlineQueryResultGif;
import com.pengrad.telegrambot.model.request.InlineQueryResultLocation;
import com.pengrad.telegrambot.model.request.InlineQueryResultMpeg4Gif;
import com.pengrad.telegrambot.model.request.InlineQueryResultPhoto;
import com.pengrad.telegrambot.model.request.InlineQueryResultVenue;
import com.pengrad.telegrambot.model.request.InlineQueryResultVideo;
import com.pengrad.telegrambot.model.request.InlineQueryResultVoice;
import com.pengrad.telegrambot.model.request.InputContactMessageContent;
import com.pengrad.telegrambot.model.request.InputLocationMessageContent;
import com.pengrad.telegrambot.model.request.InputMediaAnimation;
import com.pengrad.telegrambot.model.request.InputMediaAudio;
import com.pengrad.telegrambot.model.request.InputMediaDocument;
import com.pengrad.telegrambot.model.request.InputMediaPhoto;
import com.pengrad.telegrambot.model.request.InputMediaVideo;
import com.pengrad.telegrambot.model.request.InputTextMessageContent;
import com.pengrad.telegrambot.model.request.InputVenueMessageContent;
import com.pengrad.telegrambot.model.request.KeyboardButton;
import com.pengrad.telegrambot.model.request.KeyboardButtonPollType;
import com.pengrad.telegrambot.model.request.LoginUrl;
import com.pengrad.telegrambot.model.request.ParseMode;
import com.pengrad.telegrambot.model.request.ReplyKeyboardMarkup;
import com.pengrad.telegrambot.model.request.ReplyKeyboardRemove;
import com.pengrad.telegrambot.passport.Credentials;
import com.pengrad.telegrambot.passport.EncryptedPassportElement;
import com.pengrad.telegrambot.passport.PassportData;
import com.pengrad.telegrambot.passport.PassportElementErrorDataField;
import com.pengrad.telegrambot.passport.PassportFile;
import com.pengrad.telegrambot.passport.PersonalDetails;
import com.pengrad.telegrambot.passport.SecureData;
import com.pengrad.telegrambot.passport.SecureValue;
import com.pengrad.telegrambot.passport.SetPassportDataErrors;
import com.pengrad.telegrambot.request.*;
import com.pengrad.telegrambot.response.*;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static com.pengrad.telegrambot.request.ContentTypes.VIDEO_MIME_TYPE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* stas
* 5/2/16.
*/
public class TelegramBotTest {
private static final Properties props = new Properties();
static String getProp(String key) {
return props.getProperty(key, System.getenv(key));
}
static {
try {
props.load(new FileInputStream("local.properties"));
} catch (Exception ignored) {
}
String chat = getProp("CHAT_ID");
String group = getProp("GROUP_ID");
chatId = Integer.parseInt(chat);
groupId = Long.parseLong(group);
privateKey = getProp("PRIVATE_KEY");
testPassportData = getProp("TEST_PASSPORT_DATA");
testCallbackQuery = getProp("TEST_CALLBACK_QUERY");
testInlineQuery = getProp("TEST_INLINE_QUERY");
testChosenInlineResult = getProp("TEST_CHOSEN_INLINE_RESULT");
testPollAnswer = getProp("TEST_POLL_ANSWER");
}
public static TelegramBot createTestBot() {
boolean localBuild = new File("local.properties").exists();
String token = getProp("TEST_TOKEN");
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder()
.connectTimeout(75, TimeUnit.SECONDS)
.writeTimeout(75, TimeUnit.SECONDS)
.readTimeout(75, TimeUnit.SECONDS)
.addInterceptor(new RetryInterceptor(1000));
if (localBuild) {
okHttpBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
}
return new TelegramBot.Builder(token).okHttpClient(okHttpBuilder.build()).build();
}
static TelegramBot bot = createTestBot();
static Integer chatId;
static Long groupId;
Integer forwardMessageId = 33263;
Integer forwardMessageIdUser = 23714;
String stickerId = "BQADAgAD4AAD9HsZAAGVRXVaYXiJVAI";
String channelName = "@bottest";
Long channelId = -1001002720332L;
Integer memberBot = 215003245;
Long localGroup = -1001431704825L;
static String privateKey;
static String testPassportData;
static String testCallbackQuery;
static String testInlineQuery;
static String testChosenInlineResult;
static String testPollAnswer;
// static String testShippingQuery;
// static String testPreCheckoutQuery;
static Path resourcePath = Paths.get("src/test/resources");
static File imageFile = resourcePath.resolve("image.jpg").toFile();
static byte[] imageBytes;
static File stickerFile = resourcePath.resolve("imageSticker.png").toFile();
static File stickerFileAnim = resourcePath.resolve("sticker_anim.tgs").toFile();
static File audioFile = resourcePath.resolve("beep.mp3").toFile();
static byte[] audioBytes;
static File docFile = resourcePath.resolve("doc.txt").toFile();
static byte[] docBytes;
static File videoFile = resourcePath.resolve("tabs.mp4").toFile();
static byte[] videoBytes;
static File videoNoteFile = resourcePath.resolve("video_note.mp4").toFile();
static byte[] videoNoteBytes;
static String certificateFile = resourcePath.resolve("cert.pem").toString();
static String someUrl = "http://google.com/";
static String audioFileId = "CQADAgADXAADgNqgSevw7NljQE4lAg";
static String docFileId = "BQADAgADuwADgNqYSaVAUsHMq6hqAg";
static String voiceFileId = "AwADAgADYwADuYNZSZww_hkrzCIpAg";
static String videoFileId = "BAADAgADZAADuYNZSXhLnzJTZ2yvAg";
static String photoFileId = "AgADAgADDKgxG7mDWUlvyFIJ9XfF9yszSw0ABBhVadWwbAK1z-wIAAEC";
static String gifFileId = "CgADAgADfQADgNqgSTt9SzatJhc3FgQ";
static String withSpaceFileId = "BAADAgADZwADkg-4SQI5WM0SPNHrAg";
static String stickerSet = "testset_by_pengrad_test_bot";
static String stickerSetAnim = "testset_anim_by_pengrad_test_bot";
static File thumbFile = resourcePath.resolve("thumb.jpg").toFile();
static byte[] thumbBytes;
static Integer thumbSize = 3718;
static File gifFile = resourcePath.resolve("anim3.gif").toFile();
static byte[] gifBytes;
static {
try {
imageBytes = Files.readAllBytes(imageFile.toPath());
audioBytes = Files.readAllBytes(audioFile.toPath());
docBytes = Files.readAllBytes(docFile.toPath());
videoBytes = Files.readAllBytes(videoFile.toPath());
videoNoteBytes = Files.readAllBytes(videoNoteFile.toPath());
thumbBytes = Files.readAllBytes(thumbFile.toPath());
gifBytes = Files.readAllBytes(gifFile.toPath());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void getMe() {
GetMeResponse response = bot.execute(new GetMe());
User user = response.user();
UserTest.checkUser(user);
assertTrue(user.isBot());
assertFalse(user.canJoinGroups()); // can be changed via BotFather
assertTrue(user.canReadAllGroupMessages());
assertTrue(user.supportsInlineQueries());
}
@Test
public void getUpdates() {
GetUpdates getUpdates = new GetUpdates()
.offset(874205003)
.allowedUpdates("")
.timeout(0)
.limit(100);
assertEquals(100, getUpdates.getLimit());
GetUpdatesResponse response = bot.execute(getUpdates);
UpdateTest.check(response.updates());
}
@Test
public void getFile() throws IOException {
GetFileResponse response = bot.execute(new GetFile(withSpaceFileId));
FileTest.check(response.file());
String path = bot.getFullFilePath(response.file());
Request request = new Request.Builder().head().url(path).build();
Response pathResponse = new OkHttpClient().newCall(request).execute();
assertTrue(pathResponse.isSuccessful());
}
@Test
public void kickChatMember() {
BaseResponse response = bot.execute(new KickChatMember(channelName, chatId).untilDate(123));
assertFalse(response.isOk());
assertEquals(400, response.errorCode());
assertEquals("Bad Request: can't remove chat owner", response.description());
}
@Test
public void unbanChatMember() {
BaseResponse response = bot.execute(new UnbanChatMember(channelName, chatId));
assertFalse(response.isOk());
assertEquals(400, response.errorCode());
assertEquals("Bad Request: can't remove chat owner", response.description());
// returns true for non-banned member with onlyIfBanned(true)
response = bot.execute(new UnbanChatMember(channelName, chatId).onlyIfBanned(true));
assertTrue(response.isOk());
}
@Test
public void restrictChatMember() {
// old way of restrict
BaseResponse response = bot.execute(
new RestrictChatMember(groupId, memberBot)
.untilDate(100)
.canSendMessages(false)
.canSendMediaMessages(false)
.canSendOtherMessages(false)
.canAddWebPagePreviews(false));
assertTrue(response.isOk());
ChatPermissions permissions = new ChatPermissions()
.canChangeInfo(true)
.canInviteUsers(true)
.canPinMessages(true)
.canSendPolls(true); // implies can_send_messages
response = bot.execute(new RestrictChatMember(groupId, memberBot, permissions));
assertTrue(response.isOk());
}
@Test
public void promoteChatMember() {
BaseResponse response = bot.execute(
new PromoteChatMember(groupId, memberBot)
.isAnonymous(false)
.canChangeInfo(false)
.canPostMessages(false)
.canEditMessages(false)
.canDeleteMessages(false)
.canInviteUsers(false)
.canRestrictMembers(false)
.canPinMessages(false)
.canPromoteMembers(true));
assertTrue(response.isOk());
}
@Test
public void editMessageText() {
String text = "Update " + System.currentTimeMillis();
BaseResponse response = bot.execute(new EditMessageText(chatId, 925, text)
.parseMode(ParseMode.Markdown)
.disableWebPagePreview(true)
.replyMarkup(new InlineKeyboardMarkup()));
assertTrue(response.isOk());
assertNotNull(((SendResponse) response).message().editDate());
response = bot.execute(new EditMessageText(channelName, 306, text));
assertTrue(response.isOk());
response = bot.execute(new EditMessageText("AgAAAN3wAQCj_Q4DjX4ok5VEUZU", text));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: MESSAGE_ID_INVALID", response.description());
}
}
@Test
public void editMessageCaption() {
String text = "Update " + System.currentTimeMillis() + " <b>bold</b>";
SendResponse sendResponse = (SendResponse) bot.execute(new EditMessageCaption(chatId, 8124)
.caption(text)
.parseMode(ParseMode.HTML)
.replyMarkup(new InlineKeyboardMarkup()));
assertTrue(sendResponse.isOk());
Message message = sendResponse.message();
assertEquals(text.replace("<b>", "").replace("</b>", ""), message.caption());
MessageEntity captionEntity = message.captionEntities()[0];
assertEquals(MessageEntity.Type.bold, captionEntity.type());
assertEquals((Integer) 21, captionEntity.offset());
assertEquals((Integer) 4, captionEntity.length());
BaseResponse response = bot.execute(new EditMessageCaption(channelName, 511).caption(text));
assertTrue(response.isOk());
response = bot.execute(new EditMessageCaption("AgAAAPrwAQCj_Q4D2s-51_8jsuU").caption(text));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: MESSAGE_ID_INVALID", response.description());
}
}
@Test
public void editMessageReplyMarkup() {
String text = "Update" + System.currentTimeMillis();
InlineKeyboardMarkup keyboard = new InlineKeyboardMarkup(new InlineKeyboardButton(text).url("https://google.com"));
InlineKeyboardMarkup gameKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton(text).callbackGame("test game"));
BaseResponse response = bot.execute(new EditMessageReplyMarkup(chatId, 8124).replyMarkup(keyboard));
assertTrue(response.isOk());
response = bot.execute(new EditMessageReplyMarkup(channelName, 511).replyMarkup(keyboard));
assertTrue(response.isOk());
response = bot.execute(new EditMessageReplyMarkup("AgAAAPrwAQCj_Q4D2s-51_8jsuU").replyMarkup(gameKeyboard));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: MESSAGE_ID_INVALID", response.description());
}
}
@Test
public void answerInline() {
// inlineQuery sent by client after typing "@bot query" in message field
InlineQuery inlineQuery = BotUtils.parseUpdate(testInlineQuery).inlineQuery();
String inlineQueryId = inlineQuery.id();
assertFalse(inlineQueryId.isEmpty());
UserTest.checkUser(inlineQuery.from(), true);
assertEquals(Integer.valueOf(12345), inlineQuery.from().id());
assertEquals("if", inlineQuery.query());
assertEquals("offset", inlineQuery.offset());
assertNull(inlineQuery.location());
InlineKeyboardMarkup keyboardMarkup = new InlineKeyboardMarkup(
new InlineKeyboardButton("inline game").callbackGame("pengrad test game description"),
new InlineKeyboardButton("inline ok").callbackData("callback ok"),
new InlineKeyboardButton("cancel").callbackData("callback cancel"),
new InlineKeyboardButton("url").url(someUrl),
new InlineKeyboardButton("switch inline").switchInlineQuery("query"),
new InlineKeyboardButton("switch inline current").switchInlineQueryCurrentChat("query"));
InlineQueryResult<?>[] results = new InlineQueryResult[]{
new InlineQueryResultArticle("1", "title",
new InputTextMessageContent("message")
.entities(new MessageEntity(MessageEntity.Type.bold, 0, 2))
.disableWebPagePreview(false).parseMode(ParseMode.HTML))
.url(someUrl).hideUrl(true).description("desc").thumbUrl(someUrl).thumbHeight(100).thumbWidth(100),
new InlineQueryResultArticle("2", "title",
new InputContactMessageContent("123123123", "na,e").lastName("lastName").vcard("qr vcard")),
new InlineQueryResultArticle("3", "title", new InputLocationMessageContent(50f, 50f)
.livePeriod(60).heading(100).horizontalAccuracy(10f).proximityAlertRadius(500)),
new InlineQueryResultArticle("4", "title",
new InputVenueMessageContent(50f, 50f, "title", "address").foursquareId("sqrId").foursquareType("frType")),
new InlineQueryResultArticle("5", "title", "message"),
new InlineQueryResultAudio("6", someUrl, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML).performer("perf").audioDuration(100),
new InlineQueryResultContact("7", "123123123", "name").lastName("lastName").vcard("tt vcard")
.thumbUrl(someUrl).thumbHeight(100).thumbWidth(100),
new InlineQueryResultDocument("8", someUrl, "title", "application/pdf").caption("cap <b>bold</b>").parseMode(ParseMode.HTML).description("desc")
.thumbUrl(someUrl).thumbHeight(100).thumbWidth(100),
new InlineQueryResultGame("9", "pengrad_test_game").replyMarkup(keyboardMarkup),
new InlineQueryResultGif("10", someUrl, someUrl).caption("cap <b>bold</b>").parseMode(ParseMode.HTML).title("title")
.thumbMimeType("image/gif")
.gifHeight(100).gifWidth(100).gifDuration(100),
new InlineQueryResultLocation("11", 50f, 50f, "title").livePeriod(60)
.heading(100).horizontalAccuracy(10f).proximityAlertRadius(500)
.thumbUrl(someUrl).thumbHeight(100).thumbWidth(100),
new InlineQueryResultMpeg4Gif("12", someUrl, someUrl).caption("cap <b>bold</b>").parseMode(ParseMode.HTML).title("title")
.thumbMimeType("image/gif")
.mpeg4Height(100).mpeg4Width(100).mpeg4Duration(100),
new InlineQueryResultPhoto("13", someUrl, someUrl).photoWidth(100).photoHeight(100).title("title")
.description("desc").caption("cap <b>bold</b>").parseMode(ParseMode.HTML),
new InlineQueryResultPhoto("131", someUrl, someUrl).photoWidth(100).photoHeight(100).title("title")
.description("desc").caption("bold").captionEntities(new MessageEntity(MessageEntity.Type.bold, 0, 2)),
new InlineQueryResultVenue("14", 54f, 55f, "title", "address").foursquareId("frsqrId").foursquareType("frType")
.thumbUrl(someUrl).thumbHeight(100).thumbWidth(100),
new InlineQueryResultVideo("15", someUrl, VIDEO_MIME_TYPE, "text", someUrl, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML)
.videoWidth(100).videoHeight(100).videoDuration(100).description("desc"),
new InlineQueryResultVoice("16", someUrl, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML).voiceDuration(100),
new InlineQueryResultCachedAudio("17", audioFileId).caption("cap <b>bold</b>").parseMode(ParseMode.HTML),
new InlineQueryResultCachedDocument("18", stickerId, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML).description("desc"),
new InlineQueryResultCachedGif("19", gifFileId).caption("cap <b>bold</b>").parseMode(ParseMode.HTML).title("title"),
new InlineQueryResultCachedMpeg4Gif("21", gifFileId).caption("cap <b>bold</b>").parseMode(ParseMode.HTML).title("title"),
new InlineQueryResultCachedPhoto("22", photoFileId).caption("cap <b>bold</b>").parseMode(ParseMode.HTML).description("desc").title("title"),
new InlineQueryResultCachedSticker("23", stickerId),
new InlineQueryResultCachedVideo("24", videoFileId, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML).description("desc"),
new InlineQueryResultCachedVoice("25", voiceFileId, "title").caption("cap <b>bold</b>").parseMode(ParseMode.HTML),
};
BaseResponse response = bot.execute(new AnswerInlineQuery(inlineQueryId, results)
.cacheTime(100)
.isPersonal(true)
.nextOffset("offset")
.switchPmText("go pm")
.switchPmParameter("my_pm_parameter")
);
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: query is too old and response timeout expired or query ID is invalid", response.description());
}
}
@Test
public void chosenInlineResult() {
// chosenInlineResult is sent after user choose result from AnswerInlineQuery
// should be enabled for bot https://core.telegram.org/bots/inline#collecting-feedback
ChosenInlineResult inlineResult = BotUtils.parseUpdate(testChosenInlineResult).chosenInlineResult();
assertNotNull(inlineResult);
assertFalse(inlineResult.resultId().isEmpty());
UserTest.checkUser(inlineResult.from(), true);
assertEquals(Integer.valueOf(12345), inlineResult.from().id());
assertEquals("hi", inlineResult.query());
assertEquals("1", inlineResult.resultId());
assertNull(inlineResult.inlineMessageId());
assertNull(inlineResult.location());
}
@Test
public void answerCallback() {
// callbackQuery sent by client after pressing on InlineKeyboardButton (used in sendGame() test)
CallbackQuery callbackQuery = BotUtils.parseUpdate(testCallbackQuery).callbackQuery();
assertNotNull(callbackQuery);
assertFalse(callbackQuery.id().isEmpty());
UserTest.checkUser(callbackQuery.from(), true);
assertEquals(chatId, callbackQuery.from().id());
MessageTest.checkMessage(callbackQuery.message());
assertFalse(callbackQuery.chatInstance().isEmpty());
assertEquals("pengrad_test_game", callbackQuery.gameShortName());
assertNull(callbackQuery.inlineMessageId());
assertNull(callbackQuery.data());
BaseResponse response = bot.execute(new AnswerCallbackQuery(callbackQuery.id())
.text("answer callback")
.url("telegram.me/pengrad_test_bot?game=pengrad_test_game")
.showAlert(false)
.cacheTime(1));
assertFalse(response.isOk());
assertEquals(400, response.errorCode());
assertEquals("Bad Request: query is too old and response timeout expired or query ID is invalid", response.description());
}
@Test
public void getChat() throws MalformedURLException, URISyntaxException {
Chat chat = bot.execute(new GetChat(groupId)).chat();
ChatTest.checkChat(chat, true);
assertEquals(Chat.Type.supergroup, chat.type());
assertTrue(chat.title().contains("Test Bot Group"));
assertTrue(chat.description().contains("New desc"));
assertEquals(Integer.valueOf(10), chat.slowModeDelay());
assertNotNull(new URL(chat.inviteLink()).toURI());
if (chat.pinnedMessage() != null) MessageTest.checkMessage(chat.pinnedMessage());
assertNull(chat.allMembersAreAdministrators());
assertNull(chat.stickerSetName());
assertNull(chat.canSetStickerSet());
assertEquals(channelId, chat.linkedChatId());
chat = bot.execute(new GetChat(chatId)).chat();
assertNotNull(chat.firstName());
assertNotNull(chat.lastName());
assertEquals("yo", chat.bio());
chat = bot.execute(new GetChat(localGroup)).chat();
ChatLocation location = chat.location();
assertNotNull(location);
assertEquals(60.94062f, location.location().latitude(), 0f);
assertEquals(76.58071f, location.location().longitude(), 0f);
assertTrue(location.address().endsWith("Russia"));
}
@Test
public void leaveChat() {
BaseResponse response = bot.execute(new LeaveChat(chatId));
assertFalse(response.isOk());
assertEquals(400, response.errorCode());
assertEquals("Bad Request: chat member status can't be changed in private chats", response.description());
}
@Test
public void getChatAdministrators() {
GetChatAdministratorsResponse response = bot.execute(new GetChatAdministrators(groupId));
for (ChatMember chatMember : response.administrators()) {
ChatMemberTest.check(chatMember);
if (chatMember.user().firstName().equals("Test Bot")) {
assertFalse(chatMember.canBeEdited());
assertTrue(chatMember.canChangeInfo());
assertTrue(chatMember.canDeleteMessages());
assertTrue(chatMember.canInviteUsers());
assertTrue(chatMember.canRestrictMembers());
assertTrue(chatMember.canPinMessages());
assertTrue(chatMember.canPromoteMembers());
}
}
}
@Test
public void getChatMember() {
restrictChatMember();
ChatMember chatMember = bot.execute(new GetChatMember(groupId, memberBot)).chatMember();
ChatMemberTest.check(chatMember);
assertEquals(ChatMember.Status.restricted, chatMember.status());
assertEquals(Integer.valueOf(0), chatMember.untilDate());
assertNull(chatMember.canPostMessages());
assertNull(chatMember.canEditMessages());
assertTrue(chatMember.isMember());
assertTrue(chatMember.canChangeInfo());
assertTrue(chatMember.canInviteUsers());
assertTrue(chatMember.canPinMessages());
assertTrue(chatMember.canSendPolls());
assertTrue(chatMember.canSendMessages());
assertFalse(chatMember.canSendMediaMessages());
assertFalse(chatMember.canSendOtherMessages());
assertFalse(chatMember.canAddWebPagePreviews());
}
@Test
public void getChatMembersCount() {
GetChatMembersCountResponse response = bot.execute(new GetChatMembersCount(chatId));
assertEquals(2, response.count());
}
@Test
public void getUserProfilePhotos() {
int offset = 1;
GetUserProfilePhotosResponse response = bot.execute(new GetUserProfilePhotos(chatId).limit(100).offset(offset));
UserProfilePhotos photos = response.photos();
assertEquals(photos.totalCount() - offset, photos.photos().length);
for (PhotoSize[] photo : photos.photos()) {
PhotoSizeTest.checkPhotos(photo);
}
if (photos.totalCount() > 1) {
photos = bot.execute(new GetUserProfilePhotos(chatId).limit(1)).photos();
assertEquals(1, photos.photos().length);
}
}
@Test
public void sendMessage() {
SendResponse sendResponse = bot.execute(new SendMessage(chatId, "reply this message").replyMarkup(new ForceReply()));
MessageTest.checkTextMessage(sendResponse.message());
assertNotNull(sendResponse.message().from());
sendResponse = bot.execute(new SendMessage(chatId, "remove keyboard")
.replyMarkup(new ReplyKeyboardRemove())
.disableNotification(true)
.replyToMessageId(8087)
);
MessageTest.checkTextMessage(sendResponse.message());
assertNotNull(sendResponse.message().replyToMessage());
sendResponse = bot.execute(new SendMessage(chatId, "message with keyboard")
.parseMode(ParseMode.HTML)
.disableWebPagePreview(false)
.replyMarkup(new ReplyKeyboardMarkup(
new KeyboardButton("contact").requestContact(true),
new KeyboardButton("location").requestLocation(true))
.oneTimeKeyboard(true)
.resizeKeyboard(true)
.selective(true)));
MessageTest.checkTextMessage(sendResponse.message());
sendResponse = bot.execute(new SendMessage(chatId, "simple buttons")
.replyMarkup(new ReplyKeyboardMarkup("ok", "cancel")));
MessageTest.checkTextMessage(sendResponse.message());
}
@Test
public void sendMessageToChannel() {
String url = "https://google.com/";
SendMessage request = new SendMessage(channelName, "channel message [GG](" + url + ")").parseMode(ParseMode.Markdown);
SendResponse sendResponse = bot.execute(request);
Message message = sendResponse.message();
MessageTest.checkTextMessage(message);
assertEquals(url, message.entities()[0].url());
assertEquals(channelId, message.senderChat().id());
}
@Test
public void sendMessageToChannelId() {
SendMessage request = new SendMessage(channelId, "channel by id message");
SendResponse sendResponse = bot.execute(request);
Message message = sendResponse.message();
MessageTest.checkTextMessage(message);
}
@Test
public void forwardMessage() {
SendResponse response = bot.execute(new ForwardMessage(chatId, chatId, forwardMessageId).disableNotification(true));
Message message = response.message();
MessageTest.checkMessage(message);
assertNotNull(message.forwardDate());
assertNotNull(message.forwardSenderName());
assertNull(message.forwardFrom());
User viaBot = message.viaBot();
UserTest.checkUser(viaBot);
assertEquals("gif", viaBot.username());
// message from user with open account
message = bot.execute(new ForwardMessage(chatId, chatId, forwardMessageIdUser)).message();
MessageTest.checkMessage(message);
assertNotNull(message.forwardDate());
assertNull(message.forwardSenderName());
assertNotNull(message.forwardFrom());
message = bot.execute(new ForwardMessage(channelName, channelName, 651)).message();
assertNotNull(message.authorSignature());
assertNotNull(message.forwardSignature());
assertEquals(Integer.valueOf(651), message.forwardFromMessageId());
Chat chat = message.forwardFromChat();
assertEquals(channelName, "@" + chat.username());
assertEquals(Chat.Type.channel, chat.type());
assertNull(message.forwardSenderName());
message = bot.execute(new ForwardMessage(chatId, groupId, 352)).message();
assertEquals(MessageEntity.Type.text_mention, message.entities()[0].type());
assertNotNull(message.entities()[0].user());
assertNotNull(message.forwardSenderName());
}
@Test
public void copyMessage() {
MessageIdResponse response = bot.execute(new CopyMessage(chatId, chatId, forwardMessageId)
.caption("new **caption**")
.parseMode(ParseMode.MarkdownV2)
.captionEntities(new MessageEntity(MessageEntity.Type.bold, 0, 1))
.allowSendingWithoutReply(false)
.replyToMessageId(1)
.disableNotification(true)
);
assertTrue(response.messageId() > 0);
}
@Test
public void sendAudio() {
Message message = bot.execute(new SendAudio(chatId, audioFileId)).message();
MessageTest.checkMessage(message);
AudioTest.checkAudio(message.audio(), false);
message = bot.execute(new SendAudio(chatId, audioFile).thumb(thumbFile)).message();
MessageTest.checkMessage(message);
AudioTest.checkAudio(message.audio());
assertEquals(thumbSize, message.audio().thumb().fileSize());
String cap = "http://ya.ru <b>bold</b> #audio @pengrad_test_bot", title = "title", performer = "performer";
ParseMode parseMode = ParseMode.HTML;
int duration = 100;
SendAudio sendAudio = new SendAudio(chatId, audioBytes).thumb(thumbBytes).duration(duration)
.caption(cap).parseMode(parseMode).performer(performer).title(title);
message = bot.execute(sendAudio).message();
MessageTest.checkMessage(message);
Audio audio = message.audio();
AudioTest.checkAudio(audio);
assertEquals(cap.replace("<b>", "").replace("</b>", ""), message.caption());
assertEquals((Integer) 100, audio.duration());
assertEquals(performer, audio.performer());
assertEquals(title, audio.title());
assertEquals(thumbSize, audio.thumb().fileSize());
MessageEntity captionEntity = message.captionEntities()[0];
assertEquals(MessageEntity.Type.url, captionEntity.type());
assertEquals((Integer) 0, captionEntity.offset());
assertEquals((Integer) 12, captionEntity.length());
captionEntity = message.captionEntities()[1];
assertEquals(MessageEntity.Type.bold, captionEntity.type());
assertEquals((Integer) 14, captionEntity.offset());
assertEquals((Integer) 4, captionEntity.length());
assertEquals(MessageEntity.Type.hashtag, message.captionEntities()[2].type());
}
@Test
public void underlineStrikethroughMessageEntity() {
String cap = "<u>under1</u> <ins>under2</ins> <s>strike1</s> <strike>strike2</strike> <del>strike3</del>";
cap += " <u><del>nested-tag</del></u>";
ParseMode parseMode = ParseMode.HTML;
SendAudio sendAudio = new SendAudio(chatId, audioFileId).caption(cap).parseMode(parseMode);
Message message = bot.execute(sendAudio).message();
MessageTest.checkMessage(message);
String htmlCaption = cap
.replace("<u>", "").replace("</u>", "")
.replace("<ins>", "").replace("</ins>", "")
.replace("<s>", "").replace("</s>", "")
.replace("<strike>", "").replace("</strike>", "")
.replace("<del>", "").replace("</del>", "");
assertEquals(htmlCaption, message.caption());
assertEquals(7, message.captionEntities().length);
MessageEntity captionEntity = message.captionEntities()[0];
assertEquals(MessageEntity.Type.underline, captionEntity.type());
assertEquals((Integer) 0, captionEntity.offset());
assertEquals((Integer) 6, captionEntity.length());
captionEntity = message.captionEntities()[1];
assertEquals(MessageEntity.Type.underline, captionEntity.type());
assertEquals((Integer) 7, captionEntity.offset());
assertEquals((Integer) 6, captionEntity.length());
captionEntity = message.captionEntities()[2];
assertEquals(MessageEntity.Type.strikethrough, captionEntity.type());
assertEquals((Integer) 14, captionEntity.offset());
assertEquals((Integer) 7, captionEntity.length());
captionEntity = message.captionEntities()[3];
assertEquals(MessageEntity.Type.strikethrough, captionEntity.type());
assertEquals((Integer) 22, captionEntity.offset());
assertEquals((Integer) 7, captionEntity.length());
captionEntity = message.captionEntities()[4];
assertEquals(MessageEntity.Type.strikethrough, captionEntity.type());
assertEquals((Integer) 30, captionEntity.offset());
assertEquals((Integer) 7, captionEntity.length());
captionEntity = message.captionEntities()[5];
assertEquals(MessageEntity.Type.underline, captionEntity.type());
assertEquals((Integer) 38, captionEntity.offset());
assertEquals((Integer) 10, captionEntity.length());
captionEntity = message.captionEntities()[6];
assertEquals(MessageEntity.Type.strikethrough, captionEntity.type());
assertEquals((Integer) 38, captionEntity.offset());
assertEquals((Integer) 10, captionEntity.length());
}
@Test
public void underlineStrikethroughMarkdown() {
String cap = "__under1__ ~strike1~ __~nested~__";
ParseMode parseMode = ParseMode.MarkdownV2;
SendAudio sendAudio = new SendAudio(chatId, audioFileId).caption(cap).parseMode(parseMode);
Message message = bot.execute(sendAudio).message();
MessageTest.checkMessage(message);
String htmlCaption = cap.replace("__", "").replace("~", "");
assertEquals(htmlCaption, message.caption());
assertEquals(4, message.captionEntities().length);
MessageEntity captionEntity = message.captionEntities()[0];
assertEquals(MessageEntity.Type.underline, captionEntity.type());
assertEquals((Integer) 0, captionEntity.offset());
assertEquals((Integer) 6, captionEntity.length());
captionEntity = message.captionEntities()[1];
assertEquals(MessageEntity.Type.strikethrough, captionEntity.type());
assertEquals((Integer) 7, captionEntity.offset());
assertEquals((Integer) 7, captionEntity.length());
captionEntity = message.captionEntities()[2];
assertEquals(MessageEntity.Type.underline, captionEntity.type());
assertEquals((Integer) 15, captionEntity.offset());
assertEquals((Integer) 6, captionEntity.length());
captionEntity = message.captionEntities()[3];
assertEquals(MessageEntity.Type.strikethrough, captionEntity.type());
assertEquals((Integer) 15, captionEntity.offset());
assertEquals((Integer) 6, captionEntity.length());
}
@Test
public void preMessageEntity() {
String cap = "```java\n" +
"String s = new String();\n" +
"```";
ParseMode parseMode = ParseMode.MarkdownV2;
SendAudio sendAudio = new SendAudio(chatId, audioFileId).caption(cap).parseMode(parseMode);
Message message = bot.execute(sendAudio).message();
MessageTest.checkMessage(message);
assertEquals(1, message.captionEntities().length);
assertEquals("java", message.captionEntities()[0].language());
}
@Test
public void sendDocument() {
Message message = bot.execute(new SendDocument(chatId, docFileId)).message();
MessageTest.checkMessage(message);
DocumentTest.check(message.document());
message = bot.execute(new SendDocument(chatId, docBytes).thumb(thumbBytes)).message();
MessageTest.checkMessage(message);
DocumentTest.check(message.document());
assertEquals(thumbSize, message.document().thumb().fileSize());
String caption = "caption <b>bold</b>", fileName = "my doc.zip";
ParseMode parseMode = ParseMode.HTML;
message = bot.execute(
new SendDocument(chatId, docFile).fileName(fileName).thumb(thumbFile).caption(caption).parseMode(parseMode)
.disableContentTypeDetection(true))
.message();
MessageTest.checkMessage(message);
DocumentTest.check(message.document());
assertEquals(caption.replace("<b>", "").replace("</b>", ""), message.caption());
assertEquals(fileName, message.document().fileName());
assertEquals(thumbSize, message.document().thumb().fileSize());
MessageEntity captionEntity = message.captionEntities()[0];
assertEquals(MessageEntity.Type.bold, captionEntity.type());
assertEquals((Integer) 8, captionEntity.offset());
assertEquals((Integer) 4, captionEntity.length());
}
@Test
public void sendPhoto() {
Message message = bot.execute(new SendPhoto(chatId, photoFileId)).message();
MessageTest.checkMessage(message);
PhotoSizeTest.checkPhotos(false, message.photo());
message = bot.execute(new SendPhoto(chatId, imageFile)).message();
MessageTest.checkMessage(message);
PhotoSizeTest.checkPhotos(message.photo());
String caption = "caption <b>bold</b>";
message = bot.execute(new SendPhoto(channelName, imageBytes).caption(caption).parseMode(ParseMode.HTML)).message();
MessageTest.checkMessage(message);
assertEquals(caption.replace("<b>", "").replace("</b>", ""), message.caption());
PhotoSizeTest.checkPhotos(message.photo());
MessageEntity captionEntity = message.captionEntities()[0];
assertEquals(MessageEntity.Type.bold, captionEntity.type());
assertEquals((Integer) 8, captionEntity.offset());
assertEquals((Integer) 4, captionEntity.length());
}
@Test
public void sendSticker() {
Message message = bot.execute(new SendSticker(chatId, stickerFileAnim)).message();
MessageTest.checkMessage(message);
StickerTest.check(message.sticker(), false, true);
assertTrue(message.sticker().isAnimated());
message = bot.execute(new SendSticker(chatId, stickerId)).message();
MessageTest.checkMessage(message);
StickerTest.check(message.sticker(), true, false);
assertFalse(message.sticker().isAnimated());
message = bot.execute(new SendSticker(chatId, imageFile)).message();
MessageTest.checkMessage(message);
StickerTest.check(message.sticker(), false, true);
message = bot.execute(new SendSticker(chatId, imageBytes)).message();
MessageTest.checkMessage(message);
StickerTest.check(message.sticker(), false, true);
}
@Test
public void sendVideo() {
Message message = bot.execute(new SendVideo(chatId, videoFileId)).message();
MessageTest.checkMessage(message);
VideoTest.check(message.video(), false);
message = bot.execute(new SendVideo(chatId, videoFile).thumb(thumbFile)).message();
MessageTest.checkMessage(message);
VideoTest.check(message.video());
assertNotEquals("telegram should generate thumb", thumbSize, message.video().thumb().fileSize());
assertEquals("tabs.mp4", message.video().fileName());
String caption = "caption <b>bold</b>";
int duration = 100;
message = bot.execute(
new SendVideo(chatId, videoBytes).thumb(thumbBytes)
.caption(caption).parseMode(ParseMode.HTML)
.duration(duration).height(1).width(2).supportsStreaming(true))
.message();
MessageTest.checkMessage(message);
assertEquals(caption.replace("<b>", "").replace("</b>", ""), message.caption());
Video video = message.video();
VideoTest.check(message.video());
assertEquals(duration, video.duration().intValue());
assertEquals(120, video.height().intValue());
assertEquals(400, video.width().intValue());
assertEquals("video/mp4", video.mimeType());
assertNotEquals("telegram should generate thumb", thumbSize, video.thumb().fileSize());
MessageEntity captionEntity = message.captionEntities()[0];
assertEquals(MessageEntity.Type.bold, captionEntity.type());
assertEquals((Integer) 8, captionEntity.offset());
assertEquals((Integer) 4, captionEntity.length());
}
@Test
public void sendVoice() {
Message message = bot.execute(new SendVoice(chatId, voiceFileId)).message();
MessageTest.checkMessage(message);
VoiceTest.check(message.voice(), false);
message = bot.execute(new SendVoice(chatId, audioFile)).message();
MessageTest.checkMessage(message);
VoiceTest.check(message.voice());
String caption = "caption <b>bold</b>";
int duration = 100;
message = bot.execute(new SendVoice(chatId, audioBytes).caption(caption).parseMode(ParseMode.HTML).duration(duration)).message();
MessageTest.checkMessage(message);
assertEquals(caption.replace("<b>", "").replace("</b>", ""), message.caption());
VoiceTest.check(message.voice());
assertEquals(duration, message.voice().duration().intValue());
MessageEntity captionEntity = message.captionEntities()[0];
assertEquals(MessageEntity.Type.bold, captionEntity.type());
assertEquals(8, captionEntity.offset().intValue());
assertEquals(4, captionEntity.length().intValue());
}
@Test
public void getWebhookInfo() {
GetWebhookInfoResponse response = bot.execute(new GetWebhookInfo());
WebhookInfoTest.check(response.webhookInfo());
}
@Test
public void setWebhook() throws IOException {
String url = "https://google.com";
Integer maxConnections = 100;
String[] allowedUpdates = {"message", "callback_query"};
String ipAddress = "1.1.1.1";
BaseResponse response = bot.execute(new SetWebhook()
.url(url)
.certificate(new File(certificateFile))
.ipAddress(ipAddress)
.maxConnections(100)
.allowedUpdates(allowedUpdates)
.dropPendingUpdates(true)
);
assertTrue(response.isOk());
WebhookInfo webhookInfo = bot.execute(new GetWebhookInfo()).webhookInfo();
assertEquals(url, webhookInfo.url());
assertTrue(webhookInfo.hasCustomCertificate());
assertEquals(maxConnections, webhookInfo.maxConnections());
assertArrayEquals(allowedUpdates, webhookInfo.allowedUpdates());
Integer lastErrorDate = webhookInfo.lastErrorDate();
if (lastErrorDate != null) {
assertEquals(System.currentTimeMillis(), lastErrorDate * 1000L, 30_000L);
}
String lastErrorMessage = webhookInfo.lastErrorMessage();
if (lastErrorMessage != null) {
assertTrue(lastErrorMessage.contains("SSL"));
}
assertEquals(ipAddress, webhookInfo.ipAddress());
assertEquals(0, webhookInfo.pendingUpdateCount().intValue());
response = bot.execute(new SetWebhook().url("https://google.com")
.certificate(Files.readAllBytes(new File(certificateFile).toPath())).allowedUpdates(""));
assertTrue(response.isOk());
response = bot.execute(new SetWebhook());
assertTrue(response.isOk());
}
@Test
public void deleteWebhook() {
BaseResponse response = bot.execute(new DeleteWebhook().dropPendingUpdates(true));
assertTrue(response.isOk());
}
@Test
public void sendGame() {
InlineKeyboardButton[] buttons = {
new InlineKeyboardButton("inline game").callbackGame("pengrad test game description"),
new InlineKeyboardButton("inline ok").callbackData("callback ok"),
new InlineKeyboardButton("cancel").callbackData("callback cancel"),
new InlineKeyboardButton("url").url(someUrl),
new InlineKeyboardButton("switch inline").switchInlineQuery("query"),
new InlineKeyboardButton("switch inline current").switchInlineQueryCurrentChat("query"),
};
InlineKeyboardButton[][] inlineKeyboard = new InlineKeyboardButton[1][];
inlineKeyboard[0] = buttons;
InlineKeyboardMarkup keyboardMarkup = new InlineKeyboardMarkup(inlineKeyboard);
String desc = "pengrad_test_game";
Message message = bot.execute(new SendGame(chatId, desc).replyMarkup(keyboardMarkup)).message();
MessageTest.checkMessage(message);
Game game = message.game();
GameTest.check(game);
assertEquals(desc, game.description());
InlineKeyboardButton[] actualButtons = message.replyMarkup().inlineKeyboard()[0];
assertEquals(buttons.length, actualButtons.length);
assertNotNull(actualButtons[0].callbackGame());
for (int i = 1; i < buttons.length; i++) {
assertEquals(buttons[i].text(), actualButtons[i].text());
assertFalse(buttons[i].isPay());
}
assertEquals(buttons[1].callbackData(), actualButtons[1].callbackData());
assertEquals(buttons[2].callbackData(), actualButtons[2].callbackData());
assertEquals(buttons[3].url(), actualButtons[3].url());
assertEquals(buttons[4].switchInlineQuery(), actualButtons[4].switchInlineQuery());
assertEquals(buttons[5].switchInlineQueryCurrentChat(), actualButtons[5].switchInlineQueryCurrentChat());
}
@Test
public void setGameScore() {
int res = (int) (System.currentTimeMillis() / 1000);
BaseResponse response = bot.execute(new SetGameScore(chatId, res, "AgAAAPrwAQCj_Q4D2s-51_8jsuU"));
assertTrue(response.isOk());
SendResponse sendResponse = (SendResponse) bot.execute(
new SetGameScore(chatId, res + 1, chatId, 8162).force(true).disableEditMessage(true));
GameTest.check(sendResponse.message().game());
}
@Test
public void getGameHighScores() {
GameHighScore[] scores = bot.execute(new GetGameHighScores(chatId, "AgAAAPrwAQCj_Q4D2s-51_8jsuU")).result();
GameHighScoreTest.check(scores);
scores = bot.execute(new GetGameHighScores(chatId, chatId, 8162)).result();
GameHighScoreTest.check(scores);
}
@Test
public void sendLocation() {
float lat = 21.999998f, lng = 105.2f, horizontalAccuracy = 1.9f;
int livePeriod = 60, heading = 120, proximityAlertRadius = 50000;
Location location = bot.execute(new SendLocation(chatId, lat, lng)
.horizontalAccuracy(horizontalAccuracy)
.livePeriod(livePeriod)
.heading(heading)
.proximityAlertRadius(proximityAlertRadius)
).message().location();
assertEquals(lat, location.latitude(), 0.00001f);
assertEquals(lng, location.longitude(), 0.00001f);
assertEquals(horizontalAccuracy, location.horizontalAccuracy(), 0.11f);
assertEquals(livePeriod, location.livePeriod().intValue());
assertEquals(heading, location.heading().intValue());
assertEquals(proximityAlertRadius, location.proximityAlertRadius().intValue());
}
@Test
public void sendVenue() {
float lat = 21.999998f, lng = 105.2f;
String title = "title", address = "addr", frsqrId = "asdfasdf", frsqrType = "frType";
Venue venue = bot.execute(new SendVenue(chatId, lat, lng, title, address)
.foursquareId(frsqrId)
.foursquareType(frsqrType)
).message().venue();
assertEquals(lat, venue.location().latitude(), 0f);
assertEquals(lng, venue.location().longitude(), 0f);
assertEquals(address, venue.address());
assertEquals(title, venue.title());
assertEquals(frsqrId, venue.foursquareId());
assertEquals(frsqrType, venue.foursquareType());
}
@Test
public void sendContact() {
String phone = "000111", name = "first", lastName = "last", vcard = "ok vcard";
Contact contact = bot.execute(new SendContact(chatId, phone, name).lastName(lastName).vcard(vcard)).message().contact();
assertEquals(phone, contact.phoneNumber());
assertEquals(name, contact.firstName());
assertEquals(lastName, contact.lastName());
assertEquals(vcard, contact.vcard());
assertNull(contact.userId());
}
@Test
public void deleteMessage() {
Message message = bot.execute(new SendMessage(chatId, "message for delete")).message();
BaseResponse response = bot.execute(new DeleteMessage(chatId, message.messageId()));
assertTrue(response.isOk());
}
@Test
public void sendChatAction() {
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.typing.name())).isOk());
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.typing)).isOk());
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.upload_photo)).isOk());
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.record_video)).isOk());
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.upload_video)).isOk());
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.record_audio)).isOk());
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.upload_audio)).isOk());
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.upload_document)).isOk());
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.find_location)).isOk());
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.record_video_note)).isOk());
assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.upload_video_note)).isOk());
}
@Test
public void sendVideoNote() {
SendResponse response = bot.execute(new SendVideoNote(chatId, "DQADAgADmQADYgwpSbum1JrxPsbmAg"));
VideoNoteCheck.check(response.message().videoNote());
}
@Test
public void sendVideoNoteFile() {
SendResponse response = bot.execute(new SendVideoNote(chatId, videoNoteFile).thumb(thumbFile).length(20).duration(30));
VideoNoteCheck.check(response.message().videoNote(), true);
assertNotEquals("telegram should generate thumb", thumbSize, response.message().videoNote().thumb().fileSize());
response = bot.execute(new SendVideoNote(chatId, videoNoteBytes).thumb(thumbBytes));
VideoNoteCheck.check(response.message().videoNote(), true);
assertNotEquals("telegram should generate thumb", thumbSize, response.message().videoNote().thumb().fileSize());
}
@Test
public void setChatAdministratorCustomTitle() {
BaseResponse response = bot.execute(new PromoteChatMember(groupId, memberBot).canPromoteMembers(true));
assertTrue(response.isOk());
String customTitle = "aqi " + new Random().nextInt(999999);
response = bot.execute(new SetChatAdministratorCustomTitle(groupId, memberBot, customTitle));
assertTrue(response.isOk());
ChatMember member = bot.execute(new GetChatMember(groupId, memberBot)).chatMember();
ChatMemberTest.check(member);
assertEquals(customTitle, member.customTitle());
assertFalse(member.isAnonymous());
}
@Test
public void setChatPermissions() {
for (boolean bool : new boolean[]{true, false}) {
ChatPermissions setPerms = new ChatPermissions();
setPerms.canSendMessages(bool);
setPerms.canSendMediaMessages(bool);
setPerms.canSendPolls(bool);
setPerms.canSendOtherMessages(bool);
setPerms.canAddWebPagePreviews(bool);
setPerms.canChangeInfo(bool);
setPerms.canInviteUsers(bool);
setPerms.canPinMessages(bool);
BaseResponse response = bot.execute(new SetChatPermissions(groupId, setPerms));
assertTrue(response.isOk());
Chat chat = bot.execute(new GetChat(groupId)).chat();
ChatPermissions permissions = chat.permissions();
if (bool) {
assertTrue(permissions.canSendMessages());
assertTrue(permissions.canSendMediaMessages());
assertTrue(permissions.canSendPolls());
assertTrue(permissions.canSendOtherMessages());
assertTrue(permissions.canAddWebPagePreviews());
assertFalse(permissions.canChangeInfo());
assertTrue(permissions.canInviteUsers());
assertFalse(permissions.canPinMessages());
} else {
assertFalse(permissions.canSendMessages());
assertFalse(permissions.canSendMediaMessages());
assertFalse(permissions.canSendPolls());
assertFalse(permissions.canSendOtherMessages());
assertFalse(permissions.canAddWebPagePreviews());
assertFalse(permissions.canChangeInfo());
assertFalse(permissions.canInviteUsers());
assertFalse(permissions.canPinMessages());
}
}
}
@Test
public void exportChatInviteLink() {
StringResponse response = bot.execute(new ExportChatInviteLink(groupId));
assertTrue(response.isOk());
assertNotNull(response.result());
}
@Test
public void setChatPhoto() throws IOException {
BaseResponse response = bot.execute(new SetChatPhoto(groupId, imageFile));
assertTrue(response.isOk());
byte[] bytes = Files.readAllBytes(imageFile.toPath());
response = bot.execute(new SetChatPhoto(groupId, bytes));
assertTrue(response.isOk());
}
@Test
public void deleteChatPhoto() {
BaseResponse response = bot.execute(new DeleteChatPhoto(groupId));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: CHAT_NOT_MODIFIED", response.description());
}
}
@Test
public void setChatTitle() {
BaseResponse response = bot.execute(new SetChatTitle(groupId, "Test Bot Group " + System.currentTimeMillis()));
assertTrue(response.isOk());
}
@Test
public void setChatDescription() {
BaseResponse response = bot.execute(new SetChatDescription(groupId, "New desc " + System.currentTimeMillis()));
assertTrue(response.isOk());
}
@Test
public void pinChatMessage() {
BaseResponse response = bot.execute(new PinChatMessage(groupId, 18).disableNotification(false));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: CHAT_NOT_MODIFIED", response.description());
}
}
@Test
public void unpinChatMessage() {
BaseResponse response = bot.execute(new UnpinChatMessage(groupId).messageId(3600));
assertTrue(response.isOk());
}
@Test
public void unpinAllChatMessages() {
BaseResponse response = bot.execute(new UnpinAllChatMessages(groupId));
assertTrue(response.isOk());
}
@Test
public void getStickerSet() {
GetStickerSetResponse response = bot.execute(new GetStickerSet(stickerSet));
StickerSet stickerSet = response.stickerSet();
for (Sticker sticker : response.stickerSet().stickers()) {
StickerTest.check(sticker, true, true);
}
assertTrue(stickerSet.containsMasks());
assertEquals(TelegramBotTest.stickerSet, stickerSet.name());
assertEquals("test1", stickerSet.title());
assertFalse(stickerSet.isAnimated());
Sticker sticker = stickerSet.stickers()[0];
assertEquals(TelegramBotTest.stickerSet, sticker.setName());
MaskPosition maskPosition = sticker.maskPosition();
assertEquals(MaskPosition.Point.forehead.name(), maskPosition.point());
assertEquals(0f, maskPosition.xShift(), 0);
assertEquals(0f, maskPosition.yShift(), 0);
assertEquals(1f, maskPosition.scale(), 0);
}
@Test
public void uploadStickerFile() throws IOException {
byte[] bytes = Files.readAllBytes(stickerFile.toPath());
GetFileResponse response = bot.execute(new UploadStickerFile(chatId, bytes));
FileTest.check(response.file(), false);
}
@Test
public void createNewStickerSet() {
BaseResponse response = bot.execute(
new CreateNewStickerSet(chatId, "test" + System.currentTimeMillis() + "_by_pengrad_test_bot",
"test1", stickerFile, "\uD83D\uDE00")
.containsMasks(true)
.maskPosition(new MaskPosition(MaskPosition.Point.forehead, 0f, 0f, 1f)));
assertTrue(response.isOk());
}
@Test
public void addStickerToSet() {
BaseResponse response = bot.execute(
new AddStickerToSet(chatId, stickerSet, "BQADAgADuAAD7yupS4eB23UmZhGuAg", "\uD83D\uDE15")
.maskPosition(new MaskPosition("eyes", 0f, 0f, 1f)));
assertTrue(response.isOk());
}
@Test
public void createSetAndAddStickerTgs() {
String setName = "test" + System.currentTimeMillis() + "_by_pengrad_test_bot";
BaseResponse response = bot.execute(
CreateNewStickerSet.tgsSticker(chatId, setName, "test1", "\uD83D\uDE00", stickerFileAnim));
assertTrue(response.isOk());
response = bot.execute(
AddStickerToSet.tgsSticker(chatId, setName, "\uD83D\uDE15", stickerFileAnim));
assertTrue(response.isOk());
}
@Test
public void setStickerPositionInSet() {
GetStickerSetResponse setResponse = bot.execute(new GetStickerSet(stickerSet));
Sticker sticker = setResponse.stickerSet().stickers()[0];
BaseResponse response = bot.execute(new SetStickerPositionInSet(sticker.fileId(), 0));
assertTrue(response.isOk());
}
@Test
public void deleteStickerFromSet() {
BaseResponse response = bot.execute(new AddStickerToSet(chatId, stickerSet, stickerFile, "\uD83D\uDE15"));
assertTrue(response.isOk());
GetStickerSetResponse setResponse = bot.execute(new GetStickerSet(stickerSet));
int size = setResponse.stickerSet().stickers().length;
Sticker sticker = setResponse.stickerSet().stickers()[size - 1];
response = bot.execute(new DeleteStickerFromSet(sticker.fileId()));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: STICKERSET_NOT_MODIFIED", response.description());
}
}
@Test
public void setStickerSetThumb() {
String thumbFile = "CAACAgIAAxkBAAJ0ll6DO4bNCynpfZmS6g-YcGY2zrP5AAIBAAPANk8TGC5zMKs_LVEYBA";
BaseResponse response = bot.execute(new SetStickerSetThumb(stickerSetAnim, chatId, thumbFile));
assertTrue(response.isOk());
StickerSet set = bot.execute(new GetStickerSet(stickerSetAnim)).stickerSet();
assertTrue(set.isAnimated());
PhotoSize thumb = set.thumb();
PhotoSizeTest.checkPhotos(thumb);
assertEquals(Integer.valueOf(100), thumb.width());
assertEquals(Integer.valueOf(100), thumb.height());
assertEquals(Integer.valueOf(8244), thumb.fileSize());
// clear thumb by not sending it
response = bot.execute(new SetStickerSetThumb(stickerSetAnim, chatId));
assertTrue(response.isOk());
}
@Test
public void editMessageLiveLocation() {
BaseResponse response = bot.execute(new EditMessageLiveLocation(chatId, 10009, 21, 105)
.replyMarkup(new InlineKeyboardMarkup()));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: message can't be edited", response.description());
}
String buttonText = "btn_" + System.currentTimeMillis();
response = bot.execute(
new EditMessageLiveLocation("AgAAAPrwAQCj_Q4D2s-51_8jsuU", 21, 102)
.horizontalAccuracy(1f)
.heading(10)
.proximityAlertRadius(100)
.replyMarkup(new InlineKeyboardMarkup(new InlineKeyboardButton(buttonText).callbackGame(buttonText)))
);
assertTrue(response.isOk());
}
@Test
public void stopMessageLiveLocation() {
BaseResponse response = bot.execute(new StopMessageLiveLocation(chatId, 10009));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: message can't be edited", response.description());
}
response = bot.execute(new StopMessageLiveLocation("AgAAAPrwAQCj_Q4D2s-51_8jsuU"));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message",
response.description());
}
}
@Test
public void setChatStickerSet() {
BaseResponse response = bot.execute(new SetChatStickerSet(groupId, "PengradTest"));
assertFalse(response.isOk());
assertEquals(400, response.errorCode());
}
@Test
public void deleteChatStickerSet() {
BaseResponse response = bot.execute(new DeleteChatStickerSet(groupId));
assertFalse(response.isOk());
assertEquals(400, response.errorCode());
}
@Test
public void sendMediaGroup() {
String url = "https://google.com/";
User user = new User(memberBot);
String language = "ru";
MessagesResponse response = bot.execute(new SendMediaGroup(chatId,
new InputMediaPhoto(photoFileId),
new InputMediaPhoto(imageFile).caption("some caption bold")
.captionEntities(
new MessageEntity(MessageEntity.Type.bold, 0, 4),
new MessageEntity(MessageEntity.Type.text_link, 5, 1).url(url),
new MessageEntity(MessageEntity.Type.text_mention, 6, 1).user(user),
new MessageEntity(MessageEntity.Type.pre, 7, 1).language(language)
),
new InputMediaPhoto(imageBytes),
new InputMediaVideo(videoFileId),
new InputMediaVideo(videoFile),
new InputMediaVideo(videoBytes).caption("my video <b>bold</b>").parseMode(ParseMode.HTML)
.duration(10).width(11).height(12).supportsStreaming(true)
));
assertTrue(response.isOk());
assertEquals(6, response.messages().length);
String mediaGroupId = response.messages()[0].mediaGroupId();
assertNotNull(mediaGroupId);
int messagesWithCaption = 0;
for (Message message : response.messages()) {
assertEquals(mediaGroupId, message.mediaGroupId());
if (message.caption() != null) {
assertEquals(MessageEntity.Type.bold, message.captionEntities()[0].type());
messagesWithCaption++;
}
}
assertEquals(2, messagesWithCaption);
MessageEntity[] entities = response.messages()[1].captionEntities();
assertEquals(MessageEntity.Type.bold, entities[0].type());
assertEquals(MessageEntity.Type.text_link, entities[1].type());
assertEquals(MessageEntity.Type.text_mention, entities[2].type());
assertEquals(MessageEntity.Type.pre, entities[3].type());
assertEquals(url, entities[1].url());
assertEquals(user.id(), entities[2].user().id());
assertEquals(language, entities[3].language());
}
@Test
public void editMessageMedia() {
int messageId = 13541;
SendResponse response;
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId,
new InputMediaDocument(docFile)
.thumb(thumbFile)
.disableContentTypeDetection(true)
));
assertEquals((Integer) 14, response.message().document().fileSize());
assertEquals(thumbSize, response.message().document().thumb().fileSize());
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId,
new InputMediaDocument(docBytes).thumb(thumbBytes)));
assertEquals((Integer) 14, response.message().document().fileSize());
assertEquals(thumbSize, response.message().document().thumb().fileSize());
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId, new InputMediaDocument(docFileId)));
MessageTest.checkMessage(response.message());
DocumentTest.check(response.message().document());
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId, new InputMediaAnimation(gifFile)));
assertEquals(Integer.valueOf(1), response.message().animation().duration());
int expectedSize = 160; // idk why?
Integer durationAnim = 17, width = 21, height = 22;
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId,
new InputMediaAnimation(gifBytes).duration(durationAnim).width(width).height(height)
));
Animation animation = response.message().animation();
assertEquals(1, animation.duration().intValue());
assertEquals(expectedSize, animation.width().intValue());
assertEquals(expectedSize, animation.height().intValue());
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId, new InputMediaAnimation(gifFileId)));
assertTrue(response.isOk());
AnimationCheck.check(response.message().animation());
assertEquals(Integer.valueOf(3), response.message().animation().duration());
assertNotEquals(gifFileId, response.message().animation().fileId());
assertNotNull(response.message().document());
assertEquals((Integer) 57527, response.message().document().fileSize());
assertEquals("video/mp4", response.message().document().mimeType());
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId, new InputMediaAudio(audioFileId)));
assertEquals((Integer) 10286, response.message().audio().fileSize());
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId, new InputMediaAudio(audioFile)));
assertEquals((Integer) 10286, response.message().audio().fileSize());
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId, new InputMediaAudio(audioBytes)));
assertEquals((Integer) 10286, response.message().audio().fileSize());
Integer duration = 34;
String performer = "some performer", title = "just a title", fileName = "beep.mp3";
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId,
new InputMediaAudio(audioFile).duration(duration).performer(performer).title(title)
));
Audio audio = response.message().audio();
assertEquals((Integer) 10286, audio.fileSize());
assertEquals(duration, audio.duration());
assertEquals(performer, audio.performer());
assertEquals(title, audio.title());
assertEquals(fileName, audio.fileName());
// send multipart InputMediaPhoto, InputMediaVideo to cover getFileName and getContentType
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId, new InputMediaPhoto(photoFileId).thumb(thumbFile)));
assertNotNull(response.message().photo());
response = (SendResponse) bot.execute(new EditMessageMedia(chatId, messageId, new InputMediaVideo(videoFileId).thumb(thumbFile)));
assertNotNull(response.message().video());
}
@Test
public void sendAnimation() {
int expectedSize = 160; // idk why?
int width = 340, height = 240;
String caption = "gif *file*", captionCheck = "gif file";
SendResponse response = bot.execute(new SendAnimation(chatId, gifFile)
.duration(222).width(width).height(height).thumb(thumbFile)
.caption(caption).parseMode(ParseMode.Markdown));
assertTrue(response.isOk());
Animation animation = response.message().animation();
assertEquals((Integer) 1, animation.duration());
assertEquals(expectedSize, animation.width().intValue());
assertEquals(expectedSize, animation.height().intValue());
assertNotEquals("telegram should generate thumb", thumbSize, animation.thumb().fileSize());
assertEquals(captionCheck, response.message().caption());
assertEquals(MessageEntity.Type.bold, response.message().captionEntities()[0].type());
response = bot.execute(new SendAnimation(chatId, gifBytes).thumb(thumbBytes));
animation = response.message().animation();
assertEquals((Integer) 1, animation.duration());
assertEquals(expectedSize, animation.width().intValue());
assertEquals(expectedSize, animation.height().intValue());
assertNotEquals("telegram should generate thumb", thumbSize, animation.thumb().fileSize());
response = bot.execute(new SendAnimation(chatId, gifFileId));
animation = response.message().animation();
assertEquals((Integer) 3, animation.duration());
assertEquals((Integer) 128, animation.width());
assertEquals((Integer) 128, animation.height());
}
@Test
public void setPassportDataErrors() {
BaseResponse response = bot.execute(new SetPassportDataErrors(chatId,
new PassportElementErrorDataField("personal_details", "first_name",
"TueU2/SswOD5wgQ6uXQ62mJrr0Jdf30r/QQ/jyETHFM=",
"error in page 1")
));
System.out.println(response);
assertTrue(response.isOk());
}
@Test
public void decryptPassport() throws Exception {
PassportData passportData = BotUtils.parseUpdate(testPassportData).message().passportData();
assertNotNull(passportData);
Credentials credentials = passportData.credentials().decrypt(privateKey);
assertNull(credentials.nonce());
SecureData secureData = credentials.secureData();
assertNotNull(secureData.personalDetails());
assertNull(secureData.internalPassport());
assertNull(secureData.driverLicense());
assertNull(secureData.identityCard());
assertNull(secureData.address());
assertNull(secureData.utilityBill());
assertNull(secureData.bankStatement());
assertNull(secureData.rentalAgreement());
assertNull(secureData.passportRegistration());
assertNull(secureData.temporaryRegistration());
SecureValue securePassport = secureData.passport();
assertNull(securePassport.reverseSide());
assertNull(securePassport.selfie());
assertNull(securePassport.files());
for (EncryptedPassportElement encElement : passportData.data()) {
assertNotNull(encElement.data());
if (encElement.type() == EncryptedPassportElement.Type.personal_details) {
assertEquals("DVUCaJq6oU/hItqZjuclmKL1bWwMSACR9w0Kx8PjoHg=", encElement.hash());
assertNull(encElement.phoneNumber());
assertNull(encElement.email());
PersonalDetails pd = (PersonalDetails) encElement.decryptData(credentials);
assertEquals("Sz2", pd.firstName());
assertEquals("P", pd.lastName());
assertEquals("smid", pd.middleName());
assertEquals("1.1.1980", pd.birthDate());
assertEquals("male", pd.gender());
assertEquals("RU", pd.countryCode());
assertEquals("RU", pd.residenceCountryCode());
assertEquals("имя", pd.firstNameNative());
assertEquals("фамилия", pd.lastNameNative());
assertEquals("среднее", pd.middleNameNative());
}
if (encElement.type() == EncryptedPassportElement.Type.passport) {
assertEquals(Integer.valueOf(260608), encElement.frontSide().fileSize());
assertEquals(Integer.valueOf(1535386777), encElement.frontSide().fileDate());
List<PassportFile> files = new ArrayList<>();
files.add(encElement.frontSide());
files.add(encElement.reverseSide());
files.add(encElement.selfie());
if (encElement.files() != null) {
files.addAll(Arrays.asList(encElement.files()));
}
if (encElement.translation() != null) {
files.addAll(Arrays.asList(encElement.translation()));
}
for (PassportFile file : files) {
if (file == null) continue;
byte[] data = encElement.decryptFile(file, credentials, bot);
assertTrue(data.length > 0);
// new FileOutputStream(Paths.get("build/" + encElement.type() + i + ".jpg").toFile()).write(data);
}
}
}
}
@Test
public void sendPoll() {
String question = "Question ?";
String[] answers = {"Answer 1", "Answer 2"};
SendResponse sendResponse = bot.execute(
new SendPoll(groupId, question, answers)
.isAnonymous(false)
.type(Poll.Type.quiz)
.allowsMultipleAnswers(false)
.correctOptionId(1)
.isClosed(false)
.explanation("Some __explanation__ of poll")
.explanationParseMode(ParseMode.MarkdownV2)
.openPeriod(500)
);
Poll poll = sendResponse.message().poll();
assertFalse(poll.id().isEmpty());
assertEquals(question, poll.question());
assertEquals(answers.length, poll.options().length);
for (int i = 0; i < answers.length; i++) {
PollOption option = poll.options()[i];
assertEquals(answers[i], option.text());
assertEquals(Integer.valueOf(0), option.voterCount());
}
assertFalse(poll.isAnonymous());
assertEquals(poll.type(), Poll.Type.quiz);
assertFalse(poll.allowsMultipleAnswers());
assertEquals(poll.totalVoterCount(), Integer.valueOf(0));
assertEquals(poll.correctOptionId(), Integer.valueOf(1));
assertFalse(poll.isClosed());
assertEquals("Some explanation of poll", poll.explanation());
assertEquals(1, poll.explanationEntities().length);
assertEquals(MessageEntity.Type.underline, poll.explanationEntities()[0].type());
assertTrue(poll.openPeriod() >= 495 && poll.openPeriod() <= 500);
}
@Test
public void sendPollWithKeyboard() {
String question = "Question ?";
String[] answers = {"Answer 1", "Answer 2"};
long closeDate = System.currentTimeMillis() / 1000 + 500;
SendResponse sendResponse = bot.execute(
new SendPoll(chatId, question, answers)
.type("regular")
.allowsMultipleAnswers(true)
.replyMarkup(new ReplyKeyboardMarkup(
new KeyboardButton("all polls").requestPoll(new KeyboardButtonPollType()),
new KeyboardButton("quiz").requestPoll(new KeyboardButtonPollType(Poll.Type.quiz)),
new KeyboardButton("regular").requestPoll(new KeyboardButtonPollType("regular"))))
.closeDate(closeDate)
);
Poll poll = sendResponse.message().poll();
assertEquals(question, poll.question());
assertEquals(answers.length, poll.options().length);
assertTrue(poll.isAnonymous());
assertEquals(poll.totalVoterCount(), Integer.valueOf(0));
assertEquals(poll.type(), Poll.Type.regular);
assertTrue(poll.allowsMultipleAnswers());
assertEquals(closeDate, poll.closeDate().longValue());
}
@Test
public void stopPoll() {
String question = "Question ?";
String[] answers = {"Answer 1", "Answer 2"};
SendResponse sendResponse = bot.execute(new SendPoll(groupId, question, answers));
Integer messageId = sendResponse.message().messageId();
PollResponse response = bot.execute(new StopPoll(groupId, messageId));
Poll poll = response.poll();
assertTrue(poll.isClosed());
assertEquals(question, poll.question());
assertEquals(answers.length, poll.options().length);
for (int i = 0; i < answers.length; i++) {
PollOption option = poll.options()[i];
assertEquals(answers[i], option.text());
assertEquals(Integer.valueOf(0), option.voterCount());
}
}
@Test
public void pollAnswer() {
// pollAnswer is sent when user answers in a non-anonymous poll
PollAnswer pollAnswer = BotUtils.parseUpdate(testPollAnswer).pollAnswer();
assertNotNull(pollAnswer);
assertFalse(pollAnswer.pollId().isEmpty());
UserTest.checkUser(pollAnswer.user(), true);
assertEquals(Integer.valueOf(12345), pollAnswer.user().id());
assertArrayEquals(new Integer[]{0, 2}, pollAnswer.optionIds());
}
@Test
public void testAsyncCallback() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
bot.execute(new GetMe(), new Callback<GetMe, GetMeResponse>() {
@Override
public void onResponse(GetMe request, GetMeResponse response) {
latch.countDown();
}
@Override
public void onFailure(GetMe request, IOException e) {
throw new RuntimeException(e);
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void botClientError() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
TelegramBotClient botClient = new TelegramBotClient(new OkHttpClient(), null, TelegramBot.Builder.API_URL);
botClient.send(new GetMe(), new Callback<GetMe, GetMeResponse>() {
@Override
public void onResponse(GetMe request, GetMeResponse response) {
}
@Override
public void onFailure(GetMe request, IOException e) {
latch.countDown();
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void toWebhookResponse() {
assertEquals("{\"method\":\"getMe\"}", new GetMe().toWebhookResponse());
}
@Test
public void loginButton() {
String text = "login";
String url = "http://pengrad.herokuapp.com/hello";
SendResponse response = bot.execute(
new SendMessage(chatId, "Login button").replyMarkup(new InlineKeyboardMarkup(
new InlineKeyboardButton(text).loginUrl(new LoginUrl(url)
.forwardText("forwarded login")
.botUsername("pengrad_test_bot")
.requestWriteAccess(true)))));
assertTrue(response.isOk());
InlineKeyboardButton button = response.message().replyMarkup().inlineKeyboard()[0][0];
assertEquals(text, button.text());
assertEquals(url, button.url());
}
@Test
public void multipartNonAscii() {
String caption = "хорошо";
Message message = bot.execute(
new SendPhoto(chatId, imageFile).fileName("файл.txt").caption(caption)
).message();
assertEquals(caption, message.caption());
MessageTest.checkMessage(message);
PhotoSizeTest.checkPhotos(message.photo());
}
@Test
public void testResponseParameters() {
String errorJson = "{\"ok\":false,\"error_code\":400,\"description\":\"Bad Request: description\",\"parameters\":{\"migrate_to_chat_id\":123456789000,\"retry_after\":3}}";
BaseResponse response = BotUtils.fromJson(errorJson, BaseResponse.class);
ResponseParameters parameters = response.parameters();
assertNotNull(parameters);
assertEquals(Long.valueOf(123456789000L), parameters.migrateToChatId());
assertEquals(Integer.valueOf(3), parameters.retryAfter());
}
@Test
public void sendDice() {
SendResponse response = bot.execute(new SendDice(chatId));
Dice dice = response.message().dice();
assertNotNull(dice);
assertTrue(dice.value() >= 1 && dice.value() <= 6);
assertEquals("", dice.emoji());
response = bot.execute(new SendDice(chatId).darts());
dice = response.message().dice();
assertNotNull(dice);
assertTrue(dice.value() >= 1 && dice.value() <= 6);
assertEquals("", dice.emoji());
response = bot.execute(new SendDice(chatId).basketball());
dice = response.message().dice();
assertNotNull(dice);
assertTrue(dice.value() >= 1 && dice.value() <= 5);
assertEquals("", dice.emoji());
response = bot.execute(new SendDice(chatId).football());
dice = response.message().dice();
assertNotNull(dice);
assertTrue(dice.value() >= 1 && dice.value() <= 5);
assertEquals("", dice.emoji());
response = bot.execute(new SendDice(chatId).slotMachine());
dice = response.message().dice();
assertNotNull(dice);
assertTrue(dice.value() >= 1 && dice.value() <= 64);
assertEquals("", dice.emoji());
}
@Test
public void setMyCommands() {
BotCommand[] commands = new BotCommand[]{
new BotCommand("c1", "desc1"),
new BotCommand("c2", "desc2"),
new BotCommand("c3", "desc3"),
};
BaseResponse response = bot.execute(new SetMyCommands(commands));
assertTrue(response.isOk());
GetMyCommandsResponse commandsResponse = bot.execute(new GetMyCommands());
assertTrue(commandsResponse.isOk());
assertArrayEquals(commandsResponse.commands(), commands);
}
}
|
package org.apache.jmeter.engine;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestListener;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.JMeterThread;
import org.apache.jmeter.threads.JMeterThreadMonitor;
import org.apache.jmeter.threads.ListenerNotifier;
import org.apache.jmeter.threads.TestCompiler;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.util.ListedHashTree;
import org.apache.jmeter.util.SearchByClass;
import org.apache.log.Hierarchy;
import org.apache.log.Logger;
public class StandardJMeterEngine implements JMeterEngine,JMeterThreadMonitor,Runnable
{
private static Logger log = Hierarchy.getDefaultHierarchy().getLoggerFor(
"jmeter.engine");
private static long WAIT_TO_DIE = 5 * 1000; //5 seconds
Map allThreads;
boolean running = false;
ListedHashTree test;
SearchByClass testListeners;
String host = null;
ListenerNotifier notifier;
public StandardJMeterEngine()
{
allThreads = new HashMap();
}
public StandardJMeterEngine(String host)
{
this();
this.host = host;
}
public void configure(ListedHashTree testTree)
{
test = testTree;
}
public void setHost(String host)
{
this.host = host;
}
protected ListedHashTree getTestTree()
{
return test;
}
protected void compileTree()
{
PreCompiler compiler = new PreCompiler();
getTestTree().traverse(compiler);
}
public void runTest() throws JMeterEngineException
{
try
{
log.info("Running the test!");
running = true;
compileTree();
List testLevelElements = new LinkedList(getTestTree().list(getTestTree().getArray()[0]));
removeThreadGroups(testLevelElements);
SearchByClass searcher = new SearchByClass(ThreadGroup.class);
testListeners = new SearchByClass(TestListener.class);
setMode();
getTestTree().traverse(testListeners);
getTestTree().traverse(searcher);
TestCompiler.initialize();
//for each thread group, generate threads
// hand each thread the sampler controller
// and the listeners, and the timer
JMeterThread[] threads;
Iterator iter = searcher.getSearchResults().iterator();
if(iter.hasNext())
{
notifyTestListenersOfStart();
}
notifier = new ListenerNotifier();
notifier.start();
while(iter.hasNext())
{
ThreadGroup group = (ThreadGroup)iter.next();
threads = new JMeterThread[group.getNumThreads()];
for(int i = 0;running && i < threads.length; i++)
{
ListedHashTree threadGroupTree = searcher.getSubTree(group);
threadGroupTree.add(group,testLevelElements);
threads[i] = new JMeterThread(cloneTree(threadGroupTree),this,notifier);
threads[i].setInitialDelay((int)(((float)(group.getRampUp() * 1000) /
(float)group.getNumThreads()) * (float)i));
threads[i].setThreadName(group.getName()+"-"+(i+1));
Thread newThread = new Thread(threads[i]);
newThread.setName(group.getName()+"-"+(i+1));
allThreads.put(threads[i],newThread);
newThread.start();
}
}
}
catch(Exception err)
{
stopTest();
StringWriter string = new StringWriter();
PrintWriter writer = new PrintWriter(string);
err.printStackTrace(writer);
throw new JMeterEngineException(string.toString());
}
}
private void removeThreadGroups(List elements)
{
Iterator iter = elements.iterator();
while(iter.hasNext())
{
Object item = iter.next();
if(item instanceof ThreadGroup)
{
iter.remove();
}
else if(!(item instanceof TestElement))
{
iter.remove();
}
}
}
protected void setMode()
{
SearchByClass testPlan = new SearchByClass(TestPlan.class);
getTestTree().traverse(testPlan);
Object[] plan = testPlan.getSearchResults().toArray();
ResultCollector.enableFunctionalMode(((TestPlan)plan[0]).isFunctionalMode());
}
protected void notifyTestListenersOfStart()
{
Iterator iter = testListeners.getSearchResults().iterator();
while(iter.hasNext())
{
if(host == null)
{
((TestListener)iter.next()).testStarted();
}
else
{
((TestListener)iter.next()).testStarted(host);
}
}
}
protected void notifyTestListenersOfEnd()
{
notifier.stop();
Iterator iter = testListeners.getSearchResults().iterator();
while(!notifier.isStopped())
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
}
log.debug("Waiting for notifier thread to stop");
}
while(iter.hasNext())
{
if(host == null)
{
((TestListener)iter.next()).testEnded();
}
else
{
((TestListener)iter.next()).testEnded(host);
}
}
}
private ListedHashTree cloneTree(ListedHashTree tree)
{
TreeCloner cloner = new TreeCloner();
tree.traverse(cloner);
return cloner.getClonedTree();
}
public void reset()
{
if(running)
{
stopTest();
running = false;
}
}
public synchronized void threadFinished(JMeterThread thread)
{
allThreads.remove(thread);
if(allThreads.size() == 0)
{
stopTest();
}
/*if(allThreads.size() == 0)
{
notifyTestListenersOfEnd();
}*/
}
public synchronized void stopTest()
{
if(running)
{
running = false;
Thread stopThread = new Thread(this);
stopThread.start();
}
}
public void run()
{
tellThreadsToStop();
try
{
Thread.sleep(10 * allThreads.size());
}
catch (InterruptedException e)
{
}
verifyThreadsStopped();
notifyTestListenersOfEnd();
}
private void verifyThreadsStopped()
{
Iterator iter = new HashSet(allThreads.keySet()).iterator();
while(iter.hasNext())
{
Thread t = (Thread)allThreads.get(iter.next());
if(t != null && t.isAlive())
{
try
{
t.join(WAIT_TO_DIE);
}
catch (InterruptedException e)
{
}
if(t.isAlive())
{
log.info("Thread won't die: "+t.getName());
}
}
log.debug("finished thread");
}
}
private void tellThreadsToStop()
{
Iterator iter = new HashSet(allThreads.keySet()).iterator();
while(iter.hasNext())
{
JMeterThread item = (JMeterThread)iter.next();
item.stop();
Thread t = (Thread)allThreads.get(item);
if(t != null)
{
t.interrupt();
}
else
{
log.warn("Lost thread: "+item.getThreadName());
allThreads.remove(item);
}
}
}
}
|
package com.gooddata.connector;
import au.com.bytecode.opencsv.CSVWriter;
import com.gooddata.connector.backend.ConnectorBackend;
import com.gooddata.exception.InternalErrorException;
import com.gooddata.exception.InvalidArgumentException;
import com.gooddata.exception.ProcessingException;
import com.gooddata.google.analytics.FeedDumper;
import com.gooddata.google.analytics.GaQuery;
import com.gooddata.modeling.model.SourceColumn;
import com.gooddata.modeling.model.SourceSchema;
import com.gooddata.processor.CliParams;
import com.gooddata.processor.Command;
import com.gooddata.processor.ProcessingContext;
import com.gooddata.util.FileUtil;
import com.google.gdata.client.ClientLoginAccountType;
import com.google.gdata.client.analytics.AnalyticsService;
import com.google.gdata.data.analytics.DataFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.SQLException;
/**
* GoodData Google Analytics Connector
*
* @author zd <zd@gooddata.com>
* @version 1.0
*/
public class GaConnector extends AbstractConnector implements Connector {
public static final String GA_DATE = "ga:date";
private static Logger l = Logger.getLogger(GaConnector.class);
private static final String APP_NAME = "gdc-ga-client";
private String googleAnalyticsUsername;
private String googleAnalyticsPassword;
private GaQuery googleAnalyticsQuery;
/**
* Creates a new Google Analytics Connector
* @param connectorBackend connector backend
*/
protected GaConnector(ConnectorBackend connectorBackend) {
super(connectorBackend);
}
/**
* Creates a new Google Analytics Connector
* @param connectorBackend connector backend
* @return a new instance of the GA connector
*
*/
public static GaConnector createConnector(ConnectorBackend connectorBackend) {
return new GaConnector(connectorBackend);
}
/**
* Saves a template of the config file
* @param name the new config file name
* @param configFileName the new config file name
* @param gQuery the Google Analytics query
* @throws com.gooddata.exception.InvalidArgumentException if there is a problem with arguments
* @throws IOException if there is a problem with writing the config file
*/
public static void saveConfigTemplate(String name, String configFileName, GaQuery gQuery)
throws IOException {
l.debug("Saving GA config template.");
String dims = gQuery.getDimensions();
String mtrs = gQuery.getMetrics();
SourceSchema s = SourceSchema.createSchema(name);
if(dims != null && dims.length() > 0) {
String[] dimensions = dims.split("\\|");
for(String dim : dimensions) {
// remove the "ga:"
if(dim != null && dim.length() > 3) {
String d= dim.substring(3);
if(GA_DATE.equals(dim)) {
SourceColumn sc = new SourceColumn(d,SourceColumn.LDM_TYPE_DATE, d);
sc.setFormat("yyyy-MM-dd");
s.addColumn(sc);
}
else {
SourceColumn sc = new SourceColumn(d,SourceColumn.LDM_TYPE_ATTRIBUTE, d);
s.addColumn(sc);
}
}
else {
l.debug("Invalid dimension name '" + dim + "'");
throw new InvalidArgumentException("Invalid dimension name '" + dim + "'");
}
}
}
else {
l.debug("Please specify Google Analytics dimensions separated by comma.");
throw new InvalidArgumentException("Please specify Google Analytics dimensions separated by comma.");
}
if(mtrs != null && mtrs.length() > 0) {
String[] metrics = mtrs.split("\\|");
for(String mtr : metrics) {
// remove the "ga:"
if(mtr != null && mtr.length() > 3) {
String m= mtr.substring(3);
SourceColumn sc = new SourceColumn(m,SourceColumn.LDM_TYPE_FACT, m);
s.addColumn(sc);
}
else {
l.debug("Invalid dimension name '" + mtr + "'");
throw new InvalidArgumentException("Invalid metric name '" + mtr + "'");
}
}
}
else {
l.debug("Please specify Google Analytics metrics separated by comma.");
throw new InvalidArgumentException("Please specify Google Analytics metrics separated by comma.");
}
s.writeConfig(new File(configFileName));
l.debug("Saved GA config template.");
}
/**
* {@inheritDoc}
*/
public void extract() throws IOException {
try {
AnalyticsService as = new AnalyticsService(APP_NAME);
as.setUserCredentials(getGoogleAnalyticsUsername(), getGoogleAnalyticsPassword(), ClientLoginAccountType.GOOGLE);
File dataFile = FileUtil.getTempFile();
GaQuery gaq = getGoogleAnalyticsQuery();
gaq.setMaxResults(5000);
int cnt = 1;
CSVWriter cw = new CSVWriter(new OutputStreamWriter(new FileOutputStream(dataFile), "utf-8"));
for(int startIndex = 1; cnt > 0; startIndex += cnt + 1) {
gaq.setStartIndex(startIndex);
DataFeed feed = as.getFeed(gaq.getUrl(), DataFeed.class);
l.debug("Retrieving GA data from index="+startIndex);
cnt = FeedDumper.dump(cw, feed);
l.debug("Retrieved "+cnt+" entries.");
}
cw.flush();
cw.close();
getConnectorBackend().extract(dataFile);
FileUtil.recursiveDelete(dataFile);
}
catch (AuthenticationException e) {
throw new InternalErrorException(e);
} catch (ServiceException e) {
throw new InternalErrorException(e);
}
}
/**
* Google Analytics username getter
* @return Google Analytics username
*/
public String getGoogleAnalyticsUsername() {
return googleAnalyticsUsername;
}
/**
* Google Analytics username setter
* @param googleAnalyticsUsername Google Analytics username
*/
public void setGoogleAnalyticsUsername(String googleAnalyticsUsername) {
this.googleAnalyticsUsername = googleAnalyticsUsername;
}
/**
* Google Analytics password getter
* @return Google Analytics password
*/
public String getGoogleAnalyticsPassword() {
return googleAnalyticsPassword;
}
/**
* Google Analytics password setter
* @param googleAnalyticsPassword Google Analytics password
*/
public void setGoogleAnalyticsPassword(String googleAnalyticsPassword) {
this.googleAnalyticsPassword = googleAnalyticsPassword;
}
/**
* Google Analytics query getter
* @return Google Analytics query
*/
public GaQuery getGoogleAnalyticsQuery() {
return googleAnalyticsQuery;
}
/**
* Google Analytics query setter
* @param googleAnalyticsQuery Google Analytics query
*/
public void setGoogleAnalyticsQuery(GaQuery googleAnalyticsQuery) {
this.googleAnalyticsQuery = googleAnalyticsQuery;
}
/**
* {@inheritDoc}
*/
public boolean processCommand(Command c, CliParams cli, ProcessingContext ctx) throws ProcessingException {
l.debug("Processing command "+c.getCommand());
try {
if(c.match("GenerateGoogleAnalyticsConfig")) {
generateGAConfig(c, cli, ctx);
}
else if(c.match("LoadGoogleAnalytics")) {
loadGA(c, cli, ctx);
}
else {
l.debug("No match passing the command "+c.getCommand()+" further.");
return super.processCommand(c, cli, ctx);
}
}
catch (IOException e) {
throw new ProcessingException(e);
}
l.debug("Processed command "+c.getCommand());
return true;
}
/**
* Loads new GA data command processor
* @param c command
* @param p command line arguments
* @param ctx current processing context
* @throws IOException in case of IO issues
*/
private void loadGA(Command c, CliParams p, ProcessingContext ctx) throws IOException {
GaQuery gq;
try {
gq = new GaQuery();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e.getMessage());
}
String configFile = c.getParamMandatory("configFile");
String usr = c.getParamMandatory("username");
String psw = c.getParamMandatory("password");
String id = c.getParamMandatory("profileId");
File conf = FileUtil.getFile(configFile);
initSchema(conf.getAbsolutePath());
gq.setIds(id);
setGoogleAnalyticsUsername(usr);
setGoogleAnalyticsPassword(psw);
setGoogleAnalyticsQuery(gq);
gq.setDimensions(c.getParamMandatory("dimensions").replace("|",","));
gq.setMetrics(c.getParamMandatory("metrics").replace("|",","));
gq.setStartDate(c.getParamMandatory("startDate"));
gq.setEndDate(c.getParamMandatory("endDate"));
if(c.checkParam("filters"))
gq.setFilters(c.getParam("filters"));
// sets the current connector
ctx.setConnector(this);
setProjectId(ctx);
}
/**
* Generate GA config command processor
* @param c command
* @param p command line arguments
* @param ctx current processing context
* @throws IOException in case of IO issues
*/
private void generateGAConfig(Command c, CliParams p, ProcessingContext ctx) throws IOException {
String configFile = c.getParamMandatory("configFile");
String name = c.getParamMandatory("name");
String dimensions = c.getParamMandatory("dimensions");
String metrics = c.getParamMandatory("metrics");
GaQuery gq;
try {
gq = new GaQuery();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e.getMessage());
}
gq.setDimensions(dimensions);
gq.setMetrics(metrics);
GaConnector.saveConfigTemplate(name, configFile, gq);
}
}
|
package jp.pushmestudio.kcuc.model;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import jp.pushmestudio.kcuc.controller.KCData;
import jp.pushmestudio.kcuc.util.Result;
/**
* APIsleep setUpsetUp1+
* tearDowntearDown0.5
*/
@RunWith(Enclosed.class)
public class KCDataTest {
static KCData data = new KCData();
public static class {
static String userId = "tkhm";
static String prodId = "SSTPQH_1.0.0";
static String hrefKey1 = "SSTPQH_1.0.0/com.ibm.cloudant.local.install.doc/topics/clinstall_planning_install_location.html";
static String hrefKey2 = "SS5RWK_3.5.0/com.ibm.discovery.es.nav.doc/iiypofnv_prodover_cont.htm?sc=_latest";
@BeforeClass
public static void setUp() {
try {
// API
data.registerSubscribedPage(userId, hrefKey1);
Thread.sleep(1000);
data.registerSubscribedPage(userId, hrefKey2);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@AfterClass
public static void tearDown() {
// API
try {
Thread.sleep(500);
data.deleteSubscribedPage(userId, hrefKey1);
Thread.sleep(500);
data.deleteSubscribedPage(userId, hrefKey2);
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void 1() {
// execute
Result checkResult = data.checkUpdateByPage(hrefKey2);
// verify
List<UserInfo> userList = ((ResultUserList) checkResult).getSubscribers();
boolean actual = userList.size() >= 1;
assertTrue(actual);
}
@Test
public void 2() {
// execute
Result checkResult = data.checkUpdateByUser(userId);
// verify
List<SubscribedPage> pageList = ((ResultPageList) checkResult).getSubscribedPages();
boolean actual = pageList.size() >= 2;
assertTrue(actual);
}
@Test
public void IDID() {
// execute
Result checkResult = data.checkUpdateByUser(userId, prodId);
// verify
List<SubscribedPage> pageList = ((ResultPageList) checkResult).getSubscribedPages();
for (SubscribedPage page : pageList) {
String actual = page.getProdId();
assertThat(actual, is(prodId));
}
}
}
public static class {
static String userId = "tkhm";
static String prodId = "SSTPQH_1.0.0";
static String hrefKey1 = "SSTPQH_1.0.0/com.ibm.cloudant.local.install.doc/topics/clinstall_planning_install_location.html";
static String hrefKey2 = "SSTPQH_1.0.0/com.ibm.cloudant.local.install.doc/topics/clinstall_tuning_automatic_compactor.html";
static Result preResultPages;
static List<SubscribedPage> prePageList;
static Result preResultProducts;
static Map<String, String> preProductMap;
static Result checkResultPages;
@BeforeClass
public static void setUp() {
try {
// API
data.cancelSubscribedProduct(userId, prodId);
Thread.sleep(1000);
preResultPages = data.checkUpdateByUser(userId);
prePageList = ((ResultPageList) preResultPages).getSubscribedPages();
preResultProducts = data.getSubscribedProductList(userId);
preProductMap = ((ResultProductList) preResultProducts).getSubscribedProducts();
Thread.sleep(1000);
// execute
checkResultPages = data.registerSubscribedPage(userId, hrefKey1);
Thread.sleep(1000);
checkResultPages = data.registerSubscribedPage(userId, hrefKey2);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@AfterClass
public static void tearDown() {
try {
// API
Thread.sleep(500);
data.cancelSubscribedProduct(userId, prodId);
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void 2() {
// verify
List<SubscribedPage> pageList = ((ResultPageList) checkResultPages).getSubscribedPages();
int actual = pageList.size();
assertThat(actual, is(prePageList.size() + 2));
}
@Test
public void 21() {
// execute
Result gotResult = data.getSubscribedProductList(userId);
Map<String, String> productMap = ((ResultProductList) gotResult).getSubscribedProducts();
// verify
final int expectedSize = preProductMap.size() + 1;
final int actualSize = productMap.size();
assertThat(actualSize, is(expectedSize));
}
}
public static class {
static String userId = "meltest";
static String hrefKey = "SSYRPW_9.0.1/UsingVerseMobile.html";
static Result preResult;
static List<SubscribedPage> prePageList;
@BeforeClass
public static void setUp() {
try {
// API
data.registerSubscribedPage(userId, hrefKey);
preResult = data.checkUpdateByUser(userId);
prePageList = ((ResultPageList) preResult).getSubscribedPages();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@AfterClass
public static void tearDown() {
// API
try {
Thread.sleep(500);
data.deleteSubscribedPage(userId, hrefKey);
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void 1() {
// execute
Result checkResult = data.deleteSubscribedPage(userId, hrefKey);
// verify
List<SubscribedPage> pageList = ((ResultPageList) checkResult).getSubscribedPages();
int actual = pageList.size();
assertThat(actual, is(prePageList.size() - 1));
}
}
public static class {
static String userId = "meltest";
static String prodId = "SSTPQH_1.0.0";
static String hrefKey1 = "SSTPQH_1.0.0/com.ibm.cloudant.local.install.doc/topics/clinstall_planning_install_location.html";
static String hrefKey2 = "SSTPQH_1.0.0/com.ibm.cloudant.local.install.doc/topics/clinstall_tuning_automatic_compactor.html";
static Result preResultPages;
static List<SubscribedPage> prePageList;
static Result preResultProducts;
static Map<String, String> preProductMap;
static Result checkResultPages;
@BeforeClass
public static void setUp() {
try {
// API
data.registerSubscribedPage(userId, hrefKey1);
Thread.sleep(1000);
data.registerSubscribedPage(userId, hrefKey2);
Thread.sleep(1000);
preResultPages = data.checkUpdateByUser(userId);
prePageList = ((ResultPageList) preResultPages).getSubscribedPages();
preResultProducts = data.getSubscribedProductList(userId);
preProductMap = ((ResultProductList) preResultProducts).getSubscribedProducts();
Thread.sleep(1000);
// execute
data.cancelSubscribedProduct(userId, prodId);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void 2() {
// verify
Result checkResult = data.checkUpdateByUser(userId);
List<SubscribedPage> pageList = ((ResultPageList) checkResult).getSubscribedPages();
int actual = pageList.size();
assertThat(actual, is(prePageList.size() - 2));
}
@Test
public void () {
// verify
Result checkResult = data.getSubscribedProductList(userId);
Map<String, String> productMap = ((ResultProductList) checkResult).getSubscribedProducts();
int actual = productMap.size();
assertThat(actual, is(preProductMap.size() - 1));
assertNull(productMap.get(prodId));
}
}
public static class {
static String searchQuery = "IBM Verse";
static int offset = 5;
static int limit = 15;
static Result searchResult;
@BeforeClass
public static void setUp() {
// execute
searchResult = data.searchPages(searchQuery, "", "", offset, limit, "", "");
}
@Test
public void 1() {
// verify
int actualTopicSize = ((ResultSearchList) searchResult).getTopics().size();
assertTrue(actualTopicSize > 0);
}
@Test
public void () {
// verify
int expectedOffset = offset;
int actualOffset = ((ResultSearchList) searchResult).getOffset();
assertThat(actualOffset, is(expectedOffset)); // offset
}
@Test
public void 1() {
// verify
int expectedNext = offset + limit;
int actualNext = ((ResultSearchList) searchResult).getNext();
assertThat(actualNext, is(expectedNext)); // next
}
}
}
|
package org.xtreemfs.common.config;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.StringTokenizer;
import org.xtreemfs.common.uuids.ServiceUUID;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
import org.xtreemfs.foundation.pbrpc.Schemes;
public class ServiceConfig extends Config {
final private static Category[] debugCategoryDefault = { Category.all };
public static enum Parameter {
/*
* general configuration parameter
*/
DEBUG_LEVEL("debug.level", 6, Integer.class, false),
DEBUG_CATEGORIES("debug.categories", debugCategoryDefault, Category[].class, false),
DIRECTORY_SERVICE("dir_service.host", null, InetSocketAddress.class, true),
DIRECTORY_SERVICE0("dir_service.0.host", null, InetSocketAddress.class, false),
DIRECTORY_SERVICE1("dir_service.1.host", null, InetSocketAddress.class, false),
DIRECTORY_SERVICE2("dir_service.2.host", null, InetSocketAddress.class, false),
DIRECTORY_SERVICE3("dir_service.3.host", null, InetSocketAddress.class, false),
DIRECTORY_SERVICE4("dir_service.4.host", null, InetSocketAddress.class, false),
PORT("listen.port", null, Integer.class, true),
HTTP_PORT("http_port", null, Integer.class, true),
LISTEN_ADDRESS("listen.address", null, InetAddress.class, false),
USE_SSL("ssl.enabled", false, Boolean.class, false),
SERVICE_CREDS_FILE("ssl.service_creds", null, String.class, false ),
SERVICE_CREDS_PASSPHRASE("ssl.service_creds.pw", null, String.class, false),
SERVICE_CREDS_CONTAINER("ssl.service_creds.container", null, String.class, false),
TRUSTED_CERTS_FILE("ssl.trusted_certs", null, String.class, false),
TRUSTED_CERTS_CONTAINER("ssl.trusted_certs.container", null, String.class, false),
TRUSTED_CERTS_PASSPHRASE("ssl.trusted_certs.pw", null, String.class, false),
TRUST_MANAGER("ssl.trust_manager", "", String.class, false),
GEO_COORDINATES("geographic_coordinates", "", String.class, false ),
ADMIN_PASSWORD("admin_password", "", String.class, false),
HOSTNAME("hostname", "", String.class, false ),
USE_GRID_SSL_MODE("ssl.grid_ssl", false, Boolean.class, false),
WAIT_FOR_DIR("startup.wait_for_dir", 30, Integer.class, false),
POLICY_DIR("policy_dir", "/etc/xos/xtreemfs/policies/", String.class, false),
USE_SNMP("snmp.enabled", false, Boolean.class, false),
SNMP_ADDRESS("snmp.address", null, InetAddress.class, false),
SNMP_PORT("snmp.port", null, Integer.class, false),
SNMP_ACL("snmp.aclfile", null, String.class, false),
FAILOVER_MAX_RETRIES("failover.retries", 15, Integer.class, false),
FAILOVER_WAIT("failover.wait_ms", 15 * 1000, Integer.class, false),
MAX_CLIENT_Q("max_client_queue", 100, Integer.class, false),
MAX_REQUEST_QUEUE_LENGTH("max_requests_queue_length", 1000, Integer.class, false),
USE_MULTIHOMING("multihoming.enabled", false, Boolean.class, false),
USE_RENEWAL_SIGNAL("multihoming.renewal_signal", false, Boolean.class, false ),
/*
* DIR specific configuration parameter
*/
AUTODISCOVER_ENABLED("discover", true, Boolean.class, false),
MONITORING_ENABLED("monitoring.enabled", false, Boolean.class, false ),
ADMIN_EMAIL("monitoring.email.receiver", "", String.class, false),
SENDER_ADDRESS("monitoring.email.sender", "XtreemFS DIR monitoring <dir@localhost>", String.class, false),
MAX_WARNINGS("monitoring.max_warnings", 1, Integer.class, false),
SENDMAIL_BIN("monitoring.email.programm", "/usr/sbin/sendmail", String.class, false),
TIMEOUT_SECONDS("monitoring.service_timeout_s", 5 * 60, Integer.class, false),
VIVALDI_MAX_CLIENTS("vivaldi.max_clients", 32, Integer.class, false),
VIVALDI_CLIENT_TIMEOUT("vivaldi.client_timeout", 600000, Integer.class, false), // default: twice the recalculation interval
/*
* MRC specific configuration parameter
*/
UUID("uuid", null, ServiceUUID.class, true),
LOCAL_CLOCK_RENEW("local_clock_renewal", null, Integer.class, true),
REMOTE_TIME_SYNC("remote_time_sync", null, Integer.class, true),
OSD_CHECK_INTERVAL("osd_check_interval", null, Integer.class, true),
NOATIME("no_atime", null, Boolean.class, true),
AUTHENTICATION_PROVIDER("authentication_provider", null, String.class, true),
CAPABILITY_SECRET("capability_secret", null, String.class, true),
CAPABILITY_TIMEOUT("capability_timeout", 600, Integer.class, false),
RENEW_TIMED_OUT_CAPS("renew_to_caps", false, Boolean.class, false),
/*
* OSD specific configuration parameter
*/
OBJECT_DIR("object_dir", null, String.class, true),
REPORT_FREE_SPACE("report_free_space", null, Boolean.class, true),
CHECKSUM_ENABLED("checksums.enabled", false, Boolean.class, false),
CHECKSUM_PROVIDER("checksums.algorithm", null, String.class, false),
STORAGE_LAYOUT("storage_layout", "HashStorageLayout", String.class, false),
IGNORE_CAPABILITIES("ignore_capabilities", false, Boolean.class, false),
/** Maximum assumed drift between two server clocks. If the drift is higher, the system may not function properly. */
FLEASE_DMAX_MS("flease.dmax_ms", 1000, Integer.class, false),
FLEASE_LEASE_TIMEOUT_MS("flease.lease_timeout_ms", 14000, Integer.class, false),
/** Message timeout. Maximum allowed in-transit time for a Flease message. */
FLEASE_MESSAGE_TO_MS("flease.message_to_ms", 500, Integer.class, false),
FLEASE_RETRIES("flease.retries", 3, Integer.class, false),
SOCKET_SEND_BUFFER_SIZE("socket.send_buffer_size", -1, Integer.class, false),
SOCKET_RECEIVE_BUFFER_SIZE("socket.recv_buffer_size", -1, Integer.class, false),
VIVALDI_RECALCULATION_INTERVAL_IN_MS("vivaldi.recalculation_interval_ms", 300000, Integer.class, false),
VIVALDI_RECALCULATION_EPSILON_IN_MS("vivaldi.recalculation_epsilon_ms", 30000, Integer.class, false),
VIVALDI_ITERATIONS_BEFORE_UPDATING("vivaldi.iterations_before_updating", 12, Integer.class, false),
VIVALDI_MAX_RETRIES_FOR_A_REQUEST("vivaldi.max_retries_for_a_request", 2, Integer.class, false),
VIVALDI_MAX_REQUEST_TIMEOUT_IN_MS("vivaldi.max_request_timeout_ms", 10000, Integer.class, false),
VIVALDI_TIMER_INTERVAL_IN_MS("vivaldi.timer_interval_ms", 60000, Integer.class, false),
STORAGE_THREADS("storage_threads", 1, Integer.class, false),
/*
* Benchmark specific configuration parameter
*/
BASEFILE_SIZE_IN_BYTES("basefilesize_in_bytes", 3221225472L, Long.class, false), // 3221225472L = 3 GiB
FILESIZE("filesize", 4096, Integer.class, false), // 4096 = 4 KiB
USERNAME("username", "benchmark", String.class, false),
GROUP("group", "benchmark", String.class, false),
OSD_SELECTION_POLICIES("osd_selection_policies", "", String.class, false),
CHUNK_SIZE_IN_BYTES("chunk_size_in_bytes", 131072, Integer.class, false), // 131072 = 128 KiB
STRIPE_SIZE_IN_BYTES("stripe_size_in_bytes", 131072, Integer.class, false), // 131072 = 128 KiB
STRIPE_SIZE_SET("stripe_size_set", false, Boolean.class, false),
STRIPE_WIDTH("stripe_width", 1, Integer.class, false),
STRIPE_WIDTH_SET("stripe_width_set", false, Boolean.class, false),
NO_CLEANUP("no_cleanup", false, Boolean.class, false),
NO_CLEANUP_VOLUMES("no_cleanup_volumes", false, Boolean.class, false),
NO_CLEANUP_BASEFILE("no_cleanup_basefile", false, Boolean.class, false),
OSD_CLEANUP("osd_cleanup", false, Boolean.class, false);
Parameter(String propString, Object defaultValue, Class propClass, Boolean req) {
propertyString = propString;
this.defaultValue = defaultValue;
propertyClass = propClass;
required = req;
}
/**
* number of values the enumeration contains
*/
private static final int size = Parameter.values().length;
/**
* String representation of the parameter in .property file
*/
private final String propertyString;
/**
* Class of the parameter. Used for deserilization. Note: If you add a new Class type, don't forget to
* update the ServiceConfig(HashMap <String,String>) constructor
*/
private final Class propertyClass;
/**
* Default parameter which will be used if there is neither a Parameter in the properties file nor in
* the DIR
*/
private final Object defaultValue;
/**
* True if this is a required parameter. False otherwise.
*/
private final Boolean required;
public String getPropertyString() {
return propertyString;
}
public Object getDefaultValue() {
return defaultValue;
}
public Class getPropertyClass() {
return propertyClass;
}
public static int getSize() {
return size;
}
public Boolean isRequired() {
return required;
}
public Boolean isOptional() {
return !required;
}
public static Parameter getParameterFromString(String s) throws RuntimeException {
for (Parameter parm : Parameter.values()) {
if (s.equals(parm.getPropertyString()))
return parm;
}
throw new RuntimeException("Configuration parameter " + s + " doesn't exist!");
}
}
/**
* Parameter which are required to connect to the DIR.
*
*/
private final Parameter[] connectionParameter = {
Parameter.DEBUG_CATEGORIES,
Parameter.DEBUG_LEVEL,
Parameter.HOSTNAME,
Parameter.DIRECTORY_SERVICE,
Parameter.WAIT_FOR_DIR,
Parameter.PORT,
Parameter.USE_SSL,
Parameter.UUID
};
/**
* Checks if there are all required configuration parameter to initialize a connection to the DIR and
* request the rest of the configuration
*
* @return {@link Boolean}
*/
public Boolean isInitializable() {
for (Parameter param : connectionParameter) {
if (parameter.get(param) == null) {
throw new RuntimeException("property '" + param.getPropertyString()
+ "' is required but was not found");
}
}
checkSSLConfiguration();
return true;
}
public Parameter[] getConnectionParameter() {
return this.connectionParameter;
}
/**
* reads only the given Parameters from the config file
*
* @throws IOException
*/
public void readParameters(Parameter[] params) throws IOException {
for (Parameter param : params) {
parameter.put(param, readParameter(param));
}
setDefaults(params);
}
protected EnumMap<Parameter, Object> parameter = new EnumMap<Parameter, Object>(
Parameter.class);
public static final String OSD_CUSTOM_PROPERTY_PREFIX = "config.";
public ServiceConfig() {
super();
}
public ServiceConfig(Properties prop) {
super(prop);
}
public ServiceConfig(String filename) throws IOException {
super(filename);
}
public ServiceConfig(HashMap<String, String> hm) {
super();
/*
* Create a configuration from String Key-Values of a HashMap
*/
for (Entry<String, String> entry : hm.entrySet()) {
// ignore custom configuration properties for OSDs here
if (entry.getKey().startsWith(OSD_CUSTOM_PROPERTY_PREFIX)) {
continue;
}
Parameter param = null;
try {
param = Parameter.getParameterFromString(entry.getKey());
} catch (RuntimeException e) {
e.printStackTrace();
}
/* Integer values */
if (Integer.class == param.getPropertyClass()) {
parameter.put(param, Integer.parseInt(entry.getValue()));
}
/* Long values */
if (Long.class == param.getPropertyClass()) {
parameter.put(param, Long.parseLong(entry.getValue()));
}
/* String values */
if (String.class == param.getPropertyClass()) {
parameter.put(param, entry.getValue());
}
/* Boolean values */
if (Boolean.class == param.getPropertyClass()) {
parameter.put(param, Boolean.valueOf(entry.getValue()));
}
/* ServiceUUID values */
if (ServiceUUID.class == param.getPropertyClass()) {
parameter.put(param, new ServiceUUID(entry.getValue()));
}
/* InetAddress values */
if (InetAddress.class == param.getPropertyClass()) {
InetAddress inetAddr = null;
try {
inetAddr = InetAddress.getByName(entry.getValue().substring(
entry.getValue().indexOf('/') + 1));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parameter.put(param, inetAddr);
}
/* InetSocketAddress values */
if (InetSocketAddress.class == param.getPropertyClass()) {
/*
* Get a host and port of a string like 'hostname/192.168.2.141:36365' and create a
* InetSocketAddress
*/
String host = entry.getValue().substring(0, entry.getValue().indexOf("/"));
String port = entry.getValue().substring(entry.getValue().lastIndexOf(":") + 1);
InetSocketAddress isa = new InetSocketAddress(host, Integer.parseInt(port));
parameter.put(param, isa);
}
/* Category[] values */
if (Category[].class == param.getPropertyClass()) {
StringTokenizer stk = new StringTokenizer(entry.getValue(), ", ");
Category[] catArray = new Category[stk.countTokens()];
int count = 0;
while (stk.hasMoreElements()) {
catArray[count] = Category.valueOf(stk.nextToken());
count++;
}
parameter.put(param, catArray);
}
}
}
/**
* Merges a second configuration in this one. Only required parameters which aren't set will be used from
* the new configuration.
*
* @param conf
*/
public void mergeConfig(ServiceConfig conf) {
for (Entry<Parameter, Object> entry : conf.parameter.entrySet()) {
if (entry.getKey().isRequired() && parameter.get(entry.getKey()) == null) {
parameter.put(entry.getKey(), entry.getValue());
}
}
}
/**
* Set the default value for a specific Parameter
*
* @param param
* - {@link Parameter}
*/
public void setDefaults(Parameter param) {
if (parameter.get(param) == null) {
parameter.put(param, param.getDefaultValue());
}
}
/**
* Set the default values for the parameter in p
*
* @param p
*/
public void setDefaults(Parameter[] p) {
for (Parameter parm : p) {
if (parm.isOptional() && parameter.get(parm) == null) {
parameter.put(parm, parm.getDefaultValue());
}
}
}
protected int readDebugLevel() {
String level = props.getProperty("debug.level");
if (level == null)
return Logging.LEVEL_INFO;
else {
level = level.trim().toUpperCase();
if (level.equals("EMERG")) {
return Logging.LEVEL_EMERG;
} else if (level.equals("ALERT")) {
return Logging.LEVEL_ALERT;
} else if (level.equals("CRIT")) {
return Logging.LEVEL_CRIT;
} else if (level.equals("ERR")) {
return Logging.LEVEL_ERROR;
} else if (level.equals("WARNING")) {
return Logging.LEVEL_WARN;
} else if (level.equals("NOTICE")) {
return Logging.LEVEL_NOTICE;
} else if (level.equals("INFO")) {
return Logging.LEVEL_INFO;
} else if (level.equals("DEBUG")) {
return Logging.LEVEL_DEBUG;
} else {
try {
int levelInt = Integer.valueOf(level);
return levelInt;
} catch (NumberFormatException ex) {
throw new RuntimeException("'" + level + "' is not a valid level name nor an integer");
}
}
}
}
/**
* Read configuration parameter from property file and return an Object of the value if the parameter was
* set. Else return null.
*
* @param param the parameter
*
* @return Object
*/
protected Object readParameter(Parameter param) {
String tmpString = props.getProperty(param.getPropertyString());
if (tmpString == null) {
return null;
}
// Integer values
if (Integer.class == param.getPropertyClass()) {
return Integer.parseInt(tmpString.trim());
}
/* Long values */
if (Long.class == param.getPropertyClass()) {
return(Long.parseLong(tmpString.trim()));
}
// Boolean values
if (Boolean.class == param.getPropertyClass()) {
return Boolean.parseBoolean(tmpString.trim());
}
// String values
if (String.class == param.getPropertyClass()) {
return tmpString.trim();
}
// ServiceUUID values
if (ServiceUUID.class == param.getPropertyClass()) {
return new ServiceUUID(tmpString);
}
// InetAddress values
if (InetAddress.class == param.getPropertyClass()) {
InetAddress iAddr = null;
try {
iAddr = InetAddress.getByName(tmpString);
} catch (Exception e) {
e.printStackTrace();
}
return iAddr;
}
// InetSocketAddress values
if (InetSocketAddress.class == param.getPropertyClass()) {
// assumes that the parameter in the property file like
// "foobar.host" and "foobar.port" if you
// want to read a InetSocketAddress
return readRequiredInetAddr(param.getPropertyString(),
param.getPropertyString().replaceAll("host", "port"));
}
// Category[] values
if (Category[].class == param.getPropertyClass()) {
return readCategories(param.getPropertyString());
}
return null;
}
protected Category[] readCategories(String property) {
String tmp = this.readOptionalString(property, "");
StringTokenizer st = new StringTokenizer(tmp, " \t,");
List<Category> cats = new LinkedList<Category>();
while (st.hasMoreTokens()) {
String token = st.nextToken();
try {
cats.add(Category.valueOf(token));
} catch (IllegalArgumentException exc) {
System.err.println("invalid logging category: " + token);
}
}
if (cats.size() == 0)
cats.add(Category.all);
return cats.toArray(new Category[cats.size()]);
}
public HashMap<String, String> toHashMap() {
HashMap<String, String> hm = new HashMap<String, String>();
for (Parameter param : Parameter.values()) {
if (parameter.get(param) != null) {
if (Category[].class == param.getPropertyClass()) {
Category[] debugCategories = (Category[]) parameter.get(param);
String putString = "";
boolean firstValue = true;
for (Category cat : debugCategories) {
if (firstValue) {
putString = putString + cat.toString();
firstValue = false;
} else {
putString += ", " + cat.toString();
}
}
hm.put(param.getPropertyString(), putString);
} else {
hm.put(param.getPropertyString(), parameter.get(param).toString());
}
}
}
return hm;
}
public int getDebugLevel() {
return (Integer) parameter.get(Parameter.DEBUG_LEVEL);
}
public Category[] getDebugCategories() {
return (Category[]) parameter.get(Parameter.DEBUG_CATEGORIES);
}
public int getPort() {
return (Integer) parameter.get(Parameter.PORT);
}
public int getHttpPort() {
return (Integer) parameter.get(Parameter.HTTP_PORT);
}
public InetAddress getAddress() {
return (InetAddress) parameter.get(Parameter.LISTEN_ADDRESS);
}
public boolean isUsingSSL() {
return (Boolean) parameter.get(Parameter.USE_SSL);
}
public String getServiceCredsContainer() {
return (String) parameter.get(Parameter.SERVICE_CREDS_CONTAINER);
}
public String getServiceCredsFile() {
return (String) parameter.get(Parameter.SERVICE_CREDS_FILE);
}
public String getServiceCredsPassphrase() {
return (String) parameter.get(Parameter.SERVICE_CREDS_PASSPHRASE);
}
public String getTrustedCertsContainer() {
return (String) parameter.get(Parameter.TRUSTED_CERTS_CONTAINER);
}
public String getTrustedCertsFile() {
return (String) parameter.get(Parameter.TRUSTED_CERTS_FILE);
}
public String getTrustedCertsPassphrase() {
return (String) parameter.get(Parameter.TRUSTED_CERTS_PASSPHRASE);
}
public String getTrustManager() {
return (String) parameter.get(Parameter.TRUST_MANAGER);
}
public String getGeoCoordinates() {
return (String) parameter.get(Parameter.GEO_COORDINATES);
}
public void setGeoCoordinates(String geoCoordinates) {
parameter.put(Parameter.GEO_COORDINATES, geoCoordinates);
}
public String getAdminPassword() {
return (String) parameter.get(Parameter.ADMIN_PASSWORD);
}
public String getHostName() {
return (String) parameter.get(Parameter.HOSTNAME);
}
public ServiceUUID getUUID() {
return (ServiceUUID) parameter.get(Parameter.UUID);
}
/**
* @return the useFakeSSLmodeport
*/
public boolean isGRIDSSLmode() {
return parameter.get(Parameter.USE_GRID_SSL_MODE) != null
&& (Boolean) parameter.get(Parameter.USE_GRID_SSL_MODE);
}
public int getWaitForDIR() {
return (Integer) parameter.get(Parameter.WAIT_FOR_DIR);
}
public String getURLScheme() {
if (isUsingSSL()) {
if (isGRIDSSLmode()) {
return Schemes.SCHEME_PBRPCG;
} else {
return Schemes.SCHEME_PBRPCS;
}
}
return Schemes.SCHEME_PBRPC;
}
public String getPolicyDir() {
return (String) parameter.get(Parameter.POLICY_DIR);
}
public Boolean isUsingSnmp() {
return (Boolean) parameter.get(Parameter.USE_SNMP);
}
public InetAddress getSnmpAddress() {
return (InetAddress) parameter.get(Parameter.SNMP_ADDRESS);
}
public Integer getSnmpPort() {
return (Integer) parameter.get(Parameter.SNMP_PORT);
}
public String getSnmpACLFile() {
return (String) parameter.get(Parameter.SNMP_ACL);
}
public Integer getFailoverMaxRetries() {
return (Integer) parameter.get(Parameter.FAILOVER_MAX_RETRIES);
}
public Integer getFailoverWait() {
return (Integer) parameter.get(Parameter.FAILOVER_WAIT);
}
public InetSocketAddress getDirectoryService() {
return (InetSocketAddress) parameter.get(Parameter.DIRECTORY_SERVICE);
}
public InetSocketAddress[] getDirectoryServices() {
List<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>();
addresses.add((InetSocketAddress) parameter.get(Parameter.DIRECTORY_SERVICE));
if (parameter.get(Parameter.DIRECTORY_SERVICE0) != null) {
addresses.add((InetSocketAddress) parameter.get(Parameter.DIRECTORY_SERVICE0));
}
if (parameter.get(Parameter.DIRECTORY_SERVICE1) != null) {
addresses.add((InetSocketAddress) parameter.get(Parameter.DIRECTORY_SERVICE1));
}
if (parameter.get(Parameter.DIRECTORY_SERVICE2) != null) {
addresses.add((InetSocketAddress) parameter.get(Parameter.DIRECTORY_SERVICE2));
}
if (parameter.get(Parameter.DIRECTORY_SERVICE3) != null) {
addresses.add((InetSocketAddress) parameter.get(Parameter.DIRECTORY_SERVICE3));
}
if (parameter.get(Parameter.DIRECTORY_SERVICE4) != null) {
addresses.add((InetSocketAddress) parameter.get(Parameter.DIRECTORY_SERVICE4));
}
return addresses.toArray(new InetSocketAddress[0]);
}
public void setDirectoryService(InetSocketAddress addr) {
parameter.put(Parameter.DIRECTORY_SERVICE, addr);
}
/**
* Checks if the SSL Configuration is valid. If not throws a {@link RuntimeException}.
*
* @throws RuntimeException
*/
public void checkSSLConfiguration() {
Parameter[] sslRelatedParameter = { Parameter.SERVICE_CREDS_CONTAINER, Parameter.SERVICE_CREDS_FILE,
Parameter.SERVICE_CREDS_PASSPHRASE, Parameter.TRUSTED_CERTS_CONTAINER,
Parameter.TRUSTED_CERTS_FILE, Parameter.TRUSTED_CERTS_PASSPHRASE };
if (isUsingSSL() == true) {
for (Parameter param : sslRelatedParameter) {
if (parameter.get(param) == null) {
throw new RuntimeException("for SSL " + param.getPropertyString() + " must be set!");
}
}
} else {
if (parameter.get(Parameter.USE_GRID_SSL_MODE) != null) {
if (isGRIDSSLmode()) {
throw new RuntimeException(
"ssl must be enabled to use the grid_ssl mode. Please make sure to set ssl.enabled = true and to configure all SSL options.");
}
}
}
}
/**
* Checks if the multihoming configuration is valid. If not throws a {@link RuntimeException}.
*
* @throws RuntimeException
*/
protected void checkMultihomingConfiguration() {
if (isUsingMultihoming() && getAddress() != null) {
throw new RuntimeException(ServiceConfig.Parameter.USE_MULTIHOMING.getPropertyString() + " and "
+ ServiceConfig.Parameter.LISTEN_ADDRESS.getPropertyString() + " parameters are incompatible.");
}
}
protected void checkConfig(Parameter[] params) {
for (Parameter param : params) {
if (param.isRequired() && parameter.get(param) == null) {
throw new RuntimeException("property '" + param.getPropertyString()
+ "' is required but was not found");
}
}
this.checkSSLConfiguration();
}
public boolean isUsingRenewalSignal() {
return (Boolean) parameter.get(Parameter.USE_RENEWAL_SIGNAL);
}
public boolean isUsingMultihoming() {
return (Boolean) parameter.get(Parameter.USE_MULTIHOMING);
}
}
|
package liquibase.diff;
import liquibase.database.Database;
import liquibase.diff.compare.CompareControl;
import liquibase.diff.compare.DatabaseObjectComparatorFactory;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.DataType;
import java.math.BigDecimal;
import java.util.*;
public class ObjectDifferences {
private CompareControl compareControl;
private HashMap<String, Difference> differences = new HashMap<String, Difference>();
public ObjectDifferences(CompareControl compareControl) {
this.compareControl = compareControl;
}
public Set<Difference> getDifferences() {
return Collections.unmodifiableSet(new TreeSet<Difference>(differences.values()));
}
public Difference getDifference(String field) {
return differences.get(field);
}
public boolean isDifferent(String field) {
return differences.containsKey(field);
}
public ObjectDifferences addDifference(String changedField, Object referenceValue, Object compareToValue) {
this.differences.put(changedField, new Difference(changedField, referenceValue, compareToValue));
return this;
}
public ObjectDifferences addDifference(String message, String changedField, Object referenceValue, Object compareToValue) {
this.differences.put(changedField, new Difference(message, changedField, referenceValue, compareToValue));
return this;
}
public boolean hasDifferences() {
return differences.size() > 0;
}
public void compare(String attribute, DatabaseObject referenceObject, DatabaseObject compareToObject, CompareFunction compareFunction) {
compare(null, attribute, referenceObject, compareToObject, compareFunction);
}
public void compare(String message, String attribute, DatabaseObject referenceObject, DatabaseObject compareToObject, CompareFunction compareFunction) {
if (compareControl.isSuppressedField(referenceObject.getClass(), attribute)) {
return;
}
Object referenceValue = referenceObject.getAttribute(attribute, Object.class);
Object compareValue = compareToObject.getAttribute(attribute, Object.class);
boolean different;
if (referenceValue == null && compareValue == null) {
different = false;
} else if ((referenceValue == null && compareValue != null) || (referenceValue != null && compareValue == null)) {
different = true;
} else {
different = !compareFunction.areEqual(referenceValue, compareValue);
}
if (different) {
addDifference(message, attribute, referenceValue, compareValue);
}
}
public boolean removeDifference(String attribute) {
return differences.remove(attribute) != null;
}
public interface CompareFunction {
public boolean areEqual(Object referenceValue, Object compareToValue);
}
public static class StandardCompareFunction implements CompareFunction {
private Database accordingTo;
public StandardCompareFunction(Database accordingTo) {
this.accordingTo = accordingTo;
}
@Override
public boolean areEqual(Object referenceValue, Object compareToValue) {
if (referenceValue == null && compareToValue == null) {
return true;
}
if (referenceValue == null || compareToValue == null) {
return false;
}
if (referenceValue instanceof DatabaseObject && compareToValue instanceof DatabaseObject) {
return DatabaseObjectComparatorFactory.getInstance().isSameObject((DatabaseObject) referenceValue, (DatabaseObject) compareToValue, accordingTo);
} else {
if ((referenceValue instanceof Number) && (compareToValue instanceof Number)
&& !referenceValue.getClass().equals(compareToValue.getClass())) { //standardize on a common number type
referenceValue = new BigDecimal(referenceValue.toString());
compareToValue = new BigDecimal(compareToValue.toString());
}
return referenceValue.equals(compareToValue);
}
}
}
public static class ToStringCompareFunction implements CompareFunction {
private boolean caseSensitive;
public ToStringCompareFunction(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
@Override
public boolean areEqual(Object referenceValue, Object compareToValue) {
if (referenceValue == null && compareToValue == null) {
return true;
}
if (referenceValue == null || compareToValue == null) {
return false;
}
if (caseSensitive) {
return referenceValue.toString().equals(compareToValue.toString());
} else {
return referenceValue.toString().equalsIgnoreCase(compareToValue.toString());
}
}
}
public static class DatabaseObjectNameCompareFunction implements CompareFunction {
private final Database accordingTo;
private Class<? extends DatabaseObject> type;
public DatabaseObjectNameCompareFunction(Class<? extends DatabaseObject> type, Database accordingTo) {
this.type = type;
this.accordingTo = accordingTo;
}
@Override
public boolean areEqual(Object referenceValue, Object compareToValue) {
if (referenceValue instanceof Collection) {
if (((Collection) referenceValue).size() != ((Collection) compareToValue).size()) {
return false;
} else {
Iterator referenceIterator = ((Collection) referenceValue).iterator();
Iterator compareToIterator = ((Collection) compareToValue).iterator();
while (referenceIterator.hasNext()) {
if (!areEqual(referenceIterator.next(), compareToIterator.next())) {
return false;
}
}
return true;
}
}
if (referenceValue == null && compareToValue == null) {
return true;
}
if (referenceValue == null || compareToValue == null) {
return false;
}
String object1Name;
if (referenceValue instanceof DatabaseObject) {
object1Name = accordingTo.correctObjectName(((DatabaseObject) referenceValue).getAttribute("name", String.class), type);
} else {
object1Name = referenceValue.toString();
}
String object2Name;
if (compareToValue instanceof DatabaseObject) {
object2Name = accordingTo.correctObjectName(((DatabaseObject) compareToValue).getAttribute("name", String.class), type);
} else {
object2Name = compareToValue.toString();
}
if (object1Name == null && object2Name == null) {
return true;
}
if (object1Name == null || object2Name == null) {
return false;
}
if (accordingTo.isCaseSensitive()) {
return object1Name.equals(object2Name);
} else {
return object1Name.equalsIgnoreCase(object2Name);
}
}
}
public static class DataTypeCompareFunction implements CompareFunction {
private final Database accordingTo;
public DataTypeCompareFunction(Database accordingTo) {
this.accordingTo = accordingTo;
}
@Override
public boolean areEqual(Object referenceValue, Object compareToValue) {
if (referenceValue == null && compareToValue == null) {
return true;
}
if (referenceValue == null || compareToValue == null) {
return false;
}
DataType referenceType = (DataType) referenceValue;
DataType compareToType = (DataType) compareToValue;
if (!referenceType.getTypeName().equalsIgnoreCase(compareToType.getTypeName())) {
return false;
}
if (compareToType.toString().contains("(") && referenceType.toString().contains("(")) {
return compareToType.toString().equalsIgnoreCase(referenceType.toString());
} else {
return true;
}
}
}
public static class OrderedCollectionCompareFunction implements CompareFunction {
private StandardCompareFunction compareFunction;
public OrderedCollectionCompareFunction(StandardCompareFunction compareFunction) {
this.compareFunction = compareFunction;
}
@Override
public boolean areEqual(Object referenceValue, Object compareToValue) {
if (referenceValue == null && compareToValue == null) {
return true;
}
if (referenceValue == null || compareToValue == null) {
return false;
}
if (!(referenceValue instanceof Collection) || (!(compareToValue instanceof Collection))) {
return false;
}
if (((Collection) referenceValue).size() != ((Collection) compareToValue).size()) {
return false;
}
Iterator referenceIterator = ((Collection) referenceValue).iterator();
Iterator compareIterator = ((Collection) compareToValue).iterator();
if (((Collection) referenceValue).size() != ((Collection) compareToValue).size()) {
return false;
}
while (referenceIterator.hasNext()) {
Object referenceObj = referenceIterator.next();
Object compareObj = compareIterator.next();
if (!compareFunction.areEqual(referenceObj, compareObj)) {
return false;
}
}
return true;
}
}
public static class UnOrderedCollectionCompareFunction implements CompareFunction {
private StandardCompareFunction compareFunction;
public UnOrderedCollectionCompareFunction(StandardCompareFunction compareFunction) {
this.compareFunction = compareFunction;
}
@Override
public boolean areEqual(Object referenceValue, Object compareToValue) {
if (referenceValue == null && compareToValue == null) {
return true;
}
if (referenceValue == null || compareToValue == null) {
return false;
}
if (!(referenceValue instanceof Collection) || (!(compareToValue instanceof Collection))) {
return false;
}
if (((Collection) referenceValue).size() != ((Collection) compareToValue).size()) {
return false;
}
Iterator referenceIterator = ((Collection) referenceValue).iterator();
List unmatchedCompareToValues = new ArrayList(((Collection) compareToValue));
if (((Collection) referenceValue).size() != ((Collection) compareToValue).size()) {
return false;
}
while (referenceIterator.hasNext()) {
Object referenceObj = referenceIterator.next();
Object foundMatch = null;
for (Object compareObj : unmatchedCompareToValues) {
if (compareFunction.areEqual(referenceObj, compareObj)) {
foundMatch = compareObj;
break;
}
}
if (foundMatch == null) {
return false;
} else {
unmatchedCompareToValues.remove(foundMatch);
}
}
return true;
}
}
}
|
package com.newsblur.util;
import java.util.Map;
import static android.graphics.Bitmap.Config.ARGB_8888;
import android.app.Activity;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.newsblur.R;
import com.newsblur.activity.*;
import com.newsblur.domain.Classifier;
public class UIUtils {
private UIUtils() {} // util class - no instances
@SuppressWarnings("deprecation")
public static Bitmap clipAndRound(Bitmap source, float radius, boolean clipSquare) {
Bitmap result = source;
if (clipSquare) {
int width = result.getWidth();
int height = result.getHeight();
int newSize = Math.min(width, height);
int x = (width-newSize) / 2;
int y = (height-newSize) / 2;
try {
result = Bitmap.createBitmap(result, x, y, newSize, newSize);
} catch (Throwable t) {
// even on reasonably modern systems, it is common for the bitmap processor to reject
// requests if it thinks memory is even remotely constrained.
android.util.Log.e(UIUtils.class.getName(), "couldn't process icon or thumbnail", t);
return null;
}
}
if ((radius > 0f) && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)) {
int width = result.getWidth();
int height = result.getHeight();
Bitmap canvasMap = null;
try {
canvasMap = Bitmap.createBitmap(width, height, ARGB_8888);
} catch (Throwable t) {
// even on reasonably modern systems, it is common for the bitmap processor to reject
// requests if it thinks memory is even remotely constrained.
android.util.Log.e(UIUtils.class.getName(), "couldn't process icon or thumbnail", t);
return null;
}
Canvas canvas = new Canvas(canvasMap);
BitmapShader shader = new BitmapShader(result, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
canvas.drawRoundRect(0, 0, width, height, radius, radius, paint);
result = canvasMap;
}
return result;
}
public static int dp2px(Context context, int dp) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
public static float dp2px(Context context, float dp) {
float scale = context.getResources().getDisplayMetrics().density;
return dp * scale;
}
public static float px2dp(Context context, int px) {
return ((float) px) / context.getResources().getDisplayMetrics().density;
}
/**
* Sets the alpha of a view, totally hiding the view if the alpha is so low
* as to be invisible, but also obeying intended visibility.
*/
public static void setViewAlpha(View v, float alpha, boolean visible) {
v.setAlpha(alpha);
if ((alpha < 0.001f) || !visible) {
v.setVisibility(View.GONE);
} else {
v.setVisibility(View.VISIBLE);
}
}
/**
* Set up our customised ActionBar view that features the specified icon and title, sized
* away from system standard to meet the NewsBlur visual style.
*/
public static void setCustomActionBar(Activity activity, String imageUrl, String title) {
ImageView iconView = setupCustomActionbar(activity, title);
FeedUtils.iconLoader.displayImage(imageUrl, iconView, 0, false);
}
public static void setCustomActionBar(Activity activity, int imageId, String title) {
ImageView iconView = setupCustomActionbar(activity, title);
iconView.setImageResource(imageId);
}
private static ImageView setupCustomActionbar(final Activity activity, String title) {
// we completely replace the existing title and 'home' icon with a custom view
activity.getActionBar().setDisplayShowCustomEnabled(true);
activity.getActionBar().setDisplayShowTitleEnabled(false);
activity.getActionBar().setDisplayShowHomeEnabled(false);
View v = LayoutInflater.from(activity).inflate(R.layout.actionbar_custom_icon, null);
TextView titleView = ((TextView) v.findViewById(R.id.actionbar_text));
titleView.setText(title);
ImageView iconView = ((ImageView) v.findViewById(R.id.actionbar_icon));
// using a custom view breaks the system-standard ability to tap the icon or title to return
// to the previous activity. Re-implement that here.
titleView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
activity.finish();
}
});
iconView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
activity.finish();
}
});
activity.getActionBar().setCustomView(v, new ActionBar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
return iconView;
}
/**
* Shows a toast in a circumstance where the context might be null. This can very
* rarely happen when toasts are done from async tasks and the context is finished
* before the task completes, resulting in a crash. This prevents the crash at the
* cost of the toast not being shown.
*/
public static void safeToast(final Activity c, final int rid, final int duration) {
if (c != null) {
c.runOnUiThread(new Runnable() { public void run() {
Toast.makeText(c, rid, duration).show();
}});
}
}
public static void safeToast(final Activity c, final String text, final int duration) {
if ((c != null) && (text != null)) {
c.runOnUiThread(new Runnable() { public void run() {
Toast.makeText(c, text, duration).show();
}});
}
}
public static void restartActivity(final Activity activity) {
new Handler().post(new Runnable() {
@Override
public void run() {
Intent intent = activity.getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
activity.overridePendingTransition(0, 0);
activity.finish();
activity.overridePendingTransition(0, 0);
activity.startActivity(intent);
}
});
}
public static void startReadingActivity(FeedSet fs, String startingHash, Context context) {
Class activityClass;
if (fs.isAllSaved()) {
activityClass = SavedStoriesReading.class;
} else if (fs.getSingleSavedTag() != null) {
activityClass = SavedStoriesReading.class;
} else if (fs.isGlobalShared()) {
activityClass = GlobalSharedStoriesReading.class;
} else if (fs.isAllSocial()) {
activityClass = AllSharedStoriesReading.class;
} else if (fs.isAllNormal()) {
activityClass = AllStoriesReading.class;
} else if (fs.isFolder()) {
activityClass = FolderReading.class;
} else if (fs.getSingleFeed() != null) {
activityClass = FeedReading.class;
} else if (fs.getSingleSocialFeed() != null) {
activityClass = SocialFeedReading.class;
} else if (fs.isAllRead()) {
activityClass = ReadStoriesReading.class;
} else if (fs.isInfrequent()) {
activityClass = InfrequentReading.class;
} else {
Log.e(UIUtils.class.getName(), "can't launch reading activity for unknown feedset type");
return;
}
Intent i = new Intent(context, activityClass);
i.putExtra(Reading.EXTRA_FEEDSET, fs);
i.putExtra(Reading.EXTRA_STORY_HASH, startingHash);
context.startActivity(i);
}
public static String getMemoryUsageDebug(Context context) {
String memInfo = " (";
android.app.ActivityManager activityManager = (android.app.ActivityManager) context.getSystemService(android.app.Activity.ACTIVITY_SERVICE);
int[] pids = new int[]{android.os.Process.myPid()};
android.os.Debug.MemoryInfo[] miProc = activityManager.getProcessMemoryInfo(pids);
android.app.ActivityManager.MemoryInfo miGen = new android.app.ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(miGen);
memInfo = memInfo + (miProc[0].getTotalPss() / 1024) + "MB used, " + (miGen.availMem / (1024*1024)) + "MB free)";
return memInfo;
}
@SuppressWarnings("deprecation")
public static int getColor(Context activity, int rid) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return activity.getResources().getColor(rid, activity.getTheme());
} else {
return activity.getResources().getColor(rid);
}
}
/**
* Get a color defined by our particular way of using styles that are indirectly defined by themes.
*
* @param styleId the style that defines the attr, such as com.newsblur.R.attr.defaultText
* @param rId the resource attribute that defines the color desired, such as android.R.attr.textColor
*/
public static int getThemedColor(Context context, int styleId, int rId) {
int[] attrs = {styleId};
TypedArray val = context.getTheme().obtainStyledAttributes(attrs);
if (val.peekValue(0).type != TypedValue.TYPE_REFERENCE) {
com.newsblur.util.Log.w(UIUtils.class.getName(), "styleId didn't resolve to a style");
val.recycle();
return Color.MAGENTA;
}
int effectiveStyleId = val.getResourceId(0, -1);
val.recycle();
if (effectiveStyleId == -1) {
com.newsblur.util.Log.w(UIUtils.class.getName(), "styleId didn't resolve to a known style");
return Color.MAGENTA;
}
int[] attrs2 = {rId};
TypedArray val2 = context.getTheme().obtainStyledAttributes(effectiveStyleId, attrs2);
if ( (val2.peekValue(0).type < TypedValue.TYPE_FIRST_COLOR_INT) || (val2.peekValue(0).type > TypedValue.TYPE_LAST_COLOR_INT)) {
com.newsblur.util.Log.w(UIUtils.class.getName(), "rId didn't resolve to a color within given style");
val2.recycle();
return Color.MAGENTA;
}
int result = val2.getColor(0, Color.MAGENTA);
val2.recycle();
return result;
}
/**
* Get a resource defined by our particular way of using styles that are indirectly defined by themes.
*
* @param styleId the style that defines the attr, such as com.newsblur.R.attr.defaultText
* @param rId the resource attribute that defines the resource desired, such as android.R.attr.background
*/
public static int getThemedResource(Context context, int styleId, int rId) {
int[] attrs = {styleId};
TypedArray val = context.getTheme().obtainStyledAttributes(attrs);
if (val.peekValue(0).type != TypedValue.TYPE_REFERENCE) {
com.newsblur.util.Log.w(UIUtils.class.getName(), "styleId didn't resolve to a style");
val.recycle();
return 0;
}
int effectiveStyleId = val.getResourceId(0, -1);
val.recycle();
if (effectiveStyleId == -1) {
com.newsblur.util.Log.w(UIUtils.class.getName(), "styleId didn't resolve to a known style");
return 0;
}
int[] attrs2 = {rId};
TypedArray val2 = context.getTheme().obtainStyledAttributes(effectiveStyleId, attrs2);
int result = 0;
try {
result = val2.getResourceId(0, 0);
} catch (UnsupportedOperationException uoe) {
com.newsblur.util.Log.w(UIUtils.class.getName(), "rId didn't resolve to a drawable within given style");
}
val2.recycle();
return result;
}
@SuppressWarnings("deprecation")
public static Drawable getDrawable(Context activity, int rid) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return activity.getResources().getDrawable(rid, activity.getTheme());
} else {
return activity.getResources().getDrawable(rid);
}
}
/**
* Sets the background resource of a view, working around a platform bug that causes the declared
* padding to get reset.
*/
public static void setViewBackground(View v, Drawable background) {
// due to a framework bug, the below modification of background resource also resets the declared
// padding on the view. save a copy of said padding so it can be re-applied after the change.
int oldPadL = v.getPaddingLeft();
int oldPadT = v.getPaddingTop();
int oldPadR = v.getPaddingRight();
int oldPadB = v.getPaddingBottom();
v.setBackground(background);
v.setPadding(oldPadL, oldPadT, oldPadR, oldPadB);
}
// API 24 introduced a more customizable impl of fromHtml but also *immediately* deprecated the
// default version in the same release, so it is necessary to wrap this is plat-specific helper
@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
} else {
return Html.fromHtml(html);
}
}
private static final String POSIT_HILITE_FORMAT = "<span style=\"color: #33AA33\">%s</span>";
private static final String NEGAT_HILITE_FORMAT = "<span style=\"color: #AA3333\">%s</span>";
/**
* Alter a story title string to highlight intel training hits as positive or negative based
* upon the associated classifier, using markup that can quickly be parsed by fromHtml.
*/
public static String colourTitleFromClassifier(String title, Classifier c) {
String result = title;
for (Map.Entry<String, Integer> rule : c.title.entrySet()) {
if (rule.getValue() == Classifier.LIKE) {
result = result.replace(rule.getKey(), String.format(POSIT_HILITE_FORMAT, rule.getKey()));
}
if (rule.getValue() == Classifier.DISLIKE) {
result = result.replace(rule.getKey(), String.format(NEGAT_HILITE_FORMAT, rule.getKey()));
}
}
return result;
}
/**
* Takes an inflated R.layout.include_intel_row and activates the like/dislike buttons based
* upon the provided classifier sub-type map while also setting up handlers to alter said
* map if the buttons are pressed.
*/
public static void setupIntelDialogRow(final View row, final Map<String,Integer> classifier, final String key) {
colourIntelDialogRow(row, classifier, key);
row.findViewById(R.id.intel_row_like).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
classifier.put(key, Classifier.LIKE);
colourIntelDialogRow(row, classifier, key);
}
});
row.findViewById(R.id.intel_row_dislike).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
classifier.put(key, Classifier.DISLIKE);
colourIntelDialogRow(row, classifier, key);
}
});
row.findViewById(R.id.intel_row_clear).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
classifier.put(key, Classifier.CLEAR_LIKE);
colourIntelDialogRow(row, classifier, key);
}
});
}
private static void colourIntelDialogRow(View row, Map<String,Integer> classifier, String key) {
if (Integer.valueOf(Classifier.LIKE).equals(classifier.get(key))) {
row.findViewById(R.id.intel_row_like).setBackgroundResource(R.drawable.ic_like_active);
row.findViewById(R.id.intel_row_dislike).setBackgroundResource(R.drawable.ic_dislike_gray55);
row.findViewById(R.id.intel_row_clear).setBackgroundResource(R.drawable.ic_clear_gray55);
} else
if (Integer.valueOf(Classifier.DISLIKE).equals(classifier.get(key))) {
row.findViewById(R.id.intel_row_like).setBackgroundResource(R.drawable.ic_like_gray55);
row.findViewById(R.id.intel_row_dislike).setBackgroundResource(R.drawable.ic_dislike_active);
row.findViewById(R.id.intel_row_clear).setBackgroundResource(R.drawable.ic_clear_gray55);
} else {
row.findViewById(R.id.intel_row_like).setBackgroundResource(R.drawable.ic_like_gray55);
row.findViewById(R.id.intel_row_dislike).setBackgroundResource(R.drawable.ic_dislike_gray55);
row.findViewById(R.id.intel_row_clear).setBackgroundResource(R.drawable.ic_clear_gray55);
}
}
}
|
package com.yahoo.restapi;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.jdisc.http.HttpRequest.Method;
import com.yahoo.slime.Slime;
import com.yahoo.slime.SlimeUtils;
import com.yahoo.yolean.Exceptions;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* @author bjorncs
*/
class RestApiImpl implements RestApi {
private static final Logger log = Logger.getLogger(RestApiImpl.class.getName());
private final Route defaultRoute;
private final List<Route> routes;
private final List<ExceptionMapperHolder<?>> exceptionMappers;
private final List<ResponseMapperHolder<?>> responseMappers;
private final List<RequestMapperHolder<?>> requestMappers;
private final List<Filter> filters;
private final ObjectMapper jacksonJsonMapper;
private RestApiImpl(RestApi.Builder builder) {
BuilderImpl builderImpl = (BuilderImpl) builder;
ObjectMapper jacksonJsonMapper = builderImpl.jacksonJsonMapper != null ? builderImpl.jacksonJsonMapper : JacksonJsonMapper.instance.copy();
this.defaultRoute = builderImpl.defaultRoute != null ? builderImpl.defaultRoute : createDefaultRoute();
this.routes = List.copyOf(builderImpl.routes);
this.exceptionMappers = combineWithDefaultExceptionMappers(
builderImpl.exceptionMappers, Boolean.TRUE.equals(builderImpl.disableDefaultExceptionMappers));
this.responseMappers = combineWithDefaultResponseMappers(
builderImpl.responseMappers, jacksonJsonMapper, Boolean.TRUE.equals(builderImpl.disableDefaultResponseMappers));
this.requestMappers = combineWithDefaultRequestMappers(
builderImpl.requestMappers, jacksonJsonMapper);
this.filters = List.copyOf(builderImpl.filters);
this.jacksonJsonMapper = jacksonJsonMapper;
}
@Override
public HttpResponse handleRequest(HttpRequest request) {
Path pathMatcher = new Path(request.getUri());
Route resolvedRoute = resolveRoute(pathMatcher);
RequestContextImpl requestContext = new RequestContextImpl(request, pathMatcher, jacksonJsonMapper);
FilterContextImpl filterContext =
createFilterContextRecursive(
resolvedRoute, requestContext, filters,
createFilterContextRecursive(resolvedRoute, requestContext, resolvedRoute.filters, null));
if (filterContext != null) {
return filterContext.executeFirst();
} else {
return dispatchToRoute(resolvedRoute, requestContext);
}
}
private HttpResponse dispatchToRoute(Route route, RequestContextImpl context) {
HandlerHolder<?> resolvedHandler = resolveHandler(context, route);
RequestMapperHolder<?> resolvedRequestMapper = resolveRequestMapper(resolvedHandler);
Object requestEntity;
try {
requestEntity = resolvedRequestMapper.mapper.toRequestEntity(context).orElse(null);
} catch (RuntimeException e) {
return mapException(context, e);
}
Object responseEntity;
try {
responseEntity = resolvedHandler.executeHandler(context, requestEntity);
} catch (RuntimeException e) {
return mapException(context, e);
}
if (responseEntity == null) throw new NullPointerException("Handler must return non-null value");
ResponseMapperHolder<?> resolvedResponseMapper = resolveResponseMapper(responseEntity);
try {
return resolvedResponseMapper.toHttpResponse(context, responseEntity);
} catch (RuntimeException e) {
return mapException(context, e);
}
}
private HandlerHolder<?> resolveHandler(RequestContextImpl context, Route route) {
HandlerHolder<?> resolvedHandler = route.handlerPerMethod.get(context.request().getMethod());
return resolvedHandler == null ? route.defaultHandler : resolvedHandler;
}
private RequestMapperHolder<?> resolveRequestMapper(HandlerHolder<?> resolvedHandler) {
return requestMappers.stream()
.filter(holder -> resolvedHandler.type.isAssignableFrom(holder.type))
.findFirst().orElseThrow(() -> new IllegalStateException("No mapper configured for " + resolvedHandler.type));
}
private ResponseMapperHolder<?> resolveResponseMapper(Object responseEntity) {
return responseMappers.stream()
.filter(holder -> holder.type.isAssignableFrom(responseEntity.getClass()))
.findFirst().orElseThrow(() -> new IllegalStateException("No mapper configured for " + responseEntity.getClass()));
}
private HttpResponse mapException(RequestContextImpl context, RuntimeException e) {
log.log(Level.FINE, e, e::getMessage);
ExceptionMapperHolder<?> mapper = exceptionMappers.stream()
.filter(holder -> holder.type.isAssignableFrom(e.getClass()))
.findFirst().orElseThrow(() -> e);
return mapper.toResponse(context, e);
}
private Route resolveRoute(Path pathMatcher) {
Route matchingRoute = routes.stream()
.filter(route -> pathMatcher.matches(route.pathPattern))
.findFirst()
.orElse(null);
if (matchingRoute != null) return matchingRoute;
pathMatcher.matches(defaultRoute.pathPattern); // to populate any path parameters
return defaultRoute;
}
private FilterContextImpl createFilterContextRecursive(
Route route, RequestContextImpl requestContext, List<Filter> filters, FilterContextImpl previousContext) {
FilterContextImpl filterContext = previousContext;
ListIterator<Filter> iterator = filters.listIterator(filters.size());
while (iterator.hasPrevious()) {
filterContext = new FilterContextImpl(route, iterator.previous(), requestContext, filterContext);
}
return filterContext;
}
private static Route createDefaultRoute() {
RouteBuilder routeBuilder = new RouteBuilderImpl("{*}")
.defaultHandler(context -> {
throw new RestApiException.NotFoundException();
});
return ((RouteBuilderImpl)routeBuilder).build();
}
private static List<ExceptionMapperHolder<?>> combineWithDefaultExceptionMappers(
List<ExceptionMapperHolder<?>> configuredExceptionMappers, boolean disableDefaultMappers) {
List<ExceptionMapperHolder<?>> exceptionMappers = new ArrayList<>(configuredExceptionMappers);
if (!disableDefaultMappers){
exceptionMappers.add(new ExceptionMapperHolder<>(RestApiException.class, (context, exception) -> exception.response()));
}
return exceptionMappers;
}
private static List<ResponseMapperHolder<?>> combineWithDefaultResponseMappers(
List<ResponseMapperHolder<?>> configuredResponseMappers, ObjectMapper jacksonJsonMapper, boolean disableDefaultMappers) {
List<ResponseMapperHolder<?>> responseMappers = new ArrayList<>(configuredResponseMappers);
if (!disableDefaultMappers) {
responseMappers.add(new ResponseMapperHolder<>(HttpResponse.class, (context, entity) -> entity));
responseMappers.add(new ResponseMapperHolder<>(String.class, (context, entity) -> new MessageResponse(entity)));
responseMappers.add(new ResponseMapperHolder<>(Slime.class, (context, entity) -> new SlimeJsonResponse(entity)));
responseMappers.add(new ResponseMapperHolder<>(JsonNode.class, (context, entity) -> new JacksonJsonResponse<>(200, entity, jacksonJsonMapper, true)));
}
return responseMappers;
}
private static List<RequestMapperHolder<?>> combineWithDefaultRequestMappers(
List<RequestMapperHolder<?>> configuredRequestMappers, ObjectMapper jacksonJsonMapper) {
List<RequestMapperHolder<?>> requestMappers = new ArrayList<>(configuredRequestMappers);
requestMappers.add(new RequestMapperHolder<>(Slime.class, RestApiImpl::toSlime));
requestMappers.add(new RequestMapperHolder<>(JsonNode.class, ctx -> toJsonNode(ctx, jacksonJsonMapper)));
requestMappers.add(new RequestMapperHolder<>(String.class, RestApiImpl::toString));
requestMappers.add(new RequestMapperHolder<>(byte[].class, RestApiImpl::toByteArray));
requestMappers.add(new RequestMapperHolder<>(InputStream.class, RestApiImpl::toInputStream));
requestMappers.add(new RequestMapperHolder<>(Void.class, ctx -> Optional.empty()));
return requestMappers;
}
private static Optional<InputStream> toInputStream(RequestContext context) {
return context.requestContent().map(RequestContext.RequestContent::content);
}
private static Optional<byte[]> toByteArray(RequestContext context) {
InputStream in = toInputStream(context).orElse(null);
if (in == null) return Optional.empty();
return convertIoException(() -> Optional.of(in.readAllBytes()));
}
private static Optional<String> toString(RequestContext context) {
try {
return toByteArray(context).map(bytes -> new String(bytes, UTF_8));
} catch (RuntimeException e) {
throw new RestApiException.BadRequest("Failed parse request content as UTF-8: " + Exceptions.toMessageString(e), e);
}
}
private static Optional<JsonNode> toJsonNode(RequestContext context, ObjectMapper jacksonJsonMapper) {
if (log.isLoggable(Level.FINE)) {
return toString(context).map(string -> {
log.fine(() -> "Request content: " + string);
return convertIoException("Failed to parse JSON", () -> jacksonJsonMapper.readTree(string));
});
} else {
return toInputStream(context)
.map(in -> convertIoException("Invalid JSON", () -> jacksonJsonMapper.readTree(in)));
}
}
private static Optional<Slime> toSlime(RequestContext context) {
try {
return toString(context).map(string -> {
log.fine(() -> "Request content: " + string);
return SlimeUtils.jsonToSlimeOrThrow(string);
});
} catch (com.yahoo.slime.JsonParseException e) {
log.log(Level.FINE, e.getMessage(), e);
throw new RestApiException.BadRequest("Invalid JSON: " + Exceptions.toMessageString(e), e);
}
}
static class BuilderImpl implements RestApi.Builder {
private final List<Route> routes = new ArrayList<>();
private final List<ExceptionMapperHolder<?>> exceptionMappers = new ArrayList<>();
private final List<ResponseMapperHolder<?>> responseMappers = new ArrayList<>();
private final List<RequestMapperHolder<?>> requestMappers = new ArrayList<>();
private final List<RestApi.Filter> filters = new ArrayList<>();
private Route defaultRoute;
private ObjectMapper jacksonJsonMapper;
private Boolean disableDefaultExceptionMappers;
private Boolean disableDefaultResponseMappers;
@Override public RestApi.Builder setObjectMapper(ObjectMapper mapper) { this.jacksonJsonMapper = mapper; return this; }
@Override public RestApi.Builder setDefaultRoute(RestApi.RouteBuilder route) { this.defaultRoute = ((RouteBuilderImpl)route).build(); return this; }
@Override public RestApi.Builder addRoute(RestApi.RouteBuilder route) { routes.add(((RouteBuilderImpl)route).build()); return this; }
@Override public RestApi.Builder addFilter(RestApi.Filter filter) { filters.add(filter); return this; }
@Override public <EXCEPTION extends RuntimeException> RestApi.Builder addExceptionMapper(Class<EXCEPTION> type, RestApi.ExceptionMapper<EXCEPTION> mapper) {
exceptionMappers.add(new ExceptionMapperHolder<>(type, mapper)); return this;
}
@Override public <ENTITY> RestApi.Builder addResponseMapper(Class<ENTITY> type, RestApi.ResponseMapper<ENTITY> mapper) {
responseMappers.add(new ResponseMapperHolder<>(type, mapper)); return this;
}
@Override public <ENTITY> Builder addRequestMapper(Class<ENTITY> type, RequestMapper<ENTITY> mapper) {
requestMappers.add(new RequestMapperHolder<>(type, mapper)); return this;
}
@Override public <ENTITY> Builder registerJacksonResponseEntity(Class<ENTITY> type) {
addResponseMapper(type, new JacksonResponseMapper<>()); return this;
}
@Override public <ENTITY> Builder registerJacksonRequestEntity(Class<ENTITY> type) {
addRequestMapper(type, new JacksonRequestMapper<>(type)); return this;
}
@Override public Builder disableDefaultExceptionMappers() { this.disableDefaultExceptionMappers = true; return this; }
@Override public Builder disableDefaultResponseMappers() { this.disableDefaultResponseMappers = true; return this; }
@Override public RestApi build() { return new RestApiImpl(this); }
}
public static class RouteBuilderImpl implements RestApi.RouteBuilder {
private final String pathPattern;
private String name;
private final Map<Method, HandlerHolder<?>> handlerPerMethod = new HashMap<>();
private final List<RestApi.Filter> filters = new ArrayList<>();
private HandlerHolder<?> defaultHandler;
RouteBuilderImpl(String pathPattern) { this.pathPattern = pathPattern; }
@Override public RestApi.RouteBuilder name(String name) { this.name = name; return this; }
@Override public RestApi.RouteBuilder get(Handler<?> handler) {
return addHandler(Method.GET, handler);
}
@Override public RestApi.RouteBuilder post(Handler<?> handler) {
return addHandler(Method.POST, handler);
}
@Override public <ENTITY> RouteBuilder post(Class<ENTITY> type, HandlerWithRequestEntity<ENTITY, ?> handler) {
return addHandler(Method.POST, type, handler);
}
@Override public RestApi.RouteBuilder put(Handler<?> handler) {
return addHandler(Method.PUT, handler);
}
@Override public <ENTITY> RouteBuilder put(Class<ENTITY> type, HandlerWithRequestEntity<ENTITY, ?> handler) {
return addHandler(Method.PUT, type, handler);
}
@Override public RestApi.RouteBuilder delete(Handler<?> handler) {
return addHandler(Method.DELETE, handler);
}
@Override public RestApi.RouteBuilder patch(Handler<?> handler) {
return addHandler(Method.PATCH, handler);
}
@Override public <ENTITY> RouteBuilder patch(Class<ENTITY> type, HandlerWithRequestEntity<ENTITY, ?> handler) {
return addHandler(Method.PATCH, type, handler);
}
@Override public RestApi.RouteBuilder defaultHandler(Handler<?> handler) {
defaultHandler = HandlerHolder.of(handler); return this;
}
@Override public <ENTITY> RouteBuilder defaultHandler(Class<ENTITY> type, HandlerWithRequestEntity<ENTITY, ?> handler) {
defaultHandler = HandlerHolder.of(type, handler); return this;
}
@Override public RestApi.RouteBuilder addFilter(RestApi.Filter filter) { filters.add(filter); return this; }
private RestApi.RouteBuilder addHandler(Method method, Handler<?> handler) {
handlerPerMethod.put(method, HandlerHolder.of(handler)); return this;
}
private <ENTITY> RestApi.RouteBuilder addHandler(
Method method, Class<ENTITY> type, HandlerWithRequestEntity<ENTITY, ?> handler) {
handlerPerMethod.put(method, HandlerHolder.of(type, handler)); return this;
}
private Route build() { return new Route(this); }
}
private static class RequestContextImpl implements RestApi.RequestContext {
final HttpRequest request;
final Path pathMatcher;
final ObjectMapper jacksonJsonMapper;
final PathParameters pathParameters = new PathParametersImpl();
final QueryParameters queryParameters = new QueryParametersImpl();
final Headers headers = new HeadersImpl();
final Attributes attributes = new AttributesImpl();
final RequestContent requestContent;
RequestContextImpl(HttpRequest request, Path pathMatcher, ObjectMapper jacksonJsonMapper) {
this.request = request;
this.pathMatcher = pathMatcher;
this.jacksonJsonMapper = jacksonJsonMapper;
this.requestContent = request.getData() != null ? new RequestContentImpl() : null;
}
@Override public HttpRequest request() { return request; }
@Override public PathParameters pathParameters() { return pathParameters; }
@Override public QueryParameters queryParameters() { return queryParameters; }
@Override public Headers headers() { return headers; }
@Override public Attributes attributes() { return attributes; }
@Override public Optional<RequestContent> requestContent() { return Optional.ofNullable(requestContent); }
@Override public RequestContent requestContentOrThrow() {
return requestContent().orElseThrow(() -> new RestApiException.BadRequest("Request content missing"));
}
@Override public ObjectMapper jacksonJsonMapper() { return jacksonJsonMapper; }
private class PathParametersImpl implements RestApi.RequestContext.PathParameters {
@Override
public Optional<String> getString(String name) {
if (name.equals("*")) {
String rest = pathMatcher.getRest();
return rest.isEmpty() ? Optional.empty() : Optional.of(rest);
}
return Optional.ofNullable(pathMatcher.get(name));
}
@Override public String getStringOrThrow(String name) {
return getString(name)
.orElseThrow(() -> new RestApiException.BadRequest("Path parameter '" + name + "' is missing"));
}
}
private class QueryParametersImpl implements RestApi.RequestContext.QueryParameters {
@Override public Optional<String> getString(String name) { return Optional.ofNullable(request.getProperty(name)); }
@Override public String getStringOrThrow(String name) {
return getString(name)
.orElseThrow(() -> new RestApiException.BadRequest("Query parameter '" + name + "' is missing"));
}
}
private class HeadersImpl implements RestApi.RequestContext.Headers {
@Override public Optional<String> getString(String name) { return Optional.ofNullable(request.getHeader(name)); }
@Override public String getStringOrThrow(String name) {
return getString(name)
.orElseThrow(() -> new RestApiException.BadRequest("Header '" + name + "' missing"));
}
}
private class RequestContentImpl implements RestApi.RequestContext.RequestContent {
@Override public String contentType() { return request.getHeader("Content-Type"); }
@Override public InputStream content() { return request.getData(); }
}
private class AttributesImpl implements RestApi.RequestContext.Attributes {
@Override public Optional<Object> get(String name) { return Optional.ofNullable(request.getJDiscRequest().context().get(name)); }
@Override public void set(String name, Object value) { request.getJDiscRequest().context().put(name, value); }
}
}
private class FilterContextImpl implements RestApi.FilterContext {
final Route route;
final RestApi.Filter filter;
final RequestContextImpl requestContext;
final FilterContextImpl next;
FilterContextImpl(Route route, RestApi.Filter filter, RequestContextImpl requestContext, FilterContextImpl next) {
this.route = route;
this.filter = filter;
this.requestContext = requestContext;
this.next = next;
}
@Override public RestApi.RequestContext requestContext() { return requestContext; }
@Override public String route() { return route.name != null ? route.name : route.pathPattern; }
HttpResponse executeFirst() { return filter.filterRequest(this); }
@Override
public HttpResponse executeNext() {
if (next != null) {
return next.filter.filterRequest(next);
} else {
return dispatchToRoute(route, requestContext);
}
}
}
private static class ExceptionMapperHolder<EXCEPTION extends RuntimeException> {
final Class<EXCEPTION> type;
final RestApi.ExceptionMapper<EXCEPTION> mapper;
ExceptionMapperHolder(Class<EXCEPTION> type, RestApi.ExceptionMapper<EXCEPTION> mapper) {
this.type = type;
this.mapper = mapper;
}
HttpResponse toResponse(RestApi.RequestContext context, RuntimeException e) { return mapper.toResponse(context, type.cast(e)); }
}
private static class ResponseMapperHolder<ENTITY> {
final Class<ENTITY> type;
final RestApi.ResponseMapper<ENTITY> mapper;
ResponseMapperHolder(Class<ENTITY> type, RestApi.ResponseMapper<ENTITY> mapper) {
this.type = type;
this.mapper = mapper;
}
HttpResponse toHttpResponse(RestApi.RequestContext context, Object entity) { return mapper.toHttpResponse(context, type.cast(entity)); }
}
private static class HandlerHolder<REQUEST_ENTITY> {
final Class<REQUEST_ENTITY> type;
final HandlerWithRequestEntity<REQUEST_ENTITY, ?> handler;
HandlerHolder(Class<REQUEST_ENTITY> type, HandlerWithRequestEntity<REQUEST_ENTITY, ?> handler) {
this.type = type;
this.handler = handler;
}
static <RESPONSE_ENTITY, REQUEST_ENTITY> HandlerHolder<REQUEST_ENTITY> of(
Class<REQUEST_ENTITY> type, HandlerWithRequestEntity<REQUEST_ENTITY, RESPONSE_ENTITY> handler) {
return new HandlerHolder<>(type, handler);
}
static <RESPONSE_ENTITY> HandlerHolder<Void> of(Handler<RESPONSE_ENTITY> handler) {
return new HandlerHolder<>(
Void.class,
(HandlerWithRequestEntity<Void, RESPONSE_ENTITY>) (context, nullEntity) -> handler.handleRequest(context));
}
Object executeHandler(RestApi.RequestContext context, Object entity) { return handler.handleRequest(context, type.cast(entity)); }
}
private static class RequestMapperHolder<ENTITY> {
final Class<ENTITY> type;
final RestApi.RequestMapper<ENTITY> mapper;
RequestMapperHolder(Class<ENTITY> type, RequestMapper<ENTITY> mapper) {
this.type = type;
this.mapper = mapper;
}
}
static class Route {
private final String pathPattern;
private final String name;
private final Map<Method, HandlerHolder<?>> handlerPerMethod;
private final HandlerHolder<?> defaultHandler;
private final List<Filter> filters;
private Route(RestApi.RouteBuilder builder) {
RouteBuilderImpl builderImpl = (RouteBuilderImpl)builder;
this.pathPattern = builderImpl.pathPattern;
this.name = builderImpl.name;
this.handlerPerMethod = Map.copyOf(builderImpl.handlerPerMethod);
this.defaultHandler = builderImpl.defaultHandler != null ? builderImpl.defaultHandler : createDefaultMethodHandler();
this.filters = List.copyOf(builderImpl.filters);
}
private HandlerHolder<?> createDefaultMethodHandler() {
return HandlerHolder.of(context -> { throw new RestApiException.MethodNotAllowed(context.request()); });
}
}
private static class JacksonRequestMapper<ENTITY> implements RequestMapper<ENTITY> {
private final Class<ENTITY> type;
JacksonRequestMapper(Class<ENTITY> type) { this.type = type; }
@Override
public Optional<ENTITY> toRequestEntity(RequestContext context) throws RestApiException {
if (log.isLoggable(Level.FINE)) {
return RestApiImpl.toString(context).map(string -> {
log.fine(() -> "Request content: " + string);
return convertIoException("Failed to parse JSON", () -> context.jacksonJsonMapper().readValue(string, type));
});
} else {
return RestApiImpl.toInputStream(context)
.map(in -> convertIoException("Invalid JSON", () -> context.jacksonJsonMapper().readValue(in, type)));
}
}
}
private static class JacksonResponseMapper<ENTITY> implements ResponseMapper<ENTITY> {
@Override
public HttpResponse toHttpResponse(RequestContext context, ENTITY responseEntity) throws RestApiException {
return new JacksonJsonResponse<>(200, responseEntity, context.jacksonJsonMapper(), true);
}
}
@FunctionalInterface private interface SupplierThrowingIoException<T> { T get() throws IOException; }
private static <T> T convertIoException(String messagePrefix, SupplierThrowingIoException<T> supplier) {
try {
return supplier.get();
} catch (IOException e) {
log.log(Level.FINE, e.getMessage(), e);
throw new RestApiException.InternalServerError(messagePrefix + ": " + Exceptions.toMessageString(e), e);
}
}
private static <T> T convertIoException(SupplierThrowingIoException<T> supplier) {
return convertIoException("Failed to read request content", supplier);
}
}
|
package org.coffeeshop.application;
import java.io.*;
import java.util.*;
import org.coffeeshop.settings.ReadableSettings;
import org.coffeeshop.settings.Settings;
import org.coffeeshop.string.StringUtils;
/**
* This static class keeps track of all the opened settings files that are
* represented as <code>Settings</code> objects. It provides methods for
* loading these files in the context of an application and then
* later storing them back.
*
* @author lukacu
* @since CoffeeShop 1.0
* @see org.coffeeshop.settings.Settings
*/
public class SettingsManager {
// settings directory
private String settingsDirectory = null;
// setting directory exists flag
private boolean hasDirectory = false;
// hash map that stores opened files
private HashMap<String, Settings> files;
private static class SettingsAutosave extends Thread {
private ArrayList<SettingsManager> dirList = new ArrayList<SettingsManager>();
public synchronized void add(SettingsManager dir) {
if (!dirList.contains(dir))
dirList.add(dir);
}
public synchronized void remove(SettingsManager dir) {
dirList.remove(dir);
}
public void run() {
synchronized (this)
{
Iterator<SettingsManager> iterator = dirList.iterator();
while (iterator.hasNext()) {
try {
iterator.next().storeAllSettings();
} catch (FileNotFoundException e) {
Application.getApplicationLogger().report(e);
}
}
}
}
}
private static SettingsAutosave autosave;
static {
autosave = new SettingsAutosave();
Runtime.getRuntime().addShutdownHook(autosave);
}
/**
* Initalization of SettingsManager
*
* @param a application object
*/
public SettingsManager(Application a) {
this(a, true);
}
/**
* Initalization of SettingsManager
*
* @param a application object
* @param autosave settings should be automatically saved if application
* exits
*/
public SettingsManager(Application a, boolean autosave) {
if (a == null)
throw new IllegalArgumentException("Application must not be null");
// constucts settings directory path
settingsDirectory = Application.applicationStorageDirectory(a);
// attempt to check for the directory and possibly create it
hasDirectory = createRepository();
files = new HashMap<String, Settings>();
if (autosave)
SettingsManager.autosave.add(this);
}
/**
* Attempts to check for the directory and possibly create it.
*
* @return <code>true</code> if successful (directory exists),
* <code>false</code> otherwise.
*/
private boolean createRepository() {
File path = new File(settingsDirectory);
if (!path.exists()) {
try {
path.mkdir();
}
catch (SecurityException e) {
return false;
}
return true;
}
return true;
}
/**
* Provides a <code>Settings</code> object associated with the provided
* file. The algorythm is as follows:
* 1. if object like that exists in the list of managed object return that
* object
* 2. if we cannot load the file return empty object (added to the list)
* 3. otherwise return object with loaded settings (added to the list)
*
* @param fileName storage file for these settings
* @return <code>true</code> if successful,
* <code>false</code> if the file already has an object attached.
*/
public Settings getSettings(String fileName, ReadableSettings parent) {
// search for existing settings object
Settings result = (Settings)files.get(fileName);
if (result != null) return result;
result = new Settings(parent);
files.put(fileName, result);
// if the settings directory does not exists, we can not load
// settings ... therefore return empty object
if (hasDirectory)
result.loadSettings(settingsDirectory + fileName);
return result;
}
/**
* @param fileName storage file for these settings
* @return <code>true</code> if successful,
* <code>false</code> if the file already has an object attached.
* @see SettingsManager#getSettings(String)
*/
public Settings getSettings(String fileName) {
return getSettings(fileName, null);
}
/**
* Add a Settings object to the SettingsManager list.
*
* This method is not realy meant to be used outside this class and
* will be probaly be transformed to private method in the future.
*
* @param fileName storage file for these settings
* @param settings storage object
* @return <code>true</code> if successful,
* <code>false</code> if the file already has an object attached.
*/
public boolean addSettings(String fileName, Settings settings) {
Settings result = (Settings)files.get(fileName);
if (result != null) return false;
files.put(fileName, settings);
settings.touch();
return true;
}
/**
* Stores all the files managed by the SettingsManager
*
* @return <code>true</code> if successful, <code>false</code> if at
* least one file could not be stored.
* @throws FileNotFoundException if the settings directory could not be created
* beacuse of security reasons
*/
public boolean storeAllSettings() throws FileNotFoundException {
Object s[] = files.keySet().toArray();
boolean result = true;
for(int i = 0; i < s.length; i++) {
result &= storeSettings((String)s[i]);
}
return result;
}
/**
* Stores settings to the given file (if souch file was ever opened)
*
* This method is not realy meant to be used outside this class and
* will be probaly be transformed to private method in the future.
*
* @param fileName
* @return <code>true</code> if successful, <code>false</code> if not.
* @throws FileNotFoundException if the settings directory could not be created
* beacuse of security reasons
*/
public boolean storeSettings(String fileName) throws FileNotFoundException {
if (!hasDirectory)
throw new FileNotFoundException("Settings directory does not exists");
Settings result = (Settings)files.get(fileName);
if (result != null) {
return result.storeSettings(settingsDirectory + fileName);
}
else return false;
}
public File storageFileName(String name) {
if (StringUtils.empty(name))
return null;
return new File(settingsDirectory, name);
}
}
|
package com.newsblur.util;
import static android.graphics.Bitmap.Config.ARGB_8888;
import static android.graphics.Color.WHITE;
import static android.graphics.PorterDuff.Mode.DST_IN;
import android.app.Activity;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.newsblur.R;
import com.newsblur.activity.*;
public class UIUtils {
public static Bitmap roundCorners(Bitmap source, final float radius) {
int width = source.getWidth();
int height = source.getHeight();
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(WHITE);
Bitmap clipped = Bitmap.createBitmap(width, height, ARGB_8888);
Canvas canvas = new Canvas(clipped);
canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);
paint.setXfermode(new PorterDuffXfermode(DST_IN));
Bitmap rounded = Bitmap.createBitmap(width, height, ARGB_8888);
canvas = new Canvas(rounded);
canvas.drawBitmap(source, 0, 0, null);
canvas.drawBitmap(clipped, 0, 0, paint);
clipped.recycle();
return rounded;
}
public static int dp2px(Context context, int dp) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
public static float px2dp(Context context, int px) {
return ((float) px) / context.getResources().getDisplayMetrics().density;
}
/**
* Sets the alpha of a view, totally hiding the view if the alpha is so low
* as to be invisible, but also obeying intended visibility.
*/
public static void setViewAlpha(View v, float alpha, boolean visible) {
v.setAlpha(alpha);
if ((alpha < 0.001f) || !visible) {
v.setVisibility(View.GONE);
} else {
v.setVisibility(View.VISIBLE);
}
}
/**
* Set up our customised ActionBar view that features the specified icon and title, sized
* away from system standard to meet the NewsBlur visual style.
*/
public static void setCustomActionBar(Activity activity, String imageUrl, String title) {
ImageView iconView = setupCustomActionbar(activity, title);
FeedUtils.imageLoader.displayImage(imageUrl, iconView, false);
}
public static void setCustomActionBar(Activity activity, int imageId, String title) {
ImageView iconView = setupCustomActionbar(activity, title);
iconView.setImageResource(imageId);
}
private static ImageView setupCustomActionbar(final Activity activity, String title) {
// we completely replace the existing title and 'home' icon with a custom view
activity.getActionBar().setDisplayShowCustomEnabled(true);
activity.getActionBar().setDisplayShowTitleEnabled(false);
activity.getActionBar().setDisplayShowHomeEnabled(false);
View v = LayoutInflater.from(activity).inflate(R.layout.actionbar_custom_icon, null);
TextView titleView = ((TextView) v.findViewById(R.id.actionbar_text));
titleView.setText(title);
ImageView iconView = ((ImageView) v.findViewById(R.id.actionbar_icon));
// using a custom view breaks the system-standard ability to tap the icon or title to return
// to the previous activity. Re-implement that here.
titleView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
activity.finish();
}
});
iconView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
activity.finish();
}
});
activity.getActionBar().setCustomView(v, new ActionBar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
return iconView;
}
/**
* Shows a toast in a circumstance where the context might be null. This can very
* rarely happen when toasts are done from async tasks and the context is finished
* before the task completes, resulting in a crash. This prevents the crash at the
* cost of the toast not being shown.
*/
public static void safeToast(Context c, int rid, int duration) {
if (c != null) {
Toast.makeText(c, rid, duration).show();
}
}
public static void safeToast(Context c, String text, int duration) {
if ((c != null) && (text != null)) {
Toast.makeText(c, text, duration).show();
}
}
public static void restartActivity(final Activity activity) {
new Handler().post(new Runnable() {
@Override
public void run() {
Intent intent = activity.getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
activity.overridePendingTransition(0, 0);
activity.finish();
activity.overridePendingTransition(0, 0);
activity.startActivity(intent);
}
});
}
public static void startReadingActivity(FeedSet fs, String startingHash, Context context) {
Class activityClass;
if (fs.isAllSaved()) {
activityClass = SavedStoriesReading.class;
} else if (fs.getSingleSavedTag() != null) {
activityClass = SavedStoriesReading.class;
} else if (fs.isGlobalShared()) {
activityClass = GlobalSharedStoriesReading.class;
} else if (fs.isAllSocial()) {
activityClass = AllSharedStoriesReading.class;
} else if (fs.isAllNormal()) {
activityClass = AllStoriesReading.class;
} else if (fs.isFolder()) {
activityClass = FolderReading.class;
} else if (fs.getSingleFeed() != null) {
activityClass = FeedReading.class;
} else if (fs.getSingleSocialFeed() != null) {
activityClass = SocialFeedReading.class;
} else if (fs.isAllRead()) {
activityClass = ReadStoriesReading.class;
} else {
Log.e(UIUtils.class.getName(), "can't launch reading activity for unknown feedset type");
return;
}
Intent i = new Intent(context, activityClass);
i.putExtra(Reading.EXTRA_FEEDSET, fs);
i.putExtra(Reading.EXTRA_STORY_HASH, startingHash);
context.startActivity(i);
}
public static String getMemoryUsageDebug(Context context) {
String memInfo = " (";
android.app.ActivityManager activityManager = (android.app.ActivityManager) context.getSystemService(android.app.Activity.ACTIVITY_SERVICE);
int[] pids = new int[]{android.os.Process.myPid()};
android.os.Debug.MemoryInfo[] mi = activityManager.getProcessMemoryInfo(pids);
memInfo = memInfo + (mi[0].getTotalPss() / 1024) + "MB used)";
return memInfo;
}
@SuppressWarnings("deprecation")
public static int getColor(Context activity, int rid) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return activity.getResources().getColor(rid, activity.getTheme());
} else {
return activity.getResources().getColor(rid);
}
}
@SuppressWarnings("deprecation")
public static Drawable getDrawable(Context activity, int rid) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return activity.getResources().getDrawable(rid, activity.getTheme());
} else {
return activity.getResources().getDrawable(rid);
}
}
/**
* Sets the background resource of a view, working around a platform bug that causes the declared
* padding to get reset.
*/
public static void setViewBackground(View v, Drawable background) {
// due to a framework bug, the below modification of background resource also resets the declared
// padding on the view. save a copy of said padding so it can be re-applied after the change.
int oldPadL = v.getPaddingLeft();
int oldPadT = v.getPaddingTop();
int oldPadR = v.getPaddingRight();
int oldPadB = v.getPaddingBottom();
v.setBackground(background);
v.setPadding(oldPadL, oldPadT, oldPadR, oldPadB);
}
}
|
package ch.softappeal.yass.core.remote;
import ch.softappeal.yass.core.Interceptor;
import ch.softappeal.yass.util.Exceptions;
import ch.softappeal.yass.util.Nullable;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
public abstract class Client {
@FunctionalInterface public interface Tunnel {
void invoke(Request request) throws Exception;
}
public static final class Invocation extends AbstractInvocation {
private final @Nullable CompletableFuture<?> promise;
private final int serviceId;
Invocation(
final MethodMapper.Mapping methodMapping, final @Nullable Object[] arguments, final @Nullable InterceptorAsync<Object> interceptor,
final @Nullable CompletableFuture<?> promise, final int serviceId
) {
super(methodMapping, (arguments == null) ? List.of() : Arrays.asList(arguments), interceptor);
this.promise = promise;
this.serviceId = serviceId;
}
public void invoke(final boolean asyncSupported, final Tunnel tunnel) throws Exception {
if (async()) {
if (!asyncSupported) {
throw new UnsupportedOperationException("asynchronous services not supported (serviceId = " + serviceId + ')');
}
entry();
}
tunnel.invoke(new Request(serviceId, methodMapping.id, arguments));
}
@SuppressWarnings("unchecked")
public void settle(final Reply reply) throws Exception {
if (promise == null) {
return; // oneWay
}
try {
((CompletableFuture)promise).complete(async() ? exit(reply.process()) : reply.process());
} catch (final Exception e) {
promise.completeExceptionally(async() ? exception(e) : e);
}
}
}
/**
* @param invocation {@link Client.Invocation#invoke(boolean, Client.Tunnel)} must be called
*/
protected abstract void invoke(Invocation invocation) throws Exception;
protected Object invokeSync(final ContractId<?> contractId, final Interceptor interceptor, final Method method, final @Nullable Object[] arguments) throws Exception {
return interceptor.invoke(method, arguments, () -> {
final var methodMapping = contractId.methodMapper.mapMethod(method);
final @Nullable CompletableFuture<?> promise = methodMapping.oneWay ? null : new CompletableFuture<>();
invoke(new Invocation(methodMapping, arguments, null, promise, contractId.id));
if (promise == null) {
return null; // oneWay
}
try {
return promise.get();
} catch (final ExecutionException e) {
try {
throw e.getCause();
} catch (final Exception | Error e2) {
throw e2;
} catch (final Throwable t) {
throw new Error(t);
}
}
});
}
public final <C> C proxy(final ContractId<C> contractId, final Interceptor... interceptors) {
final var interceptor = Interceptor.composite(interceptors);
return contractId.contract.cast(Proxy.newProxyInstance(
contractId.contract.getClassLoader(),
new Class<?>[] {contractId.contract},
(proxy, method, arguments) -> invokeSync(contractId, interceptor, method, arguments)
));
}
private static @Nullable Object handlePrimitiveTypes(final Class<?> type) {
if (type == boolean.class) {
return Boolean.FALSE;
} else if (type == byte.class) {
return (byte)0;
} else if (type == short.class) {
return (short)0;
} else if (type == int.class) {
return 0;
} else if (type == long.class) {
return (long)0;
} else if (type == char.class) {
return (char)0;
} else if (type == float.class) {
return (float)0;
} else if (type == double.class) {
return (double)0;
}
return null;
}
private static final ThreadLocal<CompletableFuture<Object>> PROMISE = new ThreadLocal<>();
/**
* @see #promise(Execute)
* @see #proxyAsync(ContractId)
*/
@SuppressWarnings("unchecked")
public final <C> C proxyAsync(final ContractId<C> contractId, final InterceptorAsync<?> interceptor) {
Objects.requireNonNull(interceptor);
return contractId.contract.cast(Proxy.newProxyInstance(
contractId.contract.getClassLoader(),
new Class<?>[] {contractId.contract},
(proxy, method, arguments) -> {
final var methodMapping = contractId.methodMapper.mapMethod(method);
final var promise = PROMISE.get();
if (promise == null) {
if (!methodMapping.oneWay) {
throw new IllegalStateException("asynchronous request/reply proxy call must be enclosed with 'promise' method call");
}
} else if (methodMapping.oneWay) {
throw new IllegalStateException("asynchronous oneWay proxy call must not be enclosed with 'promise' method");
}
invoke(new Invocation(methodMapping, arguments, (InterceptorAsync)interceptor, promise, contractId.id));
return handlePrimitiveTypes(method.getReturnType());
}
));
}
/**
* @see #proxyAsync(ContractId, InterceptorAsync)
*/
public final <C> C proxyAsync(final ContractId<C> contractId) {
return proxyAsync(contractId, DirectInterceptorAsync.INSTANCE);
}
@FunctionalInterface public interface Execute<R> {
R execute() throws Exception;
}
/**
* Gets a promise for an asynchronous service invocation.
* The usage pattern is:
* <pre>
* EchoService echoService = client.proxyAsync(ECHO_SERVICE_ID);
* Client.promise(() -> echoService.echo("hello")).thenAccept(r -> System.out.println("result: " + r));
* </pre>
* @see #proxyAsync(ContractId)
* @see #promise(VoidExecute)
*/
@SuppressWarnings("unchecked")
public static <T> CompletionStage<T> promise(final Execute<T> execute) {
final var oldPromise = PROMISE.get();
final var promise = new CompletableFuture<>();
PROMISE.set(promise);
try {
execute.execute();
} catch (final Exception e) {
throw Exceptions.wrap(e);
} finally {
PROMISE.set(oldPromise);
}
return (CompletionStage)promise;
}
@FunctionalInterface public interface VoidExecute {
void execute() throws Exception;
}
/**
* @see #promise(Execute)
*/
public static CompletionStage<Void> promise(final VoidExecute execute) {
Objects.requireNonNull(execute);
return promise(() -> {
execute.execute();
return null;
});
}
}
|
package org.jetel.component;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.DataRecordFactory;
import org.jetel.data.Defaults;
import org.jetel.data.NullRecord;
import org.jetel.data.RecordKey;
import org.jetel.data.lookup.Lookup;
import org.jetel.data.lookup.LookupTable;
import org.jetel.exception.AttributeNotFoundException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.ConfigurationStatus.Priority;
import org.jetel.exception.ConfigurationStatus.Severity;
import org.jetel.exception.TransformException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.graph.modelview.MVMetadata;
import org.jetel.graph.modelview.impl.MetadataPropagationResolver;
import org.jetel.lookup.DBLookupTable;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.file.FileUtils;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.property.RefResFlag;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
public class LookupJoin extends Node implements MetadataProvider {
private static final String XML_LOOKUP_TABLE_ATTRIBUTE = "lookupTable";
private static final String XML_FREE_LOOKUP_TABLE_ATTRIBUTE = "freeLookupTable";
private static final String XML_JOIN_KEY_ATTRIBUTE = "joinKey";
private static final String XML_TRANSFORM_CLASS_ATTRIBUTE = "transformClass";
private static final String XML_TRANSFORM_ATTRIBUTE = "transform";
private static final String XML_TRANSFORMURL_ATTRIBUTE = "transformURL";
private static final String XML_CHARSET_ATTRIBUTE = "charset";
private static final String XML_LEFTOUTERJOIN_ATTRIBUTE = "leftOuterJoin";
private static final String XML_ERROR_ACTIONS_ATTRIBUTE = "errorActions";
private static final String XML_ERROR_LOG_ATTRIBUTE = "errorLog";
public final static String COMPONENT_TYPE = "LOOKUP_JOIN";
private final static int WRITE_TO_PORT = 0;
private final static int REJECTED_PORT = 1;
private final static int READ_FROM_PORT = 0;
private String transformClassName = null;
private RecordTransform transformation = null;
private String transformURL = null;
private String charset = null;
private String transformSource = null;
private String lookupTableName;
private boolean freeLookupTable = false;
private String[] joinKey;
private boolean leftOuterJoin = false;
private Properties transformationParameters = null;
private Lookup lookup;
private String errorActionsString;
private Map<Integer, ErrorAction> errorActions = new HashMap<Integer, ErrorAction>();
private String errorLogURL;
private FileWriter errorLog;
private RecordKey recordKey;
static Log logger = LogFactory.getLog(Reformat.class);
public LookupJoin(String id) {
super(id);
}
/**
* @param id component identification
* @param lookupTableName
* @param joinKey
* @param transform
* @param transformClass
*/
public LookupJoin(String id, String lookupTableName, String[] joinKey,
String transform, String transformClass, String transformURL) {
super(id);
this.lookupTableName = lookupTableName;
this.joinKey = joinKey;
this.transformClassName = transformClass;
this.transformSource = transform;
this.transformURL = transformURL;
}
public LookupJoin(String id, String lookupTableName, String[] joinKey,
RecordTransform transform) {
this(id, lookupTableName, joinKey, null, null, null);
this.transformation = transform;
}
@Override
public void preExecute() throws ComponentNotReadyException {
super.preExecute();
transformation.preExecute();
if (firstRun()) {//a phase-dependent part of initialization
//all necessary elements have been initialized in init()
}
else {
transformation.reset();
}
if (errorLogURL != null) {
try {
errorLog = new FileWriter(FileUtils.getFile(getGraph().getRuntimeContext().getContextURL(), errorLogURL));
} catch (IOException e) {
throw new ComponentNotReadyException(this, XML_ERROR_LOG_ATTRIBUTE, e);
}
}
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#postExecute(org.jetel.graph.TransactionMethod)
*/
@Override
public void postExecute() throws ComponentNotReadyException {
super.postExecute();
transformation.postExecute();
transformation.finished();
try {
if (errorLog != null) {
errorLog.close();
}
} catch (Exception e) {
//maybe this should be only logged and post execution should continue
throw new ComponentNotReadyException(e);
}
}
@Override
public Result execute() throws Exception {
// initialize in and out records
InputPort inPort = getInputPort(WRITE_TO_PORT);
DataRecord inRecord = DataRecordFactory.newRecord(inPort.getMetadata());
inRecord.init();
lookup = getGraph().getLookupTable(lookupTableName).createLookup(recordKey, inRecord);
OutputPort rejectedPort = getOutputPort(REJECTED_PORT);
DataRecord[] outRecord = { DataRecordFactory.newRecord(getOutputPort(READ_FROM_PORT)
.getMetadata()) };
outRecord[0].init();
outRecord[0].reset();
DataRecord[] inRecords = new DataRecord[] { inRecord, null };
int counter = 0;
// test if the lookup needs runtime metadata
LookupTable lookupTable = getGraph().getLookupTable(lookupTableName);
boolean createTransformation = runtimeMetadata(lookupTable);
while (inRecord != null && runIt) {
inRecord = inPort.readRecord(inRecord);
if (inRecord != null) {
// find slave record in database
lookup.seek();
inRecords[1] = lookup.hasNext() ? lookup.next() : NullRecord.NULL_RECORD;
// create the transformation
if (createTransformation){
// get metadata
DataRecordMetadata lookupMetadata = lookupTable.getMetadata();
DataRecordMetadata inMetadata[] = { getInputPort(READ_FROM_PORT).getMetadata(), lookupMetadata };
DataRecordMetadata outMetadata[] = { getOutputPort(WRITE_TO_PORT).getMetadata() };
// create the transformation
TransformFactory<RecordTransform> transformFactory = TransformFactory.createTransformFactory(RecordTransformDescriptor.newInstance());
transformFactory.setTransform(transformSource);
transformFactory.setTransformClass(transformClassName);
transformFactory.setTransformUrl(transformURL);
transformFactory.setCharset(charset);
transformFactory.setComponent(this);
transformFactory.setInMetadata(inMetadata);
transformFactory.setOutMetadata(outMetadata);
transformation = transformFactory.createTransform();
// init transformation
if (!transformation.init(transformationParameters, inMetadata, outMetadata)) {
throw new ComponentNotReadyException("Error when initializing tranformation function.");
}
createTransformation = false;
}
do {
if ((inRecords[1] != NullRecord.NULL_RECORD || leftOuterJoin)) {
outRecord[0].reset();
int transformResult = -1;
try {
transformResult = transformation.transform(inRecords, outRecord);
} catch (Exception exception) {
transformResult = transformation.transformOnError(exception, inRecords, outRecord);
}
if (transformResult >= 0) {
writeRecord(WRITE_TO_PORT, outRecord[0]);
}else if (transformResult < 0) {
ErrorAction action = errorActions.get(transformResult);
if (action == null) {
action = errorActions.get(Integer.MIN_VALUE);
if (action == null) {
action = ErrorAction.DEFAULT_ERROR_ACTION;
}
}
String message = "Transformation finished with code: " + transformResult + ". Error message: " +
transformation.getMessage();
if (action == ErrorAction.CONTINUE) {
if (errorLog != null){
errorLog.write(String.valueOf(counter));
errorLog.write(Defaults.Component.KEY_FIELDS_DELIMITER);
errorLog.write(String.valueOf(transformResult));
errorLog.write(Defaults.Component.KEY_FIELDS_DELIMITER);
message = transformation.getMessage();
if (message != null) {
errorLog.write(message);
}
errorLog.write(Defaults.Component.KEY_FIELDS_DELIMITER);
Object semiResult = transformation.getSemiResult();
if (semiResult != null) {
errorLog.write(semiResult.toString());
}
errorLog.write("\n");
} else {
//CL-2020
//if no error log is defined, the message is quietly ignored
//without messy logging in console
//only in case non empty message given from transformation, the message is printed out
if (!StringUtils.isEmpty(transformation.getMessage())) {
logger.warn(message);
}
}
} else {
throw new TransformException(message);
}
}
}else{
if (rejectedPort != null) {
writeRecord(REJECTED_PORT, inRecord);
}
}
// get next record from lookup table with the same key
inRecords[1] = lookup.hasNext() ? lookup.next() : NullRecord.NULL_RECORD;
} while (inRecords[1] != NullRecord.NULL_RECORD);
}
counter++;
}
if (freeLookupTable) {
lookup.getLookupTable().clear();
}
if (errorLog != null){
errorLog.flush();
errorLog.close();
}
broadcastEOF();
return runIt ? Result.FINISHED_OK : Result.ABORTED;
}
@Override
public void free() {
if (!isInitialized()) {
return;
}
super.free();
}
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if(!checkInputPorts(status, 1, 1) || !checkOutputPorts(status, 1, 2)) {
return status;
}
if (charset != null && !Charset.isSupported(charset)) {
status.add(new ConfigurationProblem(
"Charset "+charset+" not supported!",
ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL));
}
if (getOutputPort(REJECTED_PORT) != null) {
checkMetadata(status, getInputPort(READ_FROM_PORT).getMetadata(), getOutputPort(REJECTED_PORT).getMetadata());
}
if (errorActionsString != null){
try {
ErrorAction.checkActions(errorActionsString);
} catch (ComponentNotReadyException e) {
status.add(new ConfigurationProblem(e, Severity.ERROR, this, Priority.NORMAL, XML_ERROR_ACTIONS_ATTRIBUTE));
}
}
if (errorLog != null){
try {
FileUtils.canWrite(getGraph().getRuntimeContext().getContextURL(), errorLogURL);
} catch (ComponentNotReadyException e) {
status.add(new ConfigurationProblem(e, Severity.WARNING, this, Priority.NORMAL, XML_ERROR_LOG_ATTRIBUTE));
}
}
if (StringUtils.isEmpty(lookupTableName)) {
status.add(new ConfigurationProblem("Required lookup table is missing.", Severity.ERROR, this, Priority.NORMAL, XML_LOOKUP_TABLE_ATTRIBUTE));
} else {
LookupTable lookupTable = getGraph().getLookupTable(lookupTableName);
if (lookupTable == null) {
status.add(new ConfigurationProblem("Lookup table \"" + lookupTableName + "\" not found.", Severity.ERROR,
this, Priority.NORMAL));
} else if (transformation == null && !runtimeMetadata(lookupTable)) {
DataRecordMetadata[] inMetadata = { getInputPort(READ_FROM_PORT).getMetadata(), lookupTable.getMetadata() };
DataRecordMetadata[] outMetadata = { getOutputPort(WRITE_TO_PORT).getMetadata() };
//check transformation
getTransformFactory(inMetadata, outMetadata).checkConfig(status);
//check join key
try {
recordKey = new RecordKey(joinKey, inMetadata[0]);
recordKey.init();
} catch (Exception e) {
status.add(new ConfigurationProblem("Join key parsing error.", e, Severity.ERROR, this, Priority.NORMAL, XML_JOIN_KEY_ATTRIBUTE));
}
}
}
return status;
}
@Override
public void init() throws ComponentNotReadyException {
if(isInitialized()) return;
super.init();
// Initializing lookup table
LookupTable lookupTable = getGraph().getLookupTable(lookupTableName);
if (lookupTable == null) {
throw new ComponentNotReadyException("Lookup table \""
+ lookupTableName + "\" not found.");
}
if (!lookupTable.isInitialized()) {
lookupTable.init();
}
DataRecordMetadata lookupMetadata = lookupTable.getMetadata();
DataRecordMetadata inMetadata[] = { getInputPort(READ_FROM_PORT).getMetadata(), lookupMetadata };
DataRecordMetadata outMetadata[] = { getOutputPort(WRITE_TO_PORT).getMetadata() };
try {
recordKey = new RecordKey(joinKey, inMetadata[0]);
recordKey.init();
if (transformation == null && !runtimeMetadata(lookupTable)) {
transformation = getTransformFactory(inMetadata, outMetadata).createTransform();
}
// init transformation
if (transformation != null && !transformation.init(transformationParameters, inMetadata, outMetadata)) {
throw new ComponentNotReadyException("Error when initializing tranformation function.");
}
} catch (Exception e) {
throw new ComponentNotReadyException(this, e);
}
if (leftOuterJoin && getOutputPort(REJECTED_PORT) != null) {
logger.info(this.getId() + " info: There will be no skipped records " +
"while left outer join is switched on");
}
errorActions = ErrorAction.createMap(errorActionsString);
}
private TransformFactory<RecordTransform> getTransformFactory(DataRecordMetadata[] inMetadata, DataRecordMetadata[] outMetadata) {
TransformFactory<RecordTransform> transformFactory = TransformFactory.createTransformFactory(RecordTransformDescriptor.newInstance());
transformFactory.setTransform(transformSource);
transformFactory.setTransformClass(transformClassName);
transformFactory.setTransformUrl(transformURL);
transformFactory.setCharset(charset);
transformFactory.setComponent(this);
transformFactory.setInMetadata(inMetadata);
transformFactory.setOutMetadata(outMetadata);
return transformFactory;
}
/**
* Returns true if a lookup table doesn't have to have a metadata and doesn't have the metadata.
* @param lookupTable
* @return
*/
private boolean runtimeMetadata(LookupTable lookupTable) {
return lookupTable instanceof DBLookupTable && lookupTable.getMetadata() == null;
}
@Override
public synchronized void reset() throws ComponentNotReadyException {
super.reset();
}
public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException, AttributeNotFoundException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
LookupJoin join;
String[] joinKey;
// get necessary parameters
joinKey = xattribs.getString(XML_JOIN_KEY_ATTRIBUTE).split(
Defaults.Component.KEY_FIELDS_DELIMITER_REGEX);
join = new LookupJoin(xattribs.getString(XML_ID_ATTRIBUTE),
xattribs.getString(XML_LOOKUP_TABLE_ATTRIBUTE), joinKey,
xattribs.getStringEx(XML_TRANSFORM_ATTRIBUTE, null, RefResFlag.SPEC_CHARACTERS_OFF),
xattribs.getString(XML_TRANSFORM_CLASS_ATTRIBUTE, null),
xattribs.getStringEx(XML_TRANSFORMURL_ATTRIBUTE, null, RefResFlag.URL));
join.setCharset(xattribs.getString(XML_CHARSET_ATTRIBUTE, null));
join.setTransformationParameters(xattribs
.attributes2Properties(new String[] { XML_TRANSFORM_CLASS_ATTRIBUTE }));
if (xattribs.exists(XML_LEFTOUTERJOIN_ATTRIBUTE)) {
join.setLeftOuterJoin(xattribs
.getBoolean(XML_LEFTOUTERJOIN_ATTRIBUTE));
}
join.setFreeLookupTable(xattribs.getBoolean(
XML_FREE_LOOKUP_TABLE_ATTRIBUTE, false));
if (xattribs.exists(XML_ERROR_ACTIONS_ATTRIBUTE)){
join.setErrorActions(xattribs.getString(XML_ERROR_ACTIONS_ATTRIBUTE));
}
if (xattribs.exists(XML_ERROR_LOG_ATTRIBUTE)){
join.setErrorLog(xattribs.getString(XML_ERROR_LOG_ATTRIBUTE));
}
return join;
}
public void setErrorLog(String errorLog) {
this.errorLogURL = errorLog;
}
public void setErrorActions(String string) {
this.errorActionsString = string;
}
/**
* @param transformationParameters
* The transformationParameters to set.
*/
public void setTransformationParameters(Properties transformationParameters) {
this.transformationParameters = transformationParameters;
}
public void setLeftOuterJoin(boolean leftOuterJoin) {
this.leftOuterJoin = leftOuterJoin;
}
public void setFreeLookupTable(boolean freeLookupTable) {
this.freeLookupTable = freeLookupTable;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
@Override
public MVMetadata getInputMetadata(int portIndex, MetadataPropagationResolver metadataPropagationResolver) {
if (portIndex == 0) {
if (getOutputPort(1) != null) {
return metadataPropagationResolver.findMetadata(getOutputPort(1).getEdge());
}
}
return null;
}
@Override
public MVMetadata getOutputMetadata(int portIndex, MetadataPropagationResolver metadataPropagationResolver) {
if (portIndex == 1) {
if (getInputPort(0) != null) {
return metadataPropagationResolver.findMetadata(getInputPort(0).getEdge());
}
}
return null;
}
}
|
package org.cactoos.iterator;
import java.util.Arrays;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.cactoos.list.ListOf;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test for {@link SyncIterator}.
*
* @author Sven Diedrichsen (sven.diedrichsen@gmail.com)
* @version $Id$
* @since 1.0
* @checkstyle JavadocMethodCheck (500 lines)
* @checkstyle MagicNumberCheck (500 lines)
* @checkstyle TodoCommentCheck (500 lines)
*/
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public final class SyncIteratorTest {
/**
* TODO: There needs to more tests which test for multi-threaded safety
* when accessing the iterator.
*/
@Test
public void syncIteratorReturnsCorrectValuesWithExternalLock() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
MatcherAssert.assertThat(
"Unexpected value found.",
new ListOf<>(
new SyncIterator<>(
Arrays.asList("a", "b").iterator(), lock
)
).toArray(),
Matchers.equalTo(new Object[]{"a", "b"})
);
}
@Test
public void syncIteratorReturnsCorrectValuesWithInternalLock() {
MatcherAssert.assertThat(
"Unexpected value found.",
new ListOf<>(
new SyncIterator<>(
Arrays.asList("a", "b").iterator()
)
).toArray(),
Matchers.equalTo(new Object[]{"a", "b"})
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.