answer stringlengths 17 10.2M |
|---|
package eu.matejkormuth.rpbuild;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.matejkormuth.rpbuild.BuildStep.CompileBuildStep;
import eu.matejkormuth.rpbuild.BuildStep.GenerateBuildStep;
import eu.matejkormuth.rpbuild.compilers.JsonCompressor;
import eu.matejkormuth.rpbuild.generators.PackMcMetaGenerator;
import eu.matejkormuth.rpbuild.generators.StarvingSoundsJsonGenerator;
/**
* Represents main part of build system. Assembles files and manages build
* process and logging.
*/
public class Assembler {
private static final Logger log = LoggerFactory.getLogger(Assembler.class);
private List<Generator> generators;
private List<FileExtensionCompilerList> compilerLists;
private FileFinder fileFinder;
private SimpleDateFormat dateTimeFormat;
private SimpleDateFormat timeSpanFormat;
private Options options;
public Assembler(Options options) {
this.generators = new ArrayList<Generator>();
this.compilerLists = new ArrayList<FileExtensionCompilerList>();
this.dateTimeFormat = new SimpleDateFormat();
this.timeSpanFormat = new SimpleDateFormat("mm:ss.SSS");
this.options = options;
this.addBuildStep(BuildStep.generate(new PackMcMetaGenerator()));
this.addBuildStep(BuildStep.generate(new StarvingSoundsJsonGenerator()));
this.addBuildStep(BuildStep.compile(new JsonCompressor(), ".json"));
this.fileFinder = new FileFinder();
this.fileFinder.setIgnoreGit(this.options.ignoreGit);
}
private void findFiles() {
log.info("Looking for files...");
try {
int count = this.fileFinder.find(this.options.root);
log.info("Found {} files!", count);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build() {
printBuildStart();
long startTime = System.currentTimeMillis();
if(this.options.gitPull) {
log.info("Git pull is enabled in this build! Pulling using shell command (git pull).");
try {
Process gitProcess = Runtime.getRuntime().exec("git pull");
int exitCode = gitProcess.waitFor();
log.info("Git process exited with exit code {}.", exitCode);
} catch (IOException | InterruptedException e) {
log.error("Can't complete git pull! Giving up!", e);
printBuildEnd(System.currentTimeMillis() - startTime, "FAILURE");
}
printSeparator();
}
this.findFiles();
try {
this.generateFiles();
this.printSeparator();
this.findFiles();
this.buildFiles();
this.assembly();
this.printSeparator();
this.findFiles();
this.archive();
} catch (BuildError error) {
log.error("Build failed: ", error);
printBuildEnd(System.currentTimeMillis() - startTime, "FAILURE");
return;
}
long elapsedTime = System.currentTimeMillis() - startTime;
printBuildEnd(elapsedTime, "SUCCESS");
}
private void printBuildEnd(long elapsedTime, String status) {
printSeparator();
log.info("Build of project {} finished!", options.projectName);
printSeparator();
log.info("Status: {}", status);
log.info("Memory: {} MB / {} MB",
(Runtime.getRuntime().totalMemory() - Runtime.getRuntime()
.freeMemory()) / 1024 / 1024, Runtime.getRuntime()
.totalMemory() / 1024 / 1024);
log.info("Total time: {}",
this.timeSpanFormat.format(new Date(elapsedTime)));
printSeparator();
}
private void printBuildStart() {
printSeparator();
log.info("Build of project " + options.projectName + " started at "
+ this.dateTimeFormat.format(new Date()));
log.info("Used charset/encoding: " + this.options.encoding);
printSeparator();
}
private void printSeparator() {
log.info("
}
private void generateFiles() {
printSeparator();
int count = 0;
for (Generator g : this.generators) {
log.info("Running generator: {}", g.getClass().getSimpleName());
try {
GeneratedFile file = g.generate();
if (file == null) {
log.warn("Generator {} generated null file!", g.getClass()
.getSimpleName());
continue;
}
this.saveFile(file);
count++;
} catch (Exception e) {
throw new BuildError(e);
}
}
log.info("Totally generated {} files!", count);
}
private void buildFiles() {
printSeparator();
log.info("Compiling files...");
int count = 0;
for (FileExtensionCompilerList list : this.compilerLists) {
List<Path> paths = this.fileFinder
.getPaths(list.getFileExtension());
for (Compiler c : list) {
int ccount = 0;
for (Path path : paths) {
c.compile(path);
count++;
ccount++;
}
log.info("Compiled {} files with {}.", ccount, c.getClass()
.getSimpleName());
}
}
log.info("Totally compiled {} files!", count);
}
private void assembly() {
printSeparator();
log.info("Assembling files together...");
}
private void archive() {
printSeparator();
log.info("Archiving assebled files to zip file...");
log.info("File name: {}", this.options.zipName);
try {
int count = 0;
ZipArchive zipper = new ZipArchive(
this.options.root.toAbsolutePath(), new File(
this.options.zipName));
for (Path path : this.fileFinder.getPaths()) {
if (!isFiltered(path)) {
zipper.addFile(path);
count++;
}
}
zipper.close();
log.info("Created archive with {} files!", count);
} catch (Exception e) {
throw new BuildError(e);
}
}
private boolean isFiltered(Path path) {
for (String endFilter : this.options.fileFilters) {
if (path.toString().endsWith(endFilter)) {
return true;
}
}
return false;
}
private void saveFile(GeneratedFile file) {
try {
Files.write(this.options.root.resolve(Paths.get(file.getName())
.toAbsolutePath()), file.getContents(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE);
} catch (IOException e) {
throw new BuildError(e);
}
}
public void addBuildStep(BuildStep buildStep) {
if (buildStep instanceof CompileBuildStep) {
this.addCompileStep(((CompileBuildStep) buildStep).getCompiler(),
((CompileBuildStep) buildStep).getFileTypes());
} else if (buildStep instanceof GenerateBuildStep) {
this.addGenerateStep(((GenerateBuildStep) buildStep).getGenerator());
} else {
// Unsupported type.
log.warn("Tried to register unsupported build step: {}", buildStep
.getClass().getSimpleName());
}
}
private void addCompileStep(Compiler compiler, String... fileExtensions) {
for (String fileExtension : fileExtensions) {
this.addCompileStep(compiler, fileExtension);
}
}
private void addCompileStep(Compiler compiler, String fileExtension) {
FileExtensionCompilerList compilerList = findBuilder(fileExtension);
if (compilerList == null) {
FileExtensionCompilerList newList = new FileExtensionCompilerList(
fileExtension);
compiler.setAssembler(this);
newList.add(compiler);
this.compilerLists.add(newList);
} else {
compilerList.add(compiler);
}
}
private void addGenerateStep(Generator generator) {
generator.setAssembler(this);
this.generators.add(generator);
}
private FileExtensionCompilerList findBuilder(String fileExtension) {
for (FileExtensionCompilerList b : this.compilerLists) {
if (b.getFileExtension().equalsIgnoreCase(fileExtension)) {
return b;
}
}
return null;
}
public Options getOptions() {
return this.options;
}
public Charset getCharset() {
return Charset.forName(this.options.encoding);
}
public Path getSourcePath() {
return this.options.root;
}
public Path getTargetPath() {
return this.options.target;
}
} |
package eu.matejkormuth.rpbuild;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.matejkormuth.rpbuild.api.BuildStep;
import eu.matejkormuth.rpbuild.api.BuildStepCompile;
import eu.matejkormuth.rpbuild.api.BuildStepGenerate;
import eu.matejkormuth.rpbuild.api.Project;
import eu.matejkormuth.rpbuild.api.Setting;
import eu.matejkormuth.rpbuild.exceptions.BuildError;
import eu.matejkormuth.rpbuild.exceptions.InvalidComponentError;
import eu.matejkormuth.rpbuild.exceptions.InvalidSettingsError;
/**
* Represents main part of build system. Assembles files and manages build
* process and logging.
*/
public class Assembler {
private static final Logger log = LoggerFactory.getLogger(Assembler.class);
// List of all generator that should be run.
private List<Generator> generators;
// List of all pairs file extension - compiler(s) that should be run.
private List<CompilerListByFileExtension> compilerLists;
private FileFinder fileFinder;
private SimpleDateFormat dateTimeFormat;
private SimpleDateFormat timeSpanFormat;
// Build descriptor.
private Project project;
public Assembler(Project project) {
// Create instances.
this.generators = new ArrayList<Generator>();
this.compilerLists = new ArrayList<CompilerListByFileExtension>();
this.dateTimeFormat = new SimpleDateFormat();
this.timeSpanFormat = new SimpleDateFormat("mm:ss.SSS");
this.project = project;
// Add build steps.
for (BuildStep step : this.project.getBuild()) {
try {
this.addBuildStep(step);
} catch (InvalidSettingsError | InvalidComponentError e) {
log.error("Can't initialize build object graph!");
log.error("There is unresolved configuration error(s)!");
log.error("Exception: ", e);
terminate();
}
}
// Initialize file finder.
this.fileFinder = new FileFinder();
this.fileFinder.setIgnoreGit(this.project.isIgnoreGitFolders());
}
public void build() {
printBuildStart();
// Create temp directory to store files before putting in zip.
Path tempDirectory = null;
try {
tempDirectory = createTempDirectory();
// Request folder removal on rpbuild's exit.
tempDirectory.toFile().deleteOnExit();
} catch (BuildError e) {
log.error("Can't create temporary folder!", e);
printBuildEnd(0, "FAILURE");
terminate();
}
long startTime = System.currentTimeMillis();
// First execute git pull.
if (this.project.isGitPull()) {
log.info("Git pull is enabled in this build! Pulling using shell commands (git stash drop & git pull).");
try {
log.info("Executing: git stash save --keep-index.");
Runtime.getRuntime().exec("git stash save --keep-index")
.waitFor();
log.info("Executing: git stash drop.");
Runtime.getRuntime().exec("git stash drop").waitFor();
log.info("Executing: git pull.");
Process gitProcess = Runtime.getRuntime().exec("git pull");
int exitCode = gitProcess.waitFor();
log.info("Git process exited with exit code {}.", exitCode);
} catch (IOException | InterruptedException e) {
log.error("Can't complete git pull! Giving up!", e);
printBuildEnd(System.currentTimeMillis() - startTime, "FAILURE");
terminate();
}
printSeparator();
}
// Copy all files to temp directory.
try {
final Path sourcePath = this.getProject().getSrc();
final Path targetPath = tempDirectory;
Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(final Path dir,
final BasicFileAttributes attrs) throws IOException {
// Ignore .git direcoties, we do not need to copy them.
if (dir.getFileName().toString().equalsIgnoreCase(".git")) {
return FileVisitResult.SKIP_SUBTREE;
}
Files.createDirectories(targetPath.resolve(sourcePath
.relativize(dir)));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
Files.copy(file,
targetPath.resolve(sourcePath.relativize(file)));
return FileVisitResult.CONTINUE;
}
});
} catch (Exception e) {
log.error("Can't copy source files to temporary folder!", e);
printBuildEnd(System.currentTimeMillis() - startTime, "FAILURE");
terminate();
}
// Set source in this instance of project to temp directory.
// This way all components will work as supposed because they
// are working relative to project's src path.
try {
Field srcField = this.project.getClass().getDeclaredField("src");
if (!srcField.isAccessible())
srcField.setAccessible(true);
srcField.set(this.project, tempDirectory);
} catch (Exception e) {
log.error("Internal error: Can't set project src to temp folder.",
e);
printBuildEnd(System.currentTimeMillis() - startTime, "FAILURE");
// Terminate VM.
terminate();
}
try {
// Generate new files.
this.taskGenerate();
this.printSeparator();
// Find new generated files and files from git.
this.findFiles();
// Compiler files.
this.taskCompile();
// Assembly files in temporary directory (currently not used).
this.taskAssembly();
this.printSeparator();
// Find new files.
this.findFiles();
// Archive files to ZIP.
this.taskArchive();
} catch (BuildError error) {
// If some error(s) occurred, output them now.
log.error("Build failed: ", error);
printBuildEnd(System.currentTimeMillis() - startTime, "FAILURE");
terminate();
}
// Looks like everything went normally.
long elapsedTime = System.currentTimeMillis() - startTime;
printBuildEnd(elapsedTime, "SUCCESS");
}
// This method is overridden in rpbuild-maven
// to not make Maven exit too, when rpbuild shuts down.
public void terminate() {
System.exit(1);
}
private Path createTempDirectory() throws BuildError {
try {
return Files.createTempDirectory("rpbuild_"
+ this.project.getProjectName().toLowerCase()
.replace(" ", "_").substring(0, 5));
} catch (IOException e) {
throw new BuildError("Can't create temporary directory!", e);
}
}
private void printBuildEnd(long elapsedTime, String status) {
printSeparator();
log.info("Build of project {} had finished!", project.getProjectName());
printSeparator();
log.info("Status: {}", status);
log.info("Memory: {} MB / {} MB",
(Runtime.getRuntime().totalMemory() - Runtime.getRuntime()
.freeMemory()) / 1024 / 1024, Runtime.getRuntime()
.totalMemory() / 1024 / 1024);
log.info("Total time: {}",
this.timeSpanFormat.format(new Date(elapsedTime)));
printSeparator();
}
private void printBuildStart() {
printSeparator();
log.info("Build of project " + project.getProjectName()
+ " was started at " + this.dateTimeFormat.format(new Date()));
log.info("Used charset/encoding: " + this.project.getEncoding());
printSeparator();
}
private void printSeparator() {
log.info("
}
private void findFiles() throws BuildError {
log.info("Looking for files...");
try {
int count = this.fileFinder.find(this.project.getSrc());
log.info("Found {} files!", count);
} catch (IOException e) {
throw new BuildError(e);
}
}
private void taskGenerate() throws BuildError {
printSeparator();
int count = 0;
// Run all generators.
for (Generator g : this.generators) {
log.info("Running generator: {}", g.getClass().getSimpleName());
// Request generator to generate file.
OpenedFile file = g.generate();
// Check for null.
if (file == null) {
log.warn("Generator {} generated null file!", g.getClass()
.getSimpleName());
// Skip to next generator without saving.
continue;
}
// Save generated file.
file.save();
// Increment generated files count.
count++;
}
log.info("Totally generated {} files!", count);
}
private void taskCompile() throws BuildError {
printSeparator();
log.info("Compiling files...");
int count = 0;
// For each extension compiler list.
for (CompilerListByFileExtension list : this.compilerLists) {
// Find all matching files.
List<Path> matchingFiles = this.fileFinder.getPaths(list
.getFileExtension());
OpenedFile currentFile;
for (Path path : matchingFiles) {
count++;
currentFile = new OpenedFile(path);
for (Compiler c : list) {
c.compile(currentFile);
}
currentFile.save();
}
}
log.info("Totally compiled {} files!", count);
}
private void taskAssembly() {
printSeparator();
log.info("Assembling files together...");
}
private void taskArchive() throws BuildError {
printSeparator();
log.info("Archiving assebled files to zip file...");
log.info("File name: {}", this.project.getTarget().toString());
int count = 0;
ZipArchive zipper = new ZipArchive(this.project.getSrc()
.toAbsolutePath(), this.project.getTarget().toFile(),
this.project.getCompressionLevel());
// Add files to zip.
try {
for (Path path : this.fileFinder.getPaths()) {
if (!isFiltered(path)) {
zipper.addFile(path);
count++;
}
}
} catch (IOException e) {
throw new BuildError("Can't build zip file!", e);
}
zipper.close();
log.info("Created archive with {} files!", count);
}
private boolean isFiltered(Path path) {
for (String endFilter : this.project.getFilters()) {
if (path.toString().endsWith(endFilter)) {
return true;
}
}
return false;
}
public void addBuildStep(BuildStep buildStep) throws InvalidSettingsError,
InvalidComponentError {
// If-else for different build steps.
if (buildStep instanceof BuildStepCompile) {
// Add compile type step.
this.addCompileStep(((BuildStepCompile) buildStep).getCompiler(),
((BuildStepCompile) buildStep).getFileTypes()[0],
((BuildStepCompile) buildStep).getSettings());
} else if (buildStep instanceof BuildStepGenerate) {
// Add generate type step.
this.addGenerateStep(
((BuildStepGenerate) buildStep).getGenerator(),
((BuildStepGenerate) buildStep).getSettings());
} else {
// Unsupported type.
log.warn("Tried to register unsupported build step: {}", buildStep
.getClass().getSimpleName());
}
}
private void addCompileStep(Compiler compiler, String fileExtension,
Setting[] settings) throws InvalidSettingsError {
// Acquire list for this file extension.
CompilerListByFileExtension compilerList = getOrCreateCompilerList(fileExtension);
// Setup compiler.
compiler.setAssembler(this);
compiler.setSettings(settings);
compiler.onInit();
// Add compiler to list.
compilerList.add(compiler);
}
private void addGenerateStep(Generator generator, Setting[] settings)
throws InvalidSettingsError {
// Set up generator.
generator.setAssembler(this);
generator.setSettings(settings);
generator.onInit();
// Add generator to list.
this.generators.add(generator);
}
private CompilerListByFileExtension getOrCreateCompilerList(
String fileExtension) {
// Search for list where file extension is same.
for (CompilerListByFileExtension b : this.compilerLists) {
if (b.getFileExtension().equalsIgnoreCase(fileExtension)) {
return b;
}
}
// We need to create new list.
CompilerListByFileExtension list = new CompilerListByFileExtension(
fileExtension);
// Add created list to compiler lists.
this.compilerLists.add(list);
// Return newly created list.
return list;
}
public Project getProject() {
return this.project;
}
public Charset getCharset() {
return this.project.getCharset();
}
public Path getSourcePath() {
return this.project.getSrc();
}
} |
package hu.bme.mit.spaceship;
import java.util.Random;
/**
* Class storing and managing the torpedos of a ship
*/
public class TorpedoStore {
private int torpedos = 0;
private Random generator = new Random();
public TorpedoStore(int numberOfTorpedos){
this.torpedos = numberOfTorpedos;
}
public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedos){
throw new IllegalArgumentException("numberOfTorpedos");
}
boolean success;
//simulate random overheating of the launcher bay which prevents firing
double r = generator.nextDouble();
if (r > 0.1) {
// successful firing
this.torpedos -= numberOfTorpedos;
success = true;
} else {
// failure
success = false;
}
return success;
}
public boolean isEmpty(){
return this.torpedos <= 0;
}
public int getNumberOfTorpedos() {
return this.torpedos;
}
} |
package hu.unideb.inf.View;
import hu.unideb.inf.Core.Main;
import hu.unideb.inf.Core.Ship;
import hu.unideb.inf.Dao.HighScore;
import hu.unideb.inf.Dao.HighScoreDAOImp;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Background;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import static hu.unideb.inf.Core.Main.*;
/**
* The {@code ViewController} class implement the graphical elements.
* @author MJ
*/
public class ViewController {
/** {@link Logger} for logging.*/
private static Logger logger = LoggerFactory.getLogger( Main.class );
private HighScoreDAOImp highScoreDAOImp = new HighScoreDAOImp();
private ArrayList<HighScore> highScoreArrayList;
private ObservableList<HighScore> lista;
/** "Description" label. */
public Label descLabel = new Label("Flappy spaceship");
/** "Score" label. */
public static Label scoreLabel = new Label("Score: " + score);
/** "Fail" label. */
public Label failLabel = new Label("FAIL");
/** "New Game" label. */
public Label newGameLabel = new Label("New Game");
/** "HighScore" label. */
public Label highScoreLabel = new Label("HighScore");
/** "Exit" label. */
public Label exitLabel = new Label("Exit");
/** "Options" label. */
public Label optionsLabel = new Label("Options");
/** "Back" label. */
public Label backLabel = new Label("< Back");
/** "Sound" label. */
public Label soundText = new Label("Sound:");
/** "Leadboard" label. */
public Label leadBoardLabel = new Label("Add to leadboard");
/** "Done" label. */
public Label doneLabel = new Label("Done");
/** "Name" label. */
public Label playerNameLabel = new Label("Name:");
/** "Resume" label. */
public Label resumeLabel = new Label("Resume");
/** Sound on/off button. */
public static RadioButton onButton = new RadioButton("ON");
/** Name field. */
public TextField playerName = new TextField();
/** Highscore table. */
public TableView<HighScore> tableView = new TableView<>();
/** Name of the player. */
private static String player;
/** Creates an empty instance of {@code ViewController}. */
public ViewController() {
init();
initTable();
}
/** Set the stlye to the elements. */
private void init() {
playerNameLabel.setStyle("-fx-translate-x: 310; -fx-translate-y: 405; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
playerNameLabel.setVisible(false);
playerName.setBackground(Background.EMPTY);
playerName.setStyle("-fx-translate-x: 410; -fx-translate-y: 400; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
playerName.setVisible(false);
doneLabel.setStyle("-fx-translate-x: 340; -fx-translate-y: 550; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
doneLabel.setVisible(false);
leadBoardLabel.setStyle("-fx-translate-x: 250; -fx-translate-y: 350; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
leadBoardLabel.setVisible(false);
soundText.setStyle("-fx-translate-x: 310; -fx-translate-y: 405; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
soundText.setVisible(false);
onButton.getStyleClass().remove("radio-button");
onButton.getStyleClass().add("toggle-button");
onButton.setBackground(Background.EMPTY);
onButton.setStyle("-fx-translate-x: 430; -fx-translate-y: 400; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
onButton.setVisible(false);
scoreLabel.setStyle("-fx-translate-x: 600; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
descLabel.setStyle("-fx-translate-x: 80; -fx-translate-y: 250; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 40px;");
descLabel.setVisible(false);
failLabel.setStyle("-fx-translate-x: 300; -fx-translate-y: 200; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 60px;");
failLabel.setVisible(false);
resumeLabel.setStyle("-fx-translate-x: 345; -fx-translate-y: 350; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
resumeLabel.setVisible(false);
newGameLabel.setStyle("-fx-translate-x: 330; -fx-translate-y: 400; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
newGameLabel.setVisible(false);
highScoreLabel.setStyle("-fx-translate-x: 320; -fx-translate-y: 450; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
highScoreLabel.setVisible(false);
exitLabel.setStyle("-fx-translate-x: 370; -fx-translate-y: 550; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
exitLabel.setVisible(false);
backLabel.setStyle("-fx-translate-x: 340; -fx-translate-y: 550; -fx-text-fill: white; -fx-font-family: 'Press Start 2P'; -fx-font-size: 20px;");
backLabel.setVisible(false);
optionsLabel.setFont(Font.font("Press Start 2P", 20));
optionsLabel.setTextFill(Color.WHITE);
optionsLabel.setTranslateX(340);
optionsLabel.setTranslateY(500);
optionsLabel.setVisible(false);
tableView.setStyle("-fx-font-family: 'Press Start 2P'; -fx-font-size: 20px; -fx-text-fill: white; " +
"-fx-background-color: transparent; -fx-base: rgba(0,0,0,0);"+
"-fx-table-header-border-color: transparent; -fx-border-color: transparent; " +
"-fx-table-cell-border-color: transparent; -fx-control-inner-background: transparent;" +
"-fx-translate-x: 240; -fx-translate-y: 300; -fx-pref-width: 450; -fx-pref-height: 262;");
tableView.setVisible(false);
tableView.setSelectionModel(null);
}
/** Initialize the table and load content. */
private void initTable() {
TableColumn name = new TableColumn("");
name.setMinWidth(100);
name.setCellValueFactory(
new PropertyValueFactory<>("name"));
TableColumn score = new TableColumn("");
score.setMinWidth(50);
score.setCellValueFactory(
new PropertyValueFactory<>("score"));
tableView.getColumns().addAll(name, score);
score.setStyle("-fx-background-color: transparent;");
name.setStyle("-fx-background-color: transparent;");
highScoreArrayList = highScoreDAOImp.getAllHighScores().getHighScore();
lista = FXCollections.observableArrayList();
for (HighScore highScore : highScoreArrayList) {
lista.add(highScore);
}
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
tableView.setItems(lista);
}
/** Refreshing the content of the table. */
public void refreshTable(){
logger.debug("Refreshing table...");
highScoreArrayList = highScoreDAOImp.getAllHighScores().getHighScore();
lista = FXCollections.observableArrayList();
for (HighScore highScore : highScoreArrayList) {
lista.add(highScore);
}
tableView.setItems(lista);
//tableView.refresh();
logger.debug("Table refreshed.");
}
/** Hide the specified labels. */
private void hideLabels() {
descLabel.setVisible(false);
failLabel.setVisible(false);
newGameLabel.setVisible(false);
highScoreLabel.setVisible(false);
optionsLabel.setVisible(false);
exitLabel.setVisible(false);
leadBoardLabel.setVisible(false);
doneLabel.setVisible(false);
playerName.setVisible(false);
playerNameLabel.setVisible(false);
resumeLabel.setVisible(false);
tableView.setVisible(false);
}
/**
* Play scale effect to the newGameLabel or begins a new game.
* @param ship The spaceship.
*/
public void newGame(Ship ship) {
if (!backLabel.isVisible())
newGameLabel.setVisible(true);
newGameLabel.setOnMouseEntered(MouseEvent -> {
newGameLabel.setScaleX(1.5);
newGameLabel.setScaleY(1.5);
});
newGameLabel.setOnMouseExited(MouseEvent -> {
newGameLabel.setScaleX(1);
newGameLabel.setScaleY(1);
});
newGameLabel.setOnMouseClicked(MouseEvent -> {
logger.info("New game.");
if (!failGame) {
running = true;
score = 0;
hideLabels();
} else if (failGame) {
running = true;
ship.shipNull();
score = 0;
hideLabels();
}
});
}
/** Play scale effect to the {@link ViewController#highScoreLabel} or refreshing the content. */
public void highScore() {
if (!backLabel.isVisible())
highScoreLabel.setVisible(true);
highScoreLabel.setOnMouseEntered(MouseEvent -> {
highScoreLabel.setScaleX(1.5);
highScoreLabel.setScaleY(1.5);
});
highScoreLabel.setOnMouseExited(MouseEvent -> {
highScoreLabel.setScaleX(1);
highScoreLabel.setScaleY(1);
});
highScoreLabel.setOnMouseClicked(MouseEvent -> {
logger.info("Highscore menu.");
isHighScore = true;
refreshTable();
highScoreLabel.setTranslateX(320);
highScoreLabel.setTranslateY(250);
tableView.setVisible(true);
backLabel.setVisible(true);
failLabel.setVisible(false);
newGameLabel.setVisible(false);
highScoreLabel.setVisible(true);
optionsLabel.setVisible(false);
exitLabel.setVisible(false);
leadBoardLabel.setVisible(false);
doneLabel.setVisible(false);
playerName.setVisible(false);
playerNameLabel.setVisible(false);
resumeLabel.setVisible(false);
backMenu();
});
}
/** Play scale effect to the {@link ViewController#optionsLabel} or opening the options menu. */
public void optionsMenu() {
if (!backLabel.isVisible())
optionsLabel.setVisible(true);
optionsLabel.setOnMouseEntered(MouseEvent -> {
optionsLabel.setScaleX(1.5);
optionsLabel.setScaleY(1.5);
});
optionsLabel.setOnMouseExited(MouseEvent -> {
optionsLabel.setScaleX(1);
optionsLabel.setScaleY(1);
});
optionsLabel.setOnMouseClicked(MouseEvent -> {
logger.info("Options menu.");
isOptions = true;
optionsLabel.setFont(Font.font("Press Start 2P", 40));
optionsLabel.setTranslateX(270);
optionsLabel.setTranslateY(300);
backLabel.setVisible(true);
failLabel.setVisible(false);
newGameLabel.setVisible(false);
highScoreLabel.setVisible(false);
leadBoardLabel.setVisible(false);
exitLabel.setVisible(false);
soundText.setVisible(true);
onButton.setVisible(true);
doneLabel.setVisible(false);
playerName.setVisible(false);
playerNameLabel.setVisible(false);
resumeLabel.setVisible(false);
tableView.setVisible(false);
backMenu();
});
}
/** Play scale effect to the {@link ViewController#exitLabel} or close the game. */
public void exit() {
if (!backLabel.isVisible())
exitLabel.setVisible(true);
exitLabel.setOnMouseEntered(MouseEvent -> {
exitLabel.setScaleX(1.5);
exitLabel.setScaleY(1.5);
});
exitLabel.setOnMouseExited(MouseEvent -> {
exitLabel.setScaleX(1);
exitLabel.setScaleY(1);
});
exitLabel.setOnMouseClicked(MouseEvent -> {
logger.info("Exiting application!");
System.exit(0);
});
}
/** Play scale effect to the {@link ViewController#backLabel} or back to the previous menu. */
public void backMenu() {
backLabel.setOnMouseEntered(MouseEvent -> {
backLabel.setScaleY(1.5);
backLabel.setScaleX(1.5);
});
backLabel.setOnMouseExited(MouseEvent -> {
backLabel.setScaleX(1);
backLabel.setScaleY(1);
});
backLabel.setOnMouseClicked(MouseEvent -> {
logger.debug("Back to a previous menu.");
isOptions = false;
isHighScore = false;
if (!running && !failGame) {
descLabel.setVisible(true);
} else {
failLabel.setVisible(true);
}
if (!isOptions) {
optionsLabel.setFont(Font.font("Press Start 2P", 20));
optionsLabel.setTranslateX(340);
optionsLabel.setTranslateY(500);
}
if (!isHighScore) {
leadBoardLabel.setVisible(false);
}
if (score > 0 && isHighScore) {
leadBoardLabel.setVisible(true);
} else if (score > 0 && !isHighScore) {
leadBoardLabel.setVisible(false);
}
newGameLabel.setVisible(true);
highScoreLabel.setVisible(true);
optionsLabel.setVisible(true);
exitLabel.setVisible(true);
backLabel.setVisible(false);
onButton.setVisible(false);
soundText.setVisible(false);
doneLabel.setVisible(false);
playerName.setVisible(false);
playerNameLabel.setVisible(false);
resumeLabel.setVisible(false);
tableView.setVisible(false);
highScoreLabel.setTranslateX(320);
highScoreLabel.setTranslateY(450);
});
}
/** Play scale effect to the {@link ViewController#leadBoardLabel} or add new highscore the the HighScores.xml. */
public void addToLeadBoardMenu() {
if (score >= 1 && !isHighScore && !isOptions)
leadBoardLabel.setVisible(true);
leadBoardLabel.setOnMouseEntered(MouseEvent -> {
leadBoardLabel.setScaleY(1.5);
leadBoardLabel.setScaleX(1.5);
});
leadBoardLabel.setOnMouseExited(MouseEvent -> {
leadBoardLabel.setScaleX(1);
leadBoardLabel.setScaleY(1);
});
leadBoardLabel.setOnMouseClicked(MouseEvent -> {
backLabel.setVisible(true);
playerName.setVisible(true);
playerNameLabel.setVisible(true);
failLabel.setVisible(false);
newGameLabel.setVisible(false);
highScoreLabel.setVisible(false);
optionsLabel.setVisible(false);
exitLabel.setVisible(false);
leadBoardLabel.setVisible(false);
resumeLabel.setVisible(false);
tableView.setVisible(false);
backMenu();
playerName.setOnKeyPressed((event) -> {
if(event.getCode() == KeyCode.ENTER) {
player = playerName.getText();
initData(player,Main.score);
playerName.setText("");
newGameLabel.setVisible(true);
highScoreLabel.setVisible(true);
optionsLabel.setVisible(true);
exitLabel.setVisible(true);
backLabel.setVisible(false);
playerName.setVisible(false);
playerNameLabel.setVisible(false);
backLabel.setVisible(false);
tableView.setVisible(false);
leadBoardLabel.setVisible(false);
}
});
});
}
/** Play scale effect to the {@link ViewController#highScoreLabel} or pausing the game. */
public void resumeMenu() {
if (!backLabel.isVisible())
resumeLabel.setVisible(true);
resumeLabel.setOnMouseEntered(MouseEvent -> {
resumeLabel.setScaleX(1.5);
resumeLabel.setScaleY(1.5);
});
resumeLabel.setOnMouseExited(MouseEvent -> {
resumeLabel.setScaleX(1);
resumeLabel.setScaleY(1);
});
resumeLabel.setOnMouseClicked(MouseEvent -> {
logger.debug("Playing again.");
running = true;
hideLabels();
});
}
} |
package hudson.plugins.git.browser;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitChangeSet.Path;
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Git Browser for GitLab
*/
public class GitLab extends GitRepositoryBrowser {
private static final long serialVersionUID = 1L;
private final double version;
@DataBoundConstructor
public GitLab(String repoUrl, String version) {
super(repoUrl);
this.version = Double.valueOf(version);
}
public double getVersion() {
return version;
}
@Override
public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
String commitPrefix;
return new URL(getUrl(), calculatePrefix() + changeSet.getId().toString());
}
@Override
public URL getDiffLink(Path path) throws IOException {
final GitChangeSet changeSet = path.getChangeSet();
return new URL(getUrl(), calculatePrefix() + changeSet.getId().toString() + "#" + path.getPath());
}
@Override
public URL getFileLink(Path path) throws IOException {
if (path.getEditType().equals(EditType.DELETE)) {
return getDiffLink(path);
} else {
if(getVersion() < 5.1) {
return new URL(getUrl(), path.getChangeSet().getId() + "/tree/" + path.getPath());
} else {
return new URL(getUrl(), "blob/" + path.getChangeSet().getId() + "/" + path.getPath());
}
}
}
@Extension
public static class GitLabDescriptor extends Descriptor<RepositoryBrowser<?>> {
public String getDisplayName() {
return "gitlab";
}
@Override
public GitLab newInstance(StaplerRequest req, JSONObject jsonObject) throws FormException {
return req.bindJSON(GitLab.class, jsonObject);
}
}
private String calculatePrefix() {
if(getVersion() < 3) {
return "commits/";
} else {
return "commit/";
}
}
} |
package io.scif.ome.formats;
import io.scif.AbstractChecker;
import io.scif.AbstractFormat;
import io.scif.AbstractParser;
import io.scif.AbstractTranslator;
import io.scif.ByteArrayPlane;
import io.scif.ByteArrayReader;
import io.scif.DefaultImageMetadata;
import io.scif.Format;
import io.scif.FormatException;
import io.scif.ImageMetadata;
import io.scif.Plane;
import io.scif.Translator;
import io.scif.config.SCIFIOConfig;
import io.scif.formats.MinimalTIFFFormat;
import io.scif.formats.TIFFFormat;
import io.scif.formats.tiff.IFD;
import io.scif.formats.tiff.IFDList;
import io.scif.formats.tiff.PhotoInterp;
import io.scif.formats.tiff.TiffIFDEntry;
import io.scif.formats.tiff.TiffParser;
import io.scif.formats.tiff.TiffSaver;
import io.scif.io.Location;
import io.scif.io.RandomAccessInputStream;
import io.scif.io.RandomAccessOutputStream;
import io.scif.ome.OMEMetadata;
import io.scif.ome.services.OMEMetadataService;
import io.scif.ome.services.OMEXMLService;
import io.scif.services.FormatService;
import io.scif.services.TranslatorService;
import io.scif.util.FormatTools;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;
import loci.common.services.ServiceException;
import loci.formats.meta.IMetadata;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.meta.MetadataStore;
import loci.formats.ome.OMEXMLMetadata;
import net.imglib2.display.ColorTable;
import net.imglib2.meta.Axes;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveFloat;
import ome.xml.model.primitives.PositiveInteger;
import ome.xml.model.primitives.Timestamp;
import org.scijava.Context;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
@Plugin(type = Format.class, priority = OMETIFFFormat.PRIORITY)
public class OMETIFFFormat extends AbstractFormat {
// -- Constants --
public static final String URL_OME_TIFF =
"http:
public static final double PRIORITY = TIFFFormat.PRIORITY + 1;
// -- Format API Methods --
@Override
public String getFormatName() {
return "OME-TIFF";
}
@Override
protected String[] makeSuffixArray() {
return new String[] { "ome.tif", "ome.tiff" };
}
// -- Nested Classes --
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Metadata extends TIFFFormat.Metadata {
@Parameter
private OMEMetadataService metaService;
@Parameter
private OMEXMLService service;
// -- Fields --
/** Mapping from series and plane numbers to files and IFD entries. */
protected OMETIFFPlane[][] info; // dimensioned [numSeries][numPlanes]
private IFD firstIFD;
private List<Integer> samples;
private List<Boolean> adjustedSamples;
/** List of used files. */
protected String[] used;
// TODO maybe this should be an o mexmlmetadata...
private OMEMetadata omeMeta;
private long lastPlane = 0;
private boolean hasSPW;
private int[] tileWidth;
private int[] tileHeight;
// -- OMETIFF Metadata API methods --
/**
* Returns a MetadataStore that is populated in such a way as to produce
* valid OME-XML. The returned MetadataStore cannot be used by an
* IFormatWriter, as it will not contain the required BinData.BigEndian
* attributes.
*/
public MetadataStore getMetadataStoreForDisplay() {
final MetadataStore store = omeMeta.getRoot();
if (service.isOMEXMLMetadata(store)) {
service.removeBinData((OMEXMLMetadata) store);
for (int i = 0; i < getImageCount(); i++) {
if (((OMEXMLMetadata) store).getTiffDataCount(i) == 0) {
service.addMetadataOnly((OMEXMLMetadata) store, i);
}
}
}
return store;
}
/**
* Returns a MetadataStore that is populated in such a way as to be usable
* by an IFormatWriter. Any OME-XML generated from this MetadataStore is
* <em>very unlikely</em> to be valid, as more than likely both BinData and
* TiffData element will be present.
*/
public MetadataStore getMetadataStoreForConversion() {
final MetadataStore store = omeMeta.getRoot();
for (int i = 0; i < getImageCount(); i++) {
store.setPixelsBinDataBigEndian(new Boolean(!get(i).isLittleEndian()),
i, 0);
}
return store;
}
// -- OMETIFFMetadata getters and setters --
public OMETIFFPlane[][] getPlaneInfo() {
return info;
}
public void setPlaneInfo(final OMETIFFPlane[][] info) {
this.info = info;
}
public String[] getUsed() {
return used;
}
public void setUsed(final String[] used) {
this.used = used;
}
public OMEMetadata getOmeMeta() {
return omeMeta;
}
public void setOmeMeta(final OMEMetadata omeMeta) {
this.omeMeta = omeMeta;
}
@Override
public long getLastPlane() {
return lastPlane;
}
@Override
public void setLastPlane(final long lastPlane) {
this.lastPlane = lastPlane;
}
public IFD getFirstIFD() {
return firstIFD;
}
public void setFirstIFD(final IFD firstIFD) {
this.firstIFD = firstIFD;
}
public boolean isHasSPW() {
return hasSPW;
}
public void setHasSPW(final boolean hasSPW) {
this.hasSPW = hasSPW;
}
public int[] getTileWidth() {
return tileWidth;
}
public void setTileWidth(final int[] tileWidth) {
this.tileWidth = tileWidth;
}
public int[] getTileHeight() {
return tileHeight;
}
public void setTileHeight(final int[] tileHeight) {
this.tileHeight = tileHeight;
}
// -- Metadata API Methods --
@Override
public void populateImageMetadata() {
final OMEXMLMetadata omexmlMeta = getOmeMeta().getRoot();
for (int s = 0; s < getImageCount(); s++) {
final ImageMetadata m = get(s);
try {
m.setPlanarAxisCount(2);
// set image width
final int sizeX = omexmlMeta.getPixelsSizeX(s).getValue().intValue();
m.setAxisLength(Axes.X, sizeX);
final int tiffWidth = (int) firstIFD.getImageWidth();
if (sizeX != tiffWidth && s == 0) {
log().warn("SizeX mismatch: OME=" + sizeX + ", TIFF=" + tiffWidth);
}
// set image height
final int sizeY = omexmlMeta.getPixelsSizeY(s).getValue().intValue();
m.setAxisLength(Axes.Y, sizeY);
final int tiffHeight = (int) firstIFD.getImageLength();
if (sizeY != tiffHeight && s == 0) {
log().warn("SizeY mismatch: OME=" + sizeY + ", TIFF=" + tiffHeight);
}
// set Z, C and T lengths
final int sizeZ = omexmlMeta.getPixelsSizeZ(s).getValue().intValue();
final int sizeC = omexmlMeta.getPixelsSizeC(s).getValue().intValue();
final int sizeT = omexmlMeta.getPixelsSizeT(s).getValue().intValue();
m.setAxisLength(Axes.Z, sizeZ);
m.setAxisLength(Axes.CHANNEL, sizeC);
m.setAxisLength(Axes.TIME, sizeT);
// set pixel type
final String pixelTypeString = omexmlMeta.getPixelsType(s).toString();
final int pixelType = FormatTools.pixelTypeFromString(pixelTypeString);
m.setPixelType(pixelType);
final int tiffPixelType = firstIFD.getPixelType();
if (pixelType != tiffPixelType && (s == 0 || adjustedSamples.get(s)))
{
log().warn(
"PixelType mismatch: OME=" + pixelType + ", TIFF=" +
tiffPixelType);
m.setPixelType(tiffPixelType);
}
String dimensionOrder =
omexmlMeta.getPixelsDimensionOrder(s).toString();
// hackish workaround for files exported by OMERO that have an
// incorrect dimension order
String uuidFileName = "";
try {
if (omexmlMeta.getTiffDataCount(s) > 0) {
uuidFileName = omexmlMeta.getUUIDFileName(s, 0);
}
}
catch (final NullPointerException e) {}
if (omexmlMeta.getChannelCount(s) > 0 &&
omexmlMeta.getChannelName(s, 0) == null &&
omexmlMeta.getTiffDataCount(s) > 0 &&
uuidFileName.indexOf("__omero_export") != -1)
{
dimensionOrder = "XYZCT";
}
m.setAxisTypes(metaService.findDimensionList(dimensionOrder));
m.setOrderCertain(true);
final PhotoInterp photo = firstIFD.getPhotometricInterpretation();
if (samples.get(s) > 1 || photo == PhotoInterp.RGB) {
m.setPlanarAxisCount(3);
}
if ((samples.get(s) != m.getAxisLength(Axes.CHANNEL) &&
(samples.get(s) % m.getAxisLength(Axes.CHANNEL)) != 0 && (m
.getAxisLength(Axes.CHANNEL) % samples.get(s)) != 0) ||
m.getAxisLength(Axes.CHANNEL) == 1 || adjustedSamples.get(s))
{
m.setAxisLength(Axes.CHANNEL, m.getAxisLength(Axes.CHANNEL) *
samples.get(s));
}
if (m.getAxisLength(Axes.Z) * m.getAxisLength(Axes.TIME) *
m.getAxisLength(Axes.CHANNEL) > info[s].length &&
!m.isMultichannel())
{
if (m.getAxisLength(Axes.Z) == info[s].length) {
m.setAxisLength(Axes.TIME, 1);
m.setAxisLength(Axes.CHANNEL, 1);
}
else if (m.getAxisLength(Axes.TIME) == info[s].length) {
m.setAxisLength(Axes.Z, 1);
m.setAxisLength(Axes.CHANNEL, 1);
}
else if (m.getAxisLength(Axes.CHANNEL) == info[s].length) {
m.setAxisLength(Axes.TIME, 1);
m.setAxisLength(Axes.Z, 1);
}
}
if (omexmlMeta.getPixelsBinDataCount(s) > 1) {
log().warn(
"OME-TIFF Pixels element contains BinData elements! "
+ "Ignoring.");
}
m.setLittleEndian(firstIFD.isLittleEndian());
m.setIndexed(photo == PhotoInterp.RGB_PALETTE &&
firstIFD.getIFDValue(IFD.COLOR_MAP) != null);
m.setFalseColor(true);
m.setMetadataComplete(true);
}
catch (final NullPointerException exc) {
log().error("Incomplete Pixels metadata", exc);
}
catch (final FormatException exc) {
log().error("Format exception when creating ImageMetadata", exc);
}
// Set the physical pixel sizes
FormatTools.calibrate(m.getAxis(Axes.X), getValue(omexmlMeta
.getPixelsPhysicalSizeX(s)), 0.0);
FormatTools.calibrate(m.getAxis(Axes.Y), getValue(omexmlMeta
.getPixelsPhysicalSizeY(s)), 0.0);
FormatTools.calibrate(m.getAxis(Axes.Z), getValue(omexmlMeta
.getPixelsPhysicalSizeZ(s)), 0.0);
}
// if (getImageCount() == 1) {
// CoreMetadata ms0 = core.get(0);
// ms0.sizeZ = 1;
// if (!ms0.rgb) {
// ms0.sizeC = 1;
// ms0.sizeT = 1;
// metaService.populatePixels(getOmeMeta().getRoot(), this, false, false);
getOmeMeta().setRoot((OMEXMLMetadata) getMetadataStoreForConversion());
}
@Override
public void close(final boolean fileOnly) throws IOException {
super.close(fileOnly);
if (info != null) {
for (final OMETIFFPlane[] dimension : info) {
for (final OMETIFFPlane plane : dimension) {
if (plane.reader != null) {
try {
plane.reader.close();
}
catch (final Exception e) {
log().error("Plane closure failure!", e);
}
}
}
}
}
if (!fileOnly) {
info = null;
lastPlane = 0;
tileWidth = null;
tileHeight = null;
}
}
// -- HasColorTable API Methods --
@Override
public ColorTable
getColorTable(final int imageIndex, final long planeIndex)
{
if (info[imageIndex][(int) lastPlane] == null ||
info[imageIndex][(int) lastPlane].reader == null ||
info[imageIndex][(int) lastPlane].id == null)
{
return null;
}
try {
info[imageIndex][(int) lastPlane].reader
.setSource(info[imageIndex][(int) lastPlane].id);
return info[imageIndex][(int) lastPlane].reader.getMetadata()
.getColorTable(imageIndex, planeIndex);
}
catch (final IOException e) {
log().error("IOException when trying to read color table", e);
return null;
}
}
/**
* Helper method to extract values out of {@link PositiveFloat}s, for
* physical pixel sizes (calibration values). Returns 1.0 if given a null or
* invalid (< 0) calibration.
*/
private double getValue(PositiveFloat pixelPhysicalSize) {
if (pixelPhysicalSize == null) return 1.0;
Double physSize = pixelPhysicalSize.getValue();
if (physSize < 0) return 1.0;
return physSize;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Checker extends AbstractChecker {
@Parameter
private OMEXMLService service;
@Parameter
private OMEMetadataService metaService;
// -- Checker API Methods --
@Override
public boolean suffixNecessary() {
return false;
}
@Override
public boolean suffixSufficient() {
return false;
}
@Override
public boolean isFormat(final RandomAccessInputStream stream)
throws IOException
{
final TiffParser tp = new TiffParser(getContext(), stream);
tp.setDoCaching(false);
final boolean validHeader = tp.isValidHeader();
if (!validHeader) return false;
// look for OME-XML in first IFD's comment
final IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
final Object description = ifd.get(IFD.IMAGE_DESCRIPTION);
if (description == null) {
return false;
}
String comment = null;
if (description instanceof TiffIFDEntry) {
comment = tp.getIFDValue((TiffIFDEntry) description).toString();
}
else if (description instanceof String) {
comment = (String) description;
}
if (comment == null || comment.trim().length() == 0) return false;
comment = comment.trim();
// do a basic sanity check before attempting to parse the comment as XML
// the parsing step is a bit slow, so there is no sense in trying unless
// we are reasonably sure that the comment contains XML
if (!comment.startsWith("<") || !comment.endsWith(">")) {
return false;
}
try {
final IMetadata meta = service.createOMEXMLMetadata(comment);
for (int i = 0; i < meta.getImageCount(); i++) {
meta.setPixelsBinDataBigEndian(Boolean.TRUE, i, 0);
metaService.verifyMinimumPopulated(meta, i);
}
return meta.getImageCount() > 0;
}
catch (final ServiceException se) {
log().debug("OME-XML parsing failed", se);
}
catch (final NullPointerException e) {
log().debug("OME-XML parsing failed", e);
}
catch (final FormatException e) {
log().debug("OME-XML parsing failed", e);
}
catch (final IndexOutOfBoundsException e) {
log().debug("OME-XML parsing failed", e);
}
return false;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Parser extends AbstractParser<Metadata> {
// -- Fields --
@Parameter
private OMEXMLService service;
@Parameter
private OMEMetadataService metaService;
@Parameter
private FormatService formatService;
// -- Parser API Methods --
@Override
public String[] getImageUsedFiles(final int imageIndex,
final boolean noPixels)
{
FormatTools.assertId(getMetadata().getDatasetName(), true, 1);
if (noPixels) return null;
final Vector<String> usedFiles = new Vector<String>();
for (int i = 0; i < getMetadata().info[imageIndex].length; i++) {
if (!usedFiles.contains(getMetadata().info[imageIndex][i].id)) {
usedFiles.add(getMetadata().info[imageIndex][i].id);
}
}
return usedFiles.toArray(new String[usedFiles.size()]);
}
@Override
public Metadata parse(final String fileName, final Metadata meta,
final SCIFIOConfig config) throws IOException, FormatException
{
return super.parse(normalizeFilename(null, fileName), meta, config);
}
@Override
public Metadata parse(final File file, final Metadata meta,
final SCIFIOConfig config) throws IOException, FormatException
{
return super.parse(normalizeFilename(null, file.getPath()), meta, config);
}
@Override
public int fileGroupOption(final String id) throws FormatException,
IOException
{
final boolean single = isSingleFile(id);
return single ? FormatTools.CAN_GROUP : FormatTools.MUST_GROUP;
}
@Override
public Metadata parse(final RandomAccessInputStream stream,
final Metadata meta, final SCIFIOConfig config) throws IOException,
FormatException
{
super.parse(stream, meta, config);
for (int s = 0; s < meta.getImageCount(); s++) {
final OMETIFFPlane[][] info = meta.getPlaneInfo();
try {
if (!info[s][0].reader.getFormat().createChecker().isFormat(
info[s][0].id))
{
info[s][0].id = meta.getSource().getFileName();
}
for (int plane = 0; plane < info[s].length; plane++) {
if (!info[s][plane].reader.getFormat().createChecker().isFormat(
info[s][plane].id))
{
info[s][plane].id = info[s][0].id;
}
}
info[s][0].reader.setSource(info[s][0].id);
meta.getTileWidth()[s] =
(int) info[s][0].reader.getOptimalTileWidth(s);
meta.getTileHeight()[s] =
(int) info[s][0].reader.getOptimalTileHeight(s);
}
catch (final FormatException e) {
log().debug("OME-XML parsing failed", e);
}
}
return meta;
}
// -- Groupable API Methods --
@Override
public boolean isSingleFile(final String id) throws FormatException,
IOException
{
return OMETIFFFormat.isSingleFile(getContext(), id);
}
// -- Abstract Parser API Methods --
@Override
protected void typedParse(final io.scif.io.RandomAccessInputStream stream,
final Metadata meta, final SCIFIOConfig config) throws IOException,
io.scif.FormatException
{
// normalize file name
final String id = stream.getFileName();
final String dir = new File(id).getParent();
// parse and populate OME-XML metadata
String fileName =
new Location(getContext(), id).getAbsoluteFile().getAbsolutePath();
if (!new File(fileName).exists()) {
fileName = stream.getFileName();
}
final RandomAccessInputStream ras =
new RandomAccessInputStream(getContext(), fileName);
String xml;
IFD firstIFD;
try {
final TiffParser tp = new TiffParser(getContext(), ras);
firstIFD = tp.getFirstIFD();
xml = firstIFD.getComment();
}
finally {
ras.close();
}
meta.setFirstIFD(firstIFD);
OMEXMLMetadata omexmlMeta;
try {
omexmlMeta = service.createOMEXMLMetadata(xml);
}
catch (final ServiceException se) {
throw new FormatException(se);
}
meta.setHasSPW(omexmlMeta.getPlateCount() > 0);
for (int i = 0; i < meta.getImageCount(); i++) {
final int sizeC = omexmlMeta.getPixelsSizeC(i).getValue().intValue();
service.removeChannels(omexmlMeta, i, sizeC);
}
final Hashtable<String, Object> originalMetadata =
service.getOriginalMetadata(omexmlMeta);
if (originalMetadata != null) meta.getTable().putAll(originalMetadata);
log().trace(xml);
if (omexmlMeta.getRoot() == null) {
throw new FormatException("Could not parse OME-XML from TIFF comment");
}
meta.setOmeMeta(new OMEMetadata(getContext(), omexmlMeta));
final String[] acquiredDates = new String[meta.getImageCount()];
for (int i = 0; i < acquiredDates.length; i++) {
final Timestamp acquisitionDate = omexmlMeta.getImageAcquisitionDate(i);
if (acquisitionDate != null) {
acquiredDates[i] = acquisitionDate.getValue();
}
}
final String currentUUID = omexmlMeta.getUUID();
// determine series count from Image and Pixels elements
final int imageCount = omexmlMeta.getImageCount();
meta.createImageMetadata(imageCount);
OMETIFFPlane[][] info = new OMETIFFPlane[imageCount][];
meta.setPlaneInfo(info);
final int[] tileWidth = new int[imageCount];
final int[] tileHeight = new int[imageCount];
meta.setTileWidth(tileWidth);
meta.setTileHeight(tileHeight);
// compile list of file/UUID mappings
final Hashtable<String, String> files = new Hashtable<String, String>();
boolean needSearch = false;
for (int i = 0; i < imageCount; i++) {
final int tiffDataCount = omexmlMeta.getTiffDataCount(i);
for (int td = 0; td < tiffDataCount; td++) {
String uuid = null;
try {
uuid = omexmlMeta.getUUIDValue(i, td);
}
catch (final NullPointerException e) {}
String filename = null;
if (uuid == null) {
// no UUID means that TiffData element refers to this file
uuid = "";
filename = id;
}
else {
filename = omexmlMeta.getUUIDFileName(i, td);
if (!new Location(getContext(), dir, filename).exists()) filename =
null;
if (filename == null) {
if (uuid.equals(currentUUID) || currentUUID == null) {
// UUID references this file
filename = id;
}
else {
// will need to search for this UUID
filename = "";
needSearch = true;
}
}
else filename = normalizeFilename(dir, filename);
}
final String existing = files.get(uuid);
if (existing == null) files.put(uuid, filename);
else if (!existing.equals(filename)) {
throw new FormatException("Inconsistent UUID filenames");
}
}
}
// search for missing filenames
if (needSearch) {
final Enumeration<String> en = files.keys();
while (en.hasMoreElements()) {
final String uuid = en.nextElement();
final String filename = files.get(uuid);
if (filename.equals("")) {
// TODO search...
// should scan only other .ome.tif files
// to make this work with OME server may be a little tricky?
throw new FormatException("Unmatched UUID: " + uuid);
}
}
}
// build list of used files
final Enumeration<String> en = files.keys();
final int numUUIDs = files.size();
final HashSet<String> fileSet = new HashSet<String>(); // ensure no
// duplicate
// filenames
for (int i = 0; i < numUUIDs; i++) {
final String uuid = en.nextElement();
final String filename = files.get(uuid);
fileSet.add(filename);
}
final String[] used = new String[fileSet.size()];
meta.setUsed(used);
final Iterator<String> iter = fileSet.iterator();
for (int i = 0; i < used.length; i++)
used[i] = iter.next();
// process TiffData elements
final Hashtable<String, MinimalTIFFFormat.Reader<?>> readers =
new Hashtable<String, MinimalTIFFFormat.Reader<?>>();
final List<Boolean> adjustedSamples = new ArrayList<Boolean>();
final List<Integer> samples = new ArrayList<Integer>();
meta.adjustedSamples = adjustedSamples;
meta.samples = samples;
for (int i = 0; i < imageCount; i++) {
final int s = i;
log().debug("Image[" + i + "] {");
log().debug(" id = " + omexmlMeta.getImageID(i));
adjustedSamples.add(false);
final String order = omexmlMeta.getPixelsDimensionOrder(i).toString();
PositiveInteger samplesPerPixel = null;
if (omexmlMeta.getChannelCount(i) > 0) {
samplesPerPixel = omexmlMeta.getChannelSamplesPerPixel(i, 0);
}
samples.add(i, samplesPerPixel == null ? -1 : samplesPerPixel
.getValue());
final int tiffSamples = firstIFD.getSamplesPerPixel();
if (adjustedSamples.get(i) ||
(samples.get(i) != tiffSamples && (i == 0 || samples.get(i) < 0)))
{
log().warn(
"SamplesPerPixel mismatch: OME=" + samples.get(i) + ", TIFF=" +
tiffSamples);
samples.set(i, tiffSamples);
adjustedSamples.set(i, true);
}
else {
adjustedSamples.set(i, false);
}
if (adjustedSamples.get(i) && omexmlMeta.getChannelCount(i) <= 1) {
adjustedSamples.set(i, false);
}
int effSizeC = omexmlMeta.getPixelsSizeC(i).getValue().intValue();
if (!adjustedSamples.get(i)) {
effSizeC /= samples.get(i);
}
if (effSizeC == 0) effSizeC = 1;
if (effSizeC * samples.get(i) != omexmlMeta.getPixelsSizeC(i)
.getValue().intValue())
{
effSizeC = omexmlMeta.getPixelsSizeC(i).getValue().intValue();
}
final int sizeT = omexmlMeta.getPixelsSizeT(i).getValue().intValue();
final int sizeZ = omexmlMeta.getPixelsSizeZ(i).getValue().intValue();
int num = effSizeC * sizeT * sizeZ;
OMETIFFPlane[] planes = new OMETIFFPlane[num];
for (int no = 0; no < num; no++)
planes[no] = new OMETIFFPlane();
final int tiffDataCount = omexmlMeta.getTiffDataCount(i);
Boolean zOneIndexed = null;
Boolean cOneIndexed = null;
Boolean tOneIndexed = null;
// pre-scan TiffData indices to see if any of them are indexed from 1
for (int td = 0; td < tiffDataCount; td++) {
final NonNegativeInteger firstC = omexmlMeta.getTiffDataFirstC(i, td);
final NonNegativeInteger firstT = omexmlMeta.getTiffDataFirstT(i, td);
final NonNegativeInteger firstZ = omexmlMeta.getTiffDataFirstZ(i, td);
final int c = firstC == null ? 0 : firstC.getValue();
final int t = firstT == null ? 0 : firstT.getValue();
final int z = firstZ == null ? 0 : firstZ.getValue();
if (c >= effSizeC && cOneIndexed == null) {
cOneIndexed = true;
}
else if (c == 0) {
cOneIndexed = false;
}
if (z >= sizeZ && zOneIndexed == null) {
zOneIndexed = true;
}
else if (z == 0) {
zOneIndexed = false;
}
if (t >= sizeT && tOneIndexed == null) {
tOneIndexed = true;
}
else if (t == 0) {
tOneIndexed = false;
}
}
for (int td = 0; td < tiffDataCount; td++) {
log().debug(" TiffData[" + td + "] {");
// extract TiffData parameters
String filename = null;
String uuid = null;
try {
filename = omexmlMeta.getUUIDFileName(i, td);
}
catch (final NullPointerException e) {
log().debug("Ignoring null UUID object when retrieving filename.");
}
try {
uuid = omexmlMeta.getUUIDValue(i, td);
}
catch (final NullPointerException e) {
log().debug("Ignoring null UUID object when retrieving value.");
}
final NonNegativeInteger tdIFD = omexmlMeta.getTiffDataIFD(i, td);
final int ifd = tdIFD == null ? 0 : tdIFD.getValue();
final NonNegativeInteger numPlanes =
omexmlMeta.getTiffDataPlaneCount(i, td);
final NonNegativeInteger firstC = omexmlMeta.getTiffDataFirstC(i, td);
final NonNegativeInteger firstT = omexmlMeta.getTiffDataFirstT(i, td);
final NonNegativeInteger firstZ = omexmlMeta.getTiffDataFirstZ(i, td);
int c = firstC == null ? 0 : firstC.getValue();
int t = firstT == null ? 0 : firstT.getValue();
int z = firstZ == null ? 0 : firstZ.getValue();
// NB: some writers index FirstC, FirstZ and FirstT from 1
if (cOneIndexed != null && cOneIndexed) c
if (zOneIndexed != null && zOneIndexed) z
if (tOneIndexed != null && tOneIndexed) t
if (z >= sizeZ || c >= effSizeC || t >= sizeT) {
log().warn(
"Found invalid TiffData: Z=" + z + ", C=" + c + ", T=" + t);
break;
}
final long[] pos = metaService.zctToArray(order, z, c, t);
final long[] lengths =
metaService.zctToArray(order, sizeZ, effSizeC, sizeT);
final long index = FormatTools.positionToRaster(lengths, pos);
final int count = numPlanes == null ? 1 : numPlanes.getValue();
if (count == 0) {
meta.get(s);
break;
}
// get reader object for this filename
if (filename == null) {
if (uuid == null) filename = id;
else filename = files.get(uuid);
}
else filename = normalizeFilename(dir, filename);
MinimalTIFFFormat.Reader<?> r = readers.get(filename);
if (r == null) {
r =
(io.scif.formats.MinimalTIFFFormat.Reader<?>) formatService
.getFormatFromClass(MinimalTIFFFormat.class).createReader();
readers.put(filename, r);
}
final Location file = new Location(getContext(), filename);
if (!file.exists()) {
// if this is an absolute file name, try using a relative name
// old versions of OMETiffWriter wrote an absolute path to
// UUID.FileName, which causes problems if the file is moved to
// a different directory
filename =
filename.substring(filename.lastIndexOf(File.separator) + 1);
filename = dir + File.separator + filename;
if (!new Location(getContext(), filename).exists()) {
filename = stream.getFileName();
}
}
// populate plane index -> IFD mapping
for (int q = 0; q < count; q++) {
final int no = (int) (index + q);
planes[no].reader = r;
planes[no].id = filename;
planes[no].ifd = ifd + q;
planes[no].certain = true;
log().debug(
" Plane[" + no + "]: file=" + planes[no].id + ", IFD=" +
planes[no].ifd);
}
if (numPlanes == null) {
// unknown number of planes; fill down
for (int no = (int) (index + 1); no < num; no++) {
if (planes[no].certain) break;
planes[no].reader = r;
planes[no].id = filename;
planes[no].ifd = planes[no - 1].ifd + 1;
log().debug(" Plane[" + no + "]: FILLED");
}
}
else {
// known number of planes; clear anything subsequently filled
for (int no = (int) (index + count); no < num; no++) {
if (planes[no].certain) break;
planes[no].reader = null;
planes[no].id = null;
planes[no].ifd = -1;
log().debug(" Plane[" + no + "]: CLEARED");
}
}
log().debug(" }");
}
if (meta.get(s) == null) continue;
// verify that all planes are available
log().debug("
for (int no = 0; no < num; no++) {
log().debug(
" Plane[" + no + "]: file=" + planes[no].id + ", IFD=" +
planes[no].ifd);
if (planes[no].reader == null) {
log().warn(
"Image ID '" + omexmlMeta.getImageID(i) + "': missing plane
no + ". " +
"Using TiffReader to determine the number of planes.");
final TIFFFormat.Reader<?> r =
(io.scif.formats.TIFFFormat.Reader<?>) formatService
.getFormatFromClass(TIFFFormat.class).createReader();
r.setSource(stream.getFileName());
try {
planes = new OMETIFFPlane[r.getImageCount()];
for (int plane = 0; plane < planes.length; plane++) {
planes[plane] = new OMETIFFPlane();
planes[plane].id = stream.getFileName();
planes[plane].reader = r;
planes[plane].ifd = plane;
}
num = planes.length;
}
finally {
r.close();
}
}
}
info[i] = planes;
log().debug(" }");
}
// remove null CoreMetadata entries
final Vector<OMETIFFPlane[]> planeInfo = new Vector<OMETIFFPlane[]>();
for (int i = meta.getImageCount() - 1; i >= 0; i
if (meta.get(i) == null) {
meta.getAll().remove(i);
adjustedSamples.remove(i);
samples.remove(i);
}
else {
planeInfo.add(0, info[i]);
}
}
info = planeInfo.toArray(new OMETIFFPlane[0][0]);
// meta.getOmeMeta().populateImageMetadata();
}
// -- Helper methods --
private String normalizeFilename(final String dir, final String name) {
final File file = new File(dir, name);
if (file.exists()) return file.getAbsolutePath();
return name;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Reader extends ByteArrayReader<Metadata> {
// -- Reader API Methods --
@Override
public long getOptimalTileWidth(final int imageIndex) {
return getMetadata().getTileWidth()[imageIndex];
}
@Override
public long getOptimalTileHeight(final int imageIndex) {
return getMetadata().getTileHeight()[imageIndex];
}
@Override
public String[] getDomains() {
FormatTools.assertId(getMetadata().getDatasetName(), true, 1);
return getMetadata().isHasSPW() ? new String[] { FormatTools.HCS_DOMAIN }
: FormatTools.NON_SPECIAL_DOMAINS;
}
@Override
public ByteArrayPlane openPlane(final int imageIndex,
final long planeIndex, final ByteArrayPlane plane, final long[] offsets,
final long[] lengths, final SCIFIOConfig config)
throws io.scif.FormatException, IOException
{
final Metadata meta = getMetadata();
final byte[] buf = plane.getBytes();
final OMETIFFPlane[][] info = meta.getPlaneInfo();
FormatTools.checkPlaneForReading(meta, imageIndex, planeIndex,
buf.length, offsets, lengths);
meta.setLastPlane(planeIndex);
final int i = info[imageIndex][(int) planeIndex].ifd;
final MinimalTIFFFormat.Reader<?> r =
info[imageIndex][(int) planeIndex].reader;
if (r.getCurrentFile() == null) {
r.setSource(info[imageIndex][(int) planeIndex].id);
}
final IFDList ifdList = r.getMetadata().getIfds();
if (i >= ifdList.size()) {
log()
.warn("Error untangling IFDs; the OME-TIFF file may be malformed.");
return plane;
}
final IFD ifd = ifdList.get(i);
final RandomAccessInputStream s =
new RandomAccessInputStream(getContext(),
info[imageIndex][(int) planeIndex].id);
final TiffParser p = new TiffParser(getContext(), s);
final int xIndex = meta.get(imageIndex).getAxisIndex(Axes.X), yIndex =
meta.get(imageIndex).getAxisIndex(Axes.Y);
final int x = (int) offsets[xIndex], y = (int) offsets[yIndex], w =
(int) lengths[xIndex], h = (int) lengths[yIndex];
p.getSamples(ifd, buf, x, y, w, h);
s.close();
return plane;
}
// -- Groupable API Methods --
@Override
public boolean isSingleFile(final String id) throws FormatException,
IOException
{
return OMETIFFFormat.isSingleFile(getContext(), id);
}
@Override
public boolean hasCompanionFiles() {
return true;
}
@Override
protected String[] createDomainArray() {
return FormatTools.NON_GRAPHICS_DOMAINS;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Writer extends TIFFFormat.Writer<Metadata> {
// -- Constants --
private static final String WARNING_COMMENT =
"<!-- Warning: this comment is an OME-XML metadata block, which " +
"contains crucial dimensional parameters and other important metadata. " +
"Please edit cautiously (if at all), and back up the original data " +
"before doing so. For more information, see the OME-TIFF web site: " +
URL_OME_TIFF + ".
// -- Fields --
@Parameter
private OMEXMLService service;
@Parameter
private OMEMetadataService metaService;
private List<Integer> imageMap;
private String[][] imageLocations;
private OMEXMLMetadata omeMeta;
private final Map<String, Integer> ifdCounts =
new HashMap<String, Integer>();
private final Map<String, String> uuids = new HashMap<String, String>();
// -- Writer API Methods --
@Override
public void setDest(RandomAccessOutputStream out, int imageIndex,
SCIFIOConfig config) throws FormatException, IOException
{
// TODO if already set, return
super.setDest(out, imageIndex, config);
if (imageLocations == null) {
final MetadataRetrieve r = getMetadata().getOmeMeta().getRoot();
imageLocations = new String[r.getImageCount()][];
for (int i = 0; i < imageLocations.length; i++) {
imageLocations[i] = new String[planeCount(imageIndex)];
}
}
}
@Override
public void savePlane(final int imageIndex, final long planeIndex,
final Plane plane, final IFD ifd, final long[] offsets,
final long[] lengths) throws io.scif.FormatException, IOException
{
if (imageMap == null) imageMap = new ArrayList<Integer>();
if (!imageMap.contains(imageIndex)) {
imageMap.add(new Integer(imageIndex));
}
super.savePlane(imageIndex, planeIndex, plane, ifd, offsets, lengths);
// TODO should this be the output id?
imageLocations[imageIndex][(int) planeIndex] =
getMetadata().getDatasetName();
}
@Override
public void close() throws IOException {
try {
if (getStream() != null) {
setupServiceAndMetadata();
// remove any BinData elements from the OME-XML
service.removeBinData(omeMeta);
for (int series = 0; series < omeMeta.getImageCount(); series++) {
populateImage(omeMeta, series);
}
final List<String> files = new ArrayList<String>();
for (final String[] s : imageLocations) {
for (final String f : s) {
if (!files.contains(f) && f != null) {
files.add(f);
final String xml = getOMEXML(f);
// write OME-XML to the first IFD's comment
saveComment(f, xml);
}
}
}
}
}
catch (final ServiceException se) {
throw new RuntimeException(se);
}
catch (final FormatException fe) {
throw new RuntimeException(fe);
}
catch (final IllegalArgumentException iae) {
throw new RuntimeException(iae);
}
finally {
super.close();
boolean canReallyClose =
omeMeta == null || ifdCounts.size() == omeMeta.getImageCount();
if (omeMeta != null && canReallyClose) {
int omePlaneCount = 0;
for (int i = 0; i < omeMeta.getImageCount(); i++) {
final int sizeZ = omeMeta.getPixelsSizeZ(i).getValue();
final int sizeC = omeMeta.getPixelsSizeC(i).getValue();
final int sizeT = omeMeta.getPixelsSizeT(i).getValue();
omePlaneCount += sizeZ * sizeC * sizeT;
}
int ifdCount = 0;
for (final String key : ifdCounts.keySet()) {
ifdCount += ifdCounts.get(key);
}
canReallyClose = omePlaneCount == ifdCount;
}
if (canReallyClose) {
imageMap = null;
imageLocations = null;
omeMeta = null;
ifdCounts.clear();
}
else {
for (final String k : ifdCounts.keySet())
ifdCounts.put(k, 0);
}
}
}
// -- Helper methods --
/** Gets the UUID corresponding to the given filename. */
private String getUUID(final String filename) {
String uuid = uuids.get(filename);
if (uuid == null) {
uuid = UUID.randomUUID().toString();
uuids.put(filename, uuid);
}
return uuid;
}
private void setupServiceAndMetadata() throws ServiceException {
// extract OME-XML string from metadata object
final MetadataRetrieve retrieve = getMetadata().getOmeMeta().getRoot();
final OMEXMLMetadata originalOMEMeta = service.getOMEMetadata(retrieve);
originalOMEMeta.resolveReferences();
final String omexml = service.getOMEXML(originalOMEMeta);
omeMeta = service.createOMEXMLMetadata(omexml);
}
private String getOMEXML(final String file) throws FormatException,
IOException
{
// generate UUID and add to OME element
final String uuid =
"urn:uuid:" + getUUID(new Location(getContext(), file).getName());
omeMeta.setUUID(uuid);
String xml;
try {
xml = service.getOMEXML(omeMeta);
}
catch (final ServiceException se) {
throw new FormatException(se);
}
// insert warning comment
final String prefix = xml.substring(0, xml.indexOf(">") + 1);
final String suffix = xml.substring(xml.indexOf(">") + 1);
return prefix + WARNING_COMMENT + suffix;
}
private void saveComment(final String file, final String xml)
throws IOException, FormatException
{
if (getStream() != null) getStream().close();
setDest(new RandomAccessOutputStream(getContext(), file));
RandomAccessInputStream in = null;
try {
final TiffSaver saver = new TiffSaver(getContext(), getStream(), file);
saver.setBigTiff(isBigTiff());
in = new RandomAccessInputStream(getContext(), file);
saver.overwriteLastIFDOffset(in);
saver.overwriteComment(in, xml);
in.close();
}
catch (final FormatException exc) {
final IOException io =
new IOException("Unable to append OME-XML comment");
io.initCause(exc);
throw io;
}
finally {
if (getStream() != null) getStream().close();
if (in != null) in.close();
}
}
private void populateTiffData(final OMEXMLMetadata omeMeta,
final String dimensionOrder, final long[] zct, final int ifd,
final int series, final int plane)
{
int zIndex = 0;
int tIndex = 0;
int cIndex = 0;
// Determine zct positions
int index = 0;
for (char c : dimensionOrder.toUpperCase().toCharArray()) {
switch (c) {
case 'Z': zIndex = index++;
break;
case 'C': cIndex = index++;
break;
case 'T': tIndex = index++;
break;
}
}
omeMeta.setTiffDataFirstZ(new NonNegativeInteger((int) zct[zIndex]), series,
plane);
omeMeta.setTiffDataFirstC(new NonNegativeInteger((int) zct[cIndex]), series,
plane);
omeMeta.setTiffDataFirstT(new NonNegativeInteger((int) zct[tIndex]), series,
plane);
omeMeta.setTiffDataIFD(new NonNegativeInteger(ifd), series, plane);
omeMeta.setTiffDataPlaneCount(new NonNegativeInteger(1), series, plane);
}
private void populateImage(final OMEXMLMetadata omeMeta,
final int imageIndex)
{
final String dimensionOrder =
omeMeta.getPixelsDimensionOrder(imageIndex).toString();
final int sizeZ =
omeMeta.getPixelsSizeZ(imageIndex).getValue().intValue();
int sizeC = omeMeta.getPixelsSizeC(imageIndex).getValue().intValue();
final int sizeT =
omeMeta.getPixelsSizeT(imageIndex).getValue().intValue();
final long planeCount = getMetadata().get(imageIndex).getPlaneCount();
final int ifdCount = imageMap.size();
if (planeCount == 0) {
omeMeta.setTiffDataPlaneCount(new NonNegativeInteger(0), imageIndex, 0);
return;
}
final PositiveInteger samplesPerPixel =
new PositiveInteger((int) ((sizeZ * sizeC * sizeT) / planeCount));
for (int c = 0; c < omeMeta.getChannelCount(imageIndex); c++) {
omeMeta.setChannelSamplesPerPixel(samplesPerPixel, imageIndex, c);
}
sizeC /= samplesPerPixel.getValue();
// lengths is in ZTC order
final long[] lengths =
metaService.zctToArray(dimensionOrder, sizeZ, sizeC, sizeT);
int nextPlane = 0;
for (int plane = 0; plane < planeCount; plane++) {
final long[] zct = FormatTools.rasterToPosition(lengths, plane);
int planeIndex = plane;
if (imageLocations[imageIndex].length < planeCount) {
planeIndex /= (planeCount / imageLocations[imageIndex].length);
}
String filename = imageLocations[imageIndex][planeIndex];
if (filename != null) {
filename = new Location(getContext(), filename).getName();
final Integer ifdIndex = ifdCounts.get(filename);
final int ifd = ifdIndex == null ? 0 : ifdIndex.intValue();
omeMeta.setUUIDFileName(filename, imageIndex, nextPlane);
final String uuid = "urn:uuid:" + getUUID(filename);
omeMeta.setUUIDValue(uuid, imageIndex, nextPlane);
// fill in any non-default TiffData attributes
populateTiffData(omeMeta, dimensionOrder, zct, ifd, imageIndex,
nextPlane);
ifdCounts.put(filename, ifd + 1);
nextPlane++;
}
}
}
private int planeCount(final int imageIndex) {
final MetadataRetrieve r = getMetadata().getOmeMeta().getRoot();
final int z = r.getPixelsSizeZ(imageIndex).getValue().intValue();
final int t = r.getPixelsSizeT(imageIndex).getValue().intValue();
int c = r.getChannelCount(imageIndex);
final String pixelType = r.getPixelsType(imageIndex).getValue();
final int bytes = FormatTools.getBytesPerPixel(pixelType);
if (bytes > 1 && c == 1) {
c = r.getChannelSamplesPerPixel(imageIndex, 0).getValue();
}
return z * c * t;
}
}
// -- Helper Methods --
private static boolean isSingleFile(final Context context, final String id)
throws FormatException, IOException
{
// parse and populate OME-XML metadata
final String fileName =
new Location(context, id).getAbsoluteFile().getAbsolutePath();
final RandomAccessInputStream ras =
new RandomAccessInputStream(context, fileName);
final TiffParser tp = new TiffParser(context, ras);
final IFD ifd = tp.getFirstIFD();
final long[] ifdOffsets = tp.getIFDOffsets();
ras.close();
final String xml = ifd.getComment();
final OMEXMLService service = context.getService(OMEXMLService.class);
OMEXMLMetadata meta;
try {
meta = service.createOMEXMLMetadata(xml);
}
catch (final ServiceException se) {
throw new FormatException(se);
}
if (meta.getRoot() == null) {
throw new FormatException("Could not parse OME-XML from TIFF comment");
}
int nImages = 0;
for (int i = 0; i < meta.getImageCount(); i++) {
int nChannels = meta.getChannelCount(i);
if (nChannels == 0) nChannels = 1;
final int z = meta.getPixelsSizeZ(i).getValue().intValue();
final int t = meta.getPixelsSizeT(i).getValue().intValue();
nImages += z * t * nChannels;
}
return nImages <= ifdOffsets.length;
}
/**
* This class can be used for translating any io.scif.Metadata to Metadata for
* writing OME-TIFF. files.
* <p>
* Note that Metadata translated from Core is only write-safe.
* </p>
* <p>
* If trying to read, there should already exist an originally-parsed OME-TIFF
* Metadata object which can be used.
* </p>
* <p>
* Note also that any OME-TIFF image written must be reparsed, as the Metadata
* used to write it can not be guaranteed valid.
* </p>
*/
@Plugin(type = Translator.class, priority = OMETIFFFormat.PRIORITY)
public static class OMETIFFTranslator extends
AbstractTranslator<io.scif.Metadata, Metadata>
{
// -- Fields --
@Parameter
private FormatService formatService;
@Parameter
private TranslatorService translatorService;
// -- Translator API Methods --
@Override
public Class<? extends io.scif.Metadata> source() {
return io.scif.Metadata.class;
}
@Override
public Class<? extends io.scif.Metadata> dest() {
return Metadata.class;
}
@Override
public void translateFormatMetadata(final io.scif.Metadata source,
final Metadata dest)
{
if (dest.getOmeMeta() == null) {
final OMEMetadata omeMeta = new OMEMetadata(getContext());
translatorService.translate(source, omeMeta, false);
dest.setOmeMeta(omeMeta);
}
try {
final TIFFFormat.Metadata tiffMeta =
(TIFFFormat.Metadata) formatService.getFormatFromClass(
TIFFFormat.class).createMetadata();
translatorService.translate(source, tiffMeta, false);
dest.setFirstIFD(tiffMeta.getIfds().get(0));
}
catch (final FormatException e) {
log().error("Failed to generate TIFF data", e);
}
final OMETIFFPlane[][] info = new OMETIFFPlane[source.getImageCount()][];
dest.setPlaneInfo(info);
final List<Integer> samples = new ArrayList<Integer>();
final List<Boolean> adjustedSamples = new ArrayList<Boolean>();
dest.samples = samples;
dest.adjustedSamples = adjustedSamples;
dest.createImageMetadata(0);
for (int i = 0; i < source.getImageCount(); i++) {
info[i] = new OMETIFFPlane[(int) source.get(i).getPlaneCount()];
for (int j = 0; j < source.get(i).getPlaneCount(); j++) {
info[i][j] = new OMETIFFPlane();
}
dest.add(new DefaultImageMetadata());
samples.add((int) (source.get(i).isMultichannel() ? source.get(i)
.getAxisLength(Axes.CHANNEL) : 1));
adjustedSamples.add(false);
}
}
@Override
protected void translateImageMetadata(final List<ImageMetadata> source,
final Metadata dest)
{
// No implementation necessary. See translateFormatMetadata
}
}
// -- Helper classes --
/** Structure containing details on where to find a particular image plane. */
private static class OMETIFFPlane {
/** Reader to use for accessing this plane. */
public MinimalTIFFFormat.Reader<?> reader;
/** File containing this plane. */
public String id;
/** IFD number of this plane. */
public int ifd = -1;
/** Certainty flag, for dealing with unspecified NumPlanes. */
public boolean certain = false;
}
} |
package io.sigpipe.sing.dataset;
import java.util.NavigableSet;
import java.util.TreeSet;
import io.sigpipe.sing.dataset.feature.Feature;
public class Quantizer {
private NavigableSet<Feature> ticks = new TreeSet<>();
public Quantizer(Feature... ticks) {
for (Feature tick : ticks) {
addTick(tick);
}
}
public Quantizer(Object start, Object end, Object step) {
this(
Feature.fromPrimitiveType(start),
Feature.fromPrimitiveType(end),
Feature.fromPrimitiveType(step));
}
public Quantizer(Feature start, Feature end, Feature step) {
if (start.sameType(end) == false || start.sameType(step) == false) {
throw new IllegalArgumentException(
"All feature types must be the same");
}
Feature tick = new Feature(start);
while (tick.less(end)) {
addTick(tick);
tick = tick.add(step);
}
}
private void addTick(Feature tick) {
ticks.add(tick);
}
private void removeTick(Feature tick) {
ticks.remove(tick);
}
public int numTicks() {
return ticks.size();
}
/**
* Quantizes a given Feature based on this Quantizer's tick mark
* configuration. When quantizing a Feature, a bucket will be retrieved that
* represents the Feature in question in the tick mark range. Note that the
* bucket returned is not necessarily closest in value to the Feature, but
* simply represents its range of values.
*
* @param feature The Feature to quantize
* @return A quantized representation of the Feature
*/
public Feature quantize(Feature feature) {
Feature result = ticks.floor(feature);
if (result == null) {
return ticks.first();
}
return result;
}
/**
* Retrieves the next tick mark value after the given Feature. In other
* words, this method will return the bucket after the given Feature's
* bucket. If there is no next tick mark (the specified Feature's bucket is
* at the end of the range) then this method returns null.
*
* @param feature Feature to use to locate the next tick mark bucket in the
* range.
* @return Next tick mark, or null if the end of the range has been reached.
*/
public Feature nextTick(Feature feature) {
return ticks.higher(feature);
}
/**
* Retrieves the tick mark value preceding the given Feature. In other
* words, this method will return the bucket before the given Feature's
* bucket. If there is no previous tick mark (the specified Feature's bucket
* is at the beginning of the range) then this method returns null.
*
* @param feature Feature to use to locate the previous tick mark bucket in
* the range.
* @return Next tick mark, or null if the end of the range has been reached.
*/
public Feature prevTick(Feature feature) {
return ticks.lower(feature);
}
@Override
public String toString() {
String output = "";
for (Feature f : ticks) {
output += f.getString() + System.lineSeparator();
}
return output;
}
public static class QuantizerBuilder {
List<Feature> ticks = new ArrayList<>();
public void addTick(Feature tick) {
this.ticks.add(tick);
}
public void addTicks(Feature... ticks) {
for (Feature tick : ticks) {
addTick(tick);
}
}
public void removeTick(Feature tick) {
this.ticks.remove(tick);
}
public List<Feature> getTicks() {
return new ArrayList<Feature>(ticks);
}
public Quantizer build() {
Quantizer q = new Quantizer();
for (Feature tick : ticks) {
q.addTick(tick);
}
return q;
}
}
} |
package io.vertx.codegen;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.codegen.generators.dataobjecthelper.DataObjectHelperGenLoader;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.FilerException;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
@javax.annotation.processing.SupportedOptions({"codegen.output","codegen.generators"})
@javax.annotation.processing.SupportedSourceVersion(javax.lang.model.SourceVersion.RELEASE_8)
public class CodeGenProcessor extends AbstractProcessor {
private static final int JAVA= 0, RESOURCE = 1, OTHER = 2;
private static final String JSON_MAPPERS_PROPERTIES_PATH = "META-INF/vertx/json-mappers.properties";
public static final Logger log = Logger.getLogger(CodeGenProcessor.class.getName());
private File outputDirectory;
private List<? extends Generator<?>> codeGenerators;
private Map<String, GeneratedFile> generatedFiles = new HashMap<>();
private Map<String, GeneratedFile> generatedResources = new HashMap<>();
private Map<String, String> relocations = new HashMap<>();
private Set<Class<? extends Annotation>> supportedAnnotation = new HashSet<>();
private List<CodeGen.Converter> mappers;
@Override
public Set<String> getSupportedAnnotationTypes() {
return supportedAnnotation.stream().map(Class::getName).collect(Collectors.toSet());
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
generatedFiles.clear();
generatedResources.clear();
supportedAnnotation = new HashSet<>(Arrays.asList(DataObject.class, VertxGen.class));
getCodeGenerators()
.stream()
.flatMap(gen -> gen.annotations().stream())
.forEach(supportedAnnotation::add);
// Load mappers
if (mappers == null) {
mappers = loadJsonMappers();
}
}
private Predicate<Generator> filterGenerators() {
String generatorsOption = processingEnv.getOptions().get("codegen.generators");
if (generatorsOption != null) {
List<Pattern> wanted = Stream.of(generatorsOption.split(","))
.map(String::trim)
.map(Pattern::compile)
.collect(Collectors.toList());
return cg -> wanted.stream()
.anyMatch(p -> p.matcher(cg.name).matches());
} else {
return null;
}
}
private Collection<? extends Generator<?>> getCodeGenerators() {
if (codeGenerators == null) {
String outputDirectoryOption = processingEnv.getOptions().get("codegen.output");
if (outputDirectoryOption != null) {
outputDirectory = new File(outputDirectoryOption);
if (!outputDirectory.exists()) {
if (!outputDirectory.mkdirs()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Output directory " + outputDirectoryOption + " does not exist");
}
}
if (!outputDirectory.isDirectory()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Output directory " + outputDirectoryOption + " is not a directory");
}
}
// load GeneratorLoader by ServiceLoader
Stream<GeneratorLoader> serviceLoader = StreamSupport.stream(ServiceLoader.load(GeneratorLoader.class, CodeGenProcessor.class.getClassLoader()).spliterator(), false);
Stream<GeneratorLoader> loaders = Stream.of(new DataObjectHelperGenLoader());
Stream<Generator<?>> generators = Stream.concat(serviceLoader, loaders).flatMap(l -> l.loadGenerators(processingEnv));
Predicate<Generator> filter = filterGenerators();
if (filter != null) {
generators = generators.filter(filter);
}
generators = generators.peek(gen -> {
gen.load(processingEnv);
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Loaded " + gen.name + " code generator");
});
relocations = processingEnv.getOptions()
.entrySet()
.stream()
.filter(e -> e.getKey().startsWith("codegen.output."))
.collect(Collectors.toMap(
e -> e.getKey().substring("codegen.output.".length()),
Map.Entry::getValue)
);
codeGenerators = generators.collect(Collectors.toList());
}
return codeGenerators;
}
private static void loadJsonMappers(List<CodeGen.Converter> list, InputStream is) throws IOException {
Properties tmp = new Properties();
tmp.load(is);
tmp.stringPropertyNames().forEach(name -> {
int idx = name.lastIndexOf('.');
if (idx != -1) {
String type = name.substring(0, idx);
String value = tmp.getProperty(name);
int idx1 = value.indexOf('
if (idx1 != -1) {
String className = value.substring(0, idx1);
String rest = value.substring(idx1 + 1);
int idx2 = rest.indexOf('.');
if (idx2 != -1) {
list.add(new CodeGen.Converter(type, className, Arrays.asList(rest.substring(0, idx2), rest.substring(idx2 + 1))));
} else {
list.add(new CodeGen.Converter(type, className, Collections.singletonList(rest)));
}
}
}
});
}
/**
* This is clearly a hack and javac will complain (warning: Unclosed files for the types '[PathForCodeGenProcessor]';
* these types will not undergo annotation processing) and possibly fail the build when the {@code -Werror} compiler
* option is set.
*/
private Path determineSourcePathInEclipse() {
try {
Filer filer = processingEnv.getFiler();
if (!filer.getClass().getName().startsWith("com.sun.tools.javac")) {
JavaFileObject generationForPath = filer
.createClassFile("PathFor" + getClass().getSimpleName());
return new File(generationForPath.toUri()).toPath().getParent();
}
} catch (IOException e) {
// Possible failure (e.g with JPMS will not accept this)
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Unable to determine source file path!");
}
return null;
}
private List<CodeGen.Converter> loadJsonMappers() {
Exception exception = null;
List<CodeGen.Converter> merged = new ArrayList<>();
for (StandardLocation loc : StandardLocation.values()) {
try {
FileObject file = processingEnv.getFiler().getResource(loc, "", JSON_MAPPERS_PROPERTIES_PATH);
try(InputStream is = file.openInputStream()) {
try {
loadJsonMappers(merged, is);
exception = null;
} catch (IOException e) {
exception = e;
}
}
} catch (Exception ignore) {
exception = ignore;
// Filer#getResource and openInputStream will throw IOException when not found
}
}
if (exception != null) {
try {
Enumeration<URL> resources = getClass().getClassLoader().getResources(JSON_MAPPERS_PROPERTIES_PATH);
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
try (InputStream is = url.openStream()) {
loadJsonMappers(merged, is);
exception = null;
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Loaded json-mappers.properties " + url);
}
}
} catch (IOException e) {
exception = e;
// ignore in order to looking for the file using the source path
}
}
if (exception != null) {
Path path = determineSourcePathInEclipse();
if (path != null) {
Path source = path.getParent().getParent().resolve("src/main/resources").resolve(JSON_MAPPERS_PROPERTIES_PATH);
if (source.toFile().exists()) {
try (InputStream is = source.toUri().toURL().openStream()) {
loadJsonMappers(merged, is);
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Loaded json-mappers.properties from '" + source + "'");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not load json-mappers.properties", e);
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Unable to open properties file at " + source);
}
}
}
}
if (exception != null) {
String kaptGeneratedLocation = processingEnv.getOptions().get("kapt.kotlin.generated");
String defaultKaptGeneratedLocation = "/build/generated/source/kaptKotlin/main";
if (kaptGeneratedLocation != null && kaptGeneratedLocation.endsWith(defaultKaptGeneratedLocation)) {
File projectDir = new File(kaptGeneratedLocation.substring(0, kaptGeneratedLocation.length() - defaultKaptGeneratedLocation.length()));
Path source = projectDir.toPath().resolve("src/main/resources").resolve(JSON_MAPPERS_PROPERTIES_PATH);
if (source.toFile().exists()) {
try (InputStream is = source.toUri().toURL().openStream()) {
loadJsonMappers(merged, is);
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Loaded json-mappers.properties from '" + source + "'");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not load json-mappers.properties", e);
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Unable to open properties file at " + source);
}
}
}
}
return merged;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// find elements annotated with @SuppressWarnings("codegen-enhanced-method")
if (!roundEnv.processingOver()) {
Collection<? extends Generator> codeGenerators = getCodeGenerators();
if (!roundEnv.errorRaised()) {
CodeGen codegen = new CodeGen(processingEnv);
mappers.forEach(codegen::registerConverter);
codegen.init(roundEnv, getClass().getClassLoader());
Map<String, GeneratedFile> generatedClasses = new HashMap<>();
// Generate source code
codegen.getModels().forEach(entry -> {
try {
Model model = entry.getValue();
for (Generator codeGenerator : codeGenerators) {
if (codeGenerator.kinds.contains(model.getKind())) {
String relativeName = codeGenerator.filename(model);
if (relativeName != null) {
int kind;
if (relativeName.endsWith(".java") && !relativeName.contains("/")) {
String relocation = relocations.get(codeGenerator.name);
if (relocation != null) {
kind = OTHER;
relativeName = relocation + '/' +
relativeName.substring(0, relativeName.length() - ".java".length()).replace('.', '/') + ".java";
} else {
kind = JAVA;
}
} else if (relativeName.startsWith("resources/")) {
kind = RESOURCE;
} else {
kind = OTHER;
}
if (kind == JAVA) {
// Special handling for .java
String fqn = relativeName.substring(0, relativeName.length() - ".java".length());
// Avoid to recreate the same file (this may happen as we unzip and recompile source trees)
if (processingEnv.getElementUtils().getTypeElement(fqn) != null) {
continue;
}
List<ModelProcessing> processings = generatedClasses.computeIfAbsent(fqn, GeneratedFile::new);
processings.add(new ModelProcessing(model, codeGenerator));
} else if (kind == RESOURCE) {
relativeName = relativeName.substring("resources/".length());
List<ModelProcessing> processings = generatedResources.computeIfAbsent(relativeName, GeneratedFile::new);
processings.add(new ModelProcessing(model, codeGenerator));
} else {
List<ModelProcessing> processings = generatedFiles.computeIfAbsent(relativeName, GeneratedFile::new);
processings.add(new ModelProcessing(model, codeGenerator));
}
}
}
}
} catch (GenException e) {
reportGenException(e);
} catch (Exception e) {
reportException(e, entry.getKey());
}
});
// Generate classes
generatedClasses.values().forEach(generated -> {
boolean shouldWarningsBeSuppressed = false;
try {
String content = generated.generate();
if (content.length() > 0) {
JavaFileObject target = processingEnv.getFiler().createSourceFile(generated.uri);
try (Writer writer = target.openWriter()) {
writer.write(content);
}
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generated model " + generated.get(0).model.getFqn() + ": " + generated.uri);
}
} catch (GenException e) {
reportGenException(e);
} catch (Exception e) {
reportException(e, generated.get(0).model.getElement());
}
});
}
} else {
// Generate resources
for (GeneratedFile generated : generatedResources.values()) {
boolean shouldWarningsBeSuppressed = false;
try {
String content = generated.generate();
if (content.length() > 0) {
try (Writer w = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", generated.uri).openWriter()) {
w.write(content);
}
boolean createSource;
try {
processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT, "", generated.uri);
createSource = true;
} catch (FilerException e) {
// SOURCE_OUTPUT == CLASS_OUTPUT
createSource = false;
}
if (createSource) {
try (Writer w = processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, "", generated.uri).openWriter()) {
w.write(content);
}
}
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generated model " + generated.get(0).model.getFqn() + ": " + generated.uri);
}
} catch (GenException e) {
reportGenException(e);
} catch (Exception e) {
reportException(e, generated.get(0).model.getElement());
}
}
// Generate files
generatedFiles.values().forEach(generated -> {
Path path = new File(generated.uri).toPath();
if (path.isAbsolute()) {
// Nothing to do
} else if (outputDirectory != null) {
path = outputDirectory.toPath().resolve(path);
} else {
return;
}
File file = path.toFile();
Helper.ensureParentDir(file);
String content = generated.generate();
if (content.length() > 0) {
try (FileWriter fileWriter = new FileWriter(file)) {
fileWriter.write(content);
} catch (GenException e) {
reportGenException(e);
} catch (Exception e) {
reportException(e, generated.get(0).model.getElement());
}
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generated model " + generated.get(0).model.getFqn() + ": " + generated.uri);
}
});
}
return true;
}
private void reportGenException(GenException e) {
String name = e.element.toString();
if (e.element.getKind() == ElementKind.METHOD) {
name = e.element.getEnclosingElement() + "#" + name;
}
String msg = "Could not generate model for " + name + ": " + e.msg;
log.log(Level.SEVERE, msg, e);
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, e.element);
}
private void reportException(Exception e, Element elt) {
String msg = "Could not generate element for " + elt + ": " + e.getMessage();
log.log(Level.SEVERE, msg, e);
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, elt);
}
private static class ModelProcessing {
final Model model;
final Generator generator;
public ModelProcessing(Model model, Generator generator) {
this.model = model;
this.generator = generator;
}
}
private static class GeneratedFile extends ArrayList<ModelProcessing> {
private final String uri;
private final Map<String, Object> session = new HashMap<>();
public GeneratedFile(String uri) {
super();
this.uri = uri;
}
@Override
public boolean add(ModelProcessing modelProcessing) {
if (!modelProcessing.generator.incremental) {
clear();
}
return super.add(modelProcessing);
}
String generate() {
Collections.sort(this, (o1, o2) ->
o1.model.getElement().getSimpleName().toString().compareTo(
o2.model.getElement().getSimpleName().toString()));
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < size(); i++) {
ModelProcessing processing = get(i);
try {
String part = processing.generator.render(processing.model, i, size(), session);
if (part != null) {
buffer.append(part);
}
} catch (GenException e) {
throw e;
} catch (Exception e) {
GenException genException = new GenException(processing.model.getElement(), e.getMessage());
genException.initCause(e);
throw genException;
}
}
return buffer.toString();
}
}
} |
package mariculture.plugins.nei;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import mariculture.aesthetics.Aesthetics;
import mariculture.api.core.MaricultureHandlers;
import mariculture.api.fishery.Fishing;
import mariculture.api.fishery.fish.FishSpecies;
import mariculture.core.Core;
import mariculture.core.config.FishMechanics;
import mariculture.core.config.GeneralStuff;
import mariculture.core.lib.CoralMeta;
import mariculture.core.lib.CraftingMeta;
import mariculture.core.lib.FoodMeta;
import mariculture.core.lib.GlassMeta;
import mariculture.core.lib.GroundMeta;
import mariculture.core.lib.LimestoneMeta;
import mariculture.core.lib.MachineMeta;
import mariculture.core.lib.MachineMultiMeta;
import mariculture.core.lib.MachineRenderedMeta;
import mariculture.core.lib.MachineRenderedMultiMeta;
import mariculture.core.lib.MaterialsMeta;
import mariculture.core.lib.MetalMeta;
import mariculture.core.lib.Modules;
import mariculture.core.lib.PearlColor;
import mariculture.core.lib.RockMeta;
import mariculture.core.lib.TankMeta;
import mariculture.core.lib.TransparentMeta;
import mariculture.core.lib.WaterMeta;
import mariculture.core.lib.WoodMeta;
import mariculture.factory.Factory;
import mariculture.fishery.Fishery;
import mariculture.magic.JewelryHandler;
import mariculture.magic.Magic;
import mariculture.magic.jewelry.ItemJewelry;
import mariculture.magic.jewelry.ItemJewelry.JewelryType;
import mariculture.magic.jewelry.parts.JewelryBinding;
import mariculture.magic.jewelry.parts.JewelryMaterial;
import mariculture.plugins.nei.NEIAnvilRecipeHandler.RecipeJewelry;
import mariculture.world.WorldPlus;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData;
import net.minecraftforge.oredict.OreDictionary;
import codechicken.nei.api.API;
import codechicken.nei.api.IConfigureNEI;
public class NEIConfig implements IConfigureNEI {
public static final HashMap<String, ArrayList<ItemStack>> containers = new HashMap();
@Override
public void loadConfig() {
for (int i = 0; i < CraftingMeta.COUNT; i++) {
API.addItemListEntry(new ItemStack(Core.crafting, 1, i));
}
for (int i = 0; i < MaterialsMeta.COUNT; i++) {
API.addItemListEntry(new ItemStack(Core.materials, 1, i));
}
//HOLY HIDE IN NEI!
for (int i = 0; i < 16; i++) {
if (i >= CoralMeta.COUNT) {
if (Modules.isActive(Modules.worldplus)) {
API.hideItem(new ItemStack(WorldPlus.plantGrowable, 1, i));
API.hideItem(new ItemStack(WorldPlus.plantStatic, 1, i));
}
}
if (i >= FoodMeta.COUNT) API.hideItem(new ItemStack(Core.food, 1, i));
if (i >= GlassMeta.COUNT) API.hideItem(new ItemStack(Core.glass, 1, i));
if (i >= TransparentMeta.COUNT) API.hideItem(new ItemStack(Core.transparent, 1, i));
if (i >= WaterMeta.COUNT) API.hideItem(new ItemStack(Core.water, 1, i));
if (i >= GroundMeta.COUNT) API.hideItem(new ItemStack(Core.sands, 1, i));
if (i >= WoodMeta.COUNT) API.hideItem(new ItemStack(Core.woods, 1, i));
if (i >= MetalMeta.COUNT) API.hideItem(new ItemStack(Core.metals, 1, i));
if (i >= MachineMultiMeta.COUNT) API.hideItem(new ItemStack(Core.machinesMulti, 1, i));
if (i >= TankMeta.COUNT) API.hideItem(new ItemStack(Core.tanks, 1, i));
if (i >= MachineRenderedMultiMeta.COUNT) API.hideItem(new ItemStack(Core.renderedMachinesMulti, 1, i));
if (i >= RockMeta.COUNT) API.hideItem(new ItemStack(Core.rocks, 1, i));
if (i >= MachineMeta.COUNT) API.hideItem(new ItemStack(Core.machines, 1, i));
if (i >= MachineRenderedMeta.COUNT) API.hideItem(new ItemStack(Core.renderedMachines, 1, i));
if (i >= PearlColor.COUNT) {
API.hideItem(new ItemStack(Core.pearlBlock, 1, i));
if (Modules.isActive(Modules.aesthetics)) {
API.hideItem(new ItemStack(Aesthetics.pearlBrick, 1, i));
}
if (Modules.isActive(Modules.fishery)) {
API.hideItem(new ItemStack(Fishery.lampsOn, 1, i));
}
}
}
API.hideItem(new ItemStack(Core.tanks, 1, TankMeta.BOTTLE));
API.hideItem(new ItemStack(Core.limestone, 1, LimestoneMeta.PILLAR_2));
API.hideItem(new ItemStack(Core.limestone, 1, LimestoneMeta.PILLAR_3));
API.hideItem(new ItemStack(Core.limestone, 1, LimestoneMeta.PEDESTAL_2));
API.hideItem(new ItemStack(Core.limestone, 1, LimestoneMeta.PEDESTAL_3));
API.hideItem(new ItemStack(Core.limestone, 1, LimestoneMeta.PEDESTAL_4));
API.hideItem(new ItemStack(Core.limestone, 1, LimestoneMeta.PEDESTAL_5));
API.hideItem(new ItemStack(Core.limestone, 1, LimestoneMeta.PEDESTAL_6));
for(int i = MaterialsMeta.EMPTY_START; i <= MaterialsMeta.EMPTY_END; i++) {
API.hideItem(new ItemStack(Core.materials, 1, i));
}
if (Modules.isActive(Modules.fishery)) {
API.registerRecipeHandler(new NEIFishProductHandler());
API.registerUsageHandler(new NEIFishProductHandler());
API.hideItem(new ItemStack(Fishery.lampsOff, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Fishery.fishEggs, 1, OreDictionary.WILDCARD_VALUE));
API.registerRecipeHandler(new NEISifterRecipeHandler());
API.registerUsageHandler(new NEISifterRecipeHandler());
API.registerRecipeHandler(new NEIFishBreedingMutationHandler());
API.registerUsageHandler(new NEIFishBreedingMutationHandler());
if (FishMechanics.DISABLE_FISH) {
API.hideItem(new ItemStack(Fishery.fishy));
} else {
for (Entry<Integer, FishSpecies> species : FishSpecies.species.entrySet()) {
FishSpecies fishy = species.getValue();
ItemStack fish = Fishing.fishHelper.makePureFish(fishy);
API.addItemListEntry(fish);
}
}
}
//Hide Unusued Turbine Entries
API.hideItem(new ItemStack(Core.renderedMachines, 1, MachineRenderedMeta.REMOVED_1));
API.hideItem(new ItemStack(Core.renderedMachines, 1, MachineRenderedMeta.REMOVED_2));
API.hideItem(new ItemStack(Core.renderedMachines, 1, MachineRenderedMeta.REMOVED_3));
API.registerRecipeHandler(new NEICrucibleRecipeHandler());
API.registerUsageHandler(new NEICrucibleRecipeHandler());
API.registerRecipeHandler(new NEIVatRecipeHandler());
API.registerUsageHandler(new NEIVatRecipeHandler());
API.registerRecipeHandler(new NEIAnvilRecipeHandler());
API.registerUsageHandler(new NEIAnvilRecipeHandler());
if (GeneralStuff.SHOW_CASTER_RECIPES) {
API.registerRecipeHandler(new NEIIngotCasterRecipeHandler());
API.registerUsageHandler(new NEIIngotCasterRecipeHandler());
API.registerRecipeHandler(new NEIBlockCasterRecipeHandler());
API.registerUsageHandler(new NEIBlockCasterRecipeHandler());
API.registerRecipeHandler(new NEINuggetCasterRecipeHandler());
API.registerUsageHandler(new NEINuggetCasterRecipeHandler());
}
API.hideItem(new ItemStack(Core.air, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Core.ticking, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Core.worked, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Core.renderedMachines, 1, 1));
if (Modules.isActive(Modules.factory)) {
API.hideItem(new ItemStack(Factory.customBlock, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Factory.customFence, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Factory.customFlooring, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Factory.customGate, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Factory.customLight, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Factory.customRFBlock, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Factory.customSlabs, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Factory.customSlabsDouble, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Factory.customStairs, 1, OreDictionary.WILDCARD_VALUE));
API.hideItem(new ItemStack(Factory.customWall, 1, OreDictionary.WILDCARD_VALUE));
}
FluidContainerData[] data = FluidContainerRegistry.getRegisteredFluidContainerData().clone();
for (FluidContainerData container : data) {
String fluid = container.fluid.getFluid().getName();
if (containers.containsKey("fluid")) {
ArrayList<ItemStack> list = containers.get(fluid);
list.add(container.filledContainer);
} else {
ArrayList<ItemStack> list = new ArrayList<ItemStack>();
list.add(container.filledContainer);
containers.put(fluid, list);
}
}
if (Modules.isActive(Modules.magic)) {
API.registerRecipeHandler(new NEIJewelryShapedHandler());
API.registerUsageHandler(new NEIJewelryShapedHandler());
addJewelry((ItemJewelry) Magic.ring);
addJewelry((ItemJewelry) Magic.bracelet);
addJewelry((ItemJewelry) Magic.necklace);
}
}
private void addJewelry(ItemJewelry item) {
JewelryType type = item.getType();
for (Entry<String, JewelryBinding> binding : JewelryBinding.list.entrySet()) {
if (binding.getValue().ignore) {
continue;
}
for (Entry<String, JewelryMaterial> material : JewelryMaterial.list.entrySet()) {
if (material.getValue().ignore) {
continue;
}
JewelryBinding bind = binding.getValue();
JewelryMaterial mat = material.getValue();
ItemStack worked = JewelryHandler.createJewelry(item, bind, mat);
ItemStack output = JewelryHandler.createJewelry(item, binding.getValue(), material.getValue());
int hits = (int) (bind.getHitsBase(type) * mat.getHitsModifier(type));
NEIAnvilRecipeHandler.jewelry.put(output, new RecipeJewelry(MaricultureHandlers.anvil.createWorkedItem(worked, hits), hits));
}
}
}
@Override
public String getName() {
return "Mariculture NEI";
}
@Override
public String getVersion() {
return "1.0";
}
} |
package mcjty.deepresonance;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStoppedEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import mcjty.base.ModBase;
import mcjty.base.ModBaseRef;
import mcjty.deepresonance.blocks.ModBlocks;
import mcjty.deepresonance.crafting.ModCrafting;
import mcjty.deepresonance.items.ModItems;
import mcjty.deepresonance.worldgen.WorldGen;
import mcjty.gui.GuiStyle;
import mcjty.network.PacketHandler;
import mcjty.varia.Logging;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraftforge.common.config.Configuration;
import java.io.File;
@Mod(modid = DeepResonance.MODID, name="DeepResonance", dependencies = "required-after:Forge@["+DeepResonance.MIN_FORGE_VER+",);required-after:CoFHCore@["+DeepResonance.MIN_COFHCORE_VER+",)", version = DeepResonance.VERSION)
public class DeepResonance implements ModBase {
public static final String MODID = "deepresonance";
public static final String VERSION = "0.01alpha1";
public static final String MIN_FORGE_VER = "10.13.2.1291";
public static final String MIN_COFHCORE_VER = "1.7.10R3.0.0B9";
@SidedProxy(clientSide="mcjty.deepresonance.ClientProxy", serverSide="mcjty.deepresonance.ServerProxy")
public static CommonProxy proxy;
@Mod.Instance("deepresonance")
public static DeepResonance instance;
/** This is used to keep track of GUIs that we make*/
private static int modGuiIndex = 0;
public static final int GUI_MANUAL_MAIN = modGuiIndex++;
public static CreativeTabs tabDeepResonance = new CreativeTabs("DeepResonance") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return Item.getItemFromBlock(ModBlocks.resonatingCrystalBlock);
}
};
/**
* Run before anything else. Read your config, create blocks, items, etc, and
* register them with the GameRegistry.
*/
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent e) {
ModBaseRef.INSTANCE = this;
ModBaseRef.MODID = MODID;
this.proxy.preInit(e);
// modConfigDir = e.getModConfigurationDirectory();
// mainConfig = new Configuration(new File(modConfigDir.getPath() + File.separator + "rftools", "main.cfg"));
// readMainConfig();
// PacketHandler.registerMessages("rftools");
// RFToolsMessages.registerNetworkMessages();
ModItems.init();
ModBlocks.init();
ModCrafting.init();
WorldGen.init();
}
/**
* Do your mod setup. Build whatever data structures you care about. Register recipes.
*/
@Mod.EventHandler
public void init(FMLInitializationEvent e) {
this.proxy.init(e);
}
@Mod.EventHandler
public void serverStopped(FMLServerStoppedEvent event) {
Logging.log("Deep Resonance: server is stopping. Shutting down gracefully");
}
/**
* Handle interaction with other mods, complete your setup based on this.
*/
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent e) {
this.proxy.postInit(e);
if (Loader.isModLoaded("ComputerCraft")) {
Logging.log("Deep Resonance Detected ComputerCraft: enabling support");
// ComputerCraftHelper.register();
}
}
@Override
public void setGuiStyle(EntityPlayerMP entityPlayerMP, GuiStyle guiStyle) {
}
@Override
public GuiStyle getGuiStyle(EntityPlayer entityPlayer) {
return null;
}
@Override
public void openManual(EntityPlayer entityPlayer, int i, String s) {
}
} |
package me.lorinlee.network;
import me.lorinlee.handler.Handler;
import me.lorinlee.handler.HandlerDispatcher;
import me.lorinlee.request.Request;
import java.io.*;
import java.net.Socket;
public class RequestSocket {
private Socket socket = null;
private BufferedReader bufferedReader = null;
private BufferedWriter bufferedWriter = null;
private HandleThread handleThread = null;
private volatile boolean status = true;
private RequestSocket() {
}
private static class RequestSocketHolder {
private final static RequestSocket REQUEST_SOCKET = new RequestSocket();
}
public static RequestSocket getInstance() {
return RequestSocketHolder.REQUEST_SOCKET;
}
public void setSocket(Socket socket) throws IOException {
if (this.socket != null) this.close();
this.socket = socket;
this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
this.handleThread = new HandleThread(bufferedReader);
this.handleThread.start();
}
public void close() throws IOException {
if (this.bufferedWriter != null) {
this.bufferedWriter.close();
this.bufferedWriter = null;
}
if (this.bufferedReader != null) {
this.bufferedReader.close();
this.bufferedReader = null;
}
if (this.socket != null ) {
this.socket.close();
this.socket = null;
}
if (this.handleThread != null) {
this.handleThread.setFlag(false);
this.handleThread = null;
}
}
public void sendRequest(Request request) {
try {
bufferedWriter.write(request.toString());
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private class HandleThread extends Thread {
private BufferedReader bufferedReader;
private volatile boolean flag = true;
public HandleThread(BufferedReader bufferedReader) {
this.bufferedReader = bufferedReader;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
String readLine;
try {
while ((readLine = bufferedReader.readLine()) != null && flag) {
HandlerDispatcher.getHandler(readLine).handle();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
} |
package net.glowstone.io.anvil;
/*
* Later changes made by the Glowstone project.
*/
// Interfaces with region files on the disk
/*
Region File Format
Concept: The minimum unit of storage on hard drives is 4KB. 90% of Minecraft
chunks are smaller than 4KB. 99% are smaller than 8KB. Write a simple
container to store chunks in single files in runs of 4KB sectors.
Each region file represents a 32x32 group of chunks. The conversion from
chunk number to region number is floor(coord / 32): a chunk at (30, -3)
would be in region (0, -1), and one at (70, -30) would be at (3, -1).
Region files are named "r.x.z.data", where x and z are the region coordinates.
A region file begins with a 4KB header that describes where chunks are stored
in the file. A 4-byte big-endian integer represents sector offsets and sector
counts. The chunk offset for a chunk (x, z) begins at byte 4*(x+z*32) in the
file. The bottom byte of the chunk offset indicates the number of sectors the
chunk takes up, and the top 3 bytes represent the sector number of the chunk.
Given a chunk offset o, the chunk data begins at byte 4096*(o/256) and takes up
at most 4096*(o%256) bytes. A chunk cannot exceed 1MB in size. If a chunk
offset is 0, the corresponding chunk is not stored in the region file.
Chunk data begins with a 4-byte big-endian integer representing the chunk data
length in bytes, not counting the length field. The length must be smaller than
4096 times the number of sectors. The next byte is a version field, to allow
backwards-compatible updates to how chunks are encoded.
A version of 1 represents a gzipped NBT file. The gzipped data is the chunk
length - 1.
A version of 2 represents a deflated (zlib compressed) NBT file. The deflated
data is the chunk length - 1.
*/
import net.glowstone.GlowServer;
import java.io.*;
import java.util.ArrayList;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
public class RegionFile {
private static final int VERSION_GZIP = 1;
private static final int VERSION_DEFLATE = 2;
private static final int SECTOR_BYTES = 4096;
private static final int SECTOR_INTS = SECTOR_BYTES / 4;
private static final int CHUNK_HEADER_SIZE = 5;
private static final byte[] emptySector = new byte[SECTOR_BYTES];
private RandomAccessFile file;
private final int[] offsets;
private final int[] chunkTimestamps;
private ArrayList<Boolean> sectorFree;
private int sizeDelta;
private long lastModified = 0;
public RegionFile(File path) throws IOException {
offsets = new int[SECTOR_INTS];
chunkTimestamps = new int[SECTOR_INTS];
sizeDelta = 0;
if (path.exists()) {
lastModified = path.lastModified();
}
file = new RandomAccessFile(path, "rw");
// seek to the end to prepare size checking
file.seek(file.length());
// if the file size is under 8KB, grow it (4K chunk offset table, 4K timestamp table)
if (file.length() < 2 * SECTOR_BYTES) {
sizeDelta += 2 * SECTOR_BYTES - file.length();
if (lastModified != 0) {
// only give a warning if the region file existed beforehand
GlowServer.logger.warning("Region \"" + path + "\" under 8K: " + file.length() + " increasing by " + (2 * SECTOR_BYTES - file.length()));
}
for (long i = file.length(); i < 2 * SECTOR_BYTES; ++i) {
file.write(0);
}
}
// if the file size is not a multiple of 4KB, grow it
if ((file.length() & 0xfff) != 0) {
sizeDelta += SECTOR_BYTES - (file.length() & 0xfff);
GlowServer.logger.warning("Region \"" + path + "\" not aligned: " + file.length() + " increasing by " + (SECTOR_BYTES - (file.length() & 0xfff)));
for (long i = file.length() & 0xfff; i < SECTOR_BYTES; ++i) {
file.write(0);
}
}
// set up the available sector map
int nSectors = (int) (file.length() / SECTOR_BYTES);
sectorFree = new ArrayList<>(nSectors);
for (int i = 0; i < nSectors; ++i) {
sectorFree.add(true);
}
sectorFree.set(0, false); // chunk offset table
sectorFree.set(1, false); // for the last modified info
// read offsets from offset table
file.seek(0);
for (int i = 0; i < SECTOR_INTS; ++i) {
int offset = file.readInt();
offsets[i] = offset;
int startSector = (offset >> 8);
int numSectors = (offset & 0xff);
if (offset != 0 && startSector >= 0 && startSector + numSectors <= sectorFree.size()) {
for (int sectorNum = 0; sectorNum < numSectors; ++sectorNum) {
sectorFree.set(startSector + sectorNum, false);
}
} else if (offset != 0) {
GlowServer.logger.warning("Region \"" + path + "\": offsets[" + i + "] = " + offset + " -> " + startSector + "," + numSectors + " does not fit");
}
}
// read timestamps from timestamp table
for (int i = 0; i < SECTOR_INTS; ++i) {
chunkTimestamps[i] = file.readInt();
}
}
/* the modification date of the region file when it was first opened */
public long getLastModified() {
return lastModified;
}
/* gets how much the region file has grown since it was last checked */
public int getSizeDelta() {
int ret = sizeDelta;
sizeDelta = 0;
return ret;
}
/*
* gets an (uncompressed) stream representing the chunk data returns null if
* the chunk is not found or an error occurs
*/
public DataInputStream getChunkDataInputStream(int x, int z) throws IOException {
checkBounds(x, z);
int offset = getOffset(x, z);
if (offset == 0) {
// does not exist
return null;
}
int sectorNumber = offset >> 8;
int numSectors = offset & 0xFF;
if (sectorNumber + numSectors > sectorFree.size()) {
throw new IOException("Invalid sector: " + sectorNumber + "+" + numSectors + " > " + sectorFree.size());
}
file.seek(sectorNumber * SECTOR_BYTES);
int length = file.readInt();
if (length > SECTOR_BYTES * numSectors) {
throw new IOException("Invalid length: " + length + " > " + (SECTOR_BYTES * numSectors));
}
byte version = file.readByte();
if (version == VERSION_GZIP) {
byte[] data = new byte[length - 1];
file.read(data);
return new DataInputStream(new GZIPInputStream(new ByteArrayInputStream(data)));
} else if (version == VERSION_DEFLATE) {
byte[] data = new byte[length - 1];
file.read(data);
return new DataInputStream(new InflaterInputStream(new ByteArrayInputStream(data)));
}
throw new IOException("Unknown version: " + version);
}
public DataOutputStream getChunkDataOutputStream(int x, int z) {
checkBounds(x, z);
return new DataOutputStream(new BufferedOutputStream(new DeflaterOutputStream(new ChunkBuffer(x, z), new Deflater(Deflater.BEST_SPEED))));
}
/*
* lets chunk writing be multithreaded by not locking the whole file as a
* chunk is serializing -- only writes when serialization is over
*/
class ChunkBuffer extends ByteArrayOutputStream {
private final int x, z;
public ChunkBuffer(int x, int z) {
super(8096); // initialize to 8KB
this.x = x;
this.z = z;
}
@Override
public void close() throws IOException {
try {
RegionFile.this.write(x, z, buf, count);
} finally {
super.close();
}
}
}
/* write a chunk at (x,z) with length bytes of data to disk */
protected void write(int x, int z, byte[] data, int length) throws IOException {
int offset = getOffset(x, z);
int sectorNumber = offset >> 8;
int sectorsAllocated = offset & 0xFF;
int sectorsNeeded = (length + CHUNK_HEADER_SIZE) / SECTOR_BYTES + 1;
// maximum chunk size is 1MB
if (sectorsNeeded >= 256) {
return;
}
if (sectorNumber != 0 && sectorsAllocated == sectorsNeeded) {
/* we can simply overwrite the old sectors */
write(sectorNumber, data, length);
} else {
/* we need to allocate new sectors */
/* mark the sectors previously used for this chunk as free */
for (int i = 0; i < sectorsAllocated; ++i) {
sectorFree.set(sectorNumber + i, true);
}
/* scan for a free space large enough to store this chunk */
int runStart = sectorFree.indexOf(true);
int runLength = 0;
if (runStart != -1) {
for (int i = runStart; i < sectorFree.size(); ++i) {
if (runLength != 0) {
if (sectorFree.get(i)) runLength++;
else runLength = 0;
} else if (sectorFree.get(i)) {
runStart = i;
runLength = 1;
}
if (runLength >= sectorsNeeded) {
break;
}
}
}
if (runLength >= sectorsNeeded) {
/* we found a free space large enough */
sectorNumber = runStart;
setOffset(x, z, (sectorNumber << 8) | sectorsNeeded);
for (int i = 0; i < sectorsNeeded; ++i) {
sectorFree.set(sectorNumber + i, false);
}
write(sectorNumber, data, length);
} else {
/*
* no free space large enough found -- we need to grow the
* file
*/
file.seek(file.length());
sectorNumber = sectorFree.size();
for (int i = 0; i < sectorsNeeded; ++i) {
file.write(emptySector);
sectorFree.add(false);
}
sizeDelta += SECTOR_BYTES * sectorsNeeded;
write(sectorNumber, data, length);
setOffset(x, z, (sectorNumber << 8) | sectorsNeeded);
}
}
setTimestamp(x, z, (int) (System.currentTimeMillis() / 1000L));
//file.getChannel().force(true);
}
/* write a chunk data to the region file at specified sector number */
private void write(int sectorNumber, byte[] data, int length) throws IOException {
file.seek(sectorNumber * SECTOR_BYTES);
file.writeInt(length + 1); // chunk length
file.writeByte(VERSION_DEFLATE); // chunk version number
file.write(data, 0, length); // chunk data
}
/* is this an invalid chunk coordinate? */
private void checkBounds(int x, int z) {
if (x < 0 || x >= 32 || z < 0 || z >= 32) {
throw new IllegalArgumentException("Chunk out of bounds: (" + x + ", " + z + ")");
}
}
private int getOffset(int x, int z) {
return offsets[x + z * 32];
}
public boolean hasChunk(int x, int z) {
return getOffset(x, z) != 0;
}
private void setOffset(int x, int z, int offset) throws IOException {
offsets[x + z * 32] = offset;
file.seek((x + z * 32) * 4);
file.writeInt(offset);
}
private void setTimestamp(int x, int z, int value) throws IOException {
chunkTimestamps[x + z * 32] = value;
file.seek(SECTOR_BYTES + (x + z * 32) * 4);
file.writeInt(value);
}
public void close() throws IOException {
file.getChannel().force(true);
file.close();
}
} |
package nl.tudelft.dnainator.ui;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Screen;
import javafx.stage.Stage;
import java.io.IOException;
/**
* DNAinator's main window, from which all interaction will occur.
* <p>
* The {@link #start(Stage) start} method will automatically load
* the required fxml files, which in turn instantiates all controllers.
* </p>
*/
public class DNAinator extends Application {
private static final String DNAINATOR = "DNAinator";
private static final String FXML = "/ui/fxml/dnainator.fxml";
private static final String ICON = "/ui/dnainator.iconset/icon_512x512.png";
private static final int MIN_WIDTH = 300;
private static final int MIN_HEIGHT = 150;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle(DNAINATOR);
primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON)));
setDimensions(primaryStage);
try {
BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML));
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
} catch (IOException e) {
e.printStackTrace();
}
primaryStage.show();
}
private void setDimensions(Stage stage) {
Rectangle2D bounds = Screen.getPrimary().getVisualBounds();
stage.setMinHeight(MIN_HEIGHT);
stage.setMinWidth(MIN_WIDTH);
stage.setWidth(bounds.getWidth());
stage.setHeight(bounds.getHeight());
/* Add this for better Windows LAF. */
stage.setMaximized(true);
}
} |
package org.animotron.statement.query;
import javolution.util.FastMap;
import javolution.util.FastSet;
import org.animotron.Executor;
import org.animotron.graph.AnimoGraph;
import org.animotron.graph.GraphOperation;
import org.animotron.graph.index.Order;
import org.animotron.io.PipedInput;
import org.animotron.manipulator.Evaluator;
import org.animotron.manipulator.OnQuestion;
import org.animotron.manipulator.PFlow;
import org.animotron.manipulator.QCAVector;
import org.animotron.statement.Statement;
import org.animotron.statement.Statements;
import org.animotron.statement.operator.*;
import org.animotron.statement.relation.IC;
import org.jetlang.channels.Subscribable;
import org.jetlang.core.DisposingExecutor;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.index.IndexHits;
import org.neo4j.graphdb.traversal.Evaluation;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.kernel.Traversal;
import org.neo4j.kernel.Uniqueness;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import static org.animotron.Properties.RID;
import static org.neo4j.graphdb.Direction.OUTGOING;
import static org.animotron.graph.RelationshipTypes.RESULT;
/**
* Query operator 'Get'. Return 'have' relations on provided context.
*
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*/
public class GET extends AbstractQuery implements Evaluable, Shift {
public static final GET _ = new GET();
private static boolean debug = true;
private GET() { super("get"); }
TraversalDescription td = Traversal.description().
depthFirst().uniqueness(Uniqueness.RELATIONSHIP_PATH);
private static TraversalDescription td_eval_ic =
Traversal.description().
breadthFirst().
relationships(AN._, OUTGOING).
relationships(IC._, OUTGOING);
public OnQuestion onCalcQuestion() {
return question;
}
private OnQuestion question = new OnQuestion() {
@Override
public void onMessage(final PFlow pf) {
final Relationship op = pf.getOP();
final Node node = op.getEndNode();
final Set<Relationship> visitedREFs = new FastSet<Relationship>();
final Set<Node> thes = new FastSet<Node>();
for (QCAVector theNode : AN.getREFs(pf, op)) {
thes.add(theNode.getAnswer().getEndNode());
}
evalGet(pf, op, node, thes, visitedREFs);
pf.await();
pf.done();
}
private void evalGet(
final PFlow pf,
final Relationship op,
final Node node,
final Set<Node> thes,
final Set<Relationship> visitedREFs) {
Utils.debug(GET._, op, thes);
//check, maybe, result was already calculated
if (!Utils.results(pf)) {
//no pre-calculated result, calculate it
Subscribable<QCAVector> onContext = new Subscribable<QCAVector>() {
@Override
public void onMessage(QCAVector vector) {
if (debug) System.out.println("GET ["+op+"] vector "+vector);
if (vector == null) {
pf.countDown();
return;
}
QCAVector nV = new QCAVector(null, vector.getUnrelaxedAnswer(), vector.getContext());
//final Relationship have = searchForHAVE(context, name);
final Set<QCAVector> rSet = get(pf, op, nV, thes, visitedREFs);//new QCAVector(null, vector.getUnrelaxedAnswer())
if (rSet != null) {
for (QCAVector v : rSet) {
pf.sendAnswer(v, RESULT);
}
}
// Relationship have = searchForHAVE(pf, vector.getUnrelaxedAnswer(), thes);
// if (have != null && !pf.isInStack(have)) {
// pf.sendAnswer(new QCAVector(op, vector, have));
}
@Override
public DisposingExecutor getQueue() {
return Executor.getFiber();
}
};
pf.answer.subscribe(onContext);
if (Utils.haveContext(pf)) {
super.onMessage(pf);
} else {
boolean first = true;
Set<QCAVector> rSet = null;
for (QCAVector vector : pf.getPFlowPath()) {
System.out.println("CHECK PFLOW "+vector);
if (first) {
first = false;
if (vector.getContext() == null) continue;
Set<QCAVector> refs = new FastSet<QCAVector>();
for (QCAVector v : vector.getContext()) {
refs.add(v);
}
rSet = get(pf, op, refs, thes, visitedREFs);
} else {
rSet = get(pf, op, vector, thes, visitedREFs);
}
if (rSet != null) {
for (QCAVector v : rSet) {
pf.sendAnswer(v, RESULT);
}
break;
}
}
}
}
};
};
public Set<QCAVector> get(PFlow pf, Relationship op, QCAVector vector, final Set<Node> thes, Set<Relationship> visitedREFs) {
Set<QCAVector> refs = new FastSet<QCAVector>();
refs.add(vector);
return get(pf, op, refs, thes, visitedREFs);
}
public Set<QCAVector> get(final PFlow pf, Relationship op, Node ref, final Set<Node> thes, final Set<Relationship> visitedREFs) {
Set<QCAVector> set = new FastSet<QCAVector>();
Relationship[] have = searchForHAVE(pf, null, ref, thes);
if (have != null) {
for (int i = 0; i < have.length; i++) {
if (!pf.isInStack(have[i]))
set.add(new QCAVector(pf.getOP(), have[i]));
}
}
if (!set.isEmpty()) return set;
Set<QCAVector> newREFs = new FastSet<QCAVector>();
getOutgoingReferences(pf, null, ref, newREFs, null);
return get(pf, op, newREFs, thes, visitedREFs);
}
private boolean check(Set<QCAVector> set, final PFlow pf, final Relationship op, final QCAVector v, final Relationship toCheck, final Set<Node> thes, Set<Relationship> visitedREFs) {
if (toCheck == null) return false;
visitedREFs.add(toCheck);
Relationship[] have = searchForHAVE(pf, toCheck, thes);
if (have != null) {
boolean added = false;
for (int i = 0; i < have.length; i++) {
if (!pf.isInStack(have[i])) {
set.add(new QCAVector(op, v, have[i]));
added = true;
}
}
return added;
}
return false;
}
public Set<QCAVector> get(
final PFlow pf,
final Relationship op,
final Set<QCAVector> REFs,
final Set<Node> thes,
Set<Relationship> visitedREFs) {
//System.out.println("GET context = "+ref);
if (visitedREFs == null) visitedREFs = new FastSet<Relationship>();
Set<QCAVector> set = new FastSet<QCAVector>();
Set<QCAVector> nextREFs = new FastSet<QCAVector>();
nextREFs.addAll(REFs);
//boolean first = true;
Relationship t = null;
while (true) {
if (debug) System.out.println("nextREFs ");//+Arrays.toString(nextREFs.toArray()));
for (QCAVector v : nextREFs) {
if (debug) System.out.println("checking "+v);
if (!check(set, pf, op, v, v.getUnrelaxedAnswer(), thes, visitedREFs)) {
check(set, pf, op, v, v.getQuestion(), thes, visitedREFs);
}
}
if (set.size() > 0) return set;
Set<QCAVector> newREFs = new FastSet<QCAVector>();
for (QCAVector vector : nextREFs) {
QCAVector[] cs = vector.getContext();
if (cs != null) {
for (QCAVector c : cs) {
t = c.getUnrelaxedAnswer();
if (t != null && !visitedREFs.contains(t))
newREFs.add(c);
else {
t = c.getQuestion();
if (!visitedREFs.contains(t))
newREFs.add(c);
}
}
}
// Relationship n = vector.getClosest();
// //System.out.println(""+n);
// //System.out.println("getStartNode OUTGOING");
// if (first || !REFs.contains(n)) {
// IndexHits<Relationship> it = Order.queryDown(n.getStartNode());
// try {
// for (Relationship r : it) {
// if (r.equals(n)) continue;
// //System.out.println(r);
// Statement st = Statements.relationshipType(r);
// if (st instanceof AN) {
// for (QCAVector v : AN.getREFs(pf, r)) {
// Relationship t = v.getAnswer();
// if (!visitedREFs.contains(t))
// newREFs.add(v);
// } else if (st instanceof Reference) {
// try {
// if (!pf.isInStack(r)) {
// PipedInput<QCAVector> in = Evaluator._.execute(new PFlow(pf), r);
// for (QCAVector rr : in) {
// if (!visitedREFs.contains(rr.getAnswer()))
// newREFs.add(rr);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } finally {
// it.close();
// first = false;
// //System.out.println("getEndNode OUTGOING");
t = vector.getUnrelaxedAnswer();
if (t != null) {
if (! t.isType(AN._))
getOutgoingReferences(pf, t, t.getStartNode(), newREFs, visitedREFs);
getOutgoingReferences(pf, t, t.getEndNode(), newREFs, visitedREFs);
}
}
if (newREFs.size() == 0) return null;
nextREFs = newREFs;
}
}
private void getOutgoingReferences(PFlow pf, Relationship rr, Node node, Set<QCAVector> newREFs, Set<Relationship> visitedREFs) {
IndexHits<Relationship> it = Order.queryDown(node);
try {
boolean first = rr == null || !rr.isType(REF._);
for (Relationship r : it) {
//System.out.println(r);
if (first) {
first = false;
continue;
}
if (r.isType(REF._)) continue;
Statement st = Statements.relationshipType(r);
if (st instanceof AN) {
//System.out.println(r);
for (QCAVector v : AN.getREFs(pf, r)) {
Relationship t = v.getAnswer();
//System.out.println(t);
if (visitedREFs != null && !visitedREFs.contains(t))
newREFs.add(v);
}
} else if (st instanceof Reference) {
if (!pf.isInStack(r)) {
try {
PipedInput<QCAVector> in = Evaluator._.execute(new PFlow(pf, r), r);
for (QCAVector v : in) {
if (visitedREFs != null && !visitedREFs.contains(v.getAnswer()))
newREFs.add(v);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
pf.sendException(e);
} finally {
it.close();
}
}
private Relationship[] searchForHAVE(
final PFlow pf,
final Relationship ref,
final Set<Node> thes) {
boolean checkStart = true;
// if (!ref.isType(RESULT) || !(ref.isType(REF) || ref.isType(org.animotron.statement.operator.REF._))) {
//System.out.print("WRONG WRONG WRONG WRONG ref = "+ref+" - "+ref.getType());
// try {
// System.out.print(" "+reference(ref));
// } catch (Exception e) {
// } finally {
// System.out.println();
// checkStart = false;
Relationship[] have = null;
//search for local 'HAVE'
if (checkStart) {
have = getByHave(pf, null, ref.getStartNode(), thes);
if (have != null) return have;
}
//search for inside 'HAVE'
return searchForHAVE(pf, ref, ref.getEndNode(), thes);
}
private Relationship[] searchForHAVE(final PFlow pflow, Relationship op, final Node ref, final Set<Node> thes) {
Relationship[] have = null;
//search for inside 'HAVE'
have = getByHave(pflow, op, ref, thes);
if (have != null) return have;
//search 'IC' by 'IS' topology
for (Relationship tdR : Utils.td_eval_IS.traverse(ref).relationships()) {
//System.out.println("GET IC -> IS "+tdR);
Relationship r = getByIC(tdR.getEndNode(), thes);
if (r != null) {
final Node sNode = ref;
final Node eNode = r.getEndNode();
final long id = r.getId();
return new Relationship[] {
AnimoGraph.execute(new GraphOperation<Relationship>() {
@Override
public Relationship execute() {
Relationship res = sNode.createRelationshipTo(eNode, AN._);
RID.set(res, id);
return res;
}
})
};
}
//search for have
have = getByHave(pflow, tdR, tdR.getEndNode(), thes);
if (have != null) return have;
}
return null;
}
//XXX: in-use by SELF
public Relationship[] getBySELF(final PFlow pf, Node context, final Set<Node> thes) {
//System.out.println("GET get context = "+context);
//search for local 'HAVE'
Relationship[] have = getByHave(pf, null, context, thes);
if (have != null) return have;
Node instance = Utils.getSingleREF(context);
if (instance != null) {
//change context to the-instance by REF
context = instance;
//search for have
have = getByHave(pf, null, context, thes);
if (have != null) return have;
}
Relationship prevTHE = null;
//search 'IC' by 'IS' topology
for (Relationship tdR : td_eval_ic.traverse(context).relationships()) {
Statement st = Statements.relationshipType(tdR);
if (st instanceof AN) {
//System.out.println("GET IC -> IS "+tdR);
if (prevTHE != null) {
//search for have
have = getByHave(pf, prevTHE, prevTHE.getEndNode(), thes);
if (have != null) return have;
}
prevTHE = tdR;
} else if (st instanceof IC) {
//System.out.print("GET IC -> "+tdR);
if (thes.contains(Utils.getSingleREF(tdR.getEndNode()))) {
//System.out.println(" MATCH");
//store
final Node sNode = context;
final Relationship r = tdR;
return new Relationship[] {
AnimoGraph.execute(new GraphOperation<Relationship>() {
@Override
public Relationship execute() {
Relationship res = sNode.createRelationshipTo(r.getEndNode(), AN._);
//RID.set(res, r.getId());
return res;
}
})
};
//in-memory
//Relationship res = new InMemoryRelationship(context, tdR.getEndNode(), AN._.relationshipType());
//RID.set(res, tdR.getId());
//return res;
//as it
//return tdR;
}
//System.out.println();
}
}
if (prevTHE != null) {
//search for have
have = getByHave(pf, prevTHE, prevTHE.getEndNode(), thes);
if (have != null) return have;
}
return null;
}
private Relationship[] getByHave(final PFlow pflow, Relationship op, final Node context, final Set<Node> thes) {
if (context == null) return null;
TraversalDescription trav = td.
relationships(AN._, OUTGOING).
relationships(REF._, OUTGOING).
evaluator(new Searcher(){
@Override
public Evaluation evaluate(Path path) {
//System.out.println(path);
return _evaluate_(path, thes, AN._);
}
});
Map<Relationship, Path> paths = new FastMap<Relationship, Path>();
for (Path path : trav.traverse(context)) {
//TODO: check that this is only one answer
System.out.println(path);
if (path.length() == 1) {
if (op == null) {
System.out.println("WARNING: DONT KNOW OP");
continue;
}
paths.put(op, path);
//break;
}
Relationship fR = path.relationships().iterator().next();
Path p = paths.get(fR);
if (p == null || p.length() > path.length()) {
paths.put(fR, path);
}
}
int i = 0;
Relationship[] res = new Relationship[paths.size()];
for (Path path : paths.values()) {
for (Relationship r : path.relationships()) {
if (!pflow.isInStack(r)) {
if (r.isType(AN._)) {
res[i] = r;
}
}
}
i++;
}
// while (true) {
// try {
// res = getDb().getRelationshipById(
// (Long)res.getProperty(RID.name())
// } catch (Exception e) {
// break;
return res;
}
private Relationship getByIC(final Node context, final Set<Node> thes) {
TraversalDescription trav = td.
evaluator(new Searcher(){
@Override
public Evaluation evaluate(Path path) {
return _evaluate_(path, thes, IC._);
}
});
Relationship res = null;
for (Path path : trav.traverse(context)) {
//TODO: check that this is only one answer
//System.out.println(path);
for (Relationship r : path.relationships()) {
res = r;
break;
}
}
return res;
}
} |
package org.basex.api.xmldb;
import static org.basex.util.Token.*;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.xml.parsers.SAXParserFactory;
import org.basex.api.dom.BXDoc;
import org.basex.data.Data;
import org.basex.data.Result;
import org.basex.data.XMLSerializer;
import org.basex.io.ArrayOutput;
import org.basex.io.IOFile;
import org.basex.query.item.DBNode;
import org.basex.util.TokenBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.ErrorCodes;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;
final class BXXMLResource implements XMLResource, BXXMLDBText {
/** Collection reference. */
private final Collection coll;
/** String id. */
private String id;
/** Query result. */
private Result result;
/** Cached content. */
Object content;
/** Data reference. */
Data data;
/** Pre value or result position. */
int pre;
/**
* Constructor for generated results.
* @param d content data
* @param c Collection
*/
BXXMLResource(final byte[] d, final Collection c) {
content = d;
coll = c;
}
/**
* Constructor for query results.
* @param res query result
* @param p query counter
* @param c Collection
*/
BXXMLResource(final Result res, final int p, final Collection c) {
result = res;
coll = c;
pre = p;
}
/**
* Standard constructor.
* @param d data reference
* @param p pre value
* @param i id
* @param c collection
*/
BXXMLResource(final Data d, final int p, final String i, final Collection c) {
id = i;
coll = c;
data = d;
pre = p;
}
@Override
public Collection getParentCollection() {
return coll;
}
@Override
public String getId() {
return id;
}
@Override
public String getResourceType() {
return XMLResource.RESOURCE_TYPE;
}
@Override
public Object getContent() throws XMLDBException {
if(content == null) {
try {
// serialize and cache content
final ArrayOutput ao = new ArrayOutput();
final XMLSerializer xml = new XMLSerializer(ao);
if(data != null) {
new DBNode(data, pre).serialize(xml);
} else if(result != null) {
result.serialize(xml, pre);
} else {
return null;
}
content = ao.toArray();
} catch(final IOException ex) {
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ex.getMessage());
}
}
return content instanceof byte[] ? string((byte[]) content) : content;
}
@Override
public void setContent(final Object value) throws XMLDBException {
// allow only strings, byte arrays and {@link File} instances
if(value instanceof byte[]) {
content = value;
} else if(value instanceof String) {
content = token(value.toString());
} else if(value instanceof File) {
try {
content = new IOFile((File) value).content();
} catch(final IOException ex) {
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ERR_CONT +
"\n" + ex.getMessage());
}
} else {
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ERR_CONT);
}
}
@Override
public String getDocumentId() throws XMLDBException {
// throw exception if resource result from query; does not conform to the
// specs, but many query results are not related to a document anymore
if(result != null)
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ERR_DOC);
// resource does not result from a query - return normal id
if(id != null) return id;
// get document root id
int p = pre;
while(p >= 0) {
final int k = data.kind(p);
if(k == Data.DOC) return string(data.text(p, true));
p = data.parent(p, k);
}
return null;
}
@Override
public Node getContentAsDOM() {
if(!(content instanceof Node)) content = new BXDoc(new DBNode(data, pre));
return (Node) content;
}
@Override
public void setContentAsDOM(final Node cont) throws XMLDBException {
// allow only document instances...
if(cont == null) throw new XMLDBException(ErrorCodes.INVALID_RESOURCE);
if(cont instanceof Document) content = cont;
else throw new XMLDBException(ErrorCodes.WRONG_CONTENT_TYPE);
}
@Override
public void getContentAsSAX(final ContentHandler handler)
throws XMLDBException {
if(handler == null) throw new XMLDBException(ErrorCodes.INVALID_RESOURCE);
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
try {
// caching should be avoided and replaced by a stream reader...
final XMLReader reader = factory.newSAXParser().getXMLReader();
reader.setContentHandler(handler);
reader.parse(new InputSource(new StringReader(getContent().toString())));
} catch(final Exception pce) {
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, pce.getMessage());
}
}
@Override
public ContentHandler setContentAsSAX() throws XMLDBException {
try {
// ..might be replaced by a custom SAX content handler in future
return new BXSAXContentHandler(this);
} catch(final IOException ex) {
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ex.getMessage());
}
}
/** SAX parser. */
private static final class BXSAXContentHandler extends DefaultHandler {
/** HashMap. */
private final HashMap<String, String> ns = new HashMap<String, String>();
/** Cached output. */
private final ArrayOutput out = new ArrayOutput();
/** Serializer. */
private final XMLSerializer xml;
/** XMLResource. */
private final BXXMLResource res;
/**
* Default constructor.
* @param r resource
* @throws IOException I/O exception
*/
BXSAXContentHandler(final BXXMLResource r) throws IOException {
xml = new XMLSerializer(out);
res = r;
}
@Override
public void characters(final char[] ac, final int i, final int j)
throws SAXException {
try {
final TokenBuilder tb = new TokenBuilder();
for(int k = 0; k < j; ++k) tb.add(ac[i + k]);
xml.text(tb.finish());
} catch(final IOException ex) {
throw new SAXException(ex);
}
}
@Override
public void endDocument() {
res.content = out.toArray();
}
@Override
public void endElement(final String s, final String s1, final String s2)
throws SAXException {
try {
xml.closeElement();
} catch(final IOException ex) {
throw new SAXException(ex);
}
}
@Override
public void ignorableWhitespace(final char[] ac, final int i, final int j)
throws SAXException {
characters(ac, i, j);
}
@Override
public void processingInstruction(final String s, final String s1)
throws SAXException {
try {
xml.pi(token(s), s1 != null ? token(s1) : EMPTY);
} catch(final IOException ex) {
throw new SAXException(ex);
}
}
@Override
public void startElement(final String s, final String s1, final String s2,
final Attributes atts) throws SAXException {
try {
xml.openElement(token(s2));
for(int i = 0; i < atts.getLength(); ++i)
xml.attribute(token(atts.getQName(i)), token(atts.getValue(i)));
for(final Entry<String, String> e : ns.entrySet())
xml.attribute(concat(XMLNSC, token(e.getKey())), token(e.getValue()));
} catch(final IOException ex) {
throw new SAXException(ex);
}
}
@Override
public void startPrefixMapping(final String s, final String s1) {
ns.put(s, s1);
}
@Override
public void endPrefixMapping(final String s) {
ns.remove(s);
}
}
} |
package org.dita.dost.module;
import static java.util.stream.Collectors.toMap;
import static org.dita.dost.util.Configuration.configuration;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.util.Job.*;
import static org.dita.dost.util.URLUtils.*;
import static org.dita.dost.util.XMLUtils.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;
import org.dita.dost.module.GenMapAndTopicListModule.TempFileNameScheme;
import org.dita.dost.util.*;
import org.dita.dost.writer.TopicFragmentFilter;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.XMLFilter;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.pipeline.AbstractPipelineInput;
import org.dita.dost.pipeline.AbstractPipelineOutput;
import org.dita.dost.reader.KeyrefReader;
import org.dita.dost.util.Job.FileInfo.Filter;
import org.dita.dost.writer.ConkeyrefFilter;
import org.dita.dost.writer.KeyrefPaser;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
/**
* Keyref Module.
*
*/
final class KeyrefModule extends AbstractPipelineModuleImpl {
private TempFileNameScheme tempFileNameScheme;
/** Delayed conref utils. */
private DelayConrefUtils delayConrefUtils;
private String transtype;
final Set<URI> normalProcessingRole = new HashSet<>();
final Map<URI, Integer> usage = new HashMap<>();
private TopicFragmentFilter topicFragmentFilter;
@Override
public void setJob(final Job job) {
super.setJob(job);
try {
tempFileNameScheme = (TempFileNameScheme) getClass().forName(job.getProperty("temp-file-name-scheme")).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
tempFileNameScheme.setBaseDir(job.getInputDir());
}
/**
* Entry point of KeyrefModule.
*
* @param input Input parameters and resources.
* @return null
* @throws DITAOTException exception
*/
@Override
public AbstractPipelineOutput execute(final AbstractPipelineInput input)
throws DITAOTException {
if (fileInfoFilter == null) {
fileInfoFilter = new Filter<FileInfo>() {
@Override
public boolean accept(FileInfo f) {
return f.format == null || f.format.equals(ATTR_FORMAT_VALUE_DITA) || f.format.equals(ATTR_FORMAT_VALUE_DITAMAP);
}
};
}
final Collection<FileInfo> fis = job.getFileInfo(fileInfoFilter).stream()
.filter(f -> f.hasKeyref)
.collect(Collectors.toSet());
if (!fis.isEmpty()) {
try {
final String cls = Optional
.ofNullable(job.getProperty("temp-file-name-scheme"))
.orElse(configuration.get("temp-file-name-scheme"));
tempFileNameScheme = (GenMapAndTopicListModule.TempFileNameScheme) getClass().forName(cls).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
tempFileNameScheme.setBaseDir(job.getInputDir());
initFilters();
final Document doc = readMap();
final KeyrefReader reader = new KeyrefReader();
reader.setLogger(logger);
final URI mapFile = job.getInputMap();
logger.info("Reading " + job.tempDirURI.resolve(mapFile).toString());
reader.read(job.tempDirURI.resolve(mapFile), doc);
final KeyScope rootScope = reader.getKeyDefinition();
final List<ResolveTask> jobs = collectProcessingTopics(fis, rootScope, doc);
writeMap(doc);
transtype = input.getAttribute(ANT_INVOKER_EXT_PARAM_TRANSTYPE);
delayConrefUtils = transtype.equals(INDEX_TYPE_ECLIPSEHELP) ? new DelayConrefUtils() : null;
for (final ResolveTask r: jobs) {
if (r.out != null) {
processFile(r);
}
}
for (final ResolveTask r: jobs) {
if (r.out == null) {
processFile(r);
}
}
// Store job configuration updates
for (final URI file: normalProcessingRole) {
final FileInfo f = job.getFileInfo(file);
if (f != null) {
f.isResourceOnly = false;
job.add(f);
}
}
try {
job.write();
} catch (final IOException e) {
throw new DITAOTException("Failed to store job state: " + e.getMessage(), e);
}
}
return null;
}
private void initFilters() {
topicFragmentFilter = new TopicFragmentFilter(ATTRIBUTE_NAME_CONREF, ATTRIBUTE_NAME_CONREFEND);
}
/** Collect topics for key reference processing and modify map to reflect new file names. */
// FIXME multple topirefs in a single scope result in redundant copies, allow duplicates inside scope
private List<ResolveTask> collectProcessingTopics(final Collection<FileInfo> fis, final KeyScope rootScope, final Document doc) {
final List<ResolveTask> res = new ArrayList<>();
res.add(new ResolveTask(rootScope, job.getFileInfo(job.getInputMap()), null));
// Collect topics from map and rewrite topicrefs for duplicates
walkMap(doc.getDocumentElement(), rootScope, res);
// Collect topics not in map and map itself
for (final FileInfo f: fis) {
if (!usage.containsKey(f.uri)) {
res.add(processTopic(f, rootScope, f.isResourceOnly));
}
}
if (fileInfoFilter != null) {
return adjustResourceRenames(res.stream()
.filter(rs -> fileInfoFilter.accept(rs.in))
.collect(Collectors.toList()));
} else {
return adjustResourceRenames(res);
}
}
List<ResolveTask> adjustResourceRenames(final List<ResolveTask> renames) {
final Map<KeyScope, List<ResolveTask>> scopes = renames.stream().collect(Collectors.groupingBy(rt -> rt.scope));
final List<ResolveTask> res = new ArrayList<>();
for (final Map.Entry<KeyScope, List<ResolveTask>> group : scopes.entrySet()) {
final KeyScope scope = group.getKey();
final List<ResolveTask> tasks = group.getValue();
final Map<URI, URI> rewrites = tasks.stream()
.filter(t -> t.out != null)
.collect(toMap(
t -> t.in.uri,
t -> t.out.uri
));
final KeyScope resScope = rewriteScopeTargets(scope, rewrites);
tasks.stream().map(t -> new ResolveTask(resScope, t.in, t.out)).forEach(res::add);
}
return res;
}
KeyScope rewriteScopeTargets(KeyScope scope, Map<URI, URI> rewrites) {
final Map<String, KeyDef> newKeys = new HashMap<>();
for (Map.Entry<String, KeyDef> key : scope.keyDefinition.entrySet()) {
final KeyDef oldKey = key.getValue();
URI href = oldKey.href;
if (href != null && rewrites.containsKey(stripFragment(href))) {
href = setFragment(rewrites.get(stripFragment(href)), href.getFragment());
}
final KeyDef newKey = new KeyDef(oldKey.keys, href, oldKey.scope, oldKey.format, oldKey.source, oldKey.element);
newKeys.put(key.getKey(), newKey);
}
return new KeyScope(scope.name,
newKeys,
scope.childScopes.stream()
.map(c -> rewriteScopeTargets(c, rewrites))
.collect(Collectors.toList()));
}
/** Tuple class for key reference processing info. */
static class ResolveTask {
final KeyScope scope;
final FileInfo in;
final FileInfo out;
ResolveTask(final KeyScope scope, final FileInfo in, final FileInfo out) {
assert scope != null;
this.scope = scope;
assert in != null;
this.in = in;
this.out = out;
}
}
/** Recursively walk map and process topics that have keyrefs. */
private void walkMap(final Element elem, final KeyScope scope, final List<ResolveTask> res) {
List<KeyScope> ss = Collections.singletonList(scope);
if (elem.getAttributeNode(ATTRIBUTE_NAME_KEYSCOPE) != null) {
ss = new ArrayList<>();
for (final String keyscope: elem.getAttribute(ATTRIBUTE_NAME_KEYSCOPE).trim().split("\\s+")) {
final KeyScope s = scope.getChildScope(keyscope);
assert s != null;
ss.add(s);
}
}
Attr hrefNode = elem.getAttributeNode(ATTRIBUTE_NAME_COPY_TO);
if (hrefNode == null) {
hrefNode = elem.getAttributeNode(ATTRIBUTE_NAME_HREF);
}
final boolean isResourceOnly = isResourceOnly(elem);
for (final KeyScope s: ss) {
if (hrefNode != null) {
final URI href = stripFragment(job.getInputMap().resolve(hrefNode.getValue()));
final FileInfo fi = job.getFileInfo(href);
if (fi != null && fi.hasKeyref) {
final ResolveTask resolveTask = processTopic(fi, s, isResourceOnly);
res.add(resolveTask);
final Integer used = usage.get(fi.uri);
if (used > 1) {
final URI value = tempFileNameScheme.generateTempFileName(resolveTask.out.result);
hrefNode.setValue(value.toString());
}
}
}
for (final Element child : getChildElements(elem, MAP_TOPICREF)) {
walkMap(child, s, res);
}
}
}
private boolean isResourceOnly(final Element elem) {
Node curr = elem;
while (curr != null) {
if (curr.getNodeType() == Node.ELEMENT_NODE) {
final Attr processingRole = ((Element) curr).getAttributeNode(ATTRIBUTE_NAME_PROCESSING_ROLE);
if (processingRole != null) {
return processingRole.getValue().equals(ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY);
}
}
curr = curr.getParentNode();
}
return false;
}
/**
* Determine how topic is processed for key reference processing.
*
* @return key reference processing
*/
private ResolveTask processTopic(final FileInfo f, final KeyScope scope, final boolean isResourceOnly) {
final int increment = isResourceOnly ? 0 : 1;
final Integer used = usage.containsKey(f.uri) ? usage.get(f.uri) + increment : increment;
usage.put(f.uri, used);
if (used > 1) {
final URI result = addSuffix(f.result, "-" + (used - 1));
final URI out = tempFileNameScheme.generateTempFileName(result);
final FileInfo fo = new FileInfo.Builder(f)
.uri(out)
.result(result)
.build();
// TODO: Should this be added when content is actually generated?
job.add(fo);
return new ResolveTask(scope, f, fo);
} else {
return new ResolveTask(scope, f, null);
}
}
/**
* Process key references in a topic. Topic is stored with a new name if it's
* been processed before.
*/
private void processFile(final ResolveTask r) {
final List<XMLFilter> filters = new ArrayList<>();
final ConkeyrefFilter conkeyrefFilter = new ConkeyrefFilter();
conkeyrefFilter.setLogger(logger);
conkeyrefFilter.setJob(job);
conkeyrefFilter.setKeyDefinitions(r.scope);
conkeyrefFilter.setCurrentFile(job.tempDirURI.resolve(r.in.uri));
conkeyrefFilter.setDelayConrefUtils(delayConrefUtils);
filters.add(conkeyrefFilter);
filters.add(topicFragmentFilter);
final KeyrefPaser parser = new KeyrefPaser();
parser.setLogger(logger);
parser.setJob(job);
parser.setKeyDefinition(r.scope);
parser.setCurrentFile(job.tempDirURI.resolve(r.in.uri));
filters.add(parser);
try {
logger.debug("Using " + (r.scope.name != null ? r.scope.name + " scope" : "root scope"));
if (r.out != null) {
logger.info("Processing " + job.tempDirURI.resolve(r.in.uri) +
" to " + job.tempDirURI.resolve(r.out.uri));
XMLUtils.transform(new File(job.tempDir, r.in.file.getPath()),
new File(job.tempDir, r.out.file.getPath()),
filters);
} else {
logger.info("Processing " + job.tempDirURI.resolve(r.in.uri));
XMLUtils.transform(new File(job.tempDir, r.in.file.getPath()), filters);
}
// validate resource-only list
normalProcessingRole.addAll(parser.getNormalProcessingRoleTargets());
} catch (final DITAOTException e) {
logger.error("Failed to process key references: " + e.getMessage(), e);
}
}
/**
* Add key definition to job configuration
*
* @param keydefs key defintions to add
*/
private void writeKeyDefinition(final Map<String, KeyDef> keydefs) {
try {
KeyDef.writeKeydef(new File(job.tempDir, KEYDEF_LIST_FILE), keydefs.values());
} catch (final DITAOTException e) {
logger.error("Failed to write key definition file: " + e.getMessage(), e);
}
}
private Document readMap() throws DITAOTException {
InputSource in = null;
try {
in = new InputSource(job.tempDirURI.resolve(job.getInputMap()).toString());
return XMLUtils.getDocumentBuilder().parse(in);
} catch (final Exception e) {
throw new DITAOTException("Failed to parse map: " + e.getMessage(), e);
} finally {
try {
close(in);
} catch (IOException e) {
logger.error("Failed to close input: " + e.getMessage(), e);
}
}
}
private void writeMap(final Document doc) throws DITAOTException {
Result out = null;
try {
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
out = new StreamResult(new File(job.tempDirURI.resolve(job.getInputMap())));
transformer.transform(new DOMSource(doc), out);
} catch (final TransformerConfigurationException e) {
throw new RuntimeException(e);
} catch (final TransformerException e) {
throw new DITAOTException("Failed to write map: " + e.getMessageAndLocation(), e);
} finally {
try {
close(out);
} catch (IOException e) {
logger.error("Failed to close result: " + e.getMessage(), e);
}
}
}
} |
package org.eclipsecon;
import hudson.model.BuildBadgeAction;
import hudson.model.AbstractBuild;
/**
* @author : Anthony Dahanne
*/
public class EnglishBadgeAction implements BuildBadgeAction{
private final static String ICON_PATH = "/plugin/hello-eclipsecon/images/english_64x64.png";;
private final AbstractBuild build;
public EnglishBadgeAction(AbstractBuild build) {
this.build = build;
}
public String getIconPath() { return ICON_PATH; }
public String getText() {
return "This build said Hi in english : " + build.getProject().getName() + " #" + build.getNumber();
}
public String getDisplayName() {
return "Built in english";
}
public String getIconFileName() {
return ICON_PATH;
}
public String getUrlName() {
return "";
}
} |
package org.fiteagle.api.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Topic;
import javax.ws.rs.core.Response;
import org.apache.jena.riot.RiotException;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.vocabulary.RDF;
public class MessageUtil {
private static Logger LOGGER = Logger.getLogger(MessageUtil.class.toString());
public static Model createMsgCreate(Model messageModel) {
return createDefaultMessageModel(messageModel, MessageBusOntologyModel.propertyFiteagleCreate);
}
public static Model createMsgDiscover(Model messageModel) {
return createDefaultMessageModel(messageModel, MessageBusOntologyModel.propertyFiteagleDiscover);
}
public static Model createMsgRequest(Model messageModel) {
return createDefaultMessageModel(messageModel, MessageBusOntologyModel.propertyFiteagleRequest);
}
public static Model createMsgRelease(Model messageModel) {
return createDefaultMessageModel(messageModel, MessageBusOntologyModel.propertyFiteagleRelease);
}
public static Model createMsgInform(Model messageModel) {
return createDefaultMessageModel(messageModel, MessageBusOntologyModel.propertyFiteagleInform);
}
public static Model createMsgConfigure(Model messageModel) {
return createDefaultMessageModel(messageModel, MessageBusOntologyModel.propertyFiteagleConfigure);
}
public static Message createRDFMessage(Model rdfModel, String methodType, String serialization, String correlationID, JMSContext context) {
final Message message = context.createMessage();
try {
message.setStringProperty(IMessageBus.METHOD_TYPE, methodType);
message.setStringProperty(IMessageBus.SERIALIZATION, serialization);
message.setStringProperty(IMessageBus.RDF, serializeModel(rdfModel, serialization));
if(correlationID != null){
message.setJMSCorrelationID(correlationID);
}
else{
message.setJMSCorrelationID(UUID.randomUUID().toString());
}
} catch (JMSException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
return message;
}
public static Message createRDFMessage(String rdfModel, String methodType, String serialization, String correlationID, JMSContext context) {
final Message message = context.createMessage();
try {
message.setStringProperty(IMessageBus.METHOD_TYPE, methodType);
message.setStringProperty(IMessageBus.SERIALIZATION, serialization);
message.setStringProperty(IMessageBus.RDF, rdfModel);
if(correlationID != null){
message.setJMSCorrelationID(correlationID);
}
else{
message.setJMSCorrelationID(UUID.randomUUID().toString());
}
} catch (JMSException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
return message;
}
public static Message createErrorMessage(String errorMessage, String correlationID, JMSContext context) {
final Message message = context.createMessage();
try {
message.setStringProperty(IMessageBus.METHOD_TYPE, IMessageBus.TYPE_INFORM);
message.setStringProperty(IMessageBus.TYPE_ERROR, errorMessage);
if(correlationID != null){
message.setJMSCorrelationID(correlationID);
}
else{
message.setJMSCorrelationID(UUID.randomUUID().toString());
}
} catch (JMSException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
return message;
}
private static Model createDefaultMessageModel(Model messageModel, Resource messageTypeProperty) {
Model rdfModel = ModelFactory.createDefaultModel();
if (messageModel != null) {
rdfModel.add(messageModel);
rdfModel.setNsPrefixes(messageModel.getNsPrefixMap());
}
rdfModel.add(MessageBusOntologyModel.internalMessage, RDF.type, messageTypeProperty);
return rdfModel;
}
public static String serializeModel(Model rdfModel) {
StringWriter writer = new StringWriter();
rdfModel.write(writer, IMessageBus.SERIALIZATION_DEFAULT);
return writer.toString();
}
public static String serializeModel(Model rdfModel, String serialization) {
StringWriter writer = new StringWriter();
rdfModel.write(writer, serialization);
String serializedModel = writer.toString();
if (serialization.equals(IMessageBus.SERIALIZATION_RDFXML)) {
String[] splitted = serializedModel.split("\n");
for (int i = 0; i < splitted.length; i++) {
if (splitted[i].replace(" ", "").replace("\t", "").startsWith("xmlns:j.")) {
serializedModel = serializedModel.replace(splitted[i] + "\n", "");
}
}
}
return serializedModel;
}
public static Model parseSerializedModel(String modelString) throws RiotException {
return parseSerializedModel(modelString, IMessageBus.SERIALIZATION_DEFAULT);
}
public static Model parseSerializedModel(String modelString, String serialization) throws RiotException {
Model rdfModel = ModelFactory.createDefaultModel();
InputStream is = new ByteArrayInputStream(modelString.getBytes(Charset.defaultCharset()));
try {
rdfModel.read(is, null, serialization);
} catch (RiotException e) {
LOGGER.log(Level.SEVERE, "Error parsing serialized model: " + modelString);
}
return rdfModel;
}
public static boolean isMessageType(Model messageModel, Resource messageTypeProperty) {
return messageModel.contains(null, RDF.type, messageTypeProperty);
}
public static String getRDFResult(final Message receivedMessage) {
String result = null;
if (receivedMessage != null) {
try {
result = receivedMessage.getStringProperty(IMessageBus.RDF);
} catch (JMSException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
}
return result;
}
public static String getError(final Message receivedMessage) {
String error = null;
if (receivedMessage == null) {
error = Response.Status.REQUEST_TIMEOUT.name();
} else {
try {
error = receivedMessage.getStringProperty(IMessageBus.TYPE_ERROR);
} catch (JMSException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
}
return error;
}
public static Message waitForResult(Message requestMessage, JMSContext context, Topic topic) {
String filter = "";
try {
filter = "JMSCorrelationID='" + requestMessage.getJMSCorrelationID() + "'";
} catch (JMSException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
final Message rcvMessage = context.createConsumer(topic, filter).receive(IMessageBus.SHORT_TIMEOUT);
return rcvMessage;
}
public static String createSerializedSPARQLQueryModel(String query, String serialization) {
Model requestModel = ModelFactory.createDefaultModel();
Resource resource = requestModel.createResource(MessageBusOntologyModel.internalMessage.getURI());
resource.addProperty(RDF.type, MessageBusOntologyModel.propertyFiteagleRequest);
resource.addProperty(MessageBusOntologyModel.requestType, IMessageBus.REQUEST_TYPE_SPARQL_QUERY);
resource.addProperty(MessageBusOntologyModel.propertySparqlQuery, query);
requestModel = MessageUtil.createMsgRequest(requestModel);
return MessageUtil.serializeModel(requestModel, serialization);
}
public static String createSerializedSPARQLQueryRestoresModel(String query, Resource adapter) {
Model requestModel = ModelFactory.createDefaultModel();
Resource resource = requestModel.createResource(MessageBusOntologyModel.internalMessage.getURI());
resource.addProperty(RDF.type, MessageBusOntologyModel.propertyFiteagleRequest);
resource.addProperty(MessageBusOntologyModel.requestType, IMessageBus.REQUEST_TYPE_SPARQL_QUERY);
resource.addProperty(MessageBusOntologyModel.propertySparqlQuery, query);
resource.addProperty(MessageBusOntologyModel.methodRestores, adapter);
requestModel = MessageUtil.createMsgRequest(requestModel);
return MessageUtil.serializeModel(requestModel);
}
public static String parseResultSetToJson(ResultSet resultSet) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ResultSetFormatter.outputAsJSON(baos, resultSet);
String jsonString = "";
try {
jsonString = baos.toString(Charset.defaultCharset().toString());
baos.close();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
return jsonString;
}
public static String getSPARQLQueryFromModel(Model model) throws ParsingException {
String query = null;
Resource message = model.getResource(MessageBusOntologyModel.internalMessage.getURI());
Statement st = message.getProperty(MessageBusOntologyModel.propertySparqlQuery);
if(st != null){
query = st.getObject().toString();
}
if (query == null || query.isEmpty()) {
throw new ParsingException("SPARQL Query expected, but no sparql query found!");
}
return query;
}
public static void setCommonPrefixes(Model model) {
model.removeNsPrefix("j.0");
model.removeNsPrefix("j.1");
model.removeNsPrefix("j.2");
model.removeNsPrefix("j.3");
model.removeNsPrefix("j.4");
model.removeNsPrefix("j.5");
model.setNsPrefix("wgs", "http://www.w3.org/2003/01/geo/wgs84_pos
model.setNsPrefix("foaf", "http://xmlns.com/foaf/0.1/");
model.setNsPrefix("omn", "http://open-multinet.info/ontology/omn
model.setNsPrefix("owl", "http://www.w3.org/2002/07/owl
model.setNsPrefix("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns
model.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema
model.setNsPrefix("rdfs", "http://www.w3.org/2000/01/rdf-schema
}
public static class ParsingException extends Exception {
private static final long serialVersionUID = 8213556984621316215L;
public ParsingException(String message){
super(message);
}
}
} |
package org.javastack.bouncer;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import javax.net.ssl.SSLSocket;
/**
* Forward Plain Connections
*/
class PlainServer {
final ServerContext context;
final InboundAddress inboundAddress;
final OutboundAddress outboundAddress;
PlainServer(final ServerContext context, final InboundAddress inboundAddress,
final OutboundAddress outboundAddress) {
this.context = context;
this.inboundAddress = inboundAddress;
this.outboundAddress = outboundAddress;
}
void listenLocal() { // Entry Point
final PlainListen acceptator = new PlainListen();
context.addReloadableAwaiter(acceptator);
context.submitTask(acceptator, "ForwardListen[" + inboundAddress + "]", ClientId.newId());
}
class PlainListen implements Awaiter, Runnable {
ServerSocket listen;
volatile boolean shutdown = false;
@Override
public void setShutdown() {
shutdown = true;
context.closeSilent(listen);
}
@Override
public void run() {
try {
listen = inboundAddress.listen();
Log.info(this.getClass().getSimpleName() + " started: " + inboundAddress);
while (!shutdown) {
try {
final Socket client = listen.accept();
try {
context.registerSocket(client);
final Integer pReadTimeout = inboundAddress.getOpts().getInteger(
Options.P_READ_TIMEOUT);
if (pReadTimeout != null) {
client.setSoTimeout(pReadTimeout);
}
if (client instanceof SSLSocket) {
((SSLSocket) client).startHandshake();
}
Log.info(this.getClass().getSimpleName() + " New client from=" + client + " "
+ SSLFactory.getSocketProtocol(client));
context.submitTask(
new PlainConnector(client, inboundAddress.getOpts()),
"ForwardConnect[" + inboundAddress + "|"
+ IOHelper.socketRemoteToString(client) + "]",
(((long) client.getPort() << 48) | ClientId.newId()));
} catch (Exception e) {
Log.error(this.getClass().getSimpleName() + " Exception: " + e.toString(), e);
context.closeSilent(client);
}
} catch (SocketTimeoutException e) {
continue;
} catch (Exception e) {
if (!listen.isClosed()) {
Log.error(this.getClass().getSimpleName() + " " + e.toString(), e);
}
}
}
} catch (IOException e) {
Log.error(this.getClass().getSimpleName() + " " + e.toString());
} catch (Exception e) {
Log.error(this.getClass().getSimpleName() + " Generic exception", e);
} finally {
Log.info(this.getClass().getSimpleName() + " await end");
context.awaitShutdown(this);
Log.info(this.getClass().getSimpleName() + " end");
}
}
}
class PlainConnector implements Shutdownable, Runnable {
final Socket client;
final Options options;
Socket remote = null;
volatile boolean shutdown = false;
PlainConnector(final Socket client, final Options options) {
this.client = client;
this.options = options;
}
@Override
public void setShutdown() {
shutdown = true;
close();
}
void close() {
// FIXME: java.lang.NullPointerException: SocketRegistrator.unregisterSocket(Socket==null)
if (client != null)
context.closeSilent(client);
if (remote != null)
context.closeSilent(remote);
}
@Override
public void run() {
Log.info(this.getClass().getSimpleName() + " started: " + outboundAddress);
try {
try {
context.getStatistics().incTryingConnections();
remote = outboundAddress.connectFrom(client.getInetAddress());
} finally {
context.getStatistics().decTryingConnections();
}
if (remote == null)
throw new ConnectException("Unable to connect to " + outboundAddress);
Log.info(this.getClass().getSimpleName() + " Bouncer from " + client + " to " + remote);
final PlainSocketTransfer st1 = new PlainSocketTransfer(client, remote);
final PlainSocketTransfer st2 = new PlainSocketTransfer(remote, client);
if (options.isOption(Options.PROXY_SEND)) {
st1.setHeadersBuffer(ProxyProtocol.getInstance().formatV1(client).getBytes());
}
st1.setBrother(st2);
st2.setBrother(st1);
context.submitTask(
st1,
"ForwardTransfer-CliRem[" + inboundAddress + "|"
+ IOHelper.socketRemoteToString(client) + "|"
+ IOHelper.socketRemoteToString(remote) + "]", ClientId.getId());
context.submitTask(
st2,
"ForwardTransfer-RemCli[" + inboundAddress + "|"
+ IOHelper.socketRemoteToString(remote) + "|"
+ IOHelper.socketRemoteToString(client) + "]", ClientId.getId());
} catch (IOException e) {
Log.error(this.getClass().getSimpleName() + " " + e.toString());
close();
} catch (Exception e) {
Log.error(this.getClass().getSimpleName() + " Generic exception", e);
close();
} finally {
Log.info(this.getClass().getSimpleName() + " ended: " + outboundAddress);
}
}
}
/**
* Transfer data between sockets
*/
class PlainSocketTransfer implements Shutdownable, Runnable {
final byte[] buf = new byte[Constants.BUFFER_LEN];
final Socket sockin;
final Socket sockout;
final InputStream is;
final OutputStream os;
volatile boolean shutdown = false;
byte[] headers = null;
long keepalive = System.currentTimeMillis();
PlainSocketTransfer brother = null;
PlainSocketTransfer(final Socket sockin, final Socket sockout) throws IOException {
this.sockin = sockin;
this.sockout = sockout;
this.is = sockin.getInputStream();
this.os = sockout.getOutputStream();
}
void setBrother(final PlainSocketTransfer brother) {
this.brother = brother;
}
void setHeadersBuffer(final byte[] headers) {
this.headers = headers;
}
@Override
public void setShutdown() {
shutdown = true;
}
@Override
public void run() {
try {
if (headers != null) {
context.getStatistics().incOutMsgs().incOutBytes(headers.length);
os.write(headers, 0, headers.length);
os.flush();
headers = null;
}
final int TIMEOUT = sockin.getSoTimeout();
sockin.setSoTimeout(250);
while (!shutdown) {
try {
if (!shutdown && transfer()) {
keepalive = System.currentTimeMillis();
continue;
}
} catch (SocketTimeoutException e) {
// Idle Timeout
if (TIMEOUT > 0) {
final long now = System.currentTimeMillis();
if (((now - keepalive) > TIMEOUT) || ((now - brother.keepalive) > TIMEOUT)) {
Log.info(this.getClass().getSimpleName() + " " + e.toString());
setShutdown();
}
}
}
}
} catch (IOException e) {
if (!sockin.isClosed() && !shutdown) {
Log.error(this.getClass().getSimpleName() + " " + e.toString() + " " + sockin);
}
} catch (Exception e) {
Log.error(this.getClass().getSimpleName() + " Generic exception", e);
} finally {
context.closeSilent(sockin);
if (brother != null) {
brother.setShutdown();
}
Log.info(this.getClass().getSimpleName() + " Connection closed " + sockin);
}
}
boolean transfer() throws IOException {
final int len = is.read(buf, 0, buf.length);
if (len < 0) {
context.closeSilent(sockin);
throw new EOFException("EOF");
}
context.getStatistics().incInMsgs().incInBytes(len);
os.write(buf, 0, len);
os.flush();
context.getStatistics().incOutMsgs().incOutBytes(len);
return true;
}
}
} |
package org.jpmml.converter;
import org.dmg.pmml.DataType;
import org.dmg.pmml.FieldName;
public class ObjectFeature extends Feature {
public ObjectFeature(PMMLEncoder encoder, FieldName name, DataType dataType){
super(encoder, name, dataType);
}
@Override
public ContinuousFeature toContinuousFeature(){
throw new UnsupportedOperationException("Feature " + getName() + " (" + this + ") cannot be cast to a continuous feature");
}
} |
package org.junit.runners.model;
import static java.lang.reflect.Modifier.isStatic;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.internal.MethodSorter;
/**
* Wraps a class to be run, providing method validation and annotation searching
*
* @since 4.5
*/
public class TestClass {
private final Class<?> fClass;
private final Map<Class<? extends Annotation>, List<FrameworkMethod>> fMethodsForAnnotations;
private final Map<Class<? extends Annotation>, List<FrameworkField>> fFieldsForAnnotations;
/**
* Creates a {@code TestClass} wrapping {@code klass}. Each time this
* constructor executes, the class is scanned for annotations, which can be
* an expensive process (we hope in future JDK's it will not be.) Therefore,
* try to share instances of {@code TestClass} where possible.
*/
public TestClass(Class<?> klass) {
fClass = klass;
if (klass != null && klass.getConstructors().length > 1) {
throw new IllegalArgumentException(
"Test class can only have one constructor");
}
Map<Class<? extends Annotation>, List<FrameworkMethod>> methodsForAnnotations =
new LinkedHashMap<Class<? extends Annotation>, List<FrameworkMethod>>();
Map<Class<? extends Annotation>, List<FrameworkField>> fieldsForAnnotations =
new LinkedHashMap<Class<? extends Annotation>, List<FrameworkField>>();
for (Class<?> eachClass : getSuperClasses(fClass)) {
for (Method eachMethod : MethodSorter.getDeclaredMethods(eachClass)) {
addToAnnotationLists(new FrameworkMethod(eachMethod), methodsForAnnotations);
}
// ensuring fields are sorted to make sure that entries are inserted
// and read from fieldForAnnotations in a deterministic order
for (Field eachField : getSortedDeclaredFields(eachClass)) {
addToAnnotationLists(new FrameworkField(eachField), fieldsForAnnotations);
}
}
fMethodsForAnnotations = makeDeeplyUnmodifiable(methodsForAnnotations);
fFieldsForAnnotations = makeDeeplyUnmodifiable(fieldsForAnnotations);
}
private static Field[] getSortedDeclaredFields(Class<?> clazz) {
Field[] declaredFields = clazz.getDeclaredFields();
Arrays.sort(declaredFields, new Comparator<Field>() {
public int compare(Field field1, Field field2) {
return field1.getName().compareTo(field2.getName());
}
});
return declaredFields;
}
private static <T extends FrameworkMember<T>> void addToAnnotationLists(T member,
Map<Class<? extends Annotation>, List<T>> map) {
for (Annotation each : member.getAnnotations()) {
Class<? extends Annotation> type = each.annotationType();
List<T> members = getAnnotatedMembers(map, type, true);
if (member.isShadowedBy(members)) {
return;
}
if (runsTopToBottom(type)) {
members.add(0, member);
} else {
members.add(member);
}
}
}
private static <T extends FrameworkMember<T>> Map<Class<? extends Annotation>, List<T>>
makeDeeplyUnmodifiable(Map<Class<? extends Annotation>, List<T>> source) {
LinkedHashMap<Class<? extends Annotation>, List<T>> copy =
new LinkedHashMap<Class<? extends Annotation>, List<T>>();
for (Map.Entry<Class<? extends Annotation>, List<T>> entry : source.entrySet()) {
copy.put(entry.getKey(), Collections.unmodifiableList(entry.getValue()));
}
return Collections.unmodifiableMap(copy);
}
/**
* Returns, efficiently, all the non-overridden methods in this class and
* its superclasses that are annotated with {@code annotationClass}.
*/
public List<FrameworkMethod> getAnnotatedMethods(
Class<? extends Annotation> annotationClass) {
return Collections.unmodifiableList(getAnnotatedMembers(fMethodsForAnnotations, annotationClass, false));
}
/**
* Returns, efficiently, all the non-overridden fields in this class and its
* superclasses that are annotated with {@code annotationClass}.
*/
public List<FrameworkField> getAnnotatedFields(
Class<? extends Annotation> annotationClass) {
return Collections.unmodifiableList(getAnnotatedMembers(fFieldsForAnnotations, annotationClass, false));
}
/**
* Gets a {@code Map} between annotations and methods that have
* the annotation in this class or its superclasses.
*/
public Map<Class<? extends Annotation>, List<FrameworkMethod>> getAnnotationToMethods() {
return fMethodsForAnnotations;
}
/**
* Gets a {@code Map} between annotations and fields that have
* the annotation in this class or its superclasses.
*/
public Map<Class<? extends Annotation>, List<FrameworkField>> getAnnotationToFields() {
return fFieldsForAnnotations;
}
private static <T> List<T> getAnnotatedMembers(Map<Class<? extends Annotation>, List<T>> map,
Class<? extends Annotation> type, boolean fillIfAbsent) {
if (!map.containsKey(type) && fillIfAbsent) {
map.put(type, new ArrayList<T>());
}
List<T> members = map.get(type);
return members == null ? Collections.<T>emptyList() : members;
}
private static boolean runsTopToBottom(Class<? extends Annotation> annotation) {
return annotation.equals(Before.class)
|| annotation.equals(BeforeClass.class);
}
private static List<Class<?>> getSuperClasses(Class<?> testClass) {
ArrayList<Class<?>> results = new ArrayList<Class<?>>();
Class<?> current = testClass;
while (current != null) {
results.add(current);
current = current.getSuperclass();
}
return results;
}
/**
* Returns the underlying Java class.
*/
public Class<?> getJavaClass() {
return fClass;
}
/**
* Returns the class's name.
*/
public String getName() {
if (fClass == null) {
return "null";
}
return fClass.getName();
}
/**
* Returns the only public constructor in the class, or throws an {@code
* AssertionError} if there are more or less than one.
*/
public Constructor<?> getOnlyConstructor() {
Constructor<?>[] constructors = fClass.getConstructors();
Assert.assertEquals(1, constructors.length);
return constructors[0];
}
/**
* Returns the annotations on this class
*/
public Annotation[] getAnnotations() {
if (fClass == null) {
return new Annotation[0];
}
return fClass.getAnnotations();
}
public <T> List<T> getAnnotatedFieldValues(Object test,
Class<? extends Annotation> annotationClass, Class<T> valueClass) {
List<T> results = new ArrayList<T>();
for (FrameworkField each : getAnnotatedFields(annotationClass)) {
try {
Object fieldValue = each.get(test);
if (valueClass.isInstance(fieldValue)) {
results.add(valueClass.cast(fieldValue));
}
} catch (IllegalAccessException e) {
throw new RuntimeException(
"How did getFields return a field we couldn't access?", e);
}
}
return results;
}
public <T> List<T> getAnnotatedMethodValues(Object test,
Class<? extends Annotation> annotationClass, Class<T> valueClass) {
List<T> results = new ArrayList<T>();
for (FrameworkMethod each : getAnnotatedMethods(annotationClass)) {
try {
Object fieldValue = each.invokeExplosively(test);
if (valueClass.isInstance(fieldValue)) {
results.add(valueClass.cast(fieldValue));
}
} catch (Throwable e) {
throw new RuntimeException(
"Exception in " + each.getName(), e);
}
}
return results;
}
public boolean isANonStaticInnerClass() {
return fClass.isMemberClass() && !isStatic(fClass.getModifiers());
}
} |
package org.minimalj.model.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.minimalj.application.DevMode;
import org.minimalj.model.EnumUtils;
import org.minimalj.model.View;
import org.minimalj.model.ViewUtil;
import org.minimalj.model.annotation.AnnotationUtil;
import org.minimalj.model.properties.FlatProperties;
import org.minimalj.model.properties.Properties;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.util.Codes;
import org.minimalj.util.FieldUtils;
import org.minimalj.util.GenericUtils;
import org.minimalj.util.StringUtils;
import org.minimalj.util.resources.Resources;
/**
* Test some restricitions on model classes.<p>
*
* These tests are called by JUnit tests but also by Persistence.
* They are fast and its better to see problems at startup of an application.
*/
public class ModelTest {
private static enum ModelClassType {
MAIN, // a main class can have fields of a simple class, lists of list_elements
SIMPLE, // as simple class can have fields of simple classes but no lists
LIST_ELEMENT, // list element class cannot have a reference to simple classes or contain lists itself
VIEW,
CODE;
}
private final Map<Class<?>, ModelClassType> modelClassTypes = new HashMap<>();
private Set<Class<?>> testedClasses = new HashSet<Class<?>>();
private final List<String> problems = new ArrayList<String>();
private final SortedSet<String> missingResources = new TreeSet<String>();
public ModelTest(Class<?>... mainModelClasses) {
this(Arrays.asList(mainModelClasses));
}
public ModelTest(Collection<Class<?>> mainModelClasses) {
for (Class<?> clazz : mainModelClasses) {
modelClassTypes.put(clazz, ModelClassType.MAIN);
}
for (Class<?> clazz : mainModelClasses) {
testClass(clazz);
}
}
public List<String> getProblems() {
return problems;
}
public boolean isValid() {
return problems.isEmpty();
}
private void testClass(Class<?> clazz) {
if (!testedClasses.contains(clazz)) {
testedClasses.add(clazz);
testNoSuperclass(clazz);
testId(clazz);
testVersion(clazz);
testConstructor(clazz);
testFields(clazz);
problems.addAll(FlatProperties.testProperties(clazz));
if (DevMode.isActive()) {
testResources(clazz);
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void testConstructor(Class<?> clazz) {
if (Enum.class.isAssignableFrom(clazz)) {
try {
EnumUtils.createEnum((Class<Enum>) clazz, "Test");
} catch (Exception e) {
problems.add("Not possible to create runtime instance of enum " + clazz.getName() + ". Possibly there is no empty constructor");
}
} else {
try {
Constructor<?> constructor = clazz.getConstructor();
if (!Modifier.isPublic(constructor.getModifiers())) {
problems.add("Constructor of " + clazz.getName() + " not public");
}
} catch (NoSuchMethodException e) {
problems.add(clazz.getName() + " has no public empty constructor");
}
}
}
private boolean isMain(Class<?> clazz) {
return modelClassTypes.get(clazz) == ModelClassType.MAIN;
}
private void testNoSuperclass(Class<?> clazz) {
if (clazz.getSuperclass() != Object.class && (clazz.getSuperclass() != Enum.class || isMain(clazz))) {
problems.add(clazz.getName() + ": Domain classes must not extends other classes");
}
}
private void testId(Class<?> clazz) {
ModelClassType modelClassType = modelClassTypes.get(clazz);
try {
PropertyInterface property = FlatProperties.getProperty(clazz, "id");
switch (modelClassType) {
case CODE:
if (!FieldUtils.isAllowedCodeId(property.getClazz())) {
problems.add(clazz.getName() + ": Code id must be of Integer, String or Object");
}
break;
case MAIN:
case VIEW:
if (property.getClazz() != Object.class) {
problems.add(clazz.getName() + ": Id must be Object");
}
break;
default:
problems.add(clazz.getName() + ": is not allowed to have an id field");
break;
}
} catch (IllegalArgumentException e) {
switch (modelClassType) {
case CODE:
problems.add(clazz.getName() + ": Code classes must have an id field of Integer, String or Object");
break;
case MAIN:
problems.add(clazz.getName() + ": Domain classes must have an id field of type object");
break;
case VIEW:
problems.add(clazz.getName() + ": View classes must have an id field of type object");
break;
default:
break;
}
}
}
private void testVersion(Class<?> clazz) {
try {
Field fieldVersion = clazz.getField("version");
if (isMain(clazz)) {
if (fieldVersion.getType() == Integer.class) {
problems.add(clazz.getName() + ": Domain classes version must be of primitiv type int");
}
if (!FieldUtils.isPublic(fieldVersion)) {
problems.add(clazz.getName() + ": field version must be public");
}
} else {
problems.add(clazz.getName() + ": Only domain classes are allowed to have an version field");
}
} catch (NoSuchFieldException e) {
// thats ok, version is not mandatory
} catch (SecurityException e) {
problems.add(clazz.getName() + " makes SecurityException with the id field");
}
}
private void testFields(Class<?> clazz) {
Field[] fields = clazz.getFields();
for (Field field : fields) {
testField(field);
}
}
private void testField(Field field) {
if (FieldUtils.isPublic(field) && !FieldUtils.isStatic(field) && !FieldUtils.isTransient(field) && !field.getName().equals("id") && !field.getName().equals("version")) {
testTypeOfField(field);
testNoMethodsForPublicField(field);
Class<?> fieldType = field.getType();
if (fieldType == String.class) {
if (!View.class.isAssignableFrom(field.getDeclaringClass())) {
testSize(field);
}
} else if (List.class.equals(fieldType)) {
if (!isMain(field.getDeclaringClass())) {
String messagePrefix = field.getName() + " of " + field.getDeclaringClass().getName();
problems.add(messagePrefix + ": not allowed. Only main model class or inline fields in these classes may contain lists");
}
}
}
}
private void testTypeOfField(Field field) {
Class<?> fieldType = field.getType();
String messagePrefix = field.getName() + " of " + field.getDeclaringClass().getName();
if (fieldType == List.class || fieldType == Set.class) {
if (!FieldUtils.isFinal(field)) {
problems.add(messagePrefix + " must be final (" + fieldType.getSimpleName() + " Fields must be final)");
}
if (fieldType == List.class) {
testTypeOfListField(field, messagePrefix);
} else if (fieldType == Set.class) {
testTypeOfSetField(field, messagePrefix);
}
} else {
testTypeOfField(field, messagePrefix);
}
}
private void testTypeOfListField(Field field, String messagePrefix) {
Class<?> listType = null;
try {
listType = GenericUtils.getGenericClass(field);
} catch (Exception x) {
// silent
}
if (listType != null) {
messagePrefix = "Generic of " + messagePrefix;
testTypeOfListField(listType, messagePrefix);
} else {
problems.add("Could not evaluate generic of " + messagePrefix);
}
}
private void testTypeOfSetField(Field field, String messagePrefix) {
@SuppressWarnings("rawtypes")
Class setType = null;
try {
setType = GenericUtils.getGenericClass(field);
} catch (Exception x) {
// silent
}
if (setType != null) {
if (!Enum.class.isAssignableFrom(setType)) {
problems.add("Set type must be an enum class: " + messagePrefix);
}
@SuppressWarnings("unchecked")
List<?> values = EnumUtils.itemList(setType);
if (values.size() > 32) {
problems.add("Set enum must not have more than 32 elements: " + messagePrefix);
}
} else {
problems.add("Could not evaluate generic of " + messagePrefix);
}
}
private void testTypeOfField(Field field, String messagePrefix) {
Class<?> fieldType = field.getType();
if (FieldUtils.isAllowedPrimitive(fieldType)) {
return;
}
if (fieldType.isPrimitive()) {
problems.add(messagePrefix + " has invalid Type");
}
if (Modifier.isAbstract(fieldType.getModifiers())) {
problems.add(messagePrefix + " must not be of an abstract Type");
}
if (isMain(fieldType) && !ViewUtil.isView(field)) {
problems.add(messagePrefix + " may not reference the other main model class " + fieldType.getSimpleName());
}
if (fieldType.isArray()) {
problems.add(messagePrefix + " is an array which is not allowed");
}
if (Codes.isCode(fieldType)) {
if (!modelClassTypes.containsKey(fieldType)) {
modelClassTypes.put(fieldType, ModelClassType.CODE);
testClass(fieldType);
}
}
if (ViewUtil.isView(field)) {
if (!modelClassTypes.containsKey(fieldType)) {
modelClassTypes.put(fieldType, ModelClassType.VIEW);
testClass(fieldType);
}
}
if (!FieldUtils.isFinal(field)) {
if (!modelClassTypes.containsKey(fieldType)) {
modelClassTypes.put(fieldType, ModelClassType.SIMPLE);
testClass(fieldType);
}
}
}
private void testTypeOfListField(Class<?> fieldType, String messagePrefix) {
if (fieldType.isPrimitive()) {
problems.add(messagePrefix + " has invalid Type");
return;
}
if (Modifier.isAbstract(fieldType.getModifiers())) {
problems.add(messagePrefix + " must not be of an abstract Type");
return;
}
if (fieldType.isArray()) {
problems.add(messagePrefix + " is an array which is not allowed");
return;
}
ModelClassType type = modelClassTypes.get(fieldType);
if (type == null) {
modelClassTypes.put(fieldType, ModelClassType.LIST_ELEMENT);
testClass(fieldType);
return;
}
// report problem
switch (type) {
case MAIN:
case VIEW:
problems.add(messagePrefix + " is a list of other main objects or views which is not allowed");
break;
case CODE:
problems.add(messagePrefix + " is a list of codes which is not allowed");
break;
case SIMPLE:
case LIST_ELEMENT:
// no problem
break;
}
}
private void testSize(Field field) {
PropertyInterface property = Properties.getProperty(field);
try {
AnnotationUtil.getSize(property);
} catch (IllegalArgumentException x) {
problems.add("Missing size for: " + property.getDeclaringClass().getName() + "." + property.getPath());
}
}
private void testNoMethodsForPublicField(Field field) {
PropertyInterface property = Properties.getProperty(field);
if (property != null) {
if (property.getClass().getSimpleName().startsWith("Method")) {
problems.add("A public attribute must not have getter or setter methods: " + field.getDeclaringClass().getName() + "." + field.getName());
}
} else {
problems.add("No property for " + field.getName());
}
}
private void testResources(Class<?> clazz) {
for (PropertyInterface property : FlatProperties.getProperties(clazz).values()) {
if (StringUtils.equals(property.getName(), "id", "version")) continue;
String resourceText = Resources.getObjectFieldName(Resources.getResourceBundle(), property);
if (resourceText.startsWith("'") && resourceText.endsWith("'")) {
missingResources.add(resourceText.substring(1, resourceText.length()-1));
}
}
}
public void printMissingResources() {
for (String key : missingResources) {
System.out.println(key + " = ");
}
}
} |
package org.myrobotlab.service;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.data.MyoData;
import org.myrobotlab.service.interfaces.MyoDataListener;
import org.myrobotlab.service.interfaces.MyoDataPublisher;
import org.slf4j.Logger;
import com.thalmic.myo.DeviceListener;
import com.thalmic.myo.FirmwareVersion;
import com.thalmic.myo.Hub;
import com.thalmic.myo.Myo;
import com.thalmic.myo.Pose;
import com.thalmic.myo.Quaternion;
import com.thalmic.myo.Vector3;
import com.thalmic.myo.enums.Arm;
import com.thalmic.myo.enums.PoseType;
import com.thalmic.myo.enums.UnlockType;
import com.thalmic.myo.enums.VibrationType;
import com.thalmic.myo.enums.WarmupResult;
import com.thalmic.myo.enums.WarmupState;
import com.thalmic.myo.enums.XDirection;
public class MyoThalmic extends Service implements DeviceListener, MyoDataListener, MyoDataPublisher {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(MyoThalmic.class);
static int scale = 180;
double rollW = 0;
double pitchW = 0;
double yawW = 0;
transient Pose currentPose;
transient Arm whichArm;
transient Myo thalmicMyo = null;
transient Hub thalmicHub = null;
transient MyoProxy myo = null;
transient HubProxy hub = null;
transient HubThread hubThread = null;
MyoData myodata = new MyoData();
boolean delta = false;
boolean locked = true;
int batterLevel = 0;
boolean isConnected = false;
class HubThread extends Thread {
public boolean running = false;
MyoThalmic myService = null;
public HubThread(MyoThalmic myService) {
this.myService = myService;
}
public void run() {
running = true;
while (running) {
hub.run(1000 / 20);
// log.info(myService.toString());
}
}
}
public class HubProxy {
public HubProxy() {
if (!isVirtual && hub == null){
thalmicHub = new Hub("com.example.hello-myo");
}
}
public void run(int x){
if (!isVirtual){
thalmicHub.run(x);
}else {
sleep(1000);
}
}
public void removeListener(DeviceListener myoThalmic) {
if (!isVirtual){
thalmicHub.removeListener(myoThalmic);
}
}
public MyoProxy waitForMyo(int i) {
if (!isVirtual){
thalmicMyo = thalmicHub.waitForMyo(i);
}
myo = new MyoProxy();
return myo;
}
public void addListener(DeviceListener myoThalmic) {
if (!isVirtual){
thalmicHub.addListener(myoThalmic);
}
}
}
public class MyoProxy {
public void requestBatteryLevel() {
if (!isVirtual){
thalmicMyo.requestBatteryLevel();
}
}
public void lock() {
if (!isVirtual){
thalmicMyo.lock();
}
}
public void unlock(UnlockType unlockTimed) {
if (!isVirtual){
thalmicMyo.unlock(unlockTimed);
}
}
}
public void disconnect() {
if (hubThread != null) {
hubThread.running = false;
hubThread = null;
}
hub.removeListener(this);
isConnected = false;
broadcastState();
}
public void connect() {
if (hub == null) {
// FIXME - put in connect
try {
currentPose = new Pose();
hub = new HubProxy();
} catch (Exception e) {
Logging.logError(e);
}
}
if (myo == null) {
info("Attempting to find a Myo...");
myo = hub.waitForMyo(10000);
}
if (myo == null) {
error("Unable to find a Myo");
isConnected = false;
return;
}
info("Connected to a Myo armband!");
hub.addListener(this);
if (hubThread == null) {
hubThread = new HubThread(this);
hubThread.start();
}
isConnected = true;
myo.requestBatteryLevel();
broadcastState();
}
public MyoThalmic(String n) {
super(n);
}
@Override
public void onOrientationData(Myo myo, long timestamp, Quaternion rotation) {
Quaternion normalized = rotation.normalized();
double roll = Math.atan2(2.0f * (normalized.getW() * normalized.getX() + normalized.getY() * normalized.getZ()),
1.0f - 2.0f * (normalized.getX() * normalized.getX() + normalized.getY() * normalized.getY()));
double pitch = Math.asin(2.0f * (normalized.getW() * normalized.getY() - normalized.getZ() * normalized.getX()));
double yaw = Math.atan2(2.0f * (normalized.getW() * normalized.getZ() + normalized.getX() * normalized.getY()),
1.0f - 2.0f * (normalized.getY() * normalized.getY() + normalized.getZ() * normalized.getZ()));
rollW = Math.round((roll + Math.PI) / (Math.PI * 2.0) * scale);
pitchW = Math.round((pitch + Math.PI / 2.0) / Math.PI * scale);
yawW = Math.round((yaw + Math.PI) / (Math.PI * 2.0) * scale);
delta = (myodata.roll - rollW != 0) || (myodata.pitch - pitchW != 0) || (myodata.yaw - yawW != 0);
if (delta) {
myodata.roll = rollW;
myodata.pitch = pitchW;
myodata.yaw = yawW;
myodata.timestamp = timestamp;
invoke("publishMyoData", myodata);
}
}
@Override
public void onPose(Myo myo, long timestamp, Pose pose) {
currentPose = pose;
myodata.currentPose = pose.getType().toString();
if (currentPose.getType() == PoseType.FIST) {
myo.vibrate(VibrationType.VIBRATION_MEDIUM);
}
invoke("publishPose", pose);
invoke("publishMyoData", myodata);
}
public void addPoseListener(Service service) {
addListener("publishPose", service.getName(), "onPose");
}
public Pose publishPose(Pose pose) {
return pose;
}
/*
* @Override public void onArmSync(Myo myo, long timestamp, Arm arm,
* XDirection xDirection) { whichArm = arm; }
*/
@Override
public void onArmUnsync(Myo myo, long timestamp) {
whichArm = null;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("\r");
String xDisplay = String.format("[%s%s]", repeatCharacter('*', (int) rollW), repeatCharacter(' ', (int) (scale - rollW)));
String yDisplay = String.format("[%s%s]", repeatCharacter('*', (int) pitchW), repeatCharacter(' ', (int) (scale - pitchW)));
String zDisplay = String.format("[%s%s]", repeatCharacter('*', (int) yawW), repeatCharacter(' ', (int) (scale - yawW)));
String armString = null;
if (whichArm != null) {
armString = String.format("[%s]", whichArm == Arm.ARM_LEFT ? "L" : "R");
} else {
armString = String.format("[?]");
}
String poseString = null;
if (currentPose != null) {
String poseTypeString = currentPose.getType().toString();
poseString = String.format("[%s%" + (scale - poseTypeString.length()) + "s]", poseTypeString, " ");
} else {
poseString = String.format("[%14s]", " ");
}
builder.append(xDisplay);
builder.append(yDisplay);
builder.append(zDisplay);
builder.append(armString);
builder.append(poseString);
return builder.toString();
}
public String repeatCharacter(char character, int numOfTimes) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < numOfTimes; i++) {
builder.append(character);
}
return builder.toString();
}
@Override
public void onPair(Myo myo, long timestamp, FirmwareVersion firmwareVersion) {
info("onPair");
}
@Override
public void onUnpair(Myo myo, long timestamp) {
info("onUnpair");
}
@Override
public void onConnect(Myo myo, long timestamp, FirmwareVersion firmwareVersion) {
info("onConnect");
}
@Override
public void onDisconnect(Myo myo, long timestamp) {
info("onDisconnect");
}
@Override
public void onUnlock(Myo myo, long timestamp) {
// info("onUnlock");
locked = false;
invoke("publishLocked", locked);
}
@Override
public void onLock(Myo myo, long timestamp) {
// info("onLock");
locked = true;
invoke("publishLocked", locked);
}
public Boolean publishLocked(Boolean b) {
return b;
}
@Override
public void onAccelerometerData(Myo myo, long timestamp, Vector3 accel) {
// info("onAccelerometerData");
}
@Override
public void onGyroscopeData(Myo myo, long timestamp, Vector3 gyro) {
// info("onGyroscopeData");
}
@Override
public void onRssi(Myo myo, long timestamp, int rssi) {
info("onRssi");
}
@Override
public void onEmgData(Myo myo, long timestamp, byte[] emg) {
info("onEmgData");
}
public void lock() {
myo.lock();
}
public void unlock() {
myo.unlock(UnlockType.UNLOCK_TIMED);
}
/*
* public void setLockingPolicy(String policy){ myo.setL
* myo.setLockingPolicy("none") ; }
*/
@Override
public MyoData onMyoData(MyoData myodata) {
return myodata;
}
@Override
public MyoData publishMyoData(MyoData myodata) {
return myodata;
}
public void addMyoDataListener(Service service) {
addListener("publishMyoData", service.getName(), "onMyoData");
}
/*
@Override
public void onArmSync(Myo myo, long arg1, Arm arm, XDirection direction, WarmupState warmUpState) {
log.info("onArmSync {}", arm);
whichArm = arm;
invoke("publishArmSync", arm);
}
*/
public Arm publishArmSync(Arm arm) {
return arm;
}
@Override
public void onBatteryLevelReceived(Myo myo, long timestamp, int level) {
batterLevel = level;
log.info("onBatteryLevelReceived {} {}", timestamp, batterLevel);
invoke("publishBatteryLevel", batterLevel);
}
public Integer publishBatteryLevel(Integer level) {
return level;
}
@Override
public void onWarmupCompleted(Myo myo, long unkown, WarmupResult warmUpResult) {
log.info("onWarmupCompleted {} {}", unkown, warmUpResult);
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(MyoThalmic.class.getCanonicalName());
meta.addDescription("Myo service to control with the Myo armband");
meta.addCategory("control", "sensor");
meta.addDependency("com.github.nicholasastuart", "myo-java", "0.9.1");
return meta;
}
public static void main(String[] args) {
LoggingFactory.init(Level.INFO);
try {
MyoThalmic myo = (MyoThalmic) Runtime.start("myo", "MyoThalmic");
// myo.setVirtual(true);
myo.connect();
Runtime.start("webgui", "WebGui");
/*
* Hub hub = new Hub("com.example.hello-myo");
*
* log.info("Attempting to find a Myo..."); log.info(
* "Attempting to find a Myo");
*
* Myo myodevice = hub.waitForMyo(10000);
*
* if (myodevice == null) { throw new RuntimeException(
* "Unable to find a Myo!"); }
*
* log.info("Connected to a Myo armband!"); log.info(
* "Connected to a Myo armband");
*
* //DeviceListener dataCollector = new DataCollector();
* //hub.addListener(myo);
*
* while (true) { hub.run(1000 / 20); //System.out.print(dataCollector);
*
*
*
* }
*/
} catch (Exception e) {
Logging.logError(e);
}
}
@Override
public void onArmSync(Myo myo, long timestamp, Arm arm, XDirection xDirection, WarmupState warmupState) {
log.info("onArmSync {}", arm);
whichArm = arm;
invoke("publishArmSync", arm);
}
} |
package org.pac4j.dropwizard;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotNull;
import org.pac4j.core.authorization.authorizer.Authorizer;
import org.pac4j.core.authorization.generator.AuthorizationGenerator;
import org.pac4j.core.client.Client;
import org.pac4j.core.client.Clients;
import org.pac4j.core.config.Config;
import org.pac4j.core.http.CallbackUrlResolver;
import org.pac4j.core.matching.Matcher;
import org.pac4j.jax.rs.pac4j.JaxRsCallbackUrlResolver;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Dropwizard configuration factory to configure pac4j's {@link Config},
* {@link Clients} as well as global JAX-RS
* {@link org.pac4j.jax.rs.filters.SecurityFilter}s.
*
* @see Pac4jConfiguration
* @see org.pac4j.core.config.Config
* @see org.pac4j.core.client.Clients
* @author Evan Meagher
* @author Victor Noel - Linagora
* @since 1.0.0
*/
public class Pac4jFactory {
@NotNull
private List<FilterConfiguration> globalFilters = new ArrayList<>();
private String clientNameParameter;
private String callbackUrl;
private CallbackUrlResolver callbackUrlResolver = new JaxRsCallbackUrlResolver();
@NotNull
private List<AuthorizationGenerator> authorizationGenerators = new ArrayList<>();
@NotNull
private Map<String, Matcher> matchers = new HashMap<>();
@NotNull
private List<Client> clients = new ArrayList<>();
@NotNull
private Map<String, Authorizer> authorizers = new HashMap<>();
@JsonProperty
public List<FilterConfiguration> getGlobalFilters() {
return globalFilters;
}
@JsonProperty
public void setGlobalFilters(List<FilterConfiguration> filters) {
this.globalFilters = filters;
}
@JsonProperty
public String getClientNameParameter() {
return clientNameParameter;
}
@JsonProperty
public void setClientNameParameter(String clientNameParameter) {
this.clientNameParameter = clientNameParameter;
}
@JsonProperty
public String getCallbackUrl() {
return callbackUrl;
}
@JsonProperty
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
@JsonProperty
public List<AuthorizationGenerator> getAuthorizationGenerators() {
return authorizationGenerators;
}
@JsonProperty
public void setAuthorizationGenerators(
List<AuthorizationGenerator> authorizationGenerators) {
this.authorizationGenerators = authorizationGenerators;
}
@JsonProperty
public Map<String, Matcher> getMatchers() {
return matchers;
}
@JsonProperty
public void setMatchers(Map<String, Matcher> matchers) {
this.matchers = matchers;
}
@JsonProperty
public List<Client> getClients() {
return clients;
}
@JsonProperty
public void setClients(List<Client> clients) {
this.clients = clients;
}
@JsonProperty
public Map<String, Authorizer> getAuthorizers() {
return authorizers;
}
@JsonProperty
public void setAuthorizers(Map<String, Authorizer> authorizers) {
this.authorizers = authorizers;
}
@JsonProperty
public CallbackUrlResolver getCallbackUrlResolver() {
return callbackUrlResolver;
}
@JsonProperty
public void setCallbackUrlResolver(
CallbackUrlResolver callbackUrlResolver) {
this.callbackUrlResolver = callbackUrlResolver;
}
public Config build() {
Clients client = new Clients();
Config config = new Config(client);
if (callbackUrl != null) {
client.setCallbackUrl(callbackUrl);
}
if (clientNameParameter != null) {
client.setClientNameParameter(clientNameParameter);
}
client.setCallbackUrlResolver(callbackUrlResolver);
client.setAuthorizationGenerators(authorizationGenerators);
client.setClients(clients);
config.setAuthorizers(authorizers);
config.setMatchers(matchers);
return config;
}
public static class FilterConfiguration {
private Boolean skipResponse;
private String clients;
private String authorizers;
private String matchers;
private Boolean multiProfile;
@JsonProperty
public String getClients() {
return clients;
}
@JsonProperty
public String getAuthorizers() {
return authorizers;
}
@JsonProperty
public String getMatchers() {
return matchers;
}
@JsonProperty
public Boolean getMultiProfile() {
return multiProfile;
}
@JsonProperty
public Boolean getSkipResponse() {
return skipResponse;
}
@JsonProperty
public void setClients(String clients) {
this.clients = clients;
}
@JsonProperty
public void setAuthorizers(String authorizers) {
this.authorizers = authorizers;
}
@JsonProperty
public void setMatchers(String matchers) {
this.matchers = matchers;
}
@JsonProperty
public void setMultiProfile(Boolean multiProfile) {
this.multiProfile = multiProfile;
}
@JsonProperty
public void setSkipResponse(Boolean skipResponse) {
this.skipResponse = skipResponse;
}
}
} |
/**
Khalid
*/
package org.sikuli.slides.utils;
import java.io.File;
/**
* This class contains constants.
* @author Khalid Alharbi
*
*/
public class Constants {
/**
* The working directory absolute path.
* This holds the sikuli slides working directory in the operating system's temp directory.
*/
public static String workingDirectoryPath;
/**
* The current project directory name that contains the imported and extracted .pptx file.
*/
public static String projectDirectory;
/**
* The name of the directory that sikuli-slides creates in the operating system's tmp directory.
*/
public static final String SIKULI_SLIDES_ROOT_DIRECTORY="org.sikuli.SikuliSlides";
/**
* The name of the directory that contains all sikuli related files in the .pptx file.
*/
public static final String SIKULI_DIRECTORY=File.separator+"sikuli";
/**
* The name of the images directory that contains the cropped target images.
*/
public static final String IMAGES_DIRECTORY=File.separator+"images";
/**
* The slides directory that contains the XML files for each slide in the .pptx file.
*/
public static final String SLIDES_DIRECTORY=File.separator+"ppt"+File.separator+"slides";
/**
* The slides directory that contains the media files for each slide in the .pptx file.
*/
public static final String MEDIA_DIRECTORY=File.separator+"ppt"+File.separator+"media";
/**
* The slides directory that contains the slide notes.
*/
public static final String SLIDE_NOTES_DIRECTORY=File.separator+"ppt"+File.separator+"notesSlides";
/**
* The presentaion.xml absolute path name.
*/
public static final String PRESENTATION_DIRECTORY=File.separator+"ppt"+File.separator+"presentation.xml";
/**
* The relationship directory that contains info about the duplicated media files in the presentation slides.
*/
public static final String RELATIONSHIP_DIRECTORY=File.separator+"ppt"+File.separator+"slides"+File.separator+"_rels";
/**
* The maximum time to wait in milliseconds
*/
public static int MaxWaitTime=15000;
/**
* The duration time in seconds to display annotation (canvas) around the target on the screen.
*/
public static final int CANVAS_DURATION=1;
/**
* Screen id. Use this constant to run the test on a secondary monitor,
* 0 means the default monitor and 1 means the secondary monitor.
*/
public static int ScreenId=0;
/**
* This control how fuzzy the image search is. A value of 1 means the search
* is very precise and less fuzzy
*/
public static double MinScore=0.7;
/**
* Desktop input events
*/
public enum DesktopEvent {
LEFT_CLICK, RIGHT_CLICK, DOUBLE_CLICK, DRAG_N_DROP, KEYBOARD_TYPING, LAUNCH_BROWSER, FIND
}
} |
package com.rgi.geopackage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.FileAlreadyExistsException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import utility.DatabaseUtility;
import com.rgi.geopackage.core.GeoPackageCore;
import com.rgi.geopackage.extensions.GeoPackageExtensions;
import com.rgi.geopackage.features.GeoPackageFeatures;
import com.rgi.geopackage.metadata.GeoPackageMetadata;
import com.rgi.geopackage.schema.GeoPackageSchema;
import com.rgi.geopackage.tiles.GeoPackageTiles;
import com.rgi.geopackage.verification.ConformanceException;
import com.rgi.geopackage.verification.FailedRequirement;
import com.rgi.geopackage.verification.Severity;
public class GeoPackage implements AutoCloseable
{
/**
* @param file
* Location on disk that represents where an existing GeoPackage will opened and/or created
* @throws ClassNotFoundException
* when the SQLite JDBC driver cannot be found
* @throws ConformanceException
* when the verifyConformance parameter is true, and if
* there are any conformance violations with the severity
* {@link Severity#Error}
* @throws IOException
* when openMode is set to OpenMode.Create, and the file already
* exists, openMode is set to OpenMode.Open, and the file does not
* exist, or if there is a file read error
* @throws SQLException
* in various cases where interaction with the JDBC connection fails
*/
public GeoPackage(final File file) throws ClassNotFoundException, ConformanceException, IOException, SQLException
{
this(file, true, OpenMode.OpenOrCreate);
}
/**
* @param file
* Location on disk that represents where an existing GeoPackage will opened and/or created
* @param verifyConformance
* Indicates whether {@link #verify()} should be called
* automatically. If verifyConformance is true and
* {@link #verify()} is called automatically, it will throw if
* there are any conformance violations with the severity
* {@link Severity#Error}. Throwing from this method means that
* it won't be possible to instantiate a GeoPackage object based
* on an SQLite "GeoPackage" file with severe errors.
* @throws ClassNotFoundException
* when the SQLite JDBC driver cannot be found
* @throws ConformanceException
* when the verifyConformance parameter is true, and if
* there are any conformance violations with the severity
* {@link Severity#Error}
* @throws IOException
* when openMode is set to OpenMode.Create, and the file already
* exists, openMode is set to OpenMode.Open, and the file does not
* exist, or if there is a file read error
* @throws SQLException
* in various cases where interaction with the JDBC connection fails
*/
public GeoPackage(final File file, final boolean verifyConformance) throws ClassNotFoundException, ConformanceException, IOException, SQLException
{
this(file, verifyConformance, OpenMode.OpenOrCreate);
}
/**
* @param file
* Location on disk that represents where an existing GeoPackage will opened and/or created
* @param openMode
* Controls the file creation/opening behavior
* @throws ClassNotFoundException
* when the SQLite JDBC driver cannot be found
* @throws ConformanceException
* when the verifyConformance parameter is true, and if
* there are any conformance violations with the severity
* {@link Severity#Error}
* @throws IOException
* when openMode is set to OpenMode.Create, and the file already
* exists, openMode is set to OpenMode.Open, and the file does not
* exist, or if there is a file read error
* @throws SQLException
* in various cases where interaction with the JDBC connection fails
*/
public GeoPackage(final File file, final OpenMode openMode) throws ClassNotFoundException, ConformanceException, IOException, SQLException
{
this(file, true, openMode);
}
/**
* @param file
* Location on disk that represents where an existing GeoPackage
* will opened and/or created
* @param verifyConformance
* Indicates whether {@link #verify()} should be called
* automatically. If verifyConformance is true and
* {@link #verify()} is called automatically, it will throw if
* there are any conformance violations with the severity
* {@link Severity#Error}. Throwing from this method means that
* it won't be possible to instantiate a GeoPackage object based
* on an SQLite "GeoPackage" file with severe errors.
* @param openMode
* Controls the file creation/opening behavior
* @throws ClassNotFoundException
* when the SQLite JDBC driver cannot be found
* @throws ConformanceException
* when the verifyConformance parameter is true, and if there
* are any conformance violations with the severity
* {@link Severity#Error}
* @throws IOException
* when openMode is set to OpenMode.Create, and the file already
* exists, openMode is set to OpenMode.Open, and the file does
* not exist, or if there is a file read error
* @throws FileAlreadyExistsException
* when openMode is set to OpenMode.Create, and the file already
* exists
* @throws FileNotFoundException
* when openMode is set to OpenMode.Open, and the file does not
* exist
* @throws SQLException
* in various cases where interaction with the JDBC connection
* fails
*/
public GeoPackage(final File file, final boolean verifyConformance, final OpenMode openMode) throws ClassNotFoundException, ConformanceException, IOException, SQLException
{
if(file == null)
{
throw new IllegalArgumentException("file is null");
}
final boolean isNewFile = !file.exists();
if(openMode == OpenMode.Create && !isNewFile)
{
throw new FileAlreadyExistsException(file.getAbsolutePath());
}
if(openMode == OpenMode.Open && isNewFile)
{
throw new FileNotFoundException(String.format("%s does not exist", file.getAbsolutePath()));
}
this.file = file;
Class.forName("org.sqlite.JDBC"); // Register the driver
this.databaseConnection = DriverManager.getConnection("jdbc:sqlite:" + file.getPath()); // Initialize the database connection
try
{
this.databaseConnection.setAutoCommit(false);
DatabaseUtility.setPragmaForeignKeys(this.databaseConnection, true);
this.core = new GeoPackageCore (this.databaseConnection, isNewFile);
this.features = new GeoPackageFeatures (this.databaseConnection, this.core);
this.tiles = new GeoPackageTiles (this.databaseConnection, this.core);
this.schema = new GeoPackageSchema (this.databaseConnection);
this.metadata = new GeoPackageMetadata (this.databaseConnection);
this.extensions = new GeoPackageExtensions(this.databaseConnection);
if(isNewFile)
{
DatabaseUtility.setApplicationId(this.databaseConnection,
ByteBuffer.wrap(GeoPackage.GeoPackageSqliteApplicationId)
.asIntBuffer()
.get());
this.databaseConnection.commit();
}
if(verifyConformance)
{
this.verify();
}
try
{
this.sqliteVersion = DatabaseUtility.getSqliteVersion(this.file);
}
catch(final Exception ex)
{
throw new IOException("Unable to read SQLite version: " + ex.getMessage());
}
}
catch(final SQLException | ConformanceException | IOException ex)
{
if(this.databaseConnection != null && this.databaseConnection.isClosed() == false)
{
this.databaseConnection.close();
}
// If anything goes wrong, clean up the new file that may have been created
if(isNewFile && file.exists())
{
file.delete();
}
throw ex;
}
}
/**
* The file associated with this GeoPackage
*
* @return the file
*/
public File getFile()
{
return this.file;
}
/**
* The version of the SQLite database associated with this GeoPackage
*
* @return the sqliteVersion
*/
public String getSqliteVersion()
{
return this.sqliteVersion;
}
/**
* The application id of the SQLite database
*
* @return Returns the application id of the SQLite database. For a GeoPackage, by its standard, this must be 0x47503130 ("GP10" in ASCII)
* @throws SQLException Throws if there is an SQL error
*/
public int getApplicationId() throws SQLException
{
return DatabaseUtility.getApplicationId(this.databaseConnection);
}
/**
* Closes the connection to the underlying SQLite database file
*
* @throws SQLException throws if SQLException occurs
*/
@Override
public void close() throws SQLException
{
if(this.databaseConnection != null &&
this.databaseConnection.isClosed() == false)
{
this.databaseConnection.rollback(); // When Connection.close() is called, pending transactions are either automatically committed or rolled back depending on implementation defined behavior. Make the call explicitly to avoid relying on implementation defined behavior.
this.databaseConnection.close();
}
}
/**
* Requirements this GeoPackage failed to meet
*
* @return the GeoPackage requirements this GeoPackage fails to conform to
* @throws SQLException throws if SQLException occurs
*/
public Collection<FailedRequirement> getFailedRequirements() throws SQLException
{
return this.getFailedRequirements(false);
}
/**
* Requirements this GeoPackage failed to meet
*
* @param continueAfterCoreErrors
* If true, GeoPackage subsystem requirement violations will be
* reported even if there are fatal violations in the core.
* Subsystem verifications assumes that a GeoPackage is at
* least minimally operable (e.g. core tables are defined to
* the standard), and may behave unexpectedly if the GeoPackage
* does not. In this state, the reported failures of GeoPackage
* subsystems may only be of minimal value.
* @return the GeoPackage requirements this GeoPackage fails to conform to
* @throws SQLException throws if SQLException occurs
*/
public Collection<FailedRequirement> getFailedRequirements(final boolean continueAfterCoreErrors) throws SQLException
{
final List<FailedRequirement> failedRequirements = new ArrayList<>();
failedRequirements.addAll(this.core.getFailedRequirements(this.file));
// Skip verifying GeoPackage subsystems if there are fatal errors in core
if(continueAfterCoreErrors || !failedRequirements.stream().anyMatch(failedRequirement -> failedRequirement.getRequirement().severity() == Severity.Error))
{
failedRequirements.addAll(this.features .getFailedRequirements());
failedRequirements.addAll(this.tiles .getFailedRequirements());
failedRequirements.addAll(this.schema .getFailedRequirements());
failedRequirements.addAll(this.metadata .getFailedRequirements());
failedRequirements.addAll(this.extensions.getFailedRequirements());
}
return failedRequirements;
}
/**
* Verifies that the GeoPackage meets the core requirements of the GeoPackage specification
*
* @throws ConformanceException throws if the GeoPackage fails to meet the necessary requirements
* @throws SQLException throws if SQLException occurs
*/
public void verify() throws ConformanceException, SQLException
{
//final long startTime = System.nanoTime();
final Collection<FailedRequirement> failedRequirements = this.getFailedRequirements();
//System.out.println(String.format("GeoPackage took %.2f seconds to verify.", (System.nanoTime() - startTime)/1.0e9));
if(failedRequirements.stream().anyMatch(failedRequirement -> failedRequirement.getRequirement().severity() == Severity.Error))
{
throw new ConformanceException(failedRequirements);
}
if(failedRequirements.size() > 0)
{
System.err.println(String.format("GeoPackage failed to meet the following requirements:\n %s\n",
failedRequirements.stream()
.sorted((requirement1, requirement2) -> Integer.compare(requirement1.getRequirement().number(), requirement2.getRequirement().number()))
.map(failedRequirement -> String.format("(%s) Requirement %d: \"%s\"\n%s",
failedRequirement.getRequirement().severity(),
failedRequirement.getRequirement().number(),
failedRequirement.getRequirement().text(),
failedRequirement.getReason()))
.collect(Collectors.joining("\n"))));
}
}
/**
* Access to GeoPackage's "core" functionality
*
* @return returns a handle to a GeoPackageCore object
*/
public GeoPackageCore core()
{
return this.core;
}
/**
* Access to GeoPackage's "features" functionality
*
* @return returns a handle to a GeoPackageFeatures object
*/
public GeoPackageFeatures features()
{
return this.features;
}
/**
* Access to GeoPackage's "tiles" functionality
*
* @return returns a handle to a GeoPackageTiles object
*/
public GeoPackageTiles tiles()
{
return this.tiles;
}
/**
* Access to GeoPackage's "schema" functionality
*
* @return returns a handle to a GeoPackageTiles object
*/
public GeoPackageSchema schema()
{
return this.schema;
}
/**
* Access to GeoPackage's "extensions" functionality
*
* @return returns a handle to a GeoPackageExetensions object
*/
public GeoPackageExtensions extensions()
{
return this.extensions;
}
/**
* Access to GeoPackage's "metadata" functionality
*
* @return returns a handle to a GeoPackageMetadata object
*/
public GeoPackageMetadata metadata()
{
return this.metadata;
}
/**
* @author Luke Lambert
*
*/
public enum OpenMode
{
/**
* Open or Create a GeoPackage
*/
OpenOrCreate,
/**
* Open an Existing GeoPackage
*/
Open,
/**
* Create a GeoPackage
*/
Create
}
private final File file;
private final Connection databaseConnection;
private final String sqliteVersion;
private final GeoPackageCore core;
private final GeoPackageFeatures features;
private final GeoPackageTiles tiles;
private final GeoPackageSchema schema;
private final GeoPackageMetadata metadata;
private final GeoPackageExtensions extensions;
private final static byte[] GeoPackageSqliteApplicationId = new byte[] {'G', 'P', '1', '0' };
} |
package org.ugate.gui.components;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import org.ugate.resources.RS;
import com.sun.javafx.Utils;
/**
* Application frame that takes place of the typical native window look and feel.
* The content will be sized to fit in the frame.
*/
public class AppFrame extends StackPane {
public static final double TOP_LEFT_WIDTH = 90;
public static final double TOP_RIGHT_WIDTH = 140;
public static final double TOP_BORDER_HEIGHT = 80;
public static final double TOP_BORDER_CONTENT_ADJUSTMENT = 10;
public static final double BOTTOM_LEFT_WIDTH = 70;
public static final double BOTTOM_RIGHT_WIDTH = 70;
public static final double BOTTOM_BORDER_HEIGHT = 40;
public static final double BOTTOM_BORDER_CONTENT_ADJUSTMENT = 11;
public static final double LEFT_BORDER_WIDTH = 1;
public static final double RIGHT_BORDER_WIDTH = 1;
public static final double TOP_MIN_MAX_CLOSE_ADJUSTMENT = 5;
public static final double LOGO_X = 20;
public static final double LOGO_Y = 0;
private Rectangle2D backupWindowBounds;
private double mouseDragOffsetX = 0;
private double mouseDragOffsetY = 0;
private boolean isExiting = false;
public AppFrame(final Stage stage, final Region content, final double sceneWidth, final double sceneHeight,
final double minResizableWidth, final double minResizableHeight) {
// stage/scene adjustment for transparency/size
this.setMinSize(minResizableWidth, minResizableHeight);
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(new Scene(this, sceneWidth, sceneHeight, Color.TRANSPARENT));
setAlignment(Pos.TOP_LEFT);
// logo
final ImageView logoView = RS.imgView(RS.IMG_LOGO_64);
logoView.setTranslateX(LOGO_X);
logoView.setTranslateY(LOGO_Y);
// final ScaleTransition logoViewEffect = new ScaleTransition(Duration.seconds(4), logoView);
// logoViewEffect.setByX(0.5f);
// logoViewEffect.setByY(0.5f);
// logoViewEffect.setCycleCount(1);
// logoView.setOnMouseEntered(new EventHandler<MouseEvent>() {
// @Override
// public void handle(MouseEvent event) {
// if (logoViewEffect.getStatus() != javafx.animation.Animation.Status.RUNNING) {
// logoViewEffect.stop();
// logoViewEffect.setRate(1);
// logoViewEffect.play();
// logoView.setOnMouseExited(new EventHandler<MouseEvent>() {
// @Override
// public void handle(MouseEvent event) {
// if (logoViewEffect.getStatus() == javafx.animation.Animation.Status.RUNNING) {
// logoViewEffect.stop();
// logoViewEffect.setRate(-1);
// logoViewEffect.play();
// title bar
final HBox titleBar = new HBox();
//titleBar.setStyle("-fx-background-color: black;");
titleBar.setPrefHeight(TOP_BORDER_HEIGHT);
titleBar.setMaxHeight(TOP_BORDER_HEIGHT);
titleBar.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent event) {
mouseDragOffsetX = event.getSceneX();
mouseDragOffsetY = event.getSceneY();
}
});
titleBar.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent event) {
if (!(event.getTarget() instanceof ImageView)) {
stage.setX(event.getScreenX() - mouseDragOffsetX);
stage.setY(event.getScreenY() - mouseDragOffsetY);
}
}
});
final Region titleBarLeft = new Region();
titleBarLeft.setId("title-bar-left");
titleBarLeft.setPrefWidth(TOP_LEFT_WIDTH);
titleBarLeft.setMaxWidth(TOP_LEFT_WIDTH);
final Region titleBarCenter = new Region();
titleBarCenter.setId("title-bar");
HBox.setHgrow(titleBarCenter, Priority.ALWAYS);
final HBox titleBarRight = newMinMaxClose(stage);
titleBarRight.setId("title-bar-right");
titleBarRight.setPrefWidth(TOP_RIGHT_WIDTH);
titleBarRight.setMaxWidth(TOP_RIGHT_WIDTH);
//titleBarRight.getChildren().add(newMinMaxClose(stage, 0, TOP_BORDER_HEIGHT / 2 + TOP_MIN_MAX_CLOSE_Y));
titleBar.getChildren().addAll(titleBarLeft, titleBarCenter, titleBarRight);
final VBox leftBar = new VBox();
leftBar.setId("border-left");
leftBar.setPrefWidth(LEFT_BORDER_WIDTH);
leftBar.setMaxWidth(LEFT_BORDER_WIDTH);
leftBar.setTranslateX(1);
Bindings.bindBidirectional(leftBar.translateYProperty(), content.translateYProperty());
Bindings.bindBidirectional(leftBar.maxHeightProperty(), content.maxHeightProperty());
final VBox rightBar = new VBox();
rightBar.setId("border-right");
rightBar.setPrefWidth(RIGHT_BORDER_WIDTH);
rightBar.setMaxWidth(RIGHT_BORDER_WIDTH);
Bindings.bindBidirectional(rightBar.translateYProperty(), content.translateYProperty());
Bindings.bindBidirectional(rightBar.maxHeightProperty(), content.maxHeightProperty());
final HBox statusBar = new HBox();
//statusBar.setStyle("-fx-background-color: black;");
statusBar.setPrefHeight(BOTTOM_BORDER_HEIGHT);
statusBar.setMaxHeight(BOTTOM_BORDER_HEIGHT);
final Region statusBarLeft = new Region();
statusBarLeft.setId("status-bar-left");
statusBarLeft.setPrefWidth(BOTTOM_LEFT_WIDTH);
statusBarLeft.setMaxWidth(BOTTOM_LEFT_WIDTH);
final Region statusBarCenter = new Region();
statusBarCenter.setId("status-bar");
HBox.setHgrow(statusBarCenter, Priority.ALWAYS);
final HBox statusBarRight = new HBox();
statusBarRight.setAlignment(Pos.BOTTOM_RIGHT);
statusBarRight.setId("status-bar-right");
statusBarRight.setPrefWidth(BOTTOM_RIGHT_WIDTH);
statusBarRight.setMaxWidth(BOTTOM_RIGHT_WIDTH);
final WindowReziseButton windowResizeButton = new WindowReziseButton(stage, this.getMinWidth(), this.getMinHeight());
HBox.setMargin(windowResizeButton, new Insets(BOTTOM_BORDER_HEIGHT - 11, 0, 0, 0));
statusBarRight.getChildren().addAll(windowResizeButton);
statusBar.getChildren().addAll(statusBarLeft, statusBarCenter, statusBarRight);
// content adjustment
stage.widthProperty().addListener(new InvalidationListener() {
@Override
public void invalidated(Observable observable) {
content.setMaxWidth(stage.getWidth() - content.getTranslateX() - RIGHT_BORDER_WIDTH);
rightBar.setTranslateX(content.getMaxWidth() - RIGHT_BORDER_WIDTH);
}
});
stage.heightProperty().addListener(new InvalidationListener() {
@Override
public void invalidated(Observable observable) {
statusBar.setTranslateY(stage.getHeight() - BOTTOM_BORDER_HEIGHT);
content.setMaxHeight(stage.getHeight() - content.getTranslateY() - statusBar.getMaxHeight() + BOTTOM_BORDER_CONTENT_ADJUSTMENT);
}
});
content.setTranslateX(LEFT_BORDER_WIDTH);
content.setTranslateY(TOP_BORDER_HEIGHT - TOP_BORDER_CONTENT_ADJUSTMENT);
getChildren().addAll(content, leftBar, rightBar, titleBar, statusBar, logoView);
}
private HBox newMinMaxClose(final Stage stage) {
final HBox box = new HBox(4);
final java.awt.SystemTray st = java.awt.SystemTray.isSupported() ? java.awt.SystemTray.getSystemTray() : null;
if (st != null && st.getTrayIcons().length == 0) {
final String imageName = st.getTrayIconSize().width > 16 ? st.getTrayIconSize().width > 64 ? RS.IMG_LOGO_128 : RS.IMG_LOGO_64 : RS.IMG_LOGO_16;
try {
try {
final java.awt.Image image = javax.imageio.ImageIO.read(RS.stream(imageName));
final java.awt.TrayIcon trayIcon = new java.awt.TrayIcon(image);
trayIcon.setToolTip("Hello");
st.add(trayIcon);
} catch (java.io.IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//final java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().createImage(imageFileName);
} catch (java.awt.AWTException e) {
// TODO : Log error?
e.printStackTrace();
}
}
final ImageView minBtn = newTitleBarButton(RS.IMG_SKIN_MIN, 0.9, 0);
minBtn.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (st != null && st.getTrayIcons().length > 0) {
// Linux/Windows
if (stage.isShowing()) {
stage.hide();
} else {
stage.show();
}
//st.getTrayIcons()[0].displayMessage("Hey", "Hello World", java.awt.TrayIcon.MessageType.INFO);
} else {
// Mac just minimize/restore
stage.setIconified(!stage.isIconified());
}
}
});
final ImageView maxBtn = newTitleBarButton(RS.IMG_SKIN_MAX, 0.9, 0);
final Image maxImage = maxBtn.getImage();
final Image resImage = RS.img(RS.IMG_SKIN_RESTORE);
maxBtn.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
final double stageY = Utils.isMac() ? stage.getY() - 22 : stage.getY(); // TODO Workaround for RT-13980
final Screen screen = Screen.getScreensForRectangle(stage.getX(), stageY, 1, 1).get(0);
Rectangle2D bounds = screen.getVisualBounds();
if (bounds.getMinX() == stage.getX() && bounds.getMinY() == stageY &&
bounds.getWidth() == stage.getWidth() && bounds.getHeight() == stage.getHeight()) {
if (backupWindowBounds != null) {
stage.setX(backupWindowBounds.getMinX());
stage.setY(backupWindowBounds.getMinY());
stage.setWidth(backupWindowBounds.getWidth());
stage.setHeight(backupWindowBounds.getHeight());
maxBtn.setImage(maxImage);
}
} else {
backupWindowBounds = new Rectangle2D(stage.getX(), stage.getY(), stage.getWidth(), stage.getHeight());
final double newStageY = Utils.isMac() ? screen.getVisualBounds().getMinY() + 22 : screen.getVisualBounds().getMinY(); // TODO Workaround for RT-13980
stage.setX(screen.getVisualBounds().getMinX());
stage.setY(newStageY);
stage.setWidth(screen.getVisualBounds().getWidth());
stage.setHeight(screen.getVisualBounds().getHeight());
maxBtn.setImage(resImage);
}
}
});
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(final WindowEvent event) {
if (isExiting) {
stage.close();
}
event.consume();
}
});
final ImageView closeBtn = newTitleBarButton(RS.IMG_SKIN_CLOSE, 0.7, 0);
closeBtn.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (isExiting) {
return;
}
isExiting = true;
if (st != null) {
for (java.awt.TrayIcon trayIcon : st.getTrayIcons()) {
st.remove(trayIcon);
}
}
Platform.exit();
}
});
box.getChildren().addAll(minBtn, maxBtn, closeBtn);
return box;
}
private ImageView newTitleBarButton(final String imageName, final double enterBrightness, final double exitedBrightness) {
final ImageView btn = RS.imgView(imageName);
btn.setId("title-menu");
HBox.setMargin(btn, new Insets(TOP_BORDER_HEIGHT / 2 + TOP_MIN_MAX_CLOSE_ADJUSTMENT, 0, 0, 0));
final ColorAdjust btnEffect = new ColorAdjust();
//btnEffect.setContrast(enterBrightness);
btnEffect.setBrightness(exitedBrightness);
btn.setEffect(btnEffect);
btn.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
btnEffect.setBrightness(enterBrightness);
//btnEffect.setContrast(exitedBrightness);
}
});
btn.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
btnEffect.setBrightness(exitedBrightness);
//btnEffect.setContrast(enterBrightness);
}
});
return btn;
}
public class WindowReziseButton extends Region {
private double dragOffsetX, dragOffsetY;
public WindowReziseButton(final Stage stage, final double stageMinimumWidth, final double stageMinimumHeight) {
setId("window-resize-button");
setPrefSize(11, 11);
setOnMousePressed(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent e) {
final double stageY = Utils.isMac() ? stage.getY() + 22 : stage.getY(); // TODO Workaround for RT-13980
dragOffsetX = (stage.getX() + stage.getWidth()) - e.getScreenX();
dragOffsetY = (stageY + stage.getHeight()) - e.getScreenY();
e.consume();
}
});
setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent e) {
final double stageY = Utils.isMac() ? stage.getY() + 22 : stage.getY(); // TODO Workaround for RT-13980
final Screen screen = Screen.getScreensForRectangle(stage.getX(), stageY, 1, 1).get(0);
Rectangle2D visualBounds = screen.getVisualBounds();
if (Utils.isMac()) visualBounds = new Rectangle2D(visualBounds.getMinX(), visualBounds.getMinY() + 22,
visualBounds.getWidth(), visualBounds.getHeight()); // TODO Workaround for RT-13980
double maxX = Math.min(visualBounds.getMaxX(), e.getScreenX() + dragOffsetX);
double maxY = Math.min(visualBounds.getMaxY(), e.getScreenY() - dragOffsetY);
stage.setWidth(Math.max(stageMinimumWidth, maxX - stage.getX()));
stage.setHeight(Math.max(stageMinimumHeight, maxY - stageY));
e.consume();
}
});
}
}
} |
package org.yetiz.utils.hbase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.client.coprocessor.AggregationClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yetiz.utils.hbase.exception.DataSourceException;
import org.yetiz.utils.hbase.exception.UnHandledException;
import org.yetiz.utils.hbase.exception.YHBaseException;
import org.yetiz.utils.hbase.utils.CallbackTask;
import org.yetiz.utils.hbase.utils.ResultTask;
import org.yetiz.utils.hbase.utils.Task;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
public final class HBaseClient {
public static final Charset DEFAULT_CHARSET = Charset.forName("utf-8");
private static final int DEFAULT_MAX_FAST_BATCH_COUNT = 5000;
private static final int DEFAULT_MAX_ASYNC_BATCH_COUNT = 5000;
private static final ExecutorService EXECUTOR =
new ThreadPoolExecutor(0, Integer.MAX_VALUE, 5L, TimeUnit.SECONDS, new SynchronousQueue<>());
private static final AtomicLong INCREMENT_ID = new AtomicLong(0);
protected final HashMap<TableName, LinkedBlockingQueue<Row>>
fastCollection = new HashMap<>();
protected final HashMap<TableName, LinkedBlockingQueue<HAsyncTable.AsyncPackage>>
asyncCollection = new HashMap<>();
private final boolean reproducible;
private final String id = String.format("%s-%d", HBaseClient.class.getName(), INCREMENT_ID.getAndIncrement());
private final Logger logger = LoggerFactory.getLogger(id);
private volatile int fastBatchCount = DEFAULT_MAX_FAST_BATCH_COUNT - 1;
private volatile int asyncBatchCount = DEFAULT_MAX_ASYNC_BATCH_COUNT - 1;
private volatile boolean closed = false;
private Connection connection;
private Configuration configuration = HBaseConfiguration.create();
private HBaseClient(boolean reproducible) {
this.reproducible = reproducible;
}
public static final byte[] bytes(String string) {
return string.getBytes(DEFAULT_CHARSET);
}
/**
* Only for Get, Put, Delete, Append, Increment.<br>
* With callback
*
* @return <code>Async</code>
*/
public HAsyncTable async(TableName tableName) {
return new HAsyncTable(asyncQueue(tableName));
}
/**
* Only for Get, Put, Delete, Append, Increment.<br>
* No callback, this is faster then <code>async()</code>
*
* @return <code>Fast</code>
*/
public HFastTable fast(TableName tableName) {
return new HFastTable(fastQueue(tableName));
}
public HFastTable fast(Class<? extends HTableModel> model) {
return new HFastTable(fastQueue(HTableModel.tableName(model)));
}
public HFastTable fast(HTableModel model) {
return new HFastTable(fastQueue(model.tableName()));
}
public int fastBatchCount() {
return fastBatchCount;
}
public HBaseClient setFastBatchCount(int fastBatchCount) {
this.fastBatchCount = fastBatchCount - 1;
return this;
}
public int asyncBatchCount() {
return asyncBatchCount;
}
public HBaseClient setAsyncBatchCount(int asyncBatchCount) {
this.asyncBatchCount = asyncBatchCount - 1;
return this;
}
private void init() {
this.connection = newConnection();
}
private Connection newConnection() {
try {
Connection connection = ConnectionFactory.createConnection(configuration);
return connection;
} catch (Exception e) {
throw new DataSourceException(e);
}
}
public HBaseAdmin admin() {
try {
return new HBaseAdmin(connection.getAdmin());
} catch (Exception e) {
throw new DataSourceException(e);
}
}
public void close() {
logger.debug("Close " + id());
this.closed = true;
try {
EXECUTOR.shutdown();
while (!EXECUTOR.awaitTermination(1, TimeUnit.SECONDS)) ;
} catch (InterruptedException e) {
}
logger.debug(id() + " Closed");
}
private String id() {
return id;
}
public boolean closed() {
return this.closed;
}
private void fastLoopTask(TableName tableName, LinkedBlockingQueue<Row> fastQueue, boolean isMaster) {
List<Row> rows = new ArrayList<>();
while (!closed()) {
try {
Row row = fastQueue.poll(1, TimeUnit.SECONDS);
if (row == null) {
if (!isMaster) {
break;
}
continue;
}
rows.add(row);
if (fastQueue.drainTo(rows, fastBatchCount()) == fastBatchCount() && reproducible) {
EXECUTOR.execute(() -> fastLoopTask(tableName, fastQueue, false));
}
Object[] results = new Object[rows.size()];
HBaseTable table = null;
try {
table = table(tableName);
table.batch(rows, results);
} catch (Throwable throwable) {
throw convertedException(throwable);
} finally {
if (table != null) {
table.close();
}
}
} catch (Throwable throwable) {
}
if (!isMaster) {
break;
}
rows = new ArrayList<>();
}
}
protected LinkedBlockingQueue<Row> fastQueue(TableName tableName) {
if (!fastCollection.containsKey(tableName)) {
synchronized (fastCollection) {
if (!fastCollection.containsKey(tableName)) {
LinkedBlockingQueue<Row> fastQueue = new LinkedBlockingQueue<>();
fastCollection.put(tableName, fastQueue);
EXECUTOR.execute(() -> fastLoopTask(tableName, fastQueue, true));
}
}
}
return fastCollection.get(tableName);
}
private void asyncLoopTask(TableName tableName,
LinkedBlockingQueue<HAsyncTable.AsyncPackage> asyncQueue,
boolean isMaster) {
List<HAsyncTable.AsyncPackage> packages = new ArrayList<>();
while (!closed()) {
try {
HAsyncTable.AsyncPackage aPackage = asyncQueue.poll(1, TimeUnit.SECONDS);
if (aPackage == null) {
if (!isMaster) {
break;
}
continue;
}
packages.add(aPackage);
if (asyncQueue.drainTo(packages, asyncBatchCount()) == asyncBatchCount() && reproducible) {
EXECUTOR.execute(() -> asyncLoopTask(tableName, asyncQueue, false));
}
List<Row> rows = new ArrayList<>();
packages.stream()
.forEach(asyncPackage -> rows.add(asyncPackage.action));
Object[] results = new Object[packages.size()];
HAsyncTable.AsyncPackage[] packageArray = new HAsyncTable.AsyncPackage[packages.size()];
packages.toArray(packageArray);
HBaseTable table = null;
try {
table = table(tableName);
table.batch(rows, results);
} catch (Throwable throwable) {
throw convertedException(throwable);
} finally {
if (table != null) {
table.close();
}
}
HashMap<HAsyncTable.AsyncPackage, Object> invokes = new HashMap<>();
for (int i = 0; i < results.length; i++) {
invokes.put(packageArray[i], results[i]);
}
invokes.entrySet()
.parallelStream()
.forEach(entry -> {
Task task = entry.getKey().callback;
if (task == null) {
return;
}
if (task instanceof ResultTask) {
((ResultTask) task).callback(((Result) entry.getValue()));
}
if (task instanceof CallbackTask) {
((CallbackTask) task).callback();
}
});
} catch (Throwable throwable) {
}
if (!isMaster) {
break;
}
}
}
protected LinkedBlockingQueue<HAsyncTable.AsyncPackage> asyncQueue(TableName tableName) {
if (!asyncCollection.containsKey(tableName)) {
synchronized (asyncCollection) {
if (!asyncCollection.containsKey(tableName)) {
LinkedBlockingQueue<HAsyncTable.AsyncPackage> asyncQueue = new LinkedBlockingQueue<>();
asyncCollection.put(tableName, asyncQueue);
EXECUTOR.execute(() -> asyncLoopTask(tableName, asyncQueue, true));
}
}
}
return asyncCollection.get(tableName);
}
public HBaseTable table(HTableModel model) {
return table(model.tableName());
}
public HBaseTable table(TableName tableName) {
try {
return new HBaseTable(tableName,
connection().getTable(tableName.get()));
} catch (Throwable throwable) {
throw convertedException(throwable);
}
}
protected Connection connection() {
return connection;
}
private YHBaseException convertedException(Throwable throwable) {
if (throwable instanceof YHBaseException) {
return (YHBaseException) throwable;
} else {
return new UnHandledException(throwable);
}
}
public HBaseTable table(Class<? extends HTableModel> modelClass) {
return table(HTableModel.tableName(modelClass));
}
public long rowCount(TableName tableName, byte[] family) {
AggregationClient aggregationClient = new AggregationClient(configuration());
Scan scan = new Scan();
scan.addFamily(family);
long count = 0;
try {
count = aggregationClient.rowCount(tableName.get(), null, scan);
} catch (Throwable e) {
}
return count;
}
public Configuration configuration() {
return configuration;
}
public static class Parameter {
public static final Parameter ZK_QUORUM =
new Parameter(HConstants.ZOOKEEPER_QUORUM);
public static final Parameter ZK_PROPERTY_CLIENT_PORT =
new Parameter(HConstants.ZOOKEEPER_CLIENT_PORT);
public static final Parameter CLIENT_SCANNER_CACHING =
new Parameter(HConstants.HBASE_CLIENT_SCANNER_CACHING);
public static final Parameter RPC_TIMEOUT =
new Parameter(HConstants.HBASE_RPC_TIMEOUT_KEY);
public static final Parameter ZK_SESSION_TIMEOUT =
new Parameter(HConstants.ZK_SESSION_TIMEOUT);
private String name;
private Parameter(String name) {
this.name = name;
}
public String name() {
return name;
}
}
public static class Builder {
private HBaseClient hBaseClient;
public static final Builder create() {
return create(true);
}
/**
* @param reproducible reproduce worker when fast or async worker is busy.
* @return
*/
public static final Builder create(boolean reproducible) {
Builder builder = new Builder();
builder.hBaseClient = new HBaseClient(reproducible);
return builder;
}
public final Builder configuration(Configuration configuration) {
hBaseClient.configuration = configuration;
return this;
}
public final Builder set(Parameter key, String value) {
hBaseClient.configuration.set(key.name(), value);
return this;
}
public final Builder setLong(Parameter key, Long value) {
hBaseClient.configuration.setLong(key.name(), value);
return this;
}
public final HBaseClient build() {
hBaseClient.init();
return hBaseClient;
}
}
} |
package imj3.draft.processing;
import static imj3.draft.segmentation.CommonSwingTools.item;
import static imj3.draft.segmentation.CommonSwingTools.showEditDialog;
import static net.sourceforge.aprog.swing.SwingTools.horizontalSplit;
import static net.sourceforge.aprog.swing.SwingTools.scrollable;
import static net.sourceforge.aprog.tools.Tools.cast;
import static net.sourceforge.aprog.tools.Tools.unchecked;
import imj2.pixel3d.MouseHandler;
import imj3.draft.segmentation.CommonTools.Property;
import imj3.draft.segmentation.ImageComponent;
import imj3.tools.AwtImage2D;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.prefs.Preferences;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSplitPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import net.sourceforge.aprog.swing.SwingTools;
import net.sourceforge.aprog.tools.IllegalInstantiationException;
import net.sourceforge.aprog.tools.Tools;
/**
* @author codistmonk (creation 2015-02-13)
*/
public final class VisualAnalysis {
private VisualAnalysis() {
throw new IllegalInstantiationException();
}
static final Preferences preferences = Preferences.userNodeForPackage(VisualAnalysis.class);
public static final String IMAGE_FILE_PATH = "image.file.path";
/**
* @param commandLineArguments
* <br>Unused
*/
public static final void main(final String[] commandLineArguments) {
SwingTools.useSystemLookAndFeel();
final Context context = new Context();
SwingUtilities.invokeLater(new Runnable() {
@Override
public final void run() {
SwingTools.show(new MainPanel(context), VisualAnalysis.class.getSimpleName(), false);
context.setImageFile(new File(preferences.get(IMAGE_FILE_PATH, "")));
}
});
}
/**
* @author codistmonk (creation 2015-02-13)
*/
public static final class MainPanel extends JPanel {
private final JTree tree;
private final JSplitPane mainSplitPane;
public MainPanel(final Context context) {
super(new BorderLayout());
this.tree = new JTree();
this.mainSplitPane = horizontalSplit(scrollable(this.tree), scrollable(new JLabel("Drop file here")));
setModel(this.tree, context.setSession(new Session()).getSession(), "Session");
final JToolBar toolBar = new JToolBar();
toolBar.add(new JLabel("TODO"));
this.add(toolBar, BorderLayout.NORTH);
this.add(this.mainSplitPane, BorderLayout.CENTER);
this.mainSplitPane.getRightComponent().setDropTarget(new DropTarget() {
@Override
public final synchronized void drop(final DropTargetDropEvent event) {
final File file = SwingTools.getFiles(event).get(0);
context.setImageFile(file);
preferences.put(IMAGE_FILE_PATH, file.getPath());
}
/**
* {@value}.
*/
private static final long serialVersionUID = 5442000733451223725L;
});
this.setPreferredSize(new Dimension(800, 600));
context.setMainPanel(this);
}
public final void setContents(final Component component) {
this.mainSplitPane.setRightComponent(scrollable(component));
}
private static final long serialVersionUID = 2173077945563031333L;
}
/**
* @author codistmonk (creation 2015-02-16)
*/
public static final class UIScaffold implements Serializable {
private final Object object;
private final Method[] stringGetter;
private final Map<String, Method> propertyGetters;
private final Map<String, Method> propertySetters;
private final List<Method> inlineLists;
private final Map<String, Method> nestedLists;
public UIScaffold(final Object object) {
this.object = object;
this.stringGetter = new Method[1];
this.propertyGetters = new LinkedHashMap<>();
this.propertySetters = new LinkedHashMap<>();
this.inlineLists = new ArrayList<>();
this.nestedLists = new LinkedHashMap<>();
for (final Method method : object.getClass().getMethods()) {
for (final Annotation annotation : method.getAnnotations()) {
final StringGetter stringGetter0 = cast(StringGetter.class, annotation);
final PropertyGetter propertyGetter = cast(PropertyGetter.class, annotation);
final PropertySetter propertySetter = cast(PropertySetter.class, annotation);
final InlineList inlineList = cast(InlineList.class, annotation);
final NestedList nestedList = cast(NestedList.class, annotation);
if (stringGetter0 != null) {
this.stringGetter[0] = method;
}
if (propertyGetter != null) {
this.propertyGetters.put(propertyGetter.value(), method);
}
if (propertySetter != null) {
this.propertySetters.put(propertySetter.value(), method);
}
if (inlineList != null) {
this.inlineLists.add(method);
}
if (nestedList != null) {
this.nestedLists.put(nestedList.name(), method);
}
}
}
}
public final Object getObject() {
return this.object;
}
public final Method getStringGetter() {
return this.stringGetter[0];
}
public final Map<String, Method> getPropertyGetters() {
return this.propertyGetters;
}
public final Map<String, Method> getPropertySetters() {
return this.propertySetters;
}
public final List<Method> getInlineLists() {
return this.inlineLists;
}
public final Map<String, Method> getNestedLists() {
return this.nestedLists;
}
public final void edit(final String title, final Runnable actionIfOk) {
final List<Property> properties = new ArrayList<>();
for (final Map.Entry<String, Method> entry : this.getPropertyGetters().entrySet()) {
final Method setter = this.getPropertySetters().get(entry.getKey());
if (setter != null) {
properties.add(new Property(entry.getKey(), () -> {
try {
return entry.getValue().invoke(this.getObject());
} catch (final Exception exception) {
throw unchecked(exception);
}
}, string -> {
try {
return setter.invoke(this.getObject(), string);
} catch (final Exception exception) {
throw unchecked(exception);
}
}));
}
}
showEditDialog(title, actionIfOk, properties.toArray(new Property[properties.size()]));
}
private static final long serialVersionUID = -5160722477511458349L;
}
public static final <T> T newInstanceOf(final Class<T> cls) {
try {
return cls.newInstance();
} catch (final Exception exception) {
throw unchecked(exception);
}
}
public static final void setModel(final JTree tree, final Object object, final String rootEdtiTitle) {
final DefaultMutableTreeNode root = new DefaultMutableTreeNode();
final DefaultTreeModel model = new DefaultTreeModel(root);
final UIScaffold scaffold = new UIScaffold(object);
tree.setModel(model);
if (scaffold.getStringGetter() != null) {
final TreePath path = new TreePath(model.getPathToRoot(root));
model.valueForPathChanged(path, new UserObject(scaffold, rootEdtiTitle, tree, root));
}
for (final Map.Entry<String, Method> entry : scaffold.getNestedLists().entrySet()) {
model.insertNodeInto(new DefaultMutableTreeNode(entry.getKey()), root, model.getChildCount(root));
}
new MouseHandler(null) {
@Override
public final void mouseClicked(final MouseEvent event) {
this.mouseUsed(event);
}
@Override
public final void mousePressed(final MouseEvent event) {
this.mouseUsed(event);
}
@Override
public final void mouseReleased(final MouseEvent event) {
this.mouseUsed(event);
}
private final void mouseUsed(final MouseEvent event) {
if (event.isPopupTrigger()) {
final TreePath path = tree.getPathForLocation(event.getX(), event.getY());
final Editable editable = path == null ? null : cast(Editable.class, ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject());
if (editable != null) {
final JPopupMenu popup = new JPopupMenu();
popup.add(item("Edit...", e -> editable.edit()));
for (final Method inlineList : scaffold.getInlineLists()) {
final InlineList annotation = inlineList.getAnnotation(InlineList.class);
this.addListItem(popup, tree, root, annotation.element(), annotation.elementClass());
}
{
int i = -1;
for (final Map.Entry<String, Method> entry : scaffold.getNestedLists().entrySet()) {
final MutableTreeNode nestingNode = (MutableTreeNode) model.getChild(root, ++i);
final NestedList annotation = entry.getValue().getAnnotation(NestedList.class);
this.addListItem(popup, tree, nestingNode, annotation.element(), annotation.elementClass());
}
}
popup.show(tree, event.getX(), event.getY());
}
}
}
final void addListItem(final JPopupMenu popup, final JTree tree, final MutableTreeNode nestingNode, final String element, final Class<?> elementClass) {
final DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
popup.add(item("Add " + element + "...", e -> {
final UIScaffold newElementScaffold = new UIScaffold(newInstanceOf(elementClass));
newElementScaffold.edit("New " + element, new Runnable() {
@Override
public final void run() {
final DefaultMutableTreeNode newElementNode = new DefaultMutableTreeNode();
newElementNode.setUserObject(new UserObject(newElementScaffold, element, tree, newElementNode));
model.insertNodeInto(newElementNode, nestingNode, model.getChildCount(nestingNode));
}
});
}));
}
private static final long serialVersionUID = -475200304537897055L;
}.addTo(tree);
}
/**
* @author codistmonk (creation 2015-02-17)
*/
public static final class UserObject implements Editable {
private final UIScaffold uiScaffold;
private final String editTitle;
private final Runnable afterEdit;
public UserObject(final UIScaffold uiScaffold, final String editTitle, final JTree tree, final TreeNode node) {
this.uiScaffold = uiScaffold;
this.editTitle = editTitle;
final DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
final TreePath path = new TreePath(model.getPathToRoot(node));
this.afterEdit = new Runnable() {
@Override
public final void run() {
model.valueForPathChanged(path, UserObject.this);
tree.getRootPane().validate();
}
};
}
@Override
public final void edit() {
this.uiScaffold.edit(this.editTitle, this.afterEdit);
}
@Override
public final String toString() {
try {
return (String) this.uiScaffold.getStringGetter().invoke(this.uiScaffold.getObject());
} catch (final Exception exception) {
throw Tools.unchecked(exception);
}
}
private static final long serialVersionUID = 7406734693107943367L;
}
/**
* @author codistmonk (creation 2015-02-16)
*/
public static abstract interface Editable extends Serializable {
public abstract void edit();
}
/**
* @author codistmonk (creation 2015-02-13)
*/
public static final class Context implements Serializable {
private MainPanel mainPanel;
private Session session;
private File imageFile;
public final MainPanel getMainPanel() {
return this.mainPanel;
}
public final void setMainPanel(final MainPanel mainPanel) {
this.mainPanel = mainPanel;
}
public final Session getSession() {
return this.session;
}
public final Context setSession(final Session session) {
this.session = session;
return this;
}
public final File getImageFile() {
return this.imageFile;
}
public final void setImageFile(final File imageFile) {
if (imageFile.isFile()) {
this.getMainPanel().setContents(new ImageComponent(AwtImage2D.awtRead(imageFile.getPath())));
this.imageFile = imageFile;
}
}
private static final long serialVersionUID = -2487965125442868238L;
}
/**
* @author codistmonk (creation 2015-02-16)
*/
public static final class Session implements Serializable {
private String name = "session";
private final List<ClassDescription> classDescriptions = new ArrayList<>();
@StringGetter
@PropertyGetter("name")
public final String getName() {
return this.name;
}
@PropertySetter("name")
public final Session setName(final String name) {
this.name = name;
return this;
}
@NestedList(name="classes", element="class", elementClass=ClassDescription.class)
public final List<ClassDescription> getClassDescriptions() {
return this.classDescriptions;
}
private static final long serialVersionUID = -4539259556658072410L;
/**
* @author codistmonk (creation 2015-02-16)
*/
public static final class ClassDescription implements Serializable {
private String name = "class";
private int label = 0xFF000000;
@StringGetter
@PropertyGetter("name")
public final String getName() {
return this.name;
}
@PropertySetter("name")
public final ClassDescription setName(final String name) {
this.name = name;
return this;
}
public final int getLabel() {
return this.label;
}
public final ClassDescription setLabel(final int label) {
this.label = label;
return this;
}
@PropertyGetter("label")
public final String getLabelAsString() {
return "#" + Integer.toHexString(this.getLabel()).toUpperCase(Locale.ENGLISH);
}
@PropertySetter("label")
public final ClassDescription setLabel(final String labelAsString) {
return this.setLabel((int) Long.parseLong(labelAsString.substring(1), 16));
}
private static final long serialVersionUID = 4974707407567297906L;
}
}
/**
* @author codistmonk (creation 2015-02-16)
*/
@Retention(RetentionPolicy.RUNTIME)
public static abstract @interface StringGetter {
}
/**
* @author codistmonk (creation 2015-02-16)
*/
@Retention(RetentionPolicy.RUNTIME)
public static abstract @interface PropertyGetter {
public abstract String value();
}
/**
* @author codistmonk (creation 2015-02-16)
*/
@Retention(RetentionPolicy.RUNTIME)
public static abstract @interface PropertySetter {
public abstract String value();
}
/**
* @author codistmonk (creation 2015-02-16)
*/
@Retention(RetentionPolicy.RUNTIME)
public static abstract @interface InlineList {
public abstract String element();
public abstract Class<?> elementClass();
}
/**
* @author codistmonk (creation 2015-02-16)
*/
@Retention(RetentionPolicy.RUNTIME)
public static abstract @interface NestedList {
public abstract String name();
public abstract String element();
public abstract Class<?> elementClass();
}
} |
package pt.davidafsilva.shb;
import com.eclipsesource.json.JsonObject;
import java.util.Arrays;
import java.util.Base64;
import java.util.Optional;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.core.net.JksOptions;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
/**
* The hello-back service for slack
*
* @author David Silva
*/
public class HelloVerticle extends AbstractVerticle {
// the logger
private static final Logger LOGGER = LoggerFactory.getLogger(HelloVerticle.class);
// the hello text response format
private static final String HELLO_RESPONSE_FORMAT = "Hello, <@%s|%s> :sunglasses:";
// the http server
private HttpServer server;
@Override
public void start(final Future<Void> startFuture) throws Exception {
// override the configuration with ENV variables, if available
overrideConfigurationWithEnv();
// create the routing configuration
final Router router = Router.router(vertx);
// default handler
router.route().handler(BodyHandler.create());
// POST /hello
router.post("/hello")
.produces("application/json")
.handler(this::helloRequest);
// validate the configuration
if (!validateOptions(startFuture, "keystore_file", "keystore_pass")) {
return;
}
// the http server options
final JksOptions jksOptions = new JksOptions()
.setPassword(config().getString("keystore_pass"));
if (config().containsKey("keystore_contents")) {
jksOptions.setValue(Buffer.buffer(Base64.getDecoder().decode(
config().getString("keystore_contents"))));
} else {
jksOptions.setPath(config().getString("keystore_file"));
}
final HttpServerOptions options = new HttpServerOptions()
.setPort(config().getInteger("http_port", 8443))
.setSsl(true)
.setKeyStoreOptions(jksOptions);
// create the actual http server
server = vertx.createHttpServer(options)
.requestHandler(router::accept)
.listen(deployedHandler -> {
if (deployedHandler.succeeded()) {
LOGGER.info(String.format("http server listening at port %s", options.getPort()));
startFuture.complete();
} else {
throw new IllegalStateException("unable to start http server", deployedHandler.cause());
}
});
}
/**
* Override the {@link #config()} definition with the available SHB environment variables.
*/
private void overrideConfigurationWithEnv() {
Optional.ofNullable(System.getenv("SHB_KEYSTORE_FILE"))
.ifPresent(p -> config().put("keystore_file", p));
Optional.ofNullable(System.getenv("SHB_KEYSTORE_CONTENTS"))
.ifPresent(p -> config().put("keystore_contents", p));
Optional.ofNullable(System.getenv("SHB_KEYSTORE_PASS"))
.ifPresent(p -> config().put("keystore_pass", p));
Optional.ofNullable(System.getenv("SHB_HTTP_PORT"))
.ifPresent(p -> config().put("http_port", Integer.valueOf(p)));
}
@Override
public void stop() throws Exception {
server.close();
}
/**
* Validates the options for runtime and if there are missing options, fails the start of this
* verticle.
*
* @param startFuture the start future for startup abortion
* @param required the required properties
* @return {@code true} if the options are correct, {@code false} otherwise.
*/
private boolean validateOptions(final Future<Void> startFuture, final String... required) {
final String[] missing = Arrays.stream(required)
.filter(prop -> !config().containsKey(prop))
.toArray(String[]::new);
if (missing.length > 0) {
startFuture.fail("some required properties are missing: " + Arrays.toString(missing));
return false;
}
return true;
}
/**
* Handles the incoming hello requests
*
* @param context the routing context of the request
*/
private void helloRequest(final RoutingContext context) {
LOGGER.info("handling request..");
// create the request data from the POST request
final Optional<SlackRequest> slackRequest = SlackRequest.parse(context);
LOGGER.info("request data: " + slackRequest);
// validate the request
if (!slackRequest.isPresent()) {
context.response().setStatusCode(400).end();
} else {
final SlackRequest request = slackRequest.get();
final JsonObject response = new JsonObject()
.add("text", String.format(HELLO_RESPONSE_FORMAT,
request.getUserId(), request.getUserName()));
// send the response back to the channel
context.response().setStatusCode(200)
.end(response.toString());
}
}
} |
package com.gildedrose;
class GildedRose {
Item[] items;
public GildedRose(Item[] items) {
this.items = items;
}
public void updateQuality() {
for (int i = 0; i < items.length; i++) {
if (!items[i].name.equals("Aged Brie")
&& !items[i].name.equals("Backstage passes to a TAFKAL80ETC concert")) {
if (items[i].quality > 0) {
if (!items[i].name.equals("Sulfuras, Hand of Ragnaros")) {
items[i].quality = items[i].quality - 1;
}
}
} else {
if (items[i].quality < 50) {
items[i].quality = items[i].quality + 1;
if (items[i].name.equals("Backstage passes to a TAFKAL80ETC concert")) {
if (items[i].sellIn < 11) {
if (items[i].quality < 50) {
items[i].quality = items[i].quality + 1;
}
}
if (items[i].sellIn < 6) {
if (items[i].quality < 50) {
items[i].quality = items[i].quality + 1;
}
}
}
}
}
if (!items[i].name.equals("Sulfuras, Hand of Ragnaros")) {
items[i].sellIn = items[i].sellIn - 1;
}
if (items[i].sellIn < 0) {
if (!items[i].name.equals("Aged Brie")) {
if (!items[i].name.equals("Backstage passes to a TAFKAL80ETC concert")) {
if (items[i].quality > 0) {
if (!items[i].name.equals("Sulfuras, Hand of Ragnaros")) {
items[i].quality = items[i].quality - 1;
}
}
} else {
items[i].quality = items[i].quality - items[i].quality;
}
} else {
if (items[i].quality < 50) {
items[i].quality = items[i].quality + 1;
}
}
}
}
}
} |
package seedu.address.model.task;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.joestelmach.natty.Parser;
import seedu.address.commons.exceptions.IllegalValueException;
/**
* Represents a Task's Date and Time in the to-do-list. Guarantees: immutable;
*
*/
public class Datetime {
public static final String MESSAGE_DATETIME_CONSTRAINTS = "Date can be DD-MM-YYYY and Time can be 24h format";
public static final String MESSAGE_DATETIME_CONTAINS_DOTS = "Date should be in MM-DD-YYYY format and cannot contain '.' character";
public static final String MESSAGE_DATE_CONSTRAINTS = "Date should be in DD-MM-YYYY format";
public static final String DATE_INCORRECT_REGEX = ".*" + "(0?[1-9]|[12][0-9]|3[01])" + "\\."
+ "(0?[1-9]|1[012])" + "\\." + "\\d{2}(\\{2}){0,1}" + ".*";
public static final Pattern DATE_CORRECT_REGEX = Pattern.compile(".*" + "(?<day>(0?[1-9]|[12][0-9]|3[01]))" + "-"
+ "(?<month>(0?[1-9]|1[012]))" + "-" + "(?<year>\\d{2}(\\{2}){0,1})" + ".*");
//public static final String MESSAGE_TIME_CONSTRAINTS = "Time should be in 24hr format. Eg. 2359";
// public static final String TIME_VALIDATION_REGEX = "([01]?[0-9]|2[0-3])[0-5][0-9]";
private Date start;
private Date end;
public Datetime(String input) throws IllegalValueException {
Parser natty = initNatty();
List<Date> listOfDate;
// 'date/' not found -> floating task
if (input == null) {
listOfDate = null;
}
// check input for '.' characters in date
else if (input.matches(DATE_INCORRECT_REGEX)){
throw new IllegalValueException(MESSAGE_DATETIME_CONTAINS_DOTS);
}
// empty string preceding "date/" -> convert deadline or event to floating task
else if (input.equals("")) {
listOfDate = null;
}
// natty returns non-empty list if input is parse-able
else if (!natty.parse(input).isEmpty()) {
// rearrange DD-MM-YY to parse-able MM-DD-YY
final Matcher matcher = DATE_CORRECT_REGEX.matcher(input.trim());
if (matcher.matches()){
input = matcher.group("month") + "-" + matcher.group("day") + "-" + matcher.group("year");
}
listOfDate = natty.parse(input).get(0).getDates();
}
// natty returns empty list if input is not parse-able
else {
throw new IllegalValueException(MESSAGE_DATETIME_CONSTRAINTS);
}
//floating task
if (listOfDate == null) {
start = null;
end = null;
}
//deadline task
else if (listOfDate.size() == 1){
// date and time were specified
if (listOfDate.get(0).getSeconds() == 0){
start = listOfDate.get(0);
end = null;
}
// only date was specified; default time will be set to 23:59
else{
Date newDate = listOfDate.get(0);
newDate.setHours(23);
newDate.setMinutes(59);
newDate.setSeconds(0);
start = newDate;
end = null;
}
}
//event task
else if (listOfDate.size() == 2){
if (listOfDate.get(0).before(listOfDate.get(1))) { // check that start date is before end date
start = listOfDate.get(0);
end = listOfDate.get(1);
}
else {
throw new IllegalValueException(MESSAGE_DATETIME_CONSTRAINTS);
}
}
//wrong number of date elements -> wrong inputs
else {
throw new IllegalValueException(MESSAGE_DATETIME_CONSTRAINTS);
}
}
/**
* Initialises Natty with the current time zone.
* @return Natty's date parser
*/
private Parser initNatty() {
TimeZone tz = TimeZone.getDefault();
Parser natty = new Parser(tz);
return natty;
}
/**
* Returns if a given string is a valid task date.
*/
/* public static boolean isValidDate(String test) {
return test.equals("") || test.matches(DATE_VALIDATION_REGEX);
}*/
@Override
public String toString() {
if (end != null){ //event
return processDate(start) + " to " + processDate(end);
}
else if (start != null){ //deadline
return processDate(start);
}
else { //floating task
return "";
}
}
/*
* Returns DD-MMM-YYYY HH:MM
*/
private String processDate(Date date){
return getDate(date) + " " + getTime(date);
}
/**
* @param Date date
* @return String representation of Date in DD-MMM-YYYY
*/
private String getDate(Date date){
String[] split = date.toString().split(" ");
String toReturn = split[2] + "-" + split[1]
+ "-" + split[5];
return toReturn;
}
/**
* @param date
* @return String representation Date in HH:MM
*/
private String getTime(Date date){
String[] split = date.toString().split(" ");
return split[3].substring(0, 5);
}
/**
*
* @return event: DD-MMM-YYYY to DD-MMM-YYYY
* || deadline: DD-MMM-YYYY
* || floating: ""
*/
public String getDateString() {
if (end != null){ //event
//Starts and end on same day
if (getDate(start).equals(getDate(end))){
return getDate(start);
}
else {
return getDate(start) + " to " + getDate(end);
}
}
else if (start != null){ //deadline
return getDate(start);
}
else { //floating task
return "";
}
}
/**
*
* @return event: HH:MM to HH:MM
* || deadline: HH:MM
* || floating: ""
*/
public String getTimeString() {
if (end != null){ //event
return getTime(start) + " to " + getTime(end);
}
else if (start != null){ //deadline
return getTime(start);
}
else { //floating task
return "";
}
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Datetime // instanceof handles nulls
&& this.toString().equals(((Datetime) other).toString()));
}
@Override
public int hashCode() {
if (end != null){ //event
return Objects.hash(start, end);
}
else if (start != null){ //deadline
return Objects.hash(start);
}
else { //floating task
return Objects.hash("");
}
}
public Date getStart() {
return start;
}
public Date getEnd() {
return end;
}
} |
package com.javarush.test;
public class Solution
{
public static void main(String[] args) throws Exception
{
SimpleObject<String> stringObject = new StringObject<Object>();
}
interface SimpleObject<T>
{
SimpleObject<T> getInstance();
}
} |
package seedu.ezdo.storage;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import seedu.ezdo.commons.exceptions.IllegalValueException;
import seedu.ezdo.model.tag.Tag;
import seedu.ezdo.model.tag.UniqueTagList;
import seedu.ezdo.model.todo.DueDate;
import seedu.ezdo.model.todo.Email;
import seedu.ezdo.model.todo.Name;
import seedu.ezdo.model.todo.Priority;
import seedu.ezdo.model.todo.ReadOnlyTask;
import seedu.ezdo.model.todo.StartDate;
import seedu.ezdo.model.todo.Task;
/**
* JAXB-friendly version of the Task.
*/
public class XmlAdaptedTask {
@XmlElement(required = true)
private String name;
@XmlElement(required = true)
private String priority;
@XmlElement(required = true)
private String email;
@XmlElement(required = true)
private String startDate;
@XmlElement(required = true)
private String dueDate;
@XmlElement
private List<XmlAdaptedTag> tagged = new ArrayList<>();
/**
* Constructs an XmlAdaptedTask.
* This is the no-arg constructor that is required by JAXB.
*/
public XmlAdaptedTask() {}
/**
* Converts a given Task into this class for JAXB use.
*
* @param source future changes to this will not affect the created XmlAdaptedTask
*/
public XmlAdaptedTask(ReadOnlyTask source) {
name = source.getName().fullName;
priority = source.getPriority().value;
email = source.getEmail().value;
startDate = source.getStartDate().value;
dueDate = source.getDueDate().value;
tagged = new ArrayList<>();
for (Tag tag : source.getTags()) {
tagged.add(new XmlAdaptedTag(tag));
}
}
public Task toModelType() throws IllegalValueException {
final List<Tag> taskTags = new ArrayList<>();
for (XmlAdaptedTag tag : tagged) {
taskTags.add(tag.toModelType());
}
final Name name = new Name(this.name);
final Priority priority = new Priority(this.priority);
final Email email = new Email(this.email);
final StartDate startDate = new StartDate(this.startDate);
final DueDate dueDate = new DueDate(this.dueDate);
final UniqueTagList tags = new UniqueTagList(taskTags);
return new Task(name, priority, email, startDate, dueDate, tags);
}
} |
package seedu.mypotato.model;
import java.util.Set;
import java.util.Stack;
import java.util.logging.Logger;
import com.google.common.eventbus.Subscribe;
import javafx.collections.transformation.FilteredList;
import seedu.mypotato.commons.core.ComponentManager;
import seedu.mypotato.commons.core.Config;
import seedu.mypotato.commons.core.LogsCenter;
import seedu.mypotato.commons.core.UnmodifiableObservableList;
import seedu.mypotato.commons.events.model.AddressBookChangedEvent;
import seedu.mypotato.commons.events.model.ReadFirstTaskEvent;
import seedu.mypotato.commons.events.storage.ChangedFileLocationRequestEvent;
import seedu.mypotato.commons.events.ui.LoadFirstTaskEvent;
import seedu.mypotato.commons.events.ui.UpdateStatusBarFooterEvent;
import seedu.mypotato.commons.events.ui.UpdateUiTaskDescriptionEvent;
import seedu.mypotato.commons.util.CollectionUtil;
import seedu.mypotato.model.tag.UniqueTagList.DuplicateTagException;
import seedu.mypotato.model.task.ReadOnlyTask;
import seedu.mypotato.model.task.Task;
import seedu.mypotato.model.task.UniqueTaskList;
import seedu.mypotato.model.task.UniqueTaskList.DuplicateTaskException;
import seedu.mypotato.model.task.UniqueTaskList.TaskNotFoundException;
/**
* Represents the in-memory model of the address book data. All changes to any
* model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private final AddressBook taskManager;
private final FilteredList<ReadOnlyTask> filteredTasks;
private String currentList;
private final Stack<String> stackOfUndo;
private final Stack<ReadOnlyTask> stackOfDeletedTasksAdd;
private final Stack<ReadOnlyTask> stackOfDeletedTasks;
private final Stack<Integer> stackOfDeletedTaskIndex;
private final Stack<ReadOnlyTask> stackOfOldTask;
private final Stack<ReadOnlyTask> stackOfCurrentTask;
private final Stack<ReadOnlyAddressBook> stackOfMyPotato;
private Config config;
/**
* Initializes a ModelManager with the given addressBook and userPrefs.
*
* @throws DuplicateTaskException
* @throws DuplicateTagException
*/
public ModelManager(ReadOnlyAddressBook addressBook, UserPrefs userPrefs, Config config)
throws DuplicateTagException, DuplicateTaskException {
super();
assert !CollectionUtil.isAnyNull(addressBook, userPrefs);
stackOfUndo = new Stack<>();
stackOfDeletedTasksAdd = new Stack<>();
stackOfDeletedTasks = new Stack<>();
stackOfDeletedTaskIndex = new Stack<>();
stackOfMyPotato = new Stack<>();
stackOfOldTask = new Stack<>();
stackOfCurrentTask = new Stack<>();
this.config = config;
logger.fine("Initializing with address book: " + addressBook + " and user prefs " + userPrefs);
this.taskManager = new AddressBook(addressBook);
filteredTasks = new FilteredList<>(this.taskManager.getTaskList());
this.currentList = "all";
}
public ModelManager() throws DuplicateTagException, DuplicateTaskException {
this(new AddressBook(), new UserPrefs(), new Config());
}
//@@author A0125221Y
@Override
public void resetData(ReadOnlyAddressBook newData) {
stackOfMyPotato.push(new AddressBook(taskManager));
taskManager.resetData(newData);
indicateAddressBookChanged();
}
@Override
public synchronized void revertData() {
resetData(this.stackOfMyPotato.pop());
// AddressBook.revertEmptyAddressBook(stackOfMyPotato.pop());
indicateAddressBookChanged();
}
//@@author
@Override
public Config getConfig() {
return config;
}
@Override
public ReadOnlyAddressBook getAddressBook() {
return taskManager;
}
/** Raises an event to indicate the model has changed */
private void indicateAddressBookChanged() {
raise(new AddressBookChangedEvent(taskManager));
}
//@@author A0135807A
/** Raises events to update the file location in storage and status bar in UI */
@Override
public void updateFileLocation() {
raise(new ChangedFileLocationRequestEvent(config));
raise(new UpdateStatusBarFooterEvent());
indicateAddressBookChanged();
}
/** Raises event to update the Ui TaskDescription when task is edited. */
public void updateUiTaskDescription(ReadOnlyTask editedtask) {
raise(new UpdateUiTaskDescriptionEvent(editedtask));
}
//@@author
//@@author A0125221Y
@Override
public synchronized int deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
int indexRemoved = taskManager.removeTask(target);
indicateAddressBookChanged();
return indexRemoved;
}
//@@author
@Override
public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
taskManager.addTask(task);
updateFilteredListBasedOnTab();
indicateAddressBookChanged();
}
@Override
public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask)
throws UniqueTaskList.DuplicateTaskException {
assert editedTask != null;
int taskIndex = filteredTasks.getSourceIndex(filteredTaskListIndex);
taskManager.updateTask(taskIndex, editedTask);
updateUiTaskDescription(editedTask);
updateFilteredListBasedOnTab();
indicateAddressBookChanged();
}
//@@author A0125221Y
@Override
public synchronized void updateTask(ReadOnlyTask old, Task toUpdate)
throws TaskNotFoundException, DuplicateTaskException {
taskManager.updateTask(old, toUpdate);
updateUiTaskDescription(toUpdate);
indicateAddressBookChanged();
}
@Override
public synchronized void addTaskIdx(Task task, int idx) throws UniqueTaskList.DuplicateTaskException {
taskManager.addTaskToIndex(task, idx);
updateFilteredListToShowAll();
indicateAddressBookChanged();
}
//@@author A0125221Y
@Override
public Stack<String> getUndoStack() {
return stackOfUndo;
}
@Override
public Stack<ReadOnlyTask> getAddedStackOfTasks() {
return stackOfDeletedTasksAdd;
}
@Override
public Stack<ReadOnlyTask> getDeletedStackOfTasks() {
return stackOfDeletedTasks;
}
@Override
public Stack<Integer> getDeletedStackOfTasksIndex() {
return stackOfDeletedTaskIndex;
}
@Override
public Stack<ReadOnlyTask> getOldTask() {
return stackOfOldTask;
}
@Override
public Stack<ReadOnlyTask> getCurrentTask() {
return stackOfCurrentTask;
}
//@@author
@Override
public void setCurrentList(String currentList) {
this.currentList = currentList;
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
// here to change the list order according to the date comparator.
return new UnmodifiableObservableList<>(filteredTasks);
// return new UnmodifiableObservableList<>(filteredTasks.sorted(new
// DateComparator()));
}
@Override
public void updateFilteredListBasedOnTab() {
if (currentList.equalsIgnoreCase("today")) {
updateFilteredListToShowToday();
} else if (currentList.equalsIgnoreCase("completed")) {
updateFilteredListToShowCompleted();
} else {
updateFilteredListToShowAll();
}
}
@Override
public void updateFilteredListToShowAll() {
ListFilter.filterAll(filteredTasks);
}
@Override
public void updateFilteredListToShowToday() {
ListFilter.filterToday(filteredTasks);
}
@Override
public void updateFilteredTaskList(boolean isInContent, Set<String> keywords) {
ListFilter.filterKeywords(filteredTasks, isInContent, keywords);
}
@Override
public void updateFilteredListToShowCompleted() {
ListFilter.filterCompleted(filteredTasks);
}
//@@author A0135753A
@Override
public UnmodifiableObservableList<ReadOnlyTask> getDoneTaskList() {
FilteredList<ReadOnlyTask> newList = filteredTasks;
for (ReadOnlyTask task : newList) {
if (!task.getStatus().status) {
newList.remove(task);
}
}
return new UnmodifiableObservableList<>(newList);
}
//@@author A0135807A
@Override
@Subscribe
public void handleLoadFirstTaskEvent(LoadFirstTaskEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event, "Initializing task"));
if (taskManager.getTaskList().size() > 0) {
raise(new ReadFirstTaskEvent(taskManager.getTaskList().get(0)));
}
}
} |
package seedu.tasklist.model;
import javafx.collections.transformation.FilteredList;
import seedu.tasklist.commons.core.Config;
import seedu.tasklist.commons.core.EventsCenter;
import seedu.tasklist.commons.core.ComponentManager;
import seedu.tasklist.commons.core.LogsCenter;
import seedu.tasklist.commons.core.UnmodifiableObservableList;
import seedu.tasklist.commons.events.TickEvent;
import seedu.tasklist.commons.events.model.TaskCountersChangedEvent;
import seedu.tasklist.commons.events.model.TaskListChangedEvent;
import seedu.tasklist.commons.exceptions.IllegalValueException;
import seedu.tasklist.logic.commands.UndoCommand;
import seedu.tasklist.model.tag.UniqueTagList;
import seedu.tasklist.model.task.EndTime;
import seedu.tasklist.model.task.Priority;
import seedu.tasklist.model.task.ReadOnlyTask;
import seedu.tasklist.model.task.StartTime;
import seedu.tasklist.model.task.Task;
import seedu.tasklist.model.task.TaskDetails;
import seedu.tasklist.model.task.UniqueTaskList;
import seedu.tasklist.model.task.UniqueTaskList.DuplicateTaskException;
import seedu.tasklist.model.task.UniqueTaskList.TaskNotFoundException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.time.DateUtils;
import org.json.JSONException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.google.common.eventbus.Subscribe;
import com.joestelmach.natty.DateGroup;
import com.joestelmach.natty.Parser;
/**
* Represents the in-memory model of the task list data. All changes to any
* model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private static final int MAXIMUM_UNDO_REDO_SIZE = 3;
public static LinkedList<UndoInfo> undoStack = new LinkedList<UndoInfo>();
public static LinkedList<UndoInfo> redoStack = new LinkedList<UndoInfo>();
private final TaskList taskList;
private final FilteredList<Task> filteredTasks;
private final TaskCounter taskCounter;
/**
* Initializes a ModelManager with the given TaskList TaskList and its
* variables should not be null
*/
public ModelManager(TaskList src, UserPrefs userPrefs) {
super();
assert src != null;
assert userPrefs != null;
logger.fine("Initializing with tasklist: " + src + " and user prefs " + userPrefs);
taskList = new TaskList(src);
filteredTasks = new FilteredList<>(taskList.getTasks());
taskCounter = new TaskCounter(src);
EventsCenter.getInstance().registerHandler(this);
}
public ModelManager() {
this(new TaskList(), new UserPrefs());
}
public ModelManager(ReadOnlyTaskList initialData, UserPrefs userPrefs) {
taskList = new TaskList(initialData);
filteredTasks = new FilteredList<>(taskList.getTasks());
taskCounter = new TaskCounter(initialData);
EventsCenter.getInstance().registerHandler(this);
}
@Override
public void resetData(ReadOnlyTaskList newData) {
if (newData.isEmpty()) { // clear or redo clear was executed
List<Task> listOfTasks = (List<Task>) (List<?>) taskList.getTaskList();
addToUndoStack(UndoCommand.CLR_CMD_ID, null, listOfTasks.toArray(new Task[listOfTasks.size()]));
}
taskList.resetData(newData);
indicateTaskListChanged();
clearRedoStack();
}
@Subscribe
private void tickEvent(TickEvent te) {
indicateTaskListChanged();
}
private void clearRedoStack() {
redoStack.clear();
}
@Override
public void clearTaskUndo(ArrayList<Task> tasks) throws TaskNotFoundException {
TaskList oldTaskList = new TaskList();
oldTaskList.setTasks(tasks);
taskList.resetData(oldTaskList);
}
@Override
public ReadOnlyTaskList getTaskList() {
return taskList;
}
@Override
public TaskCounter getTaskCounter(){
return taskCounter;
}
/** Raises an event to indicate the model has changed */
private void indicateTaskListChanged() {
raise(new TaskListChangedEvent(taskList));
}
@Override
public void deleteTaskUndo(ReadOnlyTask target) throws TaskNotFoundException {
taskList.removeTask(target);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
}
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
taskList.removeTask(target);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
addToUndoStack(UndoCommand.DEL_CMD_ID, null, (Task) target);
clearRedoStack();
}
@Override
public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
taskList.addTask(task);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
addToUndoStack(UndoCommand.ADD_CMD_ID, null, task);
clearRedoStack();
}
@Override
public void addTaskUndo(Task task) throws UniqueTaskList.DuplicateTaskException {
taskList.addTask(task);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
}
@Override
public synchronized void updateTask(Task taskToUpdate, TaskDetails taskDetails, String startTime,
String endTime, Priority priority, UniqueTagList tags, String frequency)
throws IllegalValueException {
Task originalTask = new Task(taskToUpdate);
taskList.updateTask(taskToUpdate, taskDetails, startTime, endTime, priority, frequency);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
addToUndoStack(UndoCommand.UPD_CMD_ID, null, taskToUpdate, originalTask);
clearRedoStack();
}
@Override
public void updateTaskUndo(Task taskToUpdate, TaskDetails taskDetails, StartTime startTime, EndTime endTime,
Priority priority, UniqueTagList tags, String frequency) throws IllegalValueException {
taskList.updateTask(taskToUpdate, taskDetails, startTime, endTime, priority, frequency);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
}
@Override
public synchronized void markTaskAsComplete(ReadOnlyTask task) throws TaskNotFoundException {
taskList.markTaskAsComplete(task);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
addToUndoStack(UndoCommand.DONE_CMD_ID, null, (Task) task);
clearRedoStack();
}
@Override
public synchronized void markTaskAsIncomplete(ReadOnlyTask task) throws TaskNotFoundException {
taskList.markTaskAsIncomplete(task);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
}
@Override
public void addToUndoStack(int undoID, String filePath, Task... tasks) {
if (undoStack.size() == MAXIMUM_UNDO_REDO_SIZE) {
undoStack.remove(undoStack.size() - 1);
}
UndoInfo undoInfo = new UndoInfo(undoID, filePath, tasks);
undoStack.push(undoInfo);
}
@Override
public void updateFilteredListToShowPriority(String priority) {
updateFilteredListToShowAll();
updateFilteredTaskList(new PredicateExpression(new PriorityQualifier(priority)));
}
@Override
public void updateFilteredListToShowDate(String date) {
updateFilteredListToShowAll();
updateFilteredTaskList(new PredicateExpression(new DateQualifier(date)));
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
return new UnmodifiableObservableList<>(filteredTasks);
}
public UnmodifiableObservableList<Task> getListOfTasks() {
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public void updateFilteredListToShowAll() {
sortByDateAndPriority();
filteredTasks.setPredicate(null);
}
@Override
public void updateFilteredListToShowIncomplete() {
updateFilteredListToShowAll();
updateFilteredTaskList(new PredicateExpression(new DefaultDisplayQualifier()));
}
public void updateFilteredList() {
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
}
@Override
public void updateFilteredTaskList(Set<String> keywords) {
sortByDateAndPriority();
updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords)));
}
private void updateFilteredTaskList(Expression expression) {
filteredTasks.setPredicate(expression::satisfies);
}
public Set<String> getKeywordsFromList(List<ReadOnlyTask> tasks) {
Set<String> keywords = new HashSet<String>();
for (ReadOnlyTask task : tasks) {
keywords.addAll(Arrays.asList(task.getTaskDetails().toString().split(" ")));
}
return keywords;
}
@Override
public void updateFilteredListToShowComplete() {
updateFilteredListToShowAll();
updateFilteredTaskList(new PredicateExpression(new CompletedQualifier()));
}
@Override
public void updateFilteredListToShowFloating() {
updateFilteredListToShowAll();
updateFilteredTaskList(new PredicateExpression(new FloatingQualifier()));
}
@Override
public void updateFilteredListToShowOverDue() {
updateFilteredListToShowAll();
updateFilteredTaskList(new PredicateExpression(new OverDueQualifier()));
}
@Override
public void updateFilteredListToShowRecurring() {
updateFilteredListToShowAll();
updateFilteredTaskList(new PredicateExpression(new RecurringQualifier()));
}
private void sortByDateAndPriority() {
// Collections.sort(taskList.getListOfTasks(), Comparators.DATE_TIME);
Collections.sort(taskList.getListOfTasks(), Comparators.PRIORITY);
}
private static class Comparators {
public static Comparator<Task> DATE_TIME = new Comparator<Task>() {
@Override
public int compare(Task o1, Task o2) {
return o1.getStartTime().compareTo(o2.getStartTime());
}
};
public static Comparator<Task> PRIORITY = new Comparator<Task>() {
@Override
public int compare(Task o1, Task o2) {
// extract only the date without time from the card string for
// start time
String date1 = o1.getStartTime().toCardString().split(" ")[0];
String date2 = o2.getStartTime().toCardString().split(" ")[0];
if (date1.equals(date2))
return o1.getPriority().compareTo(o2.getPriority());
else
return o1.getStartTime().compareTo(o2.getStartTime());
}
};
}
interface Expression {
boolean satisfies(ReadOnlyTask person);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask person) {
return qualifier.run(person);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask person);
String toString();
}
private class DefaultDisplayQualifier implements Qualifier {
DefaultDisplayQualifier() {
}
@Override
public boolean run(ReadOnlyTask person) {
return !person.isComplete();
}
}
private class CompletedQualifier implements Qualifier {
@Override
public boolean run(ReadOnlyTask person) {
return person.isComplete();
}
}
private class FloatingQualifier implements Qualifier {
@Override
public boolean run(ReadOnlyTask person) {
return person.isFloating();
}
}
private class PriorityQualifier implements Qualifier {
private String priority;
public PriorityQualifier(String priority) {
this.priority = priority.replaceFirst("p/", "");
}
@Override
public boolean run(ReadOnlyTask person) {
return person.getPriority().priorityLevel.equals(this.priority);
}
}
private class DateQualifier implements Qualifier {
private final Calendar requestedTime;
public DateQualifier(String time) {
requestedTime = Calendar.getInstance();
List<DateGroup> dates = new Parser().parse(time);
requestedTime.setTime(dates.get(0).getDates().get(0));
}
@Override
public boolean run(ReadOnlyTask person) {
return DateUtils.isSameDay(person.getStartTime().time, requestedTime)
|| (person.getStartTime().toCardString().equals("-")
&& DateUtils.isSameDay(person.getEndTime().time, requestedTime));
}
}
private class OverDueQualifier implements Qualifier {
@Override
public boolean run(ReadOnlyTask person) {
return person.isOverDue();
}
}
private class RecurringQualifier implements Qualifier {
@Override
public boolean run(ReadOnlyTask person) {
return person.isRecurring();
}
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
private Pattern NAME_QUERY;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
this.NAME_QUERY = Pattern.compile(getRegexFromString(), Pattern.CASE_INSENSITIVE);
}
private String getRegexFromString() {
String result = "";
for (String keyword : nameKeyWords) {
for (char c : keyword.toCharArray()) {
switch (c) {
case '*':
result += ".*";
break;
default:
result += c;
}
}
}
return result;
}
@Override
public boolean run(ReadOnlyTask person) {
Matcher matcher = NAME_QUERY.matcher(person.getTaskDetails().taskDetails);
return matcher.matches();
}
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
@Override
public LinkedList<UndoInfo> getUndoStack() {
return undoStack;
}
@Override
public LinkedList<UndoInfo> getRedoStack() {
return redoStack;
}
@Override
public void changeFileStorage(String filePath) throws IOException, ParseException, JSONException {
if (filePath.equals("default")) {
filePath = "/data/tasklist.xml";
}
File targetListFile = new File(filePath);
FileReader read = new FileReader("config.json");
JSONObject obj = (JSONObject) new JSONParser().parse(read);
String currentFilePath = (String) obj.get("taskListFilePath");
File currentTaskListPath = new File(currentFilePath);
Config config = new Config();
try {
Files.move(currentTaskListPath.toPath(), targetListFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
}
config.setTaskListFilePath(filePath);
addToUndoStack(UndoCommand.STR_CMD_ID, currentFilePath);
clearRedoStack();
}
@Override
public String changeFileStorageUndo(String filePath) throws IOException, ParseException, JSONException {
if (filePath.equals("default")) {
filePath = "/data/tasklist.xml";
}
File targetListFile = new File(filePath);
FileReader read = new FileReader("config.json");
JSONObject obj = (JSONObject) new JSONParser().parse(read);
String currentFilePath = (String) obj.get("taskListFilePath");
File currentTaskListPath = new File(currentFilePath);
Config config = new Config();
try {
Files.move(currentTaskListPath.toPath(), targetListFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
}
config.setTaskListFilePath(filePath);
return currentFilePath;
}
@Override
public void deleteTaskRedo(Task target) throws TaskNotFoundException {
taskList.removeTask(target);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
addToUndoStack(UndoCommand.DEL_CMD_ID, null, (Task) target);
}
@Override
public void addTaskRedo(Task task) throws DuplicateTaskException {
taskList.addTask(task);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
addToUndoStack(UndoCommand.ADD_CMD_ID, null, task);
}
@Override
public void markTaskAsCompleteRedo(Task task) throws TaskNotFoundException {
taskList.markTaskAsComplete(task);
updateFilteredListToShowIncomplete();
indicateTaskListChanged();
addToUndoStack(UndoCommand.DONE_CMD_ID, null, (Task) task);
}
@Override
public void resetDataRedo(ReadOnlyTaskList newData) {
if (newData.isEmpty()) { // clear or redo clear was executed
List<Task> listOfTasks = (List<Task>) (List<?>) taskList.getTaskList();
addToUndoStack(UndoCommand.CLR_CMD_ID, null, listOfTasks.toArray(new Task[listOfTasks.size()]));
}
taskList.resetData(newData);
indicateTaskListChanged();
}
@Override
public void changeFileStorageRedo(String filePath) throws IOException, ParseException, JSONException {
if (filePath.equals("default")) {
filePath = "/data/tasklist.xml";
}
File targetListFile = new File(filePath);
FileReader read = new FileReader("config.json");
JSONObject obj = (JSONObject) new JSONParser().parse(read);
String currentFilePath = (String) obj.get("taskListFilePath");
File currentTaskListPath = new File(currentFilePath);
Config config = new Config();
try {
Files.move(currentTaskListPath.toPath(), targetListFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
}
config.setTaskListFilePath(filePath);
addToUndoStack(UndoCommand.STR_CMD_ID, currentFilePath);
}
} |
//@@author A0126240W
package seedu.whatnow.logic.parser;
import static seedu.whatnow.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.whatnow.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.whatnow.commons.exceptions.IllegalValueException;
import seedu.whatnow.commons.util.StringUtil;
import seedu.whatnow.logic.commands.*;
import seedu.whatnow.model.tag.Tag;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
/**
* One or more keywords separated by whitespace
*/
private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)");
/**
* Forward slashes are reserved for delimiter prefixes
* variable number of tags
*/
private static final Pattern TASK_DATA_ARGS_FORMAT = Pattern.compile("(?<name>[^/]+)" + "(?<tagArguments>(?: t/[^/]+)*)");
/**
* This arguments is for e.g. add task on today, add task on 18/10/2016
*/
private static final Pattern TASK_MODIFIED_WITH_DATE_ARGS_FORMAT = Pattern.compile("(?<name>[^/]+)\\s" + "(.*?\\bon|by\\b.*?\\s)??" +
"(?<dateArguments>([0-3]??[0-9][//][0-1]??[0-9][//][0-9]{4})??)" + "(?<tagArguments>(?: t/[^/]+)*)");
/**
* Regular Expressions
*/
private static final Pattern UPDATE_FORMAT = Pattern.compile("^((todo|schedule)\\s(\\d+)\\s(description|date|time|tag)($|\\s))");
private static final Pattern DATE = Pattern.compile("^(([3][0-1])|([1-2][0-9])|([0]??[1-9]))$");
private static final Pattern DATE_WITH_SUFFIX = Pattern.compile("^((([3][0-1])|([1-2][0-9])|([0]??[1-9]))(st|nd|rd|th))$");
private static final Pattern MONTH_IN_FULL = Pattern.compile("^(january|february|march|april|may|june|july|august|september|october|november|december)$");
private static final Pattern MONTH_IN_SHORT = Pattern.compile("^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)$");
private static final Pattern YEAR = Pattern.compile("^([0-9]{4})$");
private static final Pattern DATE_WITH_SLASH_FORMAT = Pattern.compile("^(([3][0-1])|([1-2][0-9])|([0]??[1-9]))[/](([1][0-2])|([0]??[1-9]))[/]([0-9]{4})$");
private static final Pattern TIME_FORMAT = Pattern.compile("^(([1][0-2])|([0-9]))((:|\\.)([0-5][0-9]))??((am)|(pm))$");
private static final Pattern TAG_FORMAT = Pattern.compile("^(t/)");
private static final Pattern TODAY_OR_TOMORROW = Pattern.compile("^(today|tomorrow)$");
private static final Pattern DAYS_IN_FULL = Pattern.compile("^(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$");
private static final Pattern DAYS_IN_SHORT = Pattern.compile("^(mon|tue|tues|wed|thu|thur|fri|sat|sun)$");
private static final Pattern KEYWORD_FOR_DATE = Pattern.compile("^((on)|(by)|(from)|(to))$");
private static final Pattern KEYWORD_FOR_TIME = Pattern.compile("^((at)|(by)|(from)|(to)|(till))$");
/**
* Integer Constants
*/
private static final int ONE = 1;
private static final int TWO = 2;
private static final int TASK_TYPE = 0;
private static final int INDEX = 1;
private static final int ARG_TYPE = 2;
private static final int ARG = 3;
private static final int TIME_WITHOUT_PERIOD = 0;
private static final int TIME_HOUR = 0;
private static final int TIME_MINUTES = 1;
private static final int ADD_COMMAND_DESCRIPTION_INDEX = 1;
private static final int ADD_COMMAND_TAG_INDEX = 1;
private static final int ADD_COMMAND_MIN_ARGUMENTS = 2;
private static final int NUM_OF_QUOTATION_MARKS = 2;
private static final int UPDATE_COMMAND_MIN_ARGUMENTS = 3;
private static final int LIST_ARG = 0;
private static final int CHANGE_LOCATION = 0;
private static final int CHANGE_LOCATION_TO = 1;
private static final int CHANGE_LOCATION_TO_PATH = 2;
/**
* String Constants
*/
private static final String NONE = "none";
private static final String DESCRIPTION = "description";
private static final String DELIMITER_BLANK_SPACE = " ";
private static final String DELIMITER_DOUBLE_QUOTATION_MARK = "\"";
private static final String DELIMITER_FORWARD_SLASH = "/";
private static final String BACK_SLASH = "\\";
private static final String FORWARD_SLASH = "/";
private static final String EMPTY_STRING = "";
private static final String DATE_SUFFIX_REGEX = "(st|nd|rd|th)$";
private static final String TIME_COLON = ":";
private static final String TIME_DOT = ".";
private static final String TIME_AM = "am";
private static final String TIME_PM = "pm";
private static final String TIME_DEFAULT_MINUTES = "00";
private static final String DEFAULT_START_TIME = "12:00am";
private static final String DEFAULT_END_TIME = "11:59pm";
private static final String TASK_TYPE_FLOATING = "todo";
private static final String TASK_TYPE_NON_FLOATING = "schedule";
private static final String LIST_COMMAND_ARG_COMPLETED = "done";
private static final String LIST_COMMAND_ARG_NOT_SPECIFIED = "";
private static final String LIST_COMMAND_ARG_ALL_TASKS = "all";
private static final String TASK_ARG_DESCRIPTION = "description";
private static final String TASK_ARG_TAG = "tag";
private static final String TASK_ARG_DATE = "date";
private static final String TASK_ARG_TIME = "time";
public Parser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
* @throws ParseException
*/
public Command parseCommand(String userInput) throws ParseException {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case SelectCommand.COMMAND_WORD:
return prepareSelect(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ListCommand.COMMAND_WORD:
return prepareList(arguments);
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
case UpdateCommand.COMMAND_WORD:
return prepareUpdate(arguments);
case ChangeCommand.COMMAND_WORD:
return prepareChange(arguments);
case MarkDoneCommand.COMMAND_WORD:
return prepareMarkDone(arguments);
case MarkUndoneCommand.COMMAND_WORD:
return prepareMarkUndone(arguments);
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
case RedoCommand.COMMAND_WORD:
return new RedoCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Counts the number of occurrence of a substring in a string
* @param str The given string
* @param findStr The substring to look for in a given string
* @return the number of occurrence
*/
public static int countOccurence(String str, String findStr) {
int lastIndex = 0;
int count = 0;
while(lastIndex != -1) {
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
count++;
lastIndex += findStr.length();
}
}
return count;
}
/**
* Formats the time to the colon format E.g. 12:30am, 4:20pm etc
* @param time The time to be formatted
* @param period The time period
* @return the formatted time
*/
public static String formatTime(String time, String period) {
String[] splitTimePeriod = null;
String[] splitTime = null;
splitTimePeriod = time.toLowerCase().split(period);
if (splitTimePeriod[TIME_WITHOUT_PERIOD].contains(TIME_COLON)) {
splitTime = splitTimePeriod[TIME_WITHOUT_PERIOD].split(TIME_COLON);
}
if (splitTimePeriod[TIME_WITHOUT_PERIOD].contains(TIME_DOT)) {
splitTime = splitTimePeriod[TIME_WITHOUT_PERIOD].split(BACK_SLASH + TIME_DOT);
}
time = (splitTime != null) ? splitTime[TIME_HOUR] : splitTimePeriod[TIME_WITHOUT_PERIOD];
time += TIME_COLON;
time += (splitTime != null) ? splitTime[TIME_MINUTES] : TIME_DEFAULT_MINUTES;
time += period;
return time;
}
/**
* Calls the formatTime method to format the time
* @param time The time to be formatted
* @return the formatted time
*/
public static String formatTime(String time) {
if (time.contains(TIME_AM)) {
time = formatTime(time, TIME_AM);
} else {
time = formatTime(time, TIME_PM);
}
return time;
}
public static HashMap<String, Integer> storeFullMonths(HashMap<String, Integer> months) {
months.put("january", 1);
months.put("february", 2);
months.put("march", 3);
months.put("april", 4);
months.put("may", 5);
months.put("june", 6);
months.put("july", 7);
months.put("august", 8);
months.put("september", 9);
months.put("october", 10);
months.put("november", 11);
months.put("december", 12);
return months;
}
public static HashMap<String, Integer> storeShortMonths(HashMap<String, Integer> months) {
months.put("jan", 1);
months.put("feb", 2);
months.put("mar", 3);
months.put("apr", 4);
months.put("may", 5);
months.put("jun", 6);
months.put("jul", 7);
months.put("aug", 8);
months.put("sep", 9);
months.put("oct", 10);
months.put("nov", 11);
months.put("dec", 12);
return months;
}
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args){
boolean validArgument = true;
boolean hasDate = false;
boolean hasTime = false;
int numOfDate = 0;
int numOfTime = 0;
String name = null;
String date = null;
String startDate = null;
String endDate = null;
String time = null;
String startTime = null;
String endTime = null;
Set<String> tags = new HashSet<String>();
String[] additionalArgs = null;
HashMap<String, Integer> fullMonths = new HashMap<String, Integer>();
HashMap<String, Integer> shortMonths = new HashMap<String, Integer>();
fullMonths = storeFullMonths(fullMonths);
shortMonths = storeShortMonths(shortMonths);
args = args.trim();
//final Matcher matcher = TASK_MODIFIED_WITH_DATE_ARGS_FORMAT.matcher(args.trim());
// Validate the format of the arguments
/*if (!TASK_DATA_ARGS_FORMAT.matcher(args).find() && !TASK_MODIFIED_WITH_DATE_ARGS_FORMAT.matcher(args).find()){
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}*/
// Check whether there are two quotation marks ""
if (countOccurence(args, DELIMITER_DOUBLE_QUOTATION_MARK) != NUM_OF_QUOTATION_MARKS) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
String[] arguments = args.split(DELIMITER_DOUBLE_QUOTATION_MARK);
if (arguments.length < ADD_COMMAND_MIN_ARGUMENTS) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
// E.g. add "Without date and time"
if (arguments.length == ADD_COMMAND_MIN_ARGUMENTS) {
name = arguments[ADD_COMMAND_DESCRIPTION_INDEX].trim();
try {
return new AddCommand(name, date, startDate, endDate, time, startTime, endTime, Collections.emptySet());
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (ParseException e) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
}
name = arguments[ADD_COMMAND_DESCRIPTION_INDEX].trim();
if (arguments.length > ADD_COMMAND_MIN_ARGUMENTS) {
additionalArgs = arguments[arguments.length - 1].trim().split(DELIMITER_BLANK_SPACE);
}
for (int i = 0; i < additionalArgs.length; i++) {
if (KEYWORD_FOR_DATE.matcher(additionalArgs[i].toLowerCase()).find()) {
hasDate = true;
continue;
}
else if (KEYWORD_FOR_TIME.matcher(additionalArgs[i].toLowerCase()).find()) {
hasTime = true;
continue;
}
else if (TAG_FORMAT.matcher(additionalArgs[i]).find()) {
String[] splitTag = additionalArgs[i].trim().split(DELIMITER_FORWARD_SLASH);
tags.add(splitTag[ADD_COMMAND_TAG_INDEX]);
continue;
} else if (!hasDate && TODAY_OR_TOMORROW.matcher(additionalArgs[i].toLowerCase()).find()) {
numOfDate++;
if (numOfDate == ONE) {
date = additionalArgs[i].toLowerCase();
} else if (numOfDate == TWO) {
startDate = date;
date = null;
endDate = additionalArgs[i].toLowerCase();
}
continue;
} else if (!hasTime && TIME_FORMAT.matcher(additionalArgs[i].toLowerCase()).find()) {
numOfTime++;
if (numOfTime == ONE) {
time = additionalArgs[i].toLowerCase();
if (startDate != null & endDate != null) {
endTime = time;
time = null;
startTime = DEFAULT_START_TIME;
}
} else if (numOfTime == TWO) {
startTime = time;
time = null;
endTime = additionalArgs[i].toLowerCase();
}
continue;
} else if (!hasDate && !hasTime) {
validArgument = false;
}
if (hasDate) {
if (DATE_WITH_SLASH_FORMAT.matcher(additionalArgs[i]).find()) {
numOfDate++;
if (numOfDate == ONE) {
date = additionalArgs[i];
} else if (numOfDate == TWO) {
startDate = date;
date = null;
endDate = additionalArgs[i];
}
hasDate = false;
} else if (TODAY_OR_TOMORROW.matcher(additionalArgs[i].toLowerCase()).find()) {
numOfDate++;
if (numOfDate == ONE) {
date = additionalArgs[i].toLowerCase();
} else if (numOfDate == TWO) {
startDate = date;
date = null;
endDate = additionalArgs[i].toLowerCase();
}
hasDate = false;
} else if (TIME_FORMAT.matcher(additionalArgs[i].toLowerCase()).find()) {
numOfTime++;
if (numOfTime == ONE) {
time = additionalArgs[i].toLowerCase();
if (startDate != null & endDate != null) {
endTime = time;
time = null;
startTime = DEFAULT_START_TIME;
}
} else if (numOfTime == TWO) {
startTime = time;
time = null;
endTime = additionalArgs[i].toLowerCase();
}
hasDate = false;
} else if (DATE.matcher(additionalArgs[i].toLowerCase()).find()) {
numOfDate++;
if (numOfDate == ONE) {
date = additionalArgs[i].toLowerCase();
date += FORWARD_SLASH;
} else if (numOfDate == TWO) {
startDate = date;
date = null;
endDate = additionalArgs[i].toLowerCase();
endDate += FORWARD_SLASH;
}
} else if (DATE_WITH_SUFFIX.matcher(additionalArgs[i].toLowerCase()).find()) {
numOfDate++;
if (numOfDate == ONE) {
date = additionalArgs[i].toLowerCase().replaceAll(DATE_SUFFIX_REGEX, EMPTY_STRING);
date += FORWARD_SLASH;
} else if (numOfDate == TWO) {
startDate = date;
date = null;
endDate = additionalArgs[i].toLowerCase();
endDate += FORWARD_SLASH;
}
} else if (MONTH_IN_FULL.matcher(additionalArgs[i].toLowerCase()).find()) {
if (numOfDate == ONE) {
date += fullMonths.get(additionalArgs[i].toLowerCase());
} else if (numOfDate == TWO) {
endDate += fullMonths.get(additionalArgs[i].toLowerCase());
}
} else if (MONTH_IN_SHORT.matcher(additionalArgs[i].toLowerCase()).find()) {
if (numOfDate == ONE) {
date += shortMonths.get(additionalArgs[i].toLowerCase());
} else if (numOfDate == TWO) {
endDate += shortMonths.get(additionalArgs[i].toLowerCase());
}
} else if (YEAR.matcher(additionalArgs[i].toLowerCase()).find()) {
if (numOfDate == ONE) {
date += FORWARD_SLASH;
date += additionalArgs[i].toLowerCase();
} else if (numOfDate == TWO) {
endDate += FORWARD_SLASH;
endDate += additionalArgs[i].toLowerCase();
}
hasDate = false;
} else {
hasDate = false;
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
}
if (hasTime) {
if (TIME_FORMAT.matcher(additionalArgs[i].toLowerCase()).find()) {
numOfTime++;
if (numOfTime == ONE) {
time = additionalArgs[i].toLowerCase();
if (startDate != null & endDate != null) {
endTime = time;
time = null;
startTime = DEFAULT_START_TIME;
}
} else if (numOfTime == TWO) {
startTime = time;
time = null;
endTime = additionalArgs[i].toLowerCase();
}
} else {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
hasTime = false;
}
if (!validArgument) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
}
if (time != null) {
time = formatTime(time);
} else if (startTime != null) {
startTime = formatTime(startTime);
endTime = formatTime(endTime);
}
if (startDate != null) {
if (time != null) {
startTime = time;
time = null;
endTime = DEFAULT_END_TIME;
}
}
try {
return new AddCommand(name, date, startDate, endDate, time, startTime, endTime, tags);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (ParseException e) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
}
/**
* Extracts the new task's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/"));
return new HashSet<>(tagStrings);
}
/**
* Parses arguments in the context of the change data file location command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareChange(String args) {
String[] argComponents= args.trim().split(" ");
if(argComponents[CHANGE_LOCATION].equals("location") && argComponents[CHANGE_LOCATION_TO].equals("to")){
return new ChangeCommand(argComponents[CHANGE_LOCATION_TO_PATH]);
}
else{
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, ChangeCommand.MESSAGE_USAGE));
}
}
private Command prepareList(String args) {
String[] argComponents= args.trim().split(DELIMITER_BLANK_SPACE);
String listArg = argComponents[LIST_ARG];
if (!isListCommandValid(listArg)) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE));
}
return new ListCommand(listArg);
}
private boolean isListCommandValid(String listArg) {
return listArg.equals(LIST_COMMAND_ARG_COMPLETED) || listArg.equals(LIST_COMMAND_ARG_NOT_SPECIFIED)
|| listArg.equals(LIST_COMMAND_ARG_ALL_TASKS);
}
/**
* Parses arguments in the context of the delete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
String[] argComponents = args.trim().split(DELIMITER_BLANK_SPACE);
if (argComponents.length < 2) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
Optional<Integer> index = parseIndex(argComponents[INDEX]);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(argComponents[TASK_TYPE], index.get());
}
/**
* Parses arguments in the context of the update task command.
*
* @param args full command args string
* @return the prepared command
* @throws ParseException
*/
private Command prepareUpdate(String args) {
if (args.equals(null))
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE));
if (!UPDATE_FORMAT.matcher(args.trim().toLowerCase()).find()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE));
}
String[] argComponents = args.trim().split(DELIMITER_BLANK_SPACE);
if (argComponents.length < UPDATE_COMMAND_MIN_ARGUMENTS)
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE));
String taskType = argComponents[TASK_TYPE];
Optional<Integer> index = parseIndex(argComponents[INDEX]);
String argType = argComponents[ARG_TYPE];
String arg = "";
HashMap<String, Integer> fullMonths = new HashMap<String, Integer>();
HashMap<String, Integer> shortMonths = new HashMap<String, Integer>();
fullMonths = storeFullMonths(fullMonths);
shortMonths = storeShortMonths(shortMonths);
int numOfDate = 0;
int numOfTime = 0;
if (argComponents.length > UPDATE_COMMAND_MIN_ARGUMENTS) {
for (int i = ARG; i < argComponents.length; i++) {
if (argType.toUpperCase().compareToIgnoreCase(TASK_ARG_DESCRIPTION) == 0) {
if (argComponents[i].toUpperCase().compareToIgnoreCase(NONE) == 0)
return new IncorrectCommand(MESSAGE_INVALID_COMMAND_FORMAT + UpdateCommand.MESSAGE_USAGE);
arg += argComponents[i] + DELIMITER_BLANK_SPACE;
} else if (argType.toUpperCase().compareToIgnoreCase(TASK_ARG_DATE) == 0) {
if (DATE_WITH_SLASH_FORMAT.matcher(argComponents[i]).find()) {
numOfDate++;
if (numOfDate == ONE)
arg = argComponents[i];
else if (numOfDate == TWO)
arg += DELIMITER_BLANK_SPACE + argComponents[i];
} else if (TODAY_OR_TOMORROW.matcher(argComponents[i].toLowerCase()).find()) {
numOfDate++;
if (numOfDate == ONE)
arg = argComponents[i];
else if (numOfDate == TWO)
arg += DELIMITER_BLANK_SPACE + argComponents[i];
} else if (DATE.matcher(argComponents[i].toLowerCase()).find()) {
numOfDate++;
if (numOfDate == ONE) {
arg = argComponents[i].toLowerCase();
arg += FORWARD_SLASH;
} else if (numOfDate == TWO) {
arg += DELIMITER_BLANK_SPACE + argComponents[i].toLowerCase();
arg += FORWARD_SLASH;
}
} else if (DATE_WITH_SUFFIX.matcher(argComponents[i].toLowerCase()).find()) {
numOfDate++;
if (numOfDate == ONE) {
arg = argComponents[i].toLowerCase().replaceAll(DATE_SUFFIX_REGEX, EMPTY_STRING);
arg += FORWARD_SLASH;
} else if (numOfDate == TWO) {
arg = argComponents[i].toLowerCase();
arg += FORWARD_SLASH;
}
} else if (MONTH_IN_FULL.matcher(argComponents[i].toLowerCase()).find()) {
if (numOfDate == ONE) {
arg += fullMonths.get(argComponents[i].toLowerCase());
} else if (numOfDate == TWO) {
arg += fullMonths.get(argComponents[i].toLowerCase());
}
} else if (MONTH_IN_SHORT.matcher(argComponents[i].toLowerCase()).find()) {
if (numOfDate == ONE) {
arg += shortMonths.get(argComponents[i].toLowerCase());
} else if (numOfDate == TWO) {
arg += shortMonths.get(argComponents[i].toLowerCase());
}
} else if (YEAR.matcher(argComponents[i].toLowerCase()).find()) {
if (numOfDate == ONE) {
arg += FORWARD_SLASH;
arg += argComponents[i].toLowerCase();
} else if (numOfDate == TWO) {
arg += FORWARD_SLASH;
arg += argComponents[i].toLowerCase();
}
} else if (argComponents[i].toUpperCase().compareToIgnoreCase(NONE) == 0) {
arg = null;
}
} else if (argType.toUpperCase().compareToIgnoreCase(TASK_ARG_TIME) == 0) {
if (TIME_FORMAT.matcher(argComponents[i]).find()) {
numOfTime++;
if (numOfTime == ONE)
arg = argComponents[i];
else if (numOfTime == TWO)
arg += DELIMITER_BLANK_SPACE + argComponents[i];
} else if (argComponents[i].toUpperCase().compareToIgnoreCase(NONE) == 0)
arg = null;
} else if (argType.toUpperCase().compareToIgnoreCase(TASK_ARG_TAG) == 0) {
if (argComponents[i].toUpperCase().compareToIgnoreCase(NONE) == 0)
arg = null;
else
arg += argComponents[i] + DELIMITER_BLANK_SPACE;
}
}
try {
return new UpdateCommand(taskType, index.get(), argType, arg);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (ParseException pe) {
return new IncorrectCommand(pe.getMessage());
} catch (NoSuchElementException nsee) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE));
}
}
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE));
}
if (!isValidUpdateCommandFormat(taskType, index.get(), argType)) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE));
}
try {
return new UpdateCommand(taskType, index.get(), argType, arg);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (ParseException pe) {
return new IncorrectCommand(pe.getMessage());
}
}
/**
* Parses arguments in the context of the markDone task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareMarkDone(String args) {
String[] argComponents = args.trim().split(" ");
Optional<Integer> index = parseIndex(argComponents[INDEX]);
if (!index.isPresent()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkDoneCommand.MESSAGE_USAGE));
}
return new MarkDoneCommand(argComponents[TASK_TYPE], index.get());
}
/**
* Parses arguments in the context of the markUndone task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareMarkUndone(String args) {
String[] argComponents = args.trim().split(DELIMITER_BLANK_SPACE);
Optional<Integer> index = parseIndex(argComponents[INDEX]);
if (!index.isPresent()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkUndoneCommand.MESSAGE_USAGE));
}
return new MarkUndoneCommand(argComponents[TASK_TYPE], index.get());
}
/**
* Checks that the command format is valid
* @param type is todo/schedule, index is the index of item on the list, argType is description/tag/date/time
*/
private boolean isValidUpdateCommandFormat(String type, int index, String argType) {
if (!(type.compareToIgnoreCase(TASK_TYPE_FLOATING) == 0 || type.compareToIgnoreCase(TASK_TYPE_NON_FLOATING) == 0)) {
return false;
}
if (index < 0) {
return false;
}
if (!(argType.compareToIgnoreCase(TASK_ARG_DESCRIPTION) == 0 || argType.compareToIgnoreCase(TASK_ARG_TAG) == 0
|| argType.compareToIgnoreCase(TASK_ARG_DATE) == 0 || argType.compareToIgnoreCase(TASK_ARG_TIME) == 0)) {
return false;
}
return true;
}
/**
* Parses arguments in the context of the select task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
} |
package sizebay.catalog.client;
import java.util.*;
import lombok.NonNull;
import sizebay.catalog.client.http.*;
import sizebay.catalog.client.model.*;
import sizebay.catalog.client.model.filters.*;
/**
* A Basic wrapper on generated Swagger client.
*
* @author Miere L. Teixeira
*/
public class CatalogAPI {
final static String
DEFAULT_BASE_URL = "https://catalogue.fitpeek.co/api/v1/",
ENDPOINT_DASHBOARD = "/dashboard",
ENDPOINT_BRAND = "/brands",
ENDPOINT_MODELING = "/modelings",
ENDPOINT_PRODUCT = "/products",
ENDPOINT_CATEGORIES = "/categories",
ENDPOINT_TENANTS = "/tenants",
ENDPOINT_TENANTS_DETAILS = "/tenants/details",
ENDPOINT_TENANTS_BASIC_DETAILS = "/tenants/details/basic",
ENDPOINT_USER = "/user",
ENDPOINT_SIZE_STYLE = "/style",
ENDPOINT_DEVOLUTION = "/devolution",
ENDPOINT_IMPORTATION_ERROR = "/importations",
ENDPOINT_STRONG_CATEGORY = "/categories/strong",
ENDPOINT_STRONG_SUBCATEGORY = "/categories/strong/sub",
ENDPOINT_STRONG_MODEL = "models/strong",
ENDPOINT_STRONG_MODELING = "/modelings/strong",
SEARCH_BY_TEXT = "/search/all?text=";
final RESTClient client;
/**
* Constructs the Catalog API.
*
* @param applicationToken
* @param securityToken
*/
public CatalogAPI(@NonNull String applicationToken, @NonNull String securityToken) {
this(DEFAULT_BASE_URL, applicationToken, securityToken);
}
/**
* Constructs the Catalog API.
*
* @param basePath
* @param applicationToken
* @param securityToken
*/
public CatalogAPI(@NonNull String basePath, @NonNull String applicationToken, @NonNull String securityToken) {
final CatalogAuthentication authentication = new CatalogAuthentication( applicationToken, securityToken );
final MimeType mimeType = new JSONMimeType();
client = new RESTClient( basePath, mimeType, authentication );
}
/**
* Starting dashboard management
*/
public List<Dashboard> retrieveDashboard() {
return client.getList(ENDPOINT_DASHBOARD, Dashboard.class);
}
public Dashboard retrieveDashboardByTenant(Long tenantId) {
return client.getSingle(ENDPOINT_DASHBOARD + "/single/" + tenantId, Dashboard.class);
}
/**
* End dashboard management
*/
public ProductBasicInformationToVFR retrieveProductBasicInformationToVFR(String permalink) {
return client.getSingle(ENDPOINT_PRODUCT + "/basic-info-to-vfr?"
+ "permalink=" + permalink, ProductBasicInformationToVFR.class);
}
/**
* Starting user profile management
*/
public void insertUser (UserProfile userProfile) {
client.post(ENDPOINT_USER, userProfile);
}
public UserProfile retrieveUser (String userId) {
return client.getSingle(ENDPOINT_USER + "/single/" + userId, UserProfile.class);
}
public UserProfile updateProfileName(ProfileUpdateName profileUpdateName){
return client.put( ENDPOINT_USER + "/update/profile/name", profileUpdateName, UserProfile.class);
}
public UserProfile retrieveUserByFacebook(String facebookToken) {
return client.getSingle(ENDPOINT_USER + "/social/facebook/" + facebookToken, UserProfile.class);
}
public UserProfile retrieveUserByGoogle(String googleToken) {
return client.getSingle(ENDPOINT_USER + "/social/google/" + googleToken, UserProfile.class);
}
public UserProfile retrieveUserByApple(String appleUserId) {
return client.getSingle(ENDPOINT_USER + "/social/apple/" + appleUserId, UserProfile.class);
}
public Profile retrieveProfile (long profileId) {
return client.getSingle(ENDPOINT_USER + "/profile/" + profileId, Profile.class);
}
public void updateUserFacebookToken(String userId, String facebookToken) {
client.put(ENDPOINT_USER + "/social/facebook/" + userId, facebookToken);
}
public void updateUserGoogleToken(String userId, String googleToken) {
client.put(ENDPOINT_USER + "/social/google/" + userId, googleToken);
}
public void updateUserAppleId(String userId, String appleUserId) {
client.put(ENDPOINT_USER + "/social/apple/" + userId, appleUserId);
}
public void insertProfile (Profile profile) {
client.post(ENDPOINT_USER + "/profile", profile);
}
public void deleteProfile (long profileId) { client.delete(ENDPOINT_USER + "/profile/" + profileId); }
/* User history */
public long insertProductInUserHistory(String userId, UserHistory newProductToUserHistory) {
return client.post(ENDPOINT_USER + "/history/single/"+ userId, newProductToUserHistory);
}
public List<UserHistory> retrieveUserHistory(int page, String userId) {
return client.getList(ENDPOINT_USER + "/history/all/" + userId + "?page=" + page, UserHistory.class);
}
public void deleteUserHistoryProduct(String userId, Long userHistoryId) {
client.delete(ENDPOINT_USER + "/history/single/" + userId + "?userHistoryId=" + userHistoryId);
}
/* User liked products */
public long insertLikeInTheProduct(String userId, LikedProduct likedProduct) {
return client.post(ENDPOINT_USER + "/liked-products/single/"+ userId, likedProduct);
}
public List<LikedProduct> retrieveLikedProductsByUser(int page, String userId) {
return client.getList(ENDPOINT_USER + "/liked-products/all/" + userId + "?page=" + page, LikedProduct.class);
}
public void deleteLikeInTheProduct(String userId, Long likedProductId) {
client.delete(ENDPOINT_USER + "/liked-products/single/" + userId + "?likedProductId=" + likedProductId);
}
/*
* End user profile management
*/
/*
* Starting size style management
*/
public List<SizeStyle> getSizeStyles(SizeStyleFilter filter) {
return client.getList(ENDPOINT_SIZE_STYLE + "?" + filter.createQuery(), SizeStyle.class);
}
public SizeStyle getSingleSizeStyle(long id) {
return client.getSingle(ENDPOINT_SIZE_STYLE + "/single/" + id, SizeStyle.class);
}
public long insertSizeStyle(SizeStyle sizeStyle) {
return client.post(ENDPOINT_SIZE_STYLE + "/single", sizeStyle);
}
public void updateWeightStyle(long id, SizeStyle sizeStyle) {
client.put(ENDPOINT_SIZE_STYLE + "/single/" + id, sizeStyle);
}
public void bulkUpdateWeight(BulkUpdateSizeStyle bulkUpdateSizeStyle) {
client.patch(ENDPOINT_SIZE_STYLE + "/bulk/weight", bulkUpdateSizeStyle);
}
public void bulkUpdateModeling(BulkUpdateSizeStyle bulkUpdateSizeStyle) {
client.patch(ENDPOINT_SIZE_STYLE + "/bulk/modeling", bulkUpdateSizeStyle);
}
public void deleteSizeStyle(long id) {
client.delete(ENDPOINT_SIZE_STYLE + "/single/" + id);
}
public void deleteSizeStyles(List<Integer> ids) {
client.delete(ENDPOINT_SIZE_STYLE + "/bulk/some", ids);
}
/*
* End size style management
*/
/*
* Starting devolution management
*/
public List<DevolutionError> retrieveDevolutionErrors() {
return client.getList(ENDPOINT_DEVOLUTION + "/errors", DevolutionError.class);
}
public List<DevolutionError> retrieveDevolutionErrors(DevolutionFilter filter) {
return client.getList(ENDPOINT_DEVOLUTION + "/errors?" + filter.createQuery(), DevolutionError.class);
}
public long insertDevolutionError(DevolutionError devolution) {
return client.post(ENDPOINT_DEVOLUTION + "/errors/single", devolution);
}
public void deleteDevolutionErrors() {
client.delete(ENDPOINT_DEVOLUTION + "/errors");
}
public DevolutionSummary retrieveDevolutionSummaryLastBy() {
return client.getSingle(ENDPOINT_DEVOLUTION + "/summary/last", DevolutionSummary.class);
}
public long insertDevolutionSummary(DevolutionSummary devolutionSummary) {
return client.post(ENDPOINT_DEVOLUTION + "/summary/single", devolutionSummary);
}
public void deleteDevolutionSummary() {
client.delete(ENDPOINT_DEVOLUTION + "/summary");
}
/*
* End devolution management
*/
/*
* Starting user (MySizebay) management
*/
public long insertTenantPlatformStore(TenantPlatformStore tenantPlatformStore) {
return client.post(ENDPOINT_TENANTS + "/platform/tenant", tenantPlatformStore);
}
public void updateTenantPlatformStore(Long tenantId, TenantPlatformStore tenantPlatformStore) {
client.put(ENDPOINT_TENANTS + "/platform/tenant/" + tenantId, tenantPlatformStore);
}
public UserTenants authenticateAndRetrieveUser(UserAuthenticationDTO userAuthentication) {
return client.post( "/users/authenticate/user", userAuthentication, UserTenants.class );
}
public List<Tenant> authenticateAndRetrieveTenants(String username, String password ) {
return client.getList( "/users/" + username + "/" + password + "/tenants", Tenant.class );
}
public List<UserTenants> retrieveAllUsersBy(String privilege) {
return client.getList( "/privileges/users?privilege=" + privilege, UserTenants.class );
}
/*
* End user (MySizebay) management
*/
/*
* Starting product management
*/
public List<Product> getProducts(int page) {
return client.getList(ENDPOINT_PRODUCT + "?page=" + page, Product.class);
}
public List<Product> getProducts(ProductFilter filter) {
return client.getList(ENDPOINT_PRODUCT + "/search/all" + "?" + filter.createQuery(), Product.class);
}
public Product getProduct(long id) {
return client.getSingle(ENDPOINT_PRODUCT + "/single/" + id, Product.class);
}
public Long getProductIdFromPermalink(String permalink){
return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id"
+ "?permalink=" + permalink,
Long.class);
}
public ProductCount retrieveProductCount() {
return client.getSingle(ENDPOINT_PRODUCT + "/count", ProductCount.class);
}
public ProductSlug retrieveProductSlugByPermalink(String permalink, String sizeLabel){
return client.getSingle(ENDPOINT_PRODUCT + "/slug"
+ "?permalink=" + permalink
+ "&size=" + sizeLabel,
ProductSlug.class);
}
public Long getAvailableProductIdFromPermalink(String permalink){
return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id"
+ "?permalink=" + permalink
+ "&onlyAvailable=true",
Long.class);
}
public ProductIntegration retrieveProductIntegration(Long tenantId, String feedProductId) {
return client.getSingle(ENDPOINT_PRODUCT + "/search/feed-product-id"
+ "/" + tenantId
+ "/" + feedProductId,
ProductIntegration.class);
}
public ProductBasicInformation retrieveProductByBarcode(Long barcode) {
return client.getSingle(ENDPOINT_PRODUCT + "/search/barcode/" + barcode, ProductBasicInformation.class);
}
public ProductBasicInformation getProductBasicInfo(long id){
return client.getSingle(ENDPOINT_PRODUCT
+ "/" + id
+ "/basic-info",
ProductBasicInformation.class);
}
public ProductBasicInformation getProductBasicInfoFilterSizes(long id, String sizes){
return client.getSingle( ENDPOINT_PRODUCT
+ "/" + id
+ "/basic-info-filter-sizes"
+ "?sizes=" + sizes,
ProductBasicInformation.class);
}
public long insertProduct(Product product) {
return client.post(ENDPOINT_PRODUCT + "/single", product);
}
public void insertProductIntegration(ProductIntegration product) {
client.post(ENDPOINT_PRODUCT + "/single/integration", product);
}
public void insertProductIntegrationPlatform(ProductIntegration product) {
client.post(ENDPOINT_PRODUCT + "/single/integration/platform", product);
}
public long insertMockedProduct(String permalink) {
return client.post(ENDPOINT_PRODUCT + "/mock?permalink=" + permalink, String.class);
}
public void updateProduct(long id, Product product) {
client.put(ENDPOINT_PRODUCT + "/single/" + id, product);
}
public void updateProduct(long id, Product product, boolean isAutomaticUpdate) {
client.put(ENDPOINT_PRODUCT + "/single/" + id + "?isAutomaticUpdate=" + isAutomaticUpdate, product);
}
public void bulkUpdateProducts(BulkUpdateProducts products) {
client.patch(ENDPOINT_PRODUCT, products);
}
public void deleteProducts() {
client.delete(ENDPOINT_PRODUCT);
}
public void deleteProduct(long id) {
client.delete(ENDPOINT_PRODUCT + "/single/" + id);
}
public void deleteProductByFeedProductId(long feedProductId) {
client.delete(ENDPOINT_PRODUCT + "/single/feedProduct/" + feedProductId);
}
public void deleteProducts(List<Integer> ids) {
client.delete(ENDPOINT_PRODUCT + "/bulk/some", ids);
}
/*
* End product management
*/
/*
* Starting brand management
*/
public List<Brand> searchForBrands(String text){
return client.getList(ENDPOINT_BRAND + SEARCH_BY_TEXT + text, Brand.class);
}
public List<Brand> getBrands(BrandFilter filter) {
return client.getList(ENDPOINT_BRAND + "?" + filter.createQuery(), Brand.class);
}
public List<Brand> getBrands(int page) {
return client.getList(ENDPOINT_BRAND + "?page=" + page, Brand.class);
}
public List<Brand> getBrands(int page, String name) {
return client.getList(ENDPOINT_BRAND + "?page=" + page + "&name=" + name, Brand.class);
}
public Brand getBrand(long id) {
return client.getSingle(ENDPOINT_BRAND + "/single/" + id, Brand.class);
}
public long insertBrand(Brand brand) {
return client.post(ENDPOINT_BRAND + "/single", brand);
}
public void associateBrandsWithStrongBrand() {
client.getSingle(ENDPOINT_BRAND + "/sync/associate-brand-with-strong-brand");
}
public void createStrongBrandBasedOnBrands(List<Integer> ids) {
client.post(ENDPOINT_BRAND + "/sync/create-strong-brand", ids);
}
public void updateBrand(long id, Brand brand) {
client.put(ENDPOINT_BRAND + "/single/" + id, brand);
}
public void updateBulkBrandAssociation(BulkUpdateBrandAssociation bulkUpdateBrandAssociation) { client.patch(ENDPOINT_BRAND, bulkUpdateBrandAssociation); }
public void deleteBrands() {
client.delete(ENDPOINT_BRAND);
}
public void deleteBrand(long id) {
client.delete(ENDPOINT_BRAND + "/single/" + id);
}
public void deleteBrands(List<Integer> ids) {
client.delete(ENDPOINT_BRAND + "/bulk/some", ids);
}
/*
* End brand management
*/
/*
* Starting category management
*/
public List<Category> getCategories() {
return client.getList(ENDPOINT_CATEGORIES, Category.class);
}
public List<Category> getCategories(int page) {
return client.getList(ENDPOINT_CATEGORIES + "?page=" + page, Category.class);
}
public List<Category> getCategories(int page, String name) {
return client.getList(ENDPOINT_CATEGORIES + "?page=" + page + "&name=" + name, Category.class);
}
public List<Category> getCategories(CategoryFilter filter) {
return client.getList(ENDPOINT_CATEGORIES + "?" + filter.createQuery(), Category.class);
}
public List<Category> searchForCategories(CategoryFilter filter){
return client.getList(ENDPOINT_CATEGORIES + "/search/all?" + filter.createQuery(), Category.class);
}
public Category getCategory(long id) {
return client.getSingle(ENDPOINT_CATEGORIES + "/single/" + id, Category.class);
}
public long insertCategory(Category brand) {
return client.post(ENDPOINT_CATEGORIES + "/single", brand);
}
public void updateCategory(long id, Category brand) {
client.put(ENDPOINT_CATEGORIES + "/single/" +id, brand);
}
public void bulkUpdateCategories(BulkUpdateCategories categories) {
client.patch(ENDPOINT_CATEGORIES, categories);
}
public void deleteCategories() {
client.delete(ENDPOINT_CATEGORIES);
}
public void deleteCategory(long id) {
client.delete(ENDPOINT_CATEGORIES + "/single/" + id);
}
public void deleteCategories(List<Integer> ids) {
client.delete(ENDPOINT_CATEGORIES + "/bulk/some", ids);
}
/*
* End category management
*/
/*
* Starting modeling management
*/
public List<Modeling> searchForModelings(long brandId, String gender) {
return searchForModelings(String.valueOf(brandId), gender);
}
public List<Modeling> searchForModelings(String brandId, String gender){
return client.getList(ENDPOINT_MODELING + "/search/brand/" + brandId + "/gender/" + gender, Modeling.class);
}
public List<Modeling> getModelings(int page){
return client.getList(ENDPOINT_MODELING + "?page=" + page, Modeling.class);
}
public List<Modeling> getModelings(ModelingFilter filter) {
return client.getList(ENDPOINT_MODELING + "/search/all" + "?" + filter.createQuery(), Modeling.class);
}
public List<Modeling> getAllSimplifiedModeling() {
return client.getList(ENDPOINT_MODELING + "/simplified/all", Modeling.class);
}
public Modeling getSingleSimplifiedModeling(long id) {
return client.getSingle(ENDPOINT_MODELING + "/simplified/single/" + id, Modeling.class);
}
public Modeling getModeling(long id) {
return client.getSingle(ENDPOINT_MODELING + "/single/" + id, Modeling.class);
}
public long insertModeling(Modeling modeling) {
return client.post(ENDPOINT_MODELING + "/single", modeling);
}
public long insertModelingWithPopulationOfDomainsAutomatically(Modeling modeling) {
return client.post(ENDPOINT_MODELING + "/single/automatically", modeling);
}
public void updateModeling(long id, Modeling modeling) {
client.put(ENDPOINT_MODELING + "/single/" + id + "?force=false", modeling);
}
public void updateModeling(long id, Modeling modeling, boolean force) {
client.put(ENDPOINT_MODELING + "/single/" + id + "?force=" + force, modeling);
}
public void updateModelingWithPopulationOfDomainsAutomatically(long id, Modeling modeling) {
client.put(ENDPOINT_MODELING + "/single/" + id + "/automatically", modeling);
}
public void deleteModelings() {
client.delete(ENDPOINT_MODELING);
}
public void deleteModeling(long id) {
client.delete(ENDPOINT_MODELING + "/single/" + id);
}
public void deleteModelings(List<Integer> ids) {
client.delete(ENDPOINT_MODELING + "/bulk/some", ids);
}
/*
* End modeling management
*/
/*
* Starting importation error management
*/
public List<ImportationError> getImportationErrors(String page){
return client.getList(ENDPOINT_IMPORTATION_ERROR + "/errors?page=" + page, ImportationError.class);
}
public long insertImportationError(ImportationError importationError){
return client.post( ENDPOINT_IMPORTATION_ERROR + "/errors", importationError);
}
public void deleteImportationErrors() {
client.delete(ENDPOINT_PRODUCT + "/importation-errors/all");
}
public ImportationSummary getImportationSummary(){
return client.getSingle(ENDPOINT_IMPORTATION_ERROR + "/summary/last" , ImportationSummary.class);
}
public long insertImportationSummary(ImportationSummary importationSummary){
return client.post( ENDPOINT_IMPORTATION_ERROR + "/summary/single", importationSummary);
}
public void deleteImportationSummary() {
client.delete(ENDPOINT_IMPORTATION_ERROR);
}
/*
* End importation error management
*/
/*
* Starting strong brand management
*/
public List<StrongBrand> getStrongBrands(StrongBrandFilter filter) {
return client.getList(ENDPOINT_BRAND + "/strong?" + filter.createQuery(), StrongBrand.class);
}
public StrongBrand getSingleBrand(long id) {
return client.getSingle(ENDPOINT_BRAND + "/strong/single/" + id, StrongBrand.class);
}
public long insertStrongBrand(StrongBrand strongBrand){
return client.post( ENDPOINT_BRAND + "/strong/single", strongBrand);
}
public void updateStrongBrand(long id, StrongBrand strongBrand) {
client.put(ENDPOINT_BRAND + "/strong/single/" + id, strongBrand);
}
public void deleteStrongBrand(long id) {
client.delete(ENDPOINT_BRAND + "/strong/single/" + id);
}
public void deleteStrongBrands(List<Integer> ids) {
client.delete(ENDPOINT_BRAND + "/strong/bulk/some", ids);
}
/*
* End strong brand management
*/
/*
* Starting strong category management
*/
public List<StrongCategory> getAllStrongCategories(){
return client.getList(ENDPOINT_STRONG_CATEGORY, StrongCategory.class);
}
public List<StrongCategory> getAllStrongCategories(String page, String categoryName, String type){
String condition;
condition = categoryName == null ? "" : "&name=" + categoryName;
condition += type == null ? "" : "&type=" + type;
return client.getList(ENDPOINT_STRONG_CATEGORY + "?page=" + page + condition, StrongCategory.class);
}
public StrongCategory getSingleStrongCategory(long id) {
return client.getSingle(ENDPOINT_STRONG_CATEGORY + "/single/" + id, StrongCategory.class);
}
public long insertStrongCategory(StrongCategory strongCategory){
return client.post(ENDPOINT_STRONG_CATEGORY + "/single", strongCategory);
}
public void updateStrongCategory(long id, StrongCategory strongCategory) {
client.put(ENDPOINT_STRONG_CATEGORY + "/single/" + id, strongCategory);
}
public void deleteStrongCategory(long id) {
client.delete(ENDPOINT_STRONG_CATEGORY + "/single/" + id);
}
/*
* End strong category management
*/
/*
* Starting strong subcategory management
*/
public List<StrongSubcategory> getStrongSubcategories(StrongSubcategoryFilter filter){
return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?" + filter.createQuery(), StrongSubcategory.class);
}
public List<StrongSubcategory> getStrongSubcategories(int page){
return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?page=" + page, StrongSubcategory.class);
}
public StrongSubcategory getSingleStrongSubcategory(long id) {
return client.getSingle(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, StrongSubcategory.class);
}
public long insertStrongSubcategory(StrongSubcategory strongSubcategory){
return client.post(ENDPOINT_STRONG_SUBCATEGORY + "/single", strongSubcategory);
}
public void updateStrongSubcategory(long id, StrongSubcategory strongSubcategory) {
client.put(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, strongSubcategory);
}
public void deleteStrongSubcategory(long id) {
client.delete(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id);
}
/*
* End strong subcategory management
*/
/*
* Starting strong model management
*/
public List<StrongModel> getAllStrongModels(String page){
return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page, StrongModel.class);
}
public List<StrongModel> getAllStrongModels(String page, String modelName){
return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page + "&name=" + modelName, StrongModel.class);
}
public StrongModel getSingleStrongModel(long id) {
return client.getSingle(ENDPOINT_STRONG_MODEL + "/single/" + id, StrongModel.class);
}
public long insertStrongModel(StrongModel strongModel){
return client.post(ENDPOINT_STRONG_MODEL + "/single", strongModel);
}
public void updateStrongModel(long id, StrongModel strongModel) {
client.put(ENDPOINT_STRONG_MODEL + "/single/" + id, strongModel);
}
public void deleteStrongModel(long id) {
client.delete(ENDPOINT_STRONG_MODEL + "/single/" + id);
}
/*
* End strong model management
*/
/*
* Starting strong modeling management
*/
public List<StrongModeling> getStrongModelings(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "?" + filter.createQuery(), StrongModeling.class);
}
public List<Long> retrieveAllOrganicTableIds(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "/organic/ids" , Long.class);
}
public StrongModeling getSingleStrongModeling(long id) {
return client.getSingle(ENDPOINT_STRONG_MODELING + "/single/" + id, StrongModeling.class);
}
public List<StrongModeling> getAllSimplifiedStrongModelings(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "/simplified" + "?" + filter.createQuery(), StrongModeling.class);
}
public long insertStrongModeling(StrongModeling strongModeling){
return client.post(ENDPOINT_STRONG_MODELING + "/single", strongModeling);
}
public void createStrongModelingsBasedOnBrands(String sizeSystem, List<Integer> ids) {
client.post(ENDPOINT_STRONG_MODELING + "/sync/create-strong-modelings?sizeSystem=" + sizeSystem, ids);
}
public void syncStrongModelingsWithSlugs() {
client.post(ENDPOINT_STRONG_MODELING + "/sync", null);
}
public void updateStrongModeling(long id, StrongModeling strongModeling) {
client.put(ENDPOINT_STRONG_MODELING + "/single/" + id, strongModeling);
}
public void deleteStrongModeling(long id) {
client.delete(ENDPOINT_STRONG_MODELING + "/single/" + id);
}
public void deleteStrongModelings(List<Integer> ids) {
client.delete(ENDPOINT_STRONG_MODELING + "/bulk/some", ids);
}
/*
* End strong modeling management
*/
/*
* Starting tenant management
*/
public Tenant getTenant( String appToken ){
return client.getSingle( ENDPOINT_TENANTS+ "/single/" + appToken, Tenant.class );
}
public void inactivateTenant() {
client.put(ENDPOINT_TENANTS + "/inactivate", null);
}
public TenantPlatformStore retrieveTenantPlatformStoreByStoreId(String storeId, String platform) {
return client.getSingle(ENDPOINT_TENANTS + "/platform/store/" + platform + "/" + storeId, TenantPlatformStore.class);
}
public TenantPlatformStore retrieveTenantPlatformStoreByTenantId(Long tenantId) {
return client.getSingle(ENDPOINT_TENANTS + "/platform/tenant/" + tenantId, TenantPlatformStore.class);
}
public void deleteTenantPlatformStoreByTenantId(long tenantId) {
client.delete(ENDPOINT_TENANTS + "/platform/tenant/" + tenantId);
}
public Tenant retrieveTenantByStoreId(String storeId, String platform) {
return client.getSingle(ENDPOINT_TENANTS + "/tenant/store/" + platform + "/" + storeId, Tenant.class);
}
public Tenant getTenantInfo() {
return client.getSingle( ENDPOINT_TENANTS+ "/info/", Tenant.class);
}
public List<TenantDetails> retrieveAllTenantDetails(TenantDetailsFilter filter) {
return client.getList(ENDPOINT_TENANTS_DETAILS + "?" + filter.createQuery(), TenantDetails.class);
}
public List<Tenant> retrieveAllTenants(){
return client.getList( ENDPOINT_TENANTS, Tenant.class );
}
public List<Tenant> retrieveAllTenants(final String domain){
return client.getList( ENDPOINT_TENANTS + "?domain=" + domain, Tenant.class );
}
public List<Tenant> searchTenants(TenantFilter filter) {
return client.getList( ENDPOINT_TENANTS + "/search?monitored=" + filter.getMonitored(), Tenant.class);
}
public List<Tenant> searchAllTenants() {
return client.getList( ENDPOINT_TENANTS + "/search/all", Tenant.class);
}
public Long insertTenant(Tenant tenant) {
return client.post(ENDPOINT_TENANTS, tenant);
}
public void updateTenant(long id, Tenant tenant) {
client.put(ENDPOINT_TENANTS + "/single/" + id, tenant);
}
public void updateTenantIntegration(TenantIntegration tenantIntegration) {
client.put(ENDPOINT_TENANTS + "/integration/", tenantIntegration);
}
public void updateHashXML(String hash) {
client.put(ENDPOINT_TENANTS + "/hash", hash);
}
public void updateFeedXMLHasUpdated(Boolean hasUpdated) {
client.post(ENDPOINT_TENANTS + "/xmlHasUpdated", hasUpdated);
}
public void deleteTenant(long id) {
client.delete(ENDPOINT_TENANTS + "/" + id);
}
public TenantDetails retrieveTenantDetails(long id) {
return client.getSingle(ENDPOINT_TENANTS + "/details/single/" + id, TenantDetails.class);
}
public void updateTenantDetails(TenantDetails tenantDetails) {
client.put(ENDPOINT_TENANTS + "/details/",tenantDetails);
}
public void updateTenantDetailsLogo(String tenantLogoUrl) {
client.put(ENDPOINT_TENANTS + "/details/logo/",tenantLogoUrl);
}
public void patchUpdateTenantBasicDetails(TenantBasicDetails tenantBasicDetails) {
client.patch(ENDPOINT_TENANTS_BASIC_DETAILS, tenantBasicDetails);
}
/*
* End tenant management
*/
/*
* Starting tenant management
*/
public List<MySizebayUser> attachedUsersToTenant(long id) {
return client.getList(ENDPOINT_TENANTS + "/" + id + "/users", MySizebayUser.class);
}
public void attachUserToTenant(long id, String email) {
client.getSingle(ENDPOINT_TENANTS + "/" + id + "/users/" + email);
}
public void detachUserToTenant(long id, String email) {
client.delete(ENDPOINT_TENANTS + "/" + id + "/users/" + email);
}
/*
* End tenant management
*/
/*
* Starting importation rules management
*/
public String retrieveImportRules(long id) {
return client.getSingle(ENDPOINT_TENANTS + "/" + id + "/rules", String.class);
}
public Long insertImportationRules(long id, ImportationRules rules) {
return client.post(ENDPOINT_TENANTS + "/" + id + "/rules", rules);
}
/*
* End importation rules management
*/
/*
* Starting my sizebay user management
*/
public MySizebayUser getMySizebayUser(String username){
return client.getSingle( "/users/" + username, MySizebayUser.class);
}
public Long insertMySizebayUser(MySizebayUser user){
return client.post("/users/", user);
}
public void updateMySizebayUser(Long userId, MySizebayUser user) {
client.put("/tenants/users/single/" + userId, user);
}
public void updatePasswordUser(Long userId, MySizebayUserResetPassword user) {
client.patch("/tenants/users/password/" + userId, user);
}
public void updateUserAcceptanceTerms(MySizebayUser user) {
client.post("/users/acceptance-terms/", user);
}
/*
* End my sizebay user management
*/
public void insertImportationSummary(long tenantId, ImportationSummary importationSummary) {
client.post( "/importations/tenantId/"+tenantId, importationSummary );
}
/*
* Starting product manipulation rules management
*/
public ProductManipulationRules retrieveProductManipulationRules() {
return client.getSingle(ENDPOINT_PRODUCT + "/manipulations/rules", ProductManipulationRules.class);
}
public void insertProductManipulationRules(ProductManipulationRules productManipulationRules) {
client.post(ENDPOINT_PRODUCT + "/manipulations/rules/single", productManipulationRules);
}
/*
* End product manipulation rules management
*/
} |
package sizebay.catalog.client;
import java.util.*;
import lombok.NonNull;
import sizebay.catalog.client.http.*;
import sizebay.catalog.client.model.*;
import sizebay.catalog.client.model.filters.*;
/**
* A Basic wrapper on generated Swagger client.
*
* @author Miere L. Teixeira
*/
public class CatalogAPI {
final static String
DEFAULT_BASE_URL = "https://catalogue.fitpeek.co/api/v1/",
ENDPOINT_DASHBOARD = "/dashboard",
ENDPOINT_BRAND = "/brands",
ENDPOINT_MODELING = "/modelings",
ENDPOINT_PRODUCT = "/products",
ENDPOINT_CATEGORIES = "/categories",
ENDPOINT_TENANTS = "/tenants",
ENDPOINT_TENANTS_DETAILS = "/tenants/details",
ENDPOINT_TENANTS_BASIC_DETAILS = "/tenants/details/basic",
ENDPOINT_USER = "/user",
ENDPOINT_SIZE_STYLE = "/style",
ENDPOINT_DEVOLUTION = "/devolution",
ENDPOINT_IMPORTATION_ERROR = "/importations",
ENDPOINT_STRONG_CATEGORY = "/categories/strong",
ENDPOINT_STRONG_SUBCATEGORY = "/categories/strong/sub",
ENDPOINT_STRONG_MODEL = "models/strong",
ENDPOINT_STRONG_MODELING = "/modelings/strong",
SEARCH_BY_TEXT = "/search/all?text=";
final RESTClient client;
/**
* Constructs the Catalog API.
*
* @param applicationToken
* @param securityToken
*/
public CatalogAPI(@NonNull String applicationToken, @NonNull String securityToken) {
this(DEFAULT_BASE_URL, applicationToken, securityToken);
}
/**
* Constructs the Catalog API.
*
* @param basePath
* @param applicationToken
* @param securityToken
*/
public CatalogAPI(@NonNull String basePath, @NonNull String applicationToken, @NonNull String securityToken) {
final CatalogAuthentication authentication = new CatalogAuthentication( applicationToken, securityToken );
final MimeType mimeType = new JSONMimeType();
client = new RESTClient( basePath, mimeType, authentication );
}
/**
* Starting dashboard management
*/
public List<Dashboard> retrieveDashboard() {
return client.getList(ENDPOINT_DASHBOARD, Dashboard.class);
}
public Dashboard retrieveDashboardByTenant(Long tenantId) {
return client.getSingle(ENDPOINT_DASHBOARD + "/single/" + tenantId, Dashboard.class);
}
/**
* End dashboard management
*/
public ProductBasicInformationToVFR retrieveProductBasicInformationToVFR(String permalink) {
return client.getSingle(ENDPOINT_PRODUCT + "/basic-info-to-vfr?"
+ "permalink=" + permalink, ProductBasicInformationToVFR.class);
}
/**
* Starting user profile management
*/
public void insertUser (UserProfile userProfile) {
client.post(ENDPOINT_USER, userProfile);
}
public UserProfile retrieveUser (String userId) {
return client.getSingle(ENDPOINT_USER + "/single/" + userId, UserProfile.class);
}
public UserProfile updateProfileName(ProfileUpdateName profileUpdateName){
return client.put( ENDPOINT_USER + "/update/profile/name", profileUpdateName, UserProfile.class);
}
public UserProfile retrieveUserByFacebook(String facebookToken) {
return client.getSingle(ENDPOINT_USER + "/social/facebook/" + facebookToken, UserProfile.class);
}
public UserProfile retrieveUserByGoogle(String googleToken) {
return client.getSingle(ENDPOINT_USER + "/social/google/" + googleToken, UserProfile.class);
}
public UserProfile retrieveUserByApple(String appleUserId) {
return client.getSingle(ENDPOINT_USER + "/social/apple/" + appleUserId, UserProfile.class);
}
public Profile retrieveProfile (long profileId) {
return client.getSingle(ENDPOINT_USER + "/profile/" + profileId, Profile.class);
}
public void updateUserFacebookToken(String userId, String facebookToken) {
client.put(ENDPOINT_USER + "/social/facebook/" + userId, facebookToken);
}
public void updateUserGoogleToken(String userId, String googleToken) {
client.put(ENDPOINT_USER + "/social/google/" + userId, googleToken);
}
public void updateUserAppleId(String userId, String appleUserId) {
client.put(ENDPOINT_USER + "/social/apple/" + userId, appleUserId);
}
public void insertProfile (Profile profile) {
client.post(ENDPOINT_USER + "/profile", profile);
}
public void deleteProfile (long profileId) { client.delete(ENDPOINT_USER + "/profile/" + profileId); }
/* User history */
public long insertProductInUserHistory(String userId, UserHistory newProductToUserHistory) {
return client.post(ENDPOINT_USER + "/history/single/"+ userId, newProductToUserHistory);
}
public List<UserHistory> retrieveUserHistory(int page, String userId) {
return client.getList(ENDPOINT_USER + "/history/all/" + userId + "?page=" + page, UserHistory.class);
}
public void deleteUserHistoryProduct(String userId, Long userHistoryId) {
client.delete(ENDPOINT_USER + "/history/single/" + userId + "?userHistoryId=" + userHistoryId);
}
/* User liked products */
public long insertLikeInTheProduct(String userId, LikedProduct likedProduct) {
return client.post(ENDPOINT_USER + "/liked-products/single/"+ userId, likedProduct);
}
public List<LikedProduct> retrieveLikedProductsByUser(int page, String userId) {
return client.getList(ENDPOINT_USER + "/liked-products/all/" + userId + "?page=" + page, LikedProduct.class);
}
public void deleteLikeInTheProduct(String userId, Long likedProductId) {
client.delete(ENDPOINT_USER + "/liked-products/single/" + userId + "?likedProductId=" + likedProductId);
}
/*
* End user profile management
*/
/*
* Starting size style management
*/
public List<SizeStyle> getSizeStyles(SizeStyleFilter filter) {
return client.getList(ENDPOINT_SIZE_STYLE + "?" + filter.createQuery(), SizeStyle.class);
}
public SizeStyle getSingleSizeStyle(long id) {
return client.getSingle(ENDPOINT_SIZE_STYLE + "/single/" + id, SizeStyle.class);
}
public long insertSizeStyle(SizeStyle sizeStyle) {
return client.post(ENDPOINT_SIZE_STYLE + "/single", sizeStyle);
}
public void updateWeightStyle(long id, SizeStyle sizeStyle) {
client.put(ENDPOINT_SIZE_STYLE + "/single/" + id, sizeStyle);
}
public void bulkUpdateWeight(BulkUpdateSizeStyle bulkUpdateSizeStyle) {
client.patch(ENDPOINT_SIZE_STYLE + "/bulk/weight", bulkUpdateSizeStyle);
}
public void bulkUpdateModeling(BulkUpdateSizeStyle bulkUpdateSizeStyle) {
client.patch(ENDPOINT_SIZE_STYLE + "/bulk/modeling", bulkUpdateSizeStyle);
}
public void deleteSizeStyle(long id) {
client.delete(ENDPOINT_SIZE_STYLE + "/single/" + id);
}
public void deleteSizeStyles(List<Integer> ids) {
client.delete(ENDPOINT_SIZE_STYLE + "/bulk/some", ids);
}
/*
* End size style management
*/
/*
* Starting devolution management
*/
public List<DevolutionError> retrieveDevolutionErrors() {
return client.getList(ENDPOINT_DEVOLUTION + "/errors", DevolutionError.class);
}
public List<DevolutionError> retrieveDevolutionErrors(DevolutionFilter filter) {
return client.getList(ENDPOINT_DEVOLUTION + "/errors?" + filter.createQuery(), DevolutionError.class);
}
public long insertDevolutionError(DevolutionError devolution) {
return client.post(ENDPOINT_DEVOLUTION + "/errors/single", devolution);
}
public void deleteDevolutionErrors() {
client.delete(ENDPOINT_DEVOLUTION + "/errors");
}
public DevolutionSummary retrieveDevolutionSummaryLastBy() {
return client.getSingle(ENDPOINT_DEVOLUTION + "/summary/last", DevolutionSummary.class);
}
public long insertDevolutionSummary(DevolutionSummary devolutionSummary) {
return client.post(ENDPOINT_DEVOLUTION + "/summary/single", devolutionSummary);
}
public void deleteDevolutionSummary() {
client.delete(ENDPOINT_DEVOLUTION + "/summary");
}
/*
* End devolution management
*/
/*
* Starting user (MySizebay) management
*/
public long insertTenantPlatformStore(TenantPlatformStore tenantPlatformStore) {
return client.post(ENDPOINT_TENANTS + "/platform/tenant", tenantPlatformStore);
}
public void updateTenantPlatformStore(Long tenantId, TenantPlatformStore tenantPlatformStore) {
client.put(ENDPOINT_TENANTS + "/platform/tenant/" + tenantId, tenantPlatformStore);
}
public UserTenants authenticateAndRetrieveUser(UserAuthenticationDTO userAuthentication) {
return client.post( "/users/authenticate/user", userAuthentication, UserTenants.class );
}
public List<Tenant> authenticateAndRetrieveTenants(String username, String password ) {
return client.getList( "/users/" + username + "/" + password + "/tenants", Tenant.class );
}
public List<UserTenants> retrieveAllUsersBy(String privilege) {
return client.getList( "/privileges/users?privilege=" + privilege, UserTenants.class );
}
/*
* End user (MySizebay) management
*/
/*
* Starting product management
*/
public List<Product> getProducts(int page) {
return client.getList(ENDPOINT_PRODUCT + "?page=" + page, Product.class);
}
public List<Product> getProducts(ProductFilter filter) {
return client.getList(ENDPOINT_PRODUCT + "/search/all" + "?" + filter.createQuery(), Product.class);
}
public Product getProduct(long id) {
return client.getSingle(ENDPOINT_PRODUCT + "/single/" + id, Product.class);
}
public Long getProductIdFromPermalink(String permalink){
return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id"
+ "?permalink=" + permalink,
Long.class);
}
public ProductCount retrieveProductCount() {
return client.getSingle(ENDPOINT_PRODUCT + "/count", ProductCount.class);
}
public ProductSlug retrieveProductSlugByPermalink(String permalink, String sizeLabel){
return client.getSingle(ENDPOINT_PRODUCT + "/slug"
+ "?permalink=" + permalink
+ "&size=" + sizeLabel,
ProductSlug.class);
}
public Long getAvailableProductIdFromPermalink(String permalink){
return client.getSingle(ENDPOINT_PRODUCT + "/search/product-id"
+ "?permalink=" + permalink
+ "&onlyAvailable=true",
Long.class);
}
public ProductIntegration retrieveProductIntegration(Long tenantId, String feedProductId) {
return client.getSingle(ENDPOINT_PRODUCT + "/search/feed-product-id"
+ "/" + tenantId
+ "/" + feedProductId,
ProductIntegration.class);
}
public ProductBasicInformation retrieveProductByBarcode(Long barcode) {
return client.getSingle(ENDPOINT_PRODUCT + "/search/barcode/" + barcode, ProductBasicInformation.class);
}
public ProductBasicInformation getProductBasicInfo(long id){
return client.getSingle(ENDPOINT_PRODUCT
+ "/" + id
+ "/basic-info",
ProductBasicInformation.class);
}
public ProductBasicInformation getProductBasicInfoFilterSizes(long id, String sizes){
return client.getSingle( ENDPOINT_PRODUCT
+ "/" + id
+ "/basic-info-filter-sizes"
+ "?sizes=" + sizes,
ProductBasicInformation.class);
}
public long insertProduct(Product product) {
return client.post(ENDPOINT_PRODUCT + "/single", product);
}
public void insertProductIntegration(ProductIntegration product) {
client.post(ENDPOINT_PRODUCT + "/single/integration", product);
}
public void insertProductIntegrationPlatform(ProductIntegration product) {
client.post(ENDPOINT_PRODUCT + "/single/integration/platform", product);
}
public long insertMockedProduct(String permalink) {
return client.post(ENDPOINT_PRODUCT + "/mock?permalink=" + permalink, String.class);
}
public void updateProduct(long id, Product product) {
client.put(ENDPOINT_PRODUCT + "/single/" + id, product);
}
public void updateProduct(long id, Product product, boolean isAutomaticUpdate) {
client.put(ENDPOINT_PRODUCT + "/single/" + id + "?isAutomaticUpdate=" + isAutomaticUpdate, product);
}
public void bulkUpdateProducts(BulkUpdateProducts products) {
client.patch(ENDPOINT_PRODUCT, products);
}
public void deleteProducts() {
client.delete(ENDPOINT_PRODUCT);
}
public void deleteProduct(long id) {
client.delete(ENDPOINT_PRODUCT + "/single/" + id);
}
public void deleteProductByFeedProductId(long feedProductId) {
client.delete(ENDPOINT_PRODUCT + "/single/feedProduct/" + feedProductId);
}
public void deleteProducts(List<Integer> ids) {
client.delete(ENDPOINT_PRODUCT + "/bulk/some", ids);
}
/*
* End product management
*/
/*
* Starting brand management
*/
public List<Brand> searchForBrands(String text){
return client.getList(ENDPOINT_BRAND + SEARCH_BY_TEXT + text, Brand.class);
}
public List<Brand> getBrands(BrandFilter filter) {
return client.getList(ENDPOINT_BRAND + "?" + filter.createQuery(), Brand.class);
}
public List<Brand> getBrands(int page) {
return client.getList(ENDPOINT_BRAND + "?page=" + page, Brand.class);
}
public List<Brand> getBrands(int page, String name) {
return client.getList(ENDPOINT_BRAND + "?page=" + page + "&name=" + name, Brand.class);
}
public Brand getBrand(long id) {
return client.getSingle(ENDPOINT_BRAND + "/single/" + id, Brand.class);
}
public long insertBrand(Brand brand) {
return client.post(ENDPOINT_BRAND + "/single", brand);
}
public void associateBrandsWithStrongBrand() {
client.getSingle(ENDPOINT_BRAND + "/sync/associate-brand-with-strong-brand");
}
public void createStrongBrandBasedOnBrands(List<Integer> ids) {
client.post(ENDPOINT_BRAND + "/sync/create-strong-brand", ids);
}
public void updateBrand(long id, Brand brand) {
client.put(ENDPOINT_BRAND + "/single/" + id, brand);
}
public void updateBulkBrandAssociation(BulkUpdateBrandAssociation bulkUpdateBrandAssociation) { client.patch(ENDPOINT_BRAND, bulkUpdateBrandAssociation); }
public void deleteBrands() {
client.delete(ENDPOINT_BRAND);
}
public void deleteBrand(long id) {
client.delete(ENDPOINT_BRAND + "/single/" + id);
}
public void deleteBrands(List<Integer> ids) {
client.delete(ENDPOINT_BRAND + "/bulk/some", ids);
}
/*
* End brand management
*/
/*
* Starting category management
*/
public List<Category> getCategories() {
return client.getList(ENDPOINT_CATEGORIES, Category.class);
}
public List<Category> getCategories(int page) {
return client.getList(ENDPOINT_CATEGORIES + "?page=" + page, Category.class);
}
public List<Category> getCategories(int page, String name) {
return client.getList(ENDPOINT_CATEGORIES + "?page=" + page + "&name=" + name, Category.class);
}
public List<Category> getCategories(CategoryFilter filter) {
return client.getList(ENDPOINT_CATEGORIES + "?" + filter.createQuery(), Category.class);
}
public List<Category> getCategories(String name) {
return client.getList(ENDPOINT_CATEGORIES + "/search?name=" + name,Category.class);
}
public List<Category> searchForCategories(CategoryFilter filter){
return client.getList(ENDPOINT_CATEGORIES + "/search/all?" + filter.createQuery(), Category.class);
}
public Category getCategory(long id) {
return client.getSingle(ENDPOINT_CATEGORIES + "/single/" + id, Category.class);
}
public long insertCategory(Category brand) {
return client.post(ENDPOINT_CATEGORIES + "/single", brand);
}
public void updateCategory(long id, Category brand) {
client.put(ENDPOINT_CATEGORIES + "/single/" +id, brand);
}
public void bulkUpdateCategories(BulkUpdateCategories categories) {
client.patch(ENDPOINT_CATEGORIES, categories);
}
public void deleteCategories() {
client.delete(ENDPOINT_CATEGORIES);
}
public void deleteCategory(long id) {
client.delete(ENDPOINT_CATEGORIES + "/single/" + id);
}
public void deleteCategories(List<Integer> ids) {
client.delete(ENDPOINT_CATEGORIES + "/bulk/some", ids);
}
/*
* End category management
*/
/*
* Starting modeling management
*/
public List<Modeling> searchForModelings(long brandId, String gender) {
return searchForModelings(String.valueOf(brandId), gender);
}
public List<Modeling> searchForModelings(String brandId, String gender){
return client.getList(ENDPOINT_MODELING + "/search/brand/" + brandId + "/gender/" + gender, Modeling.class);
}
public List<Modeling> getModelings(int page){
return client.getList(ENDPOINT_MODELING + "?page=" + page, Modeling.class);
}
public List<Modeling> getModelings(ModelingFilter filter) {
return client.getList(ENDPOINT_MODELING + "/search/all" + "?" + filter.createQuery(), Modeling.class);
}
public List<Modeling> getAllSimplifiedModeling() {
return client.getList(ENDPOINT_MODELING + "/simplified/all", Modeling.class);
}
public Modeling getSingleSimplifiedModeling(long id) {
return client.getSingle(ENDPOINT_MODELING + "/simplified/single/" + id, Modeling.class);
}
public Modeling getModeling(long id) {
return client.getSingle(ENDPOINT_MODELING + "/single/" + id, Modeling.class);
}
public long insertModeling(Modeling modeling) {
return client.post(ENDPOINT_MODELING + "/single", modeling);
}
public long insertModelingWithPopulationOfDomainsAutomatically(Modeling modeling) {
return client.post(ENDPOINT_MODELING + "/single/automatically", modeling);
}
public void updateModeling(long id, Modeling modeling) {
client.put(ENDPOINT_MODELING + "/single/" + id + "?force=false", modeling);
}
public void updateModeling(long id, Modeling modeling, boolean force) {
client.put(ENDPOINT_MODELING + "/single/" + id + "?force=" + force, modeling);
}
public void updateModelingWithPopulationOfDomainsAutomatically(long id, Modeling modeling) {
client.put(ENDPOINT_MODELING + "/single/" + id + "/automatically", modeling);
}
public void deleteModelings() {
client.delete(ENDPOINT_MODELING);
}
public void deleteModeling(long id) {
client.delete(ENDPOINT_MODELING + "/single/" + id);
}
public void deleteModelings(List<Integer> ids) {
client.delete(ENDPOINT_MODELING + "/bulk/some", ids);
}
/*
* End modeling management
*/
/*
* Starting importation error management
*/
public List<ImportationError> getImportationErrors(String page){
return client.getList(ENDPOINT_IMPORTATION_ERROR + "/errors?page=" + page, ImportationError.class);
}
public long insertImportationError(ImportationError importationError){
return client.post( ENDPOINT_IMPORTATION_ERROR + "/errors", importationError);
}
public void deleteImportationErrors() {
client.delete(ENDPOINT_PRODUCT + "/importation-errors/all");
}
public ImportationSummary getImportationSummary(){
return client.getSingle(ENDPOINT_IMPORTATION_ERROR + "/summary/last" , ImportationSummary.class);
}
public long insertImportationSummary(ImportationSummary importationSummary){
return client.post( ENDPOINT_IMPORTATION_ERROR + "/summary/single", importationSummary);
}
public void deleteImportationSummary() {
client.delete(ENDPOINT_IMPORTATION_ERROR);
}
/*
* End importation error management
*/
/*
* Starting strong brand management
*/
public List<StrongBrand> getStrongBrands(StrongBrandFilter filter) {
return client.getList(ENDPOINT_BRAND + "/strong?" + filter.createQuery(), StrongBrand.class);
}
public StrongBrand getSingleBrand(long id) {
return client.getSingle(ENDPOINT_BRAND + "/strong/single/" + id, StrongBrand.class);
}
public long insertStrongBrand(StrongBrand strongBrand){
return client.post( ENDPOINT_BRAND + "/strong/single", strongBrand);
}
public void updateStrongBrand(long id, StrongBrand strongBrand) {
client.put(ENDPOINT_BRAND + "/strong/single/" + id, strongBrand);
}
public void deleteStrongBrand(long id) {
client.delete(ENDPOINT_BRAND + "/strong/single/" + id);
}
public void deleteStrongBrands(List<Integer> ids) {
client.delete(ENDPOINT_BRAND + "/strong/bulk/some", ids);
}
/*
* End strong brand management
*/
/**
* Starting Strong brand Reports
*
*/
public List<ReportStrongBrandTenantsDetails> generateReportStrongBrand(Long strongBrandId, int page) {
return client.getList(ENDPOINT_BRAND + "/strong/reports?"+ "strongBrandId=" + strongBrandId + "&page=" + page, ReportStrongBrandTenantsDetails.class);
}
public StrongBrandCoverageProductsCounts generateStrongBrandCoverageProductsCounts(Long strongBrandId) {
return client.getSingle(ENDPOINT_BRAND + "/strong/reports/count?" + "strongBrandId=" + strongBrandId, StrongBrandCoverageProductsCounts.class);
}
/**
* End Strong brand Reports
*
*/
/*
* Starting strong category management
*/
public List<StrongCategory> getAllStrongCategories(){
return client.getList(ENDPOINT_STRONG_CATEGORY, StrongCategory.class);
}
public List<StrongCategory> getAllStrongCategories(String page, String categoryName, String type){
String condition;
condition = categoryName == null ? "" : "&name=" + categoryName;
condition += type == null ? "" : "&type=" + type;
return client.getList(ENDPOINT_STRONG_CATEGORY + "?page=" + page + condition, StrongCategory.class);
}
public StrongCategory getSingleStrongCategory(long id) {
return client.getSingle(ENDPOINT_STRONG_CATEGORY + "/single/" + id, StrongCategory.class);
}
public long insertStrongCategory(StrongCategory strongCategory){
return client.post(ENDPOINT_STRONG_CATEGORY + "/single", strongCategory);
}
public void updateStrongCategory(long id, StrongCategory strongCategory) {
client.put(ENDPOINT_STRONG_CATEGORY + "/single/" + id, strongCategory);
}
public void deleteStrongCategory(long id) {
client.delete(ENDPOINT_STRONG_CATEGORY + "/single/" + id);
}
/*
* End strong category management
*/
/*
* Starting strong subcategory management
*/
public List<StrongSubcategory> getStrongSubcategories(StrongSubcategoryFilter filter){
return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?" + filter.createQuery(), StrongSubcategory.class);
}
public List<StrongSubcategory> getStrongSubcategories(int page){
return client.getList(ENDPOINT_STRONG_SUBCATEGORY + "?page=" + page, StrongSubcategory.class);
}
public StrongSubcategory getSingleStrongSubcategory(long id) {
return client.getSingle(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, StrongSubcategory.class);
}
public long insertStrongSubcategory(StrongSubcategory strongSubcategory){
return client.post(ENDPOINT_STRONG_SUBCATEGORY + "/single", strongSubcategory);
}
public void updateStrongSubcategory(long id, StrongSubcategory strongSubcategory) {
client.put(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id, strongSubcategory);
}
public void deleteStrongSubcategory(long id) {
client.delete(ENDPOINT_STRONG_SUBCATEGORY + "/single/" + id);
}
/*
* End strong subcategory management
*/
/*
* Starting strong model management
*/
public List<StrongModel> getAllStrongModels(String page){
return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page, StrongModel.class);
}
public List<StrongModel> getAllStrongModels(String page, String modelName){
return client.getList(ENDPOINT_STRONG_MODEL + "?page=" + page + "&name=" + modelName, StrongModel.class);
}
public StrongModel getSingleStrongModel(long id) {
return client.getSingle(ENDPOINT_STRONG_MODEL + "/single/" + id, StrongModel.class);
}
public long insertStrongModel(StrongModel strongModel){
return client.post(ENDPOINT_STRONG_MODEL + "/single", strongModel);
}
public void updateStrongModel(long id, StrongModel strongModel) {
client.put(ENDPOINT_STRONG_MODEL + "/single/" + id, strongModel);
}
public void deleteStrongModel(long id) {
client.delete(ENDPOINT_STRONG_MODEL + "/single/" + id);
}
/*
* End strong model management
*/
/*
* Starting strong modeling management
*/
public List<StrongModeling> getStrongModelings(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "?" + filter.createQuery(), StrongModeling.class);
}
public List<Long> retrieveAllOrganicTableIds(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "/organic/ids" , Long.class);
}
public StrongModeling getSingleStrongModeling(long id) {
return client.getSingle(ENDPOINT_STRONG_MODELING + "/single/" + id, StrongModeling.class);
}
public List<StrongModeling> getAllSimplifiedStrongModelings(StrongModelingFilter filter) {
return client.getList(ENDPOINT_STRONG_MODELING + "/simplified" + "?" + filter.createQuery(), StrongModeling.class);
}
public long insertStrongModeling(StrongModeling strongModeling){
return client.post(ENDPOINT_STRONG_MODELING + "/single", strongModeling);
}
public void createStrongModelingsBasedOnBrands(String sizeSystem, List<Integer> ids) {
client.post(ENDPOINT_STRONG_MODELING + "/sync/create-strong-modelings?sizeSystem=" + sizeSystem, ids);
}
public void syncStrongModelingsWithSlugs() {
client.post(ENDPOINT_STRONG_MODELING + "/sync", null);
}
public void updateStrongModeling(long id, StrongModeling strongModeling) {
client.put(ENDPOINT_STRONG_MODELING + "/single/" + id, strongModeling);
}
public void deleteStrongModeling(long id) {
client.delete(ENDPOINT_STRONG_MODELING + "/single/" + id);
}
public void deleteStrongModelings(List<Integer> ids) {
client.delete(ENDPOINT_STRONG_MODELING + "/bulk/some", ids);
}
/*
* End strong modeling management
*/
/*
* Starting tenant management
*/
public Tenant getTenant( String appToken ){
return client.getSingle( ENDPOINT_TENANTS+ "/single/" + appToken, Tenant.class );
}
public void updateTenantStatus(TenantStatus tenantStatus) {
client.put(ENDPOINT_TENANTS + "/status", tenantStatus);
}
public Tenant getTenant( Long tenantId ) {
return client.getSingle( ENDPOINT_TENANTS+ "/single/" + tenantId, Tenant.class );
}
public void inactivateTenant() {
client.put(ENDPOINT_TENANTS + "/inactivate", null);
}
public TenantPlatformStore retrieveTenantPlatformStoreByStoreId(String storeId, String platform) {
return client.getSingle(ENDPOINT_TENANTS + "/platform/store/" + platform + "/" + storeId, TenantPlatformStore.class);
}
public TenantPlatformStore retrieveTenantPlatformStoreByTenantId(Long tenantId) {
return client.getSingle(ENDPOINT_TENANTS + "/platform/tenant/" + tenantId, TenantPlatformStore.class);
}
public void deleteTenantPlatformStoreByTenantId(long tenantId) {
client.delete(ENDPOINT_TENANTS + "/platform/tenant/" + tenantId);
}
public Tenant retrieveTenantByStoreId(String storeId, String platform) {
return client.getSingle(ENDPOINT_TENANTS + "/tenant/store/" + platform + "/" + storeId, Tenant.class);
}
public Tenant getTenantInfo() {
return client.getSingle( ENDPOINT_TENANTS+ "/info/", Tenant.class);
}
public List<TenantDetails> retrieveAllTenantDetails(TenantDetailsFilter filter) {
return client.getList(ENDPOINT_TENANTS_DETAILS + "?" + filter.createQuery(), TenantDetails.class);
}
public List<Tenant> retrieveAllTenants(){
return client.getList( ENDPOINT_TENANTS, Tenant.class );
}
public List<Tenant> retrieveAllTenants(final String domain){
return client.getList( ENDPOINT_TENANTS + "?domain=" + domain, Tenant.class );
}
public List<Tenant> searchTenants(TenantFilter filter) {
return client.getList( ENDPOINT_TENANTS + "/search?monitored=" + filter.getMonitored(), Tenant.class);
}
public List<Tenant> searchAllTenants() {
return client.getList( ENDPOINT_TENANTS + "/search/all", Tenant.class);
}
public Long insertTenant(Tenant tenant) {
return client.post(ENDPOINT_TENANTS, tenant);
}
public void updateTenant(long id, Tenant tenant) {
client.put(ENDPOINT_TENANTS + "/single/" + id, tenant);
}
public void updateTenantIntegration(TenantIntegration tenantIntegration) {
client.put(ENDPOINT_TENANTS + "/integration/", tenantIntegration);
}
public void updateHashXML(String hash) {
client.put(ENDPOINT_TENANTS + "/hash", hash);
}
public void updateFeedXMLHasUpdated(Boolean hasUpdated) {
client.post(ENDPOINT_TENANTS + "/xmlHasUpdated", hasUpdated);
}
public void deleteTenant(long id) {
client.delete(ENDPOINT_TENANTS + "/" + id);
}
public TenantDetails retrieveTenantDetails(long id) {
return client.getSingle(ENDPOINT_TENANTS + "/details/single/" + id, TenantDetails.class);
}
public void updateTenantDetails(TenantDetails tenantDetails) {
client.put(ENDPOINT_TENANTS + "/details/",tenantDetails);
}
public void updateTenantDetailsBasic(TenantDetailsBasic tenantDetailsBasic) {
client.put(ENDPOINT_TENANTS + "/details/basic", tenantDetailsBasic);
}
public void updateTenantDetailsLogo(String tenantLogoUrl) {
client.put(ENDPOINT_TENANTS + "/details/logo/",tenantLogoUrl);
}
public void patchUpdateTenantBasicDetails(TenantBasicDetails tenantBasicDetails) {
client.patch(ENDPOINT_TENANTS_BASIC_DETAILS, tenantBasicDetails);
}
/*
* End tenant management
*/
/*
* Starting tenant management
*/
public List<MySizebayUser> attachedUsersToTenant(long id) {
return client.getList(ENDPOINT_TENANTS + "/" + id + "/users", MySizebayUser.class);
}
public void attachUserToTenant(long id, String email) {
client.getSingle(ENDPOINT_TENANTS + "/" + id + "/users/" + email);
}
public void detachUserToTenant(long id, String email) {
client.delete(ENDPOINT_TENANTS + "/" + id + "/users/" + email);
}
/*
* End tenant management
*/
/*
* Starting importation rules management
*/
public String retrieveImportRules(long id) {
return client.getSingle(ENDPOINT_TENANTS + "/" + id + "/rules", String.class);
}
public Long insertImportationRules(long id, ImportationRules rules) {
return client.post(ENDPOINT_TENANTS + "/" + id + "/rules", rules);
}
/*
* End importation rules management
*/
/*
* Starting my sizebay user management
*/
public MySizebayUser getMySizebayUser(String username){
return client.getSingle( "/users/" + username, MySizebayUser.class);
}
public Long insertMySizebayUser(MySizebayUser user){
return client.post("/users/", user);
}
public Long insertMySizebayUserCS(MySizebayUser user){
return client.post("/users/cs", user);
}
public void deleteMySizebayUser(Long userId) {
client.delete("/users/" + userId);
}
public void updateMySizebayUser(Long userId, MySizebayUser user) {
client.put("/tenants/users/single/" + userId, user);
}
public void updatePasswordUser(Long userId, MySizebayUserResetPassword user) {
client.patch("/tenants/users/password/" + userId, user);
}
public void updateUserAcceptanceTerms(UserTerms userTerms) {
client.patch("/user-terms/acceptance/", userTerms);
}
public UserTerms retrieveUseTerms(Long userId){
return client.getSingle( "/user-terms/" + userId, UserTerms.class);
}
/*
* End my sizebay user management
*/
public void insertImportationSummary(long tenantId, ImportationSummary importationSummary) {
client.post( "/importations/tenantId/"+tenantId, importationSummary );
}
/*
* Starting product manipulation rules management
*/
public ProductManipulationRules retrieveProductManipulationRules() {
return client.getSingle(ENDPOINT_PRODUCT + "/manipulations/rules", ProductManipulationRules.class);
}
public void insertProductManipulationRules(ProductManipulationRules productManipulationRules) {
client.post(ENDPOINT_PRODUCT + "/manipulations/rules/single", productManipulationRules);
}
/*
* End product manipulation rules management
*/
} |
package team.unstudio.udpl.util;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public interface ChatUtils {
static String SPLITTER = translateColorCodes("&l&m
static char DEFAULT_COLOR_CHAR = '&';
static void sendSplitter(Player player){
player.sendMessage(SPLITTER);
}
static void sendEmpty(Player player){
player.sendMessage("");
}
static String translateColorCodes(String textToTranslate){
return ChatColor.translateAlternateColorCodes(DEFAULT_COLOR_CHAR, textToTranslate);
}
} |
package watodo.logic.commands;
import java.util.List;
import java.util.Set;
import watodo.logic.commands.exceptions.CommandException;
import watodo.model.tag.UniqueTagList;
import watodo.model.task.Name;
import watodo.model.task.Priority;
import watodo.model.task.ReadOnlyTask;
import watodo.model.task.Status;
import watodo.model.task.Task;
import watodo.model.task.Time;
import watodo.model.task.UniqueTaskList.TaskNotFoundException;
//@@author A0164393Y
/**
* Finds and lists all tasks in task manager whose name contains any of the
* argument keywords. Keyword matching is case sensitive.
*/
public class MarkCommand extends Command {
public static final String COMMAND_WORD = "mark";
public static final String MESSAGE_INVALID_TASK = "This task is missing in the task manager.";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Marks the task completed or not completed \n"
+ "Parameters: KEYWORD [MORE_KEYWORDS]...\n" + "Example: " + COMMAND_WORD
+ " task_number completed OR not_completed";
public static final String MESSAGE_SUCCESS = "Marked task: %1$s";
private final Set<String> keywords;
public MarkCommand(Set<String> keywords) {
this.keywords = keywords;
}
@Override
public CommandResult execute() throws CommandException {
List<ReadOnlyTask> lastShownList = model.getFilteredTaskList();
String[] parameters = keywords.toArray(new String[keywords.size()]);
int filteredTaskListIndex = Integer.parseInt(parameters[0]) - 1;
ReadOnlyTask taskToEdit;
if (filteredTaskListIndex < lastShownList.size() && filteredTaskListIndex != -1)
taskToEdit = lastShownList.get(filteredTaskListIndex);
else
throw new CommandException(MESSAGE_INVALID_TASK);
Task editedTask = createEditedTask(taskToEdit, parameters[1]);
//@@author A0119505J
try {
model.markTask(filteredTaskListIndex, editedTask);
} catch (TaskNotFoundException e) {
throw new CommandException(MESSAGE_INVALID_TASK);
}
return new CommandResult(String.format(MESSAGE_SUCCESS, editedTask));
}
/**
* Creates and returns a {@code Task} with the details of {@code taskToEdit}
* edited with {@code editTaskDescriptor}.
*/
private static Task createEditedTask(ReadOnlyTask taskToEdit, String status) {
assert taskToEdit != null;
int flag;
if (status.equals("completed")) {
flag = 1;
} else {
flag = 0;
}
Status stat = new Status(flag);
Name updatedName = taskToEdit.getName();
Time updatedEndTime = taskToEdit.getEndTime();
Time updatedStartTime = taskToEdit.getStartTime();
Status updatedStatus = stat;
Priority updatedPriority = taskToEdit.getPriority();
UniqueTagList updatedTags = taskToEdit.getTags();
return new Task(updatedName, updatedStartTime, updatedEndTime, updatedPriority, updatedTags, updatedStatus);
}
} |
package xyz.rc24.bot.commands.wii;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.commons.waiter.EventWaiter;
import com.jagrosh.jdautilities.menu.ButtonMenu;
import com.jagrosh.jdautilities.menu.Paginator;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.Event;
import net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent;
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent;
import net.dv8tion.jda.api.exceptions.PermissionException;
import xyz.rc24.bot.Bot;
import xyz.rc24.bot.commands.Categories;
import xyz.rc24.bot.core.entities.CodeType;
import xyz.rc24.bot.core.entities.GuildSettings;
import xyz.rc24.bot.database.CodeDataManager;
import xyz.rc24.bot.utils.FormatUtil;
import xyz.rc24.bot.utils.SearcherUtil;
import java.sql.Time;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Artuto
*/
public class CodeCmd extends Command
{
private final Bot bot;
private final CodeDataManager dataManager;
private final EventWaiter waiter;
private final Pattern FULL_PATTERN = Pattern.compile("(\\w+)\\s+(.+?)\\s+((?:\\d{4}|SW)[-\\s]\\d{4}[-\\s]\\d{4}(?:[-\\s]\\d{4})?|\\w+)$", Pattern.MULTILINE); // thanks Dismissed
private final Pattern REMOVE_PATTERN = Pattern.compile("(\\w+)\\s+(.+?)$", Pattern.MULTILINE);
public CodeCmd(Bot bot)
{
this.bot = bot;
this.dataManager = bot.getCodeDataManager();
this.waiter = bot.waiter;
this.name = "code";
this.help = "Manages friend codes for the user.";
this.children = new Command[]{new AddCmd(), new EditCmd(), new HelpCmd(), new LookupCmd(), new RemoveCmd()};
this.category = Categories.WII;
this.guildOnly = false;
}
@Override
protected void execute(CommandEvent event)
{
event.replyError("Please enter a valid option for the command.\n" +
"Valid subcommands: `add`, `edit`, `remove`, `lookup`, `help`.");
}
private class AddCmd extends Command
{
AddCmd()
{
this.name = "add";
this.help = "Adds a code.";
this.category = Categories.WII;
}
@Override
protected void execute(CommandEvent event)
{
GuildSettings gs = event.getClient().getSettingsFor(event.getGuild());
List<String> args = parseArgs(FULL_PATTERN, event.getArgs());
if(args.size() < 3)
{
event.replyError("Wrong format! Correct one is `" + gs.getFirstPrefix() + "code add <type> <name> <code>`");
return;
}
CodeType type = CodeType.fromCode(args.get(0));
if(type == CodeType.UNKNOWN)
{
event.replyError(FormatUtil.getCodeTypes());
return;
}
Map<String, String> codeTypes = bot.getCore().getCodesForType(type, event.getAuthor().getIdLong());
if(codeTypes.containsKey(args.get(1)))
{
event.replyWarning("You already added this code!");
return;
}
if(dataManager.addCode(type, event.getAuthor().getIdLong(), args.get(2), args.get(1)))
event.replySuccess("Added a code for `" + args.get(1) + "`");
else
event.replyError("Error whilst adding a code! Please contact a developer.");
}
}
private class EditCmd extends Command
{
EditCmd()
{
this.name = "edit";
this.help = "Edits codes.";
this.category = Categories.WII;
this.botPermissions = new Permission[]{Permission.MESSAGE_EMBED_LINKS};
}
@Override
protected void execute(CommandEvent event)
{
GuildSettings gs = event.getClient().getSettingsFor(event.getGuild());
List<String> args = parseArgs(FULL_PATTERN, event.getArgs());
if(args.size() < 3)
{
event.replyError("Wrong format! Correct one is `" + gs.getFirstPrefix() + "code edit <type> <name> <code>`");
return;
}
CodeType type = CodeType.fromCode(args.get(0));
if(type == CodeType.UNKNOWN)
{
event.replyError(FormatUtil.getCodeTypes());
return;
}
Map<String, String> codeTypes = bot.getCore().getCodesForType(type, event.getAuthor().getIdLong());
if(!(codeTypes.containsKey(args.get(1))))
{
event.replyWarning("A code for `" + args.get(1) + "` is not registered.");
return;
}
if(dataManager.editCode(type, event.getAuthor().getIdLong(), args.get(2), args.get(1)))
event.replySuccess("Edited the code for `" + args.get(1) + "`");
else
event.replyError("Error whilst editing a code! Please contact a developer.");
}
}
private class HelpCmd extends Command
{
HelpCmd()
{
this.name = "help";
this.help = "Shows help regarding codes.";
this.category = Categories.WII;
this.guildOnly = false;
}
@Override
protected void execute(CommandEvent event)
{
String prefix = bot.getPrefix(event.getGuild());
String help = "**__Using the bot__**\n\n" +
"**Adding Wii:**\n" + "`" + prefix + "code add wii Wii Name Goes here 1234-5678-9012-3456`\n" +
"**Adding games:**\n `" + prefix + "code add game Game Name 1234-5678-9012`\n" +
"and many more types! Run `" + prefix + "code add` " +
"to see all supported code types right now, such as the 3DS, PlayStation 4 and Switch.\n\n" +
"**Editing codes**\n" + "`" + prefix + "code edit type Name 1234-5678-9012-3456`\n\n" +
"**Removing codes**\n" + "`" + prefix + "code remove type Name`\n\n" +
"**Looking up codes**\n" + "`" + prefix + "code lookup @user`\n\n" +
"**Adding a user's Wii**\n" + "`" + prefix + "add @user`\n" + "This will send you their wii, and then DM them your Wii/game wii.";
event.replyInDm(help, (success) -> event.reactSuccess(), (failure) -> event.replyError("Hey, " + event.getAuthor().getAsMention() +
": I couldn't DM you. Make sure your DMs are enabled."));
}
}
private class LookupCmd extends Command
{
private final String BACK = "↩";
private final Consumer<Message> finalAction = (message) ->
{
try
{
message.clearReactions().queue();
}
catch(PermissionException ignored)
{
message.delete().queue();
}
};
LookupCmd()
{
this.name = "lookup";
this.help = "Displays codes for the user.";
this.category = Categories.WII;
this.botPermissions = new Permission[]{Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_ADD_REACTION};
}
@Override
protected void execute(CommandEvent event)
{
Member member = SearcherUtil.findMember(event, event.getArgs());
if(member == null)
return;
Paginator.Builder codePaginator = new Paginator.Builder()
.setEventWaiter(waiter)
.showPageNumbers(true)
.setTimeout(5, TimeUnit.MINUTES)
.setColumns(2)
.setFinalAction(finalAction);
if(!(displayTypeSelector(event, member, null, codePaginator)))
return;
String flag = bot.getCore().getFlag(member.getUser().getIdLong());
boolean hasFlag = !(flag.isEmpty());
if(hasFlag)
codePaginator.setTitle("Country: " + flag);
}
private boolean displayTypeSelector(CommandEvent event, Member member, Message message, Paginator.Builder codePaginator)
{
ButtonMenu.Builder typeMenu = new ButtonMenu.Builder()
.setEventWaiter(waiter)
.setTimeout(5, TimeUnit.MINUTES)
.setDescription("Please select a code type:")
.setFinalAction(finalAction)
.setUsers(member.getUser(), event.getAuthor())
.setColor(member.getColor());
boolean hasCodes = false;
Map<CodeType, Map<String, String>> userCodes = bot.getCore().getAllCodes(member.getUser().getIdLong());
for(Map.Entry<CodeType, Map<String, String>> codeType : userCodes.entrySet())
{
Map<String, String> codes = codeType.getValue();
if(codes.isEmpty())
continue;
// Discord only cares about the emote ID, so we just pass "a" as the name
typeMenu.addChoice("a:" + codeType.getKey().getEmote());
hasCodes = true;
}
if(!(hasCodes))
{
event.replyError("**" + member.getEffectiveName() + "** has not added any codes!");
return false;
}
typeMenu.setAction((msg, emote) ->
{
CodeType codeType = CodeType.fromEmote(emote.getId());
if(codeType == CodeType.UNKNOWN)
return;
displayCodes(event, msg, member, codeType, userCodes.get(codeType), codePaginator);
codePaginator.setUsers(member.getUser(), event.getAuthor())
.setColor(member.getColor());
});
if(message == null)
event.reply("Profile for **" + member.getEffectiveName() + "**", m -> typeMenu.build().display(m));
else
typeMenu.build().display(message);
return true;
}
private void displayCodes(CommandEvent event, Message message, Member member, CodeType codeType, Map<String, String> codes, Paginator.Builder codePaginator)
{
for(Map.Entry<String, String> entry : codes.entrySet())
codePaginator.addItems(FormatUtil.getCodeLayout(entry.getKey(), entry.getValue()));
codePaginator.setText(codeType.getFormattedName() + " codes for **" + member.getEffectiveName() + "**");
codePaginator.setAuthor("Profile for " + member.getEffectiveName(), member.getUser().getEffectiveAvatarUrl());
codePaginator.build().display(message);
handleBackButton(event, message, event.getMember(), member);
}
private void handleBackButton(CommandEvent cevent, Message message, Member... allowed)
{
waiter.waitForEvent(GuildMessageReactionAddEvent.class, event ->
{
if(!(event.getMessageIdLong() == message.getIdLong()))
return false;
if(!(event.getReactionEmote().isEmoji()))
return false;
if(event.getMember().getUser().isBot())
return false;
if(!(Arrays.asList(allowed).contains(event.getMember())))
return false;
return event.getReactionEmote().getName().equals(BACK);
}, event ->
{
try
{
Member member = allowed[1];
message.editMessage("Profile for **" + member.getEffectiveName() + "**").queue();
message.clearReactions().queue(s ->
{
Paginator.Builder codePaginator = new Paginator.Builder()
.setEventWaiter(waiter)
.showPageNumbers(true)
.setTimeout(5, TimeUnit.MINUTES)
.setColumns(2)
.setFinalAction(finalAction)
.setUsers(member.getUser(), allowed[0].getUser())
.setColor(member.getColor());
String flag = bot.getCore().getFlag(member.getUser().getIdLong());
boolean hasFlag = !(flag.isEmpty());
if(hasFlag)
codePaginator.setTitle("Country: " + flag);
displayTypeSelector(cevent, member, message, codePaginator);
}, e -> {});
}
catch(PermissionException ignored) {}
}, 5, TimeUnit.MINUTES, () -> finalAction.accept(message));
message.addReaction(BACK).queueAfter(1, TimeUnit.SECONDS);
}
}
private class RemoveCmd extends Command
{
RemoveCmd()
{
this.name = "remove";
this.help = "Removes a code.";
this.category = Categories.WII;
}
@Override
protected void execute(CommandEvent event)
{
GuildSettings gs = event.getClient().getSettingsFor(event.getGuild());
List<String> args = parseArgs(REMOVE_PATTERN, event.getArgs());
if(args.size() < 2)
{
event.replyError("Wrong format! Correct one is `" + gs.getFirstPrefix() + "code remove <type> <name>`");
return;
}
CodeType type = CodeType.fromCode(args.get(0));
if(type == CodeType.UNKNOWN)
{
event.replyError(FormatUtil.getCodeTypes());
return;
}
Map<String, String> codeTypes = bot.getCore().getCodesForType(type, event.getAuthor().getIdLong());
if(!(codeTypes.containsKey(args.get(1))))
{
event.replyWarning("A code for `" + args.get(1) + "` is not registered.");
return;
}
if(dataManager.removeCode(type, event.getAuthor().getIdLong(), args.get(1)))
event.replySuccess("Removed the code for `" + args.get(1) + "`");
else
event.replyError("Error whilst removing a code! Please contact a developer.");
}
}
private List<String> parseArgs(Pattern pattern, String args)
{
Matcher m = pattern.matcher(args);
List<String> list = new LinkedList<>();
while(m.find())
{
for(int i = 0; i <= m.groupCount(); i++)
{
if(!(m.group(i).trim().equals(args)))
list.add(m.group(i).trim());
}
}
return list;
}
} |
package sam.tictactoe;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
public class MulticastDiscoveryThread extends Thread{
protected DatagramSocket socket = null;
private long FIVE_SECONDS = 5000;
private int LISTEN_TIMEOUT = 3000;
public ArrayBlockingQueue<String> queue;
public MulticastDiscoveryThread() throws IOException {
super("MulticastDiscoveryThread");
queue = new ArrayBlockingQueue<String>(128, true);
}
public void run() {
String target = "";
try {
target = listen();
} catch( IOException e) {
System.out.println("Network Error");
}
try {
queue.put(target);
} catch(InterruptedException e) {
System.out.println("Queue Error");
}
if(target.equals("")) {
try {
bcast();
} catch( IOException e) {
System.out.println("Network Error");
}
}
}
/**
* Repeatedly transmits local IP ad infinitum
* @throws IOException
*/
public void bcast() throws IOException {
try {
socket = new DatagramSocket(35035);
} catch(SocketException e) {
System.out.println("Socket error");
}
boolean waiting = true;
while (waiting) {
try {
// Get current internet address
String dString = getHostAddresses()[0];
byte[] buf = dString.getBytes();
// send it
InetAddress group = InetAddress.getByName("230.0.0.1");
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
socket.send(packet);
//Check for termination command
if(queue.poll() != null) {
socket.close();
return;
}
// sleep for a while
try {
sleep((long)(Math.random() * FIVE_SECONDS));
} catch (InterruptedException e) { }
} catch (IOException e) {
e.printStackTrace();
waiting = false;
}
}
socket.close();
}
/**
* Listens for broadcasting hosts, returns IP address
* @return IP address of broadcasting host, as String
* @throws IOException
*/
public String listen() throws IOException {
MulticastSocket socket = new MulticastSocket(4446);
InetAddress address = InetAddress.getByName("230.0.0.1");
socket.joinGroup(address);
DatagramPacket packet;
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.setSoTimeout(LISTEN_TIMEOUT);
String received = "";
try {
socket.receive(packet);
received = new String(packet.getData(), 0, packet.getLength());
} catch(SocketTimeoutException e){
//Don't need to do anything
}
socket.leaveGroup(address);
socket.close();
return received;
}
private String[] getHostAddresses() {
Set<String> HostAddresses = new HashSet<>();
try {
for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
if (!ni.isLoopback() && ni.isUp() && ni.getHardwareAddress() != null) {
for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
if (ia.getBroadcast() != null) { //If limited to IPV4
HostAddresses.add(ia.getAddress().getHostAddress());
}
}
}
}
} catch (SocketException e) { }
return HostAddresses.toArray(new String[0]);
}
} |
package org.luaj.vm2.compiler;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LoadState;
import org.luaj.vm2.LocVars;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Prototype;
/** Class to dump a {@link Prototype} into an output stream, as part of compiling.
* <p>
* Generally, this class is not used directly, but rather indirectly via a command
* line interface tool such as {@link luac}.
* <p>
* A lua binary file is created via {@link DumpState#dump}:
* <pre> {@code
* Globals globals = JsePlatform.standardGlobals();
* Prototype p = globals.compilePrototype(new StringReader("print('hello, world')"), "main.lua");
* ByteArrayOutputStream o = new ByteArrayOutputStream();
* DumpState.dump(p, o, false);
* byte[] lua_binary_file_bytes = o.toByteArray();
* } </pre>
*
* The {@link LoadState} may be used directly to undump these bytes:
* <pre> {@code
* Prototypep = LoadState.instance.undump(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua");
* LuaClosure c = new LuaClosure(p, globals);
* c.call();
* } </pre>
*
*
* More commonly, the {@link Globals#undumper} may be used to undump them:
* <pre> {@code
* Prototype p = globals.loadPrototype(new ByteArrayInputStream(lua_binary_file_bytes), "main.lua", "b");
* LuaClosure c = new LuaClosure(p, globals);
* c.call();
* } </pre>
*
* @see luac
* @see LoadState
* @see Globals
* @see Prototype
*/
public class DumpState {
/** set true to allow integer compilation */
public static boolean ALLOW_INTEGER_CASTING = false;
/** format corresponding to non-number-patched lua, all numbers are floats or doubles */
public static final int NUMBER_FORMAT_FLOATS_OR_DOUBLES = 0;
/** format corresponding to non-number-patched lua, all numbers are ints */
public static final int NUMBER_FORMAT_INTS_ONLY = 1;
/** format corresponding to number-patched lua, all numbers are 32-bit (4 byte) ints */
public static final int NUMBER_FORMAT_NUM_PATCH_INT32 = 4;
/** default number format */
public static final int NUMBER_FORMAT_DEFAULT = NUMBER_FORMAT_FLOATS_OR_DOUBLES;
// header fields
private boolean IS_LITTLE_ENDIAN = true;
private int NUMBER_FORMAT = NUMBER_FORMAT_DEFAULT;
private int SIZEOF_LUA_NUMBER = 8;
private static final int SIZEOF_INT = 4;
private static final int SIZEOF_SIZET = 4;
private static final int SIZEOF_INSTRUCTION = 4;
DataOutputStream writer;
boolean strip;
int status;
public DumpState(OutputStream w, boolean strip) {
this.writer = new DataOutputStream( w );
this.strip = strip;
this.status = 0;
}
void dumpBlock(final byte[] b, int size) throws IOException {
writer.write(b, 0, size);
}
void dumpChar(int b) throws IOException {
writer.write( b );
}
void dumpInt(int x) throws IOException {
if ( IS_LITTLE_ENDIAN ) {
writer.writeByte(x&0xff);
writer.writeByte((x>>8)&0xff);
writer.writeByte((x>>16)&0xff);
writer.writeByte((x>>24)&0xff);
} else {
writer.writeInt(x);
}
}
void dumpString(LuaString s) throws IOException {
final int len = s.len().toint();
dumpInt( len+1 );
s.write( writer, 0, len );
writer.write( 0 );
}
void dumpDouble(double d) throws IOException {
long l = Double.doubleToLongBits(d);
if ( IS_LITTLE_ENDIAN ) {
dumpInt( (int) l );
dumpInt( (int) (l>>32) );
} else {
writer.writeLong(l);
}
}
void dumpCode( final Prototype f ) throws IOException {
final int[] code = f.code;
int n = code.length;
dumpInt( n );
for ( int i=0; i<n; i++ )
dumpInt( code[i] );
}
void dumpConstants(final Prototype f) throws IOException {
final LuaValue[] k = f.k;
int i, n = k.length;
dumpInt(n);
for (i = 0; i < n; i++) {
final LuaValue o = k[i];
switch ( o.type() ) {
case LuaValue.TNIL:
writer.write(LuaValue.TNIL);
break;
case LuaValue.TBOOLEAN:
writer.write(LuaValue.TBOOLEAN);
dumpChar(o.toboolean() ? 1 : 0);
break;
case LuaValue.TNUMBER:
switch (NUMBER_FORMAT) {
case NUMBER_FORMAT_FLOATS_OR_DOUBLES:
writer.write(LuaValue.TNUMBER);
dumpDouble(o.todouble());
break;
case NUMBER_FORMAT_INTS_ONLY:
if ( ! ALLOW_INTEGER_CASTING && ! o.isint() )
throw new java.lang.IllegalArgumentException("not an integer: "+o);
writer.write(LuaValue.TNUMBER);
dumpInt(o.toint());
break;
case NUMBER_FORMAT_NUM_PATCH_INT32:
if ( o.isint() ) {
writer.write(LuaValue.TINT);
dumpInt(o.toint());
} else {
writer.write(LuaValue.TNUMBER);
dumpDouble(o.todouble());
}
break;
default:
throw new IllegalArgumentException("number format not supported: "+NUMBER_FORMAT);
}
break;
case LuaValue.TSTRING:
writer.write(LuaValue.TSTRING);
dumpString((LuaString)o);
break;
default:
throw new IllegalArgumentException("bad type for " + o);
}
}
n = f.p.length;
dumpInt(n);
for (i = 0; i < n; i++)
dumpFunction(f.p[i]);
}
void dumpUpvalues(final Prototype f) throws IOException {
int n = f.upvalues.length;
dumpInt(n);
for (int i = 0; i < n; i++) {
writer.writeByte(f.upvalues[i].instack ? 1 : 0);
writer.writeByte(f.upvalues[i].idx);
}
}
void dumpDebug(final Prototype f) throws IOException {
int i, n;
if (strip)
dumpInt(0);
else
dumpString(f.source);
n = strip ? 0 : f.lineinfo.length;
dumpInt(n);
for (i = 0; i < n; i++)
dumpInt(f.lineinfo[i]);
n = strip ? 0 : f.locvars.length;
dumpInt(n);
for (i = 0; i < n; i++) {
LocVars lvi = f.locvars[i];
dumpString(lvi.varname);
dumpInt(lvi.startpc);
dumpInt(lvi.endpc);
}
n = strip ? 0 : f.upvalues.length;
dumpInt(n);
for (i = 0; i < n; i++)
dumpString(f.upvalues[i].name);
}
void dumpFunction(final Prototype f) throws IOException {
dumpInt(f.linedefined);
dumpInt(f.lastlinedefined);
dumpChar(f.numparams);
dumpChar(f.is_vararg);
dumpChar(f.maxstacksize);
dumpCode(f);
dumpConstants(f);
dumpUpvalues(f);
dumpDebug(f);
}
void dumpHeader() throws IOException {
writer.write( LoadState.LUA_SIGNATURE );
writer.write( LoadState.LUAC_VERSION );
writer.write( LoadState.LUAC_FORMAT );
writer.write( IS_LITTLE_ENDIAN? 1: 0 );
writer.write( SIZEOF_INT );
writer.write( SIZEOF_SIZET );
writer.write( SIZEOF_INSTRUCTION );
writer.write( SIZEOF_LUA_NUMBER );
writer.write( NUMBER_FORMAT );
writer.write( LoadState.LUAC_TAIL );
}
/*
** dump Lua function as precompiled chunk
*/
public static int dump( Prototype f, OutputStream w, boolean strip ) throws IOException {
DumpState D = new DumpState(w,strip);
D.dumpHeader();
D.dumpFunction(f);
return D.status;
}
public static int dump(Prototype f, OutputStream w, boolean stripDebug, int numberFormat, boolean littleendian) throws IOException {
switch ( numberFormat ) {
case NUMBER_FORMAT_FLOATS_OR_DOUBLES:
case NUMBER_FORMAT_INTS_ONLY:
case NUMBER_FORMAT_NUM_PATCH_INT32:
break;
default:
throw new IllegalArgumentException("number format not supported: "+numberFormat);
}
DumpState D = new DumpState(w,stripDebug);
D.IS_LITTLE_ENDIAN = littleendian;
D.NUMBER_FORMAT = numberFormat;
D.SIZEOF_LUA_NUMBER = (numberFormat==NUMBER_FORMAT_INTS_ONLY? 4: 8);
D.dumpHeader();
D.dumpFunction(f);
return D.status;
}
} |
package de.franziskuskiefer.pow;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import de.franziskuskiefer.android.httplibrary.Callback;
import de.franziskuskiefer.android.httplibrary.HTTPS_POST;
public class MainActivity extends Activity implements OnClickListener, Callback {
private Soke soke;
private String sessionID;
private String authURL;
private String successURL;
private String trans;
private String pwd;
private String errorURL;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.CustomTheme);
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
setContentView(R.layout.activity_main);
addListener();
// this.spake = new SPake();
this.soke = new Soke();
init();
}
private void init() {
// get custom data from webpage
Uri data = getIntent().getData();
if (data != null) {
Log.d("POW", "Params: " + data.toString());
String queryString = data.getQuery();
try {
String decoded = URLDecoder.decode(queryString, "UTF-8");
this.trans = decoded;
handleInitResult(decoded);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("POW", e.getLocalizedMessage());
// can't go anywhere specific as we can not even read the parameters
finish();
}
}
}
private void handleInitResult(String s) {
try {
JSONObject json = new JSONObject(s);
this.sessionID = json.getString("sessionID");
this.authURL = json.getString("authURL");
this.successURL = json.getString("successURL");
this.errorURL = json.getString("errorURL");
// TODO: clean up
// this.TTP = json.getString("TTP");
// this.TTPSOURCE = json.getString("TTPSOURCE");
} catch (JSONException e) {
e.printStackTrace();
Log.d("POW", e.getLocalizedMessage());
returnToBrowser(this.errorURL);
}
}
// add listener to login button
private void addListener() {
final Button loginButton = (Button) findViewById(R.id.BtnSetupOk);
loginButton.setOnClickListener(this);
final Button cancelButton = (Button) findViewById(R.id.BtnSetupCancel);
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public void onClick(View v) {
Log.d("POW", "Login Clicked ... ");
this.pwd = ((EditText) findViewById(R.id.password)).getText().toString();
// execute soke init to get first message
String m = soke.init();
HashMap<String, String> params = new HashMap<String, String>();
// FIXME
params.put("msg", "POWClientExchange");
params.put("version", "POW_v1_tSOKE_2048_SHA256_certHash");
params.put("sessionID", sessionID);
params.put("username", ((EditText) findViewById(R.id.username)).getText().toString());
params.put("clientMsg", m);
new HTTPS_POST(this, false, params).execute(authURL);
}
@Override
public void finished(String s) {
// TODO Auto-generated method stub
Log.d("POW", "finished: " + s);
}
@Override
public void finished(HashMap<String, String> arg0) {
// this.spake.next(JsonUtils.addElement(arg0.get("Result"), "sid",
// "buildthesid..."));
for (String key : arg0.keySet()) {
Log.d("POW", key);
}
for (String value : arg0.values()) {
Log.d("POW", value);
}
// add sent URI parameters to transcript
this.trans += "&POWClientExchange=" + arg0.get("Params");
// get server result
String jsonString = arg0.get("Result");
// add result to transcript
this.trans += "&POWServerExchange=" + Uri.encode(jsonString);
Log.d("POW", "jsonString: " + jsonString);
try {
JSONObject json = new JSONObject(jsonString);
String auth = soke.next(json.getString("serverPoint"), pwd, json.getString("salt"), trans);
// go back to browser with final auth token
if (auth != null)
returnToBrowser(this.successURL + "?auth1=" + auth + "&sessionID=" + this.sessionID);
else
returnToBrowser(this.errorURL);
} catch (JSONException e) {
e.printStackTrace();
Log.d("POW", e.getLocalizedMessage());
returnToBrowser(this.errorURL);
}
}
private void returnToBrowser(String url){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
finish();
}
/*
* TODO: currently not used
*/
public class Branding extends AsyncTask<String, Void, Drawable> {
@Override
protected Drawable doInBackground(String... params) {
Drawable brandingImage = loadImageFromWeb(params[0]);
return brandingImage;
}
@Override
protected void onPostExecute(Drawable result) {
// ((ImageView)findViewById(R.id.brandingImage)).setImageDrawable(result);
}
private Drawable loadImageFromWeb(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
return Drawable.createFromStream(is, ".png");
} catch (Exception e) {
return null;
}
}
}
} |
package de.onyxbits.textfiction;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.Iterator;
import org.json.JSONArray;
import de.onyxbits.textfiction.input.CompassFragment;
import de.onyxbits.textfiction.input.InputFragment;
import de.onyxbits.textfiction.input.InputProcessor;
import de.onyxbits.textfiction.input.WordExtractor;
import de.onyxbits.textfiction.zengine.GrueException;
import de.onyxbits.textfiction.zengine.StyleRegion;
import de.onyxbits.textfiction.zengine.ZMachine;
import de.onyxbits.textfiction.zengine.ZState;
import de.onyxbits.textfiction.zengine.ZStatus;
import de.onyxbits.textfiction.zengine.ZWindow;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Typeface;
import android.os.Build;
import android.preference.PreferenceManager;
/**
* The activity where actual gameplay takes place.
*
* @author patrick
*
*/
public class GameActivity extends FragmentActivity implements
DialogInterface.OnClickListener, OnInitListener,
OnSharedPreferenceChangeListener, InputProcessor {
/**
* Name of the file we keep our highlights in
*/
public static final String HIGHLIGHTFILE = "highlights.json";
/**
* This activity must be started through an intent and be passed the filename
* of the game via this extra.
*/
public static final String LOADFILE = "loadfile";
/**
* Optionally, the name of the game may be passed (if none is passed, the
* filename is used as a title).
*/
public static final String GAMETITLE = "gametitle";
/**
* How many items to keep in the messagebuffer at most. Note: this should be
* an odd number so the log starts with a narrator entry.
*/
public static final int MAXMESSAGES = 81;
private static final int PENDING_NONE = 0;
private static final int PENDING_RESTART = 1;
private static final int PENDING_RESTORE = 2;
private static final int PENDING_SAVE = 3;
/**
* Displays the message log
*/
private ListView storyBoard;
/**
* Adapter for the story list
*/
private StoryAdapter messages;
/**
* The "upper window" of the z-machine containing the status part
*/
private TextView statusWindow;
/**
* Holds stuff that needs to survive config changes (e.g. screen rotation).
*/
private RetainerFragment retainerFragment;
/**
* The input prompt
*/
private InputFragment inputFragment;
/**
* On screen compass
*/
private CompassFragment compassFragment;
/**
* Contains story- and status screen.
*/
private ViewFlipper windowFlipper;
/**
* For entering a filename to save the current game as.
*/
private EditText saveName;
/**
* The game playing in this activity
*/
private File storyFile;
/**
* State variable for when we are showing a "confirm" dialog.
*/
private int pendingAction = PENDING_NONE;
/**
* Words we are highligting in the story
*/
private String[] highlighted;
private SharedPreferences prefs;
private TextToSpeech speaker;
private boolean ttsReady;
private WordExtractor wordExtractor;
private ProgressBar loading;
@Override
protected void onCreate(Bundle savedInstanceState) {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Set the custom theme
try {
Field field = R.style.class.getField(prefs.getString("theme", ""));
setTheme(field.getInt(null));
}
catch (Exception e) {
Log.w(getClass().getName(), e);
}
prefs.registerOnSharedPreferenceChangeListener(this);
super.onCreate(savedInstanceState);
LayoutInflater infl = getLayoutInflater();
requestWindowFeature(Window.FEATURE_PROGRESS);
storyFile = new File(getIntent().getStringExtra(LOADFILE));
View content = infl.inflate(R.layout.activity_game, null);
setContentView(content);
// Check if this is a genuine start or if we are restarting because the
// device got rotated.
FragmentManager fm = getSupportFragmentManager();
inputFragment = (InputFragment) fm.findFragmentById(R.id.fragment_input);
compassFragment = (CompassFragment) fm
.findFragmentById(R.id.fragment_compass);
retainerFragment = (RetainerFragment) fm.findFragmentByTag("retainer");
if (retainerFragment == null) {
// First start
retainerFragment = new RetainerFragment();
fm.beginTransaction().add(retainerFragment, "retainer").commit();
}
else {
// Likely a restart because of the screen being rotated. This may have
// happened while loading, so don't figure if we don't have an engine.
if (retainerFragment.engine != null) {
figurePromptStyle();
figureMenuState();
}
}
// Load the highlight file
try {
File file = new File(FileUtil.getDataDir(storyFile), HIGHLIGHTFILE);
JSONArray js = new JSONArray(FileUtil.getContents(file));
for (int i = 0; i < js.length(); i++) {
retainerFragment.highlighted.add(js.getString(i));
}
}
catch (Exception e) {
// No big deal. Probably the first time this game runs -> use defaults
String[] ini = getResources().getStringArray(R.array.initial_highlights);
for (String i : ini) {
retainerFragment.highlighted.add(i);
}
}
highlighted = retainerFragment.highlighted.toArray(new String[0]);
storyBoard = (ListView) content.findViewById(R.id.storyboard);
wordExtractor = new WordExtractor(this);
wordExtractor.setInputFragment(inputFragment);
wordExtractor.setInputProcessor(this);
messages = new StoryAdapter(this, 0, retainerFragment.messageBuffer,
wordExtractor);
storyBoard.setAdapter(messages);
windowFlipper = (ViewFlipper) content.findViewById(R.id.window_flipper);
statusWindow = (TextView) content.findViewById(R.id.status);
loading = (ProgressBar) findViewById(R.id.gameloading);
statusWindow.setText(retainerFragment.upperWindow);
speaker = new TextToSpeech(this, this);
onSharedPreferenceChanged(prefs, "");
}
@Override
public void onPause() {
if (ttsReady && speaker.isSpeaking()) {
speaker.stop();
}
super.onPause();
}
@Override
public void onDestroy() {
prefs.unregisterOnSharedPreferenceChangeListener(this);
if (ttsReady) {
speaker.shutdown();
}
if (retainerFragment == null || retainerFragment.engine == null) {
if (retainerFragment.postMortem != null) {
// Let's not go into details here. The user won't understand them
// anyways.
Toast
.makeText(this, R.string.msg_corrupt_game_file, Toast.LENGTH_SHORT)
.show();
}
super.onDestroy();
return;
}
if (retainerFragment.postMortem != null) {
// Let's not go into details here. The user won't understand them anyways.
Toast.makeText(this, R.string.msg_corrupt_game_file, Toast.LENGTH_SHORT)
.show();
super.onDestroy();
return;
}
if (retainerFragment.engine.getRunState() == ZMachine.STATE_WAIT_CMD) {
ZState state = new ZState(retainerFragment.engine);
File f = new File(FileUtil.getSaveGameDir(storyFile),
getString(R.string.autosavename));
state.disk_save(f.getPath(), retainerFragment.engine.pc);
}
else {
Toast.makeText(this, R.string.mg_not_at_a_commandprompt,
Toast.LENGTH_LONG).show();
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
boolean rest = !(retainerFragment == null
|| retainerFragment.engine == null
|| retainerFragment.engine.getRunState() == ZMachine.STATE_RUNNING || retainerFragment.engine
.getRunState() == ZMachine.STATE_INIT);
menu.findItem(R.id.mi_save).setEnabled(rest && inputFragment.isPrompt());
menu.findItem(R.id.mi_restore).setEnabled(rest && inputFragment.isPrompt());
menu.findItem(R.id.mi_restart).setEnabled(rest);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mi_flip_view: {
flipView(windowFlipper.getCurrentView() != storyBoard);
return true;
}
case R.id.mi_save: {
pendingAction = PENDING_SAVE;
saveName = new EditText(this);
saveName.setSingleLine(true);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.title_save_game)
.setPositiveButton(android.R.string.ok, this).setView(saveName)
.show();
return true;
}
case R.id.mi_restore: {
String[] sg = FileUtil.listSaveName(storyFile);
if (sg.length > 0) {
pendingAction = PENDING_RESTORE;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.title_restore_game).setItems(sg, this)
.show();
}
else {
Toast.makeText(this, R.string.msg_no_savegames, Toast.LENGTH_SHORT)
.show();
}
return true;
}
case R.id.mi_clear_log: {
retainerFragment.messageBuffer.clear();
messages.notifyDataSetChanged();
return true;
}
case R.id.mi_help: {
MainActivity.openUri(this, Uri.parse(getString(R.string.url_help)));
return true;
}
case R.id.mi_restart: {
pendingAction = PENDING_RESTART;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.title_please_confirm)
.setMessage(R.string.msg_really_restart)
.setPositiveButton(android.R.string.yes, this)
.setNegativeButton(android.R.string.no, this).show();
return true;
}
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void executeCommand(char[] inputBuffer) {
ZMachine engine = retainerFragment.engine;
if (engine != null && engine.getRunState() != ZMachine.STATE_RUNNING) {
retainerFragment.engine.fillInputBuffer(inputBuffer);
if (retainerFragment.engine.getRunState() != ZMachine.STATE_WAIT_CHAR) {
String tmp = new String(inputBuffer).replaceAll("\n", "").trim();
SpannableString ss = new SpannableString(tmp);
retainerFragment.messageBuffer.add(new StoryItem(ss, StoryItem.MYSELF));
}
try {
retainerFragment.engine.run();
publishResult();
if (retainerFragment.engine.saveCalled || retainerFragment.engine.restoreCalled) {
// This is a really ugly hack to let the user know that the save/restore commands
// don't work
Toast.makeText(this,R.string.err_sr_deprecated,Toast.LENGTH_LONG).show();
retainerFragment.engine.saveCalled = false;
retainerFragment.engine.restoreCalled = false;
}
}
catch (GrueException e) {
retainerFragment.postMortem = e;
Log.w(getClass().getName(), e);
finish();
}
}
}
/**
* Callback: publish results after the engine has run
*/
public void publishResult() {
ZWindow upper = retainerFragment.engine.window[1];
ZWindow lower = retainerFragment.engine.window[0];
ZStatus status = retainerFragment.engine.status_line;
String tmp = "";
boolean showLower = false;
// Evaluate game status
if (status != null) {
// Z3 game -> copy the status bar object into the upper window.
retainerFragment.engine.update_status_line();
retainerFragment.upperWindow = status.toString();
statusWindow.setText(retainerFragment.upperWindow);
}
else {
if (upper.maxCursor > 0) {
// The normal, "status bar" upper window.
tmp = upper.stringyfy(upper.startWindow, upper.maxCursor);
}
else {
tmp = "";
}
statusWindow.setText(tmp);
retainerFragment.upperWindow = tmp;
}
upper.retrieved();
// Evaluate story progress
if (lower.cursor > 0) {
showLower = true;
tmp = new String(lower.frameBuffer, 0, lower.noPrompt());
if (ttsReady && prefs.getBoolean("narrator", false)) {
speaker.speak(tmp, TextToSpeech.QUEUE_FLUSH, null);
}
SpannableString stmp = new SpannableString(tmp);
StyleRegion reg = lower.regions;
if (reg != null) {
while (reg != null) {
if (reg.next == null) {
// The printer does not "close" the last style since it doesn't know
// when the last character is printed.
reg.end = tmp.length() - 1;
}
// Did the game style the prompt (which we cut away)?
reg.end = Math.min(reg.end, tmp.length() - 1);
switch (reg.style) {
case ZWindow.BOLD: {
stmp.setSpan(new StyleSpan(Typeface.BOLD), reg.start, reg.end, 0);
break;
}
case ZWindow.ITALIC: {
stmp.setSpan(new StyleSpan(Typeface.ITALIC), reg.start, reg.end,
0);
break;
}
case ZWindow.FIXED: {
stmp.setSpan(new TypefaceSpan("monospace"), reg.start, reg.end, 0);
break;
}
}
reg = reg.next;
}
}
highlight(stmp, highlighted);
retainerFragment.messageBuffer
.add(new StoryItem(stmp, StoryItem.NARRATOR));
}
lower.retrieved();
// Throw out old story items.
while (retainerFragment.messageBuffer.size() > MAXMESSAGES) {
retainerFragment.messageBuffer.remove(0);
}
messages.notifyDataSetChanged();
// Scroll the storyboard to the latest item.
if (prefs.getBoolean("smoothscrolling", true)) {
// NOTE:smoothScroll() does not work properly if the theme defines
// dividerheight > 0!
storyBoard
.smoothScrollToPosition(retainerFragment.messageBuffer.size() - 1);
}
else {
storyBoard.setSelection(retainerFragment.messageBuffer.size() - 1);
}
inputFragment.reset();
// Kinda dirty: assume that the lower window is the important one. If
// anything got added to it, ensure that it is visible. Otherwise assume
// that we are dealing with something like a menu and switch the display to
// display the upperwindow
flipView(showLower);
figurePromptStyle();
figureMenuState();
}
/**
* Show the correct prompt.
*/
private void figurePromptStyle() {
if (retainerFragment.engine.getRunState() == ZMachine.STATE_WAIT_CHAR
&& inputFragment.isPrompt()) {
inputFragment.toggleInput();
}
if (retainerFragment.engine.getRunState() == ZMachine.STATE_WAIT_CMD
&& !inputFragment.isPrompt()) {
inputFragment.toggleInput();
}
}
/**
* Enable/Disable menu items
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void figureMenuState() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
invalidateOptionsMenu();
}
}
/**
* Make either the storyboard or the statusscreen visible
*
* @param showstory
* true to swtich to the story view, false to swtich to the status
* screen. nothing happens if the desired view is already showing.
*/
private void flipView(boolean showstory) {
View now = windowFlipper.getCurrentView();
if (showstory) {
if (now != storyBoard) {
windowFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
R.animator.slide_in_right));
windowFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
R.animator.slide_out_left));
windowFlipper.showPrevious();
}
}
else {
if (now == storyBoard) {
windowFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.slide_in_left));
windowFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.slide_out_right));
windowFlipper.showPrevious();
}
}
}
@Override
public void onClick(DialogInterface dialog, int which) {
switch (pendingAction) {
case PENDING_RESTART: {
if (which == DialogInterface.BUTTON_POSITIVE) {
retainerFragment.messageBuffer.clear();
try {
retainerFragment.engine.restart();
retainerFragment.engine.run();
}
catch (GrueException e) {
// This should never happen
retainerFragment.postMortem = e;
finish();
}
publishResult();
}
break;
}
case PENDING_SAVE: {
String name = saveName.getEditableText().toString();
name = name.replace('/', '_');
if (name.length() > 0) {
ZState state = new ZState(retainerFragment.engine);
File f = new File(FileUtil.getSaveGameDir(storyFile), name);
state.disk_save(f.getPath(), retainerFragment.engine.pc);
Toast.makeText(this, R.string.msg_game_saved, Toast.LENGTH_SHORT)
.show();
}
}
case PENDING_RESTORE: {
if (which > -1) {
File file = FileUtil.listSaveGames(storyFile)[which];
ZState state = new ZState(retainerFragment.engine);
if (state.restore_from_disk(file.getPath())) {
statusWindow.setText(""); // Wrong, but the best we can do.
retainerFragment.messageBuffer.clear();
messages.notifyDataSetChanged();
retainerFragment.engine.restore(state);
figurePromptStyle();
figureMenuState();
Toast
.makeText(this, R.string.msg_game_restored, Toast.LENGTH_SHORT)
.show();
}
else {
Toast.makeText(this, R.string.msg_restore_failed,
Toast.LENGTH_SHORT).show();
}
}
}
}
pendingAction = PENDING_NONE;
}
@Override
public void onInit(int status) {
ttsReady = (status == TextToSpeech.SUCCESS);
if (ttsReady) {
// Was the game faster to load?
if (retainerFragment != null && retainerFragment.messageBuffer.size() > 0
&& prefs.getBoolean("narrator", false)) {
speaker.speak(retainerFragment.messageBuffer
.get(retainerFragment.messageBuffer.size() - 1).message.toString(),
TextToSpeech.QUEUE_FLUSH, null);
}
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
String font = prefs.getString("font", "");
if (font.equals("default")) {
messages.setTypeface(Typeface.DEFAULT);
}
if (font.equals("sans")) {
messages.setTypeface(Typeface.SANS_SERIF);
}
if (font.equals("serif")) {
messages.setTypeface(Typeface.SERIF);
}
if (font.equals("monospace")) {
messages.setTypeface(Typeface.MONOSPACE);
}
if (font.equals("comicsans")) {
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/LDFComicSans.ttf");
messages.setTypeface(tf);
}
if (font.equals("ziggyzoe")) {
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/ziggyzoe.ttf");
messages.setTypeface(tf);
}
String fontSize = prefs.getString("fontsize", "");
TextView tmp = new TextView(this);
if (fontSize.equals("small")) {
tmp.setTextAppearance(this, android.R.style.TextAppearance_Small);
messages.setTextSize(tmp.getTextSize());
}
if (fontSize.equals("medium")) {
tmp.setTextAppearance(this, android.R.style.TextAppearance_Medium);
messages.setTextSize(tmp.getTextSize());
}
if (fontSize.equals("large")) {
tmp.setTextAppearance(this, android.R.style.TextAppearance_Large);
messages.setTextSize(tmp.getTextSize());
}
inputFragment.setAutoCollapse(prefs.getBoolean("autocollapse", false));
wordExtractor.setKeyclick(prefs.getBoolean("keyclick", false));
compassFragment.setKeyclick(prefs.getBoolean("keyclick", false));
}
@Override
public void toggleTextHighlight(String str) {
int tmp;
String txt = str.toLowerCase();
if (retainerFragment.highlighted.contains(txt)) {
retainerFragment.highlighted.remove(txt);
tmp = R.string.msg_unmarked;
}
else {
retainerFragment.highlighted.add(txt);
tmp = R.string.msg_marked;
}
Toast
.makeText(this, getResources().getString(tmp, txt), Toast.LENGTH_SHORT)
.show();
highlighted = retainerFragment.highlighted.toArray(new String[0]);
Iterator<StoryItem> it = retainerFragment.messageBuffer.listIterator();
while (it.hasNext()) {
highlight(it.next().message, highlighted);
}
messages.notifyDataSetChanged();
try {
JSONArray array = new JSONArray(retainerFragment.highlighted);
File f = new File(FileUtil.getDataDir(storyFile), HIGHLIGHTFILE);
PrintStream ps = new PrintStream(f);
ps.write(array.toString(2).getBytes());
ps.close();
}
catch (Exception e) {
Log.w(getClass().getName(), e);
}
}
@Override
public void utterText(CharSequence txt) {
if (ttsReady) {
if (speaker.isSpeaking() && txt == null) {
speaker.stop();
}
if (txt != null) {
speaker.speak(txt.toString(), TextToSpeech.QUEUE_FLUSH, null);
}
}
}
/**
* Add underlines to a text blob. Any existing underlines are removed. before
* new ones are added.
*
* @param span
* the blob to modify
* @param words
* the words to underline (all lowercase!)
*/
private static void highlight(SpannableString span, String... words) {
UnderlineSpan old[] = span.getSpans(0, span.length(), UnderlineSpan.class);
for (UnderlineSpan del : old) {
span.removeSpan(del);
}
char spanChars[] = span.toString().toLowerCase().toCharArray();
for (String word : words) {
char[] wc = word.toCharArray();
int last = spanChars.length - wc.length + 1;
for (int i = 0; i < last; i++) {
// First check if there is a word-sized gap at spanchars[i] as we don't
// want to highlight words that are actually just substrings (e.g.
// "east" in "lEASTwise").
if ((i > 0 && Character.isLetterOrDigit(spanChars[i - 1]))
|| (i + wc.length != spanChars.length && Character
.isLetterOrDigit(spanChars[i + wc.length]))) {
continue;
}
int a = i;
int b = 0;
while (b < wc.length) {
if (spanChars[a] != wc[b]) {
b = 0;
break;
}
a++;
b++;
}
if (b == wc.length) {
span.setSpan(new UnderlineSpan(), i, a, 0);
i = a;
}
}
}
}
@Override
public File getStory() {
return storyFile;
}
/**
* Show/hide the spinner indicating that we are currently loading a game
* @param b true to show the spinner.
*/
public void setLoadingVisibility(boolean b) {
try {
loading.setIndeterminate(b);
if (b) {
loading.setVisibility(View.VISIBLE);
}
else {
loading.setVisibility(View.GONE);
}
}
catch (Exception e) {
// TODO: Getting here is a bug! I haven't figured out how to trigger it yet,
// the User message on Google Play for the stack trace reads "crash on resume".
Log.w("TextFiction",e);
}
}
} |
package org.zstack.kvm;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.util.UriComponentsBuilder;
import org.zstack.compute.host.HostBase;
import org.zstack.compute.host.HostGlobalConfig;
import org.zstack.compute.host.HostSystemTags;
import org.zstack.compute.host.MigrateNetworkExtensionPoint;
import org.zstack.compute.vm.*;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.MessageCommandRecorder;
import org.zstack.core.Platform;
import org.zstack.core.agent.AgentConstant;
import org.zstack.core.ansible.*;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.cloudbus.CloudBusGlobalProperty;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.Q;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.thread.*;
import org.zstack.core.timeout.ApiTimeoutManager;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.Constants;
import org.zstack.header.allocator.HostAllocatorConstant;
import org.zstack.header.cluster.ReportHostCapacityMessage;
import org.zstack.header.core.*;
import org.zstack.header.core.progress.TaskProgressRange;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.*;
import org.zstack.header.host.MigrateVmOnHypervisorMsg.StorageMigrationPolicy;
import org.zstack.header.image.ImageBootMode;
import org.zstack.header.image.ImagePlatform;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.message.NeedReplyMessage;
import org.zstack.header.network.l2.*;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.network.l3.L3NetworkVO;
import org.zstack.header.rest.JsonAsyncRESTCallback;
import org.zstack.header.rest.RESTFacade;
import org.zstack.header.storage.primary.*;
import org.zstack.header.storage.snapshot.VolumeSnapshotInventory;
import org.zstack.header.tag.SystemTagInventory;
import org.zstack.header.vm.*;
import org.zstack.header.vm.VmDeviceAddress;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.header.volume.VolumeType;
import org.zstack.header.volume.VolumeVO;
import org.zstack.kvm.KVMAgentCommands.*;
import org.zstack.kvm.KVMConstant.KvmVmState;
import org.zstack.network.l3.NetworkGlobalProperty;
import org.zstack.resourceconfig.ResourceConfigFacade;
import org.zstack.tag.SystemTag;
import org.zstack.tag.SystemTagCreator;
import org.zstack.tag.TagManager;
import org.zstack.utils.*;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import org.zstack.utils.network.NetworkUtils;
import org.zstack.utils.path.PathUtil;
import org.zstack.utils.ssh.Ssh;
import org.zstack.utils.ssh.SshException;
import org.zstack.utils.ssh.SshResult;
import org.zstack.utils.ssh.SshShell;
import org.zstack.utils.tester.ZTester;
import javax.persistence.TypedQuery;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.zstack.core.Platform.*;
import static org.zstack.core.progress.ProgressReportService.*;
import static org.zstack.utils.CollectionDSL.e;
import static org.zstack.utils.CollectionDSL.map;
public class KVMHost extends HostBase implements Host {
private static final CLogger logger = Utils.getLogger(KVMHost.class);
private static final ZTester tester = Utils.getTester();
@Autowired
@Qualifier("KVMHostFactory")
private KVMHostFactory factory;
@Autowired
private RESTFacade restf;
@Autowired
private KVMExtensionEmitter extEmitter;
@Autowired
private ErrorFacade errf;
@Autowired
private TagManager tagmgr;
@Autowired
private ApiTimeoutManager timeoutManager;
@Autowired
private PluginRegistry pluginRegistry;
@Autowired
private ThreadFacade thdf;
@Autowired
private AnsibleFacade asf;
@Autowired
private ResourceConfigFacade rcf;
@Autowired
private DeviceBootOrderOperator deviceBootOrderOperator;
@Autowired
private VmNicManager nicManager;
private KVMHostContext context;
// ///////////////////// REST URL //////////////////////////
private String baseUrl;
private String connectPath;
private String pingPath;
private String checkPhysicalNetworkInterfacePath;
private String startVmPath;
private String stopVmPath;
private String pauseVmPath;
private String resumeVmPath;
private String rebootVmPath;
private String destroyVmPath;
private String attachDataVolumePath;
private String detachDataVolumePath;
private String echoPath;
private String attachNicPath;
private String detachNicPath;
private String migrateVmPath;
private String snapshotPath;
private String mergeSnapshotPath;
private String hostFactPath;
private String attachIsoPath;
private String detachIsoPath;
private String updateNicPath;
private String checkVmStatePath;
private String getConsolePortPath;
private String onlineIncreaseCpuPath;
private String onlineIncreaseMemPath;
private String deleteConsoleFirewall;
private String updateHostOSPath;
private String updateDependencyPath;
private String shutdownHost;
private String updateVmPriorityPath;
private String updateSpiceChannelConfigPath;
private String cancelJob;
private String getVmFirstBootDevicePath;
private String getVmDeviceAddressPath;
private String scanVmPortPath;
private String getDevCapacityPath;
private String configPrimaryVmPath;
private String configSecondaryVmPath;
private String startColoSyncPath;
private String registerPrimaryVmHeartbeatPath;
private String agentPackageName = KVMGlobalProperty.AGENT_PACKAGE_NAME;
public KVMHost(KVMHostVO self, KVMHostContext context) {
super(self);
this.context = context;
baseUrl = context.getBaseUrl();
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONNECT_PATH);
connectPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_PING_PATH);
pingPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CHECK_PHYSICAL_NETWORK_INTERFACE_PATH);
checkPhysicalNetworkInterfacePath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_START_VM_PATH);
startVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_STOP_VM_PATH);
stopVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_PAUSE_VM_PATH);
pauseVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_RESUME_VM_PATH);
resumeVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_REBOOT_VM_PATH);
rebootVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DESTROY_VM_PATH);
destroyVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_VOLUME);
attachDataVolumePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_VOLUME);
detachDataVolumePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ECHO_PATH);
echoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_NIC_PATH);
attachNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_NIC_PATH);
detachNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_MIGRATE_VM_PATH);
migrateVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_TAKE_VOLUME_SNAPSHOT_PATH);
snapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_MERGE_SNAPSHOT_PATH);
mergeSnapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_FACT_PATH);
hostFactPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_ISO_PATH);
attachIsoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_ISO_PATH);
detachIsoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_NIC_PATH);
updateNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_CHECK_STATE);
checkVmStatePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_GET_VNC_PORT_PATH);
getConsolePortPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_CPU);
onlineIncreaseCpuPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_MEMORY);
onlineIncreaseMemPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH);
deleteConsoleFirewall = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_HOST_OS_PATH);
updateHostOSPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_UPDATE_DEPENDENCY_PATH);
updateDependencyPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.HOST_SHUTDOWN);
shutdownHost = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_UPDATE_PRIORITY_PATH);
updateVmPriorityPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.HOST_UPDATE_SPICE_CHANNEL_CONFIG_PATH);
updateSpiceChannelConfigPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(AgentConstant.CANCEL_JOB);
cancelJob = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_GET_VM_FIRST_BOOT_DEVICE_PATH);
getVmFirstBootDevicePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.GET_VM_DEVICE_ADDRESS_PATH);
getVmDeviceAddressPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_SCAN_VM_PORT_STATUS);
scanVmPortPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.GET_DEV_CAPACITY);
getDevCapacityPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONFIG_PRIMARY_VM_PATH);
configPrimaryVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONFIG_SECONDARY_VM_PATH);
configSecondaryVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_START_COLO_SYNC_PATH);
startColoSyncPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_REGISTER_PRIMARY_VM_HEARTBEAT);
registerPrimaryVmHeartbeatPath = ub.build().toString();
}
class Http<T> {
String path;
AgentCommand cmd;
Class<T> responseClass;
String commandStr;
public Http(String path, String cmd, Class<T> rspClz) {
this.path = path;
this.commandStr = cmd;
this.responseClass = rspClz;
}
public Http(String path, AgentCommand cmd, Class<T> rspClz) {
this.path = path;
this.cmd = cmd;
this.responseClass = rspClz;
}
void call(ReturnValueCompletion<T> completion) {
call(null, completion);
}
void call(String resourceUuid, ReturnValueCompletion<T> completion) {
Map<String, String> header = new HashMap<>();
header.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, resourceUuid == null ? self.getUuid() : resourceUuid);
runBeforeAsyncJsonPostExts(header);
if (commandStr != null) {
restf.asyncJsonPost(path, commandStr, header, new JsonAsyncRESTCallback<T>(completion) {
@Override
public void fail(ErrorCode err) {
completion.fail(err);
}
@Override
public void success(T ret) {
if (dbf.isExist(self.getUuid(), HostVO.class)) {
completion.success(ret);
} else {
completion.fail(operr("host[uuid:%s] has been deleted", self.getUuid()));
}
}
@Override
public Class<T> getReturnClass() {
return responseClass;
}
}, TimeUnit.MILLISECONDS, timeoutManager.getTimeout());
} else {
restf.asyncJsonPost(path, cmd, header, new JsonAsyncRESTCallback<T>(completion) {
@Override
public void fail(ErrorCode err) {
completion.fail(err);
}
@Override
public void success(T ret) {
if (dbf.isExist(self.getUuid(), HostVO.class)) {
completion.success(ret);
} else {
completion.fail(operr("host[uuid:%s] has been deleted", self.getUuid()));
}
}
@Override
public Class<T> getReturnClass() {
return responseClass;
}
}); // DO NOT pass unit, timeout here, they are null
}
}
void runBeforeAsyncJsonPostExts(Map<String, String> header) {
if (commandStr == null) {
commandStr = JSONObjectUtil.toJsonString(cmd);
}
if (commandStr == null || commandStr.isEmpty()) {
logger.warn(String.format("commandStr is empty, path: %s, header: %s", path, header));
return;
}
LinkedHashMap commandMap = JSONObjectUtil.toObject(commandStr, LinkedHashMap.class);
LinkedHashMap kvmHostAddon = new LinkedHashMap();
for (KVMBeforeAsyncJsonPostExtensionPoint extp : pluginRegistry.getExtensionList(KVMBeforeAsyncJsonPostExtensionPoint.class)) {
LinkedHashMap tmpHashMap = extp.kvmBeforeAsyncJsonPostExtensionPoint(path, commandMap, header);
if (tmpHashMap != null && !tmpHashMap.isEmpty()) {
tmpHashMap.keySet().stream().forEachOrdered((key -> {
kvmHostAddon.put(key, tmpHashMap.get(key));
}));
}
}
if (commandStr.equals("{}")) {
commandStr = commandStr.replaceAll("\\}$",
String.format("\"%s\":%s}", KVMConstant.KVM_HOST_ADDONS, JSONObjectUtil.toJsonString(kvmHostAddon)));
} else {
commandStr = commandStr.replaceAll("\\}$",
String.format(",\"%s\":%s}", KVMConstant.KVM_HOST_ADDONS, JSONObjectUtil.toJsonString(kvmHostAddon)));
}
}
}
@Override
protected void handleApiMessage(APIMessage msg) {
super.handleApiMessage(msg);
}
@Override
protected void handleLocalMessage(Message msg) {
if (msg instanceof CheckNetworkPhysicalInterfaceMsg) {
handle((CheckNetworkPhysicalInterfaceMsg) msg);
} else if (msg instanceof StartVmOnHypervisorMsg) {
handle((StartVmOnHypervisorMsg) msg);
} else if (msg instanceof CreateVmOnHypervisorMsg) {
handle((CreateVmOnHypervisorMsg) msg);
} else if (msg instanceof UpdateSpiceChannelConfigMsg) {
handle((UpdateSpiceChannelConfigMsg) msg);
} else if (msg instanceof StopVmOnHypervisorMsg) {
handle((StopVmOnHypervisorMsg) msg);
} else if (msg instanceof RebootVmOnHypervisorMsg) {
handle((RebootVmOnHypervisorMsg) msg);
} else if (msg instanceof DestroyVmOnHypervisorMsg) {
handle((DestroyVmOnHypervisorMsg) msg);
} else if (msg instanceof AttachVolumeToVmOnHypervisorMsg) {
handle((AttachVolumeToVmOnHypervisorMsg) msg);
} else if (msg instanceof DetachVolumeFromVmOnHypervisorMsg) {
handle((DetachVolumeFromVmOnHypervisorMsg) msg);
} else if (msg instanceof VmAttachNicOnHypervisorMsg) {
handle((VmAttachNicOnHypervisorMsg) msg);
} else if (msg instanceof VmUpdateNicOnHypervisorMsg) {
handle((VmUpdateNicOnHypervisorMsg) msg);
} else if (msg instanceof MigrateVmOnHypervisorMsg) {
handle((MigrateVmOnHypervisorMsg) msg);
} else if (msg instanceof TakeSnapshotOnHypervisorMsg) {
handle((TakeSnapshotOnHypervisorMsg) msg);
} else if (msg instanceof MergeVolumeSnapshotOnKvmMsg) {
handle((MergeVolumeSnapshotOnKvmMsg) msg);
} else if (msg instanceof KVMHostAsyncHttpCallMsg) {
handle((KVMHostAsyncHttpCallMsg) msg);
} else if (msg instanceof KVMHostSyncHttpCallMsg) {
handle((KVMHostSyncHttpCallMsg) msg);
} else if (msg instanceof DetachNicFromVmOnHypervisorMsg) {
handle((DetachNicFromVmOnHypervisorMsg) msg);
} else if (msg instanceof AttachIsoOnHypervisorMsg) {
handle((AttachIsoOnHypervisorMsg) msg);
} else if (msg instanceof DetachIsoOnHypervisorMsg) {
handle((DetachIsoOnHypervisorMsg) msg);
} else if (msg instanceof CheckVmStateOnHypervisorMsg) {
handle((CheckVmStateOnHypervisorMsg) msg);
} else if (msg instanceof UpdateVmPriorityMsg) {
handle((UpdateVmPriorityMsg) msg);
} else if (msg instanceof GetVmConsoleAddressFromHostMsg) {
handle((GetVmConsoleAddressFromHostMsg) msg);
} else if (msg instanceof KvmRunShellMsg) {
handle((KvmRunShellMsg) msg);
} else if (msg instanceof VmDirectlyDestroyOnHypervisorMsg) {
handle((VmDirectlyDestroyOnHypervisorMsg) msg);
} else if (msg instanceof IncreaseVmCpuMsg) {
handle((IncreaseVmCpuMsg) msg);
} else if (msg instanceof IncreaseVmMemoryMsg) {
handle((IncreaseVmMemoryMsg) msg);
} else if (msg instanceof PauseVmOnHypervisorMsg) {
handle((PauseVmOnHypervisorMsg) msg);
} else if (msg instanceof ResumeVmOnHypervisorMsg) {
handle((ResumeVmOnHypervisorMsg) msg);
} else if (msg instanceof GetKVMHostDownloadCredentialMsg) {
handle((GetKVMHostDownloadCredentialMsg) msg);
} else if (msg instanceof ShutdownHostMsg) {
handle((ShutdownHostMsg) msg);
} else if (msg instanceof CancelHostTaskMsg) {
handle((CancelHostTaskMsg) msg);
} else if (msg instanceof GetVmFirstBootDeviceOnHypervisorMsg) {
handle((GetVmFirstBootDeviceOnHypervisorMsg) msg);
} else if (msg instanceof GetVmDeviceAddressMsg) {
handle((GetVmDeviceAddressMsg) msg);
} else if (msg instanceof CheckHostCapacityMsg) {
handle((CheckHostCapacityMsg) msg);
} else if (msg instanceof ConfigPrimaryVmMsg) {
handle((ConfigPrimaryVmMsg) msg);
} else if (msg instanceof ConfigSecondaryVmMsg) {
handle((ConfigSecondaryVmMsg) msg);
} else if (msg instanceof StartColoSyncMsg) {
handle((StartColoSyncMsg) msg);
} else if (msg instanceof RegisterColoPrimaryCheckMsg) {
handle((RegisterColoPrimaryCheckMsg) msg);
} else {
super.handleLocalMessage(msg);
}
}
private void handle(CheckHostCapacityMsg msg) {
CheckHostCapacityReply re = new CheckHostCapacityReply();
KVMHostAsyncHttpCallMsg kmsg = new KVMHostAsyncHttpCallMsg();
kmsg.setHostUuid(msg.getHostUuid());
kmsg.setPath(KVMConstant.KVM_HOST_CAPACITY_PATH);
kmsg.setNoStatusCheck(true);
kmsg.setCommand(new HostCapacityCmd());
bus.makeTargetServiceIdByResourceUuid(kmsg, HostConstant.SERVICE_ID, msg.getHostUuid());
bus.send(kmsg, new CloudBusCallBack(msg) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
throw new OperationFailureException(operr("check host capacity failed, because:%s", reply.getError()));
}
KVMHostAsyncHttpCallReply r = reply.castReply();
HostCapacityResponse rsp = r.toResponse(HostCapacityResponse.class);
if (!rsp.isSuccess()) {
throw new OperationFailureException(operr("operation error, because:%s", rsp.getError()));
}
long reservedSize = SizeUtils.sizeStringToBytes(rcf.getResourceConfigValue(KVMGlobalConfig.RESERVED_MEMORY_CAPACITY, msg.getHostUuid(), String.class));
if (rsp.getTotalMemory() < reservedSize) {
throw new OperationFailureException(operr("The host[uuid:%s]'s available memory capacity[%s] is lower than the reserved capacity[%s]",
msg.getHostUuid(), rsp.getTotalMemory(), reservedSize));
}
ReportHostCapacityMessage rmsg = new ReportHostCapacityMessage();
rmsg.setHostUuid(msg.getHostUuid());
rmsg.setCpuNum((int) rsp.getCpuNum());
rmsg.setUsedCpu(rsp.getUsedCpu());
rmsg.setTotalMemory(rsp.getTotalMemory());
rmsg.setUsedMemory(rsp.getUsedMemory());
rmsg.setCpuSockets(rsp.getCpuSockets());
rmsg.setServiceId(bus.makeLocalServiceId(HostAllocatorConstant.SERVICE_ID));
bus.send(rmsg, new CloudBusCallBack(msg) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
re.setError(reply.getError());
}
bus.reply(msg, re);
}
});
}
});
}
private void handle(RegisterColoPrimaryCheckMsg msg) {
inQueue().name(String.format("register-vm-heart-beat-on-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> registerPrimaryVmHeartbeat(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void registerPrimaryVmHeartbeat(RegisterColoPrimaryCheckMsg msg, NoErrorCompletion completion) {
RegisterPrimaryVmHeartbeatCmd cmd = new RegisterPrimaryVmHeartbeatCmd();
cmd.setHostUuid(msg.getHostUuid());
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setHeartbeatPort(msg.getHeartbeatPort());
cmd.setTargetHostIp(msg.getTargetHostIp());
cmd.setColoPrimary(msg.isColoPrimary());
cmd.setRedirectNum(msg.getRedirectNum());
VmInstanceVO vm = dbf.findByUuid(msg.getVmInstanceUuid(), VmInstanceVO.class);
List<VolumeInventory> volumes = vm.getAllVolumes().stream().filter(v -> v.getType() == VolumeType.Data || v.getType() == VolumeType.Root).map(VolumeInventory::valueOf).collect(Collectors.toList());
cmd.setVolumes(VolumeTO.valueOf(volumes, KVMHostInventory.valueOf(getSelf())));
new Http<>(registerPrimaryVmHeartbeatPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final StartColoSyncReply reply = new StartColoSyncReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to register colo heartbeat for vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("unable to register colo heartbeat for vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final StartColoSyncReply reply = new StartColoSyncReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(StartColoSyncMsg msg) {
inQueue().name(String.format("start-colo-sync-vm-%s-on-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> startColoSync(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void startColoSync(StartColoSyncMsg msg, NoErrorCompletion completion) {
StartColoSyncCmd cmd = new StartColoSyncCmd();
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setBlockReplicationPort(msg.getBlockReplicationPort());
cmd.setNbdServerPort(msg.getNbdServerPort());
cmd.setSecondaryVmHostIp(msg.getSecondaryVmHostIp());
cmd.setCheckpointDelay(msg.getCheckpointDelay());
cmd.setFullSync(msg.isFullSync());
cmd.setNicNumber(msg.getNicNumber());
VmInstanceVO vm = dbf.findByUuid(msg.getVmInstanceUuid(), VmInstanceVO.class);
List<VolumeInventory> volumes = vm.getAllVolumes().stream().filter(v -> v.getType() == VolumeType.Data || v.getType() == VolumeType.Root).map(VolumeInventory::valueOf).collect(Collectors.toList());
cmd.setVolumes(VolumeTO.valueOf(volumes, KVMHostInventory.valueOf(getSelf())));
new Http<>(startColoSyncPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final StartColoSyncReply reply = new StartColoSyncReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to start colo sync vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("unable to start colo sync vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final StartColoSyncReply reply = new StartColoSyncReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(ConfigSecondaryVmMsg msg) {
inQueue().name(String.format("config-secondary-vm-%s-on-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> configSecondaryVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handle(ConfigPrimaryVmMsg msg) {
inQueue().name(String.format("config-primary-vm-%s-on-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> configPrimaryVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void configSecondaryVm(ConfigSecondaryVmMsg msg, NoErrorCompletion completion) {
checkStatus();
ConfigSecondaryVmCmd cmd = new ConfigSecondaryVmCmd();
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setPrimaryVmHostIp(msg.getPrimaryVmHostIp());
cmd.setNbdServerPort(msg.getNbdServerPort());
new Http<>(configSecondaryVmPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to config secondary vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("config secondary vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void configPrimaryVm(ConfigPrimaryVmMsg msg, NoErrorCompletion completion) {
checkStatus();
ConfigPrimaryVmCmd cmd = new ConfigPrimaryVmCmd();
cmd.setConfigs(msg.getConfigs().stream().sorted(Comparator.comparing(VmNicRedirectConfig::getDeviceId)).collect(Collectors.toList()));
cmd.setHostIp(msg.getHostIp());
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
new Http<>(configPrimaryVmPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to config primary vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("config primary vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(GetVmFirstBootDeviceOnHypervisorMsg msg) {
inQueue().name(String.format("get-first-boot-device-of-vm-%s-on-kvm-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> getVmFirstBootDevice(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void getVmFirstBootDevice(final GetVmFirstBootDeviceOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
GetVmFirstBootDeviceCmd cmd = new GetVmFirstBootDeviceCmd();
cmd.setUuid(msg.getVmInstanceUuid());
new Http<>(getVmFirstBootDevicePath, cmd, GetVmFirstBootDeviceResponse.class).call(new ReturnValueCompletion<GetVmFirstBootDeviceResponse>(msg, completion) {
@Override
public void success(GetVmFirstBootDeviceResponse ret) {
final GetVmFirstBootDeviceOnHypervisorReply reply = new GetVmFirstBootDeviceOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to get first boot dev of vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
reply.setFirstBootDevice(ret.getFirstBootDevice());
logger.debug(String.format("first boot dev of vm[uuid:%s] on kvm host[uuid:%s] is %s",
msg.getVmInstanceUuid(), self.getUuid(), ret.getFirstBootDevice()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final GetVmFirstBootDeviceOnHypervisorReply reply = new GetVmFirstBootDeviceOnHypervisorReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(GetVmDeviceAddressMsg msg) {
inQueue().name(String.format("get-device-address-of-vm-%s-on-kvm-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> getVmDeviceAddress(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void getVmDeviceAddress(final GetVmDeviceAddressMsg msg, final NoErrorCompletion completion) {
checkStatus();
GetVmDeviceAddressReply reply = new GetVmDeviceAddressReply();
GetVmDeviceAddressCmd cmd = new GetVmDeviceAddressCmd();
cmd.setUuid(msg.getVmInstanceUuid());
for (Map.Entry<String, List> e : msg.getInventories().entrySet()) {
String resourceType = e.getKey();
cmd.putDevice(resourceType, KVMVmDeviceType.fromResourceType(resourceType)
.getDeviceTOs(e.getValue(), KVMHostInventory.valueOf(getSelf()))
);
}
new Http<>(getVmDeviceAddressPath, cmd, GetVmDeviceAddressRsp.class).call(new ReturnValueCompletion<GetVmDeviceAddressRsp>(msg, completion) {
@Override
public void success(GetVmDeviceAddressRsp rsp) {
for (String resourceType : msg.getInventories().keySet()) {
reply.putAddresses(resourceType, rsp.getAddresses(resourceType).stream().map(it -> {
VmDeviceAddress address = new VmDeviceAddress();
address.setAddress(it.getAddress());
address.setAddressType(it.getAddressType());
address.setDeviceType(it.getDeviceType());
address.setResourceUuid(it.getUuid());
address.setResourceType(resourceType);
return address;
}).collect(Collectors.toList()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(GetKVMHostDownloadCredentialMsg msg) {
final GetKVMHostDownloadCredentialReply reply = new GetKVMHostDownloadCredentialReply();
String key = asf.getPrivateKey();
String hostname = null;
if (Strings.isNotEmpty(msg.getDataNetworkCidr())) {
String dataNetworkAddress = getDataNetworkAddress(self.getUuid(), msg.getDataNetworkCidr());
if (dataNetworkAddress != null) {
hostname = dataNetworkAddress;
}
}
reply.setHostname(hostname == null ? getSelf().getManagementIp() : hostname);
reply.setUsername(getSelf().getUsername());
reply.setSshPort(getSelf().getPort());
reply.setSshKey(key);
bus.reply(msg, reply);
}
protected static String getDataNetworkAddress(String hostUuid, String cidr) {
final String extraIps = HostSystemTags.EXTRA_IPS.getTokenByResourceUuid(
hostUuid, HostSystemTags.EXTRA_IPS_TOKEN);
if (extraIps == null) {
logger.debug(String.format("Host [uuid:%s] has no IPs in data network", hostUuid));
return null;
}
final String[] ips = extraIps.split(",");
for (String ip: ips) {
if (NetworkUtils.isIpv4InCidr(ip, cidr)) {
return ip;
}
}
return null;
}
private void handle(final IncreaseVmCpuMsg msg) {
IncreaseVmCpuReply reply = new IncreaseVmCpuReply();
IncreaseCpuCmd cmd = new IncreaseCpuCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setCpuNum(msg.getCpuNum());
new Http<>(onlineIncreaseCpuPath, cmd, IncreaseCpuResponse.class).call(new ReturnValueCompletion<IncreaseCpuResponse>(msg) {
@Override
public void success(IncreaseCpuResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setCpuNum(ret.getCpuNum());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final IncreaseVmMemoryMsg msg) {
IncreaseVmMemoryReply reply = new IncreaseVmMemoryReply();
IncreaseMemoryCmd cmd = new IncreaseMemoryCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setMemorySize(msg.getMemorySize());
new Http<>(onlineIncreaseMemPath, cmd, IncreaseMemoryResponse.class).call(new ReturnValueCompletion<IncreaseMemoryResponse>(msg) {
@Override
public void success(IncreaseMemoryResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setMemorySize(ret.getMemorySize());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void directlyDestroy(final VmDirectlyDestroyOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmDirectlyDestroyOnHypervisorReply reply = new VmDirectlyDestroyOnHypervisorReply();
DestroyVmCmd cmd = new DestroyVmCmd();
cmd.setUuid(msg.getVmUuid());
extEmitter.beforeDirectlyDestroyVmOnKvm(cmd);
new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(completion) {
@Override
public void success(DestroyVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
protected class RunInKVMHostQueue {
private String name;
private List<AsyncBackup> asyncBackups = new ArrayList<>();
public RunInKVMHostQueue name(String v) {
name = v;
return this;
}
public RunInKVMHostQueue asyncBackup(AsyncBackup v) {
asyncBackups.add(v);
return this;
}
public void run(Consumer<SyncTaskChain> consumer) {
DebugUtils.Assert(name != null, "name() must be called");
DebugUtils.Assert(!asyncBackups.isEmpty(), "asyncBackup must be called");
AsyncBackup one = asyncBackups.get(0);
AsyncBackup[] rest = asyncBackups.size() > 1 ?
asyncBackups.subList(1, asyncBackups.size()).toArray(new AsyncBackup[asyncBackups.size()-1]) :
new AsyncBackup[0];
thdf.chainSubmit(new ChainTask(one, rest) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(SyncTaskChain chain) {
consumer.accept(chain);
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
@Override
public String getName() {
return name;
}
});
}
}
protected RunInKVMHostQueue inQueue() {
return new RunInKVMHostQueue();
}
private void handle(final VmDirectlyDestroyOnHypervisorMsg msg) {
inQueue().name(String.format("directly-delete-vm-%s-msg-on-kvm-%s", msg.getVmUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> directlyDestroy(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private SshResult runShell(String script) {
Ssh ssh = new Ssh();
ssh.setHostname(self.getManagementIp());
ssh.setPort(getSelf().getPort());
ssh.setUsername(getSelf().getUsername());
ssh.setPassword(getSelf().getPassword());
ssh.shell(script);
return ssh.runAndClose();
}
private void handle(KvmRunShellMsg msg) {
SshResult result = runShell(msg.getScript());
KvmRunShellReply reply = new KvmRunShellReply();
if (result.isSshFailure()) {
reply.setError(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d ] to do DNS check," +
" please check if username/password is wrong; %s",
self.getManagementIp(), getSelf().getUsername(),
getSelf().getPort(), result.getExitErrorMessage()));
} else {
reply.setStdout(result.getStdout());
reply.setStderr(result.getStderr());
reply.setReturnCode(result.getReturnCode());
}
bus.reply(msg, reply);
}
private void handle(final GetVmConsoleAddressFromHostMsg msg) {
final GetVmConsoleAddressFromHostReply reply = new GetVmConsoleAddressFromHostReply();
GetVncPortCmd cmd = new GetVncPortCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
new Http<>(getConsolePortPath, cmd, GetVncPortResponse.class).call(new ReturnValueCompletion<GetVncPortResponse>(msg) {
@Override
public void success(GetVncPortResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setHostIp(self.getManagementIp());
reply.setProtocol(ret.getProtocol());
reply.setPort(ret.getPort());
VdiPortInfo vdiPortInfo = new VdiPortInfo();
if (ret.getVncPort() != null) {
vdiPortInfo.setVncPort(ret.getVncPort());
}
if (ret.getSpicePort() != null) {
vdiPortInfo.setSpicePort(ret.getSpicePort());
}
if (ret.getSpiceTlsPort() != null) {
vdiPortInfo.setSpiceTlsPort(ret.getSpiceTlsPort());
}
reply.setVdiPortInfo(vdiPortInfo);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final UpdateVmPriorityMsg msg) {
final UpdateVmPriorityReply reply = new UpdateVmPriorityReply();
if (self.getStatus() != HostStatus.Connected) {
reply.setError(operr("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus()));
bus.reply(msg, reply);
return;
}
UpdateVmPriorityCmd cmd = new UpdateVmPriorityCmd();
cmd.priorityConfigStructs = msg.getPriorityConfigStructs();
new Http<>(updateVmPriorityPath, cmd, UpdateVmPriorityRsp.class).call(new ReturnValueCompletion<UpdateVmPriorityRsp>(msg) {
@Override
public void success(UpdateVmPriorityRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final CheckVmStateOnHypervisorMsg msg) {
final CheckVmStateOnHypervisorReply reply = new CheckVmStateOnHypervisorReply();
if (self.getStatus() != HostStatus.Connected) {
reply.setError(operr("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus()));
bus.reply(msg, reply);
return;
}
// NOTE: don't run this message in the sync task
// there can be many such kind of messages
// running in the sync task may cause other tasks starved
CheckVmStateCmd cmd = new CheckVmStateCmd();
cmd.vmUuids = msg.getVmInstanceUuids();
cmd.hostUuid = self.getUuid();
extEmitter.beforeCheckVmState((KVMHostInventory) getSelfInventory(), msg, cmd);
new Http<>(checkVmStatePath, cmd, CheckVmStateRsp.class).call(new ReturnValueCompletion<CheckVmStateRsp>(msg) {
@Override
public void success(CheckVmStateRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
Map<String, String> m = new HashMap<>();
for (Map.Entry<String, String> e : ret.states.entrySet()) {
m.put(e.getKey(), KvmVmState.valueOf(e.getValue()).toVmInstanceState().toString());
}
extEmitter.afterCheckVmState((KVMHostInventory) getSelfInventory(), m);
reply.setStates(m);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final DetachIsoOnHypervisorMsg msg) {
inQueue().asyncBackup(msg)
.name(String.format("detach-iso-%s-on-host-%s", msg.getIsoUuid(), self.getUuid()))
.run(chain -> detachIso(msg, new NoErrorCompletion(msg, chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void detachIso(final DetachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) {
final DetachIsoOnHypervisorReply reply = new DetachIsoOnHypervisorReply();
DetachIsoCmd cmd = new DetachIsoCmd();
cmd.isoUuid = msg.getIsoUuid();
cmd.vmUuid = msg.getVmInstanceUuid();
Integer deviceId = IsoOperator.getIsoDeviceId(msg.getVmInstanceUuid(), msg.getIsoUuid());
assert deviceId != null;
cmd.deviceId = deviceId;
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreDetachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreDetachIsoExtensionPoint.class)) {
ext.preDetachIsoExtensionPoint(inv, cmd);
}
new Http<>(detachIsoPath, cmd, DetachIsoRsp.class).call(new ReturnValueCompletion<DetachIsoRsp>(msg, completion) {
@Override
public void success(DetachIsoRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final AttachIsoOnHypervisorMsg msg) {
inQueue().asyncBackup(msg)
.name(String.format("attach-iso-%s-on-host-%s", msg.getIsoSpec().getImageUuid(), self.getUuid()))
.run(chain -> attachIso(msg, new NoErrorCompletion(msg, chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void attachIso(final AttachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) {
final AttachIsoOnHypervisorReply reply = new AttachIsoOnHypervisorReply();
IsoTO iso = new IsoTO();
iso.setImageUuid(msg.getIsoSpec().getImageUuid());
iso.setPath(msg.getIsoSpec().getInstallPath());
iso.setDeviceId(msg.getIsoSpec().getDeviceId());
AttachIsoCmd cmd = new AttachIsoCmd();
cmd.vmUuid = msg.getVmInstanceUuid();
cmd.iso = iso;
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreAttachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreAttachIsoExtensionPoint.class)) {
ext.preAttachIsoExtensionPoint(inv, cmd);
}
new Http<>(attachIsoPath, cmd, AttachIsoRsp.class).call(new ReturnValueCompletion<AttachIsoRsp>(msg, completion) {
@Override
public void success(AttachIsoRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DetachNicFromVmOnHypervisorMsg msg) {
inQueue().name("detach-nic-on-kvm-host-" + self.getUuid())
.asyncBackup(msg)
.run(chain -> detachNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void detachNic(final DetachNicFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
final DetachNicFromVmOnHypervisorReply reply = new DetachNicFromVmOnHypervisorReply();
NicTO to = completeNicInfo(msg.getNic());
DetachNicCommand cmd = new DetachNicCommand();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setNic(to);
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KvmPreDetachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreDetachNicExtensionPoint.class)) {
ext.preDetachNicExtensionPoint(inv, cmd);
}
new Http<>(detachNicPath, cmd, DetachNicRsp.class).call(new ReturnValueCompletion<DetachNicRsp>(msg, completion) {
@Override
public void success(DetachNicRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void doHandleKvmSyncMsg(final KVMHostSyncHttpCallMsg msg, SyncTaskChain outter) {
inQueue().name(String.format("execute-sync-http-call-on-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.asyncBackup(outter)
.run(chain -> executeSyncHttpCall(msg, new NoErrorCompletion(chain, outter) {
@Override
public void done() {
chain.next();
outter.next();
}
}));
}
private static int getHostMaxThreadsNum() {
int n = (int)(KVMGlobalProperty.KVM_HOST_MAX_THREDS_RATIO * ThreadGlobalProperty.MAX_THREAD_NUM);
int m = ThreadGlobalProperty.MAX_THREAD_NUM / 5;
return Math.max(n, m);
}
private void handle(final KVMHostSyncHttpCallMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return "host-sync-control";
}
@Override
public void run(SyncTaskChain chain) {
doHandleKvmSyncMsg(msg, chain);
}
@Override
protected int getSyncLevel() {
return getHostMaxThreadsNum();
}
@Override
public String getName() {
return String.format("sync-call-on-kvm-%s", self.getUuid());
}
});
}
private void executeSyncHttpCall(KVMHostSyncHttpCallMsg msg, NoErrorCompletion completion) {
if (!msg.isNoStatusCheck()) {
checkStatus();
}
String url = buildUrl(msg.getPath());
MessageCommandRecorder.record(msg.getCommandClassName());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, self.getUuid());
LinkedHashMap rsp = restf.syncJsonPost(url, msg.getCommand(), headers, LinkedHashMap.class);
KVMHostSyncHttpCallReply reply = new KVMHostSyncHttpCallReply();
reply.setResponse(rsp);
bus.reply(msg, reply);
completion.done();
}
private void doHandleKvmAsyncMsg(final KVMHostAsyncHttpCallMsg msg, SyncTaskChain outter) {
inQueue().name(String.format("execute-async-http-call-on-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.asyncBackup(outter)
.run(chain -> executeAsyncHttpCall(msg, new NoErrorCompletion(chain, outter) {
@Override
public void done() {
chain.next();
outter.next();
}
}));
}
private void handle(final KVMHostAsyncHttpCallMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return "host-sync-control";
}
@Override
public void run(SyncTaskChain chain) {
doHandleKvmAsyncMsg(msg, chain);
}
@Override
protected int getSyncLevel() {
return getHostMaxThreadsNum();
}
@Override
public String getName() {
return String.format("async-call-on-kvm-%s", self.getUuid());
}
});
}
private String buildUrl(String path) {
UriComponentsBuilder ub = UriComponentsBuilder.newInstance();
ub.scheme(KVMGlobalProperty.AGENT_URL_SCHEME);
ub.host(self.getManagementIp());
ub.port(KVMGlobalProperty.AGENT_PORT);
if (!"".equals(KVMGlobalProperty.AGENT_URL_ROOT_PATH)) {
ub.path(KVMGlobalProperty.AGENT_URL_ROOT_PATH);
}
ub.path(path);
return ub.build().toUriString();
}
private void executeAsyncHttpCall(final KVMHostAsyncHttpCallMsg msg, final NoErrorCompletion completion) {
if (!msg.isNoStatusCheck()) {
checkStatus();
}
String url = buildUrl(msg.getPath());
MessageCommandRecorder.record(msg.getCommandClassName());
new Http<>(url, msg.getCommand(), LinkedHashMap.class)
.call(new ReturnValueCompletion<LinkedHashMap>(msg, completion) {
@Override
public void success(LinkedHashMap ret) {
KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply();
reply.setResponse(ret);
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply();
if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR)) {
reply.setError(err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "cannot do the operation on the KVM host"));
} else {
reply.setError(err);
}
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final MergeVolumeSnapshotOnKvmMsg msg) {
inQueue().name(String.format("merge-volume-snapshot-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> mergeVolumeSnapshot(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void mergeVolumeSnapshot(final MergeVolumeSnapshotOnKvmMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final MergeVolumeSnapshotOnKvmReply reply = new MergeVolumeSnapshotOnKvmReply();
VolumeInventory volume = msg.getTo();
if (volume.getVmInstanceUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, Op.EQ, volume.getVmInstanceUuid());
VmInstanceState state = q.findValue();
if (state != VmInstanceState.Stopped && state != VmInstanceState.Running && state != VmInstanceState.Paused && state != VmInstanceState.Destroyed) {
throw new OperationFailureException(operr("cannot do volume snapshot merge when vm[uuid:%s] is in state of %s." +
" The operation is only allowed when vm is Running or Stopped", volume.getUuid(), state));
}
if (state == VmInstanceState.Running) {
String libvirtVersion = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN);
if (new VersionComparator(KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION).compare(libvirtVersion) > 0) {
throw new OperationFailureException(operr("live volume snapshot merge needs libvirt version greater than %s," +
" current libvirt version is %s. Please stop vm and redo the operation or detach the volume if it's data volume",
KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION, libvirtVersion));
}
}
}
VolumeSnapshotInventory snapshot = msg.getFrom();
MergeSnapshotCmd cmd = new MergeSnapshotCmd();
cmd.setFullRebase(msg.isFullRebase());
cmd.setDestPath(volume.getInstallPath());
cmd.setSrcPath(snapshot.getPrimaryStorageInstallPath());
cmd.setVmUuid(volume.getVmInstanceUuid());
cmd.setVolume(VolumeTO.valueOf(volume, (KVMHostInventory) getSelfInventory()));
extEmitter.beforeMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd);
new Http<>(mergeSnapshotPath, cmd, MergeSnapshotRsp.class)
.call(new ReturnValueCompletion<MergeSnapshotRsp>(msg, completion) {
@Override
public void success(MergeSnapshotRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError());
}
extEmitter.afterMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd);
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final TakeSnapshotOnHypervisorMsg msg) {
inQueue().name(String.format("take-snapshot-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> {
takeSnapshot(msg);
chain.next();
});
}
private void takeSnapshot(final TakeSnapshotOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return getName();
}
@Override
public void run(SyncTaskChain chain) {
doTakeSnapshot(msg, new NoErrorCompletion() {
@Override
public void done() {
chain.next();
}
});
}
@Override
protected int getSyncLevel() {
return KVMGlobalConfig.HOST_SNAPSHOT_SYNC_LEVEL.value(Integer.class);
}
@Override
public String getName() {
return String.format("take-snapshot-on-kvm-%s", self.getUuid());
}
});
}
private void doTakeSnapshot(final TakeSnapshotOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final TakeSnapshotOnHypervisorReply reply = new TakeSnapshotOnHypervisorReply();
TakeSnapshotCmd cmd = new TakeSnapshotCmd();
if (msg.getVmUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, SimpleQuery.Op.EQ, msg.getVmUuid());
VmInstanceState vmState = q.findValue();
if (vmState != VmInstanceState.Running && vmState != VmInstanceState.Stopped && vmState != VmInstanceState.Paused) {
throw new OperationFailureException(operr("vm[uuid:%s] is not Running or Stopped, current state[%s]", msg.getVmUuid(), vmState));
}
if (!HostSystemTags.LIVE_SNAPSHOT.hasTag(self.getUuid())) {
if (vmState != VmInstanceState.Stopped) {
throw new OperationFailureException(err(SysErrors.NO_CAPABILITY_ERROR,
"kvm host[uuid:%s, name:%s, ip:%s] doesn't not support live snapshot. please stop vm[uuid:%s] and try again",
self.getUuid(), self.getName(), self.getManagementIp(), msg.getVmUuid()
));
}
}
cmd.setVolumeUuid(msg.getVolume().getUuid());
cmd.setVmUuid(msg.getVmUuid());
cmd.setVolume(VolumeTO.valueOf(msg.getVolume(), (KVMHostInventory) getSelfInventory()));
}
cmd.setVolumeInstallPath(msg.getVolume().getInstallPath());
cmd.setInstallPath(msg.getInstallPath());
cmd.setFullSnapshot(msg.isFullSnapshot());
cmd.setVolumeUuid(msg.getVolume().getUuid());
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("before-take-snapshot-%s-for-volume-%s", msg.getSnapshotName(), msg.getVolume().getUuid()));
chain.then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
extEmitter.beforeTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
new Http<>(snapshotPath, cmd, TakeSnapshotResponse.class).call(new ReturnValueCompletion<TakeSnapshotResponse>(msg, trigger) {
@Override
public void success(TakeSnapshotResponse ret) {
if (ret.isSuccess()) {
extEmitter.afterTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, ret);
reply.setNewVolumeInstallPath(ret.getNewVolumeInstallPath());
reply.setSnapshotInstallPath(ret.getSnapshotInstallPath());
reply.setSize(ret.getSize());
} else {
ErrorCode err = operr("operation error, because:%s", ret.getError());
extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, ret, err);
reply.setError(err);
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, null, errorCode);
reply.setError(errorCode);
trigger.fail(errorCode);
}
});
}
}).done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
bus.reply(msg, reply);
completion.done();
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
completion.done();
}
}).start();
}
private void migrateVm(final MigrateStruct s, final Completion completion) {
final TaskProgressRange parentStage = getTaskStage();
final TaskProgressRange MIGRATE_VM_STAGE = new TaskProgressRange(0, 90);
final String dstHostMigrateIp, dstHostMnIp, dstHostUuid;
final String vmUuid;
final StorageMigrationPolicy storageMigrationPolicy;
final boolean migrateFromDestination;
final String srcHostMigrateIp, srcHostMnIp, srcHostUuid;
vmUuid = s.vmUuid;
dstHostMigrateIp = s.dstHostMigrateIp;
dstHostMnIp = s.dstHostMnIp;
dstHostUuid = s.dstHostUuid;
storageMigrationPolicy = s.storageMigrationPolicy;
migrateFromDestination = s.migrateFromDestition;
srcHostMigrateIp = s.srcHostMigrateIp;
srcHostMnIp = s.srcHostMnIp;
srcHostUuid = s.srcHostUuid;
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.internalId);
q.add(VmInstanceVO_.uuid, Op.EQ, vmUuid);
final Long vmInternalId = q.findValue();
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("migrate-vm-%s-on-kvm-host-%s", vmUuid, self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "migrate-vm";
@Override
public void run(final FlowTrigger trigger, Map data) {
TaskProgressRange stage = markTaskStage(parentStage, MIGRATE_VM_STAGE);
boolean autoConverage = KVMGlobalConfig.MIGRATE_AUTO_CONVERGE.value(Boolean.class);
if (!autoConverage) {
autoConverage = s.strategy != null && s.strategy.equals("auto-converge");
}
boolean xbzrle = KVMGlobalConfig.MIGRATE_XBZRLE.value(Boolean.class);
MigrateVmCmd cmd = new MigrateVmCmd();
cmd.setDestHostIp(dstHostMigrateIp);
cmd.setSrcHostIp(srcHostMigrateIp);
cmd.setMigrateFromDestination(migrateFromDestination);
cmd.setStorageMigrationPolicy(storageMigrationPolicy == null ? null : storageMigrationPolicy.toString());
cmd.setVmUuid(vmUuid);
cmd.setAutoConverge(autoConverage);
cmd.setXbzrle(xbzrle);
cmd.setUseNuma(rcf.getResourceConfigValue(VmGlobalConfig.NUMA, vmUuid, Boolean.class));
cmd.setTimeout(timeoutManager.getTimeout());
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(migrateVmPath);
ub.host(migrateFromDestination ? dstHostMnIp : srcHostMnIp);
String migrateUrl = ub.build().toString();
new Http<>(migrateUrl, cmd, MigrateVmResponse.class).call(migrateFromDestination ? dstHostUuid : srcHostUuid, new ReturnValueCompletion<MigrateVmResponse>(trigger) {
@Override
public void success(MigrateVmResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = err(HostErrors.FAILED_TO_MIGRATE_VM_ON_HYPERVISOR,
"failed to migrate vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s], %s",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp, ret.getError()
);
trigger.fail(err);
} else {
String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp);
logger.debug(info);
reportProgress(stage.getEnd().toString());
trigger.next();
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "harden-vm-console-on-dst-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
HardenVmConsoleCmd cmd = new HardenVmConsoleCmd();
cmd.vmInternalId = vmInternalId;
cmd.vmUuid = vmUuid;
cmd.hostManagementIp = dstHostMnIp;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(dstHostMnIp);
ub.path(KVMConstant.KVM_HARDEN_CONSOLE_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(dstHostUuid, new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
//TODO: add GC
logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO add GC
logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, errorCode));
// continue
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "delete-vm-console-firewall-on-source-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
DeleteVmConsoleFirewallCmd cmd = new DeleteVmConsoleFirewallCmd();
cmd.vmInternalId = vmInternalId;
cmd.vmUuid = vmUuid;
cmd.hostManagementIp = srcHostMnIp;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(srcHostMnIp);
ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" +
" the source host[uuid:%s, ip:%s], %s", vmUuid, srcHostUuid, srcHostMigrateIp, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO
logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" +
" the source host[uuid:%s, ip:%s], %s", vmUuid, srcHostUuid, srcHostMigrateIp, errorCode));
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp);
logger.debug(info);
reportProgress(parentStage.getEnd().toString());
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
private void handle(final MigrateVmOnHypervisorMsg msg) {
inQueue().name(String.format("migrate-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> migrateVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
class MigrateStruct {
String vmUuid;
String dstHostMigrateIp;
String strategy;
String dstHostMnIp;
String dstHostUuid;
StorageMigrationPolicy storageMigrationPolicy;
boolean migrateFromDestition;
String srcHostMigrateIp;
String srcHostMnIp;
String srcHostUuid;
}
private MigrateStruct buildMigrateStuct(final MigrateVmOnHypervisorMsg msg){
MigrateStruct s = new MigrateStruct();
s.vmUuid = msg.getVmInventory().getUuid();
s.srcHostUuid = msg.getSrcHostUuid();
s.dstHostUuid = msg.getDestHostInventory().getUuid();
s.storageMigrationPolicy = msg.getStorageMigrationPolicy();
s.migrateFromDestition = msg.isMigrateFromDestination();
s.strategy = msg.getStrategy();
MigrateNetworkExtensionPoint.MigrateInfo migrateIpInfo = null;
for (MigrateNetworkExtensionPoint ext: pluginRgty.getExtensionList(MigrateNetworkExtensionPoint.class)) {
MigrateNetworkExtensionPoint.MigrateInfo r = ext.getMigrationAddressForVM(s.srcHostUuid, s.dstHostUuid);
if (r == null) {
continue;
}
migrateIpInfo = r;
}
s.dstHostMnIp = msg.getDestHostInventory().getManagementIp();
s.dstHostMigrateIp = migrateIpInfo == null ? s.dstHostMnIp : migrateIpInfo.dstMigrationAddress;
s.srcHostMnIp = Q.New(HostVO.class).eq(HostVO_.uuid, msg.getSrcHostUuid()).select(HostVO_.managementIp).findValue();
s.srcHostMigrateIp = migrateIpInfo == null ? s.srcHostMnIp : migrateIpInfo.srcMigrationAddress;
return s;
}
private void migrateVm(final MigrateVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
MigrateStruct s = buildMigrateStuct(msg);
final MigrateVmOnHypervisorReply reply = new MigrateVmOnHypervisorReply();
migrateVm(s, new Completion(msg, completion) {
@Override
public void success() {
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final VmUpdateNicOnHypervisorMsg msg) {
inQueue().name(String.format("update-nic-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> updateNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void updateNic(VmUpdateNicOnHypervisorMsg msg, NoErrorCompletion completion) {
checkStateAndStatus();
final VmUpdateNicOnHypervisorReply reply = new VmUpdateNicOnHypervisorReply();
List<VmNicVO> nics = Q.New(VmNicVO.class).eq(VmNicVO_.vmInstanceUuid, msg.getVmInstanceUuid()).list();
UpdateNicCmd cmd = new UpdateNicCmd();
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setNics(VmNicInventory.valueOf(nics).stream().map(this::completeNicInfo).collect(Collectors.toList()));
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreUpdateNicExtensionPoint ext : pluginRgty.getExtensionList(KVMPreUpdateNicExtensionPoint.class)) {
ext.preUpdateNic(inv, cmd);
}
new Http<>(updateNicPath, cmd, AttachNicResponse.class).call(new ReturnValueCompletion<AttachNicResponse>(msg, completion) {
@Override
public void success(AttachNicResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to update nic[vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s", msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final VmAttachNicOnHypervisorMsg msg) {
inQueue().name(String.format("attach-nic-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> attachNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void attachNic(final VmAttachNicOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
NicTO to = completeNicInfo(msg.getNicInventory());
final VmAttachNicOnHypervisorReply reply = new VmAttachNicOnHypervisorReply();
AttachNicCommand cmd = new AttachNicCommand();
cmd.setVmUuid(msg.getNicInventory().getVmInstanceUuid());
cmd.setNic(to);
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KvmPreAttachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreAttachNicExtensionPoint.class)) {
ext.preAttachNicExtensionPoint(inv, cmd);
}
new Http<>(attachNicPath, cmd, AttachNicResponse.class).call(new ReturnValueCompletion<AttachNicResponse>(msg, completion) {
@Override
public void success(AttachNicResponse ret) {
if (!ret.isSuccess()) {
if (ret.getError().contains("Device or resource busy")) {
reply.setError(operr("failed to attach nic[uuid:%s, vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s, please try again or delete device[%s] by yourself", msg.getNicInventory().getUuid(), msg.getNicInventory().getVmInstanceUuid(),
self.getUuid(), self.getManagementIp(), ret.getError(), msg.getNicInventory().getInternalName()));
} else {
reply.setError(operr("failed to attach nic[uuid:%s, vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s", msg.getNicInventory().getUuid(), msg.getNicInventory().getVmInstanceUuid(),
self.getUuid(), self.getManagementIp(), ret.getError()));
}
}
bus.reply(msg, reply);
if (ret.getPciAddress() != null) {
SystemTagCreator creator = KVMSystemTags.VMNIC_PCI_ADDRESS.newSystemTagCreator(msg.getNicInventory().getUuid());
creator.inherent = true;
creator.recreate = true;
creator.setTagByTokens(map(e(KVMSystemTags.VMNIC_PCI_ADDRESS_TOKEN, ret.getPciAddress().toString())));
creator.create();
}
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DetachVolumeFromVmOnHypervisorMsg msg) {
inQueue().name(String.format("detach-volume-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> detachVolume(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void detachVolume(final DetachVolumeFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final VolumeInventory vol = msg.getInventory();
final VmInstanceInventory vm = msg.getVmInventory();
VolumeTO to = VolumeTO.valueOfWithOutExtension(vol, (KVMHostInventory) getSelfInventory(), vm.getPlatform());
final DetachVolumeFromVmOnHypervisorReply reply = new DetachVolumeFromVmOnHypervisorReply();
final DetachDataVolumeCmd cmd = new DetachDataVolumeCmd();
cmd.setVolume(to);
cmd.setVmUuid(vm.getUuid());
extEmitter.beforeDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
new Http<>(detachDataVolumePath, cmd, DetachDataVolumeResponse.class).call(new ReturnValueCompletion<DetachDataVolumeResponse>(msg, completion) {
@Override
public void success(DetachDataVolumeResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = operr("failed to detach data volume[uuid:%s, installPath:%s] from vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s",
vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(), getSelf().getUuid(), getSelf().getManagementIp(), ret.getError());
reply.setError(err);
extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
} else {
extEmitter.afterDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
bus.reply(msg, reply);
completion.done();
}
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final AttachVolumeToVmOnHypervisorMsg msg) {
inQueue().name(String.format("attach-volume-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> attachVolume(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
static String computeWwnIfAbsent(String volumeUUid) {
String wwn;
String tag = KVMSystemTags.VOLUME_WWN.getTag(volumeUUid);
if (tag != null) {
wwn = KVMSystemTags.VOLUME_WWN.getTokenByTag(tag, KVMSystemTags.VOLUME_WWN_TOKEN);
} else {
wwn = new WwnUtils().getRandomWwn();
SystemTagCreator creator = KVMSystemTags.VOLUME_WWN.newSystemTagCreator(volumeUUid);
creator.inherent = true;
creator.setTagByTokens(Collections.singletonMap(KVMSystemTags.VOLUME_WWN_TOKEN, wwn));
creator.create();
}
DebugUtils.Assert(new WwnUtils().isValidWwn(wwn), String.format("Not a valid wwn[%s] for volume[uuid:%s]", wwn, volumeUUid));
return wwn;
}
private String makeAndSaveVmSystemSerialNumber(String vmUuid) {
String serialNumber;
String tag = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTag(vmUuid);
if (tag != null) {
serialNumber = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTokenByTag(tag, VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN);
} else {
SystemTagCreator creator = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.newSystemTagCreator(vmUuid);
creator.ignoreIfExisting = true;
creator.inherent = true;
creator.setTagByTokens(map(e(VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN, UUID.randomUUID().toString())));
SystemTagInventory inv = creator.create();
serialNumber = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTokenByTag(inv.getTag(), VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN);
}
return serialNumber;
}
private void attachVolume(final AttachVolumeToVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
KVMHostInventory host = (KVMHostInventory) getSelfInventory();
final VolumeInventory vol = msg.getInventory();
final VmInstanceInventory vm = msg.getVmInventory();
VolumeTO to = VolumeTO.valueOfWithOutExtension(vol, host, vm.getPlatform());
final AttachVolumeToVmOnHypervisorReply reply = new AttachVolumeToVmOnHypervisorReply();
final AttachDataVolumeCmd cmd = new AttachDataVolumeCmd();
cmd.setVolume(to);
cmd.setVmUuid(msg.getVmInventory().getUuid());
cmd.getAddons().put("attachedDataVolumes", VolumeTO.valueOf(msg.getAttachedDataVolumes(), host));
Map data = new HashMap();
extEmitter.beforeAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd, data);
new Http<>(attachDataVolumePath, cmd, AttachDataVolumeResponse.class).call(new ReturnValueCompletion<AttachDataVolumeResponse>(msg, completion) {
@Override
public void success(AttachDataVolumeResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to attach data volume[uuid:%s, installPath:%s] to vm[uuid:%s, name:%s]" +
" on kvm host[uuid:%s, ip:%s], because %s", vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(),
getSelf().getUuid(), getSelf().getManagementIp(), ret.getError()));
extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError(), data);
} else {
extEmitter.afterAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, err, data);
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DestroyVmOnHypervisorMsg msg) {
inQueue().name(String.format("destroy-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> destroyVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void destroyVm(final DestroyVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
DestroyVmCmd cmd = new DestroyVmCmd();
cmd.setUuid(vminv.getUuid());
try {
extEmitter.beforeDestroyVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv, cmd);
} catch (KVMException e) {
ErrorCode err = operr("failed to destroy vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(msg, completion) {
@Override
public void success(DestroyVmResponse ret) {
DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, "unable to destroy vm[uuid:%s, name:%s] on kvm host [uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
logger.debug(String.format("successfully destroyed vm[uuid:%s] on kvm host[uuid:%s]", vminv.getUuid(), self.getUuid()));
extEmitter.destroyVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply();
if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR, SysErrors.TIMEOUT)) {
err = err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "unable to destroy a vm");
}
reply.setError(err);
extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final RebootVmOnHypervisorMsg msg) {
inQueue().name(String.format("reboot-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> rebootVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private List<String> toKvmBootDev(List<String> order) {
List<String> ret = new ArrayList<String>();
for (String o : order) {
if (VmBootDevice.HardDisk.toString().equals(o)) {
ret.add(BootDev.hd.toString());
} else if (VmBootDevice.CdRom.toString().equals(o)) {
ret.add(BootDev.cdrom.toString());
} else if (VmBootDevice.Network.toString().equals(o)) {
ret.add(BootDev.network.toString());
} else {
throw new CloudRuntimeException(String.format("unknown boot device[%s]", o));
}
}
return ret;
}
private void rebootVm(final RebootVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
try {
extEmitter.beforeRebootVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv);
} catch (KVMException e) {
String err = String.format("failed to reboot vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
logger.warn(err, e);
throw new OperationFailureException(operr(err));
}
RebootVmCmd cmd = new RebootVmCmd();
long timeout = TimeUnit.MILLISECONDS.toSeconds(msg.getTimeout());
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(timeout);
cmd.setBootDev(toKvmBootDev(msg.getBootOrders()));
new Http<>(rebootVmPath, cmd, RebootVmResponse.class).call(new ReturnValueCompletion<RebootVmResponse>(msg, completion) {
@Override
public void success(RebootVmResponse ret) {
RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_REBOOT_VM_ON_HYPERVISOR, "unable to reboot vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
extEmitter.rebootVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply();
reply.setError(err);
extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final StopVmOnHypervisorMsg msg) {
inQueue().name(String.format("stop-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> stopVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void stopVm(final StopVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
StopVmCmd cmd = new StopVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setType(msg.getType());
cmd.setTimeout(120);
try {
extEmitter.beforeStopVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv, cmd);
} catch (KVMException e) {
ErrorCode err = operr("failed to stop vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
new Http<>(stopVmPath, cmd, StopVmResponse.class).call(new ReturnValueCompletion<StopVmResponse>(msg, completion) {
@Override
public void success(StopVmResponse ret) {
StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to stop vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
extEmitter.stopVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply();
if (err.isError(SysErrors.IO_ERROR, SysErrors.HTTP_ERROR)) {
err = err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "unable to stop a vm");
}
reply.setError(err);
extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err);
bus.reply(msg, reply);
completion.done();
}
});
}
@Transactional
private void setDataVolumeUseVirtIOSCSI(final VmInstanceSpec spec) {
String vmUuid = spec.getVmInventory().getUuid();
Map<String, Integer> diskOfferingUuid_Num = new HashMap<>();
List<Map<String, String>> tokenList = KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI.getTokensOfTagsByResourceUuid(vmUuid);
for (Map<String, String> tokens : tokenList) {
String diskOfferingUuid = tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_TOKEN);
Integer num = Integer.parseInt(tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_NUM_TOKEN));
diskOfferingUuid_Num.put(diskOfferingUuid, num);
}
for (VolumeInventory volumeInv : spec.getDestDataVolumes()) {
if (volumeInv.getType().equals(VolumeType.Root.toString())) {
continue;
}
if (diskOfferingUuid_Num.containsKey(volumeInv.getDiskOfferingUuid())
&& diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) > 0) {
tagmgr.createNonInherentSystemTag(volumeInv.getUuid(),
KVMSystemTags.VOLUME_VIRTIO_SCSI.getTagFormat(),
VolumeVO.class.getSimpleName());
diskOfferingUuid_Num.put(volumeInv.getDiskOfferingUuid(),
diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) - 1);
}
}
}
private void handle(final CreateVmOnHypervisorMsg msg) {
inQueue().name(String.format("start-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> {
setDataVolumeUseVirtIOSCSI(msg.getVmSpec());
startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
});
}
private void handle(final UpdateSpiceChannelConfigMsg msg) {
UpdateSpiceChannelConfigReply reply = new UpdateSpiceChannelConfigReply();
UpdateSpiceChannelConfigCmd cmd = new UpdateSpiceChannelConfigCmd();
new Http<>(updateSpiceChannelConfigPath, cmd, UpdateSpiceChannelConfigResponse.class).call(new ReturnValueCompletion<UpdateSpiceChannelConfigResponse>(msg) {
@Override
public void success(UpdateSpiceChannelConfigResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("Host[%s] update spice channel config faild, because %s", msg.getHostUuid(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
reply.setRestartLibvirt(ret.restartLibvirt);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
});
}
private L2NetworkInventory getL2NetworkTypeFromL3NetworkUuid(String l3NetworkUuid) {
String sql = "select l2 from L2NetworkVO l2 where l2.uuid = (select l3.l2NetworkUuid from L3NetworkVO l3 where l3.uuid = :l3NetworkUuid)";
TypedQuery<L2NetworkVO> query = dbf.getEntityManager().createQuery(sql, L2NetworkVO.class);
query.setParameter("l3NetworkUuid", l3NetworkUuid);
L2NetworkVO l2vo = query.getSingleResult();
return L2NetworkInventory.valueOf(l2vo);
}
@Transactional(readOnly = true)
private NicTO completeNicInfo(VmNicInventory nic) {
/* all l3 networks of the nic has same l2 network */
L3NetworkInventory l3Inv = L3NetworkInventory.valueOf(dbf.findByUuid(nic.getL3NetworkUuid(), L3NetworkVO.class));
L2NetworkInventory l2inv = getL2NetworkTypeFromL3NetworkUuid(nic.getL3NetworkUuid());
KVMCompleteNicInformationExtensionPoint extp = factory.getCompleteNicInfoExtension(L2NetworkType.valueOf(l2inv.getType()));
NicTO to = extp.completeNicInformation(l2inv, l3Inv, nic);
if (to.getUseVirtio() == null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.platform);
q.add(VmInstanceVO_.uuid, Op.EQ, nic.getVmInstanceUuid());
String platform = q.findValue();
to.setUseVirtio(ImagePlatform.valueOf(platform).isParaVirtualization());
to.setIps(getCleanTrafficIp(nic));
}
if (!nic.getType().equals(VmInstanceConstant.VIRTUAL_NIC_TYPE)) {
return to;
}
// build vhost addon
if (to.getDriverType() == null) {
if (nic.getDriverType() != null) {
to.setDriverType(nic.getDriverType());
} else {
to.setDriverType(to.getUseVirtio() ? nicManager.getDefaultPVNicDriver() : nicManager.getDefaultNicDriver());
}
}
VHostAddOn vHostAddOn = new VHostAddOn();
if (to.getDriverType().equals(nicManager.getDefaultPVNicDriver())) {
vHostAddOn.setQueueNum(rcf.getResourceConfigValue(VmGlobalConfig.VM_NIC_MULTIQUEUE_NUM, nic.getVmInstanceUuid(), Integer.class));
} else {
vHostAddOn.setQueueNum(VmGlobalConfig.VM_NIC_MULTIQUEUE_NUM.defaultValue(Integer.class));
}
if (VmSystemTags.VM_VRING_BUFFER_SIZE.hasTag(nic.getVmInstanceUuid())) {
Map<String, String> tokens = VmSystemTags.VM_VRING_BUFFER_SIZE.getTokensByResourceUuid(nic.getVmInstanceUuid());
if (tokens.get(VmSystemTags.RX_SIZE_TOKEN) != null) {
vHostAddOn.setRxBufferSize(tokens.get(VmSystemTags.RX_SIZE_TOKEN));
}
if (tokens.get(VmSystemTags.TX_SIZE_TOKEN) != null) {
vHostAddOn.setTxBufferSize(tokens.get(VmSystemTags.TX_SIZE_TOKEN));
}
}
to.setvHostAddOn(vHostAddOn);
String pci = KVMSystemTags.VMNIC_PCI_ADDRESS.getTokenByResourceUuid(nic.getUuid(), KVMSystemTags.VMNIC_PCI_ADDRESS_TOKEN);
if (pci != null) {
to.setPci(PciAddressConfig.fromString(pci));
}
return to;
}
private List<String> getCleanTrafficIp(VmNicInventory nic) {
boolean isUserVm = Q.New(VmInstanceVO.class)
.eq(VmInstanceVO_.uuid, nic.getVmInstanceUuid()).select(VmInstanceVO_.type)
.findValue().equals(VmInstanceConstant.USER_VM_TYPE);
if (!isUserVm) {
return null;
}
String tagValue = VmSystemTags.CLEAN_TRAFFIC.getTokenByResourceUuid(nic.getVmInstanceUuid(), VmSystemTags.CLEAN_TRAFFIC_TOKEN);
if (Boolean.parseBoolean(tagValue) || (tagValue == null && VmGlobalConfig.VM_CLEAN_TRAFFIC.value(Boolean.class))) {
return VmNicHelper.getIpAddresses(nic);
}
return null;
}
static String getVolumeTOType(VolumeInventory vol) {
DebugUtils.Assert(vol.getInstallPath() != null, String.format("volume [%s] installPath is null, it has not been initialized", vol.getUuid()));
return vol.getInstallPath().startsWith("iscsi") ? VolumeTO.ISCSI : VolumeTO.FILE;
}
private void startVm(final VmInstanceSpec spec, final NeedReplyMessage msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final StartVmCmd cmd = new StartVmCmd();
boolean virtio;
String nestedVirtualization;
String platform = spec.getVmInventory().getPlatform() == null ? spec.getImageSpec().getInventory().getPlatform() :
spec.getVmInventory().getPlatform();
if (ImagePlatform.Windows.toString().equals(platform)) {
virtio = VmSystemTags.WINDOWS_VOLUME_ON_VIRTIO.hasTag(spec.getVmInventory().getUuid());
} else {
virtio = ImagePlatform.valueOf(platform).isParaVirtualization();
}
int cpuNum = spec.getVmInventory().getCpuNum();
cmd.setCpuNum(cpuNum);
int socket;
int cpuOnSocket;
//TODO: this is a HACK!!!
if (ImagePlatform.Windows.toString().equals(platform) || ImagePlatform.WindowsVirtio.toString().equals(platform)) {
if (cpuNum == 1) {
socket = 1;
cpuOnSocket = 1;
} else if (cpuNum % 2 == 0) {
socket = 2;
cpuOnSocket = cpuNum / 2;
} else {
socket = cpuNum;
cpuOnSocket = 1;
}
} else {
socket = 1;
cpuOnSocket = cpuNum;
}
cmd.setImagePlatform(platform);
cmd.setSocketNum(socket);
cmd.setCpuOnSocket(cpuOnSocket);
cmd.setVmName(spec.getVmInventory().getName());
cmd.setVmInstanceUuid(spec.getVmInventory().getUuid());
cmd.setCpuSpeed(spec.getVmInventory().getCpuSpeed());
cmd.setMemory(spec.getVmInventory().getMemorySize());
cmd.setMaxMemory(self.getCapacity().getTotalPhysicalMemory());
cmd.setClock(ImagePlatform.isType(platform, ImagePlatform.Windows, ImagePlatform.WindowsVirtio) ? "localtime" : "utc");
cmd.setVideoType(VmGlobalConfig.VM_VIDEO_TYPE.value(String.class));
if (VmSystemTags.QXL_MEMORY.hasTag(spec.getVmInventory().getUuid())) {
Map<String,String> qxlMemory = VmSystemTags.QXL_MEMORY.getTokensByResourceUuid(spec.getVmInventory().getUuid());
cmd.setQxlMemory(qxlMemory);
}
if (VmSystemTags.SOUND_TYPE.hasTag(spec.getVmInventory().getUuid())) {
cmd.setSoundType(VmSystemTags.SOUND_TYPE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmInstanceVO.class, VmSystemTags.SOUND_TYPE_TOKEN));
}
cmd.setInstanceOfferingOnlineChange(VmSystemTags.INSTANCEOFFERING_ONLIECHANGE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmSystemTags.INSTANCEOFFERING_ONLINECHANGE_TOKEN) != null);
cmd.setKvmHiddenState(rcf.getResourceConfigValue(VmGlobalConfig.KVM_HIDDEN_STATE, spec.getVmInventory().getUuid(), Boolean.class));
cmd.setSpiceStreamingMode(VmGlobalConfig.VM_SPICE_STREAMING_MODE.value(String.class));
cmd.setEmulateHyperV(rcf.getResourceConfigValue(VmGlobalConfig.EMULATE_HYPERV, spec.getVmInventory().getUuid(), Boolean.class));
cmd.setAdditionalQmp(VmGlobalConfig.ADDITIONAL_QMP.value(Boolean.class));
cmd.setApplianceVm(spec.getVmInventory().getType().equals("ApplianceVm"));
cmd.setSystemSerialNumber(makeAndSaveVmSystemSerialNumber(spec.getVmInventory().getUuid()));
if (!NetworkGlobalProperty.CHASSIS_ASSET_TAG.isEmpty()) {
cmd.setChassisAssetTag(NetworkGlobalProperty.CHASSIS_ASSET_TAG);
}
String machineType = VmSystemTags.MACHINE_TYPE.getTokenByResourceUuid(cmd.getVmInstanceUuid(),
VmInstanceVO.class, VmSystemTags.MACHINE_TYPE_TOKEN);
cmd.setMachineType(StringUtils.isNotEmpty(machineType) ? machineType : "pc");
if (KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM.hasTag(spec.getVmInventory().getUuid())) {
cmd.setPredefinedPciBridgeNum(Integer.valueOf(KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM.getTokenByResourceUuid(spec.getVmInventory().getUuid(), KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM_TOKEN)));
}
if (VmMachineType.q35.toString().equals(machineType)) {
cmd.setPciePortNums(VmGlobalConfig.PCIE_PORT_NUMS.value(Integer.class));
if (cmd.getPredefinedPciBridgeNum() == null) {
cmd.setPredefinedPciBridgeNum(1);
}
}
VmPriorityLevel level = new VmPriorityOperator().getVmPriority(spec.getVmInventory().getUuid());
VmPriorityConfigVO priorityVO = Q.New(VmPriorityConfigVO.class).eq(VmPriorityConfigVO_.level, level).find();
cmd.setPriorityConfigStruct(new PriorityConfigStruct(priorityVO, spec.getVmInventory().getUuid()));
VolumeTO rootVolume = new VolumeTO();
rootVolume.setInstallPath(spec.getDestRootVolume().getInstallPath());
rootVolume.setDeviceId(spec.getDestRootVolume().getDeviceId());
rootVolume.setDeviceType(getVolumeTOType(spec.getDestRootVolume()));
rootVolume.setVolumeUuid(spec.getDestRootVolume().getUuid());
rootVolume.setUseVirtio(virtio);
rootVolume.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(spec.getDestRootVolume().getUuid()));
rootVolume.setWwn(computeWwnIfAbsent(spec.getDestRootVolume().getUuid()));
rootVolume.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value());
nestedVirtualization = KVMGlobalConfig.NESTED_VIRTUALIZATION.value(String.class);
cmd.setNestedVirtualization(nestedVirtualization);
cmd.setRootVolume(rootVolume);
cmd.setUseBootMenu(VmGlobalConfig.VM_BOOT_MENU.value(Boolean.class));
List<VolumeTO> dataVolumes = new ArrayList<>(spec.getDestDataVolumes().size());
for (VolumeInventory data : spec.getDestDataVolumes()) {
VolumeTO v = VolumeTO.valueOfWithOutExtension(data, (KVMHostInventory) getSelfInventory(), spec.getVmInventory().getPlatform());
// always use virtio driver for data volume
v.setUseVirtio(true);
dataVolumes.add(v);
}
dataVolumes.sort(Comparator.comparing(VolumeTO::getDeviceId));
cmd.setDataVolumes(dataVolumes);
List<VolumeTO> cacheVolumes = new ArrayList<>(spec.getDestCacheVolumes().size());
for (VolumeInventory data : spec.getDestCacheVolumes()) {
VolumeTO v = VolumeTO.valueOfWithOutExtension(data, (KVMHostInventory) getSelfInventory(), spec.getVmInventory().getPlatform());
// always use virtio driver for data volume
v.setUseVirtio(true);
cacheVolumes.add(v);
}
cmd.setCacheVolumes(cacheVolumes);
cmd.setVmInternalId(spec.getVmInventory().getInternalId());
List<NicTO> nics = new ArrayList<>(spec.getDestNics().size());
for (VmNicInventory nic : spec.getDestNics()) {
NicTO to = completeNicInfo(nic);
nics.add(to);
}
nics = nics.stream().sorted(Comparator.comparing(NicTO::getDeviceId)).collect(Collectors.toList());
cmd.setNics(nics);
for (VmInstanceSpec.CdRomSpec cdRomSpec : spec.getCdRomSpecs()) {
CdRomTO cdRomTO = new CdRomTO();
cdRomTO.setPath(cdRomSpec.getInstallPath());
cdRomTO.setImageUuid(cdRomSpec.getImageUuid());
cdRomTO.setDeviceId(cdRomSpec.getDeviceId());
cdRomTO.setEmpty(cdRomSpec.getImageUuid() == null);
cmd.getCdRoms().add(cdRomTO);
}
String bootMode = VmSystemTags.BOOT_MODE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmSystemTags.BOOT_MODE_TOKEN);
cmd.setBootMode(bootMode == null ? ImageBootMode.Legacy.toString() : bootMode);
deviceBootOrderOperator.updateVmDeviceBootOrder(cmd, spec);
cmd.setBootDev(toKvmBootDev(spec.getBootOrders()));
cmd.setHostManagementIp(self.getManagementIp());
cmd.setConsolePassword(spec.getConsolePassword());
cmd.setUsbRedirect(spec.getUsbRedirect());
cmd.setVDIMonitorNumber(Integer.valueOf(spec.getVDIMonitorNumber()));
cmd.setUseNuma(rcf.getResourceConfigValue(VmGlobalConfig.NUMA, spec.getVmInventory().getUuid(), Boolean.class));
cmd.setVmPortOff(VmGlobalConfig.VM_PORT_OFF.value(Boolean.class));
cmd.setConsoleMode("vnc");
cmd.setTimeout(TimeUnit.MINUTES.toSeconds(5));
if (spec.isCreatePaused()) {
cmd.setCreatePaused(true);
}
addons(spec, cmd);
KVMHostInventory khinv = KVMHostInventory.valueOf(getSelf());
extEmitter.beforeStartVmOnKvm(khinv, spec, cmd);
extEmitter.addOn(khinv, spec, cmd);
new Http<>(startVmPath, cmd, StartVmResponse.class).call(new ReturnValueCompletion<StartVmResponse>(msg, completion) {
@Override
public void success(StartVmResponse ret) {
StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply();
if (ret.isSuccess()) {
String info = String.format("successfully start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s]",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp());
logger.debug(info);
extEmitter.startVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), spec);
} else {
reply.setError(err(HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR, "failed to start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, reply.getError());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply();
reply.setError(err);
reply.setSuccess(false);
extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void addons(final VmInstanceSpec spec, StartVmCmd cmd) {
KVMAddons.Channel chan = new KVMAddons.Channel();
chan.setSocketPath(makeChannelSocketPath(spec.getVmInventory().getUuid()));
chan.setTargetName("org.qemu.guest_agent.0");
cmd.getAddons().put(KVMAddons.Channel.NAME, chan);
logger.debug(String.format("make kvm channel device[path:%s, target:%s]", chan.getSocketPath(), chan.getTargetName()));
}
private String makeChannelSocketPath(String apvmuuid) {
return PathUtil.join(String.format("/var/lib/libvirt/qemu/%s", apvmuuid));
}
private void handle(final StartVmOnHypervisorMsg msg) {
inQueue().name(String.format("start-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> startVmInQueue(msg, chain));
}
private void startVmInQueue(StartVmOnHypervisorMsg msg, SyncTaskChain outterChain) {
thdf.chainSubmit(new ChainTask(msg, outterChain) {
@Override
public String getSyncSignature() {
return getName();
}
@Override
public void run(final SyncTaskChain chain) {
startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain, outterChain) {
@Override
public void done() {
chain.next();
outterChain.next();
}
});
}
@Override
public String getName() {
return String.format("start-vm-on-kvm-%s-inner-queue", self.getUuid());
}
@Override
protected int getSyncLevel() {
return KVMGlobalConfig.VM_CREATE_CONCURRENCY.value(Integer.class);
}
});
}
private void handle(final CheckNetworkPhysicalInterfaceMsg msg) {
inQueue().name(String.format("check-network-physical-interface-on-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> checkPhysicalInterface(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void pauseVm(final PauseVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
PauseVmOnHypervisorReply reply = new PauseVmOnHypervisorReply();
PauseVmCmd cmd = new PauseVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(120);
new Http<>(pauseVmPath, cmd, PauseVmResponse.class).call(new ReturnValueCompletion<PauseVmResponse>(msg, completion) {
@Override
public void success(PauseVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to pause vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final PauseVmOnHypervisorMsg msg) {
inQueue().name(String.format("pause-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> pauseVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handle(final ResumeVmOnHypervisorMsg msg) {
inQueue().name(String.format("resume-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> resumeVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void resumeVm(final ResumeVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
ResumeVmOnHypervisorReply reply = new ResumeVmOnHypervisorReply();
ResumeVmCmd cmd = new ResumeVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(120);
new Http<>(resumeVmPath, cmd, ResumeVmResponse.class).call(new ReturnValueCompletion<ResumeVmResponse>(msg, completion) {
@Override
public void success(ResumeVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to resume vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void checkPhysicalInterface(CheckNetworkPhysicalInterfaceMsg msg, NoErrorCompletion completion) {
checkState();
CheckPhysicalNetworkInterfaceCmd cmd = new CheckPhysicalNetworkInterfaceCmd();
cmd.addInterfaceName(msg.getPhysicalInterface());
CheckNetworkPhysicalInterfaceReply reply = new CheckNetworkPhysicalInterfaceReply();
CheckPhysicalNetworkInterfaceResponse rsp = restf.syncJsonPost(checkPhysicalNetworkInterfacePath, cmd, CheckPhysicalNetworkInterfaceResponse.class);
if (!rsp.isSuccess()) {
if (rsp.getFailedInterfaceNames().isEmpty()) {
reply.setError(operr("operation error, because:%s", rsp.getError()));
} else {
reply.setError(operr("failed to check physical network interfaces[names : %s] on kvm host[uuid:%s, ip:%s]",
msg.getPhysicalInterface(), context.getInventory().getUuid(), context.getInventory().getManagementIp()));
}
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void handleMessage(Message msg) {
try {
if (msg instanceof APIMessage) {
handleApiMessage((APIMessage) msg);
} else {
handleLocalMessage(msg);
}
} catch (Exception e) {
bus.logExceptionWithMessageDump(msg, e);
bus.replyErrorByMessageType(msg, e);
}
}
@Override
public void changeStateHook(HostState current, HostStateEvent stateEvent, HostState next) {
}
@Override
public void deleteHook() {
}
@Override
protected HostInventory getSelfInventory() {
return KVMHostInventory.valueOf(getSelf());
}
@Override
protected void pingHook(final Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("ping-kvm-host-%s", self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "ping-host";
@AfterDone
List<Runnable> afterDone = new ArrayList<>();
@Override
public void run(FlowTrigger trigger, Map data) {
PingCmd cmd = new PingCmd();
cmd.hostUuid = self.getUuid();
restf.asyncJsonPost(pingPath, cmd, new JsonAsyncRESTCallback<PingResponse>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(PingResponse ret) {
if (ret.isSuccess()) {
if (!self.getUuid().equals(ret.getHostUuid())) {
afterDone.add(() -> {
String info = i18n("detected abnormal status[host uuid change, expected: %s but: %s] of kvmagent," +
"it's mainly caused by kvmagent restarts behind zstack management server. Report this to ping task, it will issue a reconnect soon", self.getUuid(), ret.getHostUuid());
logger.warn(info);
changeConnectionState(HostStatusEvent.disconnected);
new HostDisconnectedCanonicalEvent(self.getUuid(), argerr(info)).fire();
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg);
});
}
trigger.next();
} else {
trigger.fail(operr("%s", ret.getError()));
}
}
@Override
public Class<PingResponse> getReturnClass() {
return PingResponse.class;
}
},TimeUnit.SECONDS, HostGlobalConfig.PING_HOST_TIMEOUT.value(Long.class));
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-ping-no-failure-plugins";
@Override
public void run(FlowTrigger trigger, Map data) {
List<KVMPingAgentNoFailureExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentNoFailureExtensionPoint.class);
if (exts.isEmpty()) {
trigger.next();
return;
}
AsyncLatch latch = new AsyncLatch(exts.size(), new NoErrorCompletion(trigger) {
@Override
public void done() {
trigger.next();
}
});
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPingAgentNoFailureExtensionPoint ext : exts) {
ext.kvmPingAgentNoFailure(inv, new NoErrorCompletion(latch) {
@Override
public void done() {
latch.ack();
}
});
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-ping-plugins";
@Override
public void run(FlowTrigger trigger, Map data) {
List<KVMPingAgentExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentExtensionPoint.class);
Iterator<KVMPingAgentExtensionPoint> it = exts.iterator();
callPlugin(it, trigger);
}
private void callPlugin(Iterator<KVMPingAgentExtensionPoint> it, FlowTrigger trigger) {
if (!it.hasNext()) {
trigger.next();
return;
}
KVMPingAgentExtensionPoint ext = it.next();
logger.debug(String.format("calling KVMPingAgentExtensionPoint[%s]", ext.getClass()));
ext.kvmPingAgent((KVMHostInventory) getSelfInventory(), new Completion(trigger) {
@Override
public void success() {
callPlugin(it, trigger);
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
protected int getVmMigrateQuantity() {
return KVMGlobalConfig.VM_MIGRATION_QUANTITY.value(Integer.class);
}
private ErrorCode connectToAgent() {
ErrorCode errCode = null;
try {
ConnectCmd cmd = new ConnectCmd();
cmd.setHostUuid(self.getUuid());
cmd.setSendCommandUrl(restf.getSendCommandUrl());
cmd.setIptablesRules(KVMGlobalProperty.IPTABLES_RULES);
cmd.setIgnoreMsrs(KVMGlobalConfig.KVM_IGNORE_MSRS.value(Boolean.class));
if (HostSystemTags.PAGE_TABLE_EXTENSION_DISABLED.hasTag(self.getUuid(), HostVO.class) || !KVMSystemTags.EPT_CPU_FLAG.hasTag(self.getUuid())) {
cmd.setPageTableExtensionDisabled(true);
}
ConnectResponse rsp = restf.syncJsonPost(connectPath, cmd, ConnectResponse.class);
if (!rsp.isSuccess() || !rsp.isIptablesSucc()) {
errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s",
self.getUuid(), self.getManagementIp(), connectPath, rsp.getError());
} else {
VersionComparator libvirtVersion = new VersionComparator(rsp.getLibvirtVersion());
VersionComparator qemuVersion = new VersionComparator(rsp.getQemuVersion());
boolean liveSnapshot = libvirtVersion.compare(KVMConstant.MIN_LIBVIRT_LIVESNAPSHOT_VERSION) >= 0
&& qemuVersion.compare(KVMConstant.MIN_QEMU_LIVESNAPSHOT_VERSION) >= 0;
String hostOS = HostSystemTags.OS_DISTRIBUTION.getTokenByResourceUuid(self.getUuid(), HostSystemTags.OS_DISTRIBUTION_TOKEN);
//liveSnapshot = liveSnapshot && (!"CentOS".equals(hostOS) || KVMGlobalConfig.ALLOW_LIVE_SNAPSHOT_ON_REDHAT.value(Boolean.class));
if (liveSnapshot) {
logger.debug(String.format("kvm host[OS:%s, uuid:%s, name:%s, ip:%s] supports live snapshot with libvirt[version:%s], qemu[version:%s]",
hostOS, self.getUuid(), self.getName(), self.getManagementIp(), rsp.getLibvirtVersion(), rsp.getQemuVersion()));
recreateNonInherentTag(HostSystemTags.LIVE_SNAPSHOT);
} else {
HostSystemTags.LIVE_SNAPSHOT.deleteInherentTag(self.getUuid());
}
}
} catch (RestClientException e) {
errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s", self.getUuid(), self.getManagementIp(),
connectPath, e.getMessage());
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
errCode = inerr(t.getMessage());
}
return errCode;
}
private KVMHostVO getSelf() {
return (KVMHostVO) self;
}
private void continueConnect(final ConnectHostInfo info, final Completion completion) {
ErrorCode errCode = connectToAgent();
if (errCode != null) {
throw new OperationFailureException(errCode);
}
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("continue-connecting-kvm-host-%s-%s", self.getManagementIp(), self.getUuid()));
chain.allowWatch();
for (KVMHostConnectExtensionPoint extp : factory.getConnectExtensions()) {
KVMHostConnectedContext ctx = new KVMHostConnectedContext();
ctx.setInventory((KVMHostInventory) getSelfInventory());
ctx.setNewAddedHost(info.isNewAdded());
ctx.setBaseUrl(baseUrl);
ctx.setSkipPackages(info.getSkipPackages());
chain.then(extp.createKvmHostConnectingFlow(ctx));
}
chain.done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
if (noStorageAccessible()){
completion.fail(operr("host can not access any primary storage, please check network"));
} else {
completion.success();
}
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(err(HostErrors.CONNECTION_ERROR, errCode, "connection error for KVM host[uuid:%s, ip:%s]", self.getUuid(),
self.getManagementIp()));
}
}).start();
}
@Transactional(readOnly = true)
private boolean noStorageAccessible(){
// detach ps will delete PrimaryStorageClusterRefVO first.
List<String> attachedPsUuids = Q.New(PrimaryStorageClusterRefVO.class)
.select(PrimaryStorageClusterRefVO_.primaryStorageUuid)
.eq(PrimaryStorageClusterRefVO_.clusterUuid, self.getClusterUuid())
.listValues();
long attachedPsCount = attachedPsUuids.size();
long inaccessiblePsCount = attachedPsCount == 0 ? 0 : Q.New(PrimaryStorageHostRefVO.class)
.eq(PrimaryStorageHostRefVO_.hostUuid, self.getUuid())
.eq(PrimaryStorageHostRefVO_.status, PrimaryStorageHostStatus.Disconnected)
.in(PrimaryStorageHostRefVO_.primaryStorageUuid, attachedPsUuids)
.count();
return inaccessiblePsCount == attachedPsCount && attachedPsCount > 0;
}
private void createHostVersionSystemTags(String distro, String release, String version) {
createTagWithoutNonValue(HostSystemTags.OS_DISTRIBUTION, HostSystemTags.OS_DISTRIBUTION_TOKEN, distro, true);
createTagWithoutNonValue(HostSystemTags.OS_RELEASE, HostSystemTags.OS_RELEASE_TOKEN, release, true);
createTagWithoutNonValue(HostSystemTags.OS_VERSION, HostSystemTags.OS_VERSION_TOKEN, version, true);
}
private void createTagWithoutNonValue(SystemTag tag, String token, String value, boolean inherent) {
if (value == null) {
return;
}
recreateTag(tag, token, value, inherent);
}
private void recreateNonInherentTag(SystemTag tag, String token, String value) {
recreateTag(tag, token, value, false);
}
private void recreateNonInherentTag(SystemTag tag) {
recreateTag(tag, null, null, false);
}
private void recreateInherentTag(SystemTag tag, String token, String value) {
recreateTag(tag, token, value, true);
}
private void recreateTag(SystemTag tag, String token, String value, boolean inherent) {
SystemTagCreator creator = tag.newSystemTagCreator(self.getUuid());
Optional.ofNullable(token).ifPresent(it -> creator.setTagByTokens(Collections.singletonMap(token, value)));
creator.inherent = inherent;
creator.recreate = true;
creator.create();
}
@Override
public void connectHook(final ConnectHostInfo info, final Completion complete) {
if (CoreGlobalProperty.UNIT_TEST_ON) {
if (info.isNewAdded()) {
createHostVersionSystemTags("zstack", "kvmSimulator", tester.get(ZTester.KVM_HostVersion, "0.1", String.class));
if (null == KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.LIBVIRT_VERSION, KVMSystemTags.LIBVIRT_VERSION_TOKEN, tester.get(ZTester.KVM_LibvirtVersion, "1.2.9", String.class), true);
}
if (null == KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.QEMU_IMG_VERSION, KVMSystemTags.QEMU_IMG_VERSION_TOKEN, tester.get(ZTester.KVM_QemuImageVersion, "2.0.0", String.class), true);
}
if (null == KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.CPU_MODEL_NAME, KVMSystemTags.CPU_MODEL_NAME_TOKEN, tester.get(ZTester.KVM_CpuModelName, "Broadwell", String.class), true);
}
if (null == KVMSystemTags.EPT_CPU_FLAG.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.EPT_CPU_FLAG_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.EPT_CPU_FLAG, KVMSystemTags.EPT_CPU_FLAG_TOKEN, "ept", false);
}
if (null == HostSystemTags.CPU_ARCHITECTURE.getTokenByResourceUuid(self.getUuid(), HostSystemTags.CPU_ARCHITECTURE_TOKEN)) {
createTagWithoutNonValue(HostSystemTags.CPU_ARCHITECTURE, HostSystemTags.CPU_ARCHITECTURE_TOKEN, "x86_64", false);
}
if (!checkQemuLibvirtVersionOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL.hasTag(self.getClusterUuid())) {
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL
.getTokenByResourceUuid(self.getClusterUuid(), KVMSystemTags.CHECK_CLUSTER_CPU_MODEL_TOKEN)
.equals("true")
&& !checkCpuModelOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
complete.success();
return;
}
if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
}
continueConnect(info, complete);
} else {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("run-ansible-for-kvm-%s", self.getUuid()));
chain.allowWatch();
chain.then(new ShareFlow() {
boolean deployed = false;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "test-if-ssh-port-open";
@Override
public void run(FlowTrigger trigger, Map data) {
long sshTimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_OPEN_TIMEOUT.value(Long.class));
long timeout = System.currentTimeMillis() + sshTimeout;
long ctimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_CONNECT_TIMEOUT.value(Integer.class).longValue());
thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask(trigger) {
@Override
public boolean run() {
if (testPort()) {
trigger.next();
return true;
}
return ifTimeout();
}
private boolean testPort() {
if (!NetworkUtils.isRemotePortOpen(getSelf().getManagementIp(), getSelf().getPort(), (int) ctimeout)) {
logger.debug(String.format("host[uuid:%s, name:%s, ip:%s]'s ssh port[%s] is not ready yet", getSelf().getUuid(), getSelf().getName(), getSelf().getManagementIp(), getSelf().getPort()));
return false;
} else {
return true;
}
}
private boolean ifTimeout() {
if (System.currentTimeMillis() > timeout) {
trigger.fail(operr("the host[%s] ssh port[%s] not open after %s seconds, connect timeout", getSelf().getManagementIp(), getSelf().getPort(), TimeUnit.MILLISECONDS.toSeconds(sshTimeout)));
return true;
} else {
return false;
}
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return 2;
}
@Override
public String getName() {
return "test-ssh-port-open-for-kvm-host";
}
});
}
});
if (info.isNewAdded()) {
if ((!AnsibleGlobalProperty.ZSTACK_REPO.contains("zstack-mn")) && (!AnsibleGlobalProperty.ZSTACK_REPO.equals("false"))) {
flow(new NoRollbackFlow() {
String __name__ = "ping-DNS-check-list";
@Override
public void run(FlowTrigger trigger, Map data) {
String checkList;
if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.ALI_REPO)) {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_ALIYUN.value();
} else if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.NETEASE_REPO)) {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_163.value();
} else {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_LIST.value();
}
checkList = checkList.replaceAll(",", " ");
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runScriptWithToken("scripts/check-public-dns-name.sh",
map(e("dnsCheckList", checkList)));
if (ret.isSshFailure()) {
trigger.fail(operr("unable to connect to KVM[ip:%s, username:%s, sshPort: %d, ] to do DNS check, please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()));
} else if (ret.getReturnCode() != 0) {
trigger.fail(operr("failed to ping all DNS/IP in %s; please check /etc/resolv.conf to make sure your host is able to reach public internet", checkList));
} else {
trigger.next();
}
}
});
}
}
flow(new NoRollbackFlow() {
String __name__ = "check-if-host-can-reach-management-node";
@Override
public void run(FlowTrigger trigger, Map data) {
ShellUtils.run(String.format("arp -d %s || true", getSelf().getManagementIp()));
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
sshShell.setWithSudo(false);
SshResult ret = sshShell.runCommand(String.format("curl --connect-timeout 10 %s|| wget --spider -q --connect-timeout=10 %s|| test $? -eq 8", restf.getCallbackUrl(), restf.getCallbackUrl()));
if (ret.isSshFailure()) {
throw new OperationFailureException(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d] to check the management node connectivity," +
"please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()));
} else if (ret.getReturnCode() != 0) {
throw new OperationFailureException(operr("the KVM host[ip:%s] cannot access the management node's callback url. It seems" +
" that the KVM host cannot reach the management IP[%s]. %s %s", self.getManagementIp(), restf.getHostName(),
ret.getStderr(), ret.getExitErrorMessage()));
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "apply-ansible-playbook";
@Override
public void run(final FlowTrigger trigger, Map data) {
String srcPath = PathUtil.findFileOnClassPath(String.format("ansible/kvm/%s", agentPackageName), true).getAbsolutePath();
String destPath = String.format("/var/lib/zstack/kvm/package/%s", agentPackageName);
SshFileMd5Checker checker = new SshFileMd5Checker();
checker.setUsername(getSelf().getUsername());
checker.setPassword(getSelf().getPassword());
checker.setSshPort(getSelf().getPort());
checker.setTargetIp(getSelf().getManagementIp());
checker.addSrcDestPair(SshFileMd5Checker.ZSTACKLIB_SRC_PATH, String.format("/var/lib/zstack/kvm/package/%s", AnsibleGlobalProperty.ZSTACKLIB_PACKAGE_NAME));
checker.addSrcDestPair(srcPath, destPath);
SshChronyConfigChecker chronyChecker = new SshChronyConfigChecker();
chronyChecker.setTargetIp(getSelf().getManagementIp());
chronyChecker.setUsername(getSelf().getUsername());
chronyChecker.setPassword(getSelf().getPassword());
chronyChecker.setSshPort(getSelf().getPort());
SshYumRepoChecker repoChecker = new SshYumRepoChecker();
repoChecker.setTargetIp(getSelf().getManagementIp());
repoChecker.setUsername(getSelf().getUsername());
repoChecker.setPassword(getSelf().getPassword());
repoChecker.setSshPort(getSelf().getPort());
CallBackNetworkChecker callbackChecker = new CallBackNetworkChecker();
callbackChecker.setTargetIp(getSelf().getManagementIp());
callbackChecker.setUsername(getSelf().getUsername());
callbackChecker.setPassword(getSelf().getPassword());
callbackChecker.setPort(getSelf().getPort());
callbackChecker.setCallbackIp(Platform.getManagementServerIp());
callbackChecker.setCallBackPort(CloudBusGlobalProperty.HTTP_PORT);
AnsibleRunner runner = new AnsibleRunner();
runner.installChecker(checker);
runner.installChecker(chronyChecker);
runner.installChecker(repoChecker);
runner.installChecker(callbackChecker);
for (KVMHostAddSshFileMd5CheckerExtensionPoint exp : pluginRgty.getExtensionList(KVMHostAddSshFileMd5CheckerExtensionPoint.class)) {
SshFileMd5Checker sshFileMd5Checker = exp.getSshFileMd5Checker(getSelf());
if (sshFileMd5Checker != null) {
runner.installChecker(sshFileMd5Checker);
}
}
runner.setAgentPort(KVMGlobalProperty.AGENT_PORT);
runner.setTargetIp(getSelf().getManagementIp());
runner.setTargetUuid(getSelf().getUuid());
runner.setPlayBookName(KVMConstant.ANSIBLE_PLAYBOOK_NAME);
runner.setUsername(getSelf().getUsername());
runner.setPassword(getSelf().getPassword());
runner.setSshPort(getSelf().getPort());
if (info.isNewAdded()) {
runner.putArgument("init", "true");
runner.setFullDeploy(true);
}
if (NetworkGlobalProperty.SKIP_IPV6) {
runner.putArgument("skipIpv6", "true");
}
if (NetworkGlobalProperty.BRIDGE_DISABLE_IPTABLES) {
runner.putArgument("bridgeDisableIptables", "true");
}
runner.putArgument("pkg_kvmagent", agentPackageName);
runner.putArgument("hostname", String.format("%s.zstack.org", self.getManagementIp().replaceAll("\\.", "-")));
if (CoreGlobalProperty.SYNC_NODE_TIME) {
if (CoreGlobalProperty.CHRONY_SERVERS == null || CoreGlobalProperty.CHRONY_SERVERS.isEmpty()) {
trigger.fail(operr("chrony server not configured!"));
return;
}
runner.putArgument("chrony_servers", String.join(",", CoreGlobalProperty.CHRONY_SERVERS));
}
runner.putArgument("skip_packages", info.getSkipPackages());
runner.putArgument("update_packages", String.valueOf(CoreGlobalProperty.UPDATE_PKG_WHEN_CONNECT));
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl());
ub.path(new StringBind(KVMConstant.KVM_ANSIBLE_LOG_PATH_FROMAT).bind("uuid", self.getUuid()).toString());
String postUrl = ub.build().toString();
runner.putArgument("post_url", postUrl);
runner.run(new ReturnValueCompletion<Boolean>(trigger) {
@Override
public void success(Boolean run) {
if (run != null) {
deployed = run;
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "configure-iptables";
@Override
public void run(FlowTrigger trigger, Map data) {
StringBuilder builder = new StringBuilder();
if (!KVMGlobalProperty.MN_NETWORKS.isEmpty()) {
builder.append(String.format("sudo bash %s -m %s -p %s -c %s",
"/var/lib/zstack/kvm/kvmagent-iptables",
KVMConstant.IPTABLES_COMMENTS,
KVMGlobalConfig.KVMAGENT_ALLOW_PORTS_LIST.value(String.class),
String.join(",", KVMGlobalProperty.MN_NETWORKS)));
} else {
builder.append(String.format("sudo bash %s -m %s -p %s",
"/var/lib/zstack/kvm/kvmagent-iptables",
KVMConstant.IPTABLES_COMMENTS,
KVMGlobalConfig.KVMAGENT_ALLOW_PORTS_LIST.value(String.class)));
}
try {
new Ssh().shell(builder.toString())
.setUsername(getSelf().getUsername())
.setPassword(getSelf().getPassword())
.setHostname(getSelf().getManagementIp())
.setPort(getSelf().getPort()).runErrorByExceptionAndClose();
} catch (SshException ex) {
throw new OperationFailureException(operr(ex.toString()));
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "echo-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
restf.echo(echoPath, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
boolean needRestart = KVMGlobalConfig.RESTART_AGENT_IF_FAKE_DEAD.value(Boolean.class);
if (!deployed && needRestart) {
// if not deployed and echo failed, we thought it is fake dead, see: ZSTACK-18628
AnsibleRunner runner = new AnsibleRunner();
runner.setAgentPort(KVMGlobalProperty.AGENT_PORT);
runner.setTargetIp(getSelf().getManagementIp());
runner.setTargetUuid(getSelf().getUuid());
runner.setUsername(getSelf().getUsername());
runner.setPassword(getSelf().getPassword());
runner.setSshPort(getSelf().getPort());
runner.restartAgent(AnsibleConstant.KVM_AGENT_NAME, new Completion(trigger) {
@Override
public void success() {
restf.echo(echoPath, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
} else {
trigger.fail(errorCode);
}
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "update-kvmagent-dependencies";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!CoreGlobalProperty.UPDATE_PKG_WHEN_CONNECT) {
trigger.next();
return;
}
UpdateDependencyCmd cmd = new UpdateDependencyCmd();
cmd.hostUuid = self.getUuid();
new Http<>(updateDependencyPath, cmd, UpdateDependencyRsp.class)
.call(new ReturnValueCompletion<UpdateDependencyRsp>(trigger) {
@Override
public void success(UpdateDependencyRsp ret) {
if (ret.isSuccess()) {
trigger.next();
} else {
trigger.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "collect-kvm-host-facts";
@Override
public void run(final FlowTrigger trigger, Map data) {
HostFactCmd cmd = new HostFactCmd();
new Http<>(hostFactPath, cmd, HostFactResponse.class)
.call(new ReturnValueCompletion<HostFactResponse>(trigger) {
@Override
public void success(HostFactResponse ret) {
if (!ret.isSuccess()) {
trigger.fail(operr("operation error, because:%s", ret.getError()));
return;
}
if (ret.getHvmCpuFlag() == null) {
trigger.fail(operr("cannot find either 'vmx' or 'svm' in /proc/cpuinfo, please make sure you have enabled virtualization in your BIOS setting"));
return;
}
// create system tags of os::version etc
createHostVersionSystemTags(ret.getOsDistribution(), ret.getOsRelease(), ret.getOsVersion());
createTagWithoutNonValue(KVMSystemTags.QEMU_IMG_VERSION, KVMSystemTags.QEMU_IMG_VERSION_TOKEN, ret.getQemuImgVersion(), false);
createTagWithoutNonValue(KVMSystemTags.LIBVIRT_VERSION, KVMSystemTags.LIBVIRT_VERSION_TOKEN, ret.getLibvirtVersion(), false);
createTagWithoutNonValue(KVMSystemTags.HVM_CPU_FLAG, KVMSystemTags.HVM_CPU_FLAG_TOKEN, ret.getHvmCpuFlag(), false);
createTagWithoutNonValue(KVMSystemTags.EPT_CPU_FLAG, KVMSystemTags.EPT_CPU_FLAG_TOKEN, ret.getEptFlag(), false);
createTagWithoutNonValue(KVMSystemTags.CPU_MODEL_NAME, KVMSystemTags.CPU_MODEL_NAME_TOKEN, ret.getCpuModelName(), false);
createTagWithoutNonValue(HostSystemTags.CPU_ARCHITECTURE, HostSystemTags.CPU_ARCHITECTURE_TOKEN, ret.getCpuArchitecture(), true);
createTagWithoutNonValue(HostSystemTags.HOST_CPU_MODEL_NAME, HostSystemTags.HOST_CPU_MODEL_NAME_TOKEN, ret.getHostCpuModelName(), true);
createTagWithoutNonValue(HostSystemTags.CPU_GHZ, HostSystemTags.CPU_GHZ_TOKEN, ret.getCpuGHz(), true);
createTagWithoutNonValue(HostSystemTags.SYSTEM_PRODUCT_NAME, HostSystemTags.SYSTEM_PRODUCT_NAME_TOKEN, ret.getSystemProductName(), true);
createTagWithoutNonValue(HostSystemTags.SYSTEM_SERIAL_NUMBER, HostSystemTags.SYSTEM_SERIAL_NUMBER_TOKEN, ret.getSystemSerialNumber(), true);
if (ret.getLibvirtVersion().compareTo(KVMConstant.MIN_LIBVIRT_VIRTIO_SCSI_VERSION) >= 0) {
recreateNonInherentTag(KVMSystemTags.VIRTIO_SCSI);
}
List<String> ips = ret.getIpAddresses();
if (ips != null) {
ips.remove(self.getManagementIp());
if (CoreGlobalProperty.MN_VIP != null) {
ips.remove(CoreGlobalProperty.MN_VIP);
}
if (!ips.isEmpty()) {
recreateNonInherentTag(HostSystemTags.EXTRA_IPS, HostSystemTags.EXTRA_IPS_TOKEN, StringUtils.join(ips, ","));
} else {
HostSystemTags.EXTRA_IPS.delete(self.getUuid());
}
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
if (info.isNewAdded()) {
flow(new NoRollbackFlow() {
String __name__ = "check-qemu-libvirt-version";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!checkQemuLibvirtVersionOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL.hasTag(self.getClusterUuid())) {
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL
.getTokenByResourceUuid(self.getClusterUuid(), KVMSystemTags.CHECK_CLUSTER_CPU_MODEL_TOKEN)
.equals("true")
&& !checkCpuModelOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
trigger.next();
return;
}
if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
trigger.next();
}
});
}
flow(new NoRollbackFlow() {
String __name__ = "prepare-host-env";
@Override
public void run(FlowTrigger trigger, Map data) {
String script = "which iptables > /dev/null && iptables -C FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 && iptables -D FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 || true";
runShell(script);
trigger.next();
}
});
error(new FlowErrorHandler(complete) {
@Override
public void handle(ErrorCode errCode, Map data) {
complete.fail(errCode);
}
});
done(new FlowDoneHandler(complete) {
@Override
public void handle(Map data) {
continueConnect(info, complete);
}
});
}
}).start();
}
}
private void handle(final ShutdownHostMsg msg) {
inQueue().name(String.format("shut-down-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> handleShutdownHost(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handleShutdownHost(final ShutdownHostMsg msg, final NoErrorCompletion completion) {
ShutdownHostReply reply = new ShutdownHostReply();
KVMAgentCommands.ShutdownHostCmd cmd = new KVMAgentCommands.ShutdownHostCmd();
new Http<>(shutdownHost, cmd, ShutdownHostResponse.class).call(new ReturnValueCompletion<ShutdownHostResponse>(msg, completion) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
@Override
public void success(KVMAgentCommands.ShutdownHostResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
bus.reply(msg, reply);
completion.done();
} else {
changeConnectionState(HostStatusEvent.disconnected);
waitForHostShutdown(reply, completion);
}
}
private boolean testPort() {
if (CoreGlobalProperty.UNIT_TEST_ON) {
return false;
}
long ctimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_CONNECT_TIMEOUT.value(Integer.class).longValue());
if (!NetworkUtils.isRemotePortOpen(getSelf().getManagementIp(), getSelf().getPort(), (int) ctimeout)) {
logger.debug(String.format("host[uuid:%s, name:%s, ip:%s]'s ssh port[%s] is no longer open, " +
"seem to be shutdowned", getSelf().getUuid(), getSelf().getName(), getSelf().getManagementIp(), getSelf().getPort()));
return false;
} else {
return true;
}
}
private void waitForHostShutdown(ShutdownHostReply reply, NoErrorCompletion noErrorCompletion) {
thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask(msg, noErrorCompletion) {
@Override
public boolean run() {
if (testPort()) {
return false;
}
bus.reply(msg, reply);
noErrorCompletion.done();
return true;
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return 2;
}
@Override
public String getName() {
return "test-ssh-port-open-for-kvm-host";
}
});
}
});
}
private void handle(final CancelHostTaskMsg msg) {
CancelHostTaskReply reply = new CancelHostTaskReply();
cancelJob(msg.getCancellationApiId(), new Completion(msg) {
@Override
public void success() {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void cancelJob(String apiId, Completion completion) {
CancelCmd cmd = new CancelCmd();
cmd.setCancellationApiId(apiId);
new Http<>(cancelJob, cmd, CancelRsp.class).call(new ReturnValueCompletion<CancelRsp>(completion) {
@Override
public void success(CancelRsp ret) {
if (ret.isSuccess()) {
completion.success();
} else {
completion.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
}
});
}
private boolean checkCpuModelOfHost() {
List<String> hostUuidsInCluster = Q.New(HostVO.class)
.select(HostVO_.uuid)
.eq(HostVO_.clusterUuid, self.getClusterUuid())
.notEq(HostVO_.uuid, self.getUuid())
.listValues();
if (hostUuidsInCluster.isEmpty()) {
return true;
}
Map<String, List<String>> cpuModelNames = KVMSystemTags.CPU_MODEL_NAME.getTags(hostUuidsInCluster);
if (cpuModelNames != null && cpuModelNames.size() != 0) {
String clusterCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByTag(
cpuModelNames.values().iterator().next().get(0),
KVMSystemTags.CPU_MODEL_NAME_TOKEN
);
String hostCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN
);
if (clusterCpuModelName != null && !clusterCpuModelName.equals(hostCpuModelName)) {
return false;
}
}
return true;
}
private boolean isHostDisabledOrMaintenance() {
dbf.reload(self);
final boolean disabled = self.getState() == HostState.Disabled;
final boolean maintenance = self.getState() == HostState.Maintenance;
return (disabled || maintenance);
}
@Override
protected void updateOsHook(UpdateHostOSMsg msg, Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("update-operating-system-for-host-%s", self.getUuid()));
chain.then(new ShareFlow() {
final HostState oldState = self.getState();
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "double-check-host-state-status";
@Override
public void run(FlowTrigger trigger, Map data) {
if (self.getState() == HostState.PreMaintenance) {
trigger.fail(Platform.operr("host is in the premaintenance state, cannot update os"));
} else if (self.getStatus() != HostStatus.Connected) {
trigger.fail(Platform.operr("host is not in the connected status, cannot update os"));
} else {
trigger.next();
}
}
});
flow(new Flow() {
String __name__ = "make-host-in-disabled-state";
@Override
public void run(FlowTrigger trigger, Map data) {
if (isHostDisabledOrMaintenance()) {
trigger.next();
return;
}
// disable the host before update its os, keep the vms running in it
ChangeHostStateMsg cmsg = new ChangeHostStateMsg();
cmsg.setUuid(self.getUuid());
cmsg.setStateEvent(HostStateEvent.disable.toString());
bus.makeTargetServiceIdByResourceUuid(cmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(cmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
trigger.next();
} else {
trigger.fail(reply.getError());
}
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (isHostDisabledOrMaintenance()) {
trigger.rollback();
return;
}
// back to old host state
if (oldState == HostState.Disabled) {
changeState(HostStateEvent.disable);
} else {
changeState(HostStateEvent.enable);
}
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "update-host-os";
@Override
public void run(FlowTrigger trigger, Map data) {
UpdateHostOSCmd cmd = new UpdateHostOSCmd();
cmd.hostUuid = self.getUuid();
cmd.excludePackages = msg.getExcludePackages();
cmd.updatePackages = msg.getUpdatePackages();
cmd.releaseVersion = msg.getReleaseVersion();
cmd.enableExpRepo = msg.isEnableExperimentalRepo();
new Http<>(updateHostOSPath, cmd, UpdateHostOSRsp.class)
.call(new ReturnValueCompletion<UpdateHostOSRsp>(trigger) {
@Override
public void success(UpdateHostOSRsp ret) {
if (ret.isSuccess()) {
trigger.next();
} else {
trigger.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "recover-host-state";
@Override
public void run(FlowTrigger trigger, Map data) {
if (isHostDisabledOrMaintenance()) {
trigger.next();
return;
}
// back to old host state
if (oldState == HostState.Disabled) {
changeState(HostStateEvent.disable);
} else {
changeState(HostStateEvent.enable);
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "auto-reconnect-host";
@Override
public void run(FlowTrigger trigger, Map data) {
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info("successfully reconnected host " + self.getUuid());
} else {
logger.error("failed to reconnect host " + self.getUuid());
}
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
logger.debug(String.format("successfully updated operating system for host[uuid:%s]", self.getUuid()));
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
logger.warn(String.format("failed to updated operating system for host[uuid:%s] because %s",
self.getUuid(), errCode.getDetails()));
completion.fail(errCode);
}
});
}
}).start();
}
private boolean checkMigrateNetworkCidrOfHost(String cidr) {
if (NetworkUtils.isIpv4InCidr(self.getManagementIp(), cidr)) {
return true;
}
final String extraIps = HostSystemTags.EXTRA_IPS.getTokenByResourceUuid(
self.getUuid(), HostSystemTags.EXTRA_IPS_TOKEN);
if (extraIps == null) {
logger.error(String.format("Host[uuid:%s] has no IPs in migrate network", self.getUuid()));
return false;
}
final String[] ips = extraIps.split(",");
for (String ip: ips) {
if (NetworkUtils.isIpv4InCidr(ip, cidr)) {
return true;
}
}
return false;
}
private boolean checkQemuLibvirtVersionOfHost() {
List<String> hostUuidsInCluster = Q.New(HostVO.class)
.select(HostVO_.uuid)
.eq(HostVO_.clusterUuid, self.getClusterUuid())
.notEq(HostVO_.uuid, self.getUuid())
.listValues();
if (hostUuidsInCluster.isEmpty()) {
return true;
}
Map<String, List<String>> qemuVersions = KVMSystemTags.QEMU_IMG_VERSION.getTags(hostUuidsInCluster);
if (qemuVersions != null && qemuVersions.size() != 0) {
String clusterQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByTag(
qemuVersions.values().iterator().next().get(0),
KVMSystemTags.QEMU_IMG_VERSION_TOKEN
);
String hostQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN
);
if (clusterQemuVer != null && !clusterQemuVer.equals(hostQemuVer)) {
return false;
}
}
Map<String, List<String>> libvirtVersions = KVMSystemTags.LIBVIRT_VERSION.getTags(hostUuidsInCluster);
if (libvirtVersions != null && libvirtVersions.size() != 0) {
String clusterLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByTag(
libvirtVersions.values().iterator().next().get(0),
KVMSystemTags.LIBVIRT_VERSION_TOKEN
);
String hostLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN
);
if (clusterLibvirtVer != null && !clusterLibvirtVer.equals(hostLibvirtVer)) {
return false;
}
}
return true;
}
@Override
protected int getHostSyncLevel() {
return KVMGlobalConfig.HOST_SYNC_LEVEL.value(Integer.class);
}
@Override
protected HostVO updateHost(APIUpdateHostMsg msg) {
if (!(msg instanceof APIUpdateKVMHostMsg)) {
return super.updateHost(msg);
}
KVMHostVO vo = (KVMHostVO) super.updateHost(msg);
vo = vo == null ? getSelf() : vo;
APIUpdateKVMHostMsg umsg = (APIUpdateKVMHostMsg) msg;
if (umsg.getUsername() != null) {
vo.setUsername(umsg.getUsername());
}
if (umsg.getPassword() != null) {
vo.setPassword(umsg.getPassword());
}
if (umsg.getSshPort() != null && umsg.getSshPort() > 0 && umsg.getSshPort() <= 65535) {
vo.setPort(umsg.getSshPort());
}
return vo;
}
@Override
protected void scanVmPorts(ScanVmPortMsg msg) {
ScanVmPortReply reply = new ScanVmPortReply();
reply.setSupportScan(true);
checkStatus();
ScanVmPortCmd cmd = new ScanVmPortCmd();
cmd.setIp(msg.getIp());
cmd.setBrname(msg.getBrName());
cmd.setPort(msg.getPort());
new Http<>(scanVmPortPath, cmd, ScanVmPortResponse.class).call(new ReturnValueCompletion<ScanVmPortResponse>(msg) {
@Override
public void success(ScanVmPortResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setStatus(ret.getPortStatus());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
} |
package org.andengine.input.touch.detector;
import org.andengine.input.touch.TouchEvent;
import org.andengine.util.math.MathUtils;
import android.view.MotionEvent;
public class PinchZoomDetector extends BaseDetector {
// Constants
private static final float TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT = 10;
// Fields
private final IPinchZoomDetectorListener mPinchZoomDetectorListener;
private float mInitialDistance;
private float mCurrentDistance;
private boolean mPinchZooming;
// Constructors
public PinchZoomDetector(final IPinchZoomDetectorListener pPinchZoomDetectorListener) {
this.mPinchZoomDetectorListener = pPinchZoomDetectorListener;
}
// Getter & Setter
public boolean isZooming() {
return this.mPinchZooming;
}
// Methods for/from SuperClass/Interfaces
/**
* When {@link PinchZoomDetector#isZooming()} this method will call through to {@link IPinchZoomDetectorListener#onPinchZoomFinished(PinchZoomDetector, TouchEvent, float)}.
*/
@Override
public void reset() {
if(this.mPinchZooming) {
this.mPinchZoomDetectorListener.onPinchZoomFinished(this, null, this.getZoomFactor());
}
this.mInitialDistance = 0;
this.mCurrentDistance = 0;
this.mPinchZooming = false;
}
@Override
public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) {
final MotionEvent motionEvent = pSceneTouchEvent.getMotionEvent();
final int action = motionEvent.getAction() & MotionEvent.ACTION_MASK;
switch(action) {
case MotionEvent.ACTION_POINTER_DOWN:
if(!this.mPinchZooming) {
this.mInitialDistance = PinchZoomDetector.calculatePointerDistance(motionEvent);
if(this.mInitialDistance > TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT) {
this.mPinchZooming = true;
this.mPinchZoomDetectorListener.onPinchZoomStarted(this, pSceneTouchEvent);
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
if(this.mPinchZooming) {
this.mPinchZooming = false;
this.mPinchZoomDetectorListener.onPinchZoomFinished(this, pSceneTouchEvent, this.getZoomFactor());
}
break;
case MotionEvent.ACTION_MOVE:
if(this.mPinchZooming) {
this.mCurrentDistance = PinchZoomDetector.calculatePointerDistance(motionEvent);
if(this.mCurrentDistance > TRIGGER_PINCHZOOM_MINIMUM_DISTANCE_DEFAULT) {
this.mPinchZoomDetectorListener.onPinchZoom(this, pSceneTouchEvent, this.getZoomFactor());
}
}
break;
}
return true;
}
private float getZoomFactor() {
return this.mCurrentDistance / this.mInitialDistance;
}
// Methods
/**
* Calculate the euclidian distance between the first two fingers.
*/
private static float calculatePointerDistance(final MotionEvent pMotionEvent) {
return MathUtils.distance(pMotionEvent.getX(0), pMotionEvent.getY(0), pMotionEvent.getX(1), pMotionEvent.getY(1));
}
// Inner and Anonymous Classes
public static interface IPinchZoomDetectorListener {
// Constants
// Methods
public void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pSceneTouchEvent);
public void onPinchZoom(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor);
public void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor);
}
} |
package nerd.tuxmobil.fahrplan.congress;
import android.text.format.Time;
public class DateInfo {
public int dayIdx;
public String date;
public DateInfo(int dayIdx, String date) {
this.dayIdx = dayIdx;
this.date = date;
}
@Override
public boolean equals(Object object) {
if (object instanceof DateInfo) {
DateInfo date = (DateInfo)object;
return super.equals(object) &&
date.dayIdx == dayIdx &&
date.date.equals(date);
}
return false;
}
@Override
public int hashCode() {
return super.hashCode() * 13 | dayIdx + date.hashCode() * 7;
}
@Override
public String toString() {
return "dayIndex = " + dayIdx + ", date = " + date;
}
/**
* Returns the index of today
* @param dateInfos List of dates
* @param hourOfDayChange Hour of day change (all lectures which start before count to the previous day)
* @param minuteOfDayChange Minute of day change
* @return dayIndex if found, -1 otherwise
*/
public static int getIndexOfToday(DateInfos dateInfos, int hourOfDayChange, int minuteOfDayChange) {
if (dateInfos == null || dateInfos.isEmpty()) return -1;
Time today = new Time();
today.setToNow();
today.hour -= hourOfDayChange;
today.minute -= minuteOfDayChange;
today.normalize(true);
StringBuilder currentDate = new StringBuilder();
currentDate.append(String.format("%d", today.year));
currentDate.append("-");
currentDate.append(String.format("%02d", today.month + 1));
currentDate.append("-");
currentDate.append(String.format("%02d", today.monthDay));
for (DateInfo dateInfo : dateInfos) {
if (dateInfo.date.equals(currentDate.toString())) return dateInfo.dayIdx;
}
return -1;
}
public static boolean sameDay(Time today, int lectureListDay, DateInfos dateInfos) {
StringBuilder currentDate = new StringBuilder();
currentDate.append(String.format("%d", today.year));
currentDate.append("-");
currentDate.append(String.format("%02d", today.month + 1));
currentDate.append("-");
currentDate.append(String.format("%02d", today.monthDay));
for (DateInfo dateInfo : dateInfos) {
if ((dateInfo.dayIdx == lectureListDay) && (dateInfo.date.equals(currentDate.toString()))) return true;
}
return false;
}
} |
package com.antonio.samir.meteoritelandingsspots.service.server;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import com.antonio.samir.meteoritelandingsspots.service.repository.MeteoriteColumns;
import com.antonio.samir.meteoritelandingsspots.service.repository.MeteoriteProvider;
import com.antonio.samir.meteoritelandingsspots.service.server.nasa.MeteoriteNasaAsyncTaskService;
import com.antonio.samir.meteoritelandingsspots.service.server.nasa.NasaService;
import com.antonio.samir.meteoritelandingsspots.service.server.nasa.NasaServiceFactory;
public class MeteoriteNasaService implements MeteoriteService, LoaderManager.LoaderCallbacks<Cursor> {
private static final int CURSOR_LOADER_ID = 1;
private static final String TAG = MeteoriteNasaService.class.getSimpleName();
private final NasaService nasaService;
private final LoaderManager mLoaderManager;
private Context mContext;
private MeteoriteServiceDelegate mDelegate;
private boolean firstAttempt;
public MeteoriteNasaService(final Context context) {
mContext = context;
nasaService = NasaServiceFactory.getNasaService(context);
mLoaderManager = ((Activity) mContext).getLoaderManager();
firstAttempt = true;
}
@Override
public void getMeteorites(MeteoriteServiceDelegate delegate) {
mDelegate = delegate;
mLoaderManager.initLoader(CURSOR_LOADER_ID, null, this);
}
@Override
public boolean isDated() {
return false;
}
// LoaderManager.LoaderCallbacks<Cursor> implemendation
@Override
public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) {
if (data == null || data.getCount() < 1) {
if (firstAttempt) {
final MeteoriteNasaAsyncTaskService taskService = new MeteoriteNasaAsyncTaskService(nasaService, mContext) {
@Override
protected void onPostExecute(MeteoriteServerResult result) {
super.onPostExecute(result);
mLoaderManager.restartLoader(CURSOR_LOADER_ID, null, MeteoriteNasaService.this);
}
};
firstAttempt = false;
taskService.execute();
} else {
}
} else {
Log.i(TAG, String.format("Data count %s", data.getCount()));
mDelegate.setCursor(data);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mDelegate.reReseted();
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
mDelegate.onPreExecute();
// This narrows the return to only the stocks that are most current.
return new CursorLoader(mContext, MeteoriteProvider.Meteorites.LISTS,
new String[]{MeteoriteColumns.ID, MeteoriteColumns.NAME, MeteoriteColumns.YEAR
, MeteoriteColumns.RECLONG
, MeteoriteColumns.RECLAT},
null,
null,
null);
}
} |
package org.idlesoft.android.hubroid;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class RepositoriesListAdapter extends BaseAdapter {
private JSONArray m_data = new JSONArray();
private Context m_context;
private LayoutInflater m_inflater;
public static class ViewHolder {
public TextView repo_name;
public TextView repo_owner;
public TextView repo_owner_label;
public TextView repo_description;
public TextView repo_fork;
public TextView repo_watch_count;
public TextView repo_fork_count;
}
public RepositoriesListAdapter(final Context context, JSONArray jsonarray) {
Log.d("martin", "CONSTRUCTOR");
m_context = context;
m_inflater = LayoutInflater.from(m_context);
m_data = jsonarray;
}
public int getCount() {
return m_data.length();
}
public Object getItem(int i) {
try {
return m_data.get(i);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public long getItemId(int i) {
return i;
}
public View getView(int index, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = m_inflater.inflate(R.layout.repository_list_item, null);
holder = new ViewHolder();
holder.repo_name = (TextView) convertView.findViewById(R.id.repository_list_item_name);
holder.repo_owner = (TextView) convertView.findViewById(R.id.repository_list_item_owner);
holder.repo_owner_label = (TextView) convertView.findViewById(R.id.repository_list_item_owner_label);
holder.repo_description = (TextView) convertView.findViewById(R.id.repository_list_item_description);
holder.repo_fork = (TextView) convertView.findViewById(R.id.repository_list_item_fork);
holder.repo_watch_count = (TextView) convertView.findViewById(R.id.repository_list_item_watch_count);
holder.repo_fork_count = (TextView) convertView.findViewById(R.id.repository_list_item_fork_count);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String owner = "";
try {
owner = m_data.getJSONObject(index).getString("username");
} catch (JSONException e) {
try {
owner = m_data.getJSONObject(index).getString("owner");
} catch (JSONException e1) {
e1.printStackTrace();
}
}
try {
holder.repo_name.setText(m_data.getJSONObject(index).getString("name"));
holder.repo_owner.setText(owner);
holder.repo_description.setText(m_data.getJSONObject(index).getString("description"));
holder.repo_fork_count.setText(m_data.getJSONObject(index).getString("forks"));
try{
holder.repo_watch_count.setText(m_data.getJSONObject(index).getString("watchers"));
} catch(JSONException e){
holder.repo_watch_count.setText(m_data.getJSONObject(index).getString("followers"));
}
if(m_data.getJSONObject(index).getBoolean("fork"))
holder.repo_fork.setText("(Fork) ");
else
holder.repo_fork.setText("");
} catch (JSONException e) {
holder.repo_owner.setVisibility(TextView.GONE);
holder.repo_owner_label.setVisibility(TextView.GONE);
holder.repo_description.setVisibility(TextView.GONE);
}
return convertView;
}
} |
package nodomain.freeyourgadget.gadgetbridge.service.devices.miband2;
import java.util.HashMap;
import java.util.Map;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.DeviceType;
import nodomain.freeyourgadget.gadgetbridge.util.ArrayUtils;
import nodomain.freeyourgadget.gadgetbridge.util.CheckSums;
public class Mi2FirmwareInfo {
private static final byte[] FW_HEADER = new byte[]{
(byte) 0xa3,
(byte) 0x68,
(byte) 0x04,
(byte) 0x3b,
(byte) 0x02,
(byte) 0xdb,
(byte) 0xc8,
(byte) 0x58,
(byte) 0xd0,
(byte) 0x50,
(byte) 0xfa,
(byte) 0xe7,
(byte) 0x0c,
(byte) 0x34,
(byte) 0xf3,
(byte) 0xe7,
};
private static final int FW_HEADER_OFFSET = 0x150;
private static final byte[] FT_HEADER = new byte[] { // HMZK font file (*.ft, *.ft.xx)
0x48,
0x4d,
0x5a,
0x4b
};
private static Map<Integer,String> crcToVersion = new HashMap<>();
static {
// firmware
crcToVersion.put(41899, "1.0.0.39");
crcToVersion.put(49197, "1.0.0.53");
crcToVersion.put(51770, "1.0.1.34");
crcToVersion.put(3929, "1.0.1.39");
// fonts
crcToVersion.put(45624, "Font");
crcToVersion.put(6377, "Font (En)");
}
private FirmwareType firmwareType = FirmwareType.FIRMWARE;
public static String toVersion(int crc16) {
return crcToVersion.get(crc16);
}
public static int[] getWhitelistedVersions() {
return ArrayUtils.toIntArray(crcToVersion.keySet());
}
private final int crc16;
private byte[] bytes;
private String firmwareVersion;
public Mi2FirmwareInfo(byte[] bytes) {
this.bytes = bytes;
crc16 = CheckSums.getCRC16(bytes);
firmwareVersion = crcToVersion.get(crc16);
firmwareType = determineFirmwareType(bytes);
}
private FirmwareType determineFirmwareType(byte[] bytes) {
if (ArrayUtils.startsWith(bytes, FT_HEADER)) {
return FirmwareType.FONT;
}
if (ArrayUtils.equals(bytes, FW_HEADER, FW_HEADER_OFFSET)) {
// TODO: this is certainly not a correct validation, but it works for now
return FirmwareType.FIRMWARE;
}
return FirmwareType.INVALID;
}
public boolean isGenerallyCompatibleWith(GBDevice device) {
return isHeaderValid() && device.getType() == DeviceType.MIBAND2;
}
public boolean isHeaderValid() {
return getFirmwareType() != FirmwareType.INVALID;
}
public void checkValid() throws IllegalArgumentException {
}
/**
* Returns the size of the firmware in number of bytes.
* @return
*/
public int getSize() {
return bytes.length;
}
public byte[] getBytes() {
return bytes;
}
public int getCrc16() {
return crc16;
}
public int getFirmwareVersion() {
return getCrc16(); // HACK until we know how to determine the version from the fw bytes
}
public FirmwareType getFirmwareType() {
return firmwareType;
}
} |
package org.phenoscape.obd.query;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.phenoscape.obd.model.PhenotypeSpec;
import org.phenoscape.obd.model.Vocab.OBO;
import org.phenoscape.obd.query.GeneAnnotationsQueryConfig.SORT_COLUMN;
public class GeneAnnotationsQueryBuilder extends QueryBuilder {
private final GeneAnnotationsQueryConfig config;
private final boolean totalOnly;
private static final String NODE = "(SELECT node.node_id FROM node WHERE node.uid=?)";
private static final String NODE_S = "(SELECT node.node_id FROM node WHERE node.uid='%s')";
private static final Map<SORT_COLUMN, String> COLUMNS = new HashMap<SORT_COLUMN, String>();
static {
COLUMNS.put(SORT_COLUMN.GENE, "gene_label");
COLUMNS.put(SORT_COLUMN.ENTITY, "entity_label");
COLUMNS.put(SORT_COLUMN.QUALITY, "quality_label");
COLUMNS.put(SORT_COLUMN.RELATED_ENTITY, "related_entity_label");
}
public GeneAnnotationsQueryBuilder(GeneAnnotationsQueryConfig config, boolean totalOnly) {
this.config = config;
this.totalOnly = totalOnly;
}
@Override
protected void fillStatement(PreparedStatement statement) throws SQLException {
int index = 1;
for (String geneID : this.config.getGeneIDs()) {
statement.setString(index++, geneID);
}
if (!this.config.getPhenotypes().isEmpty()) {
for (PhenotypeSpec phenotype : this.config.getPhenotypes()) {
if (phenotype.getEntityID() != null) {
statement.setString(index++, phenotype.getEntityID());
}
if (phenotype.getQualityID() != null) {
statement.setString(index++, phenotype.getQualityID());
}
if (phenotype.getRelatedEntityID() != null) {
statement.setString(index++, phenotype.getRelatedEntityID());
}
}
}
if (!this.totalOnly) {
statement.setInt(index++, this.config.getLimit());
statement.setInt(index++, this.config.getIndex());
}
}
@Override
protected String getQuery() {
final List<String> intersects = new ArrayList<String>();
if (!this.config.getGeneIDs().isEmpty()) {
intersects.add(this.getGenesQuery(this.config.getGeneIDs()));
}
if (!this.config.getPhenotypes().isEmpty()) {
intersects.add(this.getPhenotypesQuery(this.config.getPhenotypes()));
}
final String baseQuery;
if (intersects.isEmpty()) {
baseQuery = "SELECT DISTINCT distinct_gene_annotation.* FROM distinct_gene_annotation ";
} else {
baseQuery = "(" + StringUtils.join(intersects, " INTERSECT ") + ") ";
}
final String query;
if (this.totalOnly) {
query = "SELECT count(*) FROM (" + baseQuery + ") AS query";
} else {
query = baseQuery + "ORDER BY " + COLUMNS.get(this.config.getSortColumn()) + " " + this.getSortText() + "LIMIT ? OFFSET ? " ;
}
log().debug("Query: " + query);
return query;
}
private String getSortText() {
return this.config.sortDescending() ? "DESC " : "";
}
private String getGenesQuery(List<String> genes) {
final StringBuffer query = new StringBuffer();
query.append("(SELECT DISTINCT distinct_gene_annotation.* FROM distinct_gene_annotation WHERE ");
query.append("distinct_gene_annotation.gene_uid IN ");
query.append(this.createPlaceholdersList(this.config.getGeneIDs().size()));
query.append(")");
return query.toString();
}
private String getPhenotypesQuery(List<PhenotypeSpec> phenotypes) {
final StringBuffer query = new StringBuffer();
query.append("(");
final List<String> unions = new ArrayList<String>();
for (PhenotypeSpec phenotype : phenotypes) {
unions.add(this.getPhenotypeQuery(phenotype));
}
query.append(StringUtils.join(unions, " UNION "));
query.append(")");
return query.toString();
}
private String getPhenotypeQuery(PhenotypeSpec phenotype) {
final StringBuffer query = new StringBuffer();
query.append("(SELECT DISTINCT distinct_gene_annotation.* FROM distinct_gene_annotation ");
if (phenotype.getEntityID() != null) {
if (phenotype.includeEntityParts()) {
query.append(String.format("JOIN link phenotype_inheres_in_part_of ON (phenotype_inheres_in_part_of.node_id = distinct_gene_annotation.phenotype_node_id AND phenotype_inheres_in_part_of.predicate_id = %s) ", this.node(OBO.INHERES_IN_PART_OF)));
} else {
query.append(String.format("JOIN link phenotype_inheres_in ON (phenotype_inheres_in.node_id = distinct_gene_annotation.phenotype_node_id AND phenotype_inheres_in.predicate_id = %s) ", this.node(OBO.INHERES_IN)));
}
}
if (phenotype.getQualityID() != null) {
query.append(String.format("JOIN link quality_is_a ON (quality_is_a.node_id = distinct_gene_annotation.quality_node_id AND quality_is_a.predicate_id = %s) ", this.node(OBO.IS_A)));
}
if (phenotype.getRelatedEntityID() != null) {
query.append(String.format("JOIN link related_entity_is_a ON (related_entity_is_a.node_id = distinct_gene_annotation.related_entity_node_id AND related_entity_is_a.predicate_id = %s) ", this.node(OBO.IS_A)));
}
query.append("WHERE ");
query.append(this.translate(phenotype));
query.append(") ");
return query.toString();
}
private String translate(PhenotypeSpec phenotype) {
final StringBuffer buffer = new StringBuffer();
buffer.append("(");
final List<String> terms = new ArrayList<String>();
if (phenotype.getEntityID() != null) {
if (phenotype.includeEntityParts()) {
terms.add("phenotype_inheres_in_part_of.object_id = " + NODE + " ");
} else {
terms.add("phenotype_inheres_in.object_id = " + NODE + " ");
}
}
if (phenotype.getQualityID() != null) {
terms.add("quality_is_a.object_id = " + NODE + " ");
}
if (phenotype.getRelatedEntityID() != null) {
terms.add("related_entity_is_a.object_id = " + NODE + " ");
}
buffer.append(StringUtils.join(terms, " AND "));
buffer.append(")");
return buffer.toString();
}
private String node(String uid) {
return String.format(NODE_S, uid);
}
private Logger log() {
return Logger.getLogger(this.getClass());
}
} |
package net.lucenews.controller;
import java.lang.reflect.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.*;
import net.lucenews.atom.*;
import net.lucenews.*;
import net.lucenews.model.*;
import net.lucenews.model.exception.*;
import net.lucenews.view.*;
import org.apache.lucene.analysis.*;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.queryParser.*;
import org.apache.lucene.search.*;
import org.apache.lucene.wordnet.*;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.transform.*;
public class SearchController extends Controller {
/**
* Performs a search.
*
* @param c The context
* @throws ParserConfigurationException
* @throws TransformerException
* @throws IndicesNotFoundException
* @throws IOException
* @throws InsufficientDataException
* @throws ParseException
*/
public static void doGet (LuceneContext c)
throws ParserConfigurationException, TransformerException, IndicesNotFoundException, IOException, InsufficientDataException, ParseException
{
c.log().debug("SearchController.doGet(LuceneContext)");
LuceneWebService service = c.service();
LuceneIndexManager manager = service.getIndexManager();
LuceneRequest req = c.req();
LuceneIndex[] indices = manager.getIndices( req.getIndexNames() );
LuceneMultiSearcher searcher = null;
IndexSearcher[] searchers = new IndexSearcher[ indices.length ];
for (int i = 0; i < indices.length; i++) {
searchers[ i ] = indices[ i ].getIndexSearcher();
}
searcher = new LuceneMultiSearcher( searchers, getSearcherIndexField() );
List<String> invalidParameterNames = new LinkedList<String>();
/**
* Query
*/
Query query = null;
try {
query = req.getQuery();
}
catch (InsufficientDataException ide) {
query = null;
}
Filter filter = req.getFilter();
Sort sort = req.getSort();
/**
* Search string
*/
String searchString = req.getSearchString();
if (searchString == null) {
if (sort == null) {
invalidParameterNames.add( req.getParameterName( LuceneKeys.SEARCH_STRING ) );
}
else {
query = new MatchAllDocsQuery();
}
}
/**
* Default field
*/
// User-specified default field
String defaultField = req.getDefaultField();
// Index-specified default field
for (int i = 0; i < indices.length && defaultField == null; i++) {
defaultField = indices[ i ].getDefaultField();
}
// Service-specified default field
if (defaultField == null) {
defaultField = service.getDefaultField();
}
if (defaultField == null) {
invalidParameterNames.add( req.getParameterName( LuceneKeys.DEFAULT_FIELD ) );
}
Analyzer analyzer = req.getAnalyzer();
if( analyzer == null )
invalidParameterNames.add( req.getParameterName( LuceneKeys.ANALYZER ) );
if (ServletUtils.parseBoolean(service.getProperty("query.expand","false"))) {
analyzer = new SynonymAnalyzer(
analyzer,
new SynExpand(),
manager.getIndex(service.getProperty("synonym.index","wordnet")).getIndexSearcher()
);
}
if (!invalidParameterNames.isEmpty()) {
StringBuffer buffer = new StringBuffer();
if (invalidParameterNames.size() == 1) {
buffer.append( "Valid '" + invalidParameterNames.get( 0 ) + "' parameter required." );
}
else {
buffer.append( "Valid" );
for( int i = 0; i < invalidParameterNames.size(); i++ ) {
if( i > 0 )
if( i == ( invalidParameterNames.size() - 1 ) )
buffer.append( " and" );
else
buffer.append( "," );
buffer.append( " '" + invalidParameterNames.get( i ) + "'" );
}
buffer.append( " parameters required." );
}
throw new InsufficientDataException( String.valueOf( buffer ) );
}
QueryParser.Operator defaultOperator = null;
if (query == null) {
/**
* Build the query parser
*/
QueryParser parser = new CustomQueryParser( defaultField, analyzer );
Locale locale = req.getLocale();
if (locale != null) {
parser.setLocale( locale );
}
defaultOperator = req.getDefaultOperator();
for (int i = 0; i < indices.length; i++) {
if (defaultOperator != null) {
break;
}
defaultOperator = indices[ i ].getDefaultOperator();
}
if (defaultOperator == null) {
defaultOperator = service.getDefaultOperator();
}
if (defaultOperator == null) {
defaultOperator = QueryParser.AND_OPERATOR;
}
if (defaultOperator != null) {
parser.setDefaultOperator( defaultOperator );
}
/**
* Build the query
*/
query = parser.parse( searchString );
}
/**
* Perform the search
*/
Hits hits = null;
if (filter != null && sort != null) {
hits = searcher.search( query, filter, sort );
}
else if (filter != null) {
hits = searcher.search( query, filter );
}
else if (sort != null) {
hits = searcher.search( query, sort );
}
else {
hits = searcher.search( query );
}
/**
* Alternate query
*/
String[] suggestedQueryStrings = new String[0];
int[] suggestedQueryCounts = new int[0];
try {
int maxSuggestions = 5;
int maxResults = 1;
PriorityQueue<SearchedQuery> queue = new PriorityQueue<SearchedQuery>( maxSuggestions, new SearchedQueryComparator() );
Query[] suggestedQueries = getSuggestedQueries( query, indices );
suggestedQueryStrings = new String[ Math.min( maxResults, suggestedQueries.length ) ];
suggestedQueryCounts = new int[ Math.min( maxResults, suggestedQueries.length ) ];
for (int i = 0; i < suggestedQueries.length && i < maxSuggestions; i++) {
Query suggestedQuery = suggestedQueries[ i ];
Hits suggestedHits = searcher.search( suggestedQuery );
if (suggestedHits.length() > hits.length())
queue.add( new SearchedQuery( suggestedQuery, suggestedHits ) );
}
int i = 0;
while (!queue.isEmpty() && i < maxResults) {
SearchedQuery q = queue.poll();
//suggestedQueryStrings[ i ] = q.getQuery().toString( defaultField );
suggestedQueryStrings[ i ] = rewriteQuery( searchString, q.getQuery() );
suggestedQueryCounts[ i ] = q.getHits().length();
i++;
}
}
catch (Exception exc) {
suggestedQueryStrings = new String[0];
suggestedQueryCounts = new int[0];
}
Limiter limiter = req.getLimiter();
limiter.setTotalEntries( null );
try {
String maximum = req.getCleanParameter("maximum");
if (maximum != null && maximum.trim().length() > 0) {
limiter.setTotalEntries( Integer.valueOf( maximum ) );
}
}
catch (NumberFormatException nfe) {
}
HitsIterator iterator = null;
try {
iterator = new HitsIterator( hits, limiter, c.service().getIndexManager().getIndex( req.getIndexName() ) );
}
catch (MultipleValueException mve) {
iterator = new HitsIterator( hits, limiter );
}
OpenSearchResponse response = asOpenSearchResponse( c, iterator, suggestedQueryStrings, suggestedQueryCounts );
StringBuffer title = new StringBuffer();
if (query instanceof MatchAllDocsQuery) {
title.append( "All documents in " );
}
else {
title.append( "Search results for query '" + req.getSearchString() + "' on " );
}
title.append( ( indices.length == 1 ? "index" : "indices" ) + " " );
title.append( ServletUtils.joined( ServletUtils.mapped( "'[content]'", ServletUtils.objectsMapped( "getTitle", indices ) ) ) );
response.setTitle( String.valueOf( title ) );
AtomView.process( c, response );
}
/**
* Transforms the given hits iterator into an OpenSearch
* response.
*
* @param c The context
* @param iterator The hits iterator
* @throws ParserConfigurationException
* @throws IOException
* @throws IndicesNotFoundException
*/
public static OpenSearchResponse asOpenSearchResponse (LuceneContext c, HitsIterator iterator, String[] suggestions, int[] suggestionCounts)
throws ParserConfigurationException, IOException, IndicesNotFoundException, InsufficientDataException
{
c.log().debug("SearchController.asOpenSearchResponse(LuceneContext,HitsIterator,String[],int[])");
LuceneWebService service = c.service();
LuceneIndexManager manager = service.getIndexManager();
LuceneRequest req = c.req();
LuceneResponse res = c.res();
LuceneIndex[] indices = manager.getIndices( req.getIndexNames() );
OpenSearchResponse response = new OpenSearchResponse();
response.setLinkHREF( service.getOpenSearchDescriptionURL( req, req.getIndexNames() ) );
response.setSearchTerms( req.getSearchString() );
response.setUpdated( Calendar.getInstance() );
response.addAuthor( new Author( "Lucene Web Service, version " + service.getVersion() ) );
response.setID( req.getRequestURL() + ( ( req.getQueryString() != null ) ? "?" + req.getQueryString() : "" ) );
for( int i = 0; i < suggestions.length; i++ )
response.addQuerySuggestion( suggestions[ i ], suggestionCounts[ i ] );
StringBuffer buffer = new StringBuffer();
buffer.append( req.getRequestURL() );
Enumeration names = req.getParameterNames();
boolean first = true;
while( names.hasMoreElements() ) {
String name = (String) names.nextElement();
if( name.equals( "page" ) )
continue;
String[] values = req.getParameterValues( name );
for( int i = 0; i < values.length; i++ ) {
if( first ) {
buffer.append( "?" );
first = false;
}
else {
buffer.append( "&" );
}
buffer.append( name + "=" + values[i] );
}
}
buffer.append( first ? "?" : "&" );
buffer.append( "page=" );
String baseURL = String.valueOf( buffer );
Limiter limiter = iterator.getLimiter();
if (limiter != null) {
c.log().debug( "Limiter: " + limiter.getClass().getCanonicalName() );
}
if( limiter != null && limiter instanceof Pager ) {
Pager pager = (Pager) limiter;
c.log().debug( "pager.getTotalEntries(): " + pager.getTotalEntries() );
c.log().debug( "pager.getFirst(): " + pager.getFirst() );
c.log().debug( "pager.getEntriesPerPage(): " + pager.getEntriesPerPage() );
response.setTotalResults( pager.getTotalEntries() );
response.setStartIndex( pager.getFirst() );
response.setItemsPerPage( pager.getEntriesPerPage() );
c.log().debug( "response.getTotalResults(): " + response.getTotalResults() );
c.log().debug( "response.getStartIndex(): " + response.getStartIndex() );
c.log().debug( "response.getItemsPerPage(): " + response.getItemsPerPage() );
if( pager.getCurrentPage() != null )
response.addLink( new Link( baseURL + pager.getCurrentPage(), "self", "application/atom+xml" ) );
if( pager.getFirstPage() != null )
response.addLink( new Link( baseURL + pager.getFirstPage(), "first", "application/atom+xml" ) );
if( pager.getPreviousPage() != null )
response.addLink( new Link( baseURL + pager.getPreviousPage(), "previous", "application/atom+xml" ) );
if( pager.getNextPage() != null )
response.addLink( new Link( baseURL + pager.getNextPage(), "next", "application/atom+xml" ) );
if( pager.getLastPage() != null )
response.addLink( new Link( baseURL + pager.getLastPage(), "last", "application/atom+xml" ) );
}
iterator.reset();
while( iterator.hasNext() ) {
LuceneDocument document = iterator.next();
Integer searcherIndex = extractSearcherIndex( document );
LuceneIndex index = null;
if( searcherIndex != null )
index = indices[ searcherIndex ];
response.addEntry( DocumentController.asEntry( c, index, document, iterator.score() ) );
}
return response;
}
public static String getSearcherIndexField () {
return "lucene_ws_subSearcher";
}
public static Integer extractSearcherIndex (LuceneDocument document) {
Integer index = null;
if (document == null)
return index;
try {
index = Integer.valueOf( document.get( getSearcherIndexField() ) );
}
catch(NullPointerException npe) {
}
catch(NumberFormatException nfe) {
}
document.removeFields( getSearcherIndexField() );
return index;
}
public static Query[] getSuggestedQueries (Query original, LuceneIndex[] indices)
throws IOException
{
IndexReader[] readers = new IndexReader[ indices.length ];
for( int i = 0; i < indices.length; i++ )
readers[ i ] = indices[ i ].getIndexReader();
MultiReader reader = new MultiReader( readers );
Query[] suggested = getSuggestedQueries( original, reader );
for( int i = 0; i < indices.length; i++ )
indices[ i ].putIndexReader( readers[ i ] );
return suggested;
}
public static Query[] getSuggestedQueries (Query original, IndexReader reader)
throws IOException
{
try {
DidYouMeanQueryGenerator generator = new DidYouMeanQueryGenerator( original, reader );
List<Query> suggestions = generator.getQuerySuggestions( true, true );
Iterator<Query> iterator = suggestions.iterator();
while( iterator.hasNext() )
setDefaultBoost( iterator.next() );
return suggestions.toArray( new Query[]{} );
}
catch(Error err) {
return new Query[]{};
}
catch(Exception e) {
e.printStackTrace();
return new Query[]{};
}
}
public static void setDefaultBoost (Query query) {
if( query instanceof BooleanQuery ) {
setDefaultBoost( (BooleanQuery) query );
}
else {
query.setBoost( 1.0f );
}
}
public static void setDefaultBoost (BooleanQuery query) {
BooleanClause[] clauses = query.getClauses();
for( int i = 0; i < clauses.length; i++ ) {
setDefaultBoost( clauses[ i ].getQuery() );
}
query.setBoost( 1.0f );
}
public static String rewriteQuery (String original, Query alternate) {
StringBuffer rewritten = new StringBuffer();
List<TokenTermQuery> termQueries = findTokenTermQueries( alternate );
Iterator<TokenTermQuery> iterator = termQueries.iterator();
int cursor = 0;
while( iterator.hasNext() ) {
TokenTermQuery query = iterator.next();
rewritten.append( original.substring( cursor, query.getToken().beginColumn ) );
rewritten.append( query.getTerm().text() );
cursor = query.getToken().endColumn;
}
rewritten.append( original.substring( cursor ) );
return rewritten.toString();
}
public static List<TokenTermQuery> findTokenTermQueries (Query query) {
List<TokenTermQuery> queries = new ArrayList<TokenTermQuery>();
if( query instanceof BooleanQuery )
queries.addAll( findTokenTermQueries( (BooleanQuery) query ) );
if( query instanceof TermQuery )
queries.addAll( findTokenTermQueries( (TermQuery) query ) );
Collections.sort( queries, new TokenTermQueryComparator() );
return queries;
}
public static List<TokenTermQuery> findTokenTermQueries (BooleanQuery query) {
BooleanClause[] clauses = query.getClauses();
List<TokenTermQuery> queries = new ArrayList<TokenTermQuery>(clauses.length);
for( int i = 0; i < clauses.length; i++ ) {
queries.addAll( findTokenTermQueries( clauses[i].getQuery() ) );
}
return queries;
}
public static List<TokenTermQuery> findTokenTermQueries (TermQuery query) {
List<TokenTermQuery> queries = new ArrayList<TokenTermQuery>(1);
if( query instanceof TokenTermQuery )
queries.add( (TokenTermQuery) query );
return queries;
}
}
class TokenTermQueryComparator implements Comparator<TokenTermQuery> {
public int compare (TokenTermQuery query1, TokenTermQuery query2) {
Integer column1 = query1.getToken().beginColumn;
Integer column2 = query2.getToken().beginColumn;
return column1.compareTo(column2);
}
}
class SearchedQuery {
public Query query;
public Hits hits;
public SearchedQuery (Query query, Hits hits) {
this.query = query;
this.hits = hits;
}
public Query getQuery () {
return query;
}
public Hits getHits () {
return hits;
}
}
class SearchedQueryComparator implements Comparator<SearchedQuery> {
public int compare (SearchedQuery q1, SearchedQuery q2) {
Integer hits1 = q1.getHits().length();
Integer hits2 = q2.getHits().length();
return hits2.compareTo( hits1 );
}
}
class CustomQueryParser extends QueryParser {
public CustomQueryParser (String f, Analyzer a) {
super( f, a );
}
public CustomQueryParser (CharStream stream) {
super( stream );
}
public CustomQueryParser (QueryParserTokenManager tm) {
super( tm );
}
protected Query getFieldQuery (String field, String queryText ) throws ParseException {
Query query = super.getFieldQuery( field, queryText );
if( query instanceof TermQuery ) {
TermQuery termQuery = (TermQuery) query;
return new TokenTermQuery( termQuery.getTerm(), getToken( 0 ) );
}
return query;
}
protected Query getRangeQuery (String field, String part1, String part2, boolean inclusive)
throws ParseException
{
return new ConstantScoreRangeQuery( field, part1, part2, inclusive, inclusive );
}
} |
//Title: TASSELMainFrame
//Company: NCSU
package net.maizegenetics.tassel;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.plugindef.Datum;
import net.maizegenetics.prefs.TasselPrefs;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.*;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import net.maizegenetics.baseplugins.ArchaeopteryxPlugin;
import net.maizegenetics.baseplugins.ConvertSBitTBitPlugin;
import net.maizegenetics.baseplugins.CreateTreePlugin;
import net.maizegenetics.baseplugins.ExportPlugin;
import net.maizegenetics.baseplugins.FileLoadPlugin;
import net.maizegenetics.baseplugins.FilterAlignmentPlugin;
import net.maizegenetics.baseplugins.FilterSiteNamePlugin;
import net.maizegenetics.baseplugins.FilterTaxaAlignmentPlugin;
import net.maizegenetics.baseplugins.FilterTaxaPropertiesPlugin;
import net.maizegenetics.baseplugins.FilterTraitsPlugin;
import net.maizegenetics.baseplugins.FixedEffectLMPlugin;
import net.maizegenetics.baseplugins.FlapjackLoadPlugin;
import net.maizegenetics.baseplugins.GenotypeImputationPlugin;
import net.maizegenetics.baseplugins.GenotypeSummaryPlugin;
import net.maizegenetics.baseplugins.Grid2dDisplayPlugin;
import net.maizegenetics.baseplugins.IntersectionAlignmentPlugin;
import net.maizegenetics.baseplugins.KinshipPlugin;
import net.maizegenetics.baseplugins.LinkageDiseqDisplayPlugin;
import net.maizegenetics.baseplugins.LinkageDisequilibriumPlugin;
import net.maizegenetics.baseplugins.MLMPlugin;
import net.maizegenetics.baseplugins.ManhattanDisplayPlugin;
import net.maizegenetics.baseplugins.MergeAlignmentsPlugin;
import net.maizegenetics.baseplugins.PlinkLoadPlugin;
import net.maizegenetics.baseplugins.QQDisplayPlugin;
import net.maizegenetics.baseplugins.SeparatePlugin;
import net.maizegenetics.baseplugins.SequenceDiversityPlugin;
import net.maizegenetics.baseplugins.SynonymizerPlugin;
import net.maizegenetics.baseplugins.TableDisplayPlugin;
import net.maizegenetics.baseplugins.TreeDisplayPlugin;
import net.maizegenetics.baseplugins.UnionAlignmentPlugin;
import net.maizegenetics.baseplugins.chart.ChartDisplayPlugin;
import net.maizegenetics.baseplugins.genomicselection.RidgeRegressionEmmaPlugin;
import net.maizegenetics.baseplugins.numericaltransform.NumericalTransformPlugin;
import net.maizegenetics.gui.PrintHeapAction;
import net.maizegenetics.plugindef.Plugin;
import net.maizegenetics.plugindef.PluginEvent;
import net.maizegenetics.plugindef.ThreadedPluginListener;
import net.maizegenetics.progress.ProgressPanel;
import net.maizegenetics.util.Utils;
import org.apache.log4j.Logger;
/**
* TASSELMainFrame
*
*/
public class TASSELMainFrame extends JFrame implements ActionListener {
private static final Logger myLogger = Logger.getLogger(TASSELMainFrame.class);
public static final String version = "4.2.1";
public static final String versionDate = "August 1, 2013";
private DataTreePanel myDataTreePanel;
private String tasselDataFile = "TasselDataFile";
//a variable to control when the progress bar was last updated
private JFileChooser filerSave = new JFileChooser();
private JFileChooser filerOpen = new JFileChooser();
private JScrollPane reportPanelScrollPane = new JScrollPane();
private JTextArea reportPanelTextArea = new JTextArea();
JScrollPane mainPanelScrollPane = new JScrollPane();
JPanel mainDisplayPanel = new JPanel();
private JTextArea mainPanelTextArea = new JTextArea();
private JTextField myStatusTextField = new JTextField();
private JMenuItem openCompleteDataTreeMenuItem = new JMenuItem();
private JMenuItem openDataMenuItem = new JMenuItem();
private JMenuItem saveCompleteDataTreeMenuItem = new JMenuItem();
private JMenuItem saveDataTreeAsMenuItem = new JMenuItem();
private PreferencesDialog thePreferencesDialog;
private final ProgressPanel myProgressPanel = ProgressPanel.getInstance();
private HashMap<JMenuItem, Plugin> myMenuItemHash = new HashMap<JMenuItem, Plugin>();
public TASSELMainFrame() {
try {
loadSettings();
myDataTreePanel = new DataTreePanel(this);
myDataTreePanel.setToolTipText("Data Tree Panel");
addMenuBar();
initializeMyFrame();
this.setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage) " + version);
myLogger.info("Tassel Version: " + version + " Date: " + versionDate);
myLogger.info("Max Available Memory Reported by JVM: " + Utils.getMaxHeapSizeMB() + " MB");
} catch (Exception e) {
e.printStackTrace();
}
}
//Component initialization
private void initializeMyFrame() throws Exception {
getContentPane().setLayout(new BorderLayout());
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// it is time for TASSEL to claim more (almost all) of the screen real estate for itself
// this size was selected so as to encourage the user to resize to full screen, thereby
// insuring that all parts of the frame are visible.
setSize(new Dimension(screenSize.width * 19 / 20, screenSize.height * 19 / 20));
setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage)");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
filerSave.setDialogType(JFileChooser.SAVE_DIALOG);
JSplitPane dataTreeReportPanelsSplitPanel = new JSplitPane();
dataTreeReportPanelsSplitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
reportPanelTextArea.setEditable(false);
reportPanelTextArea.setToolTipText("Report Panel");
mainPanelTextArea.setDoubleBuffered(true);
mainPanelTextArea.setEditable(false);
mainPanelTextArea.setFont(new java.awt.Font("Monospaced", 0, 12));
mainPanelTextArea.setToolTipText("Main Panel");
myStatusTextField.setBackground(Color.lightGray);
myStatusTextField.setBorder(null);
saveCompleteDataTreeMenuItem.setText("Save Data Tree");
saveCompleteDataTreeMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveCompleteDataTreeMenuItem_actionPerformed(e);
}
});
saveDataTreeAsMenuItem.setText("Save Data Tree As ...");
saveDataTreeAsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
saveDataTreeMenuItem_actionPerformed(e);
}
});
openCompleteDataTreeMenuItem.setText("Open Data Tree");
openCompleteDataTreeMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
openCompleteDataTreeMenuItem_actionPerformed(e);
}
});
openDataMenuItem.setText("Open Data Tree...");
openDataMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
openDataMenuItem_actionPerformed(e);
}
});
JSplitPane dataTreeReportMainPanelsSplitPanel = new JSplitPane();
getContentPane().add(dataTreeReportMainPanelsSplitPanel, BorderLayout.CENTER);
dataTreeReportMainPanelsSplitPanel.add(dataTreeReportPanelsSplitPanel, JSplitPane.LEFT);
dataTreeReportPanelsSplitPanel.add(myDataTreePanel, JSplitPane.TOP);
JSplitPane reportProgressSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
JPanel reportPanel = new JPanel(new BorderLayout());
reportProgressSplitPane.add(reportPanel, JSplitPane.TOP);
reportPanel.add(reportPanelScrollPane, BorderLayout.CENTER);
reportPanelScrollPane.getViewport().add(reportPanelTextArea, null);
reportProgressSplitPane.add(new JScrollPane(myProgressPanel), JSplitPane.BOTTOM);
dataTreeReportPanelsSplitPanel.add(reportProgressSplitPane, JSplitPane.BOTTOM);
dataTreeReportMainPanelsSplitPanel.add(mainDisplayPanel, JSplitPane.RIGHT);
mainDisplayPanel.setLayout(new BorderLayout());
mainPanelScrollPane.getViewport().add(mainPanelTextArea, null);
mainDisplayPanel.add(mainPanelScrollPane, BorderLayout.CENTER);
mainPanelScrollPane.getViewport().add(mainPanelTextArea, null);
getContentPane().add(myStatusTextField, BorderLayout.SOUTH);
dataTreeReportMainPanelsSplitPanel.setDividerLocation(getSize().width / 4);
dataTreeReportPanelsSplitPanel.setDividerLocation((int) (getSize().height / 3.5));
reportProgressSplitPane.setDividerLocation((int) (getSize().height / 3.5));
}
private void addMenuBar() {
JMenuBar jMenuBar = new JMenuBar();
jMenuBar.add(getFileMenu());
jMenuBar.add(getDataMenu());
jMenuBar.add(getFiltersMenu());
jMenuBar.add(getAnalysisMenu());
jMenuBar.add(getResultsMenu());
jMenuBar.add(getHelpMenu());
this.setJMenuBar(jMenuBar);
}
//Help | About action performed
private void helpAbout_actionPerformed(ActionEvent e) {
AboutBox dlg = new AboutBox(this);
Dimension dlgSize = dlg.getPreferredSize();
Dimension frmSize = getSize();
Point loc = getLocation();
dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
dlg.setModal(true);
dlg.setVisible(true);
}
public void sendMessage(String text) {
myStatusTextField.setForeground(Color.BLACK);
myStatusTextField.setText(text);
}
public void sendErrorMessage(String text) {
myStatusTextField.setForeground(Color.RED);
myStatusTextField.setText(text);
}
public void setMainText(String text) {
mainPanelTextArea.setText(text);
}
public void setNoteText(String text) {
reportPanelTextArea.setText(text);
}
private void loadSettings() {
filerOpen.setCurrentDirectory(new File(TasselPrefs.getOpenDir()));
filerSave.setCurrentDirectory(new File(TasselPrefs.getSaveDir()));
}
/**
* Provides a save filer that remembers the last location something was
* saved to
*/
private File getSaveFile() {
File saveFile = null;
int returnVal = filerSave.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
saveFile = filerSave.getSelectedFile();
TasselPrefs.putSaveDir(filerSave.getCurrentDirectory().getPath());
}
return saveFile;
}
/**
* Provides a open filer that remember the last location something was
* opened from
*/
private File getOpenFile() {
File openFile = null;
int returnVal = filerOpen.showOpenDialog(this);
System.out.println("returnVal = " + returnVal);
System.out.println("JFileChooser.OPEN_DIALOG " + JFileChooser.OPEN_DIALOG);
if (returnVal == JFileChooser.OPEN_DIALOG || returnVal == JFileChooser.APPROVE_OPTION) {
openFile = filerOpen.getSelectedFile();
System.out.println("openFile = " + openFile);
TasselPrefs.putOpenDir(filerOpen.getCurrentDirectory().getPath());
}
return openFile;
}
public void addDataSet(DataSet theDataSet, String defaultNode) {
myDataTreePanel.addDataSet(theDataSet, defaultNode);
}
private void saveDataTree(String file) {
Map dataToSerialize = new LinkedHashMap();
Map dataFromTree = myDataTreePanel.getDataList();
StringBuilder builder = new StringBuilder();
Iterator itr = dataFromTree.keySet().iterator();
while (itr.hasNext()) {
Datum currentDatum = (Datum) itr.next();
String currentNode = (String) dataFromTree.get(currentDatum);
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(currentDatum);
oos.close();
if (out.toByteArray().length > 0) {
dataToSerialize.put(currentDatum, currentNode);
}
} catch (Exception e) {
myLogger.warn("saveDataTree: object: " + currentDatum.getName() + " type: " + currentDatum.getData().getClass().getName() + " does not serialize.");
myLogger.warn("saveDataTree: message: " + e.getMessage());
if (builder.length() == 0) {
builder.append("Due to error, these data sets could not\n");
builder.append("included in the saved file...");
}
builder.append("Data set: ");
builder.append(currentDatum.getName());
builder.append(" type: ");
builder.append(currentDatum.getData().getClass().getName());
builder.append("\n");
}
}
try {
File theFile = new File(Utils.addSuffixIfNeeded(file, ".zip"));
FileOutputStream fos = new FileOutputStream(theFile);
java.util.zip.ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry thisEntry = new ZipEntry("DATA");
zos.putNextEntry(thisEntry);
ObjectOutputStream oos = new ObjectOutputStream(zos);
oos.writeObject(dataToSerialize);
oos.flush();
zos.closeEntry();
fos.close();
sendMessage("Data saved to " + theFile.getAbsolutePath());
} catch (Exception ee) {
sendErrorMessage("Data could not be saved: " + ee);
ee.printStackTrace();
}
if (builder.length() != 0) {
JOptionPane.showMessageDialog(this, builder.toString(), "These data sets not saved...", JOptionPane.INFORMATION_MESSAGE);
}
}
private boolean readDataTree(String file) {
String dataTreeLoadFailed = "Unable to open the saved data tree. The file format of this version is "
+ "incompatible with other versions.";
boolean loadedDataTreePanel = false;
try {
FileInputStream fis = null;
ObjectInputStream ois = null;
if (file.endsWith("zip")) {
fis = new FileInputStream(file);
java.util.zip.ZipInputStream zis = new java.util.zip.ZipInputStream(fis);
zis.getNextEntry();
ois = new ObjectInputStream(zis);
} else {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
}
try {
Map data = (Map) ois.readObject();
Iterator itr = data.keySet().iterator();
while (itr.hasNext()) {
Datum currentDatum = (Datum) itr.next();
String currentNode = (String) data.get(currentDatum);
myDataTreePanel.addDatum(currentNode, currentDatum);
}
loadedDataTreePanel = true;
} catch (InvalidClassException ice) {
JOptionPane.showMessageDialog(this, dataTreeLoadFailed, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE);
} finally {
fis.close();
}
if (loadedDataTreePanel) {
sendMessage("Data loaded.");
}
} catch (FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(this, "File not found: " + file, "File not found", JOptionPane.INFORMATION_MESSAGE);
sendErrorMessage("Data tree could not be loaded.");
return false;
} catch (Exception ee) {
JOptionPane.showMessageDialog(this, dataTreeLoadFailed + ee, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE);
sendErrorMessage("Data tree could not be loaded.");
return false;
}
return loadedDataTreePanel;
}
private void helpButton_actionPerformed(ActionEvent e) {
HelpDialog theHelpDialog = new HelpDialog(this);
theHelpDialog.setLocationRelativeTo(this);
theHelpDialog.setVisible(true);
}
private void openCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) {
String dataFileName = tasselDataFile + ".zip";
File dataFile = new File(dataFileName);
if (dataFile.exists()) {
readDataTree(dataFileName);
} else if (new File("QPGADataFile").exists()) {
// this exists to maintain backward compatibility with previous versions (pre-v0.99)
readDataTree("QPGADataFile");
} else {
JOptionPane.showMessageDialog(this, "File: " + dataFile.getAbsolutePath() + " does not exist.\n"
+ "Try using File/Open Data Tree...");
}
}
private void openDataMenuItem_actionPerformed(ActionEvent e) {
File f = getOpenFile();
if (f != null) {
readDataTree(f.getAbsolutePath());
}
}
private void saveDataTreeMenuItem_actionPerformed(ActionEvent e) {
File f = getSaveFile();
if (f != null) {
saveDataTree(f.getAbsolutePath());
}
}
private void saveCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) {
saveDataTree(tasselDataFile + ".zip");
}
private void preferencesMenuItem_actionPerformed(ActionEvent e) {
if (thePreferencesDialog == null) {
thePreferencesDialog = new PreferencesDialog();
thePreferencesDialog.pack();
}
thePreferencesDialog.setLocationRelativeTo(this);
thePreferencesDialog.setVisible(true);
}
public void updateMainDisplayPanel(JPanel panel) {
mainDisplayPanel.removeAll();
mainDisplayPanel.add(panel, BorderLayout.CENTER);
mainDisplayPanel.repaint();
mainDisplayPanel.validate();
}
public DataTreePanel getDataTreePanel() {
return myDataTreePanel;
}
public ProgressPanel getProgressPanel() {
return myProgressPanel;
}
private JMenuItem createMenuItem(Plugin theTP) {
return createMenuItem(theTP, -1);
}
private JMenuItem createMenuItem(Plugin theTP, int mnemonic) {
ImageIcon icon = theTP.getIcon();
JMenuItem menuItem = new JMenuItem(theTP.getButtonName(), icon);
if (mnemonic != -1) {
menuItem.setMnemonic(mnemonic);
}
int pixels = 30;
if (icon != null) {
pixels -= icon.getIconWidth();
pixels /= 2;
}
menuItem.setIconTextGap(pixels);
menuItem.setBackground(Color.white);
menuItem.setMargin(new Insets(2, 2, 2, 2));
menuItem.setToolTipText(theTP.getToolTipText());
menuItem.addActionListener(this);
theTP.addListener(myDataTreePanel);
myMenuItemHash.put(menuItem, theTP);
return menuItem;
}
private JMenu getFiltersMenu() {
JMenu result = new JMenu("Filter");
result.setMnemonic(KeyEvent.VK_F);
result.add(createMenuItem(new FilterAlignmentPlugin(this, true)));
result.add(createMenuItem(new FilterSiteNamePlugin(this, true)));
result.add(createMenuItem(new FilterTaxaAlignmentPlugin(this, true)));
result.add(createMenuItem(new FilterTaxaPropertiesPlugin(this, true)));
result.add(createMenuItem(new FilterTraitsPlugin(this, true)));
return result;
}
private JMenu getDataMenu() {
JMenu result = new JMenu("Data");
result.setMnemonic(KeyEvent.VK_D);
PlinkLoadPlugin plinkLoadPlugin = new PlinkLoadPlugin(this, true);
plinkLoadPlugin.addListener(myDataTreePanel);
FlapjackLoadPlugin flapjackLoadPlugin = new FlapjackLoadPlugin(this, true);
flapjackLoadPlugin.addListener(myDataTreePanel);
result.add(createMenuItem(new FileLoadPlugin(this, true, plinkLoadPlugin, flapjackLoadPlugin), KeyEvent.VK_L));
result.add(createMenuItem(new ExportPlugin(this, true)));
result.add(createMenuItem(new ConvertSBitTBitPlugin(this, true)));
result.add(createMenuItem(new GenotypeImputationPlugin(this, true)));
result.add(createMenuItem(new NumericalTransformPlugin(this, true)));
result.add(createMenuItem(new SynonymizerPlugin(this, true)));
result.add(createMenuItem(new IntersectionAlignmentPlugin(this, true)));
result.add(createMenuItem(new UnionAlignmentPlugin(this, true)));
result.add(createMenuItem(new MergeAlignmentsPlugin(this, true)));
result.add(createMenuItem(new SeparatePlugin(this, true)));
result.addSeparator();
JMenuItem delete = new JMenuItem("Delete Dataset");
delete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
myDataTreePanel.deleteSelectedNodes();
}
});
delete.setToolTipText("Delete Dataset");
URL imageURL = TASSELMainFrame.class.getResource("images/trash.gif");
if (imageURL == null) {
delete.setIconTextGap(30);
} else {
delete.setIcon(new ImageIcon(imageURL));
delete.setIconTextGap(6);
}
delete.setIconTextGap(6);
result.add(delete);
return result;
}
private JMenu getAnalysisMenu() {
JMenu result = new JMenu("Analysis");
result.setMnemonic(KeyEvent.VK_A);
result.add(createMenuItem(new SequenceDiversityPlugin(this, true)));
result.add(createMenuItem(new LinkageDisequilibriumPlugin(this, true)));
result.add(createMenuItem(new CreateTreePlugin(this, true)));
result.add(createMenuItem(new KinshipPlugin(this, true)));
result.add(createMenuItem(new FixedEffectLMPlugin(this, true)));
result.add(createMenuItem(new MLMPlugin(this, true)));
result.add(createMenuItem(new RidgeRegressionEmmaPlugin(this, true)));
result.add(createMenuItem(new GenotypeSummaryPlugin(this, true)));
return result;
}
private JMenu getResultsMenu() {
JMenu result = new JMenu("Results");
result.setMnemonic(KeyEvent.VK_R);
result.add(createMenuItem(new TableDisplayPlugin(this, true)));
result.add(createMenuItem(new ArchaeopteryxPlugin(this, true)));
result.add(createMenuItem(new Grid2dDisplayPlugin(this, true)));
result.add(createMenuItem(new LinkageDiseqDisplayPlugin(this, true)));
result.add(createMenuItem(new ChartDisplayPlugin(this, true)));
result.add(createMenuItem(new QQDisplayPlugin(this, true)));
result.add(createMenuItem(new ManhattanDisplayPlugin(this, true)));
result.add(createMenuItem(new TreeDisplayPlugin(this, true)));
return result;
}
private JMenu getFileMenu() {
JMenu fileMenu = new JMenu();
fileMenu.setText("File");
fileMenu.add(saveCompleteDataTreeMenuItem);
fileMenu.add(openCompleteDataTreeMenuItem);
fileMenu.add(saveDataTreeAsMenuItem);
fileMenu.add(openDataMenuItem);
JMenuItem preferencesMenuItem = new JMenuItem();
preferencesMenuItem.setText("Set Preferences");
preferencesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
preferencesMenuItem_actionPerformed(e);
}
});
fileMenu.add(preferencesMenuItem);
fileMenu.addSeparator();
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
fileMenu.add(exitMenuItem);
return fileMenu;
}
private JMenu getHelpMenu() {
JMenu helpMenu = new JMenu();
helpMenu.setMnemonic(KeyEvent.VK_H);
helpMenu.setText("Help");
JMenuItem helpMenuItem = new JMenuItem("Help Manual");
helpMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
helpButton_actionPerformed(e);
}
});
helpMenu.add(helpMenuItem);
JMenuItem aboutMenuItem = new JMenuItem("About");
aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
helpAbout_actionPerformed(e);
}
});
helpMenu.add(aboutMenuItem);
JMenuItem memoryUsage = new JMenuItem("Show Memory");
memoryUsage.addActionListener(PrintHeapAction.getInstance(this));
memoryUsage.setToolTipText("Show Memory Usage");
helpMenu.add(memoryUsage);
return helpMenu;
}
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem theMenuItem = (JMenuItem) e.getSource();
Plugin theTP = this.myMenuItemHash.get(theMenuItem);
PluginEvent event = new PluginEvent(myDataTreePanel.getSelectedTasselDataSet());
ProgressPanel progressPanel = getProgressPanel();
progressPanel.addPlugin(theTP);
ThreadedPluginListener thread = new ThreadedPluginListener(theTP, event);
thread.start();
}
} |
package nl.mpi.arbil.clarin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import nl.mpi.arbil.ArbilEntityResolver;
import nl.mpi.arbil.GuiHelper;
import nl.mpi.arbil.LinorgJournal;
import nl.mpi.arbil.LinorgSessionStorage;
import nl.mpi.arbil.LinorgWindowManager;
import nl.mpi.arbil.data.ImdiLoader;
import nl.mpi.arbil.data.ImdiTreeObject;
import org.apache.xmlbeans.SchemaProperty;
import org.apache.xmlbeans.SchemaType;
import org.apache.xmlbeans.SchemaTypeSystem;
import org.apache.xmlbeans.XmlBeans;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class CmdiComponentBuilder {
public Document getDocument(URI inputUri) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(false);
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document;
if (inputUri == null) {
document = documentBuilder.newDocument();
} else {
String decodeUrlString = URLDecoder.decode(inputUri.toString(), "UTF-8");
document = documentBuilder.parse(decodeUrlString);
}
return document;
}
// private Document createDocument(File inputFile) throws ParserConfigurationException, SAXException, IOException {
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// documentBuilderFactory.setValidating(false);
// DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// Document document = documentBuilder.newDocument();
// return document;
public void savePrettyFormatting(Document document, File outputFile) {
try {
if (outputFile.toString().endsWith(".imdi")) {
removeDomIds(document); // remove any dom id attributes left over by the imdi api
}
// set up input and output
DOMSource dOMSource = new DOMSource(document);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
StreamResult xmlOutput = new StreamResult(fileOutputStream);
// configure transformer
Transformer transformer = TransformerFactory.newInstance().newTransformer();
//transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(dOMSource, xmlOutput);
xmlOutput.getOutputStream().close();
// todo: this maybe excessive to do every time
// this schema check has been moved to the point of loading the file rather than saving the file
// XsdChecker xsdChecker = new XsdChecker();
// String checkerResult;
// checkerResult = xsdChecker.simpleCheck(outputFile, outputFile.toURI());
// if (checkerResult != null) {
// hasSchemaError = true;
//// LinorgWindowManager.getSingleInstance().addMessageDialogToQueue(checkerResult, "Schema Check");
//System.out.println(xmlOutput.getWriter().toString());
} catch (IllegalArgumentException illegalArgumentException) {
GuiHelper.linorgBugCatcher.logError(illegalArgumentException);
} catch (TransformerException transformerException) {
GuiHelper.linorgBugCatcher.logError(transformerException);
} catch (TransformerFactoryConfigurationError transformerFactoryConfigurationError) {
System.out.println(transformerFactoryConfigurationError.getMessage());
} catch (FileNotFoundException notFoundException) {
GuiHelper.linorgBugCatcher.logError(notFoundException);
} catch (IOException iOException) {
GuiHelper.linorgBugCatcher.logError(iOException);
}
}
public URI insertResourceProxy(ImdiTreeObject imdiTreeObject, ImdiTreeObject resourceNode) {
// there is no need to save the node at this point because metadatabuilder has already done so
synchronized (imdiTreeObject.getParentDomLockObject()) {
// <.CMD.Resources.ResourceProxyList.ResourceProxy>
// <ResourceProxyList>
// <ResourceProxy id="a_text">
// <ResourceType>Resource</ResourceType>
// <ResourceRef>bla.txt</ResourceRef>
// </ResourceProxy>
String targetXmlPath = imdiTreeObject.getURI().getFragment();
if (targetXmlPath == null) {
// todo: consider making sure that the dom parent node always has a path
targetXmlPath = ".CMD.Components." + imdiTreeObject.getParentDomNode().nodeTemplate.loadedTemplateName;
}
System.out.println("insertResourceProxy: " + targetXmlPath);
// File cmdiNodeFile = imdiTreeObject.getFile();
// String nodeFragment = "";
// geerate a uuid for new resource
String resourceProxyId = UUID.randomUUID().toString();
try {
// load the schema
SchemaType schemaType = getFirstSchemaType(imdiTreeObject.getNodeTemplate().templateFile);
// load the dom
Document targetDocument = getDocument(imdiTreeObject.getURI());
// insert the new section
try {
try {
// if (targetXmlPath == null) {
// targetXmlPath = ".CMD.Components";
Node documentNode = selectSingleNode(targetDocument, targetXmlPath);
Node previousRefNode = documentNode.getAttributes().getNamedItem("ref");
if (previousRefNode != null) {
String previousRefValue = documentNode.getAttributes().getNamedItem("ref").getNodeValue();
// todo: remove old resource nodes that this one overwrites
}
((Element) documentNode).setAttribute("ref", resourceProxyId);
} catch (TransformerException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
}
// printoutDocument(targetDocument);
Node addedResourceNode = insertSectionToXpath(targetDocument, targetDocument.getFirstChild(), schemaType, ".CMD.Resources.ResourceProxyList", ".CMD.Resources.ResourceProxyList.ResourceProxy");
addedResourceNode.getAttributes().getNamedItem("id").setNodeValue(resourceProxyId);
for (Node childNode = addedResourceNode.getFirstChild(); childNode != null; childNode = childNode.getNextSibling()) {
String localName = childNode.getNodeName();
if ("ResourceType".equals(localName)) {
childNode.setTextContent(resourceNode.mpiMimeType);
}
if ("ResourceRef".equals(localName)) {
childNode.setTextContent(resourceNode.getUrlString());
}
}
} catch (Exception exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
}
// bump the history
imdiTreeObject.bumpHistory();
// save the dom
savePrettyFormatting(targetDocument, imdiTreeObject.getFile()); // note that we want to make sure that this gets saved even without changes because we have bumped the history ant there will be no file otherwise
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
} catch (ParserConfigurationException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
} catch (SAXException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
}
return imdiTreeObject.getURI();
}
}
public boolean removeChildNodes(ImdiTreeObject imdiTreeObject, String nodePaths[]) {
if (imdiTreeObject.getNeedsSaveToDisk(false)) {
imdiTreeObject.saveChangesToCache(true);
}
synchronized (imdiTreeObject.getParentDomLockObject()) {
System.out.println("removeChildNodes: " + imdiTreeObject);
File cmdiNodeFile = imdiTreeObject.getFile();
try {
Document targetDocument = getDocument(imdiTreeObject.getURI());
// collect up all the nodes to be deleted without changing the xpath
ArrayList<Node> selectedNodes = new ArrayList<Node>();
for (String currentNodePath : nodePaths) {
System.out.println("removeChildNodes: " + currentNodePath);
// todo: search for and remove any reource links referenced by this node or its sub nodes
Node documentNode = selectSingleNode(targetDocument, currentNodePath);
selectedNodes.add(documentNode);
}
// delete all the nodes now that the xpath is no longer relevant
for (Node currentNode : selectedNodes) {
// todo: there may be an issue here when deleting a languages node with two languages within it
currentNode.getParentNode().removeChild(currentNode);
}
// bump the history
imdiTreeObject.bumpHistory();
// save the dom
savePrettyFormatting(targetDocument, cmdiNodeFile);
for (String currentNodePath : nodePaths) {
// todo log to jornal file
}
return true;
} catch (ParserConfigurationException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (SAXException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (TransformerException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
return false;
}
}
public boolean setFieldValues(ImdiTreeObject imdiTreeObject, FieldUpdateRequest[] fieldUpdates) {
synchronized (imdiTreeObject.getParentDomLockObject()) {
//new ImdiUtils().addDomIds(imdiTreeObject.getURI()); // testing only
System.out.println("setFieldValues: " + imdiTreeObject);
File cmdiNodeFile = imdiTreeObject.getFile();
try {
Document targetDocument = getDocument(imdiTreeObject.getURI());
for (FieldUpdateRequest currentFieldUpdate : fieldUpdates) {
System.out.println("currentFieldUpdate: " + currentFieldUpdate.fieldPath);
// todo: search for and remove any reource links referenced by this node or its sub nodes
Node documentNode = selectSingleNode(targetDocument, currentFieldUpdate.fieldPath);
NamedNodeMap attributesMap = documentNode.getAttributes();
if (currentFieldUpdate.fieldOldValue.equals(documentNode.getTextContent())) {
documentNode.setTextContent(currentFieldUpdate.fieldNewValue);
} else {
GuiHelper.linorgBugCatcher.logError(new Exception("expecting \'" + currentFieldUpdate.fieldOldValue + "\' not \'" + documentNode.getTextContent() + "\' in " + currentFieldUpdate.fieldPath));
return false;
}
Node keyNameNode = attributesMap.getNamedItem("Name");
if (keyNameNode != null && currentFieldUpdate.keyNameValue != null) {
keyNameNode.setNodeValue(currentFieldUpdate.keyNameValue);
}
Node languageNode = attributesMap.getNamedItem("LanguageId");
if (languageNode == null) {
languageNode = attributesMap.getNamedItem("xml:lang");
}
if (languageNode != null && currentFieldUpdate.fieldLanguageId != null) {
languageNode.setNodeValue(currentFieldUpdate.fieldLanguageId);
}
}
// bump the history
imdiTreeObject.bumpHistory();
// save the dom
savePrettyFormatting(targetDocument, cmdiNodeFile);
for (FieldUpdateRequest currentFieldUpdate : fieldUpdates) {
// log to jornal file
LinorgJournal.getSingleInstance().saveJournalEntry(imdiTreeObject.getUrlString(), currentFieldUpdate.fieldPath, currentFieldUpdate.fieldOldValue, currentFieldUpdate.fieldNewValue, "save");
if (currentFieldUpdate.fieldLanguageId != null) {
LinorgJournal.getSingleInstance().saveJournalEntry(imdiTreeObject.getUrlString(), currentFieldUpdate.fieldPath + ":LanguageId", currentFieldUpdate.fieldLanguageId, "", "save");
}
if (currentFieldUpdate.keyNameValue != null) {
LinorgJournal.getSingleInstance().saveJournalEntry(imdiTreeObject.getUrlString(), currentFieldUpdate.fieldPath + ":Name", currentFieldUpdate.keyNameValue, "", "save");
}
}
return true;
} catch (ParserConfigurationException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (SAXException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (TransformerException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
return false;
}
}
public void testInsertFavouriteComponent() {
try {
ImdiTreeObject favouriteImdiTreeObject1 = ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(new URI("file:/Users/petwit/.arbil/favourites/fav-784841449583527834.imdi#.METATRANSCRIPT.Session.MDGroup.Actors.Actor"));
ImdiTreeObject favouriteImdiTreeObject2 = ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(new URI("file:/Users/petwit/.arbil/favourites/fav-784841449583527834.imdi#.METATRANSCRIPT.Session.MDGroup.Actors.Actor(2)"));
ImdiTreeObject destinationImdiTreeObject = ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(new URI("file:/Users/petwit/.arbil/imdicache/20100527141926/20100527141926.imdi"));
insertFavouriteComponent(destinationImdiTreeObject, favouriteImdiTreeObject1);
insertFavouriteComponent(destinationImdiTreeObject, favouriteImdiTreeObject2);
} catch (URISyntaxException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (ArbilMetadataException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
public Node insertNodeInOrder(Node destinationNode, Node addableNode, String insertBefore, int maxOccurs) throws TransformerException, ArbilMetadataException {
// todo: read the template for max occurs values and use them here and for all inserts
Node insertBeforeNode = null;
if (insertBefore != null && insertBefore.length() > 0) {
String[] insertBeforeArray = insertBefore.split(",");
// find the node to add the new section before
NodeList childNodes = destinationNode.getChildNodes();
outerloop:
for (int childCounter = 0; childCounter < childNodes.getLength(); childCounter++) {
String childsName = childNodes.item(childCounter).getLocalName();
for (String currentInsertBefore : insertBeforeArray) {
if (currentInsertBefore.equals(childsName)) {
System.out.println("insertbefore: " + childsName);
insertBeforeNode = childNodes.item(childCounter);
break outerloop;
}
}
}
}
if (maxOccurs > 0) {
String addableName = addableNode.getLocalName();
if (addableName == null) {
addableName = addableNode.getNodeName();
}
NodeList childNodes = destinationNode.getChildNodes();
int duplicateNodeCounter = 0;
for (int childCounter = 0; childCounter < childNodes.getLength(); childCounter++) {
String childsName = childNodes.item(childCounter).getLocalName();
if (addableName.equals(childsName)) {
duplicateNodeCounter++;
if (duplicateNodeCounter >= maxOccurs) {
throw new ArbilMetadataException("The maximum nodes of this type have already been added.\n");
}
}
}
}
// find the node to add the new section to
Node addedNode;
if (insertBeforeNode != null) {
System.out.println("inserting before: " + insertBeforeNode.getNodeName());
addedNode = destinationNode.insertBefore(addableNode, insertBeforeNode);
} else {
System.out.println("inserting");
addedNode = destinationNode.appendChild(addableNode);
}
return addedNode;
}
public URI insertFavouriteComponent(ImdiTreeObject destinationImdiTreeObject, ImdiTreeObject favouriteImdiTreeObject) throws ArbilMetadataException {
URI returnUri = null;
// this node has already been saved in the metadatabuilder which called this
// but lets check this again in case this gets called elsewhere and to make things consistant
String elementName = favouriteImdiTreeObject.getURI().getFragment();
String insertBefore = destinationImdiTreeObject.nodeTemplate.getInsertBeforeOfTemplate(elementName);
System.out.println("insertBefore: " + insertBefore);
int maxOccurs = destinationImdiTreeObject.nodeTemplate.getMaxOccursForTemplate(elementName);
System.out.println("maxOccurs: " + maxOccurs);
if (destinationImdiTreeObject.getNeedsSaveToDisk(false)) {
destinationImdiTreeObject.saveChangesToCache(true);
}
try {
Document favouriteDocument;
synchronized (favouriteImdiTreeObject.getParentDomLockObject()) {
favouriteDocument = getDocument(favouriteImdiTreeObject.getURI());
}
synchronized (destinationImdiTreeObject.getParentDomLockObject()) {
Document destinationDocument = getDocument(destinationImdiTreeObject.getURI());
String favouriteXpath = favouriteImdiTreeObject.getURI().getFragment();
String favouriteXpathTrimmed = favouriteXpath.replaceFirst("\\.[^(^.]+$", "");
boolean onlySubNodes = !favouriteXpathTrimmed.equals(favouriteXpath);
System.out.println("favouriteXpath: " + favouriteXpathTrimmed);
String destinationXpath;
if (onlySubNodes) {
destinationXpath = favouriteXpathTrimmed;
} else {
destinationXpath = favouriteXpathTrimmed.replaceFirst("\\.[^.]+$", "");
}
System.out.println("destinationXpath: " + destinationXpath);
Node destinationNode = selectSingleNode(destinationDocument, destinationXpath);
Node selectedNode = selectSingleNode(favouriteDocument, favouriteXpathTrimmed);
Node importedNode = destinationDocument.importNode(selectedNode, true);
Node[] favouriteNodes;
if (onlySubNodes) {
NodeList selectedNodeList = importedNode.getChildNodes();
favouriteNodes = new Node[selectedNodeList.getLength()];
for (int nodeCounter = 0; nodeCounter < selectedNodeList.getLength(); nodeCounter++) {
favouriteNodes[nodeCounter] = selectedNodeList.item(nodeCounter);
}
} else {
favouriteNodes = new Node[]{importedNode};
}
for (Node singleFavouriteNode : favouriteNodes) {
if (singleFavouriteNode.getNodeType() != Node.TEXT_NODE) {
insertNodeInOrder(destinationNode, singleFavouriteNode, insertBefore, maxOccurs);
// destinationNode.appendChild(singleFavouriteNode);
System.out.println("inserting favouriteNode: " + singleFavouriteNode.getLocalName());
}
}
savePrettyFormatting(destinationDocument, destinationImdiTreeObject.getFile());
try {
String nodeFragment;
if (favouriteNodes.length != 1) {
nodeFragment = destinationXpath; // in this case show the target node
} else {
nodeFragment = convertNodeToNodePath(destinationDocument, favouriteNodes[0], destinationXpath);
}
System.out.println("nodeFragment: " + nodeFragment);
// return the child node url and path in the xml
// first strip off any fragment then add the full node fragment
returnUri = new URI(destinationImdiTreeObject.getURI().toString().split("#")[0] + "#" + nodeFragment);
} catch (URISyntaxException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (ParserConfigurationException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (SAXException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
} catch (TransformerException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
return returnUri;
}
public URI insertChildComponent(ImdiTreeObject imdiTreeObject, String targetXmlPath, String cmdiComponentId) {
if (imdiTreeObject.getNeedsSaveToDisk(false)) {
imdiTreeObject.saveChangesToCache(true);
}
synchronized (imdiTreeObject.getParentDomLockObject()) {
System.out.println("insertChildComponent: " + cmdiComponentId);
System.out.println("targetXmlPath: " + targetXmlPath);
// check for issues with the path
if (targetXmlPath == null) {
targetXmlPath = cmdiComponentId.replaceAll("\\.[^.]+$", "");
} else if (targetXmlPath.replaceAll("\\(\\d+\\)", "").length() == cmdiComponentId.length()) {
// trim the last path component if the destination equals the new node path
// i.e. xsdPath: .CMD.Components.Session.Resources.MediaFile.Keys.Key into .CMD.Components.Session.Resources.MediaFile(1).Keys.Key
targetXmlPath = targetXmlPath.replaceAll("\\.[^.]+$", "");
}
// make sure the target xpath has all the required parts
String[] cmdiComponentArray = cmdiComponentId.split("\\.");
String[] targetXmlPathArray = targetXmlPath.replaceAll("\\(\\d+\\)", "").split("\\.");
for (int pathPartCounter = targetXmlPathArray.length; pathPartCounter < cmdiComponentArray.length - 1; pathPartCounter++) {
System.out.println("adding missing path component: " + cmdiComponentArray[pathPartCounter]);
targetXmlPath = targetXmlPath + "." + cmdiComponentArray[pathPartCounter];
}
// end path corrections
System.out.println("trimmed targetXmlPath: " + targetXmlPath);
//String targetXpath = targetNode.getURI().getFragment();
//System.out.println("targetXpath: " + targetXpath);
// File cmdiNodeFile = imdiTreeObject.getFile();
String nodeFragment = "";
try {
// load the schema
SchemaType schemaType = getFirstSchemaType(imdiTreeObject.getNodeTemplate().templateFile);
// load the dom
Document targetDocument = getDocument(imdiTreeObject.getURI());
// insert the new section
try {
// printoutDocument(targetDocument);
Node AddedNode = insertSectionToXpath(targetDocument, targetDocument.getFirstChild(), schemaType, targetXmlPath, cmdiComponentId);
nodeFragment = convertNodeToNodePath(targetDocument, AddedNode, targetXmlPath);
} catch (ArbilMetadataException exception) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue(exception.getLocalizedMessage(), "Insert node error");
return null;
}
// bump the history
imdiTreeObject.bumpHistory();
// save the dom
savePrettyFormatting(targetDocument, imdiTreeObject.getFile()); // note that we want to make sure that this gets saved even without changes because we have bumped the history ant there will be no file otherwise
} catch (IOException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
} catch (ParserConfigurationException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
} catch (SAXException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
}
// diff_match_patch diffTool= new diff_match_patch();
// diffTool.diff_main(targetXpath, targetXpath);
try {
System.out.println("nodeFragment: " + nodeFragment);
// return the child node url and path in the xml
// first strip off any fragment then add the full node fragment
return new URI(imdiTreeObject.getURI().toString().split("#")[0] + "#" + nodeFragment);
} catch (URISyntaxException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
return null;
}
}
}
public void testRemoveArchiveHandles() {
try {
Document workingDocument = getDocument(new URI("http://corpus1.mpi.nl/qfs1/media-archive/Corpusstructure/MPI.imdi"));
removeArchiveHandles(workingDocument);
printoutDocument(workingDocument);
} catch (Exception exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
public void removeArchiveHandles(ImdiTreeObject imdiTreeObject) {
synchronized (imdiTreeObject.getParentDomLockObject()) {
try {
Document workingDocument = getDocument(imdiTreeObject.getURI());
removeArchiveHandles(workingDocument);
savePrettyFormatting(workingDocument, imdiTreeObject.getFile());
} catch (Exception exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
}
private void removeDomIds(Document targetDocument) { |
package org.torproject.jtor.circuits.path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.torproject.jtor.circuits.guards.EntryGuards;
import org.torproject.jtor.circuits.path.CircuitNodeChooser.WeightRule;
import org.torproject.jtor.data.IPv4Address;
import org.torproject.jtor.data.exitpolicy.ExitTarget;
import org.torproject.jtor.directory.Directory;
import org.torproject.jtor.directory.Router;
public class CircuitPathChooser {
private final Directory directory;
private final CircuitNodeChooser nodeChooser;
private EntryGuards entryGuards;
private boolean useEntryGuards;
public CircuitPathChooser(Directory directory) {
this.directory = directory;
this.nodeChooser = new CircuitNodeChooser(directory);
this.entryGuards = null;
this.useEntryGuards = false;
}
public void enableEntryGuards(EntryGuards entryGuards) {
this.entryGuards = entryGuards;
this.useEntryGuards = true;
}
public List<Router> chooseDirectoryPath() {
final Router dir = nodeChooser.chooseDirectory();
return Arrays.asList(dir);
}
public List<Router> choosePathWithExit(Router exitRouter) throws InterruptedException, PathSelectionFailedException {
final Set<Router> excluded = new HashSet<Router>();
excludeChosenRouterAndRelated(exitRouter, excluded);
final Router middleRouter = chooseMiddleNode(excluded);
if(middleRouter == null) {
throw new PathSelectionFailedException("Failed to select suitable middle node");
}
excludeChosenRouterAndRelated(middleRouter, excluded);
final Router entryRouter = chooseEntryNode(excluded);
if(entryRouter == null) {
throw new PathSelectionFailedException("Failed to select suitable entry node");
}
return Arrays.asList(entryRouter, middleRouter, exitRouter);
}
public Router chooseEntryNode(final Set<Router> excludedRouters) throws InterruptedException {
if(useEntryGuards) {
return entryGuards.chooseRandomGuard(excludedRouters);
}
return nodeChooser.chooseRandomNode(WeightRule.WEIGHT_FOR_GUARD, new RouterFilter() {
public boolean filter(Router router) {
return router.isPossibleGuard() && !excludedRouters.contains(router);
}
});
}
Router chooseMiddleNode(final Set<Router> excludedRouters) {
return nodeChooser.chooseRandomNode(WeightRule.WEIGHT_FOR_MID, new RouterFilter() {
public boolean filter(Router router) {
return router.isFast() && !excludedRouters.contains(router);
}
});
}
public Router chooseExitNodeForTargets(List<ExitTarget> targets) {
final List<Router> routers = filterForExitTargets(
getUsableExitRouters(), targets);
return nodeChooser.chooseExitNode(routers);
}
private List<Router> getUsableExitRouters() {
final List<Router> result = new ArrayList<Router>();
for(Router r: nodeChooser.getUsableRouters(true)) {
if(r.isExit() && !r.isBadExit()) {
result.add(r);
}
}
return result;
}
private void excludeChosenRouterAndRelated(Router router, Set<Router> excludedRouters) {
excludedRouters.add(router);
for(Router r: directory.getAllRouters()) {
if(areInSameSlash16(router, r)) {
excludedRouters.add(r);
}
}
for(String s: router.getFamilyMembers()) {
Router r = directory.getRouterByName(s);
if(r != null) {
excludedRouters.add(r);
}
}
}
// Are routers r1 and r2 in the same /16 network
private boolean areInSameSlash16(Router r1, Router r2) {
final IPv4Address a1 = r1.getAddress();
final IPv4Address a2 = r2.getAddress();
final int mask = 0xFFFF0000;
return (a1.getAddressData() & mask) == (a2.getAddressData() & mask);
}
private List<Router> filterForExitTargets(List<Router> routers, List<ExitTarget> exitTargets) {
int bestSupport = 0;
if(exitTargets.isEmpty()) {
return routers;
}
final int[] nSupport = new int[routers.size()];
for(int i = 0; i < routers.size(); i++) {
final Router r = routers.get(i);
nSupport[i] = countTargetSupport(r, exitTargets);
if(nSupport[i] > bestSupport) {
bestSupport = nSupport[i];
}
}
if(bestSupport == 0) {
return routers;
}
final List<Router> results = new ArrayList<Router>();
for(int i = 0; i < routers.size(); i++) {
if(nSupport[i] == bestSupport) {
results.add(routers.get(i));
}
}
return results;
}
private int countTargetSupport(Router router, List<ExitTarget> targets) {
int count = 0;
for(ExitTarget t: targets) {
if(routerSupportsTarget(router, t)) {
count += 1;
}
}
return count;
}
private boolean routerSupportsTarget(Router router, ExitTarget target) {
if(target.isAddressTarget()) {
return router.exitPolicyAccepts(target.getAddress(), target.getPort());
} else {
return router.exitPolicyAccepts(target.getPort());
}
}
} |
package org.ensembl.healthcheck;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.Utils;
/**
* Class that stores information about which databases are available.
*/
public class DatabaseRegistry {
// Entries is explicitly specified as an ArrayList rather than the list
// because the order is important
private ArrayList<DatabaseRegistryEntry> entries = new ArrayList<DatabaseRegistryEntry>();
// these global settings override guessing if they are specified
private Species globalSpecies = null;
private DatabaseType globalType = null;
/** The logger to use */
private static Logger logger = Logger.getLogger("HealthCheckLogger");
/**
* Create a new DatabaseRegistry. DatabaseRegistryEntry objects for the databases matching regexp are created and added to the
* registry.
*
* @param regexps
* The regular expressions matching the databases to use. If null, match everything.
* @param isSecondary
* If true, this is a secondary database registry.
*/
public DatabaseRegistry(List<String> regexps, DatabaseType globalType, Species globalSpecies, boolean isSecondary) {
if (!isSecondary) {
this.globalType = globalType;
this.globalSpecies = globalSpecies;
}
List<DatabaseServer> servers = isSecondary ? DBUtils.getSecondaryDatabaseServers() : DBUtils.getMainDatabaseServers();
for (DatabaseServer server : servers) {
if (regexps == null || regexps.size() == 0) {
String[] names = DBUtils.listDatabases(server.getServerConnection(), null);
addEntriesToRegistry(server, names, isSecondary);
} else {
Iterator<String> it = regexps.iterator();
while (it.hasNext()) {
String regexp = it.next();
String[] names = DBUtils.listDatabases(server.getServerConnection(), regexp);
addEntriesToRegistry(server, names, isSecondary);
}
}
}
}
/**
* Create a new DatabaseRegistry from an array of DatabaseRegistryEntries.
*
* @param dbres
* The entries to use.
*/
public DatabaseRegistry(final DatabaseRegistryEntry[] dbres) {
for (int i = 0; i < dbres.length; i++) {
entries.add(dbres[i]);
}
}
/**
* Create a new DatabaseRegistry from a list of DatabaseRegistryEntries.
*
* @param dbres
* The entries to use.
*/
public DatabaseRegistry(List<DatabaseRegistryEntry> dbres) {
Iterator<DatabaseRegistryEntry> it = dbres.iterator();
while (it.hasNext()) {
entries.add(it.next());
}
}
private void addEntriesToRegistry(DatabaseServer server, final String[] names, boolean isSecondary) {
for (String name : names) {
DatabaseRegistryEntry dbre = new DatabaseRegistryEntry(server, name, globalSpecies, globalType);
if (!this.contains(dbre)) {
//logger.finest(dbre.getName() + " appears to be type " + dbre.getType() + " and species " + dbre.getSpecies());
dbre.setDatabaseRegistry(this);
entries.add(dbre);
logger.finest("Added DatabaseRegistryEntry for " + name + " to " + (isSecondary ? "secondary" : "main") + " DatabaseRegistry");
} else {
logger.finest("Registry already contains an entry for " + dbre.getName() + ", skipping");
}
}
}
/**
* Add a new DatabaseRegistryEntry to this registry.
*
* @param dbre
* The new DatabaseRegistryEntry.
*/
public final void add(final DatabaseRegistryEntry dbre) {
entries.add(dbre);
dbre.setDatabaseRegistry(this);
}
/**
* Get all of the DatabaseRegistryEntries stored in this DatabaseRegistry.
*
* @return The DatabaseRegistryEntries stored in this DatabaseRegistry.
*/
public final DatabaseRegistryEntry[] getAll() {
return (DatabaseRegistryEntry[]) entries.toArray(new DatabaseRegistryEntry[entries.size()]);
}
/**
* Get all of the DatabaseRegistryEntries for a particular species
*
* @param species
* The species to look for.
* @return The DatabaseRegistryEntries for species..
*/
public final DatabaseRegistryEntry[] getAll(final Species species) {
List<DatabaseRegistryEntry> result = new ArrayList<DatabaseRegistryEntry>();
Iterator<DatabaseRegistryEntry> it = entries.iterator();
while (it.hasNext()) {
DatabaseRegistryEntry dbre = it.next();
if (dbre.getSpecies().equals(species)) {
result.add(dbre);
}
}
return (DatabaseRegistryEntry[]) result.toArray(new DatabaseRegistryEntry[result.size()]);
}
/**
* Get all of the DatabaseRegistryEntries for a particular database type.
*
* @param type
* The type to look for.
* @return The DatabaseRegistryEntries for type.
*/
public final DatabaseRegistryEntry[] getAll(final DatabaseType type) {
List<DatabaseRegistryEntry> result = new ArrayList<DatabaseRegistryEntry>();
Iterator<DatabaseRegistryEntry> it = entries.iterator();
while (it.hasNext()) {
DatabaseRegistryEntry dbre = it.next();
if (dbre.getType().equals(type)) {
result.add(dbre);
}
}
return (DatabaseRegistryEntry[]) result.toArray(new DatabaseRegistryEntry[result.size()]);
}
/**
* Get all of the DatabaseRegistryEntries for a particular database type and species.
*
* @param type
* The type to look for.
* @param species
* The Species to look for.
* @return The DatabaseRegistryEntries that match type and species..
*/
public final DatabaseRegistryEntry[] getAll(final DatabaseType type, final Species species) {
List<DatabaseRegistryEntry> result = new ArrayList<DatabaseRegistryEntry>();
Iterator<DatabaseRegistryEntry> it = entries.iterator();
while (it.hasNext()) {
DatabaseRegistryEntry dbre = it.next();
if (dbre.getType().equals(type) && dbre.getSpecies().equals(species)) {
result.add(dbre);
}
}
return (DatabaseRegistryEntry[]) result.toArray(new DatabaseRegistryEntry[result.size()]);
}
/**
* Get a single, named DatabaseRegistryEntry.
*
* @param name
* The name to look for.
* @return The matching DatabaseRegistryEntry, or null if none is found.
*/
public final DatabaseRegistryEntry getByExactName(String name) {
Iterator<DatabaseRegistryEntry> it = entries.iterator();
while (it.hasNext()) {
DatabaseRegistryEntry dbre = it.next();
if (dbre.getName().equals(name)) {
return dbre;
}
}
logger.warning("Can't find database matching name " + name);
return null;
}
/**
* Get a list of the types of databases in the registry.
*
* @return An array containing each DatabaseType found in the registry.
*/
public final DatabaseType[] getTypes() {
List<DatabaseType> types = new ArrayList<DatabaseType>();
Iterator<DatabaseRegistryEntry> it = entries.iterator();
while (it.hasNext()) {
DatabaseRegistryEntry dbre = it.next();
if (!types.contains(dbre.getType())) {
types.add(dbre.getType());
}
}
return (DatabaseType[]) types.toArray(new DatabaseType[types.size()]);
}
/**
* Get a list of the species in the registry.
*
* @return An array containing each Species found in the registry.
*/
public final Species[] getSpecies() {
List<Species> species = new ArrayList<Species>();
Iterator<DatabaseRegistryEntry> it = entries.iterator();
while (it.hasNext()) {
DatabaseRegistryEntry dbre = it.next();
if (!species.contains(dbre.getSpecies())) {
species.add(dbre.getSpecies());
}
}
return (Species[]) species.toArray(new Species[species.size()]);
}
/**
* @return The number of DatabaseRegistryEntries in this registry.
*/
public final int getEntryCount() {
return entries.size();
}
/**
* @return True if this registry contains a particular DatabaseRegistryEntry (note equals() method in DatabaseRegistryEntry
* determines this behaviour).
*/
public boolean contains(DatabaseRegistryEntry dbre) {
for (DatabaseRegistryEntry entry : entries) {
if (entry.equals(dbre)) {
return true;
}
}
return false;
}
/**
* @return List of entries from this registry that match a regexp. Note that this will be a subset of the entries that the
* registry was created from (based on another regexp!)
*/
public List<DatabaseRegistryEntry> getMatching(String regexp) {
List<DatabaseRegistryEntry> result = new ArrayList<DatabaseRegistryEntry>();
for (DatabaseRegistryEntry entry : entries) {
if (entry.getName().matches(regexp)) {
result.add(entry);
}
}
return result;
}
} // DatabaseRegistry |
package com.abstratt.kirra.rest.common;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import com.abstratt.kirra.Instance;
import com.abstratt.kirra.TypeRef;
import com.abstratt.kirra.TypeRef.TypeKind;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class InstanceSerializer implements JsonSerializer<Instance>, JsonDeserializer<Instance> {
public InstanceSerializer() {
}
private static final List<String> EXCLUDED_FIELDS = Arrays.<String>asList(new String[] {
"links", "objectId", "typeRef"});
@Override
public JsonElement serialize(Instance instance, Type type, JsonSerializationContext context) {
Gson gson = CommonHelper.buildBasicGson().setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
@Override
public boolean shouldSkipField(FieldAttributes arg0) {
return EXCLUDED_FIELDS.contains(arg0.getName());
}
}).create();
JsonObject asJson = (JsonObject) gson.toJsonTree(instance);
// flatten links to avoid infinite recursion due to cyclic refs
Map<String, Instance> links = instance.getLinks();
JsonObject linksAsJson = new JsonObject();
for (Map.Entry<String, Instance> link : links.entrySet()) {
String relationshipName = link.getKey();
JsonElement element;
if (link.getValue() == null)
element = JsonNull.INSTANCE;
else
element = addBasicProperties(gson, link.getValue(), new JsonObject());
linksAsJson.add(relationshipName, element);
}
asJson.add("links", linksAsJson);
addBasicProperties(gson, instance, asJson);
return asJson;
}
@Override
public Instance deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
JsonObject asJsonObject = jsonElement.getAsJsonObject();
// ensure links don't have sublinks/values and have an objectId
if (asJsonObject.has("links")) {
for (Entry<String, JsonElement> entry : asJsonObject.get("links").getAsJsonObject().entrySet()) {
JsonObject linkAsObject = entry.getValue().getAsJsonObject();
if (linkAsObject.has("uri")) {
JsonElement uri = linkAsObject.get("uri");
String uriString = uri.getAsString();
String[] segments = StringUtils.split(uriString, "/");
// uri is '...<entity>/instances/<objectId>'
if (segments.length > 0)
linkAsObject.addProperty("objectId", segments[segments.length - 1]);
if (segments.length > 2) {
String linkedTypeName = segments[segments.length - 3];
TypeRef linkType = new TypeRef(linkedTypeName, TypeKind.Entity);
linkAsObject.addProperty("scopeName", linkType.getTypeName());
linkAsObject.addProperty("scopeNamespace", linkType.getNamespace());
}
}
linkAsObject.remove("values");
linkAsObject.remove("links");
linkAsObject.addProperty("full", false);
}
}
Instance instance = new Gson().fromJson(jsonElement, Instance.class);
return instance;
}
private JsonObject addBasicProperties(Gson gson, Instance instance, JsonObject instanceAsJson) {
URI entityUri = CommonHelper.resolve(KirraContext.getBaseURI(), Paths.ENTITIES, instance.getTypeRef().toString());
URI instanceUri = CommonHelper.resolve(entityUri, Paths.INSTANCES, instance.getObjectId());
instanceAsJson.addProperty("objectId", instance.getObjectId());
instanceAsJson.addProperty("uri", instanceUri.toString());
instanceAsJson.addProperty("shorthand", getShorthand(instance));
instanceAsJson.addProperty("entityUri", entityUri.toString());
instanceAsJson.add("typeRef", gson.toJsonTree(instance.getTypeRef()));
instanceAsJson.addProperty("scopeName", instance.getTypeRef().getTypeName());
instanceAsJson.addProperty("scopeNamespace", instance.getTypeRef().getNamespace());
return instanceAsJson;
}
private String getShorthand(Instance instance) {
String shorthand = instance.getShorthand();
if (shorthand == null) {
Map<String, Object> values = instance.getValues();
if (values != null && !values.isEmpty())
shorthand = values.values().iterator().next().toString();
}
return shorthand;
}
} |
package com.reprezen.swagedit.core.json.references;
import static com.reprezen.swagedit.core.json.references.JsonReference.PROPERTY;
import java.net.URI;
import org.yaml.snakeyaml.nodes.ScalarNode;
import com.fasterxml.jackson.core.JsonPointer;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Strings;
import com.reprezen.swagedit.core.model.AbstractNode;
import com.reprezen.swagedit.core.model.Model;
import com.reprezen.swagedit.core.utils.URLUtils;
/**
* JSON Reference Factory
*
* This class should be used to instantiate JSONReferences.
*
*/
public class JsonReferenceFactory {
public JsonReference create(AbstractNode node) {
if (node == null) {
return new JsonReference(null, null, false, false, false, node);
}
if (node.isObject() && node.get(JsonReference.PROPERTY) != null) {
node = node.get(JsonReference.PROPERTY);
}
return doCreate((String) node.asValue().getValue(), node);
}
public JsonReference create(JsonNode node) {
if (node == null || node.isMissingNode()) {
return new JsonReference(null, null, false, false, false, node);
}
String text = node.isTextual() ? node.asText() : node.get(PROPERTY).asText();
return doCreate(text, node);
}
public JsonReference create(ScalarNode node) {
if (node == null) {
return new JsonReference(null, null, false, false, false, node);
}
return doCreate(node.getValue(), node);
}
/**
* Returns a simple reference if the value node points to a definition inside the same document.
*
* @param baseURI
* @param value
* @return reference
*/
public JsonReference createSimpleReference(URI baseURI, AbstractNode valueNode) {
if (valueNode.isArray() || valueNode.isObject()) {
return null;
}
final Object value = valueNode.asValue().getValue();
if (!(value instanceof String)) {
return null;
}
String stringValue = (String) value;
if (Strings.emptyToNull(stringValue) == null || stringValue.startsWith("#") || stringValue.contains("/")) {
return null;
}
final Model model = valueNode.getModel();
if (model != null) {
JsonPointer ptr = JsonPointer.compile("/definitions/" + value);
AbstractNode target = model.find(ptr);
if (target != null) {
return new JsonReference.SimpleReference(baseURI, ptr, valueNode);
}
}
return null;
}
public JsonReference doCreate(String value, Object source) {
String notNull = Strings.nullToEmpty(value);
URI uri;
try {
uri = URI.create(notNull);
} catch (NullPointerException | IllegalArgumentException e) {
try {
uri = URI.create(URLUtils.encodeURL(notNull));
} catch (NullPointerException | IllegalArgumentException e2) {
return new JsonReference(null, null, false, false, false, source);
}
}
String fragment = uri.getFragment();
JsonPointer pointer = null;
try {
// Pointer fails to resolve if ends with /
if (fragment != null && fragment.length() > 1 && fragment.endsWith("/")) {
fragment = fragment.substring(0, fragment.length() - 1);
}
pointer = JsonPointer.compile(Strings.emptyToNull(fragment));
} catch (IllegalArgumentException e) {
// let the pointer be null
}
uri = uri.normalize();
boolean absolute = uri.isAbsolute();
boolean local = !absolute && uri.getPath().isEmpty();
// should warn when using curly braces
boolean warnings = notNull.contains("{") || uri.toString().contains("}");
return new JsonReference(uri, pointer, absolute, local, warnings, source);
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ine.telluride.cochlea;
import ch.unizh.ini.caviar.chip.AEChip;
import ch.unizh.ini.caviar.event.EventPacket;
import ch.unizh.ini.caviar.eventprocessing.EventFilter2D;
import ch.unizh.ini.caviar.graphics.FrameAnnotater;
import ch.unizh.ini.caviar.hardwareinterface.HardwareInterfaceException;
import ch.unizh.ini.caviar.util.HexString;
import com.sun.opengl.util.GLUT;
import java.awt.Graphics2D;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.glu.GLU;
import org.ine.telluride.wowwee.RoboQuadCommands;
import org.ine.telluride.wowwee.WowWeeRSHardwareInterface;
/**
* Calculates ITD from binaural cochlea input
*
* @author ahs (Andrew Schwartz, MIT)
*/
public class auditoryReflex extends EventFilter2D implements FrameAnnotater {
private boolean drawOutput=getPrefs().getBoolean("MSO.drawOutput",true);
{setPropertyTooltip("drawOutput", "Enable drawing");}
private RoboQuadCommands rCommands;
private static int SPIKE_UPDATE_INTERVAL = 3000;
private static long COMMAND_UPDATE_INTERVAL = 700;
private static int NUM_CHANS = 32;
private float[] ITDState=null;
private int numITDBins=0;
private int[] ITDBins=null;
private int ITDBinWidth=0;
private int spikeCount=0;
private MSO mso=null;
private int ii, jj, bin, count;
private int cmd, lastCmd=0;
private float direction=0;
private float scale;
private WowWeeRSHardwareInterface hw;
private boolean startupCommandSequenceDone = false;
private int startupCommandCount = 0;
private long time, lastTime=0;
@Override
public String getDescription() {
return "Computes ITD of incoming binaural signal";
}
public auditoryReflex(AEChip chip) {
super(chip);
initFilter();
}
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
if(!isFilterEnabled()) {
return in;
}
if(!checkMSO()){
throw new RuntimeException("Can't find prior ANFSpikeBuffer in filter chain");
}
if(in==null) {
return in;
}
for(Object o : in) {
spikeCount++;
if (spikeCount==SPIKE_UPDATE_INTERVAL) {
determineBehavior();
spikeCount = 0;
}
}
return in;
}
public void determineBehavior() {
time = System.currentTimeMillis();
if (time>lastTime+COMMAND_UPDATE_INTERVAL) {
lastTime = time;
checkHardware();
if(hw!=null) {
if (!startupCommandSequenceDone) { //shut the damn thing up
switch (startupCommandCount) {
case 0:
cmd = rCommands.Toggle_Sensors;
break;
case 1:
case 2:
case 3:
cmd = rCommands.Volume_Down;
break;
default:
startupCommandSequenceDone = true;
System.out.println("Done startup command sequence.");
/*
cmd = rCommands.Toggle_Activity_Level_3;
cmd = rCommands.Toggle_Awareness_3;
cmd = rCommands.Toggle_Aggression_3;
*/
}
startupCommandCount++;
hw.sendWowWeeCmd((short)cmd);
System.out.println("Send command - "+ HexString.toString((short) cmd));
} else { // normal behavior
count=mso.getNumBins();
if (count != numITDBins) {
System.out.println("Bins changed! Allocating new memory");
allocateITDState();
}
direction = computeDirection();
if (direction < 30)
cmd = rCommands.Rotate_Counter_Clockwise;
else if (direction > 30)
cmd = rCommands.Rotate_Clockwise;
else
cmd = rCommands.Stop;
if (cmd!=lastCmd) {
lastCmd = cmd;
hw.sendWowWeeCmd((short)cmd);
System.out.println("Send command - "+ HexString.toString((short) cmd));
}
}
}
}
return;
}
@Override
public Object getFilterState() {
return null;
}
@Override
public void resetFilter() {
}
@Override
public void initFilter() {
}
private boolean checkMSO() {
if(mso==null) {
mso=(MSO) chip.getFilterChain().findFilter(MSO.class);
return mso!=null;
} else {
return true;
}
}
void checkHardware() {
if(hw==null) {
hw=new WowWeeRSHardwareInterface();
}
try {
if(!hw.isOpen()) {
hw.open();
}
} catch(HardwareInterfaceException e) {
log.warning(e.toString());
}
}
private void allocateITDState() {
System.out.println("Allocate ITD state");
numITDBins = mso.getNumBins();
ITDState = new float[numITDBins];
}
private float computeDirection() {
ITDState = mso.getITDState();
ITDBins = mso.getITDBins();
numITDBins = mso.getNumBins();
ITDBinWidth = mso.getBinWidth();
scale = 0;
direction = 0;
for (bin=0;bin<numITDBins;bin++) {
direction += ITDBins[bin]*ITDState[bin];
scale += ITDState[bin];
}
direction = direction/scale;
return direction;
}
public void annotate(float[][][] frame) {
}
public void annotate(Graphics2D g) {
}
private GLU glu=new GLU();
public void annotate(GLAutoDrawable drawable) {
if(!isFilterEnabled() || !drawOutput) {
return;
// if(isRelaxed) return;
}
GL gl=drawable.getGL();
gl.glPushMatrix();
//draw ITD histogram
gl.glBegin(gl.GL_LINES);
gl.glColor3d(0.8, 0, 0);
gl.glVertex3f(direction/(float)ITDBinWidth+(float)(numITDBins/2),0,0);
gl.glVertex3f(direction/(float)ITDBinWidth+(float)(numITDBins/2),1,0);
gl.glColor3d(0, 0, .6);
gl.glVertex3i(0,0,0);
gl.glVertex3i(0,1,0);
gl.glColor3d(0, 0, .6);
gl.glVertex3i(numITDBins,0,0);
gl.glVertex3i(numITDBins,1,0);
gl.glEnd();
gl.glPopMatrix();
}
public boolean getDrawOutput() {
return drawOutput;
}
public void setDrawOutput(boolean drawOutput) {
this.drawOutput = drawOutput;
getPrefs().putBoolean("MSO.drawOutput",drawOutput);
}
} |
// This source code is available under agreement available at
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
package org.talend.components.salesforce;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import org.apache.avro.Schema;
import org.apache.avro.generic.IndexedRecord;
import org.junit.Ignore;
import org.junit.Test;
import org.talend.components.api.component.ComponentDefinition;
import org.talend.components.api.container.DefaultComponentRuntimeContainerImpl;
import org.talend.components.api.container.RuntimeContainer;
import org.talend.components.api.properties.ComponentProperties;
import org.talend.components.api.properties.ComponentReferenceProperties;
import org.talend.components.api.test.ComponentTestUtils;
import org.talend.components.api.wizard.ComponentWizard;
import org.talend.components.api.wizard.ComponentWizardDefinition;
import org.talend.components.api.wizard.WizardImageType;
import org.talend.components.common.oauth.OauthProperties;
import org.talend.components.salesforce.runtime.SalesforceSourceOrSink;
import org.talend.components.salesforce.tsalesforceconnection.TSalesforceConnectionDefinition;
import org.talend.components.salesforce.tsalesforceinput.TSalesforceInputDefinition;
import org.talend.components.salesforce.tsalesforceinput.TSalesforceInputProperties;
import org.talend.components.salesforce.tsalesforceoutput.TSalesforceOutputDefinition;
import org.talend.components.salesforce.tsalesforceoutput.TSalesforceOutputProperties;
import org.talend.daikon.NamedThing;
import org.talend.daikon.properties.PresentationItem;
import org.talend.daikon.properties.Properties;
import org.talend.daikon.properties.Property;
import org.talend.daikon.properties.ValidationResult;
import org.talend.daikon.properties.presentation.Form;
import org.talend.daikon.properties.service.PropertiesServiceTest;
import org.talend.daikon.properties.service.Repository;
import org.talend.daikon.properties.test.PropertiesTestUtils;
public class SalesforceComponentTestIT extends SalesforceTestBase {
public SalesforceComponentTestIT() {
super();
}
@Override
protected ComponentProperties checkAndAfter(Form form, String propName, ComponentProperties props) throws Throwable {
assertTrue(form.getWidget(propName).isCallAfter());
return getComponentService().afterProperty(propName, props);
}
@Test
public void testGetProps() {
ComponentProperties props = new TSalesforceConnectionDefinition().createProperties();
Form f = props.getForm(Form.MAIN);
ComponentTestUtils.checkSerialize(props, errorCollector);
System.out.println(f);
System.out.println(props);
assertEquals(Form.MAIN, f.getName());
}
@Test
public void testAfterLoginType() throws Throwable {
ComponentProperties props;
props = new TSalesforceConnectionDefinition().createProperties();
ComponentTestUtils.checkSerialize(props, errorCollector);
Property loginType = (Property) props.getProperty("loginType");
System.out.println(loginType.getPossibleValues());
assertEquals("Basic", loginType.getPossibleValues().get(0).toString());
assertEquals("OAuth", loginType.getPossibleValues().get(1).toString());
assertEquals(SalesforceConnectionProperties.LOGIN_BASIC, loginType.getValue());
Form mainForm = props.getForm(Form.MAIN);
assertEquals("Salesforce Connection Settings", mainForm.getTitle());
assertTrue(mainForm.getWidget(SalesforceUserPasswordProperties.class).isVisible());
assertFalse(mainForm.getWidget(OauthProperties.class).isVisible());
loginType.setValue(SalesforceConnectionProperties.LOGIN_OAUTH);
props = checkAndAfter(mainForm, "loginType", props);
mainForm = props.getForm(Form.MAIN);
assertTrue(mainForm.isRefreshUI());
assertFalse(mainForm.getWidget(SalesforceUserPasswordProperties.class).isVisible());
assertTrue(mainForm.getWidget(OauthProperties.class).isVisible());
}
@Test
public void testInputProps() throws Throwable {
TSalesforceInputProperties props = (TSalesforceInputProperties) new TSalesforceInputDefinition().createProperties();
assertEquals(2, props.queryMode.getPossibleValues().size());
Property returns = (Property) props.getProperty(ComponentProperties.RETURNS);
assertEquals("NB_LINE", returns.getChildren().get(0).getName());
}
static class RepoProps {
Properties props;
String name;
String repoLocation;
Schema schema;
String schemaPropertyName;
RepoProps(Properties props, String name, String repoLocation, String schemaPropertyName) {
this.props = props;
this.name = name;
this.repoLocation = repoLocation;
this.schemaPropertyName = schemaPropertyName;
if (schemaPropertyName != null) {
this.schema = new Schema.Parser().parse(props.getValuedProperty(schemaPropertyName).getStringValue());
}
}
@Override
public String toString() {
return "RepoProps: " + repoLocation + "/" + name + " props: " + props;
}
}
class TestRepository implements Repository {
private int locationNum;
public String componentIdToCheck;
public ComponentProperties properties;
public List<RepoProps> repoProps;
TestRepository(List<RepoProps> repoProps) {
this.repoProps = repoProps;
}
@Override
public String storeProperties(Properties properties, String name, String repositoryLocation, String schemaPropertyName) {
RepoProps rp = new RepoProps(properties, name, repositoryLocation, schemaPropertyName);
repoProps.add(rp);
System.out.println(rp);
return repositoryLocation + ++locationNum;
}
}
class TestRuntimeContainer extends DefaultComponentRuntimeContainerImpl {
}
@Test
public void testFamily() {
ComponentDefinition cd = getComponentService().getComponentDefinition("tSalesforceConnectionNew");
assertEquals(2, cd.getFamilies().length);
assertEquals("Business/Salesforce", cd.getFamilies()[0]);
assertEquals("Cloud/Salesforce", cd.getFamilies()[1]);
}
@Test
public void testWizard() throws Throwable {
final List<RepoProps> repoProps = new ArrayList<>();
Repository repo = new TestRepository(repoProps);
getComponentService().setRepository(repo);
Set<ComponentWizardDefinition> wizards = getComponentService().getTopLevelComponentWizards();
int count = 0;
ComponentWizardDefinition wizardDef = null;
for (ComponentWizardDefinition wizardDefinition : wizards) {
if (wizardDefinition instanceof SalesforceConnectionWizardDefinition) {
wizardDef = wizardDefinition;
count++;
}
}
assertEquals(1, count);
assertEquals("Create SalesforceNew Connection", wizardDef.getMenuItemName());
ComponentWizard wiz = getComponentService().getComponentWizard(SalesforceConnectionWizardDefinition.COMPONENT_WIZARD_NAME,
"nodeSalesforce");
assertNotNull(wiz);
assertEquals("nodeSalesforce", wiz.getRepositoryLocation());
SalesforceConnectionWizard swiz = (SalesforceConnectionWizard) wiz;
List<Form> forms = wiz.getForms();
Form connFormWizard = forms.get(0);
assertEquals("Wizard", connFormWizard.getName());
assertFalse(connFormWizard.isAllowBack());
assertFalse(connFormWizard.isAllowForward());
assertFalse(connFormWizard.isAllowFinish());
// Main from SalesforceModuleListProperties
assertEquals("Main", forms.get(1).getName());
assertEquals("Salesforce Connection Settings", connFormWizard.getTitle());
assertEquals("Complete these fields in order to connect to your Salesforce account.", connFormWizard.getSubtitle());
SalesforceConnectionProperties connProps = (SalesforceConnectionProperties) connFormWizard.getProperties();
Form af = connProps.getForm(Form.ADVANCED);
assertTrue(
((PresentationItem) connFormWizard.getWidget("advanced").getContent()).getFormtoShow() + " should be == to " + af,
((PresentationItem) connFormWizard.getWidget("advanced").getContent()).getFormtoShow() == af);
Object image = getComponentService().getWizardPngImage(SalesforceConnectionWizardDefinition.COMPONENT_WIZARD_NAME,
WizardImageType.TREE_ICON_16X16);
assertNotNull(image);
image = getComponentService().getWizardPngImage(SalesforceConnectionWizardDefinition.COMPONENT_WIZARD_NAME,
WizardImageType.WIZARD_BANNER_75X66);
assertNotNull(image);
// Check the non-top-level wizard
// check password i18n
assertEquals("Name", connProps.getProperty("name").getDisplayName());
connProps.name.setValue("connName");
setupProps(connProps, !ADD_QUOTES);
Form userPassword = (Form) connFormWizard.getWidget("userPassword").getContent();
Property passwordSe = (Property) userPassword.getWidget("password").getContent();
assertEquals("Password", passwordSe.getDisplayName());
// check name i18n
NamedThing nameProp = connFormWizard.getWidget("name").getContent(); //$NON-NLS-1$
assertEquals("Name", nameProp.getDisplayName());
connProps = (SalesforceConnectionProperties) PropertiesServiceTest.checkAndValidate(getComponentService(), connFormWizard,
"testConnection", connProps);
assertTrue(connFormWizard.isAllowForward());
Form modForm = forms.get(1);
SalesforceModuleListProperties mlProps = (SalesforceModuleListProperties) modForm.getProperties();
assertFalse(modForm.isCallAfterFormBack());
assertFalse(modForm.isCallAfterFormNext());
assertTrue(modForm.isCallAfterFormFinish());
assertTrue(modForm.isCallBeforeFormPresent());
assertFalse(modForm.isAllowBack());
assertFalse(modForm.isAllowForward());
assertFalse(modForm.isAllowFinish());
mlProps = (SalesforceModuleListProperties) getComponentService().beforeFormPresent(modForm.getName(), mlProps);
assertTrue(modForm.isAllowBack());
assertFalse(modForm.isAllowForward());
assertTrue(modForm.isAllowFinish());
System.out.println(mlProps.moduleName.getValue());
@SuppressWarnings("unchecked")
List<NamedThing> all = (List<NamedThing>) mlProps.moduleName.getValue();
assertNull(all);
// TCOMP-9 Change the module list to use getPossibleValues() for SalesforceModuleListProperties
List<NamedThing> possibleValues = (List<NamedThing>) mlProps.moduleName.getPossibleValues();
assertTrue(possibleValues.size() > 50);
List<NamedThing> selected = new ArrayList<>();
selected.add(possibleValues.get(0));
selected.add(possibleValues.get(2));
selected.add(possibleValues.get(3));
mlProps.moduleName.setValue(selected);
getComponentService().afterFormFinish(modForm.getName(), mlProps);
System.out.println(repoProps);
assertEquals(4, repoProps.size());
int i = 0;
for (RepoProps rp : repoProps) {
if (i == 0) {
assertEquals("connName", rp.name);
SalesforceConnectionProperties storedConnProps = (SalesforceConnectionProperties) rp.props;
assertEquals(userId, storedConnProps.userPassword.userId.getValue());
assertEquals(password, storedConnProps.userPassword.password.getValue());
} else {
SalesforceModuleProperties storedModule = (SalesforceModuleProperties) rp.props;
assertEquals(selected.get(i - 1).getName(), storedModule.moduleName.getValue());
assertTrue(rp.schema.getFields().size() > 10);
assertThat(storedModule.schema.schema.getStringValue(), is(rp.schema.toString()));
}
i++;
}
}
@Test
public void testModuleWizard() throws Throwable {
ComponentWizard wiz = getComponentService().getComponentWizard(SalesforceConnectionWizardDefinition.COMPONENT_WIZARD_NAME,
"nodeSalesforce");
List<Form> forms = wiz.getForms();
Form connFormWizard = forms.get(0);
SalesforceConnectionProperties connProps = (SalesforceConnectionProperties) connFormWizard.getProperties();
ComponentWizard[] subWizards = getComponentService().getComponentWizardsForProperties(connProps, "location")
.toArray(new ComponentWizard[3]);
Arrays.sort(subWizards, new Comparator<ComponentWizard>() {
@Override
public int compare(ComponentWizard o1, ComponentWizard o2) {
return o1.getDefinition().getName().compareTo(o2.getDefinition().getName());
}
});
assertEquals(3, subWizards.length);
// Edit connection wizard - we copy the connection properties, as we present the UI, so we use the
assertFalse(connProps == subWizards[1].getForms().get(0).getProperties());
// Add module wizard - we refer to the existing connection properties as we don't present the UI
// for them.
assertTrue(connProps == ((SalesforceModuleListProperties) subWizards[2].getForms().get(0).getProperties())
.getConnectionProps());
assertFalse(subWizards[1].getDefinition().isTopLevel());
assertEquals("Edit SalesforceNew Connection", subWizards[1].getDefinition().getMenuItemName());
assertTrue(subWizards[0].getDefinition().isTopLevel());
assertEquals("Create SalesforceNew Connection", subWizards[0].getDefinition().getMenuItemName());
assertFalse(subWizards[2].getDefinition().isTopLevel());
assertEquals("Add SalesforceNew Modules", subWizards[2].getDefinition().getMenuItemName());
}
@Test
public void testLogin() throws Throwable {
SalesforceConnectionProperties props = setupProps(null, !ADD_QUOTES);
Form f = props.getForm(SalesforceConnectionProperties.FORM_WIZARD);
props = (SalesforceConnectionProperties) PropertiesServiceTest.checkAndValidate(getComponentService(), f,
"testConnection", props);
System.out.println(props.getValidationResult());
assertEquals(ValidationResult.Result.OK, props.getValidationResult().getStatus());
}
@Test
public void testLoginWithQuotes() throws Throwable {
SalesforceConnectionProperties props = setupProps(null, ADD_QUOTES);
Form f = props.getForm(SalesforceConnectionProperties.FORM_WIZARD);
props = (SalesforceConnectionProperties) PropertiesServiceTest.checkAndValidate(getComponentService(), f,
"testConnection", props);
System.out.println(props.getValidationResult());
assertEquals(ValidationResult.Result.OK, props.getValidationResult().getStatus());
}
@Test
public void testLoginFail() throws Throwable {
SalesforceConnectionProperties props = setupProps(null, !ADD_QUOTES);
props.userPassword.userId.setValue("blah");
Form f = props.getForm(SalesforceConnectionProperties.FORM_WIZARD);
props = (SalesforceConnectionProperties) PropertiesServiceTest.checkAndValidate(getComponentService(), f,
"testConnection", props);
System.out.println(props.getValidationResult());
assertEquals(ValidationResult.Result.ERROR, props.getValidationResult().getStatus());
}
@Test
public void testBulkLogin() throws Throwable {
SalesforceConnectionProperties props = setupProps(null, !ADD_QUOTES);
props.bulkConnection.setValue(true);
Form f = props.getForm(SalesforceConnectionProperties.FORM_WIZARD);
props = (SalesforceConnectionProperties) PropertiesServiceTest.checkAndValidate(getComponentService(), f,
"testConnection", props);
assertEquals(ValidationResult.Result.OK, props.getValidationResult().getStatus());
System.out.println(props.getValidationResult());
}
@Test
public void testBulkLoginWithQuotes() throws Throwable {
SalesforceConnectionProperties props = setupProps(null, ADD_QUOTES);
props.bulkConnection.setValue(true);
Form f = props.getForm(SalesforceConnectionProperties.FORM_WIZARD);
props = (SalesforceConnectionProperties) PropertiesServiceTest.checkAndValidate(getComponentService(), f,
"testConnection", props);
assertEquals(ValidationResult.Result.OK, props.getValidationResult().getStatus());
System.out.println(props.getValidationResult());
}
private SalesforceConnectionProperties setupOAuthProps(SalesforceConnectionProperties props) throws Throwable {
if (props == null) {
props = (SalesforceConnectionProperties) getComponentService()
.getComponentProperties(TSalesforceConnectionDefinition.COMPONENT_NAME);
}
props.loginType.setValue(SalesforceConnectionProperties.LOGIN_OAUTH);
Form mainForm = props.getForm(Form.MAIN);
props = (SalesforceConnectionProperties) checkAndAfter(mainForm, "loginType", props);
props.oauth.clientId.setValue("3MVG9Y6d_Btp4xp6ParHznfCCUh0d9fU3LYcvd_hCXz3G3Owp4KvaDhNuEOrXJTBd09JMoPdZeDtNYxXZM4X2");
props.oauth.clientSecret.setValue("3545101463828280342");
props.oauth.callbackHost.setValue("localhost");
props.oauth.callbackPort.setValue(8115);
// props.oauth.tokenFile.setValue();
return props;
}
@Ignore("oauth need manual operation")
@Test
public void testOAuthLogin() throws Throwable {
SalesforceConnectionProperties props = setupOAuthProps(null);
Form f = props.getForm(Form.MAIN);
props = (SalesforceConnectionProperties) PropertiesServiceTest.checkAndValidate(getComponentService(), f,
"testConnection", props);
assertEquals(ValidationResult.Result.OK, props.getValidationResult().getStatus());
System.out.println(props.getValidationResult());
}
@Ignore("oauth need manual operation")
@Test
public void testOAuthBulkLogin() throws Throwable {
SalesforceConnectionProperties props = setupOAuthProps(null);
props.bulkConnection.setValue(true);
Form f = props.getForm(Form.MAIN);
props = (SalesforceConnectionProperties) PropertiesServiceTest.checkAndValidate(getComponentService(), f,
"testConnection", props);
assertEquals(ValidationResult.Result.OK, props.getValidationResult().getStatus());
System.out.println(props.getValidationResult());
}
@Test
public void testModuleNames() throws Throwable {
TSalesforceInputProperties props = (TSalesforceInputProperties) getComponentService()
.getComponentProperties(TSalesforceInputDefinition.COMPONENT_NAME);
setupProps(props.connection, !ADD_QUOTES);
ComponentTestUtils.checkSerialize(props, errorCollector);
assertEquals(2, props.getForms().size());
Form f = props.module.getForm(Form.REFERENCE);
assertTrue(f.getWidget("moduleName").isCallBeforeActivate());
// The Form is bound to a Properties object that created it. The Forms might not always be associated with the
// properties object
// they came from.
ComponentProperties moduleProps = (ComponentProperties) f.getProperties();
moduleProps = (ComponentProperties) PropertiesServiceTest.checkAndBeforeActivate(getComponentService(), f, "moduleName",
moduleProps);
Property prop = (Property) f.getWidget("moduleName").getContent();
assertTrue(prop.getPossibleValues().size() > 100);
System.out.println(prop.getPossibleValues());
System.out.println(moduleProps.getValidationResult());
}
@Test
public void testSchema() throws Throwable {
TSalesforceInputProperties props = (TSalesforceInputProperties) getComponentService()
.getComponentProperties(TSalesforceInputDefinition.COMPONENT_NAME);
setupProps(props.connection, !ADD_QUOTES);
Form f = props.module.getForm(Form.REFERENCE);
SalesforceModuleProperties moduleProps = (SalesforceModuleProperties) f.getProperties();
moduleProps = (SalesforceModuleProperties) PropertiesServiceTest.checkAndBeforeActivate(getComponentService(), f,
"moduleName", moduleProps);
moduleProps.moduleName.setValue("Account");
moduleProps = (SalesforceModuleProperties) checkAndAfter(f, "moduleName", moduleProps);
Schema schema = new Schema.Parser().parse(moduleProps.schema.schema.getStringValue());
System.out.println(schema);
for (Schema.Field child : schema.getFields()) {
System.out.println(child.name());
}
assertEquals("Id", schema.getFields().get(0).name());
assertTrue(schema.getFields().size() > 50);
}
@Test
public void testOutputActionType() throws Throwable {
ComponentDefinition definition = getComponentService().getComponentDefinition(TSalesforceOutputDefinition.COMPONENT_NAME);
TSalesforceOutputProperties outputProps = (TSalesforceOutputProperties) getComponentService()
.getComponentProperties(TSalesforceOutputDefinition.COMPONENT_NAME);
setupProps(outputProps.connection, !ADD_QUOTES);
outputProps.outputAction.setValue(TSalesforceOutputProperties.ACTION_DELETE);
setupModule(outputProps.module, "Account");
ComponentTestUtils.checkSerialize(outputProps, errorCollector);
List<IndexedRecord> rows = new ArrayList<>();
try {
writeRows(null, outputProps, rows);
} catch (Exception ex) {
if (ex instanceof ClassCastException) {
System.out.println("Exception: " + ex.getMessage());
fail("Get error before delete!");
}
}
}
@Test
public void testInputConnectionRef() throws Throwable {
ComponentDefinition definition = getComponentService().getComponentDefinition(TSalesforceInputDefinition.COMPONENT_NAME);
TSalesforceInputProperties props = (TSalesforceInputProperties) getComponentService()
.getComponentProperties(TSalesforceInputDefinition.COMPONENT_NAME);
setupProps(props.connection, !ADD_QUOTES);
SalesforceSourceOrSink salesforceSourceOrSink = new SalesforceSourceOrSink();
salesforceSourceOrSink.initialize(null, props);
assertEquals(ValidationResult.Result.OK, salesforceSourceOrSink.validate(null).getStatus());
// Referenced properties simulating salesforce connect component
SalesforceConnectionProperties cProps = (SalesforceConnectionProperties) getComponentService()
.getComponentProperties(TSalesforceConnectionDefinition.COMPONENT_NAME);
setupProps(cProps, !ADD_QUOTES);
cProps.userPassword.password.setValue("xxx");
String compId = "comp1";
// Use the connection props of the salesforce connect component
props.connection.referencedComponent.referenceType
.setValue(ComponentReferenceProperties.ReferenceType.COMPONENT_INSTANCE);
props.connection.referencedComponent.componentInstanceId.setValue(compId);
props.connection.referencedComponent.componentProperties = cProps;
checkAndAfter(props.connection.getForm(Form.REFERENCE), "referencedComponent", props.connection);
salesforceSourceOrSink = new SalesforceSourceOrSink();
salesforceSourceOrSink.initialize(null, props);
salesforceSourceOrSink.validate(null);
assertEquals(ValidationResult.Result.ERROR, salesforceSourceOrSink.validate(null).getStatus());
// Back to using the connection props of the salesforce input component
props.connection.referencedComponent.referenceType.setValue(ComponentReferenceProperties.ReferenceType.THIS_COMPONENT);
props.connection.referencedComponent.componentInstanceId.setValue(null);
props.connection.referencedComponent.componentProperties = null;
salesforceSourceOrSink = new SalesforceSourceOrSink();
salesforceSourceOrSink.initialize(null, props);
salesforceSourceOrSink.validate(null);
assertEquals(ValidationResult.Result.OK, salesforceSourceOrSink.validate(null).getStatus());
}
@Test
public void testUseExistingConnection() throws Throwable {
SalesforceConnectionProperties connProps = (SalesforceConnectionProperties) getComponentService()
.getComponentProperties(TSalesforceConnectionDefinition.COMPONENT_NAME);
setupProps(connProps, !ADD_QUOTES);
final String currentComponentName = TSalesforceConnectionDefinition.COMPONENT_NAME + "_1";
RuntimeContainer connContainer = new DefaultComponentRuntimeContainerImpl() {
@Override
public String getCurrentComponentId() {
return currentComponentName;
}
};
SalesforceSourceOrSink salesforceSourceOrSink = new SalesforceSourceOrSink();
salesforceSourceOrSink.initialize(connContainer, connProps);
assertEquals(ValidationResult.Result.OK, salesforceSourceOrSink.validate(connContainer).getStatus());
// Input component get connection from the tSalesforceConnection
ComponentDefinition inputDefinition = getComponentService()
.getComponentDefinition(TSalesforceInputDefinition.COMPONENT_NAME);
TSalesforceInputProperties inProps = (TSalesforceInputProperties) getComponentService()
.getComponentProperties(TSalesforceInputDefinition.COMPONENT_NAME);
inProps.connection.referencedComponent.componentInstanceId.setValue(currentComponentName);
SalesforceSourceOrSink salesforceInputSourceOrSink = new SalesforceSourceOrSink();
salesforceInputSourceOrSink.initialize(connContainer, inProps);
assertEquals(ValidationResult.Result.OK, salesforceInputSourceOrSink.validate(connContainer).getStatus());
}
@Test
public void generateJavaNestedCompPropClassNames() {
Set<ComponentDefinition> allComponents = getComponentService().getAllComponents();
for (ComponentDefinition cd : allComponents) {
ComponentProperties props = cd.createProperties();
String javaCode = PropertiesTestUtils.generatedNestedComponentCompatibilitiesJavaCode(props);
System.out.println("Nested Props for (" + cd.getClass().getSimpleName() + ".java:1)" + javaCode);
}
}
@Test
public void testAlli18n() {
ComponentTestUtils.testAlli18n(getComponentService(), errorCollector);
}
@Test
public void testAllImages() {
ComponentTestUtils.testAllImages(getComponentService());
}
@Test
public void testAllRuntime() {
ComponentTestUtils.testAllRuntimeAvaialble(getComponentService());
}
} |
package org.owasp.esapi.reference;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.EncodingException;
import org.owasp.esapi.Logger;
import org.owasp.esapi.IntrusionException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.text.Normalizer;
public class DefaultEncoder implements org.owasp.esapi.Encoder {
/** Encoding types */
public static final int NO_ENCODING = 0;
public static final int URL_ENCODING = 1;
public static final int PERCENT_ENCODING = 2;
public static final int ENTITY_ENCODING = 3;
/** The base64 encoder. */
private static final BASE64Encoder base64Encoder = new BASE64Encoder();
/** The base64 decoder. */
private static final BASE64Decoder base64Decoder = new BASE64Decoder();
/** The IMMUNE HTML. */
private final static char[] IMMUNE_HTML = { ',', '.', '-', '_', ' ' };
/** The IMMUNE HTMLATTR. */
private final static char[] IMMUNE_HTMLATTR = { ',', '.', '-', '_' };
/** The IMMUNE JAVASCRIPT. */
private final static char[] IMMUNE_JAVASCRIPT = { ',', '.', '-', '_', ' ' };
/** The IMMUNE VBSCRIPT. */
private final static char[] IMMUNE_VBSCRIPT = { ',', '.', '-', '_', ' ' };
/** The IMMUNE XML. */
private final static char[] IMMUNE_XML = { ',', '.', '-', '_', ' ' };
/** The IMMUNE XMLATTR. */
private final static char[] IMMUNE_XMLATTR = { ',', '.', '-', '_' };
/** The IMMUNE XPATH. */
private final static char[] IMMUNE_XPATH = { ',', '.', '-', '_', ' ' };
/** The logger. */
private static final Logger logger = ESAPI.getLogger("Encoder");
/** The Constant CHAR_LOWERS. */
public final static char[] CHAR_LOWERS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
/** The Constant CHAR_UPPERS. */
public final static char[] CHAR_UPPERS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
/** The Constant CHAR_DIGITS. */
public final static char[] CHAR_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
/** The Constant CHAR_SPECIALS. */
public final static char[] CHAR_SPECIALS = { '.', '-', '_', '!', '@', '$', '^', '*', '=', '~', '|', '+', '?' };
/** The Constant CHAR_LETTERS. */
public final static char[] CHAR_LETTERS = DefaultRandomizer.union(CHAR_LOWERS, CHAR_UPPERS);
/** The Constant CHAR_ALPHANUMERICS. */
public final static char[] CHAR_ALPHANUMERICS = DefaultRandomizer.union(CHAR_LETTERS, CHAR_DIGITS);
// FIXME: ENHANCE make all character sets configurable
/**
* Password character set, is alphanumerics (without l, i, I, o, O, and 0)
* selected specials like + (bad for URL encoding, | is like i and 1,
* etc...)
*/
final static char[] CHAR_PASSWORD_LOWERS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
final static char[] CHAR_PASSWORD_UPPERS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
final static char[] CHAR_PASSWORD_DIGITS = { '2', '3', '4', '5', '6', '7', '8', '9' };
final static char[] CHAR_PASSWORD_SPECIALS = { '_', '.', '!', '@', '$', '*', '=', '-', '?' };
public final static char[] CHAR_PASSWORD_LETTERS = DefaultRandomizer.union( CHAR_PASSWORD_LOWERS, CHAR_PASSWORD_UPPERS );
private static HashMap characterToEntityMap;
private static HashMap entityToCharacterMap;
public DefaultEncoder() {
Arrays.sort( DefaultEncoder.IMMUNE_HTML );
Arrays.sort( DefaultEncoder.IMMUNE_HTMLATTR );
Arrays.sort( DefaultEncoder.IMMUNE_JAVASCRIPT );
Arrays.sort( DefaultEncoder.IMMUNE_VBSCRIPT );
Arrays.sort( DefaultEncoder.IMMUNE_XML );
Arrays.sort( DefaultEncoder.IMMUNE_XMLATTR );
Arrays.sort( DefaultEncoder.IMMUNE_XPATH );
Arrays.sort( DefaultEncoder.CHAR_LOWERS );
Arrays.sort( DefaultEncoder.CHAR_UPPERS );
Arrays.sort( DefaultEncoder.CHAR_DIGITS );
Arrays.sort( DefaultEncoder.CHAR_SPECIALS );
Arrays.sort( DefaultEncoder.CHAR_LETTERS );
Arrays.sort( DefaultEncoder.CHAR_ALPHANUMERICS );
Arrays.sort( DefaultEncoder.CHAR_PASSWORD_LOWERS );
Arrays.sort( DefaultEncoder.CHAR_PASSWORD_UPPERS );
Arrays.sort( DefaultEncoder.CHAR_PASSWORD_DIGITS );
Arrays.sort( DefaultEncoder.CHAR_PASSWORD_SPECIALS );
Arrays.sort( DefaultEncoder.CHAR_PASSWORD_LETTERS );
initializeMaps();
}
/**
* Simplifies percent-encoded and entity-encoded characters to their
* simplest form so that they can be properly validated. Attackers
* frequently use encoding schemes to disguise their attacks and bypass
* validation routines.
*
* Handling multiple encoding schemes simultaneously is difficult, and
* requires some special consideration. In particular, the problem of
* double-encoding is difficult for parsers, and combining several encoding
* schemes in double-encoding makes it even harder. Consider decoding
*
* <PRE>
* &lt;
* </PRE>
*
* or
*
* <PRE>
* %26lt;
* </PRE>
*
* or
*
* <PRE>
* &lt;
* </PRE>.
*
* This implementation disallows ALL double-encoded characters and throws an
* IntrusionException when they are detected. Also, named entities that are
* not known are simply removed.
*
* Note that most data from the browser is likely to be encoded with URL
* encoding (RFC 3986). The web server will decode the URL and form data
* once, so most encoded data received in the application must have been
* double-encoded by the attacker. However, some HTTP inputs are not decoded
* by the browser, so this routine allows a single level of decoding.
*
* @throws IntrusionException
* @see org.owasp.esapi.Validator#canonicalize(java.lang.String)
*/
public String canonicalize(String input) {
StringBuffer sb = new StringBuffer();
EncodedStringReader reader = new EncodedStringReader(input);
while (reader.hasNext()) {
EncodedCharacter c = reader.getNextCharacter();
if (c != null) {
sb.append(c.getUnencoded());
}
}
return sb.toString();
}
/**
* Normalizes special characters down to ASCII using the Normalizer built
* into Java. Note that this method may introduce security issues if
* characters are normalized into special characters that have meaning
* to the destination of the data.
*
* @see org.owasp.esapi.Validator#normalize(java.lang.String)
*/
public String normalize(String input) {
// Split any special characters into two parts, the base character and
// the modifier
String separated = Normalizer.normalize(input, Normalizer.DECOMP, 0); // Java 1.4
// String separated = Normalizer.normalize(input, Form.NFD); // Java 1.6
// remove any character that is not ASCII
return separated.replaceAll("[^\\p{ASCII}]", "");
}
/**
* Checks if the character is contained in the provided array of characters.
*
* @param array
* the array
* @param element
* the element
* @return true, if is contained
*/
private boolean isContained(char[] array, char element) {
for (int i = 0; i < array.length; i++) {
if (element == array[i])
return true;
}
return false;
// FIXME: ENHANCE Performance enhancement here but character arrays must
// be sorted, which they're currently not.
// return( Arrays.binarySearch(array, element) >= 0 );
}
/**
* HTML Entity encode utility method. To avoid double-encoding, this method
* logs a warning if HTML entity encoded characters are passed in as input.
* Double-encoded characters in the input cause an exception to be thrown.
*
* @param input
* the input
* @param immune
* the immune
* @param base
* the base
* @return the string
*/
private String entityEncode(String input, char[] base, char[] immune) {
// FIXME: Enhance - this may over-encode international data unnecessarily if charset is set properly.
StringBuffer sb = new StringBuffer();
EncodedStringReader reader = new EncodedStringReader(input);
while (reader.hasNext()) {
EncodedCharacter c = reader.getNextCharacter();
if (c != null) {
if (isContained(base, c.getUnencoded()) || isContained(immune, c.getUnencoded())) {
sb.append(c.getUnencoded());
} else {
sb.append(c.getEncoded(ENTITY_ENCODING));
}
}
}
return sb.toString();
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#encodeForHTML(java.lang.String)
*/
public String encodeForHTML(String input) {
// FIXME: ENHANCE - should this just strip out nonprintables? Why send
//  to the browser?
// card
// FIXME: AAA - disallow everything below 20, except CR LF TAB
// See the XML specification - see http://www.w3.org/TR/REC-xml/#charsets
// The question is how to proceed - strip or throw an exception?
String encoded = entityEncode(input, DefaultEncoder.CHAR_ALPHANUMERICS, IMMUNE_HTML);
encoded = encoded.replaceAll("\r", "<BR>");
encoded = encoded.replaceAll("\n", "<BR>");
return encoded;
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#encodeForHTMLAttribute(java.lang.String)
*/
public String encodeForHTMLAttribute(String input) {
return entityEncode(input, DefaultEncoder.CHAR_ALPHANUMERICS, IMMUNE_HTMLATTR);
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#encodeForJavaScript(java.lang.String)
*/
public String encodeForJavascript(String input) {
return entityEncode(input, DefaultEncoder.CHAR_ALPHANUMERICS, DefaultEncoder.IMMUNE_JAVASCRIPT);
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#encodeForVisualBasicScript(java.lang.String)
*/
public String encodeForVBScript(String input) {
return entityEncode(input, DefaultEncoder.CHAR_ALPHANUMERICS, IMMUNE_VBSCRIPT);
}
public String encodeForSQL(String input) {
String canonical = canonicalize(input);
return canonical.replaceAll("'", "''");
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#encodeForLDAP(java.lang.String)
*/
public String encodeForLDAP(String input) {
String canonical = canonicalize(input);
// FIXME: ENHANCE this is a negative list -- make positive?
StringBuffer sb = new StringBuffer();
for (int i = 0; i < canonical.length(); i++) {
char c = canonical.charAt(i);
switch (c) {
case '\\':
sb.append("\\5c");
break;
case '*':
sb.append("\\2a");
break;
case '(':
sb.append("\\28");
break;
case ')':
sb.append("\\29");
break;
case '\u0000':
sb.append("\\00");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#encodeForDN(java.lang.String)
*/
public String encodeForDN(String input) {
String canonical = canonicalize(input);
StringBuffer sb = new StringBuffer();
if ((canonical.length() > 0) && ((canonical.charAt(0) == ' ') || (canonical.charAt(0) == '
sb.append('\\'); // add the leading backslash if needed
}
for (int i = 0; i < canonical.length(); i++) {
char c = canonical.charAt(i);
switch (c) {
case '\\':
sb.append("\\\\");
break;
case ',':
sb.append("\\,");
break;
case '+':
sb.append("\\+");
break;
case '"':
sb.append("\\\"");
break;
case '<':
sb.append("\\<");
break;
case '>':
sb.append("\\>");
break;
case ';':
sb.append("\\;");
break;
default:
sb.append(c);
}
}
// add the trailing backslash if needed
if ((canonical.length() > 1) && (canonical.charAt(canonical.length() - 1) == ' ')) {
sb.insert(sb.length() - 1, '\\');
}
return sb.toString();
}
public String encodeForXPath(String input) {
return entityEncode(input, DefaultEncoder.CHAR_ALPHANUMERICS, IMMUNE_XPATH);
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#encodeForXML(java.lang.String)
*/
public String encodeForXML(String input) {
return entityEncode(input, DefaultEncoder.CHAR_ALPHANUMERICS, IMMUNE_XML);
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#encodeForXMLAttribute(java.lang.String)
*/
public String encodeForXMLAttribute(String input) {
return entityEncode(input, DefaultEncoder.CHAR_ALPHANUMERICS, IMMUNE_XMLATTR);
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#encodeForURL(java.lang.String)
*/
public String encodeForURL(String input) throws EncodingException {
String canonical = canonicalize(input);
try {
return URLEncoder.encode(canonical, ESAPI.securityConfiguration().getCharacterEncoding());
} catch (UnsupportedEncodingException ex) {
throw new EncodingException("Encoding failure", "Encoding not supported", ex);
} catch (Exception e) {
throw new EncodingException("Encoding failure", "Problem URL decoding input", e);
}
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#decodeFromURL(java.lang.String)
*/
public String decodeFromURL(String input) throws EncodingException {
String canonical = canonicalize(input);
try {
return URLDecoder.decode(canonical, ESAPI.securityConfiguration().getCharacterEncoding());
} catch (UnsupportedEncodingException ex) {
throw new EncodingException("Decoding failed", "Encoding not supported", ex);
} catch (Exception e) {
throw new EncodingException("Decoding failed", "Problem URL decoding input", e);
}
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#encodeForBase64(byte[])
*/
public String encodeForBase64(byte[] input, boolean wrap) {
String b64 = base64Encoder.encode(input);
// remove line-feeds and carriage-returns inserted in output
if (!wrap) {
b64 = b64.replaceAll("\r", "").replaceAll("\n", "");
}
return b64;
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.IEncoder#decodeFromBase64(java.lang.String)
*/
public byte[] decodeFromBase64(String input) throws IOException {
return base64Decoder.decodeBuffer(input);
}
// FIXME: ENHANCE - change formatting here to more like -- "quot", "34", //
// quotation mark
private void initializeMaps() {
String[] entityNames = { "quot"
/* 34 : quotation mark */, "amp"
/* 38 : ampersand */, "lt"
/* 60 : less-than sign */, "gt"
/* 62 : greater-than sign */, "nbsp"
/* 160 : no-break space */, "iexcl"
/* 161 : inverted exclamation mark */, "cent"
/* 162 : cent sign */, "pound"
/* 163 : pound sign */, "curren"
/* 164 : currency sign */, "yen"
/* 165 : yen sign */, "brvbar"
/* 166 : broken bar */, "sect"
/* 167 : section sign */, "uml"
/* 168 : diaeresis */, "copy"
, "ordf"
/* 170 : feminine ordinal indicator */, "laquo"
/* 171 : left-pointing double angle quotation mark */, "not"
/* 172 : not sign */, "shy"
/* 173 : soft hyphen */, "reg"
/* 174 : registered sign */, "macr"
/* 175 : macron */, "deg"
/* 176 : degree sign */, "plusmn"
/* 177 : plus-minus sign */, "sup2"
/* 178 : superscript two */, "sup3"
/* 179 : superscript three */, "acute"
/* 180 : acute accent */, "micro"
/* 181 : micro sign */, "para"
/* 182 : pilcrow sign */, "middot"
/* 183 : middle dot */, "cedil"
/* 184 : cedilla */, "sup1"
/* 185 : superscript one */, "ordm"
/* 186 : masculine ordinal indicator */, "raquo"
/* 187 : right-pointing double angle quotation mark */, "frac14"
/* 188 : vulgar fraction one quarter */, "frac12"
/* 189 : vulgar fraction one half */, "frac34"
/* 190 : vulgar fraction three quarters */, "iquest"
/* 191 : inverted question mark */, "Agrave"
/* 192 : Latin capital letter a with grave */, "Aacute"
/* 193 : Latin capital letter a with acute */, "Acirc"
/* 194 : Latin capital letter a with circumflex */, "Atilde"
/* 195 : Latin capital letter a with tilde */, "Auml"
/* 196 : Latin capital letter a with diaeresis */, "Aring"
/* 197 : Latin capital letter a with ring above */, "AElig"
/* 198 : Latin capital letter ae */, "Ccedil"
/* 199 : Latin capital letter c with cedilla */, "Egrave"
/* 200 : Latin capital letter e with grave */, "Eacute"
/* 201 : Latin capital letter e with acute */, "Ecirc"
/* 202 : Latin capital letter e with circumflex */, "Euml"
/* 203 : Latin capital letter e with diaeresis */, "Igrave"
/* 204 : Latin capital letter i with grave */, "Iacute"
/* 205 : Latin capital letter i with acute */, "Icirc"
/* 206 : Latin capital letter i with circumflex */, "Iuml"
/* 207 : Latin capital letter i with diaeresis */, "ETH"
/* 208 : Latin capital letter eth */, "Ntilde"
/* 209 : Latin capital letter n with tilde */, "Ograve"
/* 210 : Latin capital letter o with grave */, "Oacute"
/* 211 : Latin capital letter o with acute */, "Ocirc"
/* 212 : Latin capital letter o with circumflex */, "Otilde"
/* 213 : Latin capital letter o with tilde */, "Ouml"
/* 214 : Latin capital letter o with diaeresis */, "times"
/* 215 : multiplication sign */, "Oslash"
/* 216 : Latin capital letter o with stroke */, "Ugrave"
/* 217 : Latin capital letter u with grave */, "Uacute"
/* 218 : Latin capital letter u with acute */, "Ucirc"
/* 219 : Latin capital letter u with circumflex */, "Uuml"
/* 220 : Latin capital letter u with diaeresis */, "Yacute"
/* 221 : Latin capital letter y with acute */, "THORN"
/* 222 : Latin capital letter thorn */, "szlig"
/* 223 : Latin small letter sharp s, German Eszett */, "agrave"
/* 224 : Latin small letter a with grave */, "aacute"
/* 225 : Latin small letter a with acute */, "acirc"
/* 226 : Latin small letter a with circumflex */, "atilde"
/* 227 : Latin small letter a with tilde */, "auml"
/* 228 : Latin small letter a with diaeresis */, "aring"
/* 229 : Latin small letter a with ring above */, "aelig"
/* 230 : Latin lowercase ligature ae */, "ccedil"
/* 231 : Latin small letter c with cedilla */, "egrave"
/* 232 : Latin small letter e with grave */, "eacute"
/* 233 : Latin small letter e with acute */, "ecirc"
/* 234 : Latin small letter e with circumflex */, "euml"
/* 235 : Latin small letter e with diaeresis */, "igrave"
/* 236 : Latin small letter i with grave */, "iacute"
/* 237 : Latin small letter i with acute */, "icirc"
/* 238 : Latin small letter i with circumflex */, "iuml"
/* 239 : Latin small letter i with diaeresis */, "eth"
/* 240 : Latin small letter eth */, "ntilde"
/* 241 : Latin small letter n with tilde */, "ograve"
/* 242 : Latin small letter o with grave */, "oacute"
/* 243 : Latin small letter o with acute */, "ocirc"
/* 244 : Latin small letter o with circumflex */, "otilde"
/* 245 : Latin small letter o with tilde */, "ouml"
/* 246 : Latin small letter o with diaeresis */, "divide"
/* 247 : division sign */, "oslash"
/* 248 : Latin small letter o with stroke */, "ugrave"
/* 249 : Latin small letter u with grave */, "uacute"
/* 250 : Latin small letter u with acute */, "ucirc"
/* 251 : Latin small letter u with circumflex */, "uuml"
/* 252 : Latin small letter u with diaeresis */, "yacute"
/* 253 : Latin small letter y with acute */, "thorn"
/* 254 : Latin small letter thorn */, "yuml"
/* 255 : Latin small letter y with diaeresis */, "OElig"
/* 338 : Latin capital ligature oe */, "oelig"
/* 339 : Latin small ligature oe */, "Scaron"
/* 352 : Latin capital letter s with caron */, "scaron"
/* 353 : Latin small letter s with caron */, "Yuml"
/* 376 : Latin capital letter y with diaeresis */, "fnof"
/* 402 : Latin small letter f with hook */, "circ"
/* 710 : modifier letter circumflex accent */, "tilde"
/* 732 : small tilde */, "Alpha"
/* 913 : Greek capital letter alpha */, "Beta"
/* 914 : Greek capital letter beta */, "Gamma"
/* 915 : Greek capital letter gamma */, "Delta"
/* 916 : Greek capital letter delta */, "Epsilon"
/* 917 : Greek capital letter epsilon */, "Zeta"
/* 918 : Greek capital letter zeta */, "Eta"
/* 919 : Greek capital letter eta */, "Theta"
/* 920 : Greek capital letter theta */, "Iota"
/* 921 : Greek capital letter iota */, "Kappa"
/* 922 : Greek capital letter kappa */, "Lambda"
/* 923 : Greek capital letter lambda */, "Mu"
/* 924 : Greek capital letter mu */, "Nu"
/* 925 : Greek capital letter nu */, "Xi"
/* 926 : Greek capital letter xi */, "Omicron"
/* 927 : Greek capital letter omicron */, "Pi"
/* 928 : Greek capital letter pi */, "Rho"
/* 929 : Greek capital letter rho */, "Sigma"
/* 931 : Greek capital letter sigma */, "Tau"
/* 932 : Greek capital letter tau */, "Upsilon"
/* 933 : Greek capital letter upsilon */, "Phi"
/* 934 : Greek capital letter phi */, "Chi"
/* 935 : Greek capital letter chi */, "Psi"
/* 936 : Greek capital letter psi */, "Omega"
/* 937 : Greek capital letter omega */, "alpha"
/* 945 : Greek small letter alpha */, "beta"
/* 946 : Greek small letter beta */, "gamma"
/* 947 : Greek small letter gamma */, "delta"
/* 948 : Greek small letter delta */, "epsilon"
/* 949 : Greek small letter epsilon */, "zeta"
/* 950 : Greek small letter zeta */, "eta"
/* 951 : Greek small letter eta */, "theta"
/* 952 : Greek small letter theta */, "iota"
/* 953 : Greek small letter iota */, "kappa"
/* 954 : Greek small letter kappa */, "lambda"
/* 955 : Greek small letter lambda */, "mu"
/* 956 : Greek small letter mu */, "nu"
/* 957 : Greek small letter nu */, "xi"
/* 958 : Greek small letter xi */, "omicron"
/* 959 : Greek small letter omicron */, "pi"
/* 960 : Greek small letter pi */, "rho"
/* 961 : Greek small letter rho */, "sigmaf"
/* 962 : Greek small letter final sigma */, "sigma"
/* 963 : Greek small letter sigma */, "tau"
/* 964 : Greek small letter tau */, "upsilon"
/* 965 : Greek small letter upsilon */, "phi"
/* 966 : Greek small letter phi */, "chi"
/* 967 : Greek small letter chi */, "psi"
/* 968 : Greek small letter psi */, "omega"
/* 969 : Greek small letter omega */, "thetasym"
/* 977 : Greek theta symbol */, "upsih"
/* 978 : Greek upsilon with hook symbol */, "piv"
/* 982 : Greek pi symbol */, "ensp"
/* 8194 : en space */, "emsp"
/* 8195 : em space */, "thinsp"
/* 8201 : thin space */, "zwnj"
/* 8204 : zero width non-joiner */, "zwj"
/* 8205 : zero width joiner */, "lrm"
/* 8206 : left-to-right mark */, "rlm"
/* 8207 : right-to-left mark */, "ndash"
/* 8211 : en dash */, "mdash"
/* 8212 : em dash */, "lsquo"
/* 8216 : left single quotation mark */, "rsquo"
/* 8217 : right single quotation mark */, "sbquo"
/* 8218 : single low-9 quotation mark */, "ldquo"
/* 8220 : left double quotation mark */, "rdquo"
/* 8221 : right double quotation mark */, "bdquo"
/* 8222 : double low-9 quotation mark */, "dagger"
/* 8224 : dagger */, "Dagger"
/* 8225 : double dagger */, "bull"
/* 8226 : bullet */, "hellip"
/* 8230 : horizontal ellipsis */, "permil"
/* 8240 : per mille sign */, "prime"
/* 8242 : prime */, "Prime"
/* 8243 : double prime */, "lsaquo"
/* 8249 : single left-pointing angle quotation mark */, "rsaquo"
/* 8250 : single right-pointing angle quotation mark */, "oline"
/* 8254 : overline */, "frasl"
/* 8260 : fraction slash */, "euro"
/* 8364 : euro sign */, "image"
/* 8465 : black-letter capital i */, "weierp"
/* 8472 : script capital p, Weierstrass p */, "real"
/* 8476 : black-letter capital r */, "trade"
/* 8482 : trademark sign */, "alefsym"
/* 8501 : alef symbol */, "larr"
/* 8592 : leftwards arrow */, "uarr"
/* 8593 : upwards arrow */, "rarr"
/* 8594 : rightwards arrow */, "darr"
/* 8595 : downwards arrow */, "harr"
/* 8596 : left right arrow */, "crarr"
/* 8629 : downwards arrow with corner leftwards */, "lArr"
/* 8656 : leftwards double arrow */, "uArr"
/* 8657 : upwards double arrow */, "rArr"
/* 8658 : rightwards double arrow */, "dArr"
/* 8659 : downwards double arrow */, "hArr"
/* 8660 : left right double arrow */, "forall"
/* 8704 : for all */, "part"
/* 8706 : partial differential */, "exist"
/* 8707 : there exists */, "empty"
/* 8709 : empty set */, "nabla"
/* 8711 : nabla */, "isin"
/* 8712 : element of */, "notin"
/* 8713 : not an element of */, "ni"
/* 8715 : contains as member */, "prod"
/* 8719 : n-ary product */, "sum"
/* 8721 : n-ary summation */, "minus"
/* 8722 : minus sign */, "lowast"
/* 8727 : asterisk operator */, "radic"
/* 8730 : square root */, "prop"
/* 8733 : proportional to */, "infin"
/* 8734 : infinity */, "ang"
/* 8736 : angle */, "and"
/* 8743 : logical and */, "or"
/* 8744 : logical or */, "cap"
/* 8745 : intersection */, "cup"
/* 8746 : union */, "int"
/* 8747 : integral */, "there4"
/* 8756 : therefore */, "sim"
/* 8764 : tilde operator */, "cong"
/* 8773 : congruent to */, "asymp"
/* 8776 : almost equal to */, "ne"
/* 8800 : not equal to */, "equiv"
/* 8801 : identical to, equivalent to */, "le"
/* 8804 : less-than or equal to */, "ge"
/* 8805 : greater-than or equal to */, "sub"
/* 8834 : subset of */, "sup"
/* 8835 : superset of */, "nsub"
/* 8836 : not a subset of */, "sube"
/* 8838 : subset of or equal to */, "supe"
/* 8839 : superset of or equal to */, "oplus"
/* 8853 : circled plus */, "otimes"
/* 8855 : circled times */, "perp"
/* 8869 : up tack */, "sdot"
/* 8901 : dot operator */, "lceil"
/* 8968 : left ceiling */, "rceil"
/* 8969 : right ceiling */, "lfloor"
/* 8970 : left floor */, "rfloor"
/* 8971 : right floor */, "lang"
/* 9001 : left-pointing angle bracket */, "rang"
/* 9002 : right-pointing angle bracket */, "loz"
/* 9674 : lozenge */, "spades"
/* 9824 : black spade suit */, "clubs"
/* 9827 : black club suit */, "hearts"
/* 9829 : black heart suit */, "diams"
/* 9830 : black diamond suit */, };
char[] entityValues = { 34
/* " : quotation mark */, 38
/* & : ampersand */, 60
/* < : less-than sign */, 62
/* > : greater-than sign */, 160
/* : no-break space */, 161
/* ¡ : inverted exclamation mark */, 162
/* ¢ : cent sign */, 163
/* £ : pound sign */, 164
/* ¤ : currency sign */, 165
/* ¥ : yen sign */, 166
/* ¦ : broken bar */, 167
/* § : section sign */, 168
/* ¨ : diaeresis */, 169
, 170
/* ª : feminine ordinal indicator */, 171
/* « : left-pointing double angle quotation mark */, 172
/* ¬ : not sign */, 173
/* ­ : soft hyphen */, 174
/* ® : registered sign */, 175
/* ¯ : macron */, 176
/* ° : degree sign */, 177
/* ± : plus-minus sign */, 178
/* ² : superscript two */, 179
/* ³ : superscript three */, 180
/* ´ : acute accent */, 181
/* µ : micro sign */, 182
/* ¶ : pilcrow sign */, 183
/* · : middle dot */, 184
/* ¸ : cedilla */, 185
/* ¹ : superscript one */, 186
/* º : masculine ordinal indicator */, 187
/* » : right-pointing double angle quotation mark */, 188
/* ¼ : vulgar fraction one quarter */, 189
/* ½ : vulgar fraction one half */, 190
/* ¾ : vulgar fraction three quarters */, 191
/* ¿ : inverted question mark */, 192
/* À : Latin capital letter a with grave */, 193
/* Á : Latin capital letter a with acute */, 194
/* Â : Latin capital letter a with circumflex */, 195
/* Ã : Latin capital letter a with tilde */, 196
/* Ä : Latin capital letter a with diaeresis */, 197
/* Å : Latin capital letter a with ring above */, 198
/* Æ : Latin capital letter ae */, 199
/* Ç : Latin capital letter c with cedilla */, 200
/* È : Latin capital letter e with grave */, 201
/* É : Latin capital letter e with acute */, 202
/* Ê : Latin capital letter e with circumflex */, 203
/* Ë : Latin capital letter e with diaeresis */, 204
/* Ì : Latin capital letter i with grave */, 205
/* Í : Latin capital letter i with acute */, 206
/* Î : Latin capital letter i with circumflex */, 207
/* Ï : Latin capital letter i with diaeresis */, 208
/* Ð : Latin capital letter eth */, 209
/* Ñ : Latin capital letter n with tilde */, 210
/* Ò : Latin capital letter o with grave */, 211
/* Ó : Latin capital letter o with acute */, 212
/* Ô : Latin capital letter o with circumflex */, 213
/* Õ : Latin capital letter o with tilde */, 214
/* Ö : Latin capital letter o with diaeresis */, 215
/* × : multiplication sign */, 216
/* Ø : Latin capital letter o with stroke */, 217
/* Ù : Latin capital letter u with grave */, 218
/* Ú : Latin capital letter u with acute */, 219
/* Û : Latin capital letter u with circumflex */, 220
/* Ü : Latin capital letter u with diaeresis */, 221
/* Ý : Latin capital letter y with acute */, 222
/* Þ : Latin capital letter thorn */, 223
/* ß : Latin small letter sharp s, German Eszett */, 224
/* à : Latin small letter a with grave */, 225
/* á : Latin small letter a with acute */, 226
/* â : Latin small letter a with circumflex */, 227
/* ã : Latin small letter a with tilde */, 228
/* ä : Latin small letter a with diaeresis */, 229
/* å : Latin small letter a with ring above */, 230
/* æ : Latin lowercase ligature ae */, 231
/* ç : Latin small letter c with cedilla */, 232
/* è : Latin small letter e with grave */, 233
/* é : Latin small letter e with acute */, 234
/* ê : Latin small letter e with circumflex */, 235
/* ë : Latin small letter e with diaeresis */, 236
/* ì : Latin small letter i with grave */, 237
/* í : Latin small letter i with acute */, 238
/* î : Latin small letter i with circumflex */, 239
/* ï : Latin small letter i with diaeresis */, 240
/* ð : Latin small letter eth */, 241
/* ñ : Latin small letter n with tilde */, 242
/* ò : Latin small letter o with grave */, 243
/* ó : Latin small letter o with acute */, 244
/* ô : Latin small letter o with circumflex */, 245
/* õ : Latin small letter o with tilde */, 246
/* ö : Latin small letter o with diaeresis */, 247
/* ÷ : division sign */, 248
/* ø : Latin small letter o with stroke */, 249
/* ù : Latin small letter u with grave */, 250
/* ú : Latin small letter u with acute */, 251
/* û : Latin small letter u with circumflex */, 252
/* ü : Latin small letter u with diaeresis */, 253
/* ý : Latin small letter y with acute */, 254
/* þ : Latin small letter thorn */, 255
/* ÿ : Latin small letter y with diaeresis */, 338
/* Œ : Latin capital ligature oe */, 339
/* œ : Latin small ligature oe */, 352
/* Š : Latin capital letter s with caron */, 353
/* š : Latin small letter s with caron */, 376
/* Ÿ : Latin capital letter y with diaeresis */, 402
/* ƒ : Latin small letter f with hook */, 710
/* ˆ : modifier letter circumflex accent */, 732
/* ˜ : small tilde */, 913
/* Α : Greek capital letter alpha */, 914
/* Β : Greek capital letter beta */, 915
/* Γ : Greek capital letter gamma */, 916
/* Δ : Greek capital letter delta */, 917
/* Ε : Greek capital letter epsilon */, 918
/* Ζ : Greek capital letter zeta */, 919
/* Η : Greek capital letter eta */, 920
/* Θ : Greek capital letter theta */, 921
/* Ι : Greek capital letter iota */, 922
/* Κ : Greek capital letter kappa */, 923
/* Λ : Greek capital letter lambda */, 924
/* Μ : Greek capital letter mu */, 925
/* Ν : Greek capital letter nu */, 926
/* Ξ : Greek capital letter xi */, 927
/* Ο : Greek capital letter omicron */, 928
/* Π : Greek capital letter pi */, 929
/* Ρ : Greek capital letter rho */, 931
/* Σ : Greek capital letter sigma */, 932
/* Τ : Greek capital letter tau */, 933
/* Υ : Greek capital letter upsilon */, 934
/* Φ : Greek capital letter phi */, 935
/* Χ : Greek capital letter chi */, 936
/* Ψ : Greek capital letter psi */, 937
/* Ω : Greek capital letter omega */, 945
/* α : Greek small letter alpha */, 946
/* β : Greek small letter beta */, 947
/* γ : Greek small letter gamma */, 948
/* δ : Greek small letter delta */, 949
/* ε : Greek small letter epsilon */, 950
/* ζ : Greek small letter zeta */, 951
/* η : Greek small letter eta */, 952
/* θ : Greek small letter theta */, 953
/* ι : Greek small letter iota */, 954
/* κ : Greek small letter kappa */, 955
/* λ : Greek small letter lambda */, 956
/* μ : Greek small letter mu */, 957
/* ν : Greek small letter nu */, 958
/* ξ : Greek small letter xi */, 959
/* ο : Greek small letter omicron */, 960
/* π : Greek small letter pi */, 961
/* ρ : Greek small letter rho */, 962
/* ς : Greek small letter final sigma */, 963
/* σ : Greek small letter sigma */, 964
/* τ : Greek small letter tau */, 965
/* υ : Greek small letter upsilon */, 966
/* φ : Greek small letter phi */, 967
/* χ : Greek small letter chi */, 968
/* ψ : Greek small letter psi */, 969
/* ω : Greek small letter omega */, 977
/* ϑ : Greek theta symbol */, 978
/* ϒ : Greek upsilon with hook symbol */, 982
/* ϖ : Greek pi symbol */, 8194
/*   : en space */, 8195
/*   : em space */, 8201
/*   : thin space */, 8204
/* ‌ : zero width non-joiner */, 8205
/* ‍ : zero width joiner */, 8206
/* ‎ : left-to-right mark */, 8207
/* ‏ : right-to-left mark */, 8211
/* – : en dash */, 8212
/* — : em dash */, 8216
/* ‘ : left single quotation mark */, 8217
/* ’ : right single quotation mark */, 8218
/* ‚ : single low-9 quotation mark */, 8220
/* “ : left double quotation mark */, 8221
/* ” : right double quotation mark */, 8222
/* „ : double low-9 quotation mark */, 8224
/* † : dagger */, 8225
/* ‡ : double dagger */, 8226
/* • : bullet */, 8230
/* … : horizontal ellipsis */, 8240
/* ‰ : per mille sign */, 8242
/* ′ : prime */, 8243
/* ″ : double prime */, 8249
/* ‹ : single left-pointing angle quotation mark */, 8250
/* › : single right-pointing angle quotation mark */, 8254
/* ‾ : overline */, 8260
/* ⁄ : fraction slash */, 8364
/* € : euro sign */, 8465
/* ℑ : black-letter capital i */, 8472
/* ℘ : script capital p, Weierstrass p */, 8476
/* ℜ : black-letter capital r */, 8482
/* ™ : trademark sign */, 8501
/* ℵ : alef symbol */, 8592
/* ← : leftwards arrow */, 8593
/* ↑ : upwards arrow */, 8594
/* → : rightwards arrow */, 8595
/* ↓ : downwards arrow */, 8596
/* ↔ : left right arrow */, 8629
/* ↵ : downwards arrow with corner leftwards */, 8656
/* ⇐ : leftwards double arrow */, 8657
/* ⇑ : upwards double arrow */, 8658
/* ⇒ : rightwards double arrow */, 8659
/* ⇓ : downwards double arrow */, 8660
/* ⇔ : left right double arrow */, 8704
/* ∀ : for all */, 8706
/* ∂ : partial differential */, 8707
/* ∃ : there exists */, 8709
/* ∅ : empty set */, 8711
/* ∇ : nabla */, 8712
/* ∈ : element of */, 8713
/* ∉ : not an element of */, 8715
/* ∋ : contains as member */, 8719
/* ∏ : n-ary product */, 8721
/* ∑ : n-ary summation */, 8722
/* − : minus sign */, 8727
/* ∗ : asterisk operator */, 8730
/* √ : square root */, 8733
/* ∝ : proportional to */, 8734
/* ∞ : infinity */, 8736
/* ∠ : angle */, 8743
/* ∧ : logical and */, 8744
/* ∨ : logical or */, 8745
/* ∩ : intersection */, 8746
/* ∪ : union */, 8747
/* ∫ : integral */, 8756
/* ∴ : therefore */, 8764
/* ∼ : tilde operator */, 8773
/* ≅ : congruent to */, 8776
/* ≈ : almost equal to */, 8800
/* ≠ : not equal to */, 8801
/* ≡ : identical to, equivalent to */, 8804
/* ≤ : less-than or equal to */, 8805
/* ≥ : greater-than or equal to */, 8834
/* ⊂ : subset of */, 8835
/* ⊃ : superset of */, 8836
/* ⊄ : not a subset of */, 8838
/* ⊆ : subset of or equal to */, 8839
/* ⊇ : superset of or equal to */, 8853
/* ⊕ : circled plus */, 8855
/* ⊗ : circled times */, 8869
/* ⊥ : up tack */, 8901
/* ⋅ : dot operator */, 8968
/* ⌈ : left ceiling */, 8969
/* ⌉ : right ceiling */, 8970
/* ⌊ : left floor */, 8971
/* ⌋ : right floor */, 9001
/* ⟨ : left-pointing angle bracket */, 9002
/* ⟩ : right-pointing angle bracket */, 9674
/* ◊ : lozenge */, 9824
/* ♠ : black spade suit */, 9827
/* ♣ : black club suit */, 9829
/* ♥ : black heart suit */, 9830
/* ♦ : black diamond suit */, };
characterToEntityMap = new HashMap(entityNames.length);
entityToCharacterMap = new HashMap(entityValues.length);
for (int i = 0; i < entityNames.length; i++) {
String e = entityNames[i];
Character c = new Character(entityValues[i]);
entityToCharacterMap.put(e, c);
characterToEntityMap.put(c, e);
}
}
public static void main(String[] args) {
// Encoder encoder = new Encoder();
// try { System.out.println( ">>" + encoder.encodeForHTML("test <>
// test") ); } catch( Exception e1 ) { System.out.println(" !" +
// e1.getMessage() ); }
// try { System.out.println( ">>" + encoder.encodeForHTML("test %41 %42
// test") ); } catch( Exception e2 ) { System.out.println(" !" +
// e2.getMessage() ); }
// try { System.out.println( ">>" + encoder.encodeForHTML("test %26%42
// test") ); } catch( Exception e2 ) { System.out.println(" !" +
// e2.getMessage() ); }
// try { System.out.println( ">>" + encoder.encodeForHTML("test %26amp;
// test") ); } catch( Exception e3 ) { System.out.println(" !" +
// e3.getMessage() ); }
// try { System.out.println( ">>" + encoder.encodeForHTML("test &
// test") ); } catch( Exception e4 ) { System.out.println(" !" +
// e4.getMessage() ); }
// try { System.out.println( ">>" + encoder.encodeForHTML("test
// &amp; test") ); } catch( Exception e5 ) { System.out.println(" !"
// + e5.getMessage() ); }
// try { System.out.println( ">>" + encoder.encodeForHTML("test &#ridi;
// test") ); } catch( Exception e6 ) { e6.printStackTrace() ; }
//try {
// System.out.println(">>" + encoder.encodeForHTML("test  test"));
//} catch (Exception e7) {
// System.out.println(" !" + e7.getMessage());
}
private class EncodedStringReader {
String input = null;
int nextCharacter = 0;
int testCharacter = 0;
public EncodedStringReader(String input) {
if (input == null) {
this.input = "";
} else {
this.input = input;
}
}
public boolean hasNext() {
return nextCharacter < input.length();
}
public EncodedCharacter getNextCharacter() {
// get the current character and move past it
testCharacter = nextCharacter;
EncodedCharacter c = null;
c = peekNextCharacter(input.charAt(nextCharacter));
// System.out.println( nextCharacter + ":" + (int)c.getUnencoded() +
// " -> " + testCharacter );
nextCharacter = testCharacter;
if (c == null)
return null;
// if the current character is encoded, check for double-encoded
// characters
if (c.isEncoded()) {
testCharacter
EncodedCharacter next = peekNextCharacter(c.getUnencoded());
if (next != null) {
if (next.isEncoded()) {
throw new IntrusionException("Validation error", "Input contains double encoded characters.");
} else {
// System.out.println("Not double-encoded");
}
}
}
return c;
}
private EncodedCharacter peekNextCharacter(char currentCharacter) {
// if we're on the last character
if (testCharacter == input.length() - 1) {
testCharacter++;
return new EncodedCharacter(currentCharacter);
} else if (currentCharacter == '&') {
// if parsing an entity returns null - then we should skip it by
// returning null here
EncodedCharacter encoded = parseEntity(input, testCharacter);
return encoded;
} else if (currentCharacter == '%') {
// if parsing a % encoded character returns null, then just
// return the % and keep going
EncodedCharacter encoded = parsePercent(input, testCharacter);
if (encoded != null) {
return encoded;
}
// FIXME: AAA add UTF-7 decoding
// FIXME: others?
}
testCharacter++;
return new EncodedCharacter(currentCharacter);
}
// return a character or null if no good character can be parsed.
public EncodedCharacter parsePercent(String s, int startIndex) {
// FIXME: AAA check if these can be longer than 2 characters?
// consume as many as possible?
String possible = s.substring(startIndex + 1, startIndex + 3);
try {
int c = Integer.parseInt(possible, 16);
testCharacter += 3;
return new EncodedCharacter("%" + possible, (char) c, PERCENT_ENCODING);
} catch (NumberFormatException e) {
// System.out.println("Found % but there was no encoded character following it");
return null;
}
}
public EncodedCharacter parseEntity(String s, int startIndex) {
// FIXME: AAA - figure out how to handle non-semicolon terminated
// characters
int semiIndex = input.indexOf(";", startIndex + 1);
if (semiIndex != -1) {
if (semiIndex - startIndex <= 8) {
String possible = input.substring(startIndex + 1, semiIndex).toLowerCase();
// System.out.println( " " + possible + " -> " +
// testCharacter );
Character entity = (Character) entityToCharacterMap.get(possible);
if (entity != null) {
testCharacter += possible.length() + 2;
return new EncodedCharacter("&" + possible + ";", entity.charValue(), ENTITY_ENCODING);
} else if (possible.charAt(0) == '
// advance past this either way
testCharacter += possible.length() + 2;
try {
// FIXME: Enhance - consider supporting #x encoding
int c = Integer.parseInt(possible.substring(1));
return new EncodedCharacter("&#" + (char) c + ";", (char) c, ENTITY_ENCODING);
} catch (NumberFormatException e) {
// invalid character - return null
logger.warning(Logger.SECURITY, "Invalid numeric entity encoding &" + possible + ";");
}
}
}
}
// System.out.println("Found & but there was no entity following it");
testCharacter++;
return new EncodedCharacter("&", '&', NO_ENCODING);
}
}
private class EncodedCharacter {
String raw = ""; // the core of the encoded representation (without
// the prefix or suffix)
char character = 0;
int originalEncoding;
public EncodedCharacter(char character) {
this.raw = "" + character;
this.character = character;
}
public boolean isEncoded() {
return (raw.length() != 1);
}
public EncodedCharacter(String raw, char character, int originalEncoding) {
this.raw = raw;
this.character = character;
this.originalEncoding = originalEncoding;
}
public char getUnencoded() {
return character;
}
public String getEncoded(int encoding) {
switch (encoding) {
case DefaultEncoder.NO_ENCODING:
return "" + character;
case DefaultEncoder.URL_ENCODING:
// FIXME: look up rules
if (Character.isWhitespace(character))
return "+";
if (Character.isLetterOrDigit(character))
return "" + character;
return "%" + (int) character;
case DefaultEncoder.PERCENT_ENCODING:
return "%" + (int) character;
case DefaultEncoder.ENTITY_ENCODING:
String entityName = (String) characterToEntityMap.get(new Character(character));
if (entityName != null)
return "&" + entityName + ";";
return "&#" + (int) character + ";";
default:
return null;
}
}
}
} |
package io.lumify.palantir.dataImport.model;
import io.lumify.core.exception.LumifyException;
import io.lumify.core.util.LumifyLogger;
import io.lumify.core.util.LumifyLoggerFactory;
import io.lumify.palantir.dataImport.util.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DisplayFormula {
private static final LumifyLogger LOGGER = LumifyLoggerFactory.getLogger(DisplayFormula.class);
private static Pattern VALUE_BODY_PATTERN = Pattern.compile("^<VALUE>(.*)</VALUE>$", Pattern.DOTALL);
private static Pattern UNPARSED_VALUE_BODY_PATTERN = Pattern.compile("^<UNPARSED_VALUE>(.*)</UNPARSED_VALUE>$", Pattern.DOTALL);
private static Pattern VALUE_SUBSTITUTION = Pattern.compile("\\{(.*?)\\}");
private static final DocumentBuilder dBuilder;
private boolean prettyPrint;
private List<String> formulas = new ArrayList<String>();
static {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dBuilder = dbFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new LumifyException("Could not create document builder", e);
}
}
public DisplayFormula(Element displayElement) {
if (displayElement == null) {
return;
}
Element argsElement = XmlUtil.getChildByTagName(displayElement, "args");
if (argsElement == null) {
return;
}
NodeList argElements = argsElement.getChildNodes();
for (int i = 0; i < argElements.getLength(); i++) {
Node argElement = argElements.item(i);
if (!(argElement instanceof Element)) {
continue;
}
if (!((Element) argElement).getTagName().equals("arg")) {
continue;
}
String arg = argElement.getTextContent();
if (arg.startsWith("prettyprint=")) {
prettyPrint = Boolean.parseBoolean(arg.substring("prettyprint=".length()));
continue;
}
if (arg.startsWith("tokens=")) {
formulas.add(arg.substring("tokens=".length()));
continue;
}
throw new LumifyException("Could not parse arg formula " + arg);
}
}
public Object toValue(String value) {
if (value == null) {
return null;
}
value = value.trim();
if (value.equals("<null></null>")) {
return null;
}
Matcher m = VALUE_BODY_PATTERN.matcher(value);
if (m.matches()) {
value = m.group(1).trim();
}
m = UNPARSED_VALUE_BODY_PATTERN.matcher(value);
if (m.matches()) {
return m.group(1).trim();
}
if (formulas.size() > 0) {
Map<String, String> values = getValuesFromValue(value);
String formattedValue = formatValues(values);
if (formattedValue != null) {
return formattedValue;
}
}
return value;
}
private String formatValues(Map<String, String> values) {
for (String displayFormula : formulas) {
String r = formatValues(values, displayFormula);
if (r != null) {
return r;
}
}
return null;
}
private String formatValues(Map<String, String> values, String displayFormula) {
try {
StringBuffer output = new StringBuffer();
Matcher matcher = VALUE_SUBSTITUTION.matcher(displayFormula);
while (matcher.find()) {
String expr = matcher.group(1);
String[] exprParts = expr.split(",");
String v = values.get(exprParts[0]);
if (v == null) {
return null; // could not find a value to match replacement
}
if (exprParts.length > 1) {
String fn = exprParts[1].trim();
v = applyFormatFunction(fn, v);
}
if (prettyPrint) {
if (v.length() > 0) {
v = Character.toUpperCase(v.charAt(0)) + v.substring(1);
}
}
matcher.appendReplacement(output, Matcher.quoteReplacement(v));
}
matcher.appendTail(output);
return output.toString();
} catch (Exception ex) {
throw new LumifyException("Could not format using formula: " + displayFormula, ex);
}
}
private String applyFormatFunction(String fn, String value) {
if ("add_ssn_dashes".equals(fn)) {
return applyAddSsnDashes(value);
}
LOGGER.error("Unknown format function: %s", fn);
return value;
}
private String applyAddSsnDashes(String value) {
if (value.length() == 9) {
return value.substring(0, 3) + "-" + value.substring(3, 5) + "-" + value.substring(5);
}
LOGGER.error("Invalid SSN to add ssn dashes to: %s", value);
return value;
}
private Map<String, String> getValuesFromValue(String value) {
try {
Document d = dBuilder.parse(new ByteArrayInputStream(("<v>" + value + "</v>").getBytes()));
Map<String, String> values = new HashMap<String, String>();
NodeList childNodes = d.getDocumentElement().getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
if (childNode instanceof Element) {
Element e = (Element) childNode;
values.put(e.getTagName(), e.getTextContent());
}
}
return values;
} catch (Exception e) {
throw new LumifyException("Could not parse value into values: " + value, e);
}
}
} |
package com.diozero.internal.board.tinkerboard;
import com.diozero.api.PinInfo;
import com.diozero.internal.provider.MmapGpioInterface;
import com.diozero.util.BoardInfo;
import com.diozero.util.BoardInfoProvider;
public class TinkerBoardBoardInfoProvider implements BoardInfoProvider {
public static final TinkerBoardBoardInfo TINKER_BOARD = new TinkerBoardBoardInfo();
public static final String MAKE = "Asus";
private static final String TINKER_BOARD_HARDWARE_ID = "Rockchip (Device Tree)";
@Override
public BoardInfo lookup(String hardware, String revision, Integer memoryKb) {
if (hardware != null && hardware.equals(TINKER_BOARD_HARDWARE_ID)) {
return TINKER_BOARD;
}
return null;
}
public static class TinkerBoardBoardInfo extends BoardInfo {
public static final String MODEL = "Tinker Board";
private static final int MEMORY = 2048;
private static final String LIBRARY_PATH = "tinkerboard";
//private static final String LIBRARY_PATH = "linux-arm";
private TinkerBoardBoardInfo() {
super(MAKE, MODEL, MEMORY, LIBRARY_PATH);
}
@Override
public void initialisePins() {
// FIXME Externalise this to a file
// GPIO0_C1 - gpiochip0 (24 lines, GPIOs start at 0)
int chip = 0;
int lines = 24;
int line_start = 0;
int line_offset = 17; // Line 0:17 (CLKOUT) - GPIO
addGpioPinInfo(line_start + line_offset, "GPIO0_C1", 7, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_start += lines;
// gpiochip1 (32 lines, GPIOs start at 0+24=24)
chip++;
lines = 32;
// Add lines
line_start += lines;
// gpiochip2 (32 lines, GPIOs start at 24+32=56)
chip++;
lines = 32;
// Add lines
line_start += lines;
// gpiochip3 (32 lines, GPIOs start at 56+32=88)
chip++;
lines = 32;
// Add lines
line_start += lines;
// gpiochip4 (32 lines, GPIOs start at 88+32=120)
chip++;
lines = 32;
// Add lines
line_start += lines;
// GPIO5B (GP5B0-GP5B7) - gpiochip5 (32 lines, GPIOs start at 120+32=152)
chip++;
lines = 32;
line_offset = 8; // Line 5:8 (UART-1 RX) - GPIO #160
addGpioPinInfo(line_start + line_offset, "GPIO5_B0", 10, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 9; // Line 5:9 (UART-1 TX) - GPIO #161
addGpioPinInfo(line_start + line_offset, "GPIO5_B1", 8, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 10; // Line 5:10 (UART-1 CTSN) - GPIO #162
addGpioPinInfo(line_start + line_offset, "GPIO5_B2", 16, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 11; // Line 5:11 (UART-1 RTSN) - GPIO #163
addGpioPinInfo(line_start + line_offset, "GPIO5_B3", 18, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 12; // Line 5:12 (SPI-0 CLK) - GPIO #164
addGpioPinInfo(line_start + line_offset, "GPIO5_B4", 11, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 13; // Line 5:13 (SPI-0 CS N0) - GPIO #165
addGpioPinInfo(line_start + line_offset, "GPIO5_B5", 29, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 14; // Line 5:14 (SPI-0 TX) - GPIO #166
addGpioPinInfo(line_start + line_offset, "GPIO5_B6", 13, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 15; // Line 5:15 (SPI-0 RX) - GPIO #167
addGpioPinInfo(line_start + line_offset, "GPIO5_B7", 15, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
// GPIO5C (GP5C0-GP5C3) - gpiochip5
line_offset = 16; // Line 5:16 (SPI-0 CS N1) - GPIO #168
addGpioPinInfo(line_start + line_offset, "GPIO5_C0", 31, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 17; // Line 5:17 (Not connected)
addGpioPinInfo(line_start + line_offset, "GPIO5_C1", -1, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 18; // Line 5:18 (Not connected)
addGpioPinInfo(line_start + line_offset, "GPIO5_C2", -1, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 19; // Line 5:19 - GPIO #171
addGpioPinInfo(line_start + line_offset, "GPIO5_C3", 22, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_start += lines;
// GPIO6A (GP6A0-GP6A1) - gpiochip6 (32 lines, GPIOs start at 152+32=184)
chip++;
lines = 32;
line_offset = 0; // Line 6:0 (PCM / I2C CLK) - GPIO #184
addGpioPinInfo(line_start + line_offset, "GPIO6_A0", 12, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 1; // Line 6:1 (PCM I2S FS) - GPIO #185
addGpioPinInfo(line_start + line_offset, "GPIO6_A1", 35, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
// GPIO6A (GP6A3-GP6A4) - gpiochip6
line_offset = 3; // Line 6:3 (I2S SDI) - GPIO #187
addGpioPinInfo(line_start + line_offset, "GPIO6_A3", 38, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 4; // Line 6:4 (I2S SDO) - GPIO #188
addGpioPinInfo(line_start + line_offset, "GPIO6_A4", 40, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_start += lines;
// GPIO7A (GP7A7) - gpiochip7 (32 lines, GPIOs start at 184+32=216)
chip++;
lines = 32;
line_offset = 7; // Line 7:7 (UART-3 RX) - GPIO #223
addGpioPinInfo(line_start + line_offset, "GPIO7_A7", 36, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
// GPIO7B (GP7B0-GP7B2) - gpiochip7
line_offset = 8; // Line 7:8 (UART-3 TX) - GPIO #224
addGpioPinInfo(line_start + line_offset, "GPIO7_B0", 37, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 9; // Line 7:9 (Not connected)
addGpioPinInfo(line_start + line_offset, "GPIO7_B1", -1, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 10; // Line 7:10 (Not connected)
addGpioPinInfo(line_start + line_offset, "GPIO7_B2", -1, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
// GPIO7CL (GP7C1-GP7C2) - gpiochip7
line_offset = 17; // Line 7:17 (I2C-4 SDA) - GPIO #233
addGpioPinInfo(line_start + line_offset, "GPIO7_C1", 27, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 18; // Line 7:18 (I2C-4 SCL) - GPIO #234
addGpioPinInfo(line_start + line_offset, "GPIO7_C2", 28, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
// GPIO7CH (GP7C6-GP7C7) - gpiochip7
line_offset = 22; // Line 7:22 (UART-2 RX) - GPIO #238
addPwmPinInfo(line_start + line_offset, "GPIO7_C6", 33, 0, PinInfo.DIGITAL_IN_OUT_PWM, chip, line_offset);
line_offset = 23; // Line 7:23 (UART-2 TX) - GPIO #239
addPwmPinInfo(line_start + line_offset, "GPIO7_C7", 32, 1, PinInfo.DIGITAL_IN_OUT_PWM, chip, line_offset);
line_start += lines;
// GPIO8A (GP8A3-GP8A7) - gpiochip8 (16 lines, GPIOs start at 216+32=248)
chip++;
lines = 16;
line_offset = 3; // Line 8:3 (SPI-2 CS N1) - GPIO #251
addGpioPinInfo(line_start + line_offset, "GPIO8_A3", 26, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 4; // Line 8:4 (I2C-1 SDA) - GPIO #252
addGpioPinInfo(line_start + line_offset, "GPIO8_A4", 3, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 5; // Line 8:5 (I2C-1 SCL) - GPIO #253
addGpioPinInfo(line_start + line_offset, "GPIO8_A5", 5, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 6; // Line 8:6 (SPI-2 CLK) - GPIO #254
addGpioPinInfo(line_start + line_offset, "GPIO8_A6", 23, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 7; // Line 8:7 (SPI-2 CS N0) - GPIO #255
addGpioPinInfo(line_start + line_offset, "GPIO8_A7", 24, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
// GPIO8B (GP8B0-GP8B1) - gpiochip8
line_offset = 8; // Line 8:8 (SPI-2 RX) - GPIO #256
addGpioPinInfo(line_start + line_offset, "GPIO8_B0", 21, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_offset = 9; // Line 8:9 (SPI-2 TX) - GPIO #257
addGpioPinInfo(line_start + line_offset, "GPIO8_B1", 19, PinInfo.DIGITAL_IN_OUT, chip, line_offset);
line_start += lines;
// Add non-GPIO pins
addGeneralPinInfo(1, PinInfo.VCC_3V3);
addGeneralPinInfo(2, PinInfo.VCC_5V);
addGeneralPinInfo(4, PinInfo.VCC_5V);
addGeneralPinInfo(6, PinInfo.GROUND);
addGeneralPinInfo(9, PinInfo.GROUND);
addGeneralPinInfo(14, PinInfo.GROUND);
addGeneralPinInfo(17, PinInfo.VCC_3V3);
addGeneralPinInfo(20, PinInfo.GROUND);
addGeneralPinInfo(25, PinInfo.GROUND);
addGeneralPinInfo(30, PinInfo.GROUND);
addGeneralPinInfo(34, PinInfo.GROUND);
addGeneralPinInfo(39, PinInfo.GROUND);
}
@Override
public int getPwmChip(int pwmNum) {
return 0;
}
@Override
public MmapGpioInterface createMmapGpio() {
return new TinkerBoardMmapGpio();
}
}
} |
package org.pentaho.di.core.plugins;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.vfs.AllFileSelector;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.FileType;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.provider.jar.JarFileObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.PDIClassLoader;
import org.pentaho.di.core.annotations.Job;
import org.pentaho.di.core.annotations.Step;
import org.pentaho.di.core.config.ConfigManager;
import org.pentaho.di.core.config.KettleConfig;
import org.pentaho.di.core.exception.KettleConfigException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.util.ResolverUtil;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.JobPlugin;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.trans.StepPlugin;
import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* This class handles all plugin loading steps for Kettle/PDI. It uses the
* ConfigManager class to load <code>PluginConfig</code> objects, which
* contain all the location from where the plugin should be loaded.
*
* Plugins are configured by modifying the kettle-plugins.xml file.
*
* @see PluginLocation
* @see org.pentaho.di.job.JobEntryLoader
*
* @author Alex Silva
*
*/
public class PluginLoader
{
private static final String WORK_DIR = "work"; //$NON-NLS-1$
/**
* Loads all plugins identified by the string passed. This method can be
* called multiple times with different managers.
*
* @param mgr
* The manager id, as defined in kettle-config.xml.
* @throws KettleConfigException
*/
public void load(String mgr) throws KettleConfigException
{
ConfigManager<?> c = KettleConfig.getInstance().getManager(mgr);
locs.addAll((Collection<PluginLocation>) c.loadAs(PluginLocation.class));
doConfig();
}
/**
* This method does the actual plugin configuration and should be called
* after load()
*
* @return a collection containing the <code>JobPlugin</code> objects
* loaded.
* @throws KettleConfigException
*/
private void doConfig() throws KettleConfigException
{
synchronized (locs)
{
String sjar = "." + JAR;
for (PluginLocation plugin : locs)
{
// check to see if the resource type is present
File base = new File(System.getProperty("user.dir"));
try
{
FileSystemManager mgr = VFS.getManager();
FileObject fobj = mgr.resolveFile(base, plugin.getLocation());
if (fobj.isReadable())
{
String name = fobj.getName().getURI();
int jindex = name.indexOf(sjar);
int nlen = name.length();
boolean isJar = jindex == nlen - 4 || jindex == nlen - 6;
try
{
if (isJar)
build(fobj, true);
else
{
// loop thru folder
for (FileObject childFolder : fobj.getChildren())
{
boolean isAlsoJar = childFolder.getName().getURI().endsWith(sjar);
// ignore anything that is not a folder or a
// jar
if (!isAlsoJar && childFolder.getType() != FileType.FOLDER)
{
continue;
}
// ignore any subversion or CVS directories
if (childFolder.getName().getBaseName().equalsIgnoreCase(".svn"))
{
continue;
} else if (childFolder.getName().getBaseName().equalsIgnoreCase(".cvs"))
{
continue;
}
try
{
build(childFolder, isAlsoJar);
} catch (KettleConfigException e)
{
log.logError(Plugin.PLUGIN_LOADER, e.getMessage());
continue;
}
}
}
} catch (FileSystemException e)
{
log.logError(Plugin.PLUGIN_LOADER, e.getMessage());
continue;
} catch (KettleConfigException e)
{
log.logError(Plugin.PLUGIN_LOADER, e.getMessage());
continue;
}
} else
{
log.logDetailed(Plugin.PLUGIN_LOADER, fobj + " does not exist.");
}
} catch (Exception e)
{
throw new KettleConfigException(e);
}
}
}
}
@SuppressWarnings("unchecked")
public <E extends Plugin> Collection<E> getDefinedPlugins(Class<E> pluginType)
throws KettleConfigException
{
Class type = pluginType == JobPlugin.class ? Job.class : Step.class;
for (Map.Entry<Class<? extends Annotation>, Set<? extends Plugin>> entry : this.plugins.entrySet())
{
if (entry.getKey() == type)
{
return (Collection<E>) entry.getValue();
}
}
throw new KettleConfigException("Invalid plugin type: " + type);
}
private void build(FileObject parent, boolean isJar) throws KettleConfigException
{
try
{
FileObject xml = null;
if (isJar)
{
FileObject exploded = explodeJar(parent);
// try reading annotations first ...
ResolverUtil<Plugin> resPlugins = new ResolverUtil<Plugin>();
// grab all jar files not part of the "lib"
File fparent = new File(exploded.getURL().getFile());
File[] files = fparent.listFiles(new JarNameFilter());
URL[] classpath = new URL[files.length];
for (int i = 0; i < files.length; i++)
classpath[i] = files[i].toURI().toURL();
ClassLoader cl = new PDIClassLoader(classpath, Thread.currentThread().getContextClassLoader());
resPlugins.setClassLoader(cl);
for (FileObject couldBeJar : exploded.getChildren())
{
if (couldBeJar.getName().getExtension().equals(JAR))
resPlugins.loadImplementationsInJar(Const.EMPTY_STRING, new File(couldBeJar.getURL().getFile()),
tests.values().toArray(new ResolverUtil.Test[2]));
}
for (Class<? extends Plugin> match : resPlugins.getClasses())
{
for (Class<? extends Annotation> cannot : tests.keySet())
{
Annotation annot = match.getAnnotation(cannot);
if (annot != null)
fromAnnotation(annot, exploded, match);
}
}
// and we also read from the xml if present
xml = exploded.getChild(Plugin.PLUGIN_XML_FILE);
if (xml == null || !xml.exists())
return;
parent = exploded;
} else
xml = parent.getChild(Plugin.PLUGIN_XML_FILE);
// then read the xml if it is there
if (xml != null && xml.isReadable())
fromXML(xml, parent);
} catch (Exception e)
{
throw new KettleConfigException(e);
}
// throw new KettleConfigException("Unable to read plugin.xml from " +
// parent);
}
private void fromXML(FileObject xml, FileObject parent) throws IOException, ClassNotFoundException,
ParserConfigurationException, SAXException
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xml.getContent().getInputStream());
Node plugin = XMLHandler.getSubNode(doc, Plugin.PLUGIN);
String id = XMLHandler.getTagAttribute(plugin, Plugin.ID);
String description = XMLHandler.getTagAttribute(plugin, Plugin.DESCRIPTION);
String iconfile = XMLHandler.getTagAttribute(plugin, Plugin.ICONFILE);
String tooltip = XMLHandler.getTagAttribute(plugin, Plugin.TOOLTIP);
String classname = XMLHandler.getTagAttribute(plugin, Plugin.CLASSNAME);
String category = XMLHandler.getTagAttribute(plugin, Plugin.CATEGORY);
String errorHelpfile = XMLHandler.getTagAttribute(plugin, Plugin.ERRORHELPFILE);
// Localized categories
Node locCatsNode = XMLHandler.getSubNode(plugin, Plugin.LOCALIZED_CATEGORY);
int nrLocCats = XMLHandler.countNodes(locCatsNode, Plugin.CATEGORY);
Map<String, String> localizedCategories = new Hashtable<String, String>();
for (int j = 0; j < nrLocCats; j++)
{
Node locCatNode = XMLHandler.getSubNodeByNr(locCatsNode, Plugin.CATEGORY, j);
String locale = XMLHandler.getTagAttribute(locCatNode, Plugin.LOCALE);
String locCat = XMLHandler.getNodeValue(locCatNode);
if (!Const.isEmpty(locale) && !Const.isEmpty(locCat))
{
localizedCategories.put(locale.toLowerCase(), locCat);
}
}
// Localized descriptions
Node locDescsNode = XMLHandler.getSubNode(plugin, Plugin.LOCALIZED_DESCRIPTION);
int nrLocDescs = XMLHandler.countNodes(locDescsNode, Plugin.DESCRIPTION);
Map<String, String> localizedDescriptions = new Hashtable<String, String>();
for (int j = 0; j < nrLocDescs; j++)
{
Node locDescNode = XMLHandler.getSubNodeByNr(locDescsNode, Plugin.DESCRIPTION, j);
String locale = XMLHandler.getTagAttribute(locDescNode, Plugin.LOCALE);
String locDesc = XMLHandler.getNodeValue(locDescNode);
if (!Const.isEmpty(locale) && !Const.isEmpty(locDesc))
{
localizedDescriptions.put(locale.toLowerCase(), locDesc);
}
}
// Localized tooltips
Node locTipsNode = XMLHandler.getSubNode(plugin, Plugin.LOCALIZED_TOOLTIP);
int nrLocTips = XMLHandler.countNodes(locTipsNode, Plugin.TOOLTIP);
Map<String, String> localizedTooltips = new Hashtable<String, String>();
for (int j = 0; j < nrLocTips; j++)
{
Node locTipNode = XMLHandler.getSubNodeByNr(locTipsNode, Plugin.TOOLTIP, j);
String locale = XMLHandler.getTagAttribute(locTipNode, Plugin.LOCALE);
String locTip = XMLHandler.getNodeValue(locTipNode);
if (!Const.isEmpty(locale) && !Const.isEmpty(locTip))
{
localizedTooltips.put(locale.toLowerCase(), locTip);
}
}
Node libsnode = XMLHandler.getSubNode(plugin, Plugin.LIBRARIES);
int nrlibs = XMLHandler.countNodes(libsnode, Plugin.LIBRARY);
String jarfiles[] = new String[nrlibs];
for (int j = 0; j < nrlibs; j++)
{
Node libnode = XMLHandler.getSubNodeByNr(libsnode, Plugin.LIBRARY, j);
String jarfile = XMLHandler.getTagAttribute(libnode, Plugin.NAME);
jarfiles[j] = parent.resolveFile(jarfile).getURL().getFile();
// System.out.println("jar files=" + jarfiles[j]);
}
// convert to URL
List<URL> classpath = new ArrayList<URL>();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
new FileSystemResourceLoader());
for (int i = 0; i < jarfiles.length; i++)
{
try
{
Resource[] paths = resolver.getResources(jarfiles[i]);
for (Resource path : paths)
{
classpath.add(path.getURL());
}
} catch (IOException e)
{
e.printStackTrace();
continue;
}
}
URL urls[] = classpath.toArray(new URL[classpath.size()]);
URLClassLoader cl = new PDIClassLoader(urls, Thread.currentThread().getContextClassLoader());
String iconFilename = parent.resolveFile(iconfile).getURL().getFile();
Class<?> pluginClass = cl.loadClass(classname);
// here we'll have to use some reflection in order to decide
// which object we should instantiate!
if (JobEntryInterface.class.isAssignableFrom(pluginClass))
{
@SuppressWarnings("unchecked")
Set<JobPlugin> jps = (Set<JobPlugin>) this.plugins.get(Job.class);
JobPlugin plg = new JobPlugin(Plugin.TYPE_PLUGIN, id, description, tooltip, parent.getName()
.getURI(), jarfiles, iconFilename, classname);
plg.setClassLoader(cl);
jps.add(plg);
} else
{
String errorHelpFileFull = errorHelpfile;
String path = parent.getName().getURI();
if (!Const.isEmpty(errorHelpfile))
errorHelpFileFull = (path == null) ? errorHelpfile : path + Const.FILE_SEPARATOR
+ errorHelpfile;
StepPlugin sp = new StepPlugin(Plugin.TYPE_PLUGIN, new String[] { id }, description, tooltip,
path, jarfiles, iconFilename, classname, category, errorHelpFileFull);
// Add localized information too...
sp.setLocalizedCategories(localizedCategories);
sp.setLocalizedDescriptions(localizedDescriptions);
sp.setLocalizedTooltips(localizedTooltips);
@SuppressWarnings("unchecked")
Set<StepPlugin> sps = (Set<StepPlugin>) this.plugins.get(Step.class);
sps.add(sp);
}
}
private void fromAnnotation(Annotation annot, FileObject directory, Class<?> match) throws IOException
{
Class type = annot.annotationType();
if (type == Job.class)
{
Job jobAnnot = (Job) annot;
String[] libs = getLibs(directory);
@SuppressWarnings("unchecked")
Set<JobPlugin> jps = (Set<JobPlugin>) this.plugins.get(Job.class);
JobPlugin pg = new JobPlugin(Plugin.TYPE_PLUGIN, jobAnnot.id(), jobAnnot.type().getDescription(),
jobAnnot.tooltip(), directory.getURL().getFile(), libs, jobAnnot.image(), match.getName());
pg.setClassLoader(match.getClassLoader());
jps.add(pg);
} else if (type == Step.class)
{
Step jobAnnot = (Step) annot;
String[] libs = getLibs(directory);
@SuppressWarnings("unchecked")
Set<StepPlugin> jps = (Set<StepPlugin>) this.plugins.get(Step.class);
StepPlugin pg = new StepPlugin(Plugin.TYPE_PLUGIN, jobAnnot.name(), jobAnnot.description(),
jobAnnot.tooltip(), directory.getURL().getFile(), libs, jobAnnot.image(),
match.getName(), jobAnnot.categoryDescription(), Const.EMPTY_STRING);
pg.setClassLoader(match.getClassLoader());
jps.add(pg);
}
}
private String[] getLibs(FileObject pluginLocation) throws IOException
{
File[] jars = new File(pluginLocation.getURL().getFile()).listFiles(new JarNameFilter());
String[] libs = new String[jars.length];
for (int i = 0; i < jars.length; i++)
libs[i] = jars[i].getPath();
Arrays.sort(libs);
int idx = Arrays.binarySearch(libs, DEFAULT_LIB);
String[] retVal = null;
if (idx < 0) // does not contain
{
String[] completeLib = new String[libs.length + 1];
System.arraycopy(libs, 0, completeLib, 0, libs.length);
completeLib[libs.length] = pluginLocation.resolveFile(DEFAULT_LIB).getURL().getFile();
retVal = completeLib;
} else
retVal = libs;
return retVal;
}
/**
* "Deploys" the plugin jar file.
*
* @param parent
* @return
* @throws FileSystemException
*/
private FileObject explodeJar(FileObject parent) throws FileSystemException
{
// By Alex, 7/13/07
// Since the JVM does not support nested jars and
// URLClassLoaders, we have to hack it
// see
// We do so by exploding the jar, sort of like deploying it
FileObject dest = VFS.getManager().resolveFile(Const.getKettleDirectory() + File.separator + WORK_DIR);
dest.createFolder();
FileObject destFile = dest.resolveFile(parent.getName().getBaseName());
if (!destFile.exists())
destFile.createFolder();
else
// delete children
for (FileObject child : destFile.getChildren())
child.delete(new AllFileSelector());
// force VFS to treat it as a jar file explicitly with children,
// etc. and copy
destFile.copyFrom(!(parent instanceof JarFileObject) ? VFS.getManager().resolveFile(
JAR + ":" + parent.getName().getURI()) : parent, new AllFileSelector());
return destFile;
}
private static class JarNameFilter implements FilenameFilter
{
public boolean accept(File dir, String name)
{
//return patt.matcher(name).matches();
return name.endsWith(JAR) || name.endsWith(".zip");
}
}
} |
package org.pentaho.di.trans.steps.sort;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleFileException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.util.StringUtil;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Sort the rows in the input-streams based on certain criteria
*
* @author Matt
* @since 29-apr-2003
*/
public class SortRows extends BaseStep implements StepInterface
{
private SortRowsMeta meta;
private SortRowsData data;
public SortRows(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
meta=(SortRowsMeta)getStepMeta().getStepMetaInterface();
data=(SortRowsData)stepDataInterface;
}
private boolean addBuffer(RowMetaInterface rowMeta, Object[] r)
{
if (r!=null)
{
data.buffer.add( r ); // Save row
}
if (data.files.size()==0 && r==null) // No more records: sort buffer
{
quickSort(data.buffer);
}
// time to write to disk: buffer is full!
if ( data.buffer.size()==meta.getSortSize() // Buffer is full: sort & dump to disk
|| (data.files.size()>0 && r==null && data.buffer.size()>0) // No more records: join from disk
)
{
// First sort the rows in buffer[]
quickSort(data.buffer);
// Then write them to disk...
DataOutputStream dos;
GZIPOutputStream gzos;
int p;
Object[] previousRow = null;
try
{
FileObject fileObject=KettleVFS.createTempFile(meta.getPrefix(), ".tmp", StringUtil.environmentSubstitute(meta.getDirectory()));
data.files.add(fileObject); // Remember the files!
OutputStream outputStream = fileObject.getContent().getOutputStream();
if (meta.getCompress())
{
gzos = new GZIPOutputStream(new BufferedOutputStream(outputStream));
dos=new DataOutputStream(gzos);
}
else
{
dos = new DataOutputStream(outputStream);
gzos = null;
}
// Just write the data, nothing else
if (meta.isOnlyPassingUniqueRows())
{
int index=0;
while (index<data.buffer.size())
{
Object[] row = data.buffer.get(index);
if (previousRow!=null)
{
int result = data.outputRowMeta.compare(row, previousRow, data.fieldnrs);
if (result==0)
{
data.buffer.remove(index); // remove this duplicate element as requested
if (log.isRowLevel()) logRowlevel("Duplicate row removed: "+data.outputRowMeta.getString(row));
}
else
{
index++;
}
}
else
{
index++;
}
previousRow = row;
}
}
// How many records do we have left?
data.bufferSizes.add( data.buffer.size() );
for (p=0;p<data.buffer.size();p++)
{
rowMeta.writeData(dos, data.buffer.get(p));
}
// Clear the list
data.buffer.clear();
// Close temp-file
dos.close(); // close data stream
if (gzos != null)
{
gzos.close(); // close gzip stream
}
outputStream.close(); // close file stream
}
catch(Exception e)
{
logError("Error processing temp-file: "+e.toString());
return false;
}
data.getBufferIndex=0;
}
return true;
}
private Object[] getBuffer() throws KettleValueException
{
int i, f;
int smallest;
Object[] r1, r2;
Object[] retval;
// Open all files at once and read one row from each file...
if (data.files.size()>0 && ( data.dis.size()==0 || data.fis.size()==0 ))
{
logBasic("Opening "+data.files.size()+" tmp-files...");
try
{
for (f=0;f<data.files.size() && !isStopped();f++)
{
FileObject fileObject = (FileObject)data.files.get(f);
String filename = KettleVFS.getFilename(fileObject);
if (log.isDetailed()) logDetailed("Opening tmp-file: ["+filename+"]");
InputStream fi=fileObject.getContent().getInputStream();
DataInputStream di;
data.fis.add(fi);
if (meta.getCompress())
{
GZIPInputStream gzfi = new GZIPInputStream(new BufferedInputStream(fi));
di =new DataInputStream(gzfi);
data.gzis.add(gzfi);
}
else
{
di=new DataInputStream(fi);
}
data.dis.add(di);
// How long is the buffer?
int buffersize=data.bufferSizes.get(f);
if (log.isDetailed()) logDetailed("["+filename+"] expecting "+buffersize+" rows...");
if (buffersize>0)
{
// Read a row from each temp-file
data.rowbuffer.add( data.outputRowMeta.readData(di) ); // new row from input stream
}
}
}
catch(Exception e)
{
logError("Error reading back tmp-files : "+e.toString());
logError(Const.getStackTracker(e));
}
}
if (data.files.size()==0)
{
if (data.getBufferIndex<data.buffer.size())
{
retval=(Object[])data.buffer.get(data.getBufferIndex);
data.getBufferIndex++;
}
else
{
retval=null;
}
}
else
{
if (data.rowbuffer.size()==0)
{
retval=null;
}
else
{
// We now have "filenr" rows waiting: which one is the smallest?
if (log.isRowLevel())
{
for (i=0;i<data.rowbuffer.size() && !isStopped();i++)
{
Object[] b = (Object[])data.rowbuffer.get(i);
logRowlevel("--BR#"+i+": "+data.outputRowMeta.getString(b));
}
}
smallest=0;
r1=(Object[])data.rowbuffer.get(smallest);
for (f=1;f<data.rowbuffer.size() && !isStopped();f++)
{
r2=(Object[])data.rowbuffer.get(f);
if (r2!=null && data.outputRowMeta.compare(r1, r2, data.fieldnrs)>0)
{
smallest=f;
r1=(Object[])data.rowbuffer.get(smallest);
}
}
retval=r1;
data.rowbuffer.remove(smallest);
if (log.isRowLevel()) logRowlevel("Smallest row selected on ["+smallest+"] : "+retval);
// now get another Row for position smallest
FileObject file = (FileObject)data.files.get(smallest);
DataInputStream di = (DataInputStream)data.dis.get(smallest);
InputStream fi = (InputStream)data.fis.get(smallest);
GZIPInputStream gzfi = (meta.getCompress()) ? (GZIPInputStream)data.gzis.get(smallest) : null;
try
{
data.rowbuffer.add(smallest, data.outputRowMeta.readData(di));
}
catch(KettleFileException fe) // empty file or EOF mostly
{
try
{
di.close();
fi.close();
if (gzfi != null) gzfi.close();
file.delete();
}
catch(IOException e)
{
logError("Unable to close/delete file #"+smallest+" --> "+file.toString());
setErrors(1);
stopAll();
return null;
}
data.files.remove(smallest);
data.dis.remove(smallest);
data.fis.remove(smallest);
if (gzfi != null) data.gzis.remove(smallest);
}
}
}
return retval;
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
boolean err=true;
int i;
Object[] r=getRow(); // get row from rowset, wait for our turn, indicate busy!
// initialize
if (first && r!=null)
{
first=false;
data.fieldnrs=new int[meta.getFieldName().length];
for (i=0;i<meta.getFieldName().length;i++)
{
data.fieldnrs[i]=getInputRowMeta().indexOfValue( meta.getFieldName()[i] );
if (data.fieldnrs[i]<0)
{
logError("Sort field ["+meta.getFieldName()[i]+"] not found!");
setOutputDone();
return false;
}
}
// Metadata
data.outputRowMeta = (RowMetaInterface)getInputRowMeta().clone();
meta.getFields(data.outputRowMeta, getStepname(), null);
}
err=addBuffer(getInputRowMeta(), r);
if (!err)
{
setOutputDone(); // signal receiver we're finished.
return false;
}
if (r==null) // no more input to be expected...
{
// Now we can start the output!
r=getBuffer();
Object[] previousRow = null;
while (r!=null && !isStopped())
{
if (log.isRowLevel()) logRowlevel("Read row: "+r.toString());
// Do another verification pass for unique rows...
if (meta.isOnlyPassingUniqueRows())
{
if (previousRow!=null)
{
// See if this row is the same as the previous one as far as the keys are concerned.
// If so, we don't put forward this row.
int result = data.outputRowMeta.compare(r, previousRow, data.fieldnrs);
if (result!=0)
{
putRow(data.outputRowMeta, r); // copy row to possible alternate rowset(s).
}
}
else
{
putRow(data.outputRowMeta, r); // copy row to possible alternate rowset(s).
}
previousRow = r;
}
else
{
putRow(data.outputRowMeta, r); // copy row to possible alternate rowset(s).
}
r=getBuffer();
}
setOutputDone(); // signal receiver we're finished.
return false;
}
if (checkFeedback(linesRead)) logBasic("Linenr "+linesRead);
return true;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(SortRowsMeta)smi;
data=(SortRowsData)sdi;
if (super.init(smi, sdi))
{
data.buffer = new ArrayList<Object[]>(meta.getSortSize());
// Add init code here.
if (meta.getSortSize()>0)
{
data.rowbuffer=new ArrayList<Object[]>(meta.getSortSize());
}
else
{
data.rowbuffer=new ArrayList<Object[]>();
}
return true;
}
return false;
}
// Run is were the action happens!
public void run()
{
try
{
logBasic("Starting to run...");
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError("Unexpected error : "+e.toString());
logError(Const.getStackTracker(e));
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
/** Sort the entire vector, if it is not empty
*/
public void quickSort(List<Object[]> elements)
{
if (log.isDetailed()) logDetailed("Starting quickSort algorithm...");
if (elements.size()>0)
{
Collections.sort(elements, new Comparator<Object[]>()
{
public int compare(Object[] o1, Object[] o2)
{
Object[] r1 = (Object[]) o1;
Object[] r2 = (Object[]) o2;
try
{
return data.outputRowMeta.compare(r1, r2, data.fieldnrs);
}
catch(KettleValueException e)
{
logError("Error comparing rows: "+e.toString());
return 0;
}
}
}
);
}
if (log.isDetailed()) logDetailed("QuickSort algorithm has finished.");
}
} |
package gov.va.escreening.service;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import gov.va.escreening.dto.VeteranAssessmentProgressDto;
import gov.va.escreening.dto.ae.AssessmentRequest;
import gov.va.escreening.entity.*;
import gov.va.escreening.repository.SurveyAttemptRepository;
import gov.va.escreening.repository.VeteranAssessmentRepository;
import gov.va.escreening.repository.VeteranAssessmentSurveyRepository;
import java.text.NumberFormat;
import java.util.*;
import java.util.Map.Entry;
import gov.va.escreening.util.ReportsUtil;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Transactional
@Service
public class VeteranAssessmentSurveyServiceImpl implements
VeteranAssessmentSurveyService {
private static final Logger logger = LoggerFactory
.getLogger(VeteranAssessmentSurveyServiceImpl.class);
@Autowired
private VeteranAssessmentSurveyRepository veteranAssessmentSurveyRepository;
@Autowired
private VeteranAssessmentRepository veteranAssessmentRepository;
@Resource(type = SurveyAttemptRepository.class)
SurveyAttemptRepository sar;
@Transactional(readOnly = true)
@Override
public List<Survey> getSurveys(Integer veteranAssessmentId) {
return veteranAssessmentSurveyRepository
.findSurveyListByVeteranAssessmentId(veteranAssessmentId);
}
@Override
public void updateProgress(int veteranAssessmentId, long startTime) {
logger.debug("updateProgress");
// Run the SQL and get the list of counts.
List<Object[]> resultList = veteranAssessmentSurveyRepository
.calculateProgress(veteranAssessmentId);
// Update the fields accordingly and save to database.
int runningTotalResponses = 0;
int runningTotalQuestions = 0;
for (Object[] row : resultList) {
int surveyId = Integer.valueOf(row[0].toString());
int countOfTotalQuestions = Integer.valueOf(row[1].toString());
int countOfTotalResponses = Integer.valueOf(row[2].toString());
gov.va.escreening.entity.VeteranAssessmentSurvey veteranAssessmentSurvey = veteranAssessmentSurveyRepository
.getByVeteranAssessmentIdAndSurveyId(veteranAssessmentId,
surveyId);
veteranAssessmentSurvey
.setTotalQuestionCount(countOfTotalQuestions);
veteranAssessmentSurvey
.setTotalResponseCount(countOfTotalResponses);
veteranAssessmentSurveyRepository.update(veteranAssessmentSurvey);
runningTotalResponses += countOfTotalResponses;
runningTotalQuestions += countOfTotalQuestions;
}
updateVeteranAssessmentProgress(veteranAssessmentId, startTime,
runningTotalResponses, runningTotalQuestions);
}
@Override
public void updateProgress(VeteranAssessment va, AssessmentRequest req,
Survey survey, List<VeteranAssessmentMeasureVisibility> visList) {
int total = 0;
int answered = 0;
// va.getSurveyMeasureResponseList()
Set<Integer> answeredMeasures = new HashSet<Integer>();
for (SurveyMeasureResponse resp : va.getSurveyMeasureResponseList()) {
if (resp.getBooleanValue() == null || resp.getBooleanValue()) {
answeredMeasures.add(resp.getMeasure().getMeasureId());
if (resp.getMeasure().getParent() != null) {
answeredMeasures.add(resp.getMeasure().getParent().getMeasureId());
}
}
}
Set<Integer> invisibleMeasureList = new HashSet<Integer>();
for (VeteranAssessmentMeasureVisibility vis : visList) {
if (vis.getIsVisible() != null && !vis.getIsVisible()) {
invisibleMeasureList.add(vis.getMeasure().getMeasureId());
}
}
// First calculate total measures
List<SurveyPage> pageList = survey.getSurveyPageList();
for (SurveyPage sp : pageList) {
for (Measure m : sp.getMeasures()) {
if (!invisibleMeasureList.contains(m.getMeasureId())) {
if (m.getMeasureType().getMeasureTypeId() != 8 && (m.getMeasureType().getMeasureTypeId() == 4 ||
m.getChildren() == null || m.getChildren().isEmpty())) {
total++;
if (answeredMeasures.contains(m.getMeasureId())) {
answered++;
}
} else {
total += m.getChildren().size();
for (Measure c : m.getChildren()) {
if (answeredMeasures.contains(c.getMeasureId())) {
answered++;
}
}
}
}
}
}
gov.va.escreening.entity.VeteranAssessmentSurvey veteranAssessmentSurvey = veteranAssessmentSurveyRepository
.getByVeteranAssessmentIdAndSurveyId(
va.getVeteranAssessmentId(), survey.getSurveyId());
veteranAssessmentSurvey.setTotalQuestionCount(total);
veteranAssessmentSurvey.setTotalResponseCount(answered);
veteranAssessmentSurveyRepository.update(veteranAssessmentSurvey);
updateVeteranAssessmentProgress(va, req);
}
@Override
@Transactional(readOnly = true)
public Map<Integer, Map<String, String>> calculateAvgTimePerSurvey(Map<String, Object> requestData) {
List<Integer> clinics = (List<Integer>) requestData.get(ReportsUtil.CLINIC_ID_LIST);
final DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy");
final LocalDate fromDate = dtf.parseLocalDate(requestData.get(ReportsUtil.FROMDATE).toString());
final LocalDate toDate = dtf.parseLocalDate(requestData.get(ReportsUtil.TODATE).toString());
List<VeteranAssessmentSurvey> vasLst = veteranAssessmentSurveyRepository.findByClinicAndDateRange(clinics, fromDate.toDate(), toDate.toDate());
// group these by surveys
Multimap<Survey, VeteranAssessmentSurvey> surveyMap = ArrayListMultimap.create();
for (VeteranAssessmentSurvey vas : vasLst) {
surveyMap.put(vas.getSurvey(), vas);
}
// find average
Map<Integer, Map<String, String>> avgMap = Maps.newHashMap();
for (Survey s : surveyMap.keySet()) {
avgMap.put(s.getSurveyId(), findAvgElapsedTime(surveyMap.get(s)));
}
return avgMap;
}
private Map<String, String> findAvgElapsedTime(Collection<VeteranAssessmentSurvey> veteranAssessmentSurveys) {
Period totalPeriod = Period.seconds(0);
int totalSurveyAttempts = 0;
for (VeteranAssessmentSurvey vas : veteranAssessmentSurveys) {
List<SurveyAttempt> surveyAttempts = vas.getSurveyAttemptList();
if (surveyAttempts != null) {
totalSurveyAttempts += surveyAttempts.size();
for (SurveyAttempt sa : surveyAttempts) {
DateTime dtStart = new DateTime(sa.getStartDate().getTime());
DateTime dtEnd = new DateTime(sa.getEndDate().getTime());
Period period = new Period(dtStart, dtEnd);
totalPeriod = period.plus(totalPeriod);
}
}
}
// calculate the avg
long secs = totalPeriod.toStandardDuration().getStandardSeconds();
NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
String standardSecs=nf.format(secs / totalSurveyAttempts);
double avgTotalSecs = totalSurveyAttempts == 0 ? 0.00 : Double.parseDouble(standardSecs);
int avgMin = (int) avgTotalSecs / 60;
int avgSec = (int) avgTotalSecs % 60;
Map<String, String> m = Maps.newHashMap();
m.put("MODULE_TOTAL_TIME", String.valueOf(totalSurveyAttempts));
m.put("MODULE_AVG_SEC", String.format("%02d",avgSec));
m.put("MODULE_AVG_MIN", String.format("%02d",avgMin));
m.put("AVG_TIME_AS_STRING", String.format("%sm %ss n=%s", avgMin, avgSec, totalSurveyAttempts));
return m;
}
private void updateVeteranAssessmentProgress(VeteranAssessment va,
AssessmentRequest assessmentRequest) {
int total = 0;
int answered = 0;
for (VeteranAssessmentSurvey vas : va.getVeteranAssessmentSurveyList()) {
if (vas.getTotalQuestionCount() != null) {
total += vas.getTotalQuestionCount();
}
if (vas.getTotalResponseCount() != null) {
answered += vas.getTotalResponseCount();
}
// add the timing it took to complete this survey
addSurveyAttempt(vas, assessmentRequest);
}
int percentCompleted = (int) ((float) answered / total * 100);
va.setPercentComplete(percentCompleted);
int durationCurrent = getAssessmentProgressDurationInminutes(assessmentRequest.getAssessmentStartTime());
Integer previousDuration = va.getDuration();
if (previousDuration == null) {
previousDuration = 0;
}
va.setDuration(previousDuration + durationCurrent);
va.setDateUpdated(new Date());
veteranAssessmentRepository.update(va);
}
private void addSurveyAttempt(VeteranAssessmentSurvey vas, AssessmentRequest assessmentRequest) {
Long startTs = assessmentRequest.getModuleStartTime(vas.getSurvey().getSurveyId());
if (startTs != null) {
SurveyAttempt sa = new SurveyAttempt();
sa.setVeteranAssessmentSurvey(vas);
sa.setStartDate(new Date(startTs));
sa.setEndDate(new Date());
sa.setDateCreated(new Date());
sar.update(sa);
}
}
private void updateVeteranAssessmentProgress(int veteranAssessmentId,
long startTime, int countOfTotalResponses, int countOfTotalQuestions) {
VeteranAssessment va = veteranAssessmentRepository
.findOne(veteranAssessmentId);
// determine the percentage completed
int percentCompleted = (int) ((float) countOfTotalResponses
/ countOfTotalQuestions * 100);
va.setPercentComplete(percentCompleted);
int durationCurrent = getAssessmentProgressDurationInminutes(startTime);
Integer previousDuration = va.getDuration();
if (previousDuration == null) {
previousDuration = 0;
}
va.setDuration(previousDuration + durationCurrent);
// determine the duration this veteran is on this assessment (in
// minutes)
va.setDateUpdated(new Date());
veteranAssessmentRepository.update(va);
}
private int getAssessmentProgressDurationInminutes(long sessionCreationTime) {
DateTime ft = new DateTime();
int minutesOfHour = ft.minus(sessionCreationTime).getMinuteOfHour();
return minutesOfHour;
}
@Override
public Boolean doesVeteranAssessmentContainSurvey(int veteranAssessmentId,
int surveyId) {
logger.trace("doesVeteranAssessmentContainSurvey");
List<VeteranAssessmentSurvey> assignedSurveys = veteranAssessmentSurveyRepository
.findSurveyBySurveyAssessment(veteranAssessmentId, surveyId);
if (assignedSurveys.size() > 0) {
return true;
}
return false;
}
@Override
public List<VeteranAssessmentProgressDto> getProgress(
int veteranAssessmentId) {
List<VeteranAssessmentSurvey> veteranAssessmentSurveyList = veteranAssessmentSurveyRepository
.forVeteranAssessmentId(veteranAssessmentId);
LinkedHashMap<Integer, VeteranAssessmentProgressDto> map = new LinkedHashMap<Integer, VeteranAssessmentProgressDto>();
for (VeteranAssessmentSurvey veteranAssessmentSurvey : veteranAssessmentSurveyList) {
Integer surveySectionId = veteranAssessmentSurvey.getSurvey()
.getSurveySection().getSurveySectionId();
VeteranAssessmentProgressDto veteranAssessmentProgressDto = null;
if (map.containsKey(surveySectionId)) {
veteranAssessmentProgressDto = map.get(surveySectionId);
} else {
veteranAssessmentProgressDto = new VeteranAssessmentProgressDto();
veteranAssessmentProgressDto
.setVeteranAssessmentId(veteranAssessmentId);
veteranAssessmentProgressDto
.setSurveySectionId(veteranAssessmentSurvey.getSurvey()
.getSurveySection().getSurveySectionId());
veteranAssessmentProgressDto
.setSurveySectionName(veteranAssessmentSurvey
.getSurvey().getSurveySection().getName());
veteranAssessmentProgressDto.setTotalQuestionCount(0);
veteranAssessmentProgressDto.setTotalResponseCount(0);
veteranAssessmentProgressDto.setPercentComplete(0);
map.put(surveySectionId, veteranAssessmentProgressDto);
}
int totalQuestionCount = veteranAssessmentProgressDto
.getTotalQuestionCount();
if (veteranAssessmentSurvey.getTotalQuestionCount() != null) {
totalQuestionCount += veteranAssessmentSurvey
.getTotalQuestionCount();
}
int totalResponseCount = veteranAssessmentProgressDto
.getTotalResponseCount();
if (veteranAssessmentSurvey.getTotalResponseCount() != null) {
totalResponseCount += veteranAssessmentSurvey
.getTotalResponseCount();
}
veteranAssessmentProgressDto
.setTotalQuestionCount(totalQuestionCount);
veteranAssessmentProgressDto
.setTotalResponseCount(totalResponseCount);
if (totalQuestionCount > 0) {
veteranAssessmentProgressDto
.setPercentComplete(Math
.round(((float) totalResponseCount / (float) totalQuestionCount) * 100));
}
}
List<VeteranAssessmentProgressDto> results = null;
if (map != null) {
results = new ArrayList<VeteranAssessmentProgressDto>();
Iterator<Entry<Integer, VeteranAssessmentProgressDto>> it = map
.entrySet().iterator();
while (it.hasNext()) {
results.add(it.next().getValue());
}
}
return results;
}
} |
package eu.scasefp7.eclipse.core.ui.preferences;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.IPreferenceNode;
import org.eclipse.jface.preference.IPreferencePage;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.preference.PreferenceManager;
import org.eclipse.jface.preference.PreferenceNode;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Link;
import org.eclipse.ui.IWorkbenchPropertyPage;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
import eu.scasefp7.eclipse.core.ui.Activator;
/**
* Based on Berthold Daum's approach, but using project-scoped preference store
*
* @author Berthold Daum
*/
public abstract class FieldEditorOverlayPage extends FieldEditorPreferencePage implements IWorkbenchPropertyPage {
// Stores all created field editors
private List<FieldEditor> editors = new ArrayList<FieldEditor>();
// Stores owning element of properties
private IAdaptable element;
// Additional buttons for property pages
private Button useProjectSettingsButton;
// Link to configure workspace settings
private Link configureLink;
// Overlay preference store for property pages
private IPreferenceStore overlayStore;
// The image descriptor of this pages title image
private ImageDescriptor image;
// Cache for page id
private String pageId;
/**
* Constructor
*
* @param style - layout style
* @wbp.parser.constructor
*/
public FieldEditorOverlayPage(int style) {
super(style);
}
/**
* Constructor
*
* @param title - title string
* @param style - layout style
*/
public FieldEditorOverlayPage(String title, int style) {
super(title, style);
}
/**
* Constructor
*
* @param title - title string
* @param image - title image
* @param style - layout style
*/
public FieldEditorOverlayPage(String title, ImageDescriptor image, int style) {
super(title, image, style);
this.image = image;
}
/**
* Returns the id of the current preference page as defined in plugin.xml
* Subclasses must implement.
*
* @return - the qualifier
*/
protected abstract String getPageId();
/**
* Returns the id of the preference qualifier used to store JFace preferences.
* Subclasses must implement.
*
* @return - the qualifier
*/
protected abstract String getPreferenceQualifier();
/**
* Receives the object that owns the properties shown in this property page.
*
* @see org.eclipse.ui.IWorkbenchPropertyPage#setElement(org.eclipse.core.runtime.IAdaptable)
*/
public void setElement(IAdaptable element) {
this.element = element;
}
/**
* Delivers the object that owns the properties shown in this property page.
*
* @see org.eclipse.ui.IWorkbenchPropertyPage#getElement()
*/
public IAdaptable getElement() {
return element;
}
/**
* Delivers the project that owns the properties shown in this property page.
* @return project
*/
public IProject getProject() {
IAdaptable element = getElement();
IProject adapter = (IProject) element.getAdapter(IProject.class);
return adapter;
}
/**
* Returns true if this instance represents a property page
*
* @return - true for property pages, false for preference pages
*/
public boolean isPropertyPage() {
return getElement() != null;
}
/**
* We override the addField method. This allows us to store each field
* editor added by subclasses in a list for later processing.
*
* @see org.eclipse.jface.preference.FieldEditorPreferencePage#addField(org.eclipse.jface.preference.FieldEditor)
*/
protected void addField(FieldEditor editor) {
editors.add(editor);
super.addField(editor);
}
/**
* We override the createControl method. In case of property pages we create
* a new PropertyStore as local preference store. After all control have
* been create, we enable/disable these controls.
*
* @see org.eclipse.jface.preference.PreferencePage#createControl()
*/
@SuppressWarnings("javadoc")
public void createControl(Composite parent) {
// Special treatment for property pages
if (isPropertyPage()) {
// Cache the page id
pageId = getPageId();
// Create an overlay preference store and fill it with properties
IProject project = getProject();
if(project != null)
{
ProjectScope ps = new ProjectScope(getProject());
ScopedPreferenceStore scoped = new ScopedPreferenceStore(ps, getPreferenceQualifier());
scoped.setSearchContexts(new IScopeContext[] { ps, InstanceScope.INSTANCE });
overlayStore = scoped;
// Set overlay store as current preference store
}
}
super.createControl(parent);
// Update state of all subclass controls
if (isPropertyPage()) {
updateFieldEditors();
}
}
/**
* We override the createContents method. In case of property pages we
* insert two radio buttons at the top of the page.
*
* @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
if (isPropertyPage()) {
createSelectionGroup(parent);
}
return super.createContents(parent);
}
/**
* Creates and initializes a selection group with two choice buttons and one
* push button.
*
* @param parent - the parent composite
*/
private void createSelectionGroup(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(2, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
comp.setLayout(layout);
comp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
useProjectSettingsButton = createSettingsButton(comp, "Use pr&oject-specific settings");
configureLink = createLink(comp, "&Configure Workspace Settings...");
// Set workspace/project radio buttons
try {
Boolean useProject = getPreferenceStore().getBoolean(PreferenceConstants.P_USE_PROJECT_PREFS);
if (useProject) {
useProjectSettingsButton.setSelection(true);
configureLink.setEnabled(false);
} else {
useProjectSettingsButton.setSelection(false);
}
} catch (Exception e) {
useProjectSettingsButton.setSelection(false);
}
}
/**
* Convenience method creating a check button
*
* @param parent - the parent composite
* @param label - the button label
* @return - the new button
*/
private Button createSettingsButton(Composite parent, String label) {
final Button button = new Button(parent, SWT.CHECK);
button.setText(label);
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
configureLink.setEnabled(button.isEnabled());
updateFieldEditors();
}
});
return button;
}
/**
* Convenience method creating a link
*
* @param parent - the parent composite
* @param label - the link label
* @return - the new link
*/
private Link createLink(Composite composite, String label) {
Link link = new Link(composite, SWT.NONE);
link.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1));
link.setFont(composite.getFont());
link.setText("<A>" + label + "</A>"); //$NON-NLS-1$//$NON-NLS-2$
link.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
configureWorkspaceSettings();
}
public void widgetDefaultSelected(SelectionEvent e) {
configureWorkspaceSettings();
}
});
return link;
}
/**
* Returns in case of property pages the overlay store, in case of
* preference pages the standard preference store
*
* @see org.eclipse.jface.preference.PreferencePage#getPreferenceStore()
*/
public IPreferenceStore getPreferenceStore() {
if (isPropertyPage())
return overlayStore;
return super.getPreferenceStore();
}
/*
* Enables or disables the field editors and buttons of this page
*/
private void updateFieldEditors() {
// We iterate through all field editors
boolean enabled = useProjectSettingsButton.getSelection();
updateFieldEditors(enabled);
updateProjectOutputCheckbox(enabled);
}
/**
* Enables or disables the field editors and buttons of this page Subclasses
* may override.
*
* @param enabled - true if enabled
*/
protected void updateFieldEditors(boolean enabled) {
Composite parent = getFieldEditorParent();
for(FieldEditor editor : editors) {
editor.setEnabled(enabled, parent);
}
}
/**
* Enables or disables the output path according to the checkbox value for using the output folder of the S-CASE
* project.
* @param enabled - true if enabled
*/
protected void updateProjectOutputCheckbox(boolean enabled) {
boolean useProjectOutputFolder = false;
for (FieldEditor editor : editors) {
if (editor.getPreferenceName().equals("useProjectOutputFolder"))
useProjectOutputFolder = ((BooleanFieldEditor) editor).getBooleanValue();
}
for (FieldEditor editor : editors) {
if (editor.getPreferenceName().equals("outputPath"))
editor.setEnabled(enabled && !useProjectOutputFolder, getFieldEditorParent());
}
}
/**
* We override the performOk method. In case of property pages we copy the
* values in the overlay store into the property values of the selected
* project. We also save the state of the radio buttons.
*
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
public boolean performOk() {
boolean result = super.performOk();
if (result && isPropertyPage()) {
// Save state of radio buttons in project properties
getPreferenceStore().setValue(PreferenceConstants.P_USE_PROJECT_PREFS, useProjectSettingsButton.getSelection());
}
return result;
}
/**
* We override the performDefaults method. In case of property pages we
* switch back to the workspace settings and disable the field editors.
*
* @see org.eclipse.jface.preference.PreferencePage#performDefaults()
*/
protected void performDefaults() {
if (isPropertyPage()) {
useProjectSettingsButton.setSelection(false);
configureLink.setEnabled(true);
updateFieldEditors();
}
super.performDefaults();
}
/**
* Creates a new preferences page and opens it
*/
protected void configureWorkspaceSettings() {
try {
// create a new instance of the current class
IPreferencePage page = (IPreferencePage) this.getClass().newInstance();
page.setTitle(getTitle());
page.setImageDescriptor(image);
// and show it
showPreferencePage(pageId, page);
} catch (InstantiationException | IllegalAccessException e) {
Activator.log("Unable to show the preference page.", e);
}
}
/**
* Show a single preference pages
*
* @param id - the preference page identification
* @param page - the preference page
*/
protected void showPreferencePage(String id, IPreferencePage page) {
final IPreferenceNode targetNode = new PreferenceNode(id, page);
PreferenceManager manager = new PreferenceManager();
manager.addToRoot(targetNode);
final PreferenceDialog dialog = new PreferenceDialog(getControl().getShell(), manager);
BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() {
public void run() {
dialog.create();
dialog.setMessage(targetNode.getLabelText());
dialog.open();
}
});
}
} |
package com.ecyrd.jspwiki;
import junit.framework.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class TranslatorReaderTest extends TestCase
{
Properties props = new Properties();
Vector created = new Vector();
static final String PAGE_NAME = "testpage";
TestEngine testEngine;
public TranslatorReaderTest( String s )
{
super( s );
}
public void setUp()
throws Exception
{
props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") );
props.setProperty( "jspwiki.translatorReader.matchEnglishPlurals", "true" );
testEngine = new TestEngine( props );
}
public void tearDown()
{
deleteCreatedPages();
}
private void newPage( String name )
{
testEngine.saveText( name, "<test>" );
created.addElement( name );
}
private void deleteCreatedPages()
{
for( Iterator i = created.iterator(); i.hasNext(); )
{
String name = (String) i.next();
testEngine.deletePage(name);
}
created.clear();
}
private String translate( String src )
throws IOException,
NoRequiredPropertyException,
ServletException
{
WikiContext context = new WikiContext( testEngine,
PAGE_NAME );
Reader r = new TranslatorReader( context,
new BufferedReader( new StringReader(src)) );
StringWriter out = new StringWriter();
int c;
while( ( c=r.read()) != -1 )
{
out.write( c );
}
return out.toString();
}
public void testHyperlinks2()
throws Exception
{
newPage("Hyperlink");
String src = "This should be a [hyperlink]";
assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Hyperlink\">hyperlink</A>",
translate(src) );
}
public void testHyperlinks3()
throws Exception
{
newPage("HyperlinkToo");
String src = "This should be a [hyperlink too]";
assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperlinkToo\">hyperlink too</A>",
translate(src) );
}
public void testHyperlinks4()
throws Exception
{
newPage("HyperLink");
String src = "This should be a [HyperLink]";
assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>",
translate(src) );
}
public void testHyperlinks5()
throws Exception
{
newPage("HyperLink");
String src = "This should be a [here|HyperLink]";
assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">here</A>",
translate(src) );
}
// Testing CamelCase hyperlinks
public void testHyperLinks6()
throws Exception
{
newPage("DiscussionAboutWiki");
newPage("WikiMarkupDevelopment");
String src = "[DiscussionAboutWiki] [WikiMarkupDevelopment].";
assertEquals( "<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=DiscussionAboutWiki\">DiscussionAboutWiki</A> <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=WikiMarkupDevelopment\">WikiMarkupDevelopment</A>.",
translate(src) );
}
public void testHyperlinksCC()
throws Exception
{
newPage("HyperLink");
String src = "This should be a HyperLink.";
assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>.",
translate(src) );
}
public void testHyperlinksCCNonExistant()
throws Exception
{
String src = "This should be a HyperLink.";
assertEquals( "This should be a <U>HyperLink</U><A HREF=\"Edit.jsp?page=HyperLink\">?</A>.",
translate(src) );
}
/**
* Check if the CC hyperlink translator gets confused with
* unorthodox bracketed links.
*/
public void testHyperlinksCC2()
throws Exception
{
newPage("HyperLink");
String src = "This should be a [ HyperLink ].";
assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\"> HyperLink </A>.",
translate(src) );
}
public void testHyperlinksCC3()
throws Exception
{
String src = "This should be a nonHyperLink.";
assertEquals( "This should be a nonHyperLink.",
translate(src) );
}
/** Two links on same line. */
public void testHyperlinksCC4()
throws Exception
{
newPage("HyperLink");
newPage("ThisToo");
String src = "This should be a HyperLink, and ThisToo.";
assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>, and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>.",
translate(src) );
}
/** Two mixed links on same line. */
public void testHyperlinksCC5()
throws Exception
{
newPage("HyperLink");
newPage("ThisToo");
String src = "This should be a [HyperLink], and ThisToo.";
assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>, and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>.",
translate(src) );
}
/** Closing tags only. */
public void testHyperlinksCC6()
throws Exception
{
newPage("HyperLink");
newPage("ThisToo");
String src = "] This ] should be a HyperLink], and ThisToo.";
assertEquals( "] This ] should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>], and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>.",
translate(src) );
}
/** First and last words on line. */
public void testHyperlinksCCFirstAndLast()
throws Exception
{
newPage("HyperLink");
newPage("ThisToo");
String src = "HyperLink, and ThisToo";
assertEquals( "<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>, and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>",
translate(src) );
}
/** Hyperlinks inside URIs. */
public void testHyperlinksCCURLs()
throws Exception
{
String src = "http:
assertEquals( "http:
translate(src) );
}
public void testHyperlinksCCNegated()
throws Exception
{
String src = "This should not be a ~HyperLink.";
assertEquals( "This should not be a HyperLink.",
translate(src) );
}
public void testHyperlinksCCNegated2()
throws Exception
{
String src = "~HyperLinks should not be matched.";
assertEquals( "HyperLinks should not be matched.",
translate(src) );
}
public void testCCLinkInList()
throws Exception
{
newPage("HyperLink");
String src = "*HyperLink";
assertEquals( "<UL>\n<LI><A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A></LI>\n</UL>\n",
translate(src) );
}
public void testCCLinkBold()
throws Exception
{
newPage("BoldHyperLink");
String src = "__BoldHyperLink__";
assertEquals( "<B><A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=BoldHyperLink\">BoldHyperLink</A></B>",
translate(src) );
}
public void testCCLinkBold2()
throws Exception
{
newPage("HyperLink");
String src = "Let's see, if a bold __HyperLink__ is correct?";
assertEquals( "Let's see, if a bold <B><A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A></B> is correct?",
translate(src) );
}
public void testCCLinkItalic()
throws Exception
{
newPage("ItalicHyperLink");
String src = "''ItalicHyperLink''";
assertEquals( "<I><A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ItalicHyperLink\">ItalicHyperLink</A></I>",
translate(src) );
}
public void testCCLinkWithPunctuation()
throws Exception
{
newPage("HyperLink");
String src = "Test. Punctuation. HyperLink.";
assertEquals( "Test. Punctuation. <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>.",
translate(src) );
}
public void testCCLinkWithPunctuation2()
throws Exception
{
newPage("HyperLink");
newPage("ThisToo");
String src = "Punctuations: HyperLink,ThisToo.";
assertEquals( "Punctuations: <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>,<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>.",
translate(src) );
}
public void testCCLinkWithScandics()
throws Exception
{
newPage("itiSyljy");
String src = "Onko tm hyperlinkki: itiSyljy?";
assertEquals( "Onko tm hyperlinkki: <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=%C4itiSy%F6%D6ljy%E4\">itiSyljy</A>?",
translate(src) );
}
public void testHyperlinksExt()
throws Exception
{
String src = "This should be a [http:
assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http:
translate(src) );
}
public void testHyperlinksExt2()
throws Exception
{
String src = "This should be a [link|http:
assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http:
translate(src) );
}
// Testing various odds and ends about hyperlink matching.
public void testHyperlinksPluralMatch()
throws Exception
{
String src = "This should be a [HyperLinks]";
newPage("HyperLink");
assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLinks</A>",
translate(src) );
}
public void testHyperlinksPluralMatch2()
throws Exception
{
String src = "This should be a [HyperLinks]";
assertEquals( "This should be a <U>HyperLinks</U><A HREF=\"Edit.jsp?page=HyperLinks\">?</A>",
translate(src) );
}
public void testHyperlinksPluralMatch3()
throws Exception
{
String src = "This should be a [HyperLink]";
newPage("HyperLinks");
assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLinks\">HyperLink</A>",
translate(src) );
}
public void testHyperlinkJS1()
throws Exception
{
String src = "This should be a [link|http:
assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http:
translate(src) );
}
public void testHyperlinksInterWiki1()
throws Exception
{
String src = "This should be a [link|JSPWiki:HyperLink]";
assertEquals( "This should be a <A CLASS=\"interwiki\" HREF=\"http:
translate(src) );
}
public void testNoHyperlink()
throws Exception
{
newPage("HyperLink");
String src = "This should not be a [[HyperLink]";
assertEquals( "This should not be a [HyperLink]",
translate(src) );
}
public void testNoHyperlink2()
throws Exception
{
String src = "This should not be a [[[[HyperLink]";
assertEquals( "This should not be a [[[HyperLink]",
translate(src) );
}
public void testNoHyperlink3()
throws Exception
{
String src = "[[HyperLink], and this [[Neither].";
assertEquals( "[HyperLink], and this [Neither].",
translate(src) );
}
public void testNoPlugin()
throws Exception
{
String src = "There is [[{NoPlugin}] here.";
assertEquals( "There is [{NoPlugin}] here.",
translate(src) );
}
public void testErroneousHyperlink()
throws Exception
{
String src = "What if this is the last char [";
assertEquals( "What if this is the last char ",
translate(src) );
}
public void testErroneousHyperlink2()
throws Exception
{
String src = "What if this is the last char [[";
assertEquals( "What if this is the last char [",
translate(src) );
}
public void testExtraPagename1()
throws Exception
{
String src = "Link [test_page]";
newPage("Test_page");
assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test_page\">test_page</A>",
translate(src) );
}
public void testExtraPagename2()
throws Exception
{
String src = "Link [test.page]";
newPage("Test.page");
assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test.page\">test.page</A>",
translate(src) );
}
public void testExtraPagename3()
throws Exception
{
String src = "Link [.testpage_]";
newPage(".testpage_");
assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=.testpage_\">.testpage_</A>",
translate(src) );
}
public void testInlineImages()
throws Exception
{
String src = "Link [test|http:
assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http:
translate(src) );
}
public void testInlineImages2()
throws Exception
{
String src = "Link [test|http:
assertEquals("Link <A CLASS=\"external\" HREF=\"http:
translate(src) );
}
public void testInlineImages3()
throws Exception
{
String src = "Link [test|http://images.com/testi]";
assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://images.com/testi\" ALT=\"test\" />",
translate(src) );
}
public void testInlineImages4()
throws Exception
{
String src = "Link [test|http://foobar.jpg]";
assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://foobar.jpg\" ALT=\"test\" />",
translate(src) );
}
// No link text should be just embedded link.
public void testInlineImagesLink2()
throws Exception
{
String src = "Link [http://foobar.jpg]";
assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http:
translate(src) );
}
public void testInlineImagesLink()
throws Exception
{
String src = "Link [http:
assertEquals("Link <A HREF=\"http:
translate(src) );
}
public void testInlineImagesLink3()
throws Exception
{
String src = "Link [SandBox|http://foobar.jpg]";
newPage("SandBox");
assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=SandBox\"><IMG CLASS=\"inline\" SRC=\"http://foobar.jpg\" ALT=\"SandBox\" /></A>",
translate(src) );
}
public void testScandicPagename1()
throws Exception
{
String src = "Link [Test]";
newPage("Test"); // FIXME: Should be capital
assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=%C5%E4Test\">Test</A>",
translate(src));
}
public void testParagraph()
throws Exception
{
String src = "1\n\n2\n\n3";
assertEquals( "1\n<P>\n2\n<P>\n3", translate(src) );
}
public void testParagraph2()
throws Exception
{
String src = "[WikiEtiquette]\r\n\r\n[Find page]";
newPage( "WikiEtiquette" );
assertEquals( "<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=WikiEtiquette\">WikiEtiquette</A>\n"+
"<P>\n<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=FindPage\">Find page</A>", translate(src) );
}
public void testLinebreak()
throws Exception
{
String src = "1\\\\2";
assertEquals( "1<BR />2", translate(src) );
}
public void testLinebreakClear()
throws Exception
{
String src = "1\\\\\\2";
assertEquals( "1<BR clear=\"all\" />2", translate(src) );
}
public void testTT()
throws Exception
{
String src = "1{{2345}}6";
assertEquals( "1<TT>2345</TT>6", translate(src) );
}
public void testTTAcrossLines()
throws Exception
{
String src = "1{{\n2345\n}}6";
assertEquals( "1<TT>\n2345\n</TT>6", translate(src) );
}
public void testTTLinks()
throws Exception
{
String src = "1{{\n2345\n[a link]\n}}6";
newPage("ALink");
assertEquals( "1<TT>\n2345\n<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ALink\">a link</A>\n</TT>6", translate(src) );
}
public void testPre()
throws Exception
{
String src = "1{{{2345}}}6";
assertEquals( "1<PRE>2345</PRE>6", translate(src) );
}
public void testPre2()
throws Exception
{
String src = "1 {{{ {{{ 2345 }}} }}} 6";
assertEquals( "1 <PRE> {{{ 2345 </PRE> }}} 6", translate(src) );
}
public void testHTMLInPre()
throws Exception
{
String src = "1 {{{ <B> }}}";
assertEquals( "1 <PRE> <B> </PRE>", translate(src) );
}
public void testList1()
throws Exception
{
String src = "A list:\n* One\n* Two\n* Three\n";
assertEquals( "A list:\n<UL>\n<LI> One\n</LI>\n<LI> Two\n</LI>\n<LI> Three\n</LI>\n</UL>\n",
translate(src) );
}
/** Plain multi line testing:
<pre>
* One
continuing
* Two
* Three
</pre>
*/
public void testMultilineList1()
throws Exception
{
String src = "A list:\n* One\n continuing.\n* Two\n* Three\n";
assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n</LI>\n<LI> Two\n</LI>\n<LI> Three\n</LI>\n</UL>\n",
translate(src) );
}
public void testMultilineList2()
throws Exception
{
String src = "A list:\n* One\n continuing.\n* Two\n* Three\nShould be normal.";
assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n</LI>\n<LI> Two\n</LI>\n<LI> Three\n</LI>\n</UL>\nShould be normal.",
translate(src) );
}
public void testHTML()
throws Exception
{
String src = "<B>Test</B>";
assertEquals( "<B>Test</B>", translate(src) );
}
public void testHTML2()
throws Exception
{
String src = "<P>";
assertEquals( "<P>", translate(src) );
}
public void testQuotes()
throws Exception
{
String src = "\"Test\"\"";
assertEquals( ""Test""", translate(src) );
}
public void testItalicAcrossLinebreak()
throws Exception
{
String src="''This is a\ntest.''";
assertEquals( "<I>This is a\ntest.</I>", translate(src) );
}
public void testBoldAcrossLinebreak()
throws Exception
{
String src="__This is a\ntest.__";
assertEquals( "<B>This is a\ntest.</B>", translate(src) );
}
public void testBoldItalic()
throws Exception
{
String src="__This ''is'' a test.__";
assertEquals( "<B>This <I>is</I> a test.</B>", translate(src) );
}
public void testFootnote1()
throws Exception
{
String src="Footnote[1]";
assertEquals( "Footnote<A CLASS=\"footnoteref\" HREF=\"#ref-testpage-1\">[1]</A>",
translate(src) );
}
public void testFootnote2()
throws Exception
{
String src="[#2356] Footnote.";
assertEquals( "<A CLASS=\"footnote\" NAME=\"ref-testpage-2356\">[#2356]</A> Footnote.",
translate(src) );
}
/** Check an reported error condition where empty list items could cause crashes */
public void testEmptySecondLevelList()
throws Exception
{
String src="A\n\n**\n\nB";
assertEquals( "A\n<P>\n<UL>\n<UL>\n<LI>\n</LI>\n</UL>\n</UL>\n<P>\nB",
translate(src) );
}
public void testEmptySecondLevelList2()
throws Exception
{
String src="A\n\n##\n\nB";
assertEquals( "A\n<P>\n<OL>\n<OL>\n<LI>\n</LI>\n</OL>\n</OL>\n<P>\nB",
translate(src) );
}
/**
* <pre>
* *Item A
* ##Numbered 1
* ##Numbered 2
* *Item B
* </pre>
*
* would come out as:
*<ul>
* <li>Item A
* </ul>
* <ol>
* <ol>
* <li>Numbered 1
* <li>Numbered 2
* <ul>
* <li></ol>
* </ol>
* Item B
* </ul>
*
* (by Mahlen Morris).
*/
// FIXME: does not run - code base is too screwed for that.
/*
public void testMixedList()
throws Exception
{
String src="*Item A\n##Numbered 1\n##Numbered 2\n*Item B\n";
String result = translate(src);
// Remove newlines for easier parsing.
result = TextUtil.replaceString( result, "\n", "" );
assertEquals( "<UL><LI>Item A"+
"<OL><OL><LI>Numbered 1"+
"<LI>Numbered 2"+
"</OL></OL>"+
"<LI>Item B"+
"</UL>",
result );
}
*/
/**
* Like testMixedList() but the list types have been reversed.
*/
// FIXME: does not run - code base is too screwed for that.
/*
public void testMixedList2()
throws Exception
{
String src="#Item A\n**Numbered 1\n**Numbered 2\n#Item B\n";
String result = translate(src);
// Remove newlines for easier parsing.
result = TextUtil.replaceString( result, "\n", "" );
assertEquals( "<OL><LI>Item A"+
"<UL><UL><LI>Numbered 1"+
"<LI>Numbered 2"+
"</UL></UL>"+
"<LI>Item B"+
"</OL>",
result );
}
*/
public void testPluginInsert()
throws Exception
{
String src="[{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text=test}]";
assertEquals( "test", translate(src) );
}
public void testPluginNoInsert()
throws Exception
{
String src="[{SamplePlugin text=test}]";
assertEquals( "test", translate(src) );
}
public void testPluginInsertJS()
throws Exception
{
String src="Today: [{INSERT JavaScriptPlugin}] ''day''.";
assertEquals( "Today: <script language=\"JavaScript\"><!--\nfoo='';\n--></script>\n <I>day</I>.", translate(src) );
}
public void testShortPluginInsert()
throws Exception
{
String src="[{INSERT SamplePlugin WHERE text=test}]";
assertEquals( "test", translate(src) );
}
/**
* Test two plugins on same row.
*/
public void testShortPluginInsert2()
throws Exception
{
String src="[{INSERT SamplePlugin WHERE text=test}] [{INSERT SamplePlugin WHERE text=test2}]";
assertEquals( "test test2", translate(src) );
}
public void testPluginQuotedArgs()
throws Exception
{
String src="[{INSERT SamplePlugin WHERE text='test me now'}]";
assertEquals( "test me now", translate(src) );
}
public void testPluginDoublyQuotedArgs()
throws Exception
{
String src="[{INSERT SamplePlugin WHERE text='test \\'me too\\' now'}]";
assertEquals( "test 'me too' now", translate(src) );
}
public void testPluginQuotedArgs2()
throws Exception
{
String src="[{INSERT SamplePlugin WHERE text=foo}] [{INSERT SamplePlugin WHERE text='test \\'me too\\' now'}]";
assertEquals( "foo test 'me too' now", translate(src) );
}
/**
* Plugin output must not be parsed as Wiki text.
*/
public void testPluginWikiText()
throws Exception
{
String src="[{INSERT SamplePlugin WHERE text=PageContent}]";
assertEquals( "PageContent", translate(src) );
}
/**
* Nor should plugin input be interpreted as wiki text.
*/
public void testPluginWikiText2()
throws Exception
{
String src="[{INSERT SamplePlugin WHERE text='
assertEquals( "----", translate(src) );
}
public void testMultilinePlugin1()
throws Exception
{
String src="Test [{INSERT SamplePlugin WHERE\n text=PageContent}]";
assertEquals( "Test PageContent", translate(src) );
}
public void testMultilinePluginBodyContent()
throws Exception
{
String src="Test [{INSERT SamplePlugin\ntext=PageContent\n\n123\n456\n}]";
assertEquals( "Test PageContent (123+456+)", translate(src) );
}
public void testMultilinePluginBodyContent2()
throws Exception
{
String src="Test [{INSERT SamplePlugin\ntext=PageContent\n\n\n123\n456\n}]";
assertEquals( "Test PageContent (+123+456+)", translate(src) );
}
public void testMultilinePluginBodyContent3()
throws Exception
{
String src="Test [{INSERT SamplePlugin\n\n123\n456\n}]";
assertEquals( "Test (123+456+)", translate(src) );
}
/**
* Has an extra space after plugin name.
*/
public void testMultilinePluginBodyContent4()
throws Exception
{
String src="Test [{INSERT SamplePlugin \n\n123\n456\n}]";
assertEquals( "Test (123+456+)", translate(src) );
}
public void testVariableInsert()
throws Exception
{
String src="[{$pagename}]";
assertEquals( PAGE_NAME+"", translate(src) );
}
public void testTable1()
throws Exception
{
String src="|| heading || heading2 \n| Cell 1 | Cell 2 \n| Cell 3 | Cell 4\n\n";
assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+
"<TR><TH> heading </TH><TH> heading2 </TH></TR>\n"+
"<TR><TD> Cell 1 </TD><TD> Cell 2 </TD></TR>\n"+
"<TR><TD> Cell 3 </TD><TD> Cell 4</TD></TR>\n"+
"</TABLE>\n<P>\n",
translate(src) );
}
public void testTable2()
throws Exception
{
String src="||heading||heading2\n|Cell 1| Cell 2\n| Cell 3 |Cell 4\n\n";
assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+
"<TR><TH>heading</TH><TH>heading2</TH></TR>\n"+
"<TR><TD>Cell 1</TD><TD> Cell 2</TD></TR>\n"+
"<TR><TD> Cell 3 </TD><TD>Cell 4</TD></TR>\n"+
"</TABLE>\n<P>\n",
translate(src) );
}
public void testTable3()
throws Exception
{
String src="|Cell 1| Cell 2\n| Cell 3 |Cell 4\n\n";
assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+
"<TR><TD>Cell 1</TD><TD> Cell 2</TD></TR>\n"+
"<TR><TD> Cell 3 </TD><TD>Cell 4</TD></TR>\n"+
"</TABLE>\n<P>\n",
translate(src) );
}
public void testTableLink()
throws Exception
{
String src="|Cell 1| Cell 2\n|[Cell 3|ReallyALink]|Cell 4\n\n";
newPage("ReallyALink");
assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+
"<TR><TD>Cell 1</TD><TD> Cell 2</TD></TR>\n"+
"<TR><TD><A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ReallyALink\">Cell 3</A></TD><TD>Cell 4</TD></TR>\n"+
"</TABLE>\n<P>\n",
translate(src) );
}
public void testTableLinkEscapedBar()
throws Exception
{
String src="|Cell 1| Cell~| 2\n|[Cell 3|ReallyALink]|Cell 4\n\n";
newPage("ReallyALink");
assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+
"<TR><TD>Cell 1</TD><TD> Cell| 2</TD></TR>\n"+
"<TR><TD><A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ReallyALink\">Cell 3</A></TD><TD>Cell 4</TD></TR>\n"+
"</TABLE>\n<P>\n",
translate(src) );
}
public void testDescription()
throws Exception
{
String src=";:Foo";
assertEquals( "<DL>\n<DT></DT><DD>Foo</DD>\n</DL>",
translate(src) );
}
public void testDescription2()
throws Exception
{
String src=";Bar:Foo";
assertEquals( "<DL>\n<DT>Bar</DT><DD>Foo</DD>\n</DL>",
translate(src) );
}
public void testDescription3()
throws Exception
{
String src=";:";
assertEquals( "<DL>\n<DT></DT><DD></DD>\n</DL>",
translate(src) );
}
public void testDescription4()
throws Exception
{
String src=";Bar:Foo :-)";
assertEquals( "<DL>\n<DT>Bar</DT><DD>Foo :-)</DD>\n</DL>",
translate(src) );
}
public void testRuler()
throws Exception
{
String src="
assertEquals( "<HR />",
translate(src) );
}
public void testRulerCombo()
throws Exception
{
String src="----Foo";
assertEquals( "<HR />Foo",
translate(src) );
}
public void testShortRuler1()
throws Exception
{
String src="-";
assertEquals( "-",
translate(src) );
}
public void testShortRuler2()
throws Exception
{
String src="
assertEquals( "
translate(src) );
}
public void testShortRuler3()
throws Exception
{
String src="
assertEquals( "
translate(src) );
}
public void testLongRuler()
throws Exception
{
String src="
assertEquals( "<HR />",
translate(src) );
}
public void testHeading1()
throws Exception
{
String src="!Hello";
assertEquals( "<H4>Hello</H4>",
translate(src) );
}
public void testHeading2()
throws Exception
{
String src="!!Hello";
assertEquals( "<H3>Hello</H3>",
translate(src) );
}
public void testHeading3()
throws Exception
{
String src="!!!Hello";
assertEquals( "<H2>Hello</H2>",
translate(src) );
}
public void testHeadingHyperlinks()
throws Exception
{
String src="!!![Hello]";
assertEquals( "<H2><U>Hello</U><A HREF=\"Edit.jsp?page=Hello\">?</A></H2>",
translate(src) );
}
public static Test suite()
{
return new TestSuite( TranslatorReaderTest.class );
}
} |
package org.ihtsdo.rvf.execution.service;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import org.ihtsdo.otf.snomedboot.ReleaseImportException;
import org.ihtsdo.otf.snomedboot.ReleaseImporter;
import org.ihtsdo.otf.snomedboot.factory.ComponentFactory;
import org.ihtsdo.otf.snomedboot.factory.LoadingProfile;
import org.ihtsdo.rvf.entity.FailureDetail;
import org.ihtsdo.rvf.entity.TestRunItem;
import org.ihtsdo.rvf.entity.TestType;
import org.ihtsdo.rvf.execution.service.config.ValidationRunConfig;
import org.ihtsdo.rvf.execution.service.traceability.ChangeSummaryReport;
import org.ihtsdo.rvf.execution.service.traceability.ComponentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
@Service
public class TraceabilityComparisonService {
public static final String ASSERTION_ID_ALL_COMPONENTS_IN_TRACEABILITY_ALSO_IN_DELTA = "f68c761b-3b5c-4223-bc00-6e181e7f68c3";
public static final String ASSERTION_ID_ALL_COMPONENTS_IN_DELTA_ALSO_IN_TRACEABILITY = "b7f727d7-9226-4eef-9a7e-47a8580f6e7a";
private final Logger logger = LoggerFactory.getLogger(getClass());
private final RestTemplate traceabilityServiceRestTemplate;
private static final ParameterizedTypeReference<ChangeSummaryReport> CHANGE_SUMMARY_REPORT_TYPE_REFERENCE = new ParameterizedTypeReference<>() {};
// 900000000000534007 | Module dependency reference set (foundation metadata concept) | - Ignore these because they will be generated during the export in Snowstorm.
private Set<String> refsetsToIgnore = Sets.newHashSet("900000000000534007");
public TraceabilityComparisonService(@Value("${traceability-service.url}") String traceabilityServiceUrl) {
if (!Strings.isNullOrEmpty(traceabilityServiceUrl)) {
traceabilityServiceRestTemplate = new RestTemplateBuilder().rootUri(traceabilityServiceUrl).build();
} else {
traceabilityServiceRestTemplate = null;
}
}
public void runTraceabilityComparison(ValidationStatusReport report, ValidationRunConfig validationConfig) {
if (traceabilityServiceRestTemplate == null) {
final String message = "Traceability test requested but service URL not configured.";
logger.warn(message);
report.addFailureMessage(message);
return;
}
final String branchPath = validationConfig.getBranchPath();
if (Strings.isNullOrEmpty(branchPath)) {
final String message = "Traceability test requested but no branchPath given.";
logger.warn(message);
report.addFailureMessage(message);
return;
}
try {
final Map<ComponentType, Set<String>> rf2Changes = gatherRF2ComponentChanges(validationConfig);
final Map<ComponentType, Set<String>> traceabilityChanges = getTraceabilityComponentChanges(branchPath);
final TestRunItem traceabilityAndDelta = new TestRunItem();
traceabilityAndDelta.setTestType(TestType.TRACEABILITY);
traceabilityAndDelta.setAssertionUuid(UUID.fromString(ASSERTION_ID_ALL_COMPONENTS_IN_TRACEABILITY_ALSO_IN_DELTA));
traceabilityAndDelta.setAssertionText("All components in the branch traceability summary must also be in the RF2 export.");
traceabilityAndDelta.setFailureCount(0L);// Initial value
AtomicInteger remainingFailureExport = new AtomicInteger(validationConfig.getFailureExportMax());
diffAndAddFailures(ComponentType.CONCEPT, "Concept change in traceability is missing from RF2 export.",
traceabilityChanges, rf2Changes, remainingFailureExport, traceabilityAndDelta);
diffAndAddFailures(ComponentType.DESCRIPTION, "Description change in traceability is missing from RF2 export.",
traceabilityChanges, rf2Changes, remainingFailureExport, traceabilityAndDelta);
diffAndAddFailures(ComponentType.RELATIONSHIP, "Relationship change in traceability is missing from RF2 export.",
traceabilityChanges, rf2Changes, remainingFailureExport, traceabilityAndDelta);
diffAndAddFailures(ComponentType.REFERENCE_SET_MEMBER, "Refset member change in traceability is missing from RF2 export.",
traceabilityChanges, rf2Changes, remainingFailureExport, traceabilityAndDelta);
if (traceabilityAndDelta.getFirstNInstances().isEmpty()) {
report.getResultReport().addPassedAssertions(Collections.singletonList(traceabilityAndDelta));
} else {
report.getResultReport().addFailedAssertions(Collections.singletonList(traceabilityAndDelta));
}
final TestRunItem deltaAndTraceability = new TestRunItem();
deltaAndTraceability.setTestType(TestType.TRACEABILITY);
deltaAndTraceability.setAssertionUuid(UUID.fromString(ASSERTION_ID_ALL_COMPONENTS_IN_DELTA_ALSO_IN_TRACEABILITY));
deltaAndTraceability.setAssertionText("All components in the RF2 export must also be in the branch traceability summary.");
deltaAndTraceability.setFailureCount(0L);// Initial value
remainingFailureExport = new AtomicInteger(validationConfig.getFailureExportMax());
diffAndAddFailures(ComponentType.CONCEPT, "Concept change in RF2 export is missing from traceability.",
rf2Changes, traceabilityChanges, remainingFailureExport, deltaAndTraceability);
diffAndAddFailures(ComponentType.DESCRIPTION, "Description change in RF2 export is missing from traceability.",
rf2Changes, traceabilityChanges, remainingFailureExport, deltaAndTraceability);
diffAndAddFailures(ComponentType.RELATIONSHIP, "Relationship change in RF2 export is missing from traceability.",
rf2Changes, traceabilityChanges, remainingFailureExport, deltaAndTraceability);
diffAndAddFailures(ComponentType.REFERENCE_SET_MEMBER, "Refset member change in RF2 export is missing from traceability.",
rf2Changes, traceabilityChanges, remainingFailureExport, deltaAndTraceability);
if (deltaAndTraceability.getFirstNInstances().isEmpty()) {
report.getResultReport().addPassedAssertions(Collections.singletonList(deltaAndTraceability));
} else {
report.getResultReport().addFailedAssertions(Collections.singletonList(deltaAndTraceability));
}
} catch (IOException | ReleaseImportException e) {
String message = "Traceability validation failed";
logger.error(message, e);
report.addFailureMessage(e.getMessage() != null ? message + " due to error: " + e.getMessage() : message);
}
}
private void diffAndAddFailures(ComponentType componentType, String message, Map<ComponentType, Set<String>> leftSide, Map<ComponentType, Set<String>> rightSide,
AtomicInteger remainingFailureExport, TestRunItem report) {
final Sets.SetView<String> missing = Sets.difference(leftSide.getOrDefault(componentType, Collections.emptySet()), rightSide.getOrDefault(componentType, Collections.emptySet()));
for (String inLeftNotRight : missing) {
if (remainingFailureExport.get() > 0) {
remainingFailureExport.incrementAndGet();
report.addFirstNInstance(new FailureDetail(null, message).setComponentId(inLeftNotRight));
}
report.setFailureCount(report.getFailureCount() + 1);
}
}
private Map<ComponentType, Set<String>> gatherRF2ComponentChanges(ValidationRunConfig validationConfig) throws IOException, ReleaseImportException {
final String releaseEffectiveTime = validationConfig.getEffectiveTime();
logger.info("Collecting component ids from snapshot using effectiveTime filter.");
Set<String> concepts = new HashSet<>();
Set<String> descriptions = new HashSet<>();
Set<String> relationships = new HashSet<>();
Set<String> concreteRelationships = new HashSet<>();
Set<String> refsetMembers = new HashSet<>();
try (final FileInputStream releaseZip = new FileInputStream(validationConfig.getLocalProspectiveFile())) {
final boolean rf2DeltaOnly = validationConfig.isRf2DeltaOnly();
Predicate<String> effectiveTimePredicate =
rf2DeltaOnly ?
effectiveTime -> true :// Let all delta rows through
effectiveTime -> inDelta(effectiveTime, releaseEffectiveTime);// Only let snapshot rows through if they have the right date
final ComponentFactory componentFactory = new ComponentFactory() {
@Override
public void preprocessingContent() {
// Not needed
}
@Override
public void loadingComponentsStarting() {
// Not needed
}
@Override
public void loadingComponentsCompleted() {
// Not needed
}
@Override
public void newConceptState(String id, String effectiveTime, String active, String moduleId, String s4) {
if (effectiveTimePredicate.test(effectiveTime)) {
concepts.add(id);
}
}
@Override
public void newDescriptionState(String id, String effectiveTime, String active, String moduleId, String s4, String s5, String s6, String s7, String s8) {
if (effectiveTimePredicate.test(effectiveTime)) {
descriptions.add(id);
}
}
@Override
public void newRelationshipState(String id, String effectiveTime, String active, String moduleId, String s4, String s5, String s6, String s7, String s8, String s9) {
if (effectiveTimePredicate.test(effectiveTime)) {
relationships.add(id);
}
}
@Override
public void newConcreteRelationshipState(String id, String effectiveTime, String active, String moduleId, String s4, String s5, String s6, String s7, String s8, String s9) {
if (effectiveTimePredicate.test(effectiveTime)) {
concreteRelationships.add(id);
}
}
@Override
public void newReferenceSetMemberState(String[] strings, String id, String effectiveTime, String active, String moduleId, String refsetId, String referencedComponentId, String... strings1) {
if (effectiveTimePredicate.test(effectiveTime) && !refsetsToIgnore.contains(refsetId)) {
refsetMembers.add(id);
}
}
};
if (rf2DeltaOnly) {
new ReleaseImporter().loadDeltaReleaseFiles(releaseZip, LoadingProfile.complete, componentFactory, false);
} else {
new ReleaseImporter().loadSnapshotReleaseFiles(releaseZip, LoadingProfile.complete, componentFactory, false);
}
}
relationships.addAll(concreteRelationships);
logger.info("Collected component ids: concepts:{}, descriptions:{}, relationships:{}, refset members:{}.",
concepts.size(), descriptions.size(), relationships.size(), refsetMembers.size());
final Map<ComponentType, Set<String>> rf2Changes = new EnumMap<>(ComponentType.class);
rf2Changes.put(ComponentType.CONCEPT, concepts);
rf2Changes.put(ComponentType.DESCRIPTION, descriptions);
rf2Changes.put(ComponentType.RELATIONSHIP, relationships);
rf2Changes.put(ComponentType.REFERENCE_SET_MEMBER, refsetMembers);
return rf2Changes;
}
private Map<ComponentType, Set<String>> getTraceabilityComponentChanges(String branchPath) throws IOException {
logger.info("Fetching diff from traceability service..");
final String uri = UriComponentsBuilder.fromPath("/change-summary").queryParam("branch", branchPath).toUriString();
final ResponseEntity<ChangeSummaryReport> response =
traceabilityServiceRestTemplate.exchange(uri, HttpMethod.GET, null, CHANGE_SUMMARY_REPORT_TYPE_REFERENCE);
final ChangeSummaryReport summaryReport = response.getBody();
if (summaryReport == null || summaryReport.getComponentChanges() == null) {
throw new IOException("No change report returned from traceability service.");
}
return summaryReport.getComponentChanges();
}
private boolean inDelta(String effectiveTime, String releaseEffectiveTime) {
return Strings.isNullOrEmpty(releaseEffectiveTime) ? effectiveTime.isEmpty() : releaseEffectiveTime.equals(effectiveTime);
}
} |
package org.sugarj.common.cleardep;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.sugarj.common.cleardep.mode.Mode;
import org.sugarj.common.path.RelativePath;
public class BuildSchedule {
public static enum TaskState {
OPEN, IN_PROGESS, SUCCESS, FAILURE;
}
static int maxID = 0;
public static class Task {
Set<CompilationUnit> unitsToCompile;
Set<Task> requiredTasks;
Set<Task> tasksRequiringMe;
private TaskState state;
private int id;
public Task() {
this(new HashSet<CompilationUnit>());
}
public Task(CompilationUnit unit) {
this();
this.unitsToCompile.add(unit);
}
public Task(Set<CompilationUnit> units) {
Objects.requireNonNull(units);
this.unitsToCompile = units;
this.requiredTasks = new HashSet<>();
this.tasksRequiringMe = new HashSet<>();
this.state = TaskState.OPEN;
id = maxID;
maxID++;
}
public boolean containsUnits(CompilationUnit unit) {
return this.unitsToCompile.contains(unit);
}
public boolean needsToBeBuild(Map<RelativePath, Integer> editedSourceFiles, Mode mode) {
// Check the states of the depending tasks
for (Task t : this.requiredTasks) {
switch (t.getState()) {
case OPEN:
break;
case IN_PROGESS:
throw new IllegalBuildStateException("Can only determine whether a task has to be build with depending tasks are build");
case FAILURE:
return false; // Do not need to build if depending builds
// failed
case SUCCESS:
}
}
// The task needs to be build iff one unit is not shallow consistent
// not consistent or not consistent to interfaces
for (CompilationUnit u : this.unitsToCompile) {
if (!u.isConsistentShallow(editedSourceFiles, mode)) {
return true;
}
if (!u.isConsistentToDependencyInterfaces()) {
return true;
}
}
return false;
}
public boolean isCompleted() {
return this.state == TaskState.SUCCESS || this.state == TaskState.FAILURE;
}
public TaskState getState() {
return this.state;
}
public Set<CompilationUnit> getUnitsToCompile() {
return unitsToCompile;
}
public void setState(TaskState state) {
this.state = state;
}
public void addUnit(CompilationUnit unit) {
this.unitsToCompile.add(unit);
}
public void addRequiredTask(Task task) {
if (task == this) {
throw new IllegalArgumentException("Cannot require itself");
}
this.requiredTasks.add(task);
task.tasksRequiringMe.add(this);
}
public boolean requires(Task task) {
return this.requiredTasks.contains(task);
}
public boolean hasNoRequiredTasks() {
return this.requiredTasks.isEmpty();
}
public void remove() {
for (Task t : this.requiredTasks) {
t.tasksRequiringMe.remove(this);
}
for (Task t : this.tasksRequiringMe) {
t.requiredTasks.remove(this);
}
}
@Override
public String toString() {
String reqs = "";
for (Task dep : this.requiredTasks) {
reqs += dep.id + ",";
}
String s = "Task_" + id + "_(" + reqs + ")[";
for (CompilationUnit u : this.unitsToCompile)
for (RelativePath p : u.getSourceArtifacts())
s += p.getRelativePath() + ", ";
s += "]";
return s;
}
@Override
public int hashCode() {
return this.id;
}
}
private Set<Task> rootTasks;
private List<Task> orderedSchedule;
public BuildSchedule() {
this.rootTasks = new HashSet<>();
}
protected void setOrderedTasks(List<Task> tasks) {
this.orderedSchedule = tasks;
}
public List<Task> getOrderedSchedule() {
return orderedSchedule;
}
public void addRootTask(Task task) {
assert task.hasNoRequiredTasks() : "Given task is not a root";
this.rootTasks.add(task);
}
public static enum ScheduleMode {
REBUILD_ALL, REBUILD_INCONSISTENT;
}
@Override
public String toString() {
String str = "BuildSchedule: " + this.rootTasks.size() + " root tasks\n";
return str;
}
} |
package com.flash3388.flashlib.robot.io.devices.actuators;
import java.util.*;
/**
* A container for multiple speed controllers. Grouping controllers in such manner allows simultaneous
* control of several motors. When motors should be activated together, this container is extremely useful.
*
* @author Tom Tzook
* @since FlashLib 1.0.0
*/
public class SpeedControllerGroup implements SpeedController {
private final List<SpeedController> mControllers;
private boolean mIsInverted;
/**
* Creates a new container for a list of speed controller.
*
* @param controllers list of controllers to be contained
* @param isInverted whether or not to invert the controllers
*/
public SpeedControllerGroup(Collection<SpeedController> controllers, boolean isInverted){
mControllers = Collections.unmodifiableList(new ArrayList<>(controllers));
setInverted(isInverted);
set(0);
}
public SpeedControllerGroup(Collection<SpeedController> controllers) {
this(controllers, false);
}
public SpeedControllerGroup(boolean isInverted, SpeedController... controllers) {
this(Arrays.asList(controllers), isInverted);
}
public SpeedControllerGroup(SpeedController... controllers) {
this(false, controllers);
}
public List<SpeedController> getControllers() {
return mControllers;
}
/**
* {@inheritDoc}
* <p>
* Sets the speed value to all the speed controllers contained in this object.
* </p>
*/
@Override
public void set(double speed) {
for (SpeedController controller : mControllers) {
controller.set(speed);
}
}
/**
* {@inheritDoc}
* <p>
* Stops all the speed controllers contained in this object.
* </p>
*/
@Override
public void stop() {
for (SpeedController controller : mControllers) {
controller.stop();
}
}
/**
* {@inheritDoc}
*<p>
* Gets the average speed value of all the speed controllers contained in this object.
*</p>
*/
@Override
public double get() {
double totalSpeed = 0.0;
for (SpeedController controller : mControllers) {
totalSpeed += controller.get();
}
return totalSpeed / mControllers.size();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isInverted() {
return mIsInverted;
}
/**
* {@inheritDoc}
* <p>
* Sets all the speed controllers contained in this object .
* </p>
*/
@Override
public void setInverted(boolean inverted) {
mIsInverted = inverted;
for (SpeedController controller : mControllers) {
controller.setInverted(inverted);
}
}
} |
package de.gurkenlabs.litiengine;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.*;
public class GameTimeTests {
@ParameterizedTest(name="toMilliseconds_Positive ticks={0}, updateRate={1}, expected={2}")
@CsvSource({
"100, 50, 2000",
"450, 33, 13636",
"33, 100, 330"
})
public void toMilliseconds_Positive(long ticks, int updateRate, long expected) {
// arrange
GameTime time = new GameTime();
// act, assert
assertEquals(expected, time.toMilliseconds(ticks, updateRate));
}
@Test
public void toMilliseconds_Negative() {
// arrange
GameTime time = new GameTime();
// act, assert
assertEquals(-200, time.toMilliseconds(-20, 100));
assertEquals(-400, time.toMilliseconds(1000, -2500));
assertEquals(200, time.toMilliseconds(-100, -500));
}
@Test
public void toMilliseconds_ZeroTicks() {
// arrange
GameTime time = new GameTime();
// act, assert
assertEquals(0, time.toMilliseconds(0, 1000));
}
@Test
public void toMilliseconds_ZeroUpdateRateThrows() {
// arrange
GameTime time = new GameTime();
// act, assert
assertThrows(ArithmeticException.class, () -> {
long failed = time.toMilliseconds(100, 0);
});
}
} |
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
// FILE NAME: Autonomous.java (Team 339 - Kilroy)
// ABSTRACT:
// This file is where almost all code for Kilroy will be
// written. Some of these functions are functions that should
// override methods in the base class (IterativeRobot). The
// functions are as follows:
// Init() - Initialization code for autonomous mode
// should go here. Will be called each time the robot enters
// autonomous mode.
// Periodic() - Periodic code for autonomous mode should
// go here. Will be called periodically at a regular rate while
// the robot is in autonomous mode.
// Team 339.
package org.usfirst.frc.team339.robot;
import org.usfirst.frc.team339.Hardware.Hardware;
import org.usfirst.frc.team339.HardwareInterfaces.transmission.Transmission_old.debugStateValues;
import org.usfirst.frc.team339.Utils.Drive;
import org.usfirst.frc.team339.Utils.ErrorMessage.PrintsTo;
import org.usfirst.frc.team339.Utils.ManipulatorArm;
import org.usfirst.frc.team339.Utils.ManipulatorArm.ArmPosition;
import edu.wpi.first.wpilibj.DoubleSolenoid.Value;
import edu.wpi.first.wpilibj.Relay;
/**
* An Autonomous class.
* This class <b>beautifully</b> uses state machines in order to periodically
* execute instructions during the Autonomous period.
*
* This class contains all of the user code for the Autonomous part
* of the
* match, namely, the Init and Periodic code
*
* TODO: "make it worky".
*
*
* @author Michael Andrzej Klaczynski
* @written at the eleventh stroke of midnight, the 28th of January,
* Year of our LORD 2016. Rewritten ever thereafter.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public class Autonomous
{
/**
* The overarching states of autonomous mode.
* Each state represents a set of instructions the robot must execute
* periodically at a given time.
* These states are mainly used in the runMainStateMachine() method
*
*/
private static enum MainState
{
/**
* The first state.
* Initializes things if necessary,
* though most things are initialized
* in init().
* Proceeds to INIT_DELAY, or BEGIN_LOWERING_ARM, if in lane 1 or 6.
*/
INIT,
/**
* Sets arm to head downward.
* Used at the beginning for going under the low bar.
* Proceeds to INIT_DELAY
*/
BEGIN_LOWERING_ARM,
/**
* Resets and starts delay timer.
* Proceeds to DELAY.
*/
INIT_DELAY,
/**
* Waits.
* Waits until the delay is up.
* Proceeds to ACCELERATE_FROM_ZERO.
*/
DELAY,
/**
* Slowly increases speed from 0;
* Used at the start, as sudden movements can cause unpredictable
* turning.
* Proceeds to MOVE_TO_OUTER_WORKS.
*/
ACCELERATE_FROM_ZERO,
/**
* Moves to outer works at a lane-specific speed.
* Proceeds to FORWARDS_OVER_OUTER_WORKS.
* <p>
* UNLESS we are in lanes 1 0r 6. Then,
* If it reaches the end of the distance, and the arm is not fully down,
* proceeds to WAIT_FOR_ARM_DESCENT.
*/
MOVE_TO_OUTER_WORKS,
/**
* Wait for the arm to come down before crossing the outer works.
* Proceeds to FORWARDS_OVER_OUTER_WORKS.
*/
WAIT_FOR_ARM_DESCENT,
/**
* Go the distance over the outer works at lane-specific speed.
* Proceeds to FORWARDS_BASED_ON_ENCODERS_OR_IR.
* TODO: Continuing after this point has been temporarily disabled for
* lane 3.
*/
FORWARDS_OVER_OUTER_WORKS,
/**
* This state checks to see if we are in lane 1 (or "6").
* If so, we go until we reach an encoder distance (set to distance to
* alignment tape),
* Else, we go until the sensors find the Alignment tape.
* Proceeds to FORWARDS_TO_TAPE_BY_DISTANCE or FORWARDS_UNTIL_TAPE
*/
FORWARDS_BASED_ON_ENCODERS_OR_IR,
/**
* Goes forward until it reaches the set distance to the Alignment tape.
* Proceeds to CENTER_TO_TAPE.
*/
FORWARDS_TO_TAPE_BY_DISTANCE,
/**
* Goes forward until it senses the Alignment tape.
* Proceeds to CENTER_TO_TAPE.
*/
FORWARDS_UNTIL_TAPE,
/**
* Drives up 16 inches to put the center of the robot over the Alignment
* line.
* Brakes in lanes 3 and 4 for turning.
* Proceeds to DELAY_IF_REVERSE.
*/
CENTER_TO_TAPE,
/**
* If we are in backup plan (lane 6), start a delay so that we can
* reverse.
* TODO: this is untested.
* Proceeds to ROTATE_ON_ALIGNMENT_LINE.
*/
DELAY_IF_REVERSE,
/**
* Upon reaching the Alignment line, sometimes we must rotate.
* The angle of rotation is lane-specific. In lanes 1, 2, and 5,
* this is set to zero.
* Proceeds to FORWARDS_FROM_ALIGNMENT_LINE.
*/
ROTATE_ON_ALIGNMENT_LINE,
/**
* After reaching the A-line, or after rotating upon reaching it, drives
* towards a position in front of the goal.
* Distance is lane-specific.
* Proceeds to TURN_TO_FACE_GOAL.
*/
FORWARDS_FROM_ALIGNMENT_LINE,
/**
* After reaching a spot in front of the goal, we turn to face it.
* Angle is pre-set and lane-specific.
* Proceeds to DRIVE_UP_TO_GOAL.
*/
TURN_TO_FACE_GOAL,
/**
* Once we are facing the goal, we may sometimes drive forwards.
* Distance is lane-specific. In lanes 3 & 4, distance is zero.
*/
DRIVE_UP_TO_GOAL,
/**
* Once we are in the shooting position, we align based on the chimera.
* Proceeds to SHOOT.
*/
ALIGN_IN_FRONT_OF_GOAL,
/**
* Navigate the rest of the way by camera.
*/
DRIVE_BY_CAMERA,
/**
* We shoot the cannon ball.
* Proceeds to DELAY_AFTER_SHOOT.
*/
SHOOT,
/**
* Wait to close the solenoids, allowing the catapult to rest.
* Proceeds to DONE.
*/
DELAY_AFTER_SHOOT,
/**
* We stop, and do nothing else.
*/
DONE
}
/**
* States to run arm movements in parallel.
* Used by the runArm() state machine.
*/
private static enum ArmState
{
/**
* Begins moving the arm in a downwards/down-to-the-floor action
* fashion.
*/
INIT_DOWN,
/**
* Czecks to see if the arm is all the way down.
*/
MOVE_DOWN,
/**
* Begins moving the arm in a upwards/up-to-the-shooter action fashion.
*/
INIT_UP,
/**
* Czecks to see if the arm is all the way up.
*/
CHECK_UP,
/**
* Moves, and czecks to see if the arm is all the way up, so that we may
* deposit.
*/
MOVE_UP_TO_DEPOSIT,
/**
* Begins spinning its wheels so as to spit out the cannon ball.
*/
INIT_DEPOSIT,
/**
* Have we spit out the cannon ball? If so, INIT_DOWN.
*/
DEPOSIT,
/**
* Hold the ball out of the way.
*/
HOLD,
/**
* Do nothing, but set armStatesOn to false.
*/
DONE
}
private static final double MAXIMUM_ULTRASONIC_SLOPE = 0;
// AUTO STATES
/**
* The state to be executed periodically throughout Autonomous.
*/
private static MainState mainState = MainState.INIT;
private static MainState prevState = MainState.DONE;
/**
* Used to run arm movements in parallel to the main state machine.
*/
private static ArmState armState = ArmState.DONE;
// VARIABLES
/**
* The boolean that decides whether or not we run autonomous.
*/
public static boolean autonomousEnabled;
/**
* Time to delay at beginning. 0-3 seconds
*/
public static double delay; // time to delay before beginning.
/**
* Number of our starting position, and path further on.
*/
public static int lane;
/**
* The current index in the Acceleration arrays.
*/
private static int accelerationStage = 0;
/**
* The sum of all encoder distances before reset.
*/
private static double totalDistance = 0;
private static double[] ultrasonicDistances = new double[5];
private static int ultrasonicDistancesIndex = 0;
private static int pointCollectionIntervalCheck = 0;
/**
* Run the arm state machine only when necessary (when true).
*/
private static boolean runArmStates = false;
/**
* Prints print that it prints prints while it prints true.
*/
public static boolean debug;
//the following are for testing and debugging.
//created to print a statement only once in the run of the program.
//TODO: remove.
private static boolean oneTimePrint1 = true;
private static boolean oneTimePrint2 = true;
private static boolean oneTimePrint3 = true;
private static boolean oneTimePrint4 = false;
// TUNEABLES
/**
* User-Initialization code for autonomous mode should go here. Will be
* called once when the robot enters autonomous mode.
*
* @author Nathanial Lydick
*
* @written Jan 13, 2015
*/
public static void init ()
{
try
{
//check the Autonomous ENABLED/DISABLED switch.
autonomousEnabled = Hardware.autonomousEnabled.isOn();
// set the delay time based on potentiometer.
delay = initDelayTime();
// get the lane based off of startingPositionPotentiometer
lane = getLane();
//Enable debugging prints.
debug = DEBUGGING_DEFAULT; //true
//set Auto state to INIT.
initAutoState();
//do not print from transmission
Hardware.transmission.setDebugState(
debugStateValues.DEBUG_NONE);
// Hardware.drive.setMaxSpeed(MAXIMUM_AUTONOMOUS_SPEED);
// motor initialization
Hardware.transmission.setFirstGearPercentage(1.0);
Hardware.transmission.setGear(1);
Hardware.transmission.setJoysticksAreReversed(true);
Hardware.transmission.setJoystickDeadbandRange(0.0);
Hardware.leftFrontMotor.set(0.0);
Hardware.leftRearMotor.set(0.0);
Hardware.rightFrontMotor.set(0.0);
Hardware.rightRearMotor.set(0.0);
Hardware.armMotor.set(0.0);
Hardware.armIntakeMotor.set(0.0);
// Encoder Initialization
Hardware.leftRearEncoder.reset();
Hardware.rightRearEncoder.reset();
// Sets Resolution of camera
Hardware.ringLightRelay.set(Relay.Value.kOff);
Hardware.axisCamera.writeBrightness(
Hardware.MINIMUM_AXIS_CAMERA_BRIGHTNESS);
// turn the timer off and reset the counter
// so that we can use it in autonomous
Hardware.kilroyTimer.stop();
Hardware.kilroyTimer.reset();
//Solenoid Initialization
Hardware.catapultSolenoid0.set(false);
Hardware.catapultSolenoid1.set(false);
Hardware.catapultSolenoid2.set(false);
// setup things to run on the field or in
// the lab
if (Hardware.runningInLab == true)
labScalingFactor = 0.4;
else
labScalingFactor = 1.0;
//clear error log, so as not to take up space needlessly.
//this can be buggy, hence the try/catch.
try
{
Hardware.errorMessage.clearErrorlog();
}
catch (Exception e)
{
System.out.println("clearing log is the problem");
}
}
catch (Exception e)
{
System.out.println("Auto init died");
}
} // end Init
/**
* User Periodic code for autonomous mode should go here. Will be called
* periodically at a regular rate while the robot is in autonomous mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public static void periodic ()
{
// Checks the "enabled" switch.
if (autonomousEnabled == true)
{
//runs the overarching state machine.
runMainStateMachine();
}
// Czecks if we are running any arm functions.
if (runArmStates == true)
//run the arm state machine.
{
//System.out.println("\t" + armState);
runArmStates();
}
else
//if not, we do not want the arm to move.
{
Hardware.pickupArm.stopArmMotor();
}
if (isGettingCloserToWall(
Hardware.ultrasonic.getRefinedDistanceValue()))
{
System.out.println("Closer...");
}
} // end Periodic
/**
* Sets the delay time in full seconds based on potentiometer.
*
* @return the seconds to delay.
*/
public static int initDelayTime ()
{
//scales ratio of degrees turned by our maximum delay.
return (int) (MAXIMUM_DELAY * Hardware.delayPot.get() /
Hardware.DELAY_POT_DEGREES);
}
/**
* Sets the main state to INIT.
*/
public static void initAutoState ()
{
mainState = MainState.INIT;
}
/**
* Called periodically to run the overarching states.
* The state machine works by periodically executing a switch statement,
* which is based off of the value of the enum, mainState.
* A case that corresponds to a value of the enum is referred to as a
* "state."
* A state, therefore, is executed periodically until its end conditions are
* met, at which point it changes the value of mainState, thereby proceeding
* to the next state.
* <p>
* For information on the individual states, @see MainState.
*/
private static void runMainStateMachine ()
{
//use the debug flag
if (debug == true)
{
// print out states ONCE.
if (mainState != prevState)
{
prevState = mainState;
System.out.println(
"Legnth: " + Hardware.kilroyTimer.get() +
" seconds.\n");
System.out.println("Main State: " + mainState);
Hardware.errorMessage.printError(
"MainState" + mainState, PrintsTo.roboRIO,
false);
}
}
switch (mainState)
{
case INIT:
// Doesn't do much.
// Just a Platypus.
mainInit();
//if we are in a lane that goes beneath the low bar,
if (DriveInformation.BRING_ARM_DOWN_BEFORE_DEFENSES[lane] == true)
// lower the arm to pass beneath the bar.
{
mainState = MainState.BEGIN_LOWERING_ARM;
}
else
// lowering the arm would get in the way. Skip to delay.
{
mainState = MainState.INIT_DELAY;
}
break;
case BEGIN_LOWERING_ARM:
// starts the arm movement to the floor
runArmStates = true;
armState = ArmState.MOVE_DOWN;
// goes into initDelay
mainState = MainState.INIT_DELAY;
break;
case INIT_DELAY:
// reset and start timer
initDelay();
// run DELAY state.
mainState = MainState.DELAY;
break;
case DELAY:
// check whether done or not until done.
if (delayIsDone() == true)
// go to move forwards when finished.
{
mainState = MainState.ACCELERATE_FROM_ZERO;
//start a timer for ACCELERATE.
Hardware.delayTimer.reset();
Hardware.delayTimer.start();
}
break;
case ACCELERATE_FROM_ZERO:
//Allows us to slowly accelerate from zero without turning
//So long as there are more acceleration numbers in the series.
if (accelerationStage < DriveInformation.ACCELERATION_RATIOS.length)
{
//Drive continuously at speed increments
Hardware.drive.driveStraightByInches(99999, false,
DriveInformation.ACCELERATION_RATIOS[accelerationStage],
DriveInformation.ACCELERATION_RATIOS[accelerationStage]);
//When the time has come,
if (Hardware.delayTimer
.get() > DriveInformation.ACCELERATION_TIMES[accelerationStage])
{
//go to next stage.
accelerationStage++;
}
}
else
//there are no stages left. continue onwards.
{
//stop timer.
Hardware.delayTimer.stop();
Hardware.delayTimer.reset();
//continue forwards at regular speed.
mainState = MainState.MOVE_TO_OUTER_WORKS;
}
break;
case MOVE_TO_OUTER_WORKS:
if (oneTimePrint4 == false)
{
Hardware.transmission.setDebugState(
debugStateValues.DEBUG_ALL);
Hardware.errorMessage.printError("Left: " +
Hardware.leftRearEncoder.getDistance(),
PrintsTo.roboRIO,
false);
Hardware.errorMessage.printError("Right: " +
Hardware.leftRearEncoder.getDistance(),
PrintsTo.roboRIO,
false);
oneTimePrint4 = true;
}
else
{
Hardware.transmission.setDebugState(
debugStateValues.DEBUG_NONE);
}
// goes forwards to outer works.
if (Hardware.drive.driveStraightByInches(
DriveInformation.DISTANCE_TO_OUTER_WORKS *
labScalingFactor,
false,
DriveInformation.MOTOR_RATIO_TO_OUTER_WORKS[lane],
DriveInformation.MOTOR_RATIO_TO_OUTER_WORKS[lane]) == true)
//continue over the outer works unless the arm is going to get in the way.
{
//continue over the Outer Works
mainState = MainState.FORWARDS_OVER_OUTER_WORKS;
resetEncoders();
//UNLESS...
// if we are in a lane that goes beneath the low bar,
if ((DriveInformation.BRING_ARM_DOWN_BEFORE_DEFENSES[lane] == true)
&&
(Hardware.pickupArm.isUnderBar() == false))
//arm is not down in time. STOP.
{
mainState = MainState.WAIT_FOR_ARM_DESCENT;
}
}
break;
case WAIT_FOR_ARM_DESCENT:
Hardware.transmission.setDebugState(
debugStateValues.DEBUG_NONE);
//Stop during the wait. We do not want to ram the bar.
Hardware.transmission.controls(0.0, 0.0);
//Put the arm down,
//and when that is done, continue.
if (Hardware.pickupArm.moveToPosition(
ManipulatorArm.ArmPosition.FULL_DOWN) == true)
{
//drive over the outer works.
mainState = MainState.FORWARDS_OVER_OUTER_WORKS;
}
break;
case FORWARDS_OVER_OUTER_WORKS:
//Drive over Outer Works.
if (Hardware.drive.driveStraightByInches(
DriveInformation.DISTANCE_OVER_OUTER_WORKS *
labScalingFactor +
DriveInformation.ADDED_DISTANCE_FROM_OW[lane],
false,
DriveInformation.DRIVE_OVER_OUTER_WORKS_MOTOR_RATIOS[lane],
DriveInformation.DRIVE_OVER_OUTER_WORKS_MOTOR_RATIOS[lane]) == true)
//put up all the things we had to put down under the low bar.
//begin loading the catapult.
{
//put up camera.
Hardware.cameraSolenoid.set(Value.kReverse);
Hardware.ringLightRelay.set(Relay.Value.kOn);
//Teleop.printStatements();
// System.out.println("Encoders: "
// + Hardware.leftRearEncoder.getDistance() + "\t"
// + Hardware.rightRearEncoder.getDistance());
resetEncoders();
//We are over the outer works. Start the arm back up.
armState = ArmState.MOVE_UP_TO_DEPOSIT;
runArmStates = true;
//decide whether to stop next by encoder distance, or when IRs detect tape.
mainState = MainState.FORWARDS_BASED_ON_ENCODERS_OR_IR;
//temporary; stops after over outer works.
//3 is chosen for this arbitrarily.
if (lane == 3)
{
mainState = MainState.DONE;
}
if (DriveInformation.SKIP_TO_DRIVE_BY_CAMERA[lane] == true)
{
mainState = MainState.DRIVE_BY_CAMERA;
}
}
break;
case FORWARDS_BASED_ON_ENCODERS_OR_IR:
// Check if we are in lane One.
if (lane == 1 || lane == 6)
// If so, move forwards the distance to the A-tape.
{
mainState = MainState.FORWARDS_TO_TAPE_BY_DISTANCE;
}
else
// If in another lane, move forwards until we detect the A-tape.
{
mainState = MainState.FORWARDS_UNTIL_TAPE;
}
break;
case FORWARDS_TO_TAPE_BY_DISTANCE:
// Drive the distance from outer works to A-Line.
if ((Hardware.drive.driveStraightByInches(
DriveInformation.DISTANCE_TO_TAPE *
labScalingFactor,
false, DriveInformation.MOTOR_RATIO_TO_A_LINE[lane],
DriveInformation.MOTOR_RATIO_TO_A_LINE[lane]) == true))
// when done, proceed from Alignment line.
{
//Teleop.printStatements();
//reset Encoders to prepare for next state.
resetEncoders();
//Move the center of the robot to the tape.
mainState = MainState.CENTER_TO_TAPE;
}
break;
case FORWARDS_UNTIL_TAPE:
// Drive until IR sensors pick up tape.
if (hasMovedToTape() == true)
{
//reset Encoders to prepare for next state.
resetEncoders();
// When done, possibly rotate.
mainState = MainState.CENTER_TO_TAPE;
}
break;
case CENTER_TO_TAPE:
//Drive up from front of the Alignment Line to put the pivoting center of the robot on the Line.
if (Hardware.drive.driveStraightByInches(
DriveInformation.DISTANCE_TO_CENTRE_OF_ROBOT,
DriveInformation.BREAK_ON_ALIGNMENT_LINE[lane],
DriveInformation.CENTRE_TO_ALIGNMENT_LINE_MOTOR_RATIO[lane],
DriveInformation.CENTRE_TO_ALIGNMENT_LINE_MOTOR_RATIO[lane]))
{
//Next, we will stop if necessary.
mainState = MainState.DELAY_IF_REVERSE;
//start timer for the coming delay.
Hardware.delayTimer.reset();
Hardware.delayTimer.start();
}
break;
case DELAY_IF_REVERSE:
//when the delay is up,
if (Hardware.delayTimer
.get() >= DriveInformation.DELAY_IF_REVERSE[lane])
//continue driving.
{
//stop the timer
Hardware.delayTimer.stop();
//rotate, possibly
mainState = MainState.ROTATE_ON_ALIGNMENT_LINE;
}
break;
case ROTATE_ON_ALIGNMENT_LINE:
//Rotates until we are pointed at the place from whence we want to shoot.
if (hasTurnedBasedOnSign(
DriveInformation.ROTATE_ON_ALIGNMENT_LINE_DISTANCE[lane]
*
labScalingFactor) == true)
{
//reset Encoders to prepare for next state.
resetEncoders();
//then move.
mainState = MainState.FORWARDS_FROM_ALIGNMENT_LINE;
}
break;
case FORWARDS_FROM_ALIGNMENT_LINE:
//Drive until we reach the line normal to the goal.
if (Hardware.drive.driveStraightByInches(
DriveInformation.FORWARDS_FROM_ALIGNMENT_LINE_DISTANCE[lane]
*
labScalingFactor,
true, //breaking here is preferable.
DriveInformation.FORWARDS_FROM_ALIGNMENT_LINE_MOTOR_RATIO[lane],
DriveInformation.FORWARDS_FROM_ALIGNMENT_LINE_MOTOR_RATIO[lane]) == true)
{
//reset Encoders to prepare for next state.
resetEncoders();
//turn once more.
mainState = MainState.TURN_TO_FACE_GOAL;
}
break;
case TURN_TO_FACE_GOAL:
//Turns until we are facing the goal.
if (hasTurnedBasedOnSign(
DriveInformation.TURN_TO_FACE_GOAL_DEGREES[lane]) == true)
//when done move up to the batter.
{
//reset Encoders to prepare for next state
resetEncoders();
//Hardware.ringLightRelay.set(Relay.Value.kOn);
//Hold the arm up (Out of the Way).
armState = ArmState.HOLD;
Hardware.transmission.controls(0.0, 0.0);
//then drive.
mainState = MainState.DRIVE_UP_TO_GOAL;
}
break;
case DRIVE_UP_TO_GOAL:
//print encoders once
//TODO: remove.
if (oneTimePrint1 == false)
{
oneTimePrint1 = true;
System.out.println(mainState + "\n\tLeft Encoder: " +
Hardware.leftRearEncoder.getDistance() +
"\n\tLeft Encoder: " +
Hardware.leftRearEncoder.getDistance());
}
//Moves to goal. Stops to align.
if (((Hardware.drive.driveStraightByInches(
DriveInformation.DRIVE_UP_TO_GOAL[lane] *
labScalingFactor,
false,
DriveInformation.DRIVE_UP_TO_GOAL_MOTOR_RATIO[lane],
DriveInformation.DRIVE_UP_TO_GOAL_MOTOR_RATIO[lane]) == true)))
//Go to align.
{
if (oneTimePrint2 == false)
{
oneTimePrint2 = true;
System.out.println(mainState +
"\n\tLeft Encoder: " +
Hardware.leftRearEncoder.getDistance() +
"\n\tLeft Encoder: " +
Hardware.leftRearEncoder.getDistance());
}
//reset Encoders to prepare for next state.
resetEncoders();
//go to align.
mainState = MainState.ALIGN_IN_FRONT_OF_GOAL;
}
//print IR values once if they are on.
// if (oneTimePrint3 == false &&
// (Hardware.leftIR.isOn() || Hardware.rightIR.isOn()))
// oneTimePrint3 = true;
// System.out.println("An IR found something.");
break;
case ALIGN_IN_FRONT_OF_GOAL:
//align based on the camera until we are facing the goal. head-on.
//Hardware.transmission.controls(0.0, 0.0);
if (Hardware.drive.alignByCamera(
Autonomous.CAMERA_ALIGN_X_DEADBAND,
DriveInformation.ALIGNMENT_SPEED,
CAMERA_X_AXIS_ADJUSTED_PROPORTIONAL_CENTER,
true) == Drive.alignByCameraReturn.DONE)
//Once we are in position, we shoot!
{
mainState = MainState.SHOOT;
}
break;
case DRIVE_BY_CAMERA:
if (Hardware.drive.alignByCameraStateMachine(
CAMERA_ALIGN_X_DEADBAND,
CAMERA_ALIGN_Y_DEADBAND,
CAMERA_X_AXIS_ADJUSTED_PROPORTIONAL_CENTER,
CAMERA_Y_AXIS_ADJUSTED_PROPORTIONAL_CENTER,
ALIGN_BY_CAMERA_TURNING_SPEED,
ALIGN_BY_CAMERA_DRIVE_SPEED,
false,
false, false) == Drive.alignByCameraReturn.DONE)
{
mainState = MainState.SHOOT;
}
break;
case SHOOT:
//FIRE!!!
if (shoot() == true)
{
//go to wait a little bit, before turning off solenoids
mainState = MainState.DELAY_AFTER_SHOOT;
}
break;
case DELAY_AFTER_SHOOT:
//Check if enough time has passed for the air to have been released.
if (hasShot() == true)
{
//This block will close all solenoids,
//allowing the catapult to go back down.
Hardware.catapultSolenoid0.set(false);
Hardware.catapultSolenoid1.set(false);
Hardware.catapultSolenoid2.set(false);
//finish it.
mainState = MainState.DONE;
}
break;
default:
case DONE:
//clean everything up;
//the blood of our enemies stains quickly.
done();
break;
}
}
private static void mainInit ()
{
//start at zero.
resetEncoders();
//start the timer.
Hardware.kilroyTimer.reset();
Hardware.kilroyTimer.start();
}
/**
* Starts the delay timer.
*/
private static void initDelay ()
{
Hardware.delayTimer.reset();
Hardware.delayTimer.start();
}
/**
* Waits.
* One of the overarching states.
*/
private static boolean delayIsDone ()
{
boolean done = false;
// stop.
Hardware.transmission.controls(0.0, 0.0);
// check timer
if (Hardware.delayTimer.get() > delay)
// return true. stop and reset timer.
{
done = true;
Hardware.delayTimer.stop();
Hardware.delayTimer.reset();
}
return done;
}
/**
* Drives, and
* Checks to see if the IRSensors detect Alignment tape.
*
* @return true when it does.
*/
private static boolean hasMovedToTape ()
{
//The stateness of being on the tape.
boolean tapeness = false;
// Move forwards.
Hardware.drive.driveStraightContinuous();
// simply check if we have detected the tape on either side.
if (Hardware.leftIR.isOn() || Hardware.rightIR.isOn())
// we are done here.
{
tapeness = true;
}
return tapeness;
}
/**
* <b> FIRE!!! </b>
* <p>
* Shoots the ball.
*
*/
private static boolean shoot ()
{
//to be returned true if done.
boolean done;
//Turn off motors. We do NOT want to move.
Hardware.transmission.controls(0.0, 0.0);
//Make sure the arm is out of the way.
if (Hardware.pickupArm.isClearOfArm())
{
//RELEASE THE KRACKEN! I mean, the pressurized air...
Hardware.catapultSolenoid0.set(true);
Hardware.catapultSolenoid1.set(true);
Hardware.catapultSolenoid2.set(true);
//set a timer so that we know when to close the solenoids.
Hardware.kilroyTimer.reset();
Hardware.kilroyTimer.start();
//stop arm motion.
runArmStates = false;
//is finished.
done = true;
}
else
{
//get the arm out of the way.
runArmStates = true;
armState = ArmState.MOVE_DOWN;
//continue until it is done.
done = false;
}
//true if done.
return done;
}
/**
* Wait a second...
* Close the solenoids.
*
* @return true when delay is up.
*/
private static boolean hasShot ()
{
//Check the time.
if (Hardware.kilroyTimer.get() > DELAY_TIME_AFTER_SHOOT)
//Close the airways, and finish.
{
Hardware.catapultSolenoid0.set(false);
Hardware.catapultSolenoid1.set(false);
Hardware.catapultSolenoid2.set(false);
return true;
}
return false;
}
/**
* Stop everything.
*/
private static void done ()
{
//after autonomous is disabled, the state machine will stop.
//this code will run but once.
autonomousEnabled = false;
//stop printing debug statements.
debug = false;
//turn off all motors.
Hardware.transmission.controls(0.0, 0.0);
//including the arm.
//end any surviving arm motions.
armState = ArmState.DONE;
Hardware.armMotor.set(0.0);
//reset delay timer
Hardware.delayTimer.stop();
Hardware.delayTimer.reset();
//turn off ringlight.
Hardware.ringLightRelay.set(Relay.Value.kOff);
Hardware.transmission
.setDebugState(debugStateValues.DEBUG_NONE);
}
/**
* A separate state machine, used to run arm movements in parallel.
*/
private static void runArmStates ()
{
switch (armState)
{
case INIT_DOWN:
//begin moving arm down
Hardware.pickupArm.move(-1.0);
//go to periodically check.
armState = ArmState.MOVE_DOWN;
break;
case MOVE_DOWN:
//move to down position.
if (Hardware.pickupArm.moveToPosition(
ArmPosition.FULL_DOWN) == true)
//if done, stop.
{
//stop the motor.
Hardware.pickupArm.move(0.0);
armState = ArmState.DONE;
}
break;
case INIT_UP:
//begin moving arm up.
Hardware.pickupArm.move(1.0);
//go to periodically check.
armState = ArmState.CHECK_UP;
break;
case CHECK_UP:
//check if up.
if (Hardware.pickupArm.isUp() == true)
{
//stop.
Hardware.pickupArm.move(0.0);
armState = ArmState.DONE;
}
break;
case MOVE_UP_TO_DEPOSIT:
//check is in up position so that we may deposit the ball.
if (Hardware.pickupArm.moveToPosition(
ArmPosition.DEPOSIT) == true)
//stop, and go to deposit.
{
Hardware.pickupArm.move(0.0);
armState = ArmState.INIT_DEPOSIT;
}
break;
case INIT_DEPOSIT:
//spin wheels to release ball. Uses override.
Hardware.pickupArm.pullInBall(true);
armState = ArmState.DEPOSIT;
break;
case DEPOSIT:
//check if the ball is out.
if (Hardware.pickupArm.ballIsOut())
//stop rollers, and move down.
{
//stop the intake motors.
Hardware.pickupArm.stopIntakeMotors();
//TODO: get arms out of the way.
armState = ArmState.DONE;
}
break;
case HOLD:
//do not move the intake motors.
Hardware.pickupArm.stopIntakeMotors();
//keep the arms in holding position
Hardware.pickupArm.moveToPosition(ArmPosition.HOLD);
//note: no end conditions, unless if the state is manually changed.
break;
default:
case DONE:
//stop running state machine.
runArmStates = false;
break;
}
}
//TODO: Remove unecessary TODOs
/**
* Return the starting position based on 6-position switch on the robot.
*
* @return lane/starting position
*/
public static int getLane ()
{
//get the value from the six-position switch.
int position = Hardware.startingPositionDial.getPosition();
//-1 is returned when there is no signal.
if (position == -1)
//Go to lane 1 by default.
{
position = 0;
}
//increment by one, to correspond to lane
position++;
return position;
}
/**
* Reset left and right encoders.
* To be called at the end of any state that uses Drive.
*/
public static void resetEncoders ()
{
//accumulate total distance. used for debugging.
totalDistance += (Hardware.leftRearEncoder.getDistance() +
Hardware.rightRearEncoder.get()) / 2;
//reset.
Hardware.leftRearEncoder.reset();
Hardware.rightRearEncoder.reset();
}
/**
* For turning in drive based on array of positive and negative values.
* Use to turn a number of degrees
* COUNTERCLOCKWISE.
* Kilroy must turn along different paths.
* You must use this to be versatile.
*
* @param degrees
* is the number of degrees to be turned. A positive value will
* turn left, while a negative value will turn right.
*
* @param turnSpeed
* will be passed into both motors, one positive, one negative,
* depending on the direction of the turn.
*
* @return true when the turn is finished.
*/
private static boolean hasTurnedBasedOnSign (double degrees,
double turnSpeed)
{
//the value of done will be returned.
boolean done = false;
if (degrees < 0)
//Turn right. Make degrees positive.
{
done = Hardware.drive.turnRightDegrees(-degrees, true,
turnSpeed,
-turnSpeed);
}
else
//Turn left the given number of degrees.
{
done = Hardware.drive.turnLeftDegrees(degrees, true,
-turnSpeed,
turnSpeed);
}
return done;
}
/**
* Tells us if we are getting any closer to a thing after being given 55
* points.
*
*
*
* @param point
* is given one-at-a-time.
* @return true if closer.
*/
private static boolean isGettingCloserToWall (double point)
{
//TODO: Demystify magic numbers.
//return true if we are closer.
boolean isCloser = false;
//We do not take a point every iteration. Only every 11th point.
//We end up with 5 point for each check.
pointCollectionIntervalCheck++;
if (pointCollectionIntervalCheck == 11)
{
//reset
pointCollectionIntervalCheck = 0;
//add the point to the array
ultrasonicDistances[ultrasonicDistancesIndex] = (int) point;
ultrasonicDistancesIndex++;
//if the array is full, check the slope.
if (ultrasonicDistancesIndex == ultrasonicDistances.length)
{
//if the slope is negative, we are getting closer.
if (getRegressionSlopeOfArray(
ultrasonicDistances) < MAXIMUM_ULTRASONIC_SLOPE)
{
//and so, we will return true.
isCloser = true;
}
//reset the array.
ultrasonicDistances = new double[5];
ultrasonicDistancesIndex = 0;
}
}
return isCloser;
}
/**
* Used by isGettingCloserToWall to determine the direction of the robot.
*
* @param data
* in which index is the x axis.
* @return slope technically is in inches per fifth of a second.
*/
private static double getRegressionSlopeOfArray (double[] data)
{
/*
* Formula: (Sigma --> E)
* E ((x-(mean x))(y-(mean y))) / E ((x-(mean x))^2)
*/
int slope;
int ySum = 0;
int xSum = 0;
int bigN = data.length;
//sum all values for regression calculation
for (int i = 0; i < data.length; i++)
{
ySum += data[i];
xSum += i;
}
int xBar = xSum / bigN;
int yBar = ySum / bigN;
int numeratorSum = 0;
int denomenatorSum = 0;
for (int i = 0; i < data.length; i++)
{
numeratorSum += ((i - xBar) * (data[i] - yBar));
denomenatorSum += ((i - xBar) * (i - xBar));
}
//calculate regression line slope
slope = numeratorSum / denomenatorSum;
return slope;
}
/**
* For turning in drive based on array of positive and negative values.
* Use to turn a number of degrees
* COUNTERCLOCKWISE.
* Kilroy must turn along different paths.
* You must use this to be versatile.
*
* @param degrees
* is the number of degrees to be turned. A positive value will
* turn left, while a negative value will turn right.
*
* @return true when the turn is finished.
*/
private static boolean hasTurnedBasedOnSign (double degrees)
{
return hasTurnedBasedOnSign(degrees,
DriveInformation.DEFAULT_TURN_SPEED);
}
/**
* Contains distances and speeds at which to drive.
*
* Note that many of these are arrays.
* This is usually to determine different speeds and distances for each
* lane.
* Such arrays will follow the following format:
*
* </p>
* [0]: placeholder, so that the index will match up with the lane number
* </p>
* [1]: lane 1
* </p>
* [2]: lane 2
* </p>
* [3]: lane 3
* </p>
* [4]: lane 4
* </p>
* [5]: lane 5
* </p>
* [6]: "lane 6" -- not a real lane, but can serve as an alternate strategy.
*/
private static final class DriveInformation
{
/**
* A set of motor ratios that will be used in succession
* when accelerating from zero.
*
* Index here does not correspond to lane, but rather order of
* execution.
*/
private static final double[] ACCELERATION_RATIOS =
{
0.1,
0.2,
0.3
};
/**
* The time at which each acceleration stage will end.
*
* Index here does not correspond to lane, but rather order of
* execution.
*/
private static final double[] ACCELERATION_TIMES =
{
0.2,
0.4,
0.6
};
/**
* The speed at which we want to go over the outer works, for each lane.
* note that it is to be low for lane 1, yet high for the others,
* so as to accommodate more difficult obstacles.
*/
private static final double[] DRIVE_OVER_OUTER_WORKS_MOTOR_RATIOS =
{
0.0,
0.5,//not much is required for the low bar.
0.5,
0.8,
0.5,
0.5,
0.4
};
private static final boolean[] BRING_ARM_DOWN_BEFORE_DEFENSES =
{
false, // a placeholder, allowing lane to line up with index
true, // lane 1 - bring arm down
false, // lane 2
false, // lane 3
false, // lane 4
false, // lane 5
true // lane 6 - bring arm down
};
/**
* For each lane, decides whether or not to break on the Alignment Line
*/
private static final boolean[] BREAK_ON_ALIGNMENT_LINE =
{
false, // A placeholder, allowing lane to line up with index.
false,
false,
true, // true in lanes 3 and 4,
true, // because we mean to turn next.
false,
true //or go backwards.
};
private static final boolean[] SKIP_TO_DRIVE_BY_CAMERA =
{
false,
false,
false,
false,
true, //lane 4.
false,
false
};
/**
* The motor controller values for moving to the outer works.
* As these are initial speeds, keep them low, to go easy on the motors.
* Lane is indicated by index.
*/
private static final double[] MOTOR_RATIO_TO_OUTER_WORKS =
{
0.0, // nothing. Not used. Arbitrary; makes it work.
0.50,//0.25, // lane 1, should be extra low.
1.0, // lane 2
0.5, // lane 3
0.5, // lane 4
0.5, // lane 5
0.5 //backup plan
};
/**
* "Speeds" at which to drive from the Outer Works to the Alignment
* Line.
*/
private static final double[] MOTOR_RATIO_TO_A_LINE =
{
0.0, //PLACEHOLDER
0.5, //lane 1
0.5, //lane 2
0.4, //lane 3
0.4, //lane 4
0.5, //lane 5
0.0 //backup plan
};
/**
* Distances to rotate upon reaching alignment line.
* Lane is indicated by index.
* Set to Zero for 1, 2, and 5.
*/
private static final double[] ROTATE_ON_ALIGNMENT_LINE_DISTANCE =
{
0.0, // nothing. Not used. Arbitrary; makes it work.
0.0, // lane 1 (not neccesary)
0.0, // lane 2 (not neccesary)
-72.85,//-20, // lane 3
64.24,//24.8, // lane 4
0.0, // lane 5 (not neccesary)
0.0 //backup plan
};
/**
* Distances to drive after reaching alignment tape.
* Lane is indicated by index.
* 16 inchworms added inevitably, to start from centre of robot.
*/
private static final double[] FORWARDS_FROM_ALIGNMENT_LINE_DISTANCE =
{
0.0, // nothing. Not used. Arbitrary; makes it work.
36.57,// lane 1 //48.57
77.44,//68.0,// lane 2
66.14,//64.0, // lane 3
63.2,//66.1,// lane 4
85.8, // lane 5
-169.0 //backup plan
};
/**
* Speed when we move the centre of the robot to the Alignment line.,
*/
private static final double[] CENTRE_TO_ALIGNMENT_LINE_MOTOR_RATIO =
{
0.0,
0.5,
0.5,
.25,
.25,
0.5,
0.25 //backup plan
};
/**
* "Speeds" at which to drive from the A-Line to the imaginary line
* normal to
* the goal.
*/
private static final double[] FORWARDS_FROM_ALIGNMENT_LINE_MOTOR_RATIO =
{
0.0, // nothing. A Placeholder.
0.5, //lane 1
0.5, //lane 2
0.7, //lane 3
0.7, //lane 4
0.5, //lane 5
-0.5 //backup plan
};
/**
* Distances to rotate to face goal.
*/
private static final double[] TURN_TO_FACE_GOAL_DEGREES =
{
0.0, // makes it so the indexes line up with the lane
-60.0,// lane 1 //-60
-60.0,// lane 2
72.85,//20.0,// lane 3
-64.24,//-24.85,// lane 4
60, // lane 5
-90.0 //backup plan
};
/**
* Distances to travel once facing the goal.
* Not neccesary for lanes 3 and 4; set to zero.
* Actually, we may not use this much at all, given that we will
* probably just
* use the IR to sense the cleets at the bottom of the tower.
*/
private static final double[] DRIVE_UP_TO_GOAL =
{
0.0, // nothing. Not used. Arbitrary; makes it work.
53.85,//previously 62.7//65.85,// lane 1
18.1,//52.9,// lane 2
0.0,// lane 3 (not neccesary)
0.0,// lane 4 (not neccesary)
32.8,//12.0, // lane 5
0.0 //backup plan
};
/**
* "Speeds" at which to drive to the Batter.
*/
private static final double[] DRIVE_UP_TO_GOAL_MOTOR_RATIO =
{
0.0,
0.50,
0.5,
0.5,
0.5,
0.5,
0.0
};
/**
* Time to delay at A-line. Only used if reversing.
*/
private static final double[] DELAY_IF_REVERSE =
{
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0//only used in "lane 6."
};
/**
* Should we want to stop upon going over the outer works,
* this should add extra distance, for assurance.
*/
private static final double[] ADDED_DISTANCE_FROM_OW =
{
0.0,
0.0,
0.0,
48.0,// Further driving is disabled in this lane,
// so this is to be sure we are all the way over.
60.0,
0.0,
0.0
};
/**
* Distance from Outer Works checkpoint to Alignment Line.
* The front of the robot will be touching the Lion.
*/
private static final double DISTANCE_TO_TAPE = 27.5;
/**
* Distance to get the front of the robot to the Outer Works.
*/
private static final double DISTANCE_TO_OUTER_WORKS = 16.75; //prev. 22.75;
/**
* Distance to travel to get over the Outer Works.
*/
private static final double DISTANCE_OVER_OUTER_WORKS = 104.86; //prev. 98.86;
/**
* The distance to the central pivot point from the front of the robot.
* We will use this so that we may rotate around a desired point at the
* end of a
* distance.
*/
private static final double DISTANCE_TO_CENTRE_OF_ROBOT = 16.0;
/**
* Speed at which to make turns by default.
*/
private static final double DEFAULT_TURN_SPEED = 0.55;
/**
* Speed at which we may align by camera.
*/
private static final double ALIGNMENT_SPEED = 0.5;
}
/**
* The maximum time to wait at the beginning of the match.
* Used to scale the ratio given by the potentiometer.
*/
private static final double MAXIMUM_DELAY = 3.0;
/**
* Set to true to print out print statements.
*/
public static final boolean DEBUGGING_DEFAULT = true;
/**
* Factor by which to scale all distances for testing in our small lab
* space.
*/
public static double labScalingFactor = 1.0;
/**
* Time to wait after releasing the solenoids before closing them back up.
*/
private static final double DELAY_TIME_AFTER_SHOOT = 1.0;
private static final double CAMERA_ALIGN_Y_DEADBAND = .10;
private static final double CAMERA_ALIGN_X_DEADBAND = .125;
private static final double CAMERA_X_AXIS_ADJUSTED_PROPORTIONAL_CENTER =
-.375;
private static final double CAMERA_Y_AXIS_ADJUSTED_PROPORTIONAL_CENTER =
-.192;
private static final double ALIGN_BY_CAMERA_TURNING_SPEED = .55;
private static final double ALIGN_BY_CAMERA_DRIVE_SPEED = .45;
} // end class |
package org.vitrivr.cineast.core.util;
public class MathHelper {
private MathHelper(){}
public static final double SQRT2 = Math.sqrt(2);
public static final float SQRT2_f = (float)SQRT2;
public static double getScore(double dist, double maxDist){
if(Double.isNaN(dist) || Double.isNaN(maxDist)){
return 0d;
}
double score = 1d - (dist / maxDist);
if(score > 1d){
return 1d;
}
if(score < 0d){
return 0d;
}
return score;
}
/**
* Normalizes a float array with respect to the L2 (euclidian) norm. The
* method will return a new array and leave the original array unchanged.
*
* @param v Array that should be normalized.
* @return Normalized array.
*/
public static float[] normalizeL2(float[] v) {
double norm = normL2(v);
if (norm > 0.0f) {
float[] vn = new float[v.length];
for (int i = 0; i < v.length; i++) {
vn[i] = (float) (v[i] / norm);
}
return vn;
} else {
return v;
}
}
/**
* Normalizes a double array with respect to the L2 (euclidian) norm. The
* method will return a new array and leave the original array unchanged.
*
* @param v Array that should be normalized.
* @return Normalized array.
*/
public static double[] normalizeL2(double[] v) {
double norm = normL2(v);
if (norm > 0.0f) {
double[] vn = new double[v.length];
for (int i = 0; i < v.length; i++) {
vn[i] = (float) (v[i] / norm);
}
return vn;
} else {
return v;
}
}
/**
* Calculates and returns the L2 (euclidian) norm of a float array.
*
* @param v Float array for which to calculate the L2 norm.
* @return L2 norm
*/
public static double normL2(float[] v) {
float dist = 0;
for(int i = 0; i < v.length; i++){
dist += Math.pow(v[i], 2);
}
return Math.sqrt(dist);
}
/**
* Calculates and returns the L2 (euclidian) norm of a double array.
*
* @param v Double array for which to calculate the L2 norm.
* @return L2 norm
*/
public static double normL2(double[] v) {
float dist = 0;
for(int i = 0; i < v.length; i++){
dist += Math.pow(v[i], 2);
}
return Math.sqrt(dist);
}
/**
* Checks whether the provided array is a zero array or not.
*
* @param array Array to check
* @return true if array is not zero, false otherwise.
*/
public static boolean checkNotZero(double[] array) {
for (double v : array) {
if (v > 0.0 || v < 0.0) return true;
}
return false;
}
/**
* Checks whether the provided array is a zero array or not.
*
* @param array Array to check
* @return true if array is not zero, false otherwise.
*/
public static boolean checkNotZero(float[] array) {
for (float v : array) {
if (v > 0.0 || v < 0.0) return true;
}
return false;
}
/**
* Checks whether the provided array is a zero array or not.
*
* @param array Array to check
* @return true if array is not zero, false otherwise.
*/
public static boolean checkNotNaN(double[] array) {
for (double v : array) {
if (Double.isNaN(v)) return false;
}
return true;
}
/**
* Checks whether the provided array is a zero array or not.
*
* @param array Array to check
* @return true if array is not zero, false otherwise.
*/
public static boolean checkNotNaN(float[] array) {
for (float v : array) {
if (Float.isNaN(v)) return false;
}
return true;
}
public static float limit(float val, float min, float max){
val = val > max ? max : val;
val = val < min ? min : val;
return val;
}
/**
* Kronecker-Delta function. Returns 1 if i=j and 0 otherwise.
*
* @param i Value of i
* @param j Value of j
* @return Result of Kronecker-Delta.
*/
public static int kronecker(int i, int j) {
if (j == i) {
return 1;
} else {
return 0;
}
}
} |
package com.oracle.graal.phases.common.inlining;
import static com.oracle.graal.compiler.common.GraalOptions.*;
import java.util.*;
import java.util.function.*;
import com.oracle.graal.api.code.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.compiler.common.*;
import com.oracle.graal.debug.*;
import com.oracle.graal.debug.Debug.Scope;
import com.oracle.graal.graph.Graph.Mark;
import com.oracle.graal.graph.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.java.*;
import com.oracle.graal.options.*;
import com.oracle.graal.phases.common.*;
import com.oracle.graal.phases.common.inlining.info.InlineInfo;
import com.oracle.graal.phases.common.inlining.InliningUtil.Inlineable;
import com.oracle.graal.phases.common.inlining.InliningUtil.InlineableGraph;
import com.oracle.graal.phases.common.inlining.InliningUtil.InlineableMacroNode;
import com.oracle.graal.phases.common.inlining.policy.GreedyInliningPolicy;
import com.oracle.graal.phases.common.inlining.policy.InliningPolicy;
import com.oracle.graal.phases.graph.*;
import com.oracle.graal.phases.tiers.*;
import com.oracle.graal.phases.util.*;
public class InliningPhase extends AbstractInliningPhase {
public static class Options {
// @formatter:off
@Option(help = "Unconditionally inline intrinsics")
public static final OptionValue<Boolean> AlwaysInlineIntrinsics = new OptionValue<>(false);
// @formatter:on
}
private final InliningPolicy inliningPolicy;
private final CanonicalizerPhase canonicalizer;
private int inliningCount;
private int maxMethodPerInlining = Integer.MAX_VALUE;
private static final DebugMetric metricInliningConsidered = Debug.metric("InliningConsidered");
public InliningPhase(CanonicalizerPhase canonicalizer) {
this(new GreedyInliningPolicy(null), canonicalizer);
}
public InliningPhase(Map<Invoke, Double> hints, CanonicalizerPhase canonicalizer) {
this(new GreedyInliningPolicy(hints), canonicalizer);
}
public InliningPhase(InliningPolicy policy, CanonicalizerPhase canonicalizer) {
this.inliningPolicy = policy;
this.canonicalizer = canonicalizer;
}
public void setMaxMethodsPerInlining(int max) {
maxMethodPerInlining = max;
}
public int getInliningCount() {
return inliningCount;
}
/**
* <p>
* The space of inlining decisions is explored depth-first with the help of a stack realized by
* {@link InliningData}. At any point in time, its topmost element consist of:
* <ul>
* <li>
* one or more {@link CallsiteHolder}s of inlining candidates, all of them corresponding to a
* single callsite (details below). For example, "exact inline" leads to a single candidate.</li>
* <li>
* the callsite (for the targets above) is tracked as a {@link MethodInvocation}. The difference
* between {@link MethodInvocation#totalGraphs()} and {@link MethodInvocation#processedGraphs()}
* indicates the topmost {@link CallsiteHolder}s that might be delved-into to explore inlining
* opportunities.</li>
* </ul>
* </p>
*
* <p>
* The bottom-most element in the stack consists of:
* <ul>
* <li>
* a single {@link CallsiteHolder} (the root one, for the method on which inlining was called)</li>
* <li>
* a single {@link MethodInvocation} (the {@link MethodInvocation#isRoot} one, ie the unknown
* caller of the root graph)</li>
* </ul>
*
* </p>
*
* <p>
* The stack grows and shrinks as choices are made among the alternatives below:
* <ol>
* <li>
* not worth inlining: pop any remaining graphs not yet delved into, pop the current invocation.
* </li>
* <li>
* process next invoke: delve into one of the callsites hosted in the current candidate graph,
* determine whether any inlining should be performed in it</li>
* <li>
* try to inline: move past the current inlining candidate (remove it from the topmost element).
* If that was the last one then try to inline the callsite that is (still) in the topmost
* element of {@link InliningData}, and then remove such callsite.</li>
* </ol>
* </p>
*
* <p>
* Some facts about the alternatives above:
* <ul>
* <li>
* the first step amounts to backtracking, the 2nd one to delving, and the 3rd one also involves
* bakctraking (however after may-be inlining).</li>
* <li>
* the choice of abandon-and-backtrack or delve-into is depends on
* {@link InliningPolicy#isWorthInlining} and {@link InliningPolicy#continueInlining}.</li>
* <li>
* the 3rd choice is picked when both of the previous one aren't picked</li>
* <li>
* as part of trying-to-inline, {@link InliningPolicy#isWorthInlining} again sees use, but
* that's another story.</li>
* </ul>
* </p>
*
*/
@Override
protected void run(final StructuredGraph graph, final HighTierContext context) {
final InliningData data = new InliningData(graph, context.getAssumptions(), maxMethodPerInlining, canonicalizer);
ToDoubleFunction<FixedNode> probabilities = new FixedNodeProbabilityCache();
while (data.hasUnprocessedGraphs()) {
final MethodInvocation currentInvocation = data.currentInvocation();
if (!currentInvocation.isRoot() &&
!inliningPolicy.isWorthInlining(probabilities, context.getReplacements(), currentInvocation.callee(), data.inliningDepth(), currentInvocation.probability(),
currentInvocation.relevance(), false)) {
int remainingGraphs = currentInvocation.totalGraphs() - currentInvocation.processedGraphs();
assert remainingGraphs > 0;
data.popGraphs(remainingGraphs);
data.popInvocation();
} else if (data.currentGraph().hasRemainingInvokes() && inliningPolicy.continueInlining(data.currentGraph().graph())) {
data.processNextInvoke(context);
} else {
data.popGraph();
if (!currentInvocation.isRoot()) {
assert currentInvocation.callee().invoke().asNode().isAlive();
currentInvocation.incrementProcessedGraphs();
if (currentInvocation.processedGraphs() == currentInvocation.totalGraphs()) {
data.popInvocation();
final MethodInvocation parentInvoke = data.currentInvocation();
try (Scope s = Debug.scope("Inlining", data.inliningContext())) {
boolean wasInlined = tryToInline(probabilities, data.currentGraph(), currentInvocation, parentInvoke, data.inliningDepth() + 1, context, inliningPolicy, canonicalizer);
if (wasInlined) {
inliningCount++;
}
} catch (Throwable e) {
throw Debug.handle(e);
}
}
}
}
}
assert data.inliningDepth() == 0;
assert data.graphCount() == 0;
}
/**
* @return true iff inlining was actually performed
*/
private static boolean tryToInline(ToDoubleFunction<FixedNode> probabilities, CallsiteHolder callerCallsiteHolder, MethodInvocation calleeInfo, MethodInvocation parentInvocation,
int inliningDepth, HighTierContext context, InliningPolicy inliningPolicy, CanonicalizerPhase canonicalizer) {
InlineInfo callee = calleeInfo.callee();
Assumptions callerAssumptions = parentInvocation.assumptions();
metricInliningConsidered.increment();
if (inliningPolicy.isWorthInlining(probabilities, context.getReplacements(), callee, inliningDepth, calleeInfo.probability(), calleeInfo.relevance(), true)) {
InliningData.doInline(callerCallsiteHolder, calleeInfo, callerAssumptions, context, canonicalizer);
return true;
}
if (context.getOptimisticOptimizations().devirtualizeInvokes()) {
callee.tryToDevirtualizeInvoke(context.getMetaAccess(), callerAssumptions);
}
return false;
}
/**
* Holds the data for building the callee graphs recursively: graphs and invocations (each
* invocation can have multiple graphs).
*/
static class InliningData {
private static final CallsiteHolder DUMMY_CALLSITE_HOLDER = new CallsiteHolder(null, 1.0, 1.0);
// Metrics
private static final DebugMetric metricInliningPerformed = Debug.metric("InliningPerformed");
private static final DebugMetric metricInliningRuns = Debug.metric("InliningRuns");
/**
* Call hierarchy from outer most call (i.e., compilation unit) to inner most callee.
*/
private final ArrayDeque<CallsiteHolder> graphQueue;
private final ArrayDeque<MethodInvocation> invocationQueue;
private final int maxMethodPerInlining;
private final CanonicalizerPhase canonicalizer;
private int maxGraphs;
public InliningData(StructuredGraph rootGraph, Assumptions rootAssumptions, int maxMethodPerInlining, CanonicalizerPhase canonicalizer) {
assert rootGraph != null;
this.graphQueue = new ArrayDeque<>();
this.invocationQueue = new ArrayDeque<>();
this.maxMethodPerInlining = maxMethodPerInlining;
this.canonicalizer = canonicalizer;
this.maxGraphs = 1;
invocationQueue.push(new MethodInvocation(null, rootAssumptions, 1.0, 1.0));
pushGraph(rootGraph, 1.0, 1.0);
}
private static void doInline(CallsiteHolder callerCallsiteHolder, MethodInvocation calleeInfo, Assumptions callerAssumptions, HighTierContext context, CanonicalizerPhase canonicalizer) {
StructuredGraph callerGraph = callerCallsiteHolder.graph();
Mark markBeforeInlining = callerGraph.getMark();
InlineInfo callee = calleeInfo.callee();
try {
try (Scope scope = Debug.scope("doInline", callerGraph)) {
List<Node> invokeUsages = callee.invoke().asNode().usages().snapshot();
callee.inline(new Providers(context), callerAssumptions);
callerAssumptions.record(calleeInfo.assumptions());
metricInliningRuns.increment();
Debug.dump(callerGraph, "after %s", callee);
if (OptCanonicalizer.getValue()) {
Mark markBeforeCanonicalization = callerGraph.getMark();
canonicalizer.applyIncremental(callerGraph, context, invokeUsages, markBeforeInlining);
// process invokes that are possibly created during canonicalization
for (Node newNode : callerGraph.getNewNodes(markBeforeCanonicalization)) {
if (newNode instanceof Invoke) {
callerCallsiteHolder.pushInvoke((Invoke) newNode);
}
}
}
callerCallsiteHolder.computeProbabilities();
metricInliningPerformed.increment();
}
} catch (BailoutException bailout) {
throw bailout;
} catch (AssertionError | RuntimeException e) {
throw new GraalInternalError(e).addContext(callee.toString());
} catch (GraalInternalError e) {
throw e.addContext(callee.toString());
}
}
/**
* Process the next invoke and enqueue all its graphs for processing.
*/
void processNextInvoke(HighTierContext context) {
CallsiteHolder callsiteHolder = currentGraph();
Invoke invoke = callsiteHolder.popInvoke();
MethodInvocation callerInvocation = currentInvocation();
Assumptions parentAssumptions = callerInvocation.assumptions();
InlineInfo info = InliningUtil.getInlineInfo(this, invoke, maxMethodPerInlining, context.getReplacements(), parentAssumptions, context.getOptimisticOptimizations());
if (info != null) {
double invokeProbability = callsiteHolder.invokeProbability(invoke);
double invokeRelevance = callsiteHolder.invokeRelevance(invoke);
MethodInvocation calleeInvocation = pushInvocation(info, parentAssumptions, invokeProbability, invokeRelevance);
for (int i = 0; i < info.numberOfMethods(); i++) {
Inlineable elem = DepthSearchUtil.getInlineableElement(info.methodAt(i), info.invoke(), context.replaceAssumptions(calleeInvocation.assumptions()), canonicalizer);
info.setInlinableElement(i, elem);
if (elem instanceof InlineableGraph) {
pushGraph(((InlineableGraph) elem).getGraph(), invokeProbability * info.probabilityAt(i), invokeRelevance * info.relevanceAt(i));
} else {
assert elem instanceof InlineableMacroNode;
pushDummyGraph();
}
}
}
}
public int graphCount() {
return graphQueue.size();
}
private void pushGraph(StructuredGraph graph, double probability, double relevance) {
assert graph != null;
assert !contains(graph);
graphQueue.push(new CallsiteHolder(graph, probability, relevance));
assert graphQueue.size() <= maxGraphs;
}
private void pushDummyGraph() {
graphQueue.push(DUMMY_CALLSITE_HOLDER);
}
public boolean hasUnprocessedGraphs() {
return !graphQueue.isEmpty();
}
public CallsiteHolder currentGraph() {
return graphQueue.peek();
}
public void popGraph() {
graphQueue.pop();
assert graphQueue.size() <= maxGraphs;
}
public void popGraphs(int count) {
assert count >= 0;
for (int i = 0; i < count; i++) {
graphQueue.pop();
}
}
private static final Object[] NO_CONTEXT = {};
/**
* Gets the call hierarchy of this inlining from outer most call to inner most callee.
*/
public Object[] inliningContext() {
if (!Debug.isDumpEnabled()) {
return NO_CONTEXT;
}
Object[] result = new Object[graphQueue.size()];
int i = 0;
for (CallsiteHolder g : graphQueue) {
result[i++] = g.method();
}
return result;
}
public MethodInvocation currentInvocation() {
return invocationQueue.peekFirst();
}
private MethodInvocation pushInvocation(InlineInfo info, Assumptions assumptions, double probability, double relevance) {
MethodInvocation methodInvocation = new MethodInvocation(info, new Assumptions(assumptions.useOptimisticAssumptions()), probability, relevance);
invocationQueue.addFirst(methodInvocation);
maxGraphs += info.numberOfMethods();
assert graphQueue.size() <= maxGraphs;
return methodInvocation;
}
public void popInvocation() {
maxGraphs -= invocationQueue.peekFirst().callee.numberOfMethods();
assert graphQueue.size() <= maxGraphs;
invocationQueue.removeFirst();
}
public int countRecursiveInlining(ResolvedJavaMethod method) {
int count = 0;
for (CallsiteHolder callsiteHolder : graphQueue) {
if (method.equals(callsiteHolder.method())) {
count++;
}
}
return count;
}
public int inliningDepth() {
assert invocationQueue.size() > 0;
return invocationQueue.size() - 1;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("Invocations: ");
for (MethodInvocation invocation : invocationQueue) {
if (invocation.callee() != null) {
result.append(invocation.callee().numberOfMethods());
result.append("x ");
result.append(invocation.callee().invoke());
result.append("; ");
}
}
result.append("\nGraphs: ");
for (CallsiteHolder graph : graphQueue) {
result.append(graph.graph());
result.append("; ");
}
return result.toString();
}
private boolean contains(StructuredGraph graph) {
for (CallsiteHolder info : graphQueue) {
if (info.graph() == graph) {
return true;
}
}
return false;
}
}
private static class MethodInvocation {
private final InlineInfo callee;
private final Assumptions assumptions;
private final double probability;
private final double relevance;
private int processedGraphs;
public MethodInvocation(InlineInfo info, Assumptions assumptions, double probability, double relevance) {
this.callee = info;
this.assumptions = assumptions;
this.probability = probability;
this.relevance = relevance;
}
public void incrementProcessedGraphs() {
processedGraphs++;
assert processedGraphs <= callee.numberOfMethods();
}
public int processedGraphs() {
assert processedGraphs <= callee.numberOfMethods();
return processedGraphs;
}
public int totalGraphs() {
return callee.numberOfMethods();
}
public InlineInfo callee() {
return callee;
}
public Assumptions assumptions() {
return assumptions;
}
public double probability() {
return probability;
}
public double relevance() {
return relevance;
}
public boolean isRoot() {
return callee == null;
}
@Override
public String toString() {
if (isRoot()) {
return "<root>";
}
CallTargetNode callTarget = callee.invoke().callTarget();
if (callTarget instanceof MethodCallTargetNode) {
ResolvedJavaMethod calleeMethod = ((MethodCallTargetNode) callTarget).targetMethod();
return MetaUtil.format("Invoke#%H.%n(%p)", calleeMethod);
} else {
return "Invoke#" + callTarget.targetName();
}
}
}
} |
package org.innovateuk.ifs.workflow.audit;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.innovateuk.ifs.commons.util.AuditableEntity;
import org.innovateuk.ifs.workflow.domain.Process;
import javax.persistence.*;
/**
* Records a {@link Process} state change.
*
* @see AuditableEntity
* @see Process
*/
@Entity
public class ProcessHistory extends AuditableEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(optional = false)
@JoinColumn(name="process_id", referencedColumnName = "id")
private final Process process;
private final String processStateName;
public ProcessHistory() {
this.process = null;
this.processStateName = null;
}
ProcessHistory(Process process) {
if (process == null) throw new NullPointerException("process cannot be null");
this.process = process;
this.processStateName = process.getProcessState().getStateName();
}
Process getProcess() {
return process;
}
String getProcessStateName() {
return processStateName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProcessHistory that = (ProcessHistory) o;
return new EqualsBuilder()
.append(id, that.id)
.append(process, that.process)
.append(processStateName, that.processStateName)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(id)
.append(process)
.append(processStateName)
.toHashCode();
}
} |
package com.worth.ifs.assessment.security;
import com.worth.ifs.BaseServiceSecurityTest;
import com.worth.ifs.assessment.domain.Assessment;
import com.worth.ifs.assessment.resource.AssessmentResource;
import com.worth.ifs.assessment.transactional.AssessmentService;
import com.worth.ifs.commons.service.ServiceResult;
import com.worth.ifs.user.resource.RoleResource;
import com.worth.ifs.user.resource.UserResource;
import com.worth.ifs.workflow.domain.ProcessOutcome;
import org.junit.Before;
import org.junit.Test;
import static com.worth.ifs.assessment.builder.AssessmentBuilder.newAssessment;
import static com.worth.ifs.assessment.builder.AssessmentResourceBuilder.newAssessmentResource;
import static com.worth.ifs.commons.service.ServiceResult.serviceSuccess;
import static com.worth.ifs.user.builder.RoleResourceBuilder.newRoleResource;
import static com.worth.ifs.user.builder.UserResourceBuilder.newUserResource;
import static com.worth.ifs.user.resource.UserRoleType.*;
import static java.util.Collections.singletonList;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AssessmentServiceSecurityTest extends BaseServiceSecurityTest<AssessmentService> {
private AssessmentPermissionRules assessmentPermissionRules;
private AssessmentLookupStrategy assessmentLookupStrategy;
@Override
protected Class<? extends AssessmentService> getServiceClass() {
return TestAssessmentService.class;
}
@Before
public void setUp() throws Exception {
assessmentPermissionRules = getMockPermissionRulesBean(AssessmentPermissionRules.class);
assessmentLookupStrategy = getMockPermissionEntityLookupStrategiesBean(AssessmentLookupStrategy.class);
}
@Test
public void test_getAssessmentById_allowedIfGlobalCompAdminRole() {
final Long assessmentId = 1L;
RoleResource compAdminRole = newRoleResource().withType(COMP_ADMIN).build();
setLoggedInUser(newUserResource().withRolesGlobal(singletonList(compAdminRole)).build());
when(assessmentLookupStrategy.getAssessment(assessmentId)).thenReturn(newAssessment().withId(assessmentId).build());
service.findById(assessmentId);
verify(assessmentPermissionRules).userCanReadAssessment(isA(Assessment.class), isA(UserResource.class));
}
@Test
public void test_getAssessmentById_allowedIfAssessorRole() {
RoleResource assessorRole = newRoleResource().withType(ASSESSOR).build();
setLoggedInUser(newUserResource().withRolesGlobal(singletonList(assessorRole)).build());
service.findById(1L);
}
@Test
public void testAccessIsDenied() {
final Long assessmentId = 1L;
RoleResource applicantRole = newRoleResource().withType(APPLICANT).build();
setLoggedInUser(newUserResource().withRolesGlobal(singletonList(applicantRole)).build());
when(assessmentLookupStrategy.getAssessmentResource(assessmentId)).thenReturn(newAssessmentResource().withId(assessmentId).build());
assertAccessDenied(
() -> service.findById(assessmentId),
() -> verify(assessmentPermissionRules).userCanReadAssessment(isA(Assessment.class), isA(UserResource.class))
);
}
public static class TestAssessmentService implements AssessmentService {
@Override
public ServiceResult<AssessmentResource> findById(Long id) {
return serviceSuccess(newAssessmentResource().withId(id).build());
}
@Override
public ServiceResult<Void> updateStatus(Long id, ProcessOutcome processOutcome) {
return null;
}
}
} |
package com.db.jar;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.CodeSigner;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import sun.security.util.SignatureFileVerifier;
/**
* A SignedJarVerifier is used to verify signed jar files.
*
* @author Dave Longley
*/
public class SignedJarVerifier
{
/**
* The valid certificates. This is the list of certificates that can
* be used to verify jars.
*/
protected Certificate[] mCertificates;
/**
* A hashmap of valid certificates. Each entry in the map is an alias
* that points to a certificate chain.
*/
protected HashMap<String, Certificate[]> mAliasToCertificateChain;
/**
* Stores the minimum number of certificates that must be validated for
* any jar entry.
*/
protected int mMinCertificateCount;
/**
* Set to true if all of the certificates in the list of certificates
* must have been used to verify a jar in order for it to pass
* verification.
*/
protected boolean mRequireAllCertificatesToVerify;
/**
* Creates a new default SignedJarVerifier. This verifier will only
* ensure that jars that are verified were signed by "some certificate" --
* if you wish to restrict that "some certificate" you must use a
* constructor that specifies an array of certificates or a keystore.
*/
public SignedJarVerifier()
{
this(null, false);
}
/**
* Creates a new SignedJarVerifier. A jar will only pass verification if
* either <code>all</code> is set to false and the jar has been verified
* by at least one certificate owned by an alias in the list of aliases,
* or if <code>all</code> has been set to true and all of the aliases
* must have a certificate that verified the jar.
*
* @param keystoreFilename the filename of the keystore to use.
* @param keystorePassword the keystore password.
* @param aliases the list of aliases to use from the keystore.
* @param all true to require that every alias has a certificate that
* verified the jar, false to require that at least one
* alias has a certificate that has verified the jar.
*
* @exception CertificateException if any certificates can't be loaded from
* the keystore.
* @exception IOException if there is an IO error while reading the keystore.
* @exception KeyStoreException if there is an error with the keystore.
* @exception NoSuchAlgorithmException if the algorithm for the keystore
* can't be found.
*/
public SignedJarVerifier(
String keystoreFilename, String keystorePassword, String[] aliases,
boolean all)
throws CertificateException, IOException, KeyStoreException,
NoSuchAlgorithmException
{
// array of certificates not used
mCertificates = null;
// load certificates into map
loadCertificates(keystoreFilename, keystorePassword, aliases);
mRequireAllCertificatesToVerify = all;
// set the minimum number of certificates required to verify a jar entry
if(mRequireAllCertificatesToVerify)
{
mMinCertificateCount = aliases.length;
}
else
{
mMinCertificateCount = 1;
}
}
/**
* Creates a new SignedJarVerifier. A jar will only pass verification if
* either <code>all</code> is set to false and the jar has been verified
* by at least one certificate owned by an alias in the list of aliases,
* or if <code>all</code> has been set to true and all of the aliases
* must have a certificate that verified the jar.
*
* @param keystore the keystore to get the code signers from.
* @param aliases the list of aliases to use from the keystore.
* @param all true to require that every alias has a certificate that
* verified the jar, false to require that at least one
* alias has a certificate that has verified the jar.
*
* @exception KeyStoreException if there is an error with the keystore.
*/
public SignedJarVerifier(KeyStore keystore, String[] aliases, boolean all)
throws KeyStoreException
{
// array of certificates not used
mCertificates = null;
// load certificates into map
loadCertificates(keystore, aliases);
mRequireAllCertificatesToVerify = all;
// set the minimum number of certificates required to verify a jar entry
if(mRequireAllCertificatesToVerify)
{
mMinCertificateCount = aliases.length;
}
else
{
mMinCertificateCount = 1;
}
}
/**
* Creates a new SignedJarVerifier. A jar will only pass verification if
* either <code>all</code> is set to false and the jar has been verified
* by at least one certificate in the passed list, or if <code>all</code>
* has been set to true and all of the certificates have verified the jar.
*
* @param certificates the accepted certificates.
* @param all true to require that all of the certificates have verified
* a jar for it to be considered verified, false to require that
* at least certificate to have verified a jar for it to be
* considered verified.
*/
public SignedJarVerifier(Certificate[] certificates, boolean all)
{
// map of certificates not used
mAliasToCertificateChain = null;
// store certificates
mCertificates = certificates;
mRequireAllCertificatesToVerify = all;
// set the minimum number of certificates required to verify a jar entry
if(mRequireAllCertificatesToVerify)
{
mMinCertificateCount = mCertificates.length;
}
else
{
mMinCertificateCount = 1;
}
}
/**
* Gets the certificates from a keystore into a map with entries of
* alias -> certificateChain.
*
* @param keystoreFilename the filename of the keystore.
* @param keystorePassword the keystore password.
* @param aliases the aliases for the keystore.
*
* @exception CertificateException if any certificates can't be loaded from
* the keystore.
* @exception IOException if there is an IO error while reading the keystore.
* @exception KeyStoreException if there is an error with the keystore.
* @exception NoSuchAlgorithmException if the algorithm for the keystore
* can't be found.
*/
protected void loadCertificates(
String keystoreFilename, String keystorePassword, String[] aliases)
throws CertificateException, IOException, KeyStoreException,
NoSuchAlgorithmException
{
// load keystore
FileInputStream fis = new FileInputStream(keystoreFilename);
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(fis, keystorePassword.toCharArray());
// load the certificates from the keystore
loadCertificates(keystore, aliases);
}
/**
* Gets the certificates from a keystore into a map with entries of
* alias -> certificateChain.
*
* @param keystore the keystore.
* @param aliases the aliases for the keystore.
*
* @exception KeyStoreException if there is an error with the keystore.
*/
protected void loadCertificates(KeyStore keystore, String[] aliases)
throws KeyStoreException
{
// create the certificates map
mAliasToCertificateChain = new HashMap<String, Certificate[]>();
// iterate through the aliases
for(int i = 0; i < aliases.length; i++)
{
// load certificates from keystore for the alias
Certificate[] chain = keystore.getCertificateChain(aliases[i]);
// add entry to the map
mAliasToCertificateChain.put(aliases[i], chain);
}
}
/**
* If <code>all</code> is true then this method checks to see if the
* first array of certificates contains all of the certificates in
* the second array. If <code>all</code> is false, then this method
* checks to see if at least one certificate from the secon array is
* in the first array.
*
* @param certs1 the first array of certificates.
* @param certs2 the second array of certificates.
* @param all true to check to see if the two arrays of certificates
* are equal, false to see if the first array contains
* at least one certificate from the second array.
*
* @return true if enough certificates from the second array were found
* in the first array.
*/
protected boolean findArrayCertificates(
Certificate[] certs1, Certificate[] certs2, boolean all)
{
boolean rval = false;
if(all)
{
rval = Arrays.equals(certs1, certs2);
}
else
{
// ensure at least one of the certificates in the second array
// is in the first array -- keep checking the first array
// until we run out of certificates or one is found from the
// second array
for(int i = 0; i < certs1.length && !rval; i++)
{
for(int j = 0; j < certs2.length && !rval; j++)
{
if(certs1[i].equals(certs2[j]))
{
// certificate found
rval = true;
}
}
}
}
return rval;
}
/**
* Checks to see if the map of certificates for this verifier are
* in the passed array of entry certificates.
*
* @param entryCertificates the entry certificates.
*
* @return true if the certificates were found in the entry certificates,
* false if not.
*/
protected boolean findMappedCertificates(Certificate[] entryCertificates)
{
boolean rval = false;
// go through the alias map and check the certificates --
// keep checking until a certificate is deemed missing or
// the minimum certificate count is reached
boolean certificateMissing = false;
int foundCount = 0;
for(Iterator i = mAliasToCertificateChain.values().iterator();
i.hasNext() && foundCount < mMinCertificateCount &&
!certificateMissing;)
{
Certificate[] chain = (Certificate[])i.next();
if(chain != null &&
findArrayCertificates(entryCertificates, chain, false))
{
foundCount++;
}
else if(mRequireAllCertificatesToVerify)
{
// certificate missing if at least one certificate was not
// found for this alias and all are required
certificateMissing = true;
}
}
// see if enough certificates were found
if(!certificateMissing && foundCount >= mMinCertificateCount)
{
rval = true;
}
return rval;
}
/**
* Checks to see if the certificates for this verifier are found in
* the passed entry certificates.
*
* @param entryCertificates the entry certificates.
*
* @return true if the certificates were found in the entry certificates,
* false if not.
*/
protected boolean findCertificates(Certificate[] entryCertificates)
{
boolean rval = false;
// ensure that there are enough entry certificates
if(entryCertificates.length >= mMinCertificateCount)
{
// determine if we're using the array of certificates or the
// alias to certificate chain map
if(mCertificates != null)
{
// using the array of certificates
rval = findArrayCertificates(
entryCertificates, mCertificates,
mRequireAllCertificatesToVerify);
}
else if(mAliasToCertificateChain != null)
{
// using the map of alias -> certificate chains
rval = findMappedCertificates(entryCertificates);
}
else
{
// any certificate will do
rval = true;
}
}
return rval;
}
/**
* Verifies the signature of an input stream with jar data.
*
* @param is the input stream with jar data.
*
* @exception IOException thrown if an IO error occurs.
* @exception SecurityException thrown if the jar's signature cannot be
* verified.
*
* @return true if the jar was signed, or false if it was not.
*/
public boolean verifyJar(InputStream is)
throws IOException, SecurityException
{
boolean rval = false;
// create a jar input stream
JarInputStream jis = new JarInputStream(is, true);
// set to true if it is detected that any of the jar entries are
// missing a signature
boolean signatureMissing = false;
// a buffer for reading in jar entries
byte[] buffer = new byte[2048];
// iterate through all jar entries -- according to JarInputStream
// documentation, the signature will be verified for each entry --
// however, we must verify that each entry has a digest in the
// manifest or else no verification will take place and no exceptions
// will be thrown (the entry will be treated as unsigned and valid)
JarEntry jarEntry = null;
while((jarEntry = jis.getNextJarEntry()) != null && !signatureMissing)
{
if(!jarEntry.isDirectory())
{
// get the name of the entry in upper case
String name = jarEntry.getName().toUpperCase(Locale.ENGLISH);
// see if the jar entry is not a signature block or file
if(!SignatureFileVerifier.isBlockOrSF(name))
{
// read the entry all the way through so that the
// certificates can be checked -- the end of the
// stream will be at the end of the entry
while(jis.read(buffer) != -1);
// get the code signers for the jar entry
CodeSigner[] codeSigners = jarEntry.getCodeSigners();
if(codeSigners != null)
{
// get the list of certificates for the code signers
ArrayList<Certificate> list = new ArrayList<Certificate>();
for(int n = 0; n < codeSigners.length; n++)
{
// iterate through the certificates and add them to
// the certificates list
for(Iterator<? extends Certificate> i =
codeSigners[n].getSignerCertPath().
getCertificates().iterator(); i.hasNext();)
{
list.add(i.next());
}
}
// build an array of entry certificates
Certificate[] entryCertificates =
new Certificate[list.size()];
for(int i = 0; i < list.size(); i++)
{
entryCertificates[i] = list.get(i);
}
// see if the certificates for the entry match those
// provided to this verifier -- if we can't find
// the appropriate matches, then we're missing a signature
signatureMissing = !findCertificates(entryCertificates);
}
else
{
// code signers are missing!
signatureMissing = true;
}
}
}
}
// if no signatures were missing then the jar was signed
rval = !signatureMissing;
return rval;
}
/**
* Verifies the signature of a jar file.
*
* @param file the file with jar data.
*
* @exception IOException thrown if an IO error occurs.
* @exception SecurityException thrown if the jar's signature cannot be
* verified.
*
* @return true if the jar was signed, or false if it was not.
*/
public boolean verifyJar(File file) throws IOException, SecurityException
{
boolean rval = false;
FileInputStream fis = new FileInputStream(file);
rval = verifyJar(fis);
fis.close();
return rval;
}
} |
package org.innovateuk.ifs.user.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.commons.service.BaseRestService;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;
import java.util.List;
import static org.innovateuk.ifs.commons.service.ParameterizedTypeReferences.organisationResourceListType;
/**
* OrganisationRestServiceImpl is a utility for CRUD operations on {@link OrganisationResource}.
* This class connects to the {org.innovateuk.ifs.user.controller.OrganisationController}
* through a REST call.
*/
@Service
public class OrganisationRestServiceImpl extends BaseRestService implements OrganisationRestService {
private static final Log log = LogFactory.getLog(OrganisationRestServiceImpl.class);
private static final String ORGANISATION_BASE_URL = "/organisation";
@Override
public RestResult<List<OrganisationResource>> getOrganisationsByApplicationId(Long applicationId) {
return getWithRestResult(ORGANISATION_BASE_URL + "/find-by-application-id/" + applicationId, organisationResourceListType());
}
@Override
public RestResult<OrganisationResource> getOrganisationById(long organisationId) {
return getWithRestResult(ORGANISATION_BASE_URL + "/find-by-id/" + organisationId, OrganisationResource.class);
}
@Override
public RestResult<OrganisationResource> getOrganisationByIdForAnonymousUserFlow(Long organisationId) {
return getWithRestResultAnonymous(ORGANISATION_BASE_URL + "/find-by-id/" + organisationId, OrganisationResource.class);
}
@Override
public RestResult<OrganisationResource> getByUserAndApplicationId(long userId, long applicationId) {
return getWithRestResult(ORGANISATION_BASE_URL + "/by-user-and-application-id/" + userId + "/" + applicationId, OrganisationResource.class);
}
@Override
public RestResult<OrganisationResource> getByUserAndProjectId(long userId, long projectId) {
return getWithRestResult(ORGANISATION_BASE_URL + "/by-user-and-project-id/" + userId + "/" + projectId, OrganisationResource.class);
}
@Override
public RestResult<List<OrganisationResource>> getAllByUserId(long userId) {
return getWithRestResult(ORGANISATION_BASE_URL + "/all-by-user-id/" + userId, organisationResourceListType());
}
@Override
public RestResult<List<OrganisationResource>> getOrganisations(long userId, boolean international) {
return getWithRestResult(ORGANISATION_BASE_URL + "?userId=" + userId + "&international=" + international, organisationResourceListType());
}
@Override
public RestResult<OrganisationResource> createOrMatch(OrganisationResource organisation) {
return postWithRestResultAnonymous(ORGANISATION_BASE_URL + "/create-or-match", organisation, OrganisationResource.class);
}
@Override
public RestResult<OrganisationResource> updateNameAndRegistration(OrganisationResource organisation) {
String organisationName;
try {
organisationName = UriUtils.encode(organisation.getName(), "UTF-8");
} catch (Exception e) {
log.error(e);
organisationName = organisation.getName();
}
return postWithRestResult(ORGANISATION_BASE_URL + "/update-name-and-registration/" + organisation.getId() + "?name=" + organisationName + "®istration=" + organisation.getCompaniesHouseNumber(), OrganisationResource.class);
}
} |
package ilg.gnuarmeclipse.debug.gdbjtag.pyocd.ui;
import ilg.gnuarmeclipse.core.EclipseUtils;
import ilg.gnuarmeclipse.debug.gdbjtag.DebugUtils;
import ilg.gnuarmeclipse.debug.gdbjtag.pyocd.Activator;
import ilg.gnuarmeclipse.debug.gdbjtag.pyocd.ConfigurationAttributes;
import ilg.gnuarmeclipse.debug.gdbjtag.pyocd.DefaultPreferences;
import ilg.gnuarmeclipse.debug.gdbjtag.pyocd.PersistentPreferences;
import ilg.gnuarmeclipse.debug.gdbjtag.pyocd.PyOCD;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
import org.eclipse.cdt.debug.gdbjtag.core.IGDBJtagConstants;
import org.eclipse.cdt.debug.gdbjtag.ui.GDBJtagImages;
import org.eclipse.cdt.debug.mi.core.IMILaunchConfigurationConstants;
import org.eclipse.cdt.debug.mi.core.MIPlugin;
import org.eclipse.cdt.debug.mi.core.command.factories.CommandFactoryDescriptor;
import org.eclipse.cdt.debug.mi.core.command.factories.CommandFactoryManager;
import org.eclipse.cdt.dsf.gdb.IGDBLaunchConfigurationConstants;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.debug.ui.StringVariableSelectionDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;
/**
* @since 7.0
*/
public class TabDebugger extends AbstractLaunchConfigurationTab {
private static final String TAB_NAME = "Debugger";
private static final String TAB_ID = Activator.PLUGIN_ID + ".ui.debuggertab";
/** The launch configuration this GUI is showing/modifying */
private ILaunchConfiguration fConfiguration;
private List<PyOCD.Board> fBoards;
private String fSelectedBoardId;
private Button fDoStartGdbServer;
private Text fGdbClientExecutable;
private Text fGdbClientOtherOptions;
private Text fGdbClientOtherCommands;
private Text fTargetIpAddress;
private Text fTargetPortNumber;
private Combo fGdbServerBoardId;
private Button fGdbServerRefreshBoards;
private Text fGdbServerGdbPort;
private Text fGdbServerTelnetPort;
private Button fGdbServerOverrideTarget;
private Combo fGdbServerTargetName;
private Combo fGdbServerBusSpeed;
private Button fGdbServerHaltAtHardFault;
private Button fGdbServerStepIntoInterrupts;
private Combo fGdbServerFlashMode;
private Button fGdbServerFlashFastVerify;
private Button fGdbServerEnableSemihosting;
private Button fGdbServerUseGdbSyscallsForSemihosting;
private Text fGdbServerExecutable;
private Button fGdbServerBrowseButton;
private Button fGdbServerVariablesButton;
private Text fGdbServerOtherOptions;
private Button fDoGdbServerAllocateConsole;
private Button fDoGdbServerAllocateSemihostingConsole;
protected Button fUpdateThreadlistOnSuspend;
/** Active errors , if any. When any, only first is shown */
private Set<String> fErrors = new LinkedHashSet<String>();
/**
* Where widgets in a row are rendered in columns, the amount of padding (in
* pixels) between columns
*/
private static final int COLUMN_PAD = 30;
private static class Msgs {
public static final String INVALID_PYOCD_EXECUTABLE = "pyOCD gdbserver not found where specified";
}
protected TabDebugger(TabStartup tabStartup) {
super();
}
@Override
public String getName() {
return TAB_NAME;
}
@Override
public Image getImage() {
return GDBJtagImages.getDebuggerTabImage();
}
private Composite createHorizontalLayout(Composite comp, int columns, int spanSub) {
Composite local = new Composite(comp, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = columns;
layout.marginHeight = 0;
layout.marginWidth = 0;
local.setLayout(layout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
if (spanSub > 0) {
gd.horizontalSpan = ((GridLayout) comp.getLayout()).numColumns - spanSub;
}
local.setLayoutData(gd);
return local;
}
@Override
public void createControl(Composite parent) {
ScrolledComposite sc = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
sc.setExpandHorizontal(true);
sc.setExpandVertical(true);
setControl(sc);
Composite comp = new Composite(sc, SWT.NONE);
sc.setContent(comp);
GridLayout layout = new GridLayout();
comp.setLayout(layout);
createGdbServerGroup(comp);
createGdbClientControls(comp);
createRemoteControl(comp);
fUpdateThreadlistOnSuspend = new Button(comp, SWT.CHECK);
fUpdateThreadlistOnSuspend.setText(Messages.getString("DebuggerTab.update_thread_list_on_suspend_Text"));
fUpdateThreadlistOnSuspend
.setToolTipText(Messages.getString("DebuggerTab.update_thread_list_on_suspend_ToolTipText"));
Link restoreDefaults;
GridData gd;
{
restoreDefaults = new Link(comp, SWT.NONE);
restoreDefaults.setText(Messages.getString("DebuggerTab.restoreDefaults_Link"));
restoreDefaults.setToolTipText(Messages.getString("DebuggerTab.restoreDefaults_ToolTipText"));
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.RIGHT;
gd.horizontalSpan = ((GridLayout) comp.getLayout()).numColumns;
restoreDefaults.setLayoutData(gd);
}
fUpdateThreadlistOnSuspend.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateLaunchConfigurationDialog();
}
});
restoreDefaults.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent event) {
initializeFromDefaults();
scheduleUpdateJob();
}
});
}
private void browseButtonSelected(String title, Text text) {
FileDialog dialog = new FileDialog(getShell(), SWT.NONE);
dialog.setText(title);
String str = text.getText().trim();
int lastSeparatorIndex = str.lastIndexOf(File.separator);
if (lastSeparatorIndex != -1)
dialog.setFilterPath(str.substring(0, lastSeparatorIndex));
str = dialog.open();
if (str != null)
text.setText(str);
}
private void variablesButtonSelected(Text text) {
StringVariableSelectionDialog dialog = new StringVariableSelectionDialog(getShell());
if (dialog.open() == StringVariableSelectionDialog.OK) {
text.insert(dialog.getVariableExpression());
}
}
private void createGdbServerGroup(Composite parent) {
Group group = new Group(parent, SWT.NONE);
GridLayout layout = new GridLayout();
group.setLayout(layout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
group.setLayoutData(gd);
group.setText(Messages.getString("DebuggerTab.gdbServerGroup_Text"));
Composite comp = new Composite(group, SWT.NONE);
layout = new GridLayout();
layout.numColumns = 5;
layout.marginHeight = 0;
comp.setLayout(layout);
gd = new GridData(GridData.FILL_HORIZONTAL);
comp.setLayoutData(gd);
Composite local;
Label label;
{
fDoStartGdbServer = new Button(comp, SWT.CHECK);
fDoStartGdbServer.setText(Messages.getString("DebuggerTab.doStartGdbServer_Text"));
fDoStartGdbServer.setToolTipText(Messages.getString("DebuggerTab.doStartGdbServer_ToolTipText"));
gd = new GridData();
gd.horizontalSpan = ((GridLayout) comp.getLayout()).numColumns;
fDoStartGdbServer.setLayoutData(gd);
}
{
Composite subcomp = new Composite(comp, SWT.NONE);
gd = new GridData(SWT.FILL, SWT.TOP, true, false);
gd.horizontalSpan = ((GridLayout) comp.getLayout()).numColumns;
subcomp.setLayoutData(gd);
layout = new GridLayout(2, false);
layout.marginWidth = layout.marginHeight = 0;
subcomp.setLayout(layout);
label = new Label(subcomp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbServerExecutable_Label"));
label.setToolTipText(Messages.getString("DebuggerTab.gdbServerExecutable_ToolTipText"));
{
local = createHorizontalLayout(subcomp, 3, 1);
{
fGdbServerExecutable = new Text(local, SWT.SINGLE | SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
fGdbServerExecutable.setLayoutData(gd);
fGdbServerBrowseButton = new Button(local, SWT.NONE);
fGdbServerBrowseButton.setText(Messages.getString("DebuggerTab.gdbServerExecutableBrowse"));
fGdbServerVariablesButton = new Button(local, SWT.NONE);
fGdbServerVariablesButton.setText(Messages.getString("DebuggerTab.gdbServerExecutableVariable"));
}
}
label = new Label(subcomp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbServerGdbPort_Label"));
label.setToolTipText(Messages.getString("DebuggerTab.gdbServerGdbPort_ToolTipText"));
{
Composite subcomp2 = new Composite(subcomp, SWT.NONE);
gd = new GridData(SWT.FILL, SWT.TOP, true, false);
subcomp2.setLayoutData(gd);
layout = new GridLayout(2, false);
layout.horizontalSpacing = COLUMN_PAD;
layout.marginWidth = layout.marginHeight = 0;
subcomp2.setLayout(layout);
fGdbServerGdbPort = new Text(subcomp2, SWT.SINGLE | SWT.BORDER);
gd = new GridData();
gd.widthHint = 60;
fGdbServerGdbPort.setLayoutData(gd);
fDoGdbServerAllocateConsole = new Button(subcomp2, SWT.CHECK);
fDoGdbServerAllocateConsole.setLayoutData(new GridData());
fDoGdbServerAllocateConsole.setText(Messages.getString("DebuggerTab.gdbServerAllocateConsole_Label"));
fDoGdbServerAllocateConsole.setToolTipText(Messages
.getString("DebuggerTab.gdbServerAllocateConsole_ToolTipText"));
}
label = new Label(subcomp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbServerTelnetPort_Label"));
label.setToolTipText(Messages.getString("DebuggerTab.gdbServerTelnetPort_ToolTipText"));
{
Composite subcomp2 = new Composite(subcomp, SWT.NONE);
gd = new GridData(SWT.FILL, SWT.TOP, true, false);
subcomp2.setLayoutData(gd);
layout = new GridLayout(2, false);
layout.horizontalSpacing = COLUMN_PAD;
layout.marginWidth = layout.marginHeight = 0;
subcomp2.setLayout(layout);
fGdbServerTelnetPort = new Text(subcomp2, SWT.SINGLE | SWT.BORDER);
gd = new GridData();
gd.widthHint = 60;
fGdbServerTelnetPort.setLayoutData(gd);
fDoGdbServerAllocateSemihostingConsole = new Button(subcomp2, SWT.CHECK);
fDoGdbServerAllocateSemihostingConsole.setLayoutData(new GridData());
fDoGdbServerAllocateSemihostingConsole.setText(Messages
.getString("DebuggerTab.gdbServerAllocateTelnetConsole_Label"));
fDoGdbServerAllocateSemihostingConsole.setToolTipText(Messages
.getString("DebuggerTab.gdbServerAllocateTelnetConsole_ToolTipText"));
fDoGdbServerAllocateSemihostingConsole.setLayoutData(new GridData());
}
}
createSeparator(comp, ((GridLayout) comp.getLayout()).numColumns);
{
label = new Label(comp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbServerBoardId_Label"));
label.setToolTipText(Messages.getString("DebuggerTab.gdbServerBoardId_ToolTipText"));
local = createHorizontalLayout(comp, 2, 1);
{
fGdbServerBoardId = new Combo(local, SWT.DROP_DOWN | SWT.READ_ONLY);
gd = new GridData(GridData.FILL_HORIZONTAL);
fGdbServerBoardId.setLayoutData(gd);
fGdbServerBoardId.setItems(new String[] {});
fGdbServerBoardId.select(0);
fGdbServerRefreshBoards = new Button(local, SWT.NONE);
fGdbServerRefreshBoards.setText(Messages.getString("DebuggerTab.gdbServerRefreshBoards_Label"));
}
}
{
fGdbServerOverrideTarget = new Button(comp, SWT.CHECK);
fGdbServerOverrideTarget.setText(Messages.getString("DebuggerTab.gdbServerOverrideTarget_Label"));
fGdbServerOverrideTarget.setToolTipText(Messages
.getString("DebuggerTab.gdbServerOverrideTarget_ToolTipText"));
gd = new GridData();
fGdbServerOverrideTarget.setLayoutData(gd);
fGdbServerTargetName = new Combo(comp, SWT.DROP_DOWN);
gd = new GridData();
gd.widthHint = 120;
gd.horizontalSpan = ((GridLayout) comp.getLayout()).numColumns - 1;
fGdbServerTargetName.setLayoutData(gd);
}
{
label = new Label(comp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbServerBusSpeed_Label"));
label.setToolTipText(Messages.getString("DebuggerTab.gdbServerBusSpeed_ToolTipText"));
fGdbServerBusSpeed = new Combo(comp, SWT.DROP_DOWN);
gd = new GridData();
gd.widthHint = 120;
fGdbServerBusSpeed.setLayoutData(gd);
fGdbServerBusSpeed.setItems(new String[] { "1000000", "2000000", "8000000", "12000000" });
fGdbServerBusSpeed.select(0);
label = new Label(comp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbServerBusSpeedUnits_Label"));
gd = new GridData();
gd.horizontalSpan = ((GridLayout) comp.getLayout()).numColumns - 2;
label.setLayoutData(gd);
}
{
label = new Label(comp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbServerFlashMode_Label")); //$NON-NLS-1$
label.setToolTipText(Messages.getString("DebuggerTab.gdbServerFlashMode_ToolTipText"));
gd = new GridData();
label.setLayoutData(gd);
fGdbServerFlashMode = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY);
gd = new GridData();
gd.widthHint = 120;
fGdbServerFlashMode.setLayoutData(gd);
fGdbServerFlashMode.setItems(new String[] { Messages.getString("DebuggerTab.gdbServerFlashMode.AutoErase"),
Messages.getString("DebuggerTab.gdbServerFlashMode.ChipErase"),
Messages.getString("DebuggerTab.gdbServerFlashMode.SectorErase"), });
fGdbServerFlashMode.select(0);
fGdbServerFlashFastVerify = new Button(comp, SWT.CHECK);
fGdbServerFlashFastVerify.setText(Messages.getString("DebuggerTab.gdbServerFlashFastVerify_Label"));
fGdbServerFlashFastVerify.setToolTipText(Messages
.getString("DebuggerTab.gdbServerFlashFastVerify_ToolTipText"));
gd = new GridData();
gd.horizontalSpan = ((GridLayout) comp.getLayout()).numColumns - 2;
gd.horizontalIndent = COLUMN_PAD;
fGdbServerFlashFastVerify.setLayoutData(gd);
}
// Composite for next four checkboxes. Will render using two columns
{
Composite subcomp = new Composite(comp, SWT.NONE);
gd = new GridData();
gd.horizontalSpan = ((GridLayout) comp.getLayout()).numColumns;
subcomp.setLayoutData(gd);
layout = new GridLayout(2, false);
layout.horizontalSpacing = COLUMN_PAD;
layout.marginWidth = layout.marginHeight = 0;
subcomp.setLayout(layout);
{
fGdbServerHaltAtHardFault = new Button(subcomp, SWT.CHECK);
fGdbServerHaltAtHardFault.setLayoutData(new GridData());
fGdbServerHaltAtHardFault.setText(Messages.getString("DebuggerTab.gdbServerHaltAtHardFault_Label"));
fGdbServerHaltAtHardFault.setToolTipText(Messages
.getString("DebuggerTab.gdbServerHaltAtHardFault_ToolTipText"));
}
{
fGdbServerStepIntoInterrupts = new Button(subcomp, SWT.CHECK);
fGdbServerStepIntoInterrupts.setLayoutData(new GridData());
fGdbServerStepIntoInterrupts.setText(Messages
.getString("DebuggerTab.gdbServerStepIntoInterrupts_Label"));
fGdbServerStepIntoInterrupts.setToolTipText(Messages
.getString("DebuggerTab.gdbServerStepIntoInterrupts_ToolTipText"));
}
{
fGdbServerEnableSemihosting = new Button(subcomp, SWT.CHECK);
fGdbServerEnableSemihosting.setLayoutData(new GridData());
fGdbServerEnableSemihosting.setText(Messages.getString("DebuggerTab.gdbServerEnableSemihosting_Label"));
fGdbServerEnableSemihosting.setToolTipText(Messages
.getString("DebuggerTab.gdbServerEnableSemihosting_ToolTipText"));
}
{
fGdbServerUseGdbSyscallsForSemihosting = new Button(subcomp, SWT.CHECK);
fGdbServerUseGdbSyscallsForSemihosting.setLayoutData(new GridData());
fGdbServerUseGdbSyscallsForSemihosting.setText(Messages
.getString("DebuggerTab.gdbServerUseGdbSyscallsForSemihosting_Label"));
fGdbServerUseGdbSyscallsForSemihosting.setToolTipText(Messages
.getString("DebuggerTab.gdbServerUseGdbSyscallsForSemihosting_ToolTipText"));
}
}
{
label = new Label(comp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbServerOther_Label")); //$NON-NLS-1$
label.setToolTipText(Messages.getString("DebuggerTab.gdbServerOther_ToolTipText"));
gd = new GridData();
gd.verticalAlignment = SWT.TOP;
label.setLayoutData(gd);
fGdbServerOtherOptions = new Text(comp, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.heightHint = 60;
gd.horizontalSpan = ((GridLayout) comp.getLayout()).numColumns - 1;
fGdbServerOtherOptions.setLayoutData(gd);
}
ModifyListener scheduleUpdateJobModifyListener = new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
scheduleUpdateJob();
}
};
SelectionAdapter scheduleUpdateJobSelectionAdapter = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
scheduleUpdateJob();
}
};
fDoStartGdbServer.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
doStartGdbServerChanged();
if (fDoStartGdbServer.getSelection()) {
fTargetIpAddress.setText(DefaultPreferences.REMOTE_IP_ADDRESS_LOCALHOST);
}
scheduleUpdateJob();
}
});
fGdbServerExecutable.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
if (fConfiguration != null) {
updateBoards();
updateTargets();
scheduleUpdateJob(); // provides much better performance for
// Text listeners
}
}
});
fGdbServerBrowseButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
browseButtonSelected(Messages.getString("DebuggerTab.gdbServerExecutableBrowse_Title"),
fGdbServerExecutable);
}
});
fGdbServerVariablesButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
variablesButtonSelected(fGdbServerExecutable);
}
});
fGdbServerGdbPort.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
// make the target port the same
fTargetPortNumber.setText(fGdbServerGdbPort.getText());
scheduleUpdateJob();
}
});
fGdbServerBoardId.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boardSelected(((Combo) e.widget).getSelectionIndex());
}
});
fGdbServerRefreshBoards.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateBoards();
}
});
fGdbServerOverrideTarget.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
overrideTargetChanged();
scheduleUpdateJob();
}
});
fGdbServerTelnetPort.addModifyListener(scheduleUpdateJobModifyListener);
fGdbServerBusSpeed.addModifyListener(scheduleUpdateJobModifyListener);
fGdbServerTargetName.addModifyListener(scheduleUpdateJobModifyListener);
fGdbServerHaltAtHardFault.addSelectionListener(scheduleUpdateJobSelectionAdapter);
fGdbServerStepIntoInterrupts.addSelectionListener(scheduleUpdateJobSelectionAdapter);
fGdbServerFlashMode.addModifyListener(scheduleUpdateJobModifyListener);
fGdbServerFlashFastVerify.addSelectionListener(scheduleUpdateJobSelectionAdapter);
fGdbServerEnableSemihosting.addSelectionListener(scheduleUpdateJobSelectionAdapter);
fGdbServerUseGdbSyscallsForSemihosting.addSelectionListener(scheduleUpdateJobSelectionAdapter);
fGdbServerOtherOptions.addModifyListener(scheduleUpdateJobModifyListener);
fDoGdbServerAllocateConsole.addSelectionListener(scheduleUpdateJobSelectionAdapter);
fDoGdbServerAllocateSemihostingConsole.addSelectionListener(scheduleUpdateJobSelectionAdapter);
}
private void createGdbClientControls(Composite parent) {
Group group = new Group(parent, SWT.NONE);
group.setText(Messages.getString("DebuggerTab.gdbSetupGroup_Text"));
GridLayout layout = new GridLayout();
group.setLayout(layout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
group.setLayoutData(gd);
Composite comp = new Composite(group, SWT.NONE);
layout = new GridLayout();
layout.numColumns = 2;
layout.marginHeight = 0;
comp.setLayout(layout);
gd = new GridData(GridData.FILL_HORIZONTAL);
comp.setLayoutData(gd);
Label label;
Button browseButton;
Button variableButton;
{
label = new Label(comp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbCommand_Label"));
label.setToolTipText(Messages.getString("DebuggerTab.gdbCommand_ToolTipText"));
Composite local = createHorizontalLayout(comp, 3, -1);
{
fGdbClientExecutable = new Text(local, SWT.SINGLE | SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
fGdbClientExecutable.setLayoutData(gd);
browseButton = new Button(local, SWT.NONE);
browseButton.setText(Messages.getString("DebuggerTab.gdbCommandBrowse"));
variableButton = new Button(local, SWT.NONE);
variableButton.setText(Messages.getString("DebuggerTab.gdbCommandVariable"));
}
}
{
label = new Label(comp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbOtherOptions_Label"));
label.setToolTipText(Messages.getString("DebuggerTab.gdbOtherOptions_ToolTipText"));
gd = new GridData();
label.setLayoutData(gd);
fGdbClientOtherOptions = new Text(comp, SWT.SINGLE | SWT.BORDER);
gd = new GridData(GridData.FILL_HORIZONTAL);
fGdbClientOtherOptions.setLayoutData(gd);
}
{
label = new Label(comp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.gdbOtherCommands_Label"));
label.setToolTipText(Messages.getString("DebuggerTab.gdbOtherCommands_ToolTipText"));
gd = new GridData();
gd.verticalAlignment = SWT.TOP;
label.setLayoutData(gd);
fGdbClientOtherCommands = new Text(comp, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.heightHint = 60;
fGdbClientOtherCommands.setLayoutData(gd);
}
fGdbClientExecutable.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
scheduleUpdateJob(); // provides much better performance for
// Text listeners
}
});
fGdbClientOtherOptions.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
scheduleUpdateJob();
}
});
fGdbClientOtherCommands.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
scheduleUpdateJob();
}
});
browseButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
browseButtonSelected(Messages.getString("DebuggerTab.gdbCommandBrowse_Title"), fGdbClientExecutable);
}
});
variableButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
variablesButtonSelected(fGdbClientExecutable);
}
});
}
private void createRemoteControl(Composite parent) {
Group group = new Group(parent, SWT.NONE);
group.setText(Messages.getString("DebuggerTab.remoteGroup_Text"));
GridLayout layout = new GridLayout();
group.setLayout(layout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
group.setLayoutData(gd);
Composite comp = createHorizontalLayout(group, 2, -1);
comp.setLayoutData(gd);
// Create entry fields for TCP/IP connections
Label label;
{
label = new Label(comp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.ipAddressLabel")); //$NON-NLS-1$
fTargetIpAddress = new Text(comp, SWT.BORDER);
gd = new GridData();
gd.widthHint = 125;
fTargetIpAddress.setLayoutData(gd);
label = new Label(comp, SWT.NONE);
label.setText(Messages.getString("DebuggerTab.portNumberLabel")); //$NON-NLS-1$
fTargetPortNumber = new Text(comp, SWT.BORDER);
gd = new GridData();
gd.widthHint = 125;
fTargetPortNumber.setLayoutData(gd);
}
// Add watchers for user data entry
fTargetIpAddress.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
scheduleUpdateJob(); // provides much better performance for
// Text listeners
}
});
fTargetPortNumber.addVerifyListener(new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
e.doit = Character.isDigit(e.character) || Character.isISOControl(e.character);
}
});
fTargetPortNumber.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
scheduleUpdateJob(); // provides much better performance for
// Text listeners
}
});
}
private void doStartGdbServerChanged() {
boolean enabled = fDoStartGdbServer.getSelection();
fGdbServerExecutable.setEnabled(enabled);
fGdbServerBrowseButton.setEnabled(enabled);
fGdbServerVariablesButton.setEnabled(enabled);
fGdbServerOtherOptions.setEnabled(enabled);
fGdbServerGdbPort.setEnabled(enabled);
fGdbServerTelnetPort.setEnabled(enabled);
fGdbServerBusSpeed.setEnabled(enabled);
fGdbServerOverrideTarget.setEnabled(enabled);
fGdbServerTargetName.setEnabled(enabled && fGdbServerOverrideTarget.getSelection());
fGdbServerHaltAtHardFault.setEnabled(enabled);
fGdbServerStepIntoInterrupts.setEnabled(enabled);
fGdbServerFlashMode.setEnabled(enabled);
fGdbServerFlashFastVerify.setEnabled(enabled);
fDoGdbServerAllocateConsole.setEnabled(enabled);
fDoGdbServerAllocateSemihostingConsole.setEnabled(enabled);
// Disable remote target params when the server is started
fTargetIpAddress.setEnabled(!enabled);
fTargetPortNumber.setEnabled(!enabled);
}
private void overrideTargetChanged() {
boolean enabled = fGdbServerOverrideTarget.getSelection();
fGdbServerTargetName.setEnabled(enabled);
}
private String getPyOCDExecutablePath() {
String path = null;
try {
path = fGdbServerExecutable.getText().trim();
if (path.length() == 0) {
return null;
}
if (Activator.getInstance().isDebugging()) {
System.out.printf("pyOCD path = %s\n", path);
}
path = DebugUtils.resolveAll(path, fConfiguration.getAttributes());
ICConfigurationDescription buildConfig = EclipseUtils.getBuildConfigDescription(fConfiguration);
if (buildConfig != null) {
path = DebugUtils.resolveAll(path, buildConfig);
}
if (Activator.getInstance().isDebugging()) {
System.out.printf("pyOCD resolved path = %s\n", path);
}
// Validate path.
File file = new File(path);
if (!file.exists() || file.isDirectory()) {
// TODO: Use java.nio.Files when we move to Java 7 to also check
// that file is executable
if (Activator.getInstance().isDebugging()) {
System.out.printf("pyOCD path is invalid\n");
}
return null;
}
} catch (CoreException e) {
Activator.log(e);
return null;
}
return path;
}
private int indexForBoardId(String boardId) {
// Search for a matching board.
if (fBoards != null) {
int index = 0;
for (PyOCD.Board b : fBoards) {
if (b.fUniqueId.equals(boardId)) {
return index;
}
index += 1;
}
}
return -1;
}
private void boardSelected(int index) {
PyOCD.Board selectedBoard = fBoards.get(index);
fSelectedBoardId = selectedBoard.fUniqueId;
}
private void selectActiveBoard() {
// Get current board ID.
int index = indexForBoardId(fSelectedBoardId);
if (index != -1) {
fGdbServerBoardId.select(index);
} else {
}
}
private void updateBoards() {
String path = getPyOCDExecutablePath();
if (path != null) {
deregisterError(Msgs.INVALID_PYOCD_EXECUTABLE);
List<PyOCD.Board> boards = PyOCD.getBoards(path);
if (boards == null) {
boards = new ArrayList<PyOCD.Board>();
}
System.out.printf("board = %s\n", boards);
Collections.sort(boards, PyOCD.Board.COMPARATOR);
fBoards = boards;
final ArrayList<String> itemList = new ArrayList<String>();
for (PyOCD.Board board : boards) {
String desc = board.fProductName;
if (!board.fProductName.startsWith(board.fVendorName)) {
desc = board.fVendorName + " " + board.fProductName;
}
itemList.add(String.format("%s - %s (%s)", board.fName, desc, board.fUniqueId));
}
String[] items = itemList.toArray(new String[itemList.size()]);
fGdbServerBoardId.setItems(items);
selectActiveBoard();
} else {
fGdbServerBoardId.setItems(new String[] {});
registerError(Msgs.INVALID_PYOCD_EXECUTABLE);
}
}
private void updateTargets() {
String path = getPyOCDExecutablePath();
if (path != null) {
deregisterError(Msgs.INVALID_PYOCD_EXECUTABLE);
List<PyOCD.Target> targets = PyOCD.getTargets(path);
if (targets == null) {
targets = new ArrayList<PyOCD.Target>();
}
System.out.printf("target = %s\n", targets);
Collections.sort(targets, PyOCD.Target.COMPARATOR);
final ArrayList<String> itemList = new ArrayList<String>();
for (PyOCD.Target target : targets) {
itemList.add(String.format("%s", target.fPartNumber));
}
String[] items = itemList.toArray(new String[itemList.size()]);
fGdbServerTargetName.setItems(items);
} else {
// Clear combobox and show error
fGdbServerTargetName.setItems(new String[] {});
registerError(Msgs.INVALID_PYOCD_EXECUTABLE);
}
}
@Override
public void initializeFrom(ILaunchConfiguration configuration) {
try {
Boolean booleanDefault;
String stringDefault;
// PyOCD GDB server
{
// Start server locally
booleanDefault = PersistentPreferences.getGdbServerDoStart();
fDoStartGdbServer.setSelection(
configuration.getAttribute(ConfigurationAttributes.DO_START_GDB_SERVER, booleanDefault));
// Executable
stringDefault = PersistentPreferences.getGdbServerExecutable();
fGdbServerExecutable.setText(
configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_EXECUTABLE, stringDefault));
// Ports
fGdbServerGdbPort.setText(
Integer.toString(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_GDB_PORT_NUMBER,
DefaultPreferences.GDB_SERVER_GDB_PORT_NUMBER_DEFAULT)));
fGdbServerTelnetPort.setText(Integer
.toString(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_TELNET_PORT_NUMBER,
DefaultPreferences.GDB_SERVER_TELNET_PORT_NUMBER_DEFAULT)));
// Board ID
fSelectedBoardId = configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_BOARD_ID,
DefaultPreferences.GDB_SERVER_BOARD_ID_DEFAULT);
selectActiveBoard();
// Target override
fGdbServerOverrideTarget
.setSelection(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_OVERRIDE_TARGET,
DefaultPreferences.GDB_SERVER_OVERRIDE_TARGET_DEFAULT));
fGdbServerTargetName.setText(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_TARGET_NAME,
DefaultPreferences.GDB_SERVER_TARGET_NAME_DEFAULT));
// Misc options
fGdbServerHaltAtHardFault
.setSelection(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_HALT_AT_HARD_FAULT,
DefaultPreferences.GDB_SERVER_HALT_AT_HARD_FAULT_DEFAULT));
fGdbServerStepIntoInterrupts.setSelection(
configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_STEP_INTO_INTERRUPTS,
DefaultPreferences.GDB_SERVER_STEP_INTO_INTERRUPTS_DEFAULT));
// Flash
fGdbServerFlashMode.select(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_FLASH_MODE,
DefaultPreferences.GDB_SERVER_FLASH_MODE_DEFAULT));
fGdbServerFlashFastVerify
.setSelection(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_FLASH_FAST_VERIFY,
DefaultPreferences.GDB_SERVER_FLASH_FAST_VERIFY_DEFAULT));
// Semihosting
fGdbServerEnableSemihosting
.setSelection(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_ENABLE_SEMIHOSTING,
DefaultPreferences.GDB_SERVER_ENABLE_SEMIHOSTING_DEFAULT));
fGdbServerUseGdbSyscallsForSemihosting
.setSelection(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_USE_GDB_SYSCALLS,
DefaultPreferences.GDB_SERVER_USE_GDB_SYSCALLS_DEFAULT));
// Bus speed
fGdbServerBusSpeed.setText(
Integer.toString(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_BUS_SPEED,
DefaultPreferences.GDB_SERVER_BUS_SPEED_DEFAULT)));
// Other options
stringDefault = PersistentPreferences.getGdbServerOtherOptions();
fGdbServerOtherOptions
.setText(configuration.getAttribute(ConfigurationAttributes.GDB_SERVER_OTHER, stringDefault));
// Allocate server console
if (EclipseUtils.isWindows()) {
fDoGdbServerAllocateConsole.setSelection(true);
} else {
fDoGdbServerAllocateConsole.setSelection(
configuration.getAttribute(ConfigurationAttributes.DO_GDB_SERVER_ALLOCATE_CONSOLE,
DefaultPreferences.DO_GDB_SERVER_ALLOCATE_CONSOLE_DEFAULT));
}
// Allocate telnet console
fDoGdbServerAllocateSemihostingConsole.setSelection(
configuration.getAttribute(ConfigurationAttributes.DO_GDB_SERVER_ALLOCATE_SEMIHOSTING_CONSOLE,
DefaultPreferences.DO_GDB_SERVER_ALLOCATE_SEMIHOSTING_CONSOLE_DEFAULT));
}
// GDB Client Setup
{
// Executable
stringDefault = PersistentPreferences.getGdbClientExecutable();
String gdbCommandAttr = configuration.getAttribute(IGDBLaunchConfigurationConstants.ATTR_DEBUG_NAME,
stringDefault);
fGdbClientExecutable.setText(gdbCommandAttr);
// Other options
stringDefault = PersistentPreferences.getGdbClientOtherOptions();
fGdbClientOtherOptions.setText(
configuration.getAttribute(ConfigurationAttributes.GDB_CLIENT_OTHER_OPTIONS, stringDefault));
stringDefault = PersistentPreferences.getGdbClientCommands();
fGdbClientOtherCommands.setText(
configuration.getAttribute(ConfigurationAttributes.GDB_CLIENT_OTHER_COMMANDS, stringDefault));
}
// Remote target
{
fTargetIpAddress.setText(configuration.getAttribute(IGDBJtagConstants.ATTR_IP_ADDRESS,
DefaultPreferences.REMOTE_IP_ADDRESS_DEFAULT)); // $NON-NLS-1$
int storedPort = 0;
storedPort = configuration.getAttribute(IGDBJtagConstants.ATTR_PORT_NUMBER, 0); // Default
// 0 means undefined, use default
if ((storedPort <= 0) || (65535 < storedPort)) {
storedPort = DefaultPreferences.REMOTE_PORT_NUMBER_DEFAULT;
}
String portString = Integer.toString(storedPort); // $NON-NLS-1$
fTargetPortNumber.setText(portString);
}
fConfiguration = configuration;
doStartGdbServerChanged();
overrideTargetChanged();
updateBoards();
updateTargets();
// Force thread update
boolean updateThreadsOnSuspend = configuration.getAttribute(
IGDBLaunchConfigurationConstants.ATTR_DEBUGGER_UPDATE_THREADLIST_ON_SUSPEND,
DefaultPreferences.UPDATE_THREAD_LIST_DEFAULT);
fUpdateThreadlistOnSuspend.setSelection(updateThreadsOnSuspend);
} catch (CoreException e) {
Activator.log(e.getStatus());
}
}
public void initializeFromDefaults() {
String stringDefault;
// PyOCD GDB server
{
// Start server locally
fDoStartGdbServer.setSelection(DefaultPreferences.DO_START_GDB_SERVER_DEFAULT);
// Executable
stringDefault = DefaultPreferences.getGdbServerExecutable();
fGdbServerExecutable.setText(stringDefault);
// Ports
fGdbServerGdbPort.setText(Integer.toString(DefaultPreferences.GDB_SERVER_GDB_PORT_NUMBER_DEFAULT));
fGdbServerTelnetPort.setText(Integer.toString(DefaultPreferences.GDB_SERVER_TELNET_PORT_NUMBER_DEFAULT));
// Board ID
// fGdbServerBoardId.setText(DefaultPreferences.GDB_SERVER_BOARD_ID_DEFAULT);
// Target override
fGdbServerOverrideTarget.setSelection(DefaultPreferences.GDB_SERVER_OVERRIDE_TARGET_DEFAULT);
fGdbServerTargetName.setText(DefaultPreferences.GDB_SERVER_TARGET_NAME_DEFAULT);
// Misc options
fGdbServerHaltAtHardFault.setSelection(DefaultPreferences.GDB_SERVER_HALT_AT_HARD_FAULT_DEFAULT);
fGdbServerStepIntoInterrupts.setSelection(DefaultPreferences.GDB_SERVER_STEP_INTO_INTERRUPTS_DEFAULT);
// Flash
fGdbServerFlashMode.select(DefaultPreferences.GDB_SERVER_FLASH_MODE_DEFAULT);
fGdbServerFlashFastVerify.setSelection(DefaultPreferences.GDB_SERVER_FLASH_FAST_VERIFY_DEFAULT);
// Semihosting
fGdbServerEnableSemihosting.setSelection(DefaultPreferences.GDB_SERVER_ENABLE_SEMIHOSTING_DEFAULT);
fGdbServerUseGdbSyscallsForSemihosting.setSelection(DefaultPreferences.GDB_SERVER_USE_GDB_SYSCALLS_DEFAULT);
// Bus speed
fGdbServerBusSpeed.setText(Integer.toString(DefaultPreferences.GDB_SERVER_BUS_SPEED_DEFAULT));
// Other options
stringDefault = DefaultPreferences.getPyocdConfig();
fGdbServerOtherOptions.setText(stringDefault);
// Allocate server console
if (EclipseUtils.isWindows()) {
fDoGdbServerAllocateConsole.setSelection(true);
} else {
fDoGdbServerAllocateConsole.setSelection(DefaultPreferences.DO_GDB_SERVER_ALLOCATE_CONSOLE_DEFAULT);
}
// Allocate telnet console
fDoGdbServerAllocateSemihostingConsole
.setSelection(DefaultPreferences.DO_GDB_SERVER_ALLOCATE_SEMIHOSTING_CONSOLE_DEFAULT);
}
// GDB Client Setup
{
// Executable
stringDefault = DefaultPreferences.getGdbClientExecutable();
fGdbClientExecutable.setText(stringDefault);
// Other options
fGdbClientOtherOptions.setText(DefaultPreferences.GDB_CLIENT_OTHER_OPTIONS_DEFAULT);
fGdbClientOtherCommands.setText(DefaultPreferences.GDB_CLIENT_OTHER_COMMANDS_DEFAULT);
}
// Remote target
{
fTargetIpAddress.setText(DefaultPreferences.REMOTE_IP_ADDRESS_DEFAULT); // $NON-NLS-1$
String portString = Integer.toString(DefaultPreferences.REMOTE_PORT_NUMBER_DEFAULT); // $NON-NLS-1$
fTargetPortNumber.setText(portString);
}
doStartGdbServerChanged();
overrideTargetChanged();
updateBoards();
updateTargets();
// Force thread update
fUpdateThreadlistOnSuspend.setSelection(DefaultPreferences.UPDATE_THREAD_LIST_DEFAULT);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.debug.ui.AbstractLaunchConfigurationTab#getId()
*/
@Override
public String getId() {
return TAB_ID;
}
@Override
public void activated(ILaunchConfigurationWorkingCopy workingCopy) {
// Do nothing. Override is necessary to avoid heavy cost of
// reinitialization (see super implementation)
}
@Override
public void deactivated(ILaunchConfigurationWorkingCopy workingCopy) {
// Do nothing. Override is necessary to avoid heavy unnecessary Apply
// (see super implementation)
}
@Override
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
{
// legacy definition; although the jtag device class is not used,
// it must be there, to avoid NPEs
configuration.setAttribute(IGDBJtagConstants.ATTR_JTAG_DEVICE, ConfigurationAttributes.JTAG_DEVICE);
}
boolean booleanValue;
String stringValue;
// PyOCD server
{
// Start server
booleanValue = fDoStartGdbServer.getSelection();
configuration.setAttribute(ConfigurationAttributes.DO_START_GDB_SERVER, booleanValue);
PersistentPreferences.putGdbServerDoStart(booleanValue);
// Executable
stringValue = fGdbServerExecutable.getText().trim();
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_EXECUTABLE, stringValue);
PersistentPreferences.putGdbServerExecutable(stringValue);
// Ports
int port;
port = Integer.parseInt(fGdbServerGdbPort.getText().trim());
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_GDB_PORT_NUMBER, port);
port = Integer.parseInt(fGdbServerTelnetPort.getText().trim());
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_TELNET_PORT_NUMBER, port);
// Board ID
if (fSelectedBoardId != null) {
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_BOARD_ID, fSelectedBoardId);
}
// Target override
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_OVERRIDE_TARGET,
fGdbServerOverrideTarget.getSelection());
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_TARGET_NAME, fGdbServerTargetName.getText());
// Misc options
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_HALT_AT_HARD_FAULT,
fGdbServerHaltAtHardFault.getSelection());
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_STEP_INTO_INTERRUPTS,
fGdbServerStepIntoInterrupts.getSelection());
// Flash
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_FLASH_MODE,
fGdbServerFlashMode.getSelectionIndex());
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_FLASH_FAST_VERIFY,
fGdbServerFlashFastVerify.getSelection());
// Semihosting
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_ENABLE_SEMIHOSTING,
fGdbServerEnableSemihosting.getSelection());
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_USE_GDB_SYSCALLS,
fGdbServerUseGdbSyscallsForSemihosting.getSelection());
// Bus speed
int freq;
freq = Integer.parseInt(fGdbServerBusSpeed.getText().trim());
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_BUS_SPEED, freq);
// Other options
stringValue = fGdbServerOtherOptions.getText().trim();
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_OTHER, stringValue);
PersistentPreferences.putGdbServerOtherOptions(stringValue);
// Allocate server console
configuration.setAttribute(ConfigurationAttributes.DO_GDB_SERVER_ALLOCATE_CONSOLE,
fDoGdbServerAllocateConsole.getSelection());
// Allocate semihosting console
configuration.setAttribute(ConfigurationAttributes.DO_GDB_SERVER_ALLOCATE_SEMIHOSTING_CONSOLE,
fDoGdbServerAllocateSemihostingConsole.getSelection());
}
// GDB client
{
// always use remote
configuration.setAttribute(IGDBJtagConstants.ATTR_USE_REMOTE_TARGET,
DefaultPreferences.USE_REMOTE_TARGET_DEFAULT);
stringValue = fGdbClientExecutable.getText().trim();
configuration.setAttribute(IGDBLaunchConfigurationConstants.ATTR_DEBUG_NAME, stringValue); // DSF
PersistentPreferences.putGdbClientExecutable(stringValue);
stringValue = fGdbClientOtherOptions.getText().trim();
configuration.setAttribute(ConfigurationAttributes.GDB_CLIENT_OTHER_OPTIONS, stringValue);
PersistentPreferences.putGdbClientOtherOptions(stringValue);
stringValue = fGdbClientOtherCommands.getText().trim();
configuration.setAttribute(ConfigurationAttributes.GDB_CLIENT_OTHER_COMMANDS, stringValue);
PersistentPreferences.putGdbClientCommands(stringValue);
}
{
if (fDoStartGdbServer.getSelection()) {
configuration.setAttribute(IGDBJtagConstants.ATTR_IP_ADDRESS, "localhost");
try {
int port;
port = Integer.parseInt(fGdbServerGdbPort.getText().trim());
configuration.setAttribute(IGDBJtagConstants.ATTR_PORT_NUMBER, port);
} catch (NumberFormatException e) {
Activator.log(e);
}
} else {
String ip = fTargetIpAddress.getText().trim();
configuration.setAttribute(IGDBJtagConstants.ATTR_IP_ADDRESS, ip);
try {
int port = Integer.valueOf(fTargetPortNumber.getText().trim()).intValue();
configuration.setAttribute(IGDBJtagConstants.ATTR_PORT_NUMBER, port);
} catch (NumberFormatException e) {
Activator.log(e);
}
}
}
// Force thread update
configuration.setAttribute(IGDBLaunchConfigurationConstants.ATTR_DEBUGGER_UPDATE_THREADLIST_ON_SUSPEND,
fUpdateThreadlistOnSuspend.getSelection());
PersistentPreferences.flush();
}
@Override
public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
configuration.setAttribute(IGDBJtagConstants.ATTR_JTAG_DEVICE, ConfigurationAttributes.JTAG_DEVICE);
String defaultString;
boolean defaultBoolean;
// These are inherited from the generic implementation.
// Some might need some trimming.
{
CommandFactoryManager cfManager = MIPlugin.getDefault().getCommandFactoryManager();
CommandFactoryDescriptor defDesc = cfManager.getDefaultDescriptor(IGDBJtagConstants.DEBUGGER_ID);
configuration.setAttribute(IMILaunchConfigurationConstants.ATTR_DEBUGGER_COMMAND_FACTORY,
defDesc.getName());
configuration.setAttribute(IMILaunchConfigurationConstants.ATTR_DEBUGGER_PROTOCOL,
defDesc.getMIVersions()[0]);
configuration.setAttribute(IMILaunchConfigurationConstants.ATTR_DEBUGGER_VERBOSE_MODE,
IMILaunchConfigurationConstants.DEBUGGER_VERBOSE_MODE_DEFAULT);
configuration.setAttribute(IGDBLaunchConfigurationConstants.ATTR_DEBUGGER_UPDATE_THREADLIST_ON_SUSPEND,
IGDBLaunchConfigurationConstants.DEBUGGER_UPDATE_THREADLIST_ON_SUSPEND_DEFAULT);
}
// PyOCD GDB server setup
{
defaultBoolean = PersistentPreferences.getGdbServerDoStart();
configuration.setAttribute(ConfigurationAttributes.DO_START_GDB_SERVER, defaultBoolean);
defaultString = PersistentPreferences.getGdbServerExecutable();
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_EXECUTABLE, defaultString);
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_CONNECTION_ADDRESS,
DefaultPreferences.GDB_SERVER_CONNECTION_ADDRESS_DEFAULT);
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_GDB_PORT_NUMBER,
DefaultPreferences.GDB_SERVER_GDB_PORT_NUMBER_DEFAULT);
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_TELNET_PORT_NUMBER,
DefaultPreferences.GDB_SERVER_TELNET_PORT_NUMBER_DEFAULT);
// Board ID
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_BOARD_ID,
DefaultPreferences.GDB_SERVER_BOARD_ID_DEFAULT);
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_BOARD_NAME,
DefaultPreferences.GDB_SERVER_BOARD_NAME_DEFAULT);
// Bus speed
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_BUS_SPEED,
DefaultPreferences.GDB_SERVER_BUS_SPEED_DEFAULT);
// Target override
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_OVERRIDE_TARGET,
DefaultPreferences.GDB_SERVER_OVERRIDE_TARGET_DEFAULT);
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_TARGET_NAME,
DefaultPreferences.GDB_SERVER_TARGET_NAME_DEFAULT);
// Misc options
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_HALT_AT_HARD_FAULT,
DefaultPreferences.GDB_SERVER_HALT_AT_HARD_FAULT_DEFAULT);
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_STEP_INTO_INTERRUPTS,
DefaultPreferences.GDB_SERVER_STEP_INTO_INTERRUPTS_DEFAULT);
// Flash
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_FLASH_MODE,
DefaultPreferences.GDB_SERVER_FLASH_MODE_DEFAULT);
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_FLASH_FAST_VERIFY,
DefaultPreferences.GDB_SERVER_FLASH_FAST_VERIFY_DEFAULT);
// Semihosting
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_ENABLE_SEMIHOSTING,
DefaultPreferences.GDB_SERVER_ENABLE_SEMIHOSTING_DEFAULT);
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_USE_GDB_SYSCALLS,
DefaultPreferences.GDB_SERVER_USE_GDB_SYSCALLS_DEFAULT);
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_LOG,
DefaultPreferences.GDB_SERVER_LOG_DEFAULT);
defaultString = PersistentPreferences.getGdbServerOtherOptions();
configuration.setAttribute(ConfigurationAttributes.GDB_SERVER_OTHER, defaultString);
configuration.setAttribute(ConfigurationAttributes.DO_GDB_SERVER_ALLOCATE_CONSOLE,
DefaultPreferences.DO_GDB_SERVER_ALLOCATE_CONSOLE_DEFAULT);
configuration.setAttribute(ConfigurationAttributes.DO_GDB_SERVER_ALLOCATE_SEMIHOSTING_CONSOLE,
DefaultPreferences.DO_GDB_SERVER_ALLOCATE_SEMIHOSTING_CONSOLE_DEFAULT);
}
// GDB client setup
{
defaultString = PersistentPreferences.getGdbClientExecutable();
configuration.setAttribute(IGDBLaunchConfigurationConstants.ATTR_DEBUG_NAME, defaultString);
configuration.setAttribute(IGDBJtagConstants.ATTR_USE_REMOTE_TARGET,
DefaultPreferences.USE_REMOTE_TARGET_DEFAULT);
defaultString = PersistentPreferences.getGdbClientOtherOptions();
configuration.setAttribute(ConfigurationAttributes.GDB_CLIENT_OTHER_OPTIONS, defaultString);
defaultString = PersistentPreferences.getGdbClientCommands();
configuration.setAttribute(ConfigurationAttributes.GDB_CLIENT_OTHER_COMMANDS, defaultString);
}
// Force thread update
configuration.setAttribute(IGDBLaunchConfigurationConstants.ATTR_DEBUGGER_UPDATE_THREADLIST_ON_SUSPEND,
DefaultPreferences.UPDATE_THREAD_LIST_DEFAULT);
}
/**
* Register an error
*
* <p>
* Any number of unique errors can be registered. Only one is shown to the
* user. First come first serve.
*/
private void registerError(String msg) {
if (fErrors.isEmpty()) {
setErrorMessage(msg);
}
fErrors.add(msg);
}
/**
* Remove a previously registered error.
*
* If the removed error was being displayed, the next in line (if any) is
* shown.
*/
private void deregisterError(String msg) {
if (fErrors.remove(msg)) {
if (fErrors.isEmpty()) {
setErrorMessage(null);
} else {
setErrorMessage(fErrors.iterator().next());
}
}
}
} |
package fi.iot.iiframework.restapi;
import fi.iot.iiframework.application.ApplicationSettings;
import fi.iot.iiframework.domain.SensorConfiguration;
import fi.iot.iiframework.domain.Sensor;
import fi.iot.iiframework.domain.SensorConfiguration;
import fi.iot.iiframework.restapi.exceptions.InvalidObjectException;
import fi.iot.iiframework.restapi.exceptions.InvalidParametersException;
import fi.iot.iiframework.restapi.exceptions.ResourceNotFoundException;
import fi.iot.iiframework.services.domain.SensorConfigurationService;
import fi.iot.iiframework.services.domain.SensorService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("1.0/configurations/sensors")
public class SensorConfigurationController {
@Autowired
private RestAPIHelper helper;
@Autowired
private ApplicationSettings settings;
@Autowired
private SensorConfigurationService sensorConfigurationService;
@Autowired
private SensorService sensorService;
@RequestMapping(value = "/{sensorid}/view", produces = "application/json")
@ResponseBody
public SensorConfiguration getSensorConfiguration(
@PathVariable String sensorid
) throws InvalidParametersException, ResourceNotFoundException {
Sensor sensor = (Sensor) helper.returnOrException(sensorService.get(sensorid));
return (SensorConfiguration) helper.returnOrException(sensor.getSensorConfiguration());
}
@RequestMapping(
value = "/{sensorid}/add",
method = RequestMethod.POST,
produces = "application/json",
consumes = "application/json"
)
@ResponseBody
public ResponseEntity<SensorConfiguration> addSensorConfiguration(
@PathVariable String sensorid,
@RequestBody SensorConfiguration configuration
) throws InvalidParametersException, ResourceNotFoundException, InvalidObjectException {
Sensor sensor = (Sensor) helper.returnOrException(sensorService.get(sensorid));
configuration.setSensor(sensor);
sensor.setSensorConfiguration(configuration);
helper.checkIfObjectIsValid(configuration);
sensorConfigurationService.save(configuration);
sensorService.save(sensor);
return new ResponseEntity<>(configuration, HttpStatus.CREATED);
}
@RequestMapping(
value = "/{sensorid}/edit",
method = RequestMethod.POST,
produces = "application/json",
consumes = "application/json"
)
@ResponseBody
public ResponseEntity<SensorConfiguration> editSensorConfiguration(
@PathVariable String sensorid,
@RequestBody SensorConfiguration configuration
) throws InvalidParametersException, ResourceNotFoundException, InvalidObjectException {
Sensor sensor = (Sensor) helper.returnOrException(sensorService.get(sensorid));
configuration.setSensor(sensor);
sensor.setSensorConfiguration(configuration);
sensorConfigurationService.save(configuration);
sensorService.save(sensor);
return new ResponseEntity<>(configuration, HttpStatus.CREATED);
}
@RequestMapping(
value = "/{sensorid}/delete",
method = RequestMethod.DELETE,
produces = "application/json"
)
@ResponseBody
public ResponseEntity<SensorConfiguration> deleteSensorConfiguration(
@PathVariable String sensorid
) throws InvalidParametersException, ResourceNotFoundException {
Sensor sensor = (Sensor) helper.returnOrException(sensorService.get(sensorid));
SensorConfiguration configuration = (SensorConfiguration) helper.returnOrException(sensor.getSensorConfiguration());
sensorConfigurationService.delete(sensor.getSensorConfiguration());
return new ResponseEntity<>(configuration, HttpStatus.CREATED);
}
@RequestMapping(value = "/list", produces = "application/json")
@ResponseBody
public List<SensorConfiguration> listSensorConfigurationsList(
) throws InvalidParametersException {
return sensorConfigurationService.get(0, settings.getDefaultSensorConfigurationsRetrievedFromDatabase());
}
@RequestMapping(value = "/list/{amount}", produces = "application/json")
@ResponseBody
public List<SensorConfiguration> listSensorConfigurationsListAmount(
@PathVariable int amount
) throws InvalidParametersException {
helper.exceptionIfWrongLimits(0, amount);
return sensorConfigurationService.get(0, amount);
}
@RequestMapping(value = "/list/{to}/{from}", produces = "application/json")
@ResponseBody
public List<SensorConfiguration> listSensorConfigurationsListFromTo(
@PathVariable int from,
@PathVariable int to
) throws InvalidParametersException {
helper.exceptionIfWrongLimits(to, from);
return sensorConfigurationService.get(to, from);
}
} |
package net.sf.jguard.jee.authentication.http;
import com.mycila.testing.junit.MycilaJunitRunner;
import net.sf.jguard.core.PolicyEnforcementPointOptions;
import net.sf.jguard.core.authentication.StatefulAuthenticationServicePoint;
import net.sf.jguard.core.authentication.credentials.JGuardCredential;
import net.sf.jguard.core.authentication.manager.AuthenticationManager;
import net.sf.jguard.core.authorization.permissions.RolePrincipal;
import net.sf.jguard.core.principals.Organization;
import net.sf.jguard.core.test.JGuardTestFiles;
import net.sf.jguard.jee.JGuardJEETest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import javax.security.auth.login.Configuration;
import java.security.Principal;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MycilaJunitRunner.class)
public class JGuardServletRequestWrapperTest extends JGuardJEETest {
private static final Logger logger = LoggerFactory.getLogger(JGuardServletRequestWrapperTest.class);
private static final String TEST_USER = "testUser";
private String configurationLocation;
private String applicationName = "jguard-struts-example";
private Configuration configuration;
private AuthenticationManager authenticationManager;
private static final String LOGIN = "login";
private static final String DUMMY_VALUE = "bla";
@Before
public void setUp() throws Exception {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String jguardAuthentication = JGuardTestFiles.J_GUARD_AUTHENTICATION_XML.getLabel();
configurationLocation = cl.getResource(jguardAuthentication).toString();
authenticationManager = mock(AuthenticationManager.class);
configuration = mock(Configuration.class);
when(authenticationManager.getCredentialId()).thenReturn(LOGIN);
}
@Test
public void testIsUserInRole() {
//given
HttpServletRequestSimulator request = new HttpServletRequestSimulator();
HttpSessionSimulator session = new HttpSessionSimulator();
request.setSession(session);
ServletContextSimulator context = new ServletContextSimulator();
context.setAttribute(PolicyEnforcementPointOptions.APPLICATION_NAME.getLabel(), applicationName);
session.setServletContext(context);
// Mock subject and principal creation
Subject subj = new Subject();
Organization organization = new Organization();
Principal p1 = new RolePrincipal(TEST_USER, applicationName, organization);
Principal p2 = new RolePrincipal("testAnotherUser", applicationName, organization);
subj.getPrincipals().add(p1);
subj.getPrincipals().add(p2);
LoginContextWrapperMockImpl loginContextWrapperMock = new LoginContextWrapperMockImpl(applicationName, configuration);
loginContextWrapperMock.setSubject(subj);
// Putting into session object
request.getSession().setAttribute(StatefulAuthenticationServicePoint.LOGIN_CONTEXT_WRAPPER, loginContextWrapperMock);
JGuardServletRequestWrapper wrapper = new JGuardServletRequestWrapper(applicationName, authenticationManager, request, loginContextWrapperMock);
// Testing
assertTrue(wrapper.isUserInRole(TEST_USER));
assertTrue(wrapper.isUserInRole("testAnotherUser"));
assertFalse(wrapper.isUserInRole("testOneMoreUser"));
}
@Test
public void testGetRemoteUser_nominal_case() {
HttpServletRequestSimulator request = new HttpServletRequestSimulator();
// Mock subject and credential
Subject subj = new Subject();
JGuardCredential login = new JGuardCredential(LOGIN, TEST_USER);
subj.getPublicCredentials().add(login);
LoginContextWrapperMockImpl loginContextWrapperMock = new LoginContextWrapperMockImpl(applicationName, configuration);
loginContextWrapperMock.setSubject(subj);
request.getSession(true).setAttribute(StatefulAuthenticationServicePoint.LOGIN_CONTEXT_WRAPPER, loginContextWrapperMock);
JGuardServletRequestWrapper wrapper = new JGuardServletRequestWrapper(applicationName, authenticationManager, request, loginContextWrapperMock);
when(authenticationManager.getIdentityCredential(subj)).thenReturn(login);
// Testing with public credentials
subj.getPublicCredentials().add(login);
assertEquals(TEST_USER, wrapper.getRemoteUser());
}
@Test
public void testGetRemoteUser_with_identityCredential_inprivateCredentials() {
HttpServletRequestSimulator request = new HttpServletRequestSimulator();
// Mock subject and credential
Subject subj = new Subject();
JGuardCredential login = new JGuardCredential(LOGIN, TEST_USER);
subj.getPublicCredentials().add(login);
LoginContextWrapperMockImpl loginContextWrapperMock = new LoginContextWrapperMockImpl(applicationName, configuration);
loginContextWrapperMock.setSubject(subj);
request.getSession(true).setAttribute(StatefulAuthenticationServicePoint.LOGIN_CONTEXT_WRAPPER, loginContextWrapperMock);
JGuardServletRequestWrapper wrapper = new JGuardServletRequestWrapper(applicationName, authenticationManager, request, loginContextWrapperMock);
when(authenticationManager.getIdentityCredential(subj)).thenReturn(null);
// Testing with public credentials
subj.getPublicCredentials().add(login);
// Testing with private credentials
subj.getPublicCredentials().clear();
assertEquals(subj.getPublicCredentials().size(), 0);
subj.getPrivateCredentials().add(login);
//login can only be present in the public subject credential set
assertNull(TEST_USER, wrapper.getRemoteUser());
}
@Test
public void testGetRemoteUser_with_no_valid_credentials() {
HttpServletRequestSimulator request = new HttpServletRequestSimulator();
// Mock subject and credential
Subject subj = new Subject();
JGuardCredential login = new JGuardCredential(LOGIN, TEST_USER);
subj.getPublicCredentials().add(login);
LoginContextWrapperMockImpl loginContextWrapperMock = new LoginContextWrapperMockImpl(applicationName, configuration);
loginContextWrapperMock.setSubject(subj);
request.getSession(true).setAttribute(StatefulAuthenticationServicePoint.LOGIN_CONTEXT_WRAPPER, loginContextWrapperMock);
JGuardServletRequestWrapper wrapper = new JGuardServletRequestWrapper(applicationName, authenticationManager, request, loginContextWrapperMock);
JGuardCredential invalidCredential = new JGuardCredential(DUMMY_VALUE, DUMMY_VALUE);
when(authenticationManager.getIdentityCredential(subj)).thenReturn(null);
// Testing with public credentials
subj.getPublicCredentials().add(login);
// Testing with no valid credential
Subject invalidSubj = new Subject();
invalidSubj.getPublicCredentials().add(invalidCredential);
invalidSubj.getPrivateCredentials().add(invalidCredential);
((LoginContextWrapperMockImpl) request.getSession().getAttribute(StatefulAuthenticationServicePoint.LOGIN_CONTEXT_WRAPPER)).setSubject(invalidSubj);
assertNull(wrapper.getRemoteUser());
}
} |
package generator;
import util.State;
public class FstGenerator {
private StringBuffer strBuff;
public FstGenerator() {
}
public StringBuffer compute(State initState, String className) {
strBuff = new StringBuffer();
System.out.println("[FstGenerator] Transforming Fst to a java class");
append("package generated;");
append("public class " + className + " {");
appendWithTab("public static float compute(int[] token) {", 1);
appendWithTab("int pos=0;", 2);
appendWithTab("float result=0f;", 2);
generateCases(initState, 2);
appendWithTab("}", 1);
append("}");
System.out.println("[FstGenerator] Successfully transformed fst to " + className + ".java");
return strBuff;
}
private void generateCases(State currentState, int tab) {
if( currentState.getNumArcs() > 0) {
generateTokenLengthTest(tab);
appendWithTab("switch(token[pos++]) {", tab);
for (int i = 0; i < currentState.getNumArcs(); i++) {
appendWithTab("case " + currentState.getArc(i).getIlabel() + ":", tab+1);
if (currentState.getArc(i).getOlabel() != 0) {
appendWithTab("result+=" + currentState.getArc(i).getOlabel() + "f;", tab+2);
}
if (currentState.getArc(i).getNextState().isFinalState()) {
appendWithTab("if(pos==token.length) {return result;}", tab+2);
}
generateCases(currentState.getArc(i).getNextState(), tab+2);
}
appendWithTab("default:", tab+1);
appendWithTab("return -1;", tab+2);
appendWithTab("}", tab);
} else {
appendWithTab("return (pos!=token.length) ? -1 : result;", tab);
}
}
private void generateTokenLengthTest(int tab) {
appendWithTab("if(pos>=token.length) {return -1;}", tab);
}
private void append(String strToAppend) {
strBuff.append(strToAppend);
strBuff.append("\n");
}
private void appendWithTab(String strToAppend, int numberOfTab) {
for (int i = 0; i < numberOfTab; i++) {
strBuff.append("\t");
}
strBuff.append(strToAppend);
strBuff.append("\n");
}
} |
package game;
import language.Dictionary;
import language.WordProperties;
import utilities.functions.StringUtilities;
/**
* The {@code Hangman} class contains the logic for a game of "Hangman." Game
* operations, such as updating the game board, are executed through methods
* contained within this class.
*
* <p> This class allows for the selection of word difficulty during
* construction.
*
* @author Oliver Abdulrahim
*/
public class Hangman {
/**
* Stores words for this instance.
*/
private Dictionary words;
/**
* Stores the current word that is being guessed by the player.
*/
private String currentWord;
/**
* Stores the characters that the player has already guessed for relaying to
* a user interface.
*/
private String alreadyGuessed;
/**
* Stores the characters that the player has already correctly guessed,
* (i.e. they exist in {@link #currentWord}). This should be relayed to the
* user interface.
*/
private String correctGuesses;
/**
* Stores the amount of character guesses the player has already made.
*/
private int guessesRemaining;
/**
* Stores the current image repository for use in a graphical interface.
*/
private Actor actor;
/**
* Initializes a new game with medium difficulty
* ({@link WordProperties#MEDIUM_WORD}).
*/
public Hangman() {
this(WordProperties.MEDIUM_WORD);
}
/**
* Initializes a new game with the difficulty setting given.
*
* @param difficulty The difficulty for this game.
*/
public Hangman(WordProperties difficulty) {
words = new Dictionary();
actor = Actor.HUMAN;
guessesRemaining = actor.getImageArray().length;
resetGame(difficulty);
}
/**
* Initializes a new game with the given difficulty.
*
* <p> If the given difficulty is invalid, defaults to medium difficulty.
*
* @param difficulty The difficulty setting to use for this game. If this
* is either {@code null} or an invalid property, defaults to
* {@link WordProperties#MEDIUM_WORD}.
*/
public final void resetGame(WordProperties difficulty) {
switch(difficulty) {
case EASY_WORD: {
currentWord = words.getEasyWord().characters();
break;
}
case MEDIUM_WORD: {
currentWord = words.getMediumWord().characters();
break;
}
case HARD_WORD: {
currentWord = words.getHardWord().characters();
break;
}
default: {
currentWord = words.getMediumWord().characters();
}
}
correctGuesses = StringUtilities.createRepeating(currentWord.length(), '_');
alreadyGuessed = "";
}
/**
* Returns the current word for this game instance.
*
* @return The current word of this instance.
*/
public String getCurrentWord() {
return currentWord;
}
/**
* Returns a {@code String} containing all the characters that have already
* been guessed in this game.
*
* @return The characters that have already been guessed.
*/
public String getAlreadyGuessed() {
return alreadyGuessed;
}
/**
* Appends the given character to the end of the {@code String} containing
* the other characters that have been guessed.
*
* @param guess The character guess to append.
*/
public void appendAlreadyGuessed(char guess) {
alreadyGuessed += guess;
}
/**
* Returns a {@code String} containing all the characters that have been
* guessed correctly in this game instance.
*
* <p> This returns, in other words, the union between the current word and
* the characters that have already been guessed.
*
* @return The characters that have already been guessed correctly.
*/
public String getCorrectGuesses() {
return correctGuesses;
}
/**
* Appends the given character to the end of the {@code String} containing
* the other characters that have been guessed.
*
* @param guess The character guess to append.
*/
public void appendCorrectGuesses(char guess) {
correctGuesses += guess;
}
/**
* Returns the actor for this game instance.
*
* @return The actor for this instance.
*/
public Actor getActor() {
return actor;
}
/**
* Method that delegates a guess operation to the {@code isValidGuess(char)}
* method in this class. Returns {@code true} if the guess is valid,
* {@code false} if not.
*
* @param guess The character to attempt to guess for.
* @return Returns {@code true} if the guess is valid, {@code false} if
* not.
*/
public boolean guessLetter(char guess) {
guess = Character.toLowerCase(guess);
boolean validFlag = isValidGuess(guess);
alreadyGuessed = StringUtilities.sortString(alreadyGuessed);
return validFlag;
}
/**
* Method that attempts to add a guess character to the appropriate words.
* If the character has already been guessed, do nothing. If the character
* has not already been guessed but is not in the current word, increment
* the amount of guesses made and add the letter to the list of guessed
* letters. Otherwise update the correct guess display appropriately.
*
* @param guess The character to attempt to guess for.
* @return Returns {@code true} if the guess is valid, {@code false} if
* not.
*/
private boolean isValidGuess(char guess) {
guess = Character.toLowerCase(guess);
if (alreadyGuessed.contains(String.valueOf(guess))) {
return false;
}
if (!currentWord.contains(String.valueOf(guess))) {
alreadyGuessed += guess;
guessesMade++;
return false;
}
else {
alreadyGuessed += guess;
correctGuess(guess);
}
return true;
}
/**
* Method that updates the correct guess display. For each time the given
* argument appears in the current word, add it to the correct guesses.
*
* @param guess The character to add to the correct display.
*/
private void correctGuess(char guess) {
guess = Character.toLowerCase(guess);
for (int i = 0; i < currentWord.length(); i++) {
if (currentWord.charAt(i) == guess) {
correctGuesses = correctGuesses.substring(0, i)
+ guess
+ correctGuesses.substring(i + 1);
}
}
}
/**
* Method that checks for the win state of Hangman, or, in other words, when
* the user's guesses are equal to the actual word.
*
* While this method does take into account the amount of guesses the user
* has already made, implementations of this class should ensure that the
* amount of guesses that a user may make are kept concurrent with the
* maximum amount of guesses that are possible for this instance.
*
* @return Returns {@code true} if the user's correct guesses are the same
* as the actual word, otherwise returns {@code false}.
*/
public boolean hasWon() {
return correctGuesses.equalsIgnoreCase(currentWord)
&& guessesMade <= maxGuesses;
}
} |
package scala.tools.partest.javaagent;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
/**
* Profiling agent that instruments byte-code to insert calls to
* {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
* by using ASM library for byte-code manipulation.
*/
public class ProfilingAgent {
public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
// NOTE: we are adding transformer that won't be applied to classes that are already loaded
// This should be ok because premain should be executed before main is executed so Scala library
// and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
// not depend on Scala library. In case our assumptions are wrong we can always insert call to
// inst.retransformClasses.
inst.addTransformer(new ASMTransformer(), false);
}
} |
import java.util.Vector;
import com.sun.star.wizards.text.TextDocument;
import com.sun.star.awt.Point;
import com.sun.star.awt.Size;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.XNameContainer;
import com.sun.star.frame.XModel;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.wizards.db.*;
import com.sun.star.wizards.common.*;
import com.sun.star.wizards.ui.*;
import com.sun.star.wizards.text.TextStyleHandler;
import com.sun.star.wizards.text.ViewHandler;
import com.sun.star.wizards.document.Control;
import com.sun.star.wizards.document.DatabaseControl;
import com.sun.star.wizards.document.FormHandler;
import com.sun.star.wizards.document.GridControl;
public class FormDocument extends TextDocument {
public FormHandler oFormHandler;
public ViewHandler oViewHandler;
public TextStyleHandler oTextStyleHandler;
public XPropertySet xPropPageStyle;
public final int SOSYMBOLMARGIN = 2000;
private final int SOFORMGAP = 1000;
public Vector oControlForms = new Vector();
public CommandMetaData oMainFormDBMetaData;
public CommandMetaData oSubFormDBMetaData;
private boolean bhasSubForm;
private UIControlArranger curUIControlArranger;
public StyleApplier curStyleApplier;
public String[][] LinkFieldNames;
public XModel xModel;
private String sMsgEndAutopilot;
int MainFormStandardHeight;
int nPageWidth;
int nPageHeight;
int nFormWidth;
int nFormHeight;
int nMainFormFieldCount;
int totfieldcount;
Point aMainFormPoint;
Point aSubFormPoint;
final static String SOMAINFORM = "MainForm";
final static String SOSUBFORM = "SubForm";
public FormDocument(XMultiServiceFactory xMSF, boolean bshowStatusIndicator, boolean bgetCurrentFrame, Resource oResource) {
super(xMSF, bshowStatusIndicator, bgetCurrentFrame, null);
try {
oFormHandler = new FormHandler(xMSF, xTextDocument);
oFormHandler.setDrawObjectsCaptureMode(false);
oTextStyleHandler = new TextStyleHandler(xMSFDoc, xTextDocument);
oViewHandler = new ViewHandler(xMSFDoc, xTextDocument);
oMainFormDBMetaData = new CommandMetaData(xMSF);// , CharLocale);
oSubFormDBMetaData = new CommandMetaData(xMSF);// , CharLocale);
ViewHandler oViewHandler = new ViewHandler(xMSF, xTextDocument);
TextStyleHandler oTextStyleSupplier = new TextStyleHandler(xMSFDoc, xTextDocument);
Helper.setUnoPropertyValue(xTextDocument, "ApplyFormDesignMode", Boolean.FALSE);
oViewHandler.setViewSetting("ShowTableBoundaries", Boolean.FALSE);
oViewHandler.setViewSetting("ShowOnlineLayout", Boolean.TRUE);
xPropPageStyle = oTextStyleSupplier.getStyleByName("PageStyles", "Standard");
Size aSize = oTextStyleHandler.changePageAlignment(xPropPageStyle, true);
nPageWidth = aSize.Width;
nPageHeight = aSize.Height;
sMsgEndAutopilot = oResource.getResText(UIConsts.RID_DB_COMMON + 33);
} catch (Exception e) {
e.printStackTrace(System.out);
}}
public void addUIFormController(UIControlArranger _curUIControlArranger){
this.curUIControlArranger = _curUIControlArranger;
}
public void addStyleApplier(StyleApplier _curStyleApplier){
this.curStyleApplier = _curStyleApplier;
}
private String getDataSourceName(){
return this.oMainFormDBMetaData.DataSourceName;
}
private void adjustPageStyle(){
try {
int nMargin;
totfieldcount = getTotFieldCount();
if (totfieldcount > 30)
nMargin = 500;
else if (totfieldcount > 20)
nMargin = 750;
else
nMargin = 1000;
xPropPageStyle.setPropertyValue("RightMargin", new Integer(nMargin));
xPropPageStyle.setPropertyValue("LeftMargin", new Integer(nMargin));
xPropPageStyle.setPropertyValue("TopMargin", new Integer(nMargin));
xPropPageStyle.setPropertyValue("BottomMargin", new Integer(nMargin));
aMainFormPoint = new Point(nMargin, nMargin);
nFormWidth = (int) (0.8 * (double) nPageWidth) - 2 * nMargin;
nFormHeight = (int) (0.65 * (double) nPageHeight) - 2 * nMargin;
} catch (Exception e) {
e.printStackTrace(System.out);
}}
public void initialize(boolean _baddParentForm, boolean _bhasSubForm, boolean _bModifySubForm){
bhasSubForm = _bhasSubForm;
adjustPageStyle();
if (_baddParentForm ){
if (oControlForms.size() == 0)
oControlForms.addElement(new ControlForm(this, SOMAINFORM, aMainFormPoint, getMainFormSize(FormWizard.SOGRID)));
else{
oFormHandler.removeControlsofForm(SOMAINFORM);
((ControlForm) oControlForms.get(0)).oFormController = null;
}
((ControlForm) oControlForms.get(0)).initialize(curUIControlArranger.getSelectedArrangement(0));
}
if(_bhasSubForm){
if (oControlForms.size() == 1){
adjustMainFormSize();
oControlForms.addElement(new ControlForm(this, SOSUBFORM, getSubFormPoint(), getSubFormSize()));
((ControlForm) oControlForms.get(1)).initialize(curUIControlArranger.getSelectedArrangement(1));
}
else if (_bModifySubForm){
if (oControlForms.size() > 1){
oFormHandler.removeControlsofForm(SOSUBFORM);
((ControlForm) oControlForms.get(1)).oFormController = null;
((ControlForm) oControlForms.get(1)).initialize(curUIControlArranger.getSelectedArrangement(1));
}
}
}
else{
if (oFormHandler.hasFormByName(SOSUBFORM)){
oFormHandler.removeFormByName(SOSUBFORM);
oControlForms.remove(1);
adjustMainFormSize();
}
}
}
private int getTotFieldCount(){
nMainFormFieldCount = oMainFormDBMetaData.FieldNames.length;
totfieldcount = nMainFormFieldCount + oSubFormDBMetaData.FieldNames.length;
return totfieldcount;
}
private Size getMainFormSize(int _curArrangement){
int nMainFormHeight = nFormHeight;
if (bhasSubForm){
if (_curArrangement == FormWizard.SOGRID)
nMainFormHeight = (int) ((double)(nFormHeight-SOFORMGAP)/2);
else{
totfieldcount = getTotFieldCount();
nMainFormHeight = (int) (((double) nMainFormFieldCount/(double) totfieldcount) * ((double)(nFormHeight-SOFORMGAP)/2));
}
}
Size aMainFormSize = new Size(nFormWidth, nMainFormHeight);
MainFormStandardHeight = nMainFormHeight;
return aMainFormSize;
}
private Size getSubFormSize(){
// int nSubFormHeight = (int) ((double)nFormHeight/2) - SOFORMGAP;
// int nSubFormFieldCount = this.oSubFormDBMetaData.FieldNames.length;
// int totfieldcount = oMainFormDBMetaData.FieldNames.length + nSubFormFieldCount;
int nMainFormHeight = ((ControlForm) oControlForms.get(0)).getActualFormHeight();
Size aSubFormSize = new Size(nFormWidth, nFormHeight - nMainFormHeight - SOFORMGAP);
return aSubFormSize;
}
private Point getSubFormPoint(){
ControlForm curMainControlForm = ((ControlForm) oControlForms.get(0));
return new Point(curMainControlForm.aStartPoint.X,
(curMainControlForm.aStartPoint.Y + curMainControlForm.getFormSize().Height + SOFORMGAP));
}
private void adjustMainFormSize(){
ControlForm oMainControlForm = (ControlForm) oControlForms.get(0);
oMainControlForm.setFormSize(getMainFormSize(oMainControlForm.curArrangement));
if (oMainControlForm.curArrangement == FormWizard.SOGRID)
oMainControlForm.oGridControl.setSize(oMainControlForm.getFormSize());
else
oMainControlForm.oFormController.positionControls(oMainControlForm.curArrangement,
oMainControlForm.aStartPoint,
oMainControlForm.getFormSize(),
curUIControlArranger.getAlignValue());
}
private void adjustSubFormPosSize(){
ControlForm oMainControlForm = (ControlForm) oControlForms.get(0);
ControlForm oSubControlForm = (ControlForm) oControlForms.get(1);
oSubControlForm.setFormSize(new Size(nFormWidth, (int)nFormHeight - oMainControlForm.getFormSize().Height));
if (oSubControlForm.curArrangement == FormWizard.SOGRID){
Point aPoint = oSubControlForm.oGridControl.getPosition();
int idiffheight = oSubControlForm.getEntryPointY() - oMainControlForm.getActualFormHeight()- oMainControlForm.aStartPoint.Y - SOFORMGAP;
oSubControlForm.setStartPoint(new Point(aPoint.X, (aPoint.Y - idiffheight)));
oSubControlForm.oGridControl.setPosition(oSubControlForm.aStartPoint);
oSubControlForm.oGridControl.setSize(getSubFormSize());
}
else{
// oSubControlForm.oFormController.adjustYPositions(_idiffheight);
oSubControlForm.setStartPoint( new Point(oSubControlForm.aStartPoint.X, oMainControlForm.getActualFormHeight() + oMainControlForm.aStartPoint.Y + SOFORMGAP));
oSubControlForm.oFormController.positionControls(oSubControlForm.curArrangement, oSubControlForm.aStartPoint, oSubControlForm.getAvailableFormSize(), curUIControlArranger.getAlignValue());
}
}
public ControlForm getControlFormByName(String _sname){
for (int i = 0; i < oControlForms.size(); i++){
ControlForm curControlForm = ((ControlForm) oControlForms.get(i));
if (curControlForm.Name.equals(_sname))
return curControlForm;
}
return null;
}
public ControlForm[] getControlForms(){
return (ControlForm[]) oControlForms.toArray();
}
public boolean finalizeForms(DataEntrySetter _curDataEntrySetter, FieldLinker _curFieldLinker, FormConfiguration _curFormConfiguration){
try {
this.xTextDocument.lockControllers();
PropertyValue[] aFormProperties = _curDataEntrySetter.getFormProperties();
ControlForm oMasterControlForm = getControlFormByName(SOMAINFORM);
oMasterControlForm.setFormProperties(aFormProperties, oMainFormDBMetaData);
oMasterControlForm.finalizeControls();
if (oMasterControlForm.xFormContainer.hasByName(SOSUBFORM)){
ControlForm oSubControlForm = getControlFormByName(SOSUBFORM);
oSubControlForm.setFormProperties(aFormProperties, oSubFormDBMetaData);
String sRefTableName = _curFormConfiguration.getreferencedTableName();
if (sRefTableName.equals(""))
LinkFieldNames = _curFieldLinker.getLinkFieldNames();
else
LinkFieldNames = _curFieldLinker.getLinkFieldNames(_curFormConfiguration.getRelationController(), sRefTableName);
if (LinkFieldNames != null){
if (LinkFieldNames.length > 0){
oSubControlForm.xPropertySet.setPropertyValue("DetailFields", LinkFieldNames[0]);
oSubControlForm.xPropertySet.setPropertyValue("MasterFields", LinkFieldNames[1]);
oSubControlForm.finalizeControls();
return true;
}
}
return false;
}
return true;
} catch (Exception e) {
e.printStackTrace(System.out);
return false;
}
finally{
unlockallControllers();
}
}
public class ControlForm{
XNameContainer xFormContainer;
GridControl oGridControl;
FormControlArranger oFormController;
int curArrangement;
FormDocument oFormDocument;
String Name;
Point aStartPoint;
private Size aFormSize;
CommandMetaData oDBMetaData;
XPropertySet xPropertySet;
public ControlForm(FormDocument _oFormDocument, String _sname, Point _astartPoint, Size _aFormSize){
aStartPoint = _astartPoint;
aFormSize = _aFormSize;
oFormDocument = _oFormDocument;
Name = _sname;
if (_sname.equals(SOSUBFORM)){
ControlForm oMainControlForm = ((ControlForm) oControlForms.get(0));
xFormContainer = oFormHandler.insertFormbyName(_sname, oMainControlForm.xFormContainer);
}
else
xFormContainer = oFormHandler.insertFormbyName(_sname);
xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xFormContainer);
if (_sname.equals(SOMAINFORM))
oDBMetaData = oFormDocument.oMainFormDBMetaData;
else
oDBMetaData = oFormDocument.oSubFormDBMetaData;
}
public void initialize(int _curArrangement){
boolean badaptControlStyles = false;
xTextDocument.lockControllers();
curArrangement = _curArrangement;
if (oGridControl != null){
oFormHandler.xDrawPage.remove(oGridControl.xShape);
oGridControl.xComponent.dispose();
oGridControl = null;
}
if (oFormController == null)
oFormController = new FormControlArranger(oFormHandler, xFormContainer, oDBMetaData, xProgressBar, aStartPoint, aFormSize);
else{
if (curArrangement == FormWizard.SOGRID){
oFormHandler.moveShapesToNirwana(getLabelControls());
oFormHandler.moveShapesToNirwana(getDatabaseControls());
}
}
if (curArrangement == FormWizard.SOGRID){
insertGridControl();
badaptControlStyles = true;
}
else{
badaptControlStyles = !oFormController.areControlsexisting();
oFormController.positionControls(_curArrangement, aStartPoint, getAvailableFormSize(), curUIControlArranger.getAlignValue());
}
if (badaptControlStyles)
curStyleApplier.applyStyle(false, true);
if ((Name.equals(SOMAINFORM)) && (oControlForms.size() > 1)){
ControlForm curSubControlForm = ((ControlForm) oControlForms.get(1));
if (curSubControlForm != null){
adjustSubFormPosSize();
}
}
setFormSize(new Size(aFormSize.Width, getActualFormHeight()));
unlockallControllers();
}
public Control[] getLabelControls(){
if (oFormController != null)
return oFormController.LabelControlList;
else return null;
}
public Size getFormSize(){
return aFormSize;
}
private Size getAvailableFormSize(){
if (this.Name.equals(SOMAINFORM))
setFormSize(getMainFormSize(curArrangement));
else
setFormSize(getSubFormSize());
return aFormSize;
}
public void setFormSize(Size _aSize){
aFormSize = _aSize;
oFormController.setFormSize(aFormSize);
}
private void setStartPoint(Point _aPoint){
aStartPoint = _aPoint;
if (oFormController != null)
oFormController.setStartPoint(_aPoint);
}
private int getActualFormHeight(){
if (curArrangement == FormWizard.SOGRID)
return oGridControl.xShape.getSize().Height;
else
return oFormController.getFormHeight();
}
private int getEntryPointY(){
if (curArrangement == FormWizard.SOGRID)
return oGridControl.xShape.getPosition().Y;
else
return oFormController.getEntryPointY();
}
private void setFormProperties(PropertyValue[] _aPropertySetList, CommandMetaData _oDBMetaData){
try {
xPropertySet.setPropertyValue("DataSourceName", getDataSourceName());
xPropertySet.setPropertyValue("Command", _oDBMetaData.getCommandName());
xPropertySet.setPropertyValue("CommandType", new Integer(_oDBMetaData.getCommandType()));
for (int i = 0; i < _aPropertySetList.length; i++){
xPropertySet.setPropertyValue(_aPropertySetList[i].Name, _aPropertySetList[i].Value);
}
} catch (Exception e) {
e.printStackTrace(System.out);
}}
public DatabaseControl[] getDatabaseControls(){
if (oFormController != null)
return oFormController.DBControlList;
else return null;
}
public GridControl getGridControl(){
return oGridControl;
}
public int getArrangemode(){
return curArrangement;
}
private void insertGridControl(){
curArrangement = FormWizard.SOGRID;
if (Name.equals(SOMAINFORM))
oGridControl = new GridControl(xMSF,Name + "_Grid", oFormHandler, xFormContainer, oDBMetaData.DBFieldColumns, aStartPoint, getMainFormSize(FormWizard.SOGRID));
else
oGridControl = new GridControl(xMSF, Name + "_Grid", oFormHandler, xFormContainer, oDBMetaData.DBFieldColumns, aStartPoint, getSubFormSize());
}
public void finalizeControls(){
Control[] oLabelControls = getLabelControls();
Control[] oDBControls = getDatabaseControls();
if (oLabelControls != null){
for (int i = 0; i < getLabelControls().length; i++){
if (curArrangement == FormWizard.SOGRID){
if ((oLabelControls[i] != null) && (oDBControls[i] != null)){
oFormHandler.removeShape(oLabelControls[i].xShape);
oFormHandler.removeShape(oDBControls[i].xShape);
}
}
else{
oFormHandler.groupShapesTogether(xMSF,oLabelControls[i].xShape, oDBControls[i].xShape);
}
}
}
}
}
} |
package org.bouncycastle.tsp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Date;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.cms.IssuerAndSerialNumber;
import org.bouncycastle.asn1.ess.ESSCertID;
import org.bouncycastle.asn1.ess.ESSCertIDv2;
import org.bouncycastle.asn1.ess.SigningCertificate;
import org.bouncycastle.asn1.ess.SigningCertificateV2;
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.tsp.TSTInfo;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.IssuerSerial;
import org.bouncycastle.cert.X509AttributeCertificateHolder;
import org.bouncycastle.cert.X509CRLHolder;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessable;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerId;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationVerifier;
import org.bouncycastle.operator.DigestCalculator;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Store;
/**
* Carrier class for a TimeStampToken.
*/
public class TimeStampToken
{
CMSSignedData tsToken;
SignerInformation tsaSignerInfo;
Date genTime;
TimeStampTokenInfo tstInfo;
CertID certID;
public TimeStampToken(ContentInfo contentInfo)
throws TSPException, IOException
{
this(getSignedData(contentInfo));
}
private static CMSSignedData getSignedData(ContentInfo contentInfo)
throws TSPException
{
try
{
return new CMSSignedData(contentInfo);
}
catch (CMSException e)
{
throw new TSPException("TSP parsing error: " + e.getMessage(), e.getCause());
}
}
public TimeStampToken(CMSSignedData signedData)
throws TSPException, IOException
{
this.tsToken = signedData;
if (!this.tsToken.getSignedContentTypeOID().equals(PKCSObjectIdentifiers.id_ct_TSTInfo.getId()))
{
throw new TSPValidationException("ContentInfo object not for a time stamp.");
}
Collection<SignerInformation> signers = tsToken.getSignerInfos().getSigners();
if (signers.size() != 1)
{
throw new IllegalArgumentException("Time-stamp token signed by "
+ signers.size()
+ " signers, but it must contain just the TSA signature.");
}
tsaSignerInfo = signers.iterator().next();
try
{
CMSProcessable content = tsToken.getSignedContent();
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
content.write(bOut);
@SuppressWarnings("resource")
ASN1InputStream aIn = new ASN1InputStream(bOut.toByteArray());
this.tstInfo = new TimeStampTokenInfo(TSTInfo.getInstance(aIn.readObject()));
Attribute attr = tsaSignerInfo.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
if (attr != null)
{
SigningCertificate signCert = SigningCertificate.getInstance(attr.getAttrValues().getObjectAt(0));
this.certID = new CertID(ESSCertID.getInstance(signCert.getCerts()[0]));
}
else
{
attr = tsaSignerInfo.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
if (attr == null)
{
throw new TSPValidationException("no signing certificate attribute found, time stamp invalid.");
}
SigningCertificateV2 signCertV2 = SigningCertificateV2.getInstance(attr.getAttrValues().getObjectAt(0));
this.certID = new CertID(ESSCertIDv2.getInstance(signCertV2.getCerts()[0]));
}
}
catch (CMSException e)
{
throw new TSPException(e.getMessage(), e.getUnderlyingException());
}
}
public TimeStampTokenInfo getTimeStampInfo()
{
return tstInfo;
}
public SignerId getSID()
{
return tsaSignerInfo.getSID();
}
public AttributeTable getSignedAttributes()
{
return tsaSignerInfo.getSignedAttributes();
}
public AttributeTable getUnsignedAttributes()
{
return tsaSignerInfo.getUnsignedAttributes();
}
public Store<X509CertificateHolder> getCertificates()
{
return tsToken.getCertificates();
}
public Store<X509CRLHolder> getCRLs()
{
return tsToken.getCRLs();
}
public Store<X509AttributeCertificateHolder> getAttributeCertificates()
{
return tsToken.getAttributeCertificates();
}
public void validate(
SignerInformationVerifier sigVerifier)
throws TSPException, TSPValidationException
{
if (!sigVerifier.hasAssociatedCertificate())
{
throw new IllegalArgumentException("verifier provider needs an associated certificate");
}
try
{
X509CertificateHolder certHolder = sigVerifier.getAssociatedCertificate();
DigestCalculator calc = sigVerifier.getDigestCalculator(certID.getHashAlgorithm());
OutputStream cOut = calc.getOutputStream();
cOut.write(certHolder.getEncoded());
cOut.close();
if (!Arrays.constantTimeAreEqual(certID.getCertHash(), calc.getDigest()))
{
throw new TSPValidationException("certificate hash does not match certID hash.");
}
if (certID.getIssuerSerial() != null)
{
IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(certHolder.toASN1Structure());
if (!certID.getIssuerSerial().getSerial().equals(issuerSerial.getSerialNumber()))
{
throw new TSPValidationException("certificate serial number does not match certID for signature.");
}
GeneralName[] names = certID.getIssuerSerial().getIssuer().getNames();
boolean found = false;
for (int i = 0; i != names.length; i++)
{
if (names[i].getTagNo() == 4 && X500Name.getInstance(names[i].getName()).equals(X500Name.getInstance(issuerSerial.getName())))
{
found = true;
break;
}
}
if (!found)
{
throw new TSPValidationException("certificate name does not match certID for signature. ");
}
}
TSPUtil.validateCertificate(certHolder);
if (!certHolder.isValidOn(tstInfo.getGenTime()))
{
throw new TSPValidationException("certificate not valid when time stamp created.");
}
if (!tsaSignerInfo.verify(sigVerifier))
{
throw new TSPValidationException("signature not created by certificate.");
}
}
catch (CMSException e)
{
if (e.getUnderlyingException() != null)
{
throw new TSPException(e.getMessage(), e.getUnderlyingException());
}
else
{
throw new TSPException("CMS exception: " + e, e);
}
}
catch (IOException e)
{
throw new TSPException("problem processing certificate: " + e, e);
}
catch (OperatorCreationException e)
{
throw new TSPException("unable to create digest: " + e.getMessage(), e);
}
}
/**
* Return true if the signature on time stamp token is valid.
* <p>
* Note: this is a much weaker proof of correctness than calling validate().
* </p>
*
* @param sigVerifier the content verifier create the objects required to verify the CMS object in the timestamp.
* @return true if the signature matches, false otherwise.
* @throws TSPException if the signature cannot be processed or the provider cannot match the algorithm.
*/
public boolean isSignatureValid(
SignerInformationVerifier sigVerifier)
throws TSPException
{
try
{
return tsaSignerInfo.verify(sigVerifier);
}
catch (CMSException e)
{
if (e.getUnderlyingException() != null)
{
throw new TSPException(e.getMessage(), e.getUnderlyingException());
}
else
{
throw new TSPException("CMS exception: " + e, e);
}
}
}
/**
* Return the underlying CMSSignedData object.
*
* @return the underlying CMS structure.
*/
public CMSSignedData toCMSSignedData()
{
return tsToken;
}
/**
* Return a ASN.1 encoded byte stream representing the encoded object.
*
* @throws IOException if encoding fails.
*/
public byte[] getEncoded()
throws IOException
{
return tsToken.getEncoded();
}
// perhaps this should be done using an interface on the ASN.1 classes...
private class CertID
{
private ESSCertID certID;
private ESSCertIDv2 certIDv2;
CertID(ESSCertID certID)
{
this.certID = certID;
this.certIDv2 = null;
}
CertID(ESSCertIDv2 certID)
{
this.certIDv2 = certID;
this.certID = null;
}
public AlgorithmIdentifier getHashAlgorithm()
{
if (certID != null)
{
return new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1);
}
else
{
return certIDv2.getHashAlgorithm();
}
}
public byte[] getCertHash()
{
if (certID != null)
{
return certID.getCertHash();
}
else
{
return certIDv2.getCertHash();
}
}
public IssuerSerial getIssuerSerial()
{
if (certID != null)
{
return certID.getIssuerSerial();
}
else
{
return certIDv2.getIssuerSerial();
}
}
}
} |
package com.intellij.psi.impl;
import com.intellij.lang.ASTNode;
import com.intellij.lang.LighterASTNode;
import com.intellij.lang.LighterASTTokenNode;
import com.intellij.lang.impl.PsiBuilderImpl;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.stubs.ObjectStubSerializer;
import com.intellij.psi.stubs.Stub;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.diff.FlyweightCapableTreeStructure;
import com.intellij.util.graph.InboundSemiGraph;
import com.intellij.util.graph.OutboundSemiGraph;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
@SuppressWarnings({"HardCodedStringLiteral", "UtilityClassWithoutPrivateConstructor", "UnusedDeclaration", "TestOnlyProblems"})
public class DebugUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.DebugUtil");
public static /*final*/ boolean CHECK = false;
public static final boolean DO_EXPENSIVE_CHECKS;
static {
Application application = ApplicationManager.getApplication();
DO_EXPENSIVE_CHECKS = application != null && application.isUnitTestMode();
}
public static final boolean CHECK_INSIDE_ATOMIC_ACTION_ENABLED = DO_EXPENSIVE_CHECKS;
public static String psiTreeToString(@NotNull final PsiElement element, final boolean skipWhitespaces) {
final ASTNode node = SourceTreeToPsiMap.psiElementToTree(element);
assert node != null : element;
return treeToString(node, skipWhitespaces);
}
public static String treeToString(@NotNull final ASTNode root, final boolean skipWhitespaces) {
StringBuilder buffer = new StringBuilder();
treeToBuffer(buffer, root, 0, skipWhitespaces, false, false, true);
return buffer.toString();
}
public static String nodeTreeToString(@NotNull final ASTNode root, final boolean skipWhitespaces) {
StringBuilder buffer = new StringBuilder();
treeToBuffer(buffer, root, 0, skipWhitespaces, false, false, false);
return buffer.toString();
}
public static String treeToString(@NotNull ASTNode root, boolean skipWhitespaces, boolean showRanges) {
StringBuilder buffer = new StringBuilder();
treeToBuffer(buffer, root, 0, skipWhitespaces, showRanges, false, true);
return buffer.toString();
}
public static void treeToBuffer(@NotNull final Appendable buffer,
@NotNull final ASTNode root,
final int indent,
final boolean skipWhiteSpaces,
final boolean showRanges,
final boolean showChildrenRanges,
final boolean usePsi) {
treeToBuffer(buffer, root, indent, skipWhiteSpaces, showRanges, showChildrenRanges, usePsi, null);
}
public static void treeToBuffer(@NotNull final Appendable buffer,
@NotNull final ASTNode root,
final int indent,
final boolean skipWhiteSpaces,
final boolean showRanges,
final boolean showChildrenRanges,
final boolean usePsi,
@Nullable PairConsumer<PsiElement, Consumer<PsiElement>> extra) {
((TreeElement) root).acceptTree(
new TreeToBuffer(buffer, indent, skipWhiteSpaces, showRanges, showChildrenRanges, usePsi, extra));
}
private static class TreeToBuffer extends RecursiveTreeElementWalkingVisitor {
final Appendable buffer;
final boolean skipWhiteSpaces;
final boolean showRanges;
final boolean showChildrenRanges;
final boolean usePsi;
final PairConsumer<PsiElement, Consumer<PsiElement>> extra;
int indent;
TreeToBuffer(Appendable buffer, int indent, boolean skipWhiteSpaces,
boolean showRanges, boolean showChildrenRanges, boolean usePsi,
PairConsumer<PsiElement, Consumer<PsiElement>> extra) {
this.buffer = buffer;
this.skipWhiteSpaces = skipWhiteSpaces;
this.showRanges = showRanges;
this.showChildrenRanges = showChildrenRanges;
this.usePsi = usePsi;
this.extra = extra;
this.indent = indent;
}
@Override
protected void visitNode(TreeElement root) {
if (shouldSkipNode(root)) {
indent += 2;
return;
}
StringUtil.repeatSymbol(buffer, ' ', indent);
try {
if (root instanceof CompositeElement) {
if (usePsi) {
PsiElement psiElement = root.getPsi();
if (psiElement != null) {
buffer.append(psiElement.toString());
}
else {
buffer.append(root.getElementType().toString());
}
}
else {
buffer.append(root.toString());
}
}
else {
final String text = fixWhiteSpaces(root.getText());
buffer.append(root.toString()).append("('").append(text).append("')");
}
if (showRanges) buffer.append(root.getTextRange().toString());
buffer.append("\n");
indent += 2;
if (root instanceof CompositeElement && root.getFirstChildNode() == null) {
StringUtil.repeatSymbol(buffer, ' ', indent);
buffer.append("<empty list>\n");
}
}
catch (IOException e) {
LOG.error(e);
}
super.visitNode(root);
}
protected boolean shouldSkipNode(TreeElement node) {
return skipWhiteSpaces && node.getElementType() == TokenType.WHITE_SPACE;
}
@Override
protected void elementFinished(@NotNull ASTNode e) {
PsiElement psiElement = extra != null && usePsi && e instanceof CompositeElement ? e.getPsi() : null;
if (psiElement != null) {
extra.consume(psiElement, element ->
treeToBuffer(buffer, element.getNode(), indent, skipWhiteSpaces, showRanges, showChildrenRanges, true, null));
}
indent -= 2;
}
}
public static String lightTreeToString(@NotNull final FlyweightCapableTreeStructure<LighterASTNode> tree,
final boolean skipWhitespaces) {
final StringBuilder buffer = new StringBuilder();
lightTreeToBuffer(tree, tree.getRoot(), buffer, 0, skipWhitespaces);
return buffer.toString();
}
public static void lightTreeToBuffer(@NotNull final FlyweightCapableTreeStructure<LighterASTNode> tree,
@NotNull final LighterASTNode node,
@NotNull final Appendable buffer,
final int indent,
final boolean skipWhiteSpaces) {
final IElementType tokenType = node.getTokenType();
if (skipWhiteSpaces && tokenType == TokenType.WHITE_SPACE) return;
final boolean isLeaf = (node instanceof LighterASTTokenNode);
StringUtil.repeatSymbol(buffer, ' ', indent);
try {
if (tokenType == TokenType.ERROR_ELEMENT) {
buffer.append("PsiErrorElement:").append(PsiBuilderImpl.getErrorMessage(node));
}
else if (tokenType == TokenType.WHITE_SPACE) {
buffer.append("PsiWhiteSpace");
}
else {
buffer.append(isLeaf ? "PsiElement" : "Element").append('(').append(tokenType.toString()).append(')');
}
if (isLeaf) {
final String text = ((LighterASTTokenNode)node).getText().toString();
buffer.append("('").append(fixWhiteSpaces(text)).append("')");
}
buffer.append('\n');
if (!isLeaf) {
final Ref<LighterASTNode[]> kids = new Ref<>();
final int numKids = tree.getChildren(node, kids);
if (numKids == 0) {
StringUtil.repeatSymbol(buffer, ' ', indent + 2);
buffer.append("<empty list>\n");
}
else {
for (int i = 0; i < numKids; i++) {
lightTreeToBuffer(tree, kids.get()[i], buffer, indent + 2, skipWhiteSpaces);
}
}
}
}
catch (IOException e) {
LOG.error(e);
}
}
public static String stubTreeToString(final Stub root) {
StringBuilder builder = new StringBuilder();
stubTreeToBuffer(root, builder, 0);
return builder.toString();
}
public static void stubTreeToBuffer(final Stub node, final Appendable buffer, final int indent) {
StringUtil.repeatSymbol(buffer, ' ', indent);
try {
final ObjectStubSerializer stubType = node.getStubType();
if (stubType != null) {
buffer.append(stubType.toString()).append(':');
}
buffer.append(node.toString()).append('\n');
@SuppressWarnings({"unchecked"})
final List<? extends Stub> children = node.getChildrenStubs();
for (final Stub child : children) {
stubTreeToBuffer(child, buffer, indent + 2);
}
}
catch (IOException e) {
LOG.error(e);
}
}
private static void treeToBufferWithUserData(Appendable buffer, TreeElement root, int indent, boolean skipWhiteSpaces) {
if (skipWhiteSpaces && root.getElementType() == TokenType.WHITE_SPACE) return;
StringUtil.repeatSymbol(buffer, ' ', indent);
try {
final PsiElement psi = SourceTreeToPsiMap.treeElementToPsi(root);
assert psi != null : root;
if (root instanceof CompositeElement) {
buffer.append(psi.toString());
}
else {
final String text = fixWhiteSpaces(root.getText());
buffer.append(root.toString()).append("('").append(text).append("')");
}
buffer.append(root.getUserDataString());
buffer.append("\n");
if (root instanceof CompositeElement) {
PsiElement[] children = psi.getChildren();
for (PsiElement child : children) {
treeToBufferWithUserData(buffer, (TreeElement)SourceTreeToPsiMap.psiElementToTree(child), indent + 2, skipWhiteSpaces);
}
if (children.length == 0) {
StringUtil.repeatSymbol(buffer, ' ', indent + 2);
buffer.append("<empty list>\n");
}
}
}
catch (IOException e) {
LOG.error(e);
}
}
private static void treeToBufferWithUserData(Appendable buffer, PsiElement root, int indent, boolean skipWhiteSpaces) {
if (skipWhiteSpaces && root instanceof PsiWhiteSpace) return;
StringUtil.repeatSymbol(buffer, ' ', indent);
try {
if (root instanceof CompositeElement) {
buffer.append(root.toString());
}
else {
final String text = fixWhiteSpaces(root.getText());
buffer.append(root.toString()).append("('").append(text).append("')");
}
buffer.append(((UserDataHolderBase)root).getUserDataString());
buffer.append("\n");
PsiElement[] children = root.getChildren();
for (PsiElement child : children) {
treeToBufferWithUserData(buffer, child, indent + 2, skipWhiteSpaces);
}
if (children.length == 0) {
StringUtil.repeatSymbol(buffer, ' ', indent + 2);
buffer.append("<empty list>\n");
}
}
catch (IOException e) {
LOG.error(e);
}
}
public static void doCheckTreeStructure(@Nullable ASTNode anyElement) {
if (anyElement == null) return;
ASTNode root = anyElement;
while (root.getTreeParent() != null) {
root = root.getTreeParent();
}
if (root instanceof CompositeElement) {
checkSubtree((CompositeElement)root);
}
}
private static void checkSubtree(CompositeElement root) {
if (root.rawFirstChild() == null) {
if (root.rawLastChild() != null) {
throw new IncorrectTreeStructureException(root, "firstChild == null, but lastChild != null");
}
}
else {
for (ASTNode child = root.getFirstChildNode(); child != null; child = child.getTreeNext()) {
if (child instanceof CompositeElement) {
checkSubtree((CompositeElement)child);
}
if (child.getTreeParent() != root) {
throw new IncorrectTreeStructureException(child, "child has wrong parent value");
}
if (child == root.getFirstChildNode()) {
if (child.getTreePrev() != null) {
throw new IncorrectTreeStructureException(root, "firstChild.prev != null");
}
}
else {
if (child.getTreePrev() == null) {
throw new IncorrectTreeStructureException(child, "not first child has prev == null");
}
if (child.getTreePrev().getTreeNext() != child) {
throw new IncorrectTreeStructureException(child, "element.prev.next != element");
}
}
if (child.getTreeNext() == null) {
if (root.getLastChildNode() != child) {
throw new IncorrectTreeStructureException(child, "not last child has next == null");
}
}
}
}
}
public static void checkParentChildConsistent(@NotNull ASTNode element) {
ASTNode treeParent = element.getTreeParent();
if (treeParent == null) return;
ASTNode[] elements = treeParent.getChildren(null);
if (ArrayUtil.find(elements, element) == -1) {
throw new IncorrectTreeStructureException(element, "child cannot be found among parents children");
}
//LOG.debug("checked consistence: "+System.identityHashCode(element));
}
public static void checkSameCharTabs(@NotNull ASTNode element1, @NotNull ASTNode element2) {
final CharTable fromCharTab = SharedImplUtil.findCharTableByTree(element1);
final CharTable toCharTab = SharedImplUtil.findCharTableByTree(element2);
LOG.assertTrue(fromCharTab == toCharTab);
}
public static String psiToString(@NotNull PsiElement element, final boolean skipWhitespaces) {
return psiToString(element, skipWhitespaces, false);
}
public static String psiToString(@NotNull final PsiElement root, final boolean skipWhiteSpaces, final boolean showRanges) {
return psiToString(root, skipWhiteSpaces, showRanges, null);
}
public static String psiToString(@NotNull final PsiElement root, final boolean skipWhiteSpaces, final boolean showRanges, PairConsumer<PsiElement, Consumer<PsiElement>> extra) {
StringBuilder buffer = new StringBuilder();
psiToBuffer(buffer, root, skipWhiteSpaces, showRanges, extra);
return buffer.toString();
}
@NotNull
public static String psiToStringIgnoringNonCode(@NotNull PsiElement element) {
StringBuilder buffer = new StringBuilder();
((TreeElement)element.getNode()).acceptTree(
new TreeToBuffer(buffer, 0, true, false, false, true, null) {
@Override
protected boolean shouldSkipNode(TreeElement node) {
return super.shouldSkipNode(node) || node instanceof PsiErrorElement || node instanceof PsiComment ||
node instanceof LeafPsiElement && StringUtil.isEmptyOrSpaces(node.getText());
}
});
return buffer.toString();
}
private static void psiToBuffer(final Appendable buffer,
final PsiElement root,
final boolean skipWhiteSpaces,
final boolean showRanges,
PairConsumer<PsiElement, Consumer<PsiElement>> extra) {
final ASTNode node = root.getNode();
if (node == null) {
psiToBuffer(buffer, root, 0, skipWhiteSpaces, showRanges, showRanges, extra);
}
else {
treeToBuffer(buffer, node, 0, skipWhiteSpaces, showRanges, showRanges, true, extra);
}
}
public static void psiToBuffer(@NotNull final Appendable buffer,
@NotNull final PsiElement root,
int indent,
boolean skipWhiteSpaces,
boolean showRanges,
boolean showChildrenRanges) {
psiToBuffer(buffer, root, indent, skipWhiteSpaces, showRanges, showChildrenRanges, null);
}
public static void psiToBuffer(@NotNull final Appendable buffer,
@NotNull final PsiElement root,
final int indent,
final boolean skipWhiteSpaces,
boolean showRanges,
final boolean showChildrenRanges,
PairConsumer<PsiElement, Consumer<PsiElement>> extra) {
if (skipWhiteSpaces && root instanceof PsiWhiteSpace) return;
StringUtil.repeatSymbol(buffer, ' ', indent);
try {
buffer.append(root.toString());
PsiElement child = root.getFirstChild();
if (child == null) {
final String text = root.getText();
assert text != null : "text is null for <" + root + ">";
buffer.append("('").append(fixWhiteSpaces(text)).append("')");
}
if (showRanges) buffer.append(root.getTextRange().toString());
buffer.append("\n");
while (child != null) {
psiToBuffer(buffer, child, indent + 2, skipWhiteSpaces, showChildrenRanges, showChildrenRanges, extra);
child = child.getNextSibling();
}
if (extra != null) {
extra.consume(root,
element -> psiToBuffer(buffer, element, indent + 2, skipWhiteSpaces, showChildrenRanges, showChildrenRanges, null));
}
}
catch (IOException e) {
LOG.error(e);
}
}
public static String fixWhiteSpaces(String text) {
text = StringUtil.replace(text, "\n", "\\n");
text = StringUtil.replace(text, "\r", "\\r");
text = StringUtil.replace(text, "\t", "\\t");
return text;
}
public static String currentStackTrace() {
return ExceptionUtil.currentStackTrace();
}
public static class IncorrectTreeStructureException extends RuntimeException {
private final ASTNode myElement;
public IncorrectTreeStructureException(ASTNode element, String message) {
super(message);
myElement = element;
}
public ASTNode getElement() {
return myElement;
}
}
private static final ThreadLocal<Object> ourPsiModificationTrace = new ThreadLocal<>();
private static final ThreadLocal<Integer> ourPsiModificationDepth = new ThreadLocal<>();
private static final Set<Integer> ourNonTransactedTraces = ContainerUtil.newConcurrentSet();
/**
* Marks a start of PSI modification action. Any PSI/AST elements invalidated inside such an action will contain a debug trace
* identifying this transaction, and so will {@link PsiInvalidElementAccessException} thrown when accessing such invalid
* elements. This should help finding out why a specific PSI element has become invalid.
*
* @param trace The debug trace that the invalidated elements should be identified by. May be null, then current stack trace is used.
* @deprecated use {@link #performPsiModification(String, ThrowableRunnable)} instead
*/
public static void startPsiModification(@Nullable String trace) {
if (!PsiInvalidElementAccessException.isTrackingInvalidation()) {
return;
}
//noinspection ThrowableResultOfMethodCallIgnored
if (ourPsiModificationTrace.get() == null) {
ourPsiModificationTrace.set(trace != null ? trace : new Throwable());
}
Integer depth = ourPsiModificationDepth.get();
if (depth == null) depth = 0;
ourPsiModificationDepth.set(depth + 1);
}
/**
* Finished PSI modification action.
* @see #startPsiModification(String)
* @deprecated use {@link #performPsiModification(String, ThrowableRunnable)} instead
*/
public static void finishPsiModification() {
if (!PsiInvalidElementAccessException.isTrackingInvalidation()) {
return;
}
Integer depth = ourPsiModificationDepth.get();
if (depth == null) {
LOG.warn("Unmatched PSI modification end", new Throwable());
depth = 0;
} else {
depth
ourPsiModificationDepth.set(depth);
}
if (depth == 0) {
ourPsiModificationTrace.set(null);
}
}
public static <T extends Throwable> void performPsiModification(String trace, @NotNull ThrowableRunnable<T> runnable) throws T {
startPsiModification(trace);
try {
runnable.run();
}
finally {
finishPsiModification();
}
}
public static <T, E extends Throwable> T performPsiModification(String trace, @NotNull ThrowableComputable<T, E> runnable) throws E {
startPsiModification(trace);
try {
return runnable.compute();
}
finally {
finishPsiModification();
}
}
public static void onInvalidated(@NotNull ASTNode treeElement) {
Object trace = calcInvalidationTrace(treeElement);
if (trace != null) {
PsiInvalidElementAccessException.setInvalidationTrace(treeElement, trace);
}
}
public static void onInvalidated(@NotNull PsiElement o) {
Object trace = PsiInvalidElementAccessException.getInvalidationTrace(o);
if (trace != null) return;
PsiInvalidElementAccessException.setInvalidationTrace(o, currentInvalidationTrace());
}
public static void onInvalidated(@NotNull FileViewProvider provider) {
Object trace = calcInvalidationTrace(null);
if (trace != null) {
PsiInvalidElementAccessException.setInvalidationTrace(provider, trace);
}
}
@Nullable
private static Object calcInvalidationTrace(@Nullable ASTNode treeElement) {
if (!PsiInvalidElementAccessException.isTrackingInvalidation()) {
return null;
}
if (PsiInvalidElementAccessException.findInvalidationTrace(treeElement) != null) {
return null;
}
return currentInvalidationTrace();
}
@NotNull
private static Object currentInvalidationTrace() {
Object trace = ourPsiModificationTrace.get();
if (trace == null) {
trace = new Throwable();
if (ourNonTransactedTraces.add(ExceptionUtil.getThrowableText((Throwable)trace).hashCode())) {
LOG.info("PSI invalidated outside transaction", (Throwable)trace);
}
}
return trace;
}
public static void revalidateNode(@NotNull ASTNode element) {
PsiInvalidElementAccessException.setInvalidationTrace(element, null);
}
public static void sleep(long millis) {
TimeoutUtil.sleep(millis);
}
public static void checkTreeStructure(ASTNode element) {
if (CHECK){
doCheckTreeStructure(element);
}
}
@NotNull
public static String diagnosePsiDocumentInconsistency(@NotNull PsiElement element, @NotNull Document document) {
PsiUtilCore.ensureValid(element);
PsiFile file = element.getContainingFile();
if (file == null) return "no file for " + element + " of " + element.getClass();
PsiUtilCore.ensureValid(file);
FileViewProvider viewProvider = file.getViewProvider();
PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject());
Document actualDocument = manager.getDocument(file);
String fileDiagnostics = "File[" + file + " " + file.getName() + ", " + file.getLanguage() + ", " + viewProvider + "]";
if (actualDocument != document) {
return "wrong document for " + fileDiagnostics + "; expected " + document + "; actual " + actualDocument;
}
PsiFile cachedPsiFile = manager.getCachedPsiFile(document);
FileViewProvider actualViewProvider = cachedPsiFile == null ? null : cachedPsiFile.getViewProvider();
if (actualViewProvider != viewProvider) {
return "wrong view provider for " + document + ", expected " + viewProvider + "; actual " + actualViewProvider;
}
if (!manager.isCommitted(document)) return "not committed document " + document + ", " + fileDiagnostics;
int fileLength = file.getTextLength();
int docLength = document.getTextLength();
if (fileLength != docLength) {
return "file/doc text length different, " + fileDiagnostics + " file.length=" + fileLength + "; doc.length=" + docLength;
}
return "unknown inconsistency in " + fileDiagnostics;
}
public static <T> String graphToString(InboundSemiGraph<T> graph) {
StringBuilder buffer = new StringBuilder();
printNodes(graph.getNodes().iterator(), node -> graph.getIn(node), 0, new HashSet<>(), buffer);
return buffer.toString();
}
public static <T> String graphToString(OutboundSemiGraph<T> graph) {
StringBuilder buffer = new StringBuilder();
printNodes(graph.getNodes().iterator(), node -> graph.getOut(node), 0, new HashSet<>(), buffer);
return buffer.toString();
}
private static <T> void printNodes(Iterator<T> nodes, Function<T, Iterator<T>> getter, int indent, Set<T> visited, StringBuilder buffer) {
while (nodes.hasNext()) {
T node = nodes.next();
StringUtil.repeatSymbol(buffer, ' ', indent);
buffer.append(node);
if (visited.add(node)) {
buffer.append('\n');
printNodes(getter.fun(node), getter, indent + 2, visited, buffer);
}
else {
buffer.append(" [...]\n");
}
}
}
} |
package com.intellij.util;
import com.intellij.execution.configurations.PathEnvironmentVariableUtil;
import com.intellij.execution.process.UnixProcessManager;
import com.intellij.execution.process.WinProcessManager;
import com.intellij.ide.actions.CreateDesktopEntryAction;
import com.intellij.jna.JnaLoader;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.AtomicNotNullLazyValue;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.StdCallLibrary;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Restarter {
private Restarter() { }
public static boolean isSupported() {
return ourRestartSupported.getValue();
}
private static final NotNullLazyValue<Boolean> ourRestartSupported = new AtomicNotNullLazyValue<Boolean>() {
@NotNull
@Override
protected Boolean compute() {
String problem;
if (SystemInfo.isWindows) {
if (!JnaLoader.isLoaded()) {
problem = "JNA not loaded";
}
else {
problem = checkRestarter("restarter.exe");
}
}
else if (SystemInfo.isMac) {
if (getMacOsAppDir() == null) {
problem = "not a bundle: " + PathManager.getHomePath();
}
else {
problem = checkRestarter("restarter");
}
}
else if (SystemInfo.isUnix) {
if (UnixProcessManager.getCurrentProcessId() <= 0) {
problem = "cannot detect process ID";
}
else if (CreateDesktopEntryAction.getLauncherScript() == null) {
problem = "cannot find launcher script in " + PathManager.getBinPath();
}
else if (PathEnvironmentVariableUtil.findInPath("python") == null && PathEnvironmentVariableUtil.findInPath("python3") == null) {
problem = "cannot find neither 'python' nor 'python3' in PATH";
}
else {
problem = checkRestarter("restart.py");
}
}
else {
problem = "unknown platform: " + SystemInfo.OS_NAME;
}
if (problem == null) {
return true;
}
else {
Logger.getInstance(Restarter.class).info("not supported: " + problem);
return false;
}
}
};
private static String checkRestarter(String restarterName) {
File restarter = PathManager.findBinFile(restarterName);
return restarter != null && restarter.isFile() && restarter.canExecute() ? null : "not an executable file: " + restarter;
}
public static void scheduleRestart(@NotNull String... beforeRestart) throws IOException {
scheduleRestart(false, beforeRestart);
}
public static void scheduleRestart(boolean elevate, @NotNull String... beforeRestart) throws IOException {
Logger.getInstance(Restarter.class).info("restart: " + Arrays.toString(beforeRestart));
if (SystemInfo.isWindows) {
restartOnWindows(elevate, beforeRestart);
}
else if (SystemInfo.isMac) {
restartOnMac(beforeRestart);
}
else if (SystemInfo.isUnix) {
restartOnUnix(beforeRestart);
}
else {
throw new IOException("Cannot restart application: not supported.");
}
}
private static void restartOnWindows(boolean elevate, String... beforeRestart) throws IOException {
Kernel32 kernel32 = Native.loadLibrary("kernel32", Kernel32.class);
Shell32 shell32 = Native.loadLibrary("shell32", Shell32.class);
int pid = WinProcessManager.getCurrentProcessId();
IntByReference argc = new IntByReference();
Pointer argvPtr = shell32.CommandLineToArgvW(kernel32.GetCommandLineW(), argc);
String[] argv = getRestartArgv(argvPtr.getWideStringArray(0, argc.getValue()));
kernel32.LocalFree(argvPtr);
// argv[0] as the program name is only a convention, i.e. there is no guarantee
// the name is the full path to the executable.
// To retrieve the full path to the executable, use "GetModuleFileName(NULL, ...)".
// Note: We use 32,767 as buffer size to avoid limiting ourselves to MAX_PATH (260).
char[] buffer = new char[32767];
if (kernel32.GetModuleFileNameW(null, buffer, new WinDef.DWORD(buffer.length)).intValue() > 0) {
argv[0] = Native.toString(buffer);
}
ArrayList<String> args = new ArrayList<>();
args.add(String.valueOf(pid));
args.add(String.valueOf(beforeRestart.length));
Collections.addAll(args, beforeRestart);
if (elevate) {
File launcher = PathManager.findBinFile("launcher.exe");
if (launcher != null) {
args.add(String.valueOf(argv.length + 1));
args.add(launcher.getPath());
}
else {
args.add(String.valueOf(argv.length));
}
}
else {
args.add(String.valueOf(argv.length));
}
Collections.addAll(args, argv);
File restarter = PathManager.findBinFile("restarter.exe");
if (restarter == null) {
throw new IOException("Can't find restarter.exe; please reinstall the IDE");
}
runRestarter(restarter, args);
// Since the process ID is passed through the command line, we want to make sure that we don't exit before the "restarter"
// process has a chance to open the handle to our process, and that it doesn't wait for the termination of an unrelated
// process which happened to have the same process ID.
TimeoutUtil.sleep(500);
}
private static String[] getRestartArgv(String[] argv) {
String mainClass = System.getProperty("idea.main.class.name", "com.intellij.idea.Main");
int countArgs = argv.length;
for (int i = argv.length-1; i >=0; i
if (argv[i].equals(mainClass) || argv[i].endsWith(".exe")) {
countArgs = i + 1;
if (argv[i].endsWith(".exe") && argv[i].indexOf(File.separatorChar) < 0) {
//absolute path
argv[i] = new File(PathManager.getBinPath(), argv[i]).getPath();
}
break;
}
}
String[] restartArg = new String[countArgs];
System.arraycopy(argv, 0, restartArg, 0, countArgs);
return restartArg;
}
private static void restartOnMac(String... beforeRestart) throws IOException {
File appDir = getMacOsAppDir();
if (appDir == null) throw new IOException("Application bundle not found: " + PathManager.getHomePath());
List<String> args = new ArrayList<>();
args.add(appDir.getPath());
Collections.addAll(args, beforeRestart);
runRestarter(new File(PathManager.getBinPath(), "restarter"), args);
}
private static File getMacOsAppDir() {
File appDir = new File(PathManager.getHomePath()).getParentFile();
return appDir != null && appDir.getName().endsWith(".app") && appDir.isDirectory() ? appDir : null;
}
private static void restartOnUnix(String... beforeRestart) throws IOException {
String launcherScript = CreateDesktopEntryAction.getLauncherScript();
if (launcherScript == null) throw new IOException("Launcher script not found in " + PathManager.getBinPath());
int pid = UnixProcessManager.getCurrentProcessId();
if (pid <= 0) throw new IOException("Invalid process ID: " + pid);
File python = PathEnvironmentVariableUtil.findInPath("python");
if (python == null) python = PathEnvironmentVariableUtil.findInPath("python3");
if (python == null) throw new IOException("Cannot find neither 'python' nor 'python3' in PATH");
File script = new File(PathManager.getBinPath(), "restart.py");
List<String> args = new ArrayList<>();
if ("python".equals(python.getName())) {
args.add(String.valueOf(pid));
args.add(launcherScript);
Collections.addAll(args, beforeRestart);
runRestarter(script, args);
}
else {
args.add(script.getPath());
args.add(String.valueOf(pid));
args.add(launcherScript);
Collections.addAll(args, beforeRestart);
runRestarter(python, args);
}
}
private static void runRestarter(File restarterFile, List<String> restarterArgs) throws IOException {
restarterArgs.add(0, createTempExecutable(restarterFile).getPath());
Runtime.getRuntime().exec(ArrayUtil.toStringArray(restarterArgs));
}
@NotNull
public static File createTempExecutable(@NotNull File executable) throws IOException {
File tempDir = new File(PathManager.getSystemPath(), "restart");
if (!FileUtilRt.createDirectory(tempDir)) {
throw new IOException("Cannot create directory: " + tempDir);
}
File copy = new File(tempDir, executable.getName());
if (!FileUtilRt.ensureCanCreateFile(copy) || (copy.exists() && !copy.delete())) {
String prefix = FileUtilRt.getNameWithoutExtension(copy.getName());
String ext = FileUtilRt.getExtension(executable.getName());
String suffix = StringUtil.isEmptyOrSpaces(ext) ? ".tmp" : ("." + ext);
copy = FileUtilRt.createTempFile(tempDir, prefix, suffix, true, false);
}
FileUtilRt.copy(executable, copy);
if (executable.canExecute() && !copy.setExecutable(true)) {
throw new IOException("Cannot make file executable: " + copy);
}
return copy;
}
@SuppressWarnings({"SameParameterValue", "UnusedReturnValue"})
private interface Kernel32 extends StdCallLibrary {
WString GetCommandLineW();
Pointer LocalFree(Pointer pointer);
WinDef.DWORD GetModuleFileNameW(WinDef.HMODULE hModule, char[] lpFilename, WinDef.DWORD nSize);
}
private interface Shell32 extends StdCallLibrary {
Pointer CommandLineToArgvW(WString command_line, IntByReference argc);
}
} |
package com.intellij.openapi.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.registry.RegistryValue;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.reference.SoftReference;
import com.intellij.ui.RetrievableIcon;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.ImageLoader;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.RetinaImage;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.ImageUtil;
import com.intellij.util.ui.JBImageIcon;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.JBUI.BaseScaleContext.UpdateListener;
import com.intellij.util.ui.JBUI.RasterJBIcon;
import com.intellij.util.ui.JBUI.ScaleContext;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageFilter;
import java.awt.image.RGBImageFilter;
import java.lang.ref.Reference;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import static com.intellij.util.ui.JBUI.ScaleType.*;
public final class IconLoader {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.IconLoader");
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private static final ConcurrentMap<URL, CachedImageIcon> ourIconsCache = ContainerUtil.newConcurrentMap(100, 0.9f, 2);
/**
* This cache contains mapping between icons and disabled icons.
*/
private static final Map<Icon, Icon> ourIcon2DisabledIcon = ContainerUtil.createWeakMap(200);
@NonNls private static final List<IconPathPatcher> ourPatchers = new ArrayList<IconPathPatcher>(2);
public static boolean STRICT;
private static boolean USE_DARK_ICONS = UIUtil.isUnderDarcula();
private static ImageFilter IMAGE_FILTER;
private volatile static int clearCacheCounter;
static {
installPathPatcher(new DeprecatedDuplicatesIconPathPatcher());
}
private static final ImageIcon EMPTY_ICON = new ImageIcon(UIUtil.createImage(1, 1, BufferedImage.TYPE_3BYTE_BGR)) {
@NonNls
public String toString() {
return "Empty icon " + super.toString();
}
};
private static boolean ourIsActivated;
private IconLoader() { }
public static void installPathPatcher(@NotNull IconPathPatcher patcher) {
ourPatchers.add(patcher);
clearCache();
}
@Deprecated
@NotNull
public static Icon getIcon(@NotNull final Image image) {
return new JBImageIcon(image);
}
public static void setUseDarkIcons(boolean useDarkIcons) {
USE_DARK_ICONS = useDarkIcons;
clearCache();
}
public static void setFilter(ImageFilter filter) {
if (IMAGE_FILTER != filter) {
IMAGE_FILTER = filter;
clearCache();
}
}
public static void clearCache() {
ourIconsCache.clear();
ourIcon2DisabledIcon.clear();
clearCacheCounter++;
}
//TODO[kb] support iconsets
//public static Icon getIcon(@NotNull final String path, @NotNull final String darkVariantPath) {
// return new InvariantIcon(getIcon(path), getIcon(darkVariantPath));
@NotNull
public static Icon getIcon(@NonNls @NotNull final String path) {
Class callerClass = ReflectionUtil.getGrandCallerClass();
assert callerClass != null : path;
return getIcon(path, callerClass);
}
@Nullable
private static Icon getReflectiveIcon(@NotNull String path, ClassLoader classLoader) {
try {
@NonNls String pckg = path.startsWith("AllIcons.") ? "com.intellij.icons." : "icons.";
Class cur = Class.forName(pckg + path.substring(0, path.lastIndexOf('.')).replace('.', '$'), true, classLoader);
Field field = cur.getField(path.substring(path.lastIndexOf('.') + 1));
return (Icon)field.get(null);
}
catch (Exception e) {
return null;
}
}
/**
* Might return null if icon was not found.
* Use only if you expected null return value, otherwise see {@link IconLoader#getIcon(String)}
*/
@Nullable
public static Icon findIcon(@NonNls @NotNull String path) {
Class callerClass = ReflectionUtil.getGrandCallerClass();
if (callerClass == null) return null;
return findIcon(path, callerClass);
}
@Nullable
public static Icon findIcon(@NonNls @NotNull String path, boolean strict) {
Class callerClass = ReflectionUtil.getGrandCallerClass();
if (callerClass == null) return null;
return findIcon(path, callerClass, false, strict);
}
@NotNull
public static Icon getIcon(@NotNull String path, @NotNull final Class aClass) {
final Icon icon = findIcon(path, aClass);
if (icon == null) {
LOG.error("Icon cannot be found in '" + path + "', aClass='" + aClass + "'");
}
return icon;
}
public static void activate() {
ourIsActivated = true;
}
private static boolean isLoaderDisabled() {
return !ourIsActivated;
}
/**
* Might return null if icon was not found.
* Use only if you expected null return value, otherwise see {@link IconLoader#getIcon(String, Class)}
*/
@Nullable
public static Icon findIcon(@NotNull final String path, @NotNull final Class aClass) {
return findIcon(path, aClass, false);
}
@Nullable
public static Icon findIcon(@NotNull String path, @NotNull final Class aClass, boolean computeNow) {
return findIcon(path, aClass, computeNow, STRICT);
}
@Nullable
public static Icon findIcon(@NotNull String path, @NotNull Class aClass, boolean computeNow, boolean strict) {
String originalPath = path;
Pair<String, Class> patchedPath = patchPath(path);
path = patchedPath.first;
if (patchedPath.second != null) {
aClass = patchedPath.second;
}
if (isReflectivePath(path)) return getReflectiveIcon(path, aClass.getClassLoader());
URL myURL = findURL(path, aClass);
if (myURL == null) {
if (strict) throw new RuntimeException("Can't find icon in '" + path + "' near " + aClass);
return null;
}
final Icon icon = findIcon(myURL);
if (icon instanceof CachedImageIcon) {
((CachedImageIcon)icon).myOriginalPath = originalPath;
((CachedImageIcon)icon).myClassLoader = aClass.getClassLoader();
}
return icon;
}
@NotNull
private static Pair<String, Class> patchPath(@NotNull String path) {
for (IconPathPatcher patcher : ourPatchers) {
String newPath = patcher.patchPath(path);
if (newPath != null) {
LOG.info("replace '" + path + "' with '" + newPath + "'");
return Pair.create(newPath, patcher.getContextClass(path));
}
}
return Pair.create(path, null);
}
private static boolean isReflectivePath(@NotNull String path) {
List<String> paths = StringUtil.split(path, ".");
return paths.size() > 1 && paths.get(0).endsWith("Icons");
}
@Nullable
private static URL findURL(@NotNull String path, @Nullable Object context) {
URL url;
if (context instanceof Class) {
url = ((Class)context).getResource(path);
}
else if (context instanceof ClassLoader) {
url = ((ClassLoader)context).getResource(path);
}
else {
LOG.warn("unexpected: " + context);
return null;
}
// Find either PNG or SVG icon. The icon will then be wrapped into CachedImageIcon
// which will load proper icon version depending on the context - UI theme, DPI.
// SVG version, when present, has more priority than PNG.
// See for details: com.intellij.util.ImageLoader.ImageDescList#create
if (url != null || !path.endsWith(".png")) return url;
url = findURL(path.substring(0, path.length() - 4) + ".svg", context);
if (url != null) LOG.info("replace '" + path + "' with '" + url + "'");
return url;
}
@Nullable
public static Icon findIcon(URL url) {
return findIcon(url, true);
}
@Nullable
public static Icon findIcon(URL url, boolean useCache) {
if (url == null) {
return null;
}
CachedImageIcon icon = ourIconsCache.get(url);
if (icon == null) {
icon = new CachedImageIcon(url, useCache);
if (useCache) {
icon = ConcurrencyUtil.cacheOrGet(ourIconsCache, url, icon);
}
}
return icon;
}
@Nullable
public static Icon findIcon(@NotNull String path, @NotNull ClassLoader classLoader) {
String originalPath = path;
Pair<String, Class> patchedPath = patchPath(path);
path = patchedPath.first;
if (patchedPath.second != null) {
classLoader = patchedPath.second.getClassLoader();
}
if (isReflectivePath(path)) return getReflectiveIcon(path, classLoader);
if (!StringUtil.startsWithChar(path, '/')) return null;
final URL url = findURL(path.substring(1), classLoader);
final Icon icon = findIcon(url);
if (icon instanceof CachedImageIcon) {
((CachedImageIcon)icon).myOriginalPath = originalPath;
((CachedImageIcon)icon).myClassLoader = classLoader;
}
return icon;
}
@Nullable
public static Image toImage(@NotNull Icon icon) {
if (icon instanceof CachedImageIcon) {
icon = ((CachedImageIcon)icon).getRealIcon();
}
if (icon instanceof ImageIcon) {
return ((ImageIcon)icon).getImage();
}
else {
final int w = icon.getIconWidth();
final int h = icon.getIconHeight();
final BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
final Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
@Nullable
private static ImageIcon checkIcon(final Image image, @NotNull URL url) {
if (image == null || image.getHeight(null) < 1) { // image wasn't loaded or broken
return null;
}
final Icon icon = getIcon(image);
if (!isGoodSize(icon)) {
LOG.error("Invalid icon: " + url); // # 22481
return EMPTY_ICON;
}
assert icon instanceof ImageIcon;
return (ImageIcon)icon;
}
public static boolean isGoodSize(@NotNull final Icon icon) {
return icon.getIconWidth() > 0 && icon.getIconHeight() > 0;
}
/**
* Gets (creates if necessary) disabled icon based on the passed one.
*
* @return {@code ImageIcon} constructed from disabled image of passed icon.
*/
@Nullable
public static Icon getDisabledIcon(Icon icon) {
if (icon instanceof LazyIcon) icon = ((LazyIcon)icon).getOrComputeIcon();
if (icon == null) return null;
Icon disabledIcon = ourIcon2DisabledIcon.get(icon);
if (disabledIcon == null) {
disabledIcon = filterIcon(icon, UIUtil.getGrayFilter(), null); // [tav] todo: lack ancestor
ourIcon2DisabledIcon.put(icon, disabledIcon);
}
return disabledIcon;
}
/**
* Creates new icon with the filter applied.
*/
@Nullable
public static Icon filterIcon(@NotNull Icon icon, RGBImageFilter filter, @Nullable Component ancestor) {
if (icon instanceof LazyIcon) icon = ((LazyIcon)icon).getOrComputeIcon();
if (icon == null) return null;
if (!isGoodSize(icon)) {
LOG.error(icon); // # 22481
return EMPTY_ICON;
}
if (icon instanceof CachedImageIcon) {
icon = ((CachedImageIcon)icon).createWithFilter(filter);
} else {
final float scale;
if (icon instanceof JBUI.ScaleContextAware) {
scale = (float)((JBUI.ScaleContextAware)icon).getScale(SYS_SCALE);
}
else {
scale = UIUtil.isJreHiDPI() ? JBUI.sysScale(ancestor) : 1f;
}
@SuppressWarnings("UndesirableClassUsage")
BufferedImage image = new BufferedImage((int)(scale * icon.getIconWidth()), (int)(scale * icon.getIconHeight()), BufferedImage.TYPE_INT_ARGB);
final Graphics2D graphics = image.createGraphics();
graphics.setColor(UIUtil.TRANSPARENT_COLOR);
graphics.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight());
graphics.scale(scale, scale);
icon.paintIcon(LabelHolder.ourFakeComponent, graphics, 0, 0);
graphics.dispose();
Image img = ImageUtil.filter(image, filter);
if (UIUtil.isJreHiDPI()) img = RetinaImage.createFrom(img, scale, null);
icon = new JBImageIcon(img);
}
return icon;
}
@NotNull
public static Icon getTransparentIcon(@NotNull final Icon icon) {
return getTransparentIcon(icon, 0.5f);
}
@NotNull
public static Icon getTransparentIcon(@NotNull final Icon icon, final float alpha) {
return new RetrievableIcon() {
@Override
public Icon retrieveIcon() {
return icon;
}
@Override
public int getIconHeight() {
return icon.getIconHeight();
}
@Override
public int getIconWidth() {
return icon.getIconWidth();
}
@Override
public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
final Graphics2D g2 = (Graphics2D)g;
final Composite saveComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
icon.paintIcon(c, g2, x, y);
g2.setComposite(saveComposite);
}
};
}
/**
* Gets a snapshot of the icon, immune to changes made by these calls:
* {@link #setFilter(ImageFilter)}, {@link #setUseDarkIcons(boolean)}
*
* @param icon the source icon
* @return the icon snapshot
*/
@NotNull
public static Icon getIconSnapshot(@NotNull Icon icon) {
if (icon instanceof CachedImageIcon) {
return ((CachedImageIcon)icon).getRealIcon();
}
return icon;
}
/**
* For internal usage. Converts the icon to 1x scale when applicable.
*/
public static Icon get1xIcon(Icon icon) {
if (icon instanceof LazyIcon) {
icon = ((LazyIcon)icon).getOrComputeIcon();
}
if (icon instanceof CachedImageIcon) {
Image img = ((CachedImageIcon)icon).loadFromUrl(ScaleContext.createIdentity());
if (img != null) {
icon = new ImageIcon(img);
}
}
return icon;
}
public static final class CachedImageIcon extends RasterJBIcon implements ScalableIcon {
private volatile Object myRealIcon;
private String myOriginalPath;
private ClassLoader myClassLoader;
@NotNull
private URL myUrl;
private volatile boolean dark;
private volatile int numberOfPatchers = ourPatchers.size();
private final boolean useCacheOnLoad;
private int myClearCacheCounter = clearCacheCounter;
private ImageFilter[] myFilters;
private final MyScaledIconsCache myScaledIconsCache = new MyScaledIconsCache();
{
// For instance, ShadowPainter updates the context from outside.
getScaleContext().addUpdateListener(new UpdateListener() {
@Override
public void contextUpdated() {
myRealIcon = null;
}
});
}
private CachedImageIcon(@NotNull CachedImageIcon icon) {
myRealIcon = null; // to be computed
myOriginalPath = icon.myOriginalPath;
myClassLoader = icon.myClassLoader;
myUrl = icon.myUrl;
dark = icon.dark;
numberOfPatchers = icon.numberOfPatchers;
myFilters = icon.myFilters;
useCacheOnLoad = icon.useCacheOnLoad;
}
public CachedImageIcon(@NotNull URL url) {
this(url, true);
}
public CachedImageIcon(@NotNull URL url, boolean useCacheOnLoad) {
myUrl = url;
dark = USE_DARK_ICONS;
myFilters = new ImageFilter[] {IMAGE_FILTER};
this.useCacheOnLoad = useCacheOnLoad;
}
private void setGlobalFilter(ImageFilter globalFilter) {
myFilters[0] = globalFilter;
}
private ImageFilter getGlobalFilter() {
return myFilters[0];
}
@NotNull
private synchronized ImageIcon getRealIcon() {
return getRealIcon(null);
}
@Nullable
@TestOnly
public ImageIcon doGetRealIcon() {
Object icon = myRealIcon;
if (icon instanceof Reference) {
icon = ((Reference<ImageIcon>)icon).get();
}
return icon instanceof ImageIcon ? (ImageIcon)icon : null;
}
@NotNull
private synchronized ImageIcon getRealIcon(@Nullable ScaleContext ctx) {
if (!isValid()) {
if (isLoaderDisabled()) return EMPTY_ICON;
myClearCacheCounter = clearCacheCounter;
myRealIcon = null;
dark = USE_DARK_ICONS;
setGlobalFilter(IMAGE_FILTER);
myScaledIconsCache.clear();
if (numberOfPatchers != ourPatchers.size()) {
numberOfPatchers = ourPatchers.size();
Pair<String, Class> patchedPath = patchPath(myOriginalPath);
String path = myOriginalPath == null ? null : patchedPath.first;
if (patchedPath.second != null) {
myClassLoader = patchedPath.second.getClassLoader();
}
if (myClassLoader != null && path != null && path.startsWith("/")) {
path = path.substring(1);
URL url = findURL(path, myClassLoader);
if (url != null) {
myUrl = url;
}
}
}
}
if (!updateScaleContext(ctx) && myRealIcon != null) {
// try returning the current icon as the context is up-to-date
Object icon = myRealIcon;
if (icon instanceof Reference) icon = ((Reference<ImageIcon>)icon).get();
if (icon instanceof ImageIcon) return (ImageIcon)icon;
}
ImageIcon icon = myScaledIconsCache.getOrScaleIcon(1f);
if (icon != null) {
myRealIcon = icon.getIconWidth() < 50 && icon.getIconHeight() < 50 ? icon : new SoftReference<ImageIcon>(icon);
return icon;
}
return EMPTY_ICON;
}
private boolean isValid() {
return dark == USE_DARK_ICONS &&
getGlobalFilter() == IMAGE_FILTER &&
numberOfPatchers == ourPatchers.size() &&
myClearCacheCounter == clearCacheCounter;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = g instanceof Graphics2D ? (Graphics2D)g : null;
getRealIcon(ScaleContext.create(c, g2d)).paintIcon(c, g, x, y);
}
@Override
public int getIconWidth() {
return getRealIcon().getIconWidth();
}
@Override
public int getIconHeight() {
return getRealIcon().getIconHeight();
}
@Override
public String toString() {
return myUrl.toString();
}
@Override
public float getScale() {
return 1f;
}
@NotNull
@Override
public Icon scale(float scale) {
if (scale == 1f) return this;
getRealIcon(); // force state update & cache reset
Icon icon = myScaledIconsCache.getOrScaleIcon(scale);
if (icon != null) {
return icon;
}
return this;
}
@NotNull
private Icon createWithFilter(@NotNull RGBImageFilter filter) {
CachedImageIcon icon = new CachedImageIcon(this);
icon.myFilters = new ImageFilter[] {getGlobalFilter(), filter};
return icon;
}
private Image loadFromUrl(@NotNull ScaleContext ctx) {
return ImageLoader.loadFromUrl(myUrl, true, useCacheOnLoad, myFilters, ctx);
}
private class MyScaledIconsCache {
private static final int SCALED_ICONS_CACHE_LIMIT = 5;
private final Map<Couple<Double>, SoftReference<ImageIcon>> scaledIconsCache = Collections.synchronizedMap(new LinkedHashMap<Couple<Double>, SoftReference<ImageIcon>>(SCALED_ICONS_CACHE_LIMIT) {
@Override
public boolean removeEldestEntry(Map.Entry<Couple<Double>, SoftReference<ImageIcon>> entry) {
return size() > SCALED_ICONS_CACHE_LIMIT;
}
});
private Couple<Double> key(@NotNull ScaleContext ctx) {
return new Couple<Double>(ctx.getScale(USR_SCALE) * ctx.getScale(OBJ_SCALE), ctx.getScale(SYS_SCALE));
}
/**
* Retrieves the orig icon scaled by the provided scale.
*/
ImageIcon getOrScaleIcon(final float scale) {
ScaleContext ctx = getScaleContext();
if (scale != 1) {
ctx = ctx.copy();
ctx.update(OBJ_SCALE.of(scale));
}
ImageIcon icon = SoftReference.dereference(scaledIconsCache.get(key(ctx)));
if (icon != null) {
return icon;
}
Image image = loadFromUrl(ctx);
icon = checkIcon(image, myUrl);
if (icon != null && icon.getIconWidth() * icon.getIconHeight() * 4 < ImageLoader.CACHED_IMAGE_MAX_SIZE) {
scaledIconsCache.put(key(ctx), new SoftReference<ImageIcon>(icon));
}
return icon;
}
public void clear() {
scaledIconsCache.clear();
}
}
}
public abstract static class LazyIcon extends RasterJBIcon {
private boolean myWasComputed;
private Icon myIcon;
private boolean isDarkVariant = USE_DARK_ICONS;
private int numberOfPatchers = ourPatchers.size();
private ImageFilter filter = IMAGE_FILTER;
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
if (updateScaleContext(ScaleContext.create((Graphics2D)g))) {
myIcon = null;
}
final Icon icon = getOrComputeIcon();
if (icon != null) {
icon.paintIcon(c, g, x, y);
}
}
@Override
public int getIconWidth() {
final Icon icon = getOrComputeIcon();
return icon != null ? icon.getIconWidth() : 0;
}
@Override
public int getIconHeight() {
final Icon icon = getOrComputeIcon();
return icon != null ? icon.getIconHeight() : 0;
}
protected final synchronized Icon getOrComputeIcon() {
if (!myWasComputed || isDarkVariant != USE_DARK_ICONS ||
myIcon == null ||
filter != IMAGE_FILTER || numberOfPatchers != ourPatchers.size())
{
isDarkVariant = USE_DARK_ICONS;
filter = IMAGE_FILTER;
myWasComputed = true;
numberOfPatchers = ourPatchers.size();
myIcon = compute();
}
return myIcon;
}
public final void load() {
getIconWidth();
}
protected abstract Icon compute();
}
private static class LabelHolder {
/**
* To get disabled icon with paint it into the image. Some icons require
* not null component to paint.
*/
private static final JComponent ourFakeComponent = new JLabel();
}
} |
package fi.aalto.tripchain.route;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import fi.aalto.tripchain.here.Address;
import fi.aalto.tripchain.receivers.EventDispatcher;
import android.location.Location;
import android.util.Log;
public class RoadSegment {
private final static String TAG = RoadSegment.class.getSimpleName();
String currentStreetName;
Address latestAddress;
List<Location> locations = new ArrayList<Location>();
List<List<Address>> addressLists = new ArrayList<List<Address>>();
List<Address> currentStreetAddresses = new ArrayList<Address>();
RoadSegment(Location location, List<Address> addresses) {
stillOnTheSameStreet(addresses);
addLocation(location, addresses);
}
private Map<String, Integer> calculateStreetFrequency(List<Address> newAddresses) {
List<List<Address>> addresses = new ArrayList<List<Address>>();
addresses.addAll(addressLists);
addresses.add(newAddresses);
Map<String, Integer> streetFrequency = new HashMap<String, Integer>();
for (List<Address> addressList : addresses) {
Set<String> streetSet = new HashSet<String>();
for (Address a : addressList) {
String street = a.street;
// to not add streets multiple times per one location
if (streetSet.contains(street)) {
continue;
}
streetSet.add(street);
if (streetFrequency.containsKey(street)) {
int f = streetFrequency.get(street);
streetFrequency.put(street, f + 1);
} else {
streetFrequency.put(street, 1);
}
}
}
return streetFrequency;
}
private String checkCommonStreet(Map<String, Integer> frequency, int locations) {
for (String street : frequency.keySet()) {
if (frequency.get(street) == locations) {
return street;
}
}
return null;
}
private void updateStreetAddressList() {
if (this.currentStreetName == null) {
this.currentStreetAddresses = null;
return;
}
List<Address> streetAddresses = new ArrayList<Address>();
for (List<Address> locationAddresses : addressLists) {
for (Address a : locationAddresses) {
if (a.street.equals(currentStreetName)) {
streetAddresses.add(a);
break;
}
}
}
this.currentStreetAddresses = streetAddresses;
this.latestAddress = streetAddresses.get(streetAddresses.size() - 1);
Log.d(TAG, "Current address: " + latestAddress.label);
EventDispatcher.onAddress(latestAddress);
}
boolean stillOnTheSameStreet(List<Address> addresses) {
Map<String, Integer> frequency = calculateStreetFrequency(addresses);
String street = checkCommonStreet(frequency, this.locations.size() + 1);
if (street != null) {
this.currentStreetName = street;
return true;
}
return false;
}
void addLocation(Location location, List<Address> addresses) {
this.locations.add(location);
this.addressLists.add(addresses);
this.updateStreetAddressList();
}
JSONArray toAddresses() throws JSONException {
return Address.toJSONArray(this.currentStreetAddresses);
}
} |
package ucar.nc2.grib;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import ucar.nc2.Attribute;
import ucar.nc2.constants.CDM;
import ucar.nc2.dt.GridDataset;
import ucar.nc2.dt.GridDatatype;
import ucar.unidata.util.StringUtil2;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* Try to figure out what GRIB name in 4.2 maps to in 4.3 NCEP IDD datasets.
* Not guaranteed to be correct.
* See ToolsUI IOSP/GRIB2/GRIB-RENAME
*
* @author caron
* @since 4/7/12
*/
public class GribVariableRenamer {
static private boolean debug = false;
static private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(GribVariableRenamer.class);
private static HashMap<String, Renamer> map1;
private static HashMap<String, Renamer> map2;
//Map<String, List<String>> mapr = new HashMap<String, List<String>>();
private void initMap1() {
List<VariableRenamerBean> beans = readVariableRenameFile("resources/grib1/grib1VarMap.xml");
map1 = makeMapBeans(beans);
}
private void initMap2() {
List<VariableRenamerBean> beans = readVariableRenameFile("resources/grib2/grib2VarMap.xml");
map2 = makeMapBeans(beans);
}
public List<String> getMappedNamesGrib2(String oldName) {
if (map2 == null) initMap2();
List<String> result = new ArrayList<String>();
Renamer mbean = map2.get(oldName);
if (mbean == null) return null;
for (VariableRenamerBean r : mbean.newVars) {
result.add(r.newName);
}
return result;
}
public List<String> getMappedNamesGrib1(String oldName) {
if (map1 == null) initMap1();
List<String> result = new ArrayList<String>();
Renamer mbean = map1.get(oldName);
if (mbean == null) return null;
for (VariableRenamerBean r : mbean.newVars) {
result.add(r.newName);
}
return result;
}
/**
* Get unique list of old names associated with this new name
* @param newName the new name
* @return unique list of old names, or null if not exist
*
private List<String> getOldNames(String newName) {
return mapr.get(newName);
} */
/**
* Look for possible matches of old (4.2) grib names in new (4.3) dataset.
*
* @param gds check existence in this dataset. Must be from a GRIB1 or GRIB2 dataset.
* @param oldName old name from 4.2 dataset
* @return list of possible matches (as grid short name), each exists in the dataset
*/
public List<String> matchNcepNames(GridDataset gds, String oldName) {
List<String> result = new ArrayList<String>();
// look for exact match
if (contains(gds, oldName)) {
result.add(oldName);
return result;
}
Attribute att = gds.findGlobalAttributeIgnoreCase(CDM.FILE_FORMAT);
boolean isGrib1 = (att != null) && att.getStringValue().startsWith("GRIB-1");
boolean isGrib2 = (att != null) && att.getStringValue().startsWith("GRIB-2");
HashMap<String, Renamer> map;
if (isGrib1) {
if (map1 == null) initMap1();
map = map1;
} else if (isGrib2) {
if (map2 == null) initMap2();
map = map2;
} else {
return result; // empty list
}
// look in our renamer map
Renamer mbean = map.get(oldName);
if (mbean != null && mbean.newName != null && contains(gds, mbean.newName)) {
result.add(mbean.newName); // if its unique, then we are done
return result;
}
// not unique - match against NCEP dataset
if (mbean != null) {
String dataset = extractDatasetFromLocation(gds.getLocationURI());
if (dataset != null) {
for (VariableRenamerBean r : mbean.newVars) {
if (r.getDatasetType().equals(dataset) && contains(gds, r.newName)) result.add(r.newName);
}
if (result.size() == 1) return result; // return if unique
}
}
// not unique, no unique match against dataset - check existence in the dataset
result.clear();
if (mbean != null) {
for (VariableRenamerBean r : mbean.newVarsMap.values()) {
if (contains(gds, r.newName)) result.add(r.newName);
}
if (result.size() > 0) return result;
}
// try to map oldName -> new prefix
result.clear();
String oldMunged = munge(oldName);
for (GridDatatype grid : gds.getGrids()) {
String newMunged = munge(grid.getShortName());
if (newMunged.startsWith(oldMunged))
result.add(grid.getShortName());
}
if (result.size() > 0) return result;
// return empty list
return result;
}
public List<String> matchNcepNames(String datasetType, String oldName) {
boolean isGrib1 = datasetType.endsWith("grib1");
List<String> result = new ArrayList<String>();
HashMap<String, Renamer> map;
if (isGrib1) {
if (map1 == null) initMap1();
map = map1;
} else {
if (map2 == null) initMap2();
map = map2;
}
// look in our renamer map
Renamer mbean = map.get(oldName);
if (mbean != null && mbean.newName != null) {
result.add(mbean.newName); // if its unique, then we are done
return result;
}
// not unique - match against NCEP datasetType
if (mbean != null) {
for (VariableRenamerBean r : mbean.newVars) {
if (r.getDatasetType().equals(datasetType)) result.add(r.newName);
}
}
return result;
}
private String munge(String old) {
StringBuilder oldLower = new StringBuilder( old.toLowerCase());
StringUtil2.remove(oldLower, "_-");
return oldLower.toString();
}
private boolean contains(GridDataset gds, String name) {
return gds.findGridByShortName(name) != null;
}
private String getNewName(HashMap<String, Renamer> map, String datasetLocation, String oldName) {
Renamer mbean = map.get(oldName);
if (mbean == null) return null;
if (mbean.newName != null) return mbean.newName; // if its unique, then we are done
String dataset = extractDatasetFromLocation(datasetLocation);
for (VariableRenamerBean r : mbean.newVars) {
if (r.getDatasetType().equals(dataset)) return r.getNewName();
}
return null;
}
public static String extractDatasetFromLocation(String location) {
int pos = location.lastIndexOf("/");
if (pos > 0) location = location.substring(pos+1);
int posSuffix = location.lastIndexOf(".");
if (posSuffix-14 > 0)
return location.substring(0, posSuffix-14) + location.substring(posSuffix);
return "";
}
/*
<dataset name="DGEX_Alaska_12km_20100524_0000.grib2">
<param oldName="Geopotential_height" newName="Geopotential_height_pressure" varId="VAR_0-3-5_L100" />
<param oldName="Geopotential_height_surface" newName="Geopotential_height_surface" varId="VAR_0-3-5_L1" />
<param oldName="MSLP_Eta_Reduction" newName="MSLP_Eta_model_reduction_msl" varId="VAR_0-3-192_L101" />
<param oldName="Maximum_temperature" newName="Maximum_temperature_height_above_ground" varId="VAR_0-0-4_L103" />
<param oldName="Minimum_temperature" newName="Minimum_temperature_height_above_ground" varId="VAR_0-0-5_L103" />
</dataset>
*/
// debugging only
public List<VariableRenamerBean> readVariableRenamerBeans(String which) {
if (which.equals("GRIB-1"))
return readVariableRenameFile("resources/grib1/grib1VarMap.xml");
else
return readVariableRenameFile("resources/grib2/grib2VarMap.xml");
}
private List<VariableRenamerBean> readVariableRenameFile(String path) {
java.util.List<VariableRenamerBean> beans = new ArrayList<VariableRenamerBean>(1000);
if (debug) System.out.printf("reading table %s%n", path);
InputStream is = null;
try {
is = GribResourceReader.getInputStream(path);
if (is == null) {
logger.warn("Cant read file " + path);
return null;
}
SAXBuilder builder = new SAXBuilder();
org.jdom2.Document doc = builder.build(is);
Element root = doc.getRootElement();
List<Element> dsElems = root.getChildren("dataset");
for (Element dsElem : dsElems) {
String dsName = dsElem.getAttributeValue("name");
List<Element> params = dsElem.getChildren("param");
for (Element elem : params) {
String oldName = elem.getAttributeValue("oldName");
String newName = elem.getAttributeValue("newName");
String varId = elem.getAttributeValue("varId");
beans.add(new VariableRenamerBean(dsName, oldName, newName, varId));
}
}
return beans;
} catch (IOException ioe) {
ioe.printStackTrace();
return null;
} catch (JDOMException e) {
e.printStackTrace();
return null;
} finally {
if (is != null) try {
is.close();
} catch (IOException e) {
}
}
}
public static class VariableRenamerBean implements Comparable<VariableRenamerBean> {
String dsName, dsType, oldName, newName, varId;
// no-arg constructor
public VariableRenamerBean() {
}
public VariableRenamerBean(String dsName, String oldName, String newName, String varId) {
this.dsName = dsName;
this.dsType = extractDatasetFromLocation(dsName);
this.oldName = oldName;
this.newName = newName;
this.varId = varId;
}
public String getDataset() {
return dsName;
}
public String getDatasetType() {
return dsType;
}
public String getVarId() {
return varId;
}
public String getOldName() {
return oldName;
}
public String getNewName() {
return newName;
}
public String getStatus() {
if (oldName.equals(newName)) return "*";
if (oldName.equalsIgnoreCase(newName)) return "**";
return "";
}
@Override
public int compareTo(VariableRenamerBean o) {
return newName.compareTo(o.getNewName());
}
}
private HashMap<String, Renamer> makeMapBeans(List<VariableRenamerBean> vbeans) {
HashMap<String, Renamer> map = new HashMap<String, Renamer>(3000);
for (VariableRenamerBean vbean : vbeans) {
// construct the old -> new mapping
Renamer mbean = map.get(vbean.getOldName());
if (mbean == null) {
mbean = new Renamer(vbean.getOldName());
map.put(vbean.getOldName(), mbean);
}
mbean.add(vbean);
/* construct the new -> old mapping
String newName = vbean.getNewName();
String oldName = vbean.getOldName();
List<String> maprList = mapr.get(newName);
if (maprList == null) {
maprList = new ArrayList<String>();
mapr.put(newName, maprList);
}
if (!maprList.contains(oldName))
maprList.add(oldName); */
}
for (Renamer rmap : map.values()) {
rmap.finish();
}
return map;
}
private class Renamer {
String oldName, newName; // newName exists when theres only one
List<VariableRenamerBean> newVars = new ArrayList<VariableRenamerBean>();
HashMap<String, VariableRenamerBean> newVarsMap = new HashMap<String, VariableRenamerBean>();
// no-arg constructor
public Renamer() {
}
public Renamer(String oldName) {
this.oldName = oldName;
}
void add(VariableRenamerBean vbean) {
newVarsMap.put(vbean.getNewName(), vbean);
newVars.add(vbean);
}
void finish() {
if (newVarsMap.values().size() == 1) {
newName = newVars.get(0).getNewName();
// newVars = null; // GC
}
}
public int getCount() {
return newVars.size();
}
public String getOldName() {
return oldName;
}
}
public static void main(String[] args) throws IOException {
ucar.nc2.dt.grid.GridDataset gds = ucar.nc2.dt.grid.GridDataset.open("Q:/cdmUnitTest/tds/ncep/GFS_CONUS_80km_20100513_0600.grib1");
GribVariableRenamer r = new GribVariableRenamer();
List<String> result = r.matchNcepNames(gds, "Precipitable_water");
}
} |
package edu.colorado.csdms.wmt.client.ui;
import java.util.Map;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import edu.colorado.csdms.wmt.client.Constants;
import edu.colorado.csdms.wmt.client.control.DataManager;
import edu.colorado.csdms.wmt.client.data.LabelJSO;
import edu.colorado.csdms.wmt.client.ui.handler.AuthenticationHandler;
import edu.colorado.csdms.wmt.client.ui.widgets.ComponentInfoDialogBox;
import edu.colorado.csdms.wmt.client.ui.widgets.LoginPanel;
/**
* Defines the initial layout of views (a perspective, in Eclipse parlance)
* for a WMT instance in a browser window. The Perspective holds three views,
* named North, West, and East. The top-level organizing panel for the
* GUI is a DockLayoutPanel. Includes getters and setters for the UI elements
* that are arrayed on the Perspective.
*
* @author Mark Piper (mark.piper@colorado.edu)
*/
public class Perspective extends DockLayoutPanel {
private DataManager data;
// Browser window dimensions (in px) used for setting up UI views.
private Integer browserWindowWidth;
// Primary UI panels.
private ViewNorth viewNorth;
private ViewWest viewWest;
private ViewEast viewEast;
// Secondary UI panels/widgets.
private ScrollPanel scrollModel;
private ScrollPanel scrollParameters;
private LoginPanel loginPanel;
private ModelActionPanel modelActionPanel;
private ModelTree modelTree;
private ParameterTable parameterTable;
private ComponentInfoDialogBox componentInfoBox;
private LabelsMenu labelsMenu;
/**
* Draws the panels and their children that compose the basic WMT GUI.
*/
public Perspective(DataManager data) {
super(Unit.PX);
this.data = data;
this.data.setPerspective(this);
this.addStyleName("wmt-DockLayoutPanel");
if (data.isDevelopmentMode()) {
this.addStyleDependentName("devmode");
}
// Determine initial view sizes based on browser window dimensions.
browserWindowWidth = Window.getClientWidth();
Integer viewEastInitialWidth =
(int) Math.round(Constants.VIEW_EAST_FRACTION * browserWindowWidth);
Integer headerHeight = 50; // TODO diagnose from largest header elt
// The Perspective has two children, a header in the north panel
// and a SplitLayoutPanel below.
viewNorth = new ViewNorth();
this.addNorth(viewNorth, headerHeight);
SplitLayoutPanel splitter = new SplitLayoutPanel(Constants.SPLITTER_SIZE);
splitter.addStyleName("wmt-SplitLayoutPanel");
this.add(splitter);
// The SplitLayoutPanel defines panels which translate to the West
// and East views of WMT.
viewEast = new ViewEast();
splitter.addEast(viewEast, viewEastInitialWidth);
viewWest = new ViewWest();
splitter.add(viewWest); // must be last
// The ComponentInfoDialogBox floats above the Perspective.
this.setComponentInfoBox(new ComponentInfoDialogBox());
}
/**
* An inner class to define the header (North view) of the WMT GUI.
*/
private class ViewNorth extends HorizontalPanel {
/**
* Makes the Header (North) view of the WMT GUI.
*/
public ViewNorth() {
this.setStyleName("wmt-NavBar");
HTML title = new HTML("The CSDMS Web Modeling Tool");
title.setStyleName("wmt-NavBarTitle");
this.add(title);
loginPanel = new LoginPanel();
loginPanel.getSignInButton().addClickHandler(
new AuthenticationHandler(data, loginPanel));
this.add(loginPanel);
}
} // end ViewNorth
/**
* An inner class to define the West panel of the WMT client.
*/
private class ViewWest extends TabLayoutPanel {
/**
* Makes the West view of the WMT client. It displays the model.
*/
public ViewWest() {
super(Constants.TAB_BAR_HEIGHT, Unit.PX);
setModelPanel(new ScrollPanel());
String tabTitle = data.tabPrefix("model") + "Model";
this.add(scrollModel, tabTitle, true);
}
} // end ViewWest
/**
* An inner class to define the East panel of the WMT client.
*/
private class ViewEast extends TabLayoutPanel {
/**
* Makes the East view of the WMT client. It displays the parameters of the
* currently selected model.
*/
public ViewEast() {
super(Constants.TAB_BAR_HEIGHT, Unit.PX);
setParametersPanel(new ScrollPanel());
String tabTitle = data.tabPrefix("parameter") + "Parameters";
this.add(scrollParameters, tabTitle, true);
}
} // end ViewEast
public ScrollPanel getModelPanel() {
return scrollModel;
}
public void setModelPanel(ScrollPanel scrollModel) {
this.scrollModel = scrollModel;
}
/**
* A convenience method for setting the tab title of the Model panel. If the
* model isn't saved, prepend an asterisk to its name.
*/
public void setModelPanelTitle() {
String tabTitle = data.tabPrefix("model") + "Model";
if (data.getModel().getName() != null) {
String marker = data.modelIsSaved() ? "" : "*";
tabTitle += " (" + marker + data.getModel().getName() + ")";
} else {
data.getModel().setName("Model " + data.saveAttempts.toString());
}
viewWest.setTabHTML(0, tabTitle);
}
public ComponentInfoDialogBox getComponentInfoBox() {
return componentInfoBox;
}
public void setComponentInfoBox(ComponentInfoDialogBox componentInfoBox) {
this.componentInfoBox = componentInfoBox;
}
/**
* Returns a reference to the {@link ModelTree} used in a WMT session.
*/
public ModelTree getModelTree() {
return modelTree;
}
/**
* Stores a reference to the {@link ModelTree} used in a WMT session.
*
* @param modelTree the ModelTree instance
*/
public void setModelTree(ModelTree modelTree) {
this.modelTree = modelTree;
}
public ScrollPanel getParametersPanel() {
return scrollParameters;
}
public void setParametersPanel(ScrollPanel scrollParameters) {
this.scrollParameters = scrollParameters;
}
/**
* A convenience method for setting the title of the Parameters panel.
*
* @param componentId the id of the component whose parameters are displayed
*/
public void setParameterPanelTitle(String componentId) {
String tabTitle = data.tabPrefix("parameter") + "Parameters";
if (componentId != null) {
String componentName = data.getModelComponent(componentId).getName();
tabTitle += " (" + componentName + ")";
}
viewEast.setTabHTML(0, tabTitle);
}
/**
* Returns a reference to the {@link ParameterTable} used in the
* "Parameters" tab of a WMT session.
*/
public ParameterTable getParameterTable() {
return parameterTable;
}
/**
* Stores a reference to the {@link ParameterTable} used in the "Parameters"
* tab of a WMT session.
*
* @param parameterTable the parameterTable to set
*/
public void setParameterTable(ParameterTable parameterTable) {
this.parameterTable = parameterTable;
}
public TabLayoutPanel getViewEast() {
return viewEast;
}
public TabLayoutPanel getViewWest() {
return viewWest;
}
public ModelActionPanel getActionButtonPanel() {
return modelActionPanel;
}
public void setActionButtonPanel(ModelActionPanel modelActionPanel) {
this.modelActionPanel = modelActionPanel;
}
public LabelsMenu getLabelsMenu() {
return labelsMenu;
}
public void setLabelsMenu(LabelsMenu labelsMenu) {
this.labelsMenu = labelsMenu;
}
public LoginPanel getLoginPanel() {
return loginPanel;
}
public void setLoginPanel(LoginPanel loginPanel) {
this.loginPanel = loginPanel;
}
/**
* Sets up the {@link ModelActionPanel} and the default starting
* {@link ModelTree} in the "Model" tab, showing only the open port for the
* driver of the model.
*/
public void initializeModel() {
modelTree = new ModelTree(data);
modelActionPanel = new ModelActionPanel(data);
modelActionPanel.setStyleName("wmt-ModelActionPanel");
VerticalPanel panel = new VerticalPanel();
panel.add(modelActionPanel);
panel.add(modelTree);
scrollModel.add(panel);
}
/**
* Creates an empty ParameterTable to display in the "Parameters" tab.
*/
public void initializeParameterTable() {
parameterTable = new ParameterTable(data);
scrollParameters.add(parameterTable);
}
/**
* Resets WMT to an approximation of its startup state.
*/
public void reset() {
data.resetModelComponents();
parameterTable.clearTable();
modelTree.initializeTree();
data.modelIsSaved(false);
((ComponentSelectionMenu) modelTree.getDriverComponentCell()
.getComponentMenu()).updateComponents();
setModelPanelTitle();
// Deselect all labels except for the owner label.
for (Map.Entry<String, LabelJSO> entry : data.modelLabels.entrySet()) {
try {
entry.getValue().isSelected(entry.getKey().equals(data.security.getWmtUsername()));
} catch (Exception e) {
GWT.log(e.toString());
}
}
labelsMenu.populateMenu();
}
} |
package io.hawt.web;
import io.hawt.util.IOHelper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.protocol.Protocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
public class ProxyServlet extends HttpServlet {
private static final transient Logger LOG = LoggerFactory.getLogger(ProxyServlet.class);
/**
* Serialization UID.
*/
private static final long serialVersionUID = 1L;
/**
* Key for redirect location header.
*/
private static final String STRING_LOCATION_HEADER = "Location";
/**
* Key for content type header.
*/
private static final String STRING_CONTENT_TYPE_HEADER_NAME = "Content-Type";
/**
* Key for content length header.
*/
private static final String STRING_CONTENT_LENGTH_HEADER_NAME = "Content-Length";
private static final String[] IGNORE_HEADER_NAMES = {STRING_CONTENT_LENGTH_HEADER_NAME, "Origin", "Authorization"};
/**
* Key for host header
*/
private static final String STRING_HOST_HEADER_NAME = "Host";
/**
* The directory to use to temporarily store uploaded files
*/
private static final File FILE_UPLOAD_TEMP_DIRECTORY = new File(System.getProperty("java.io.tmpdir"));
/**
* The maximum size for uploaded files in bytes. Default value is 5MB.
*/
private int intMaxFileUploadSize = 5 * 1024 * 1024;
/**
* Initialize the <code>ProxyServlet</code>
*
* @param servletConfig The Servlet configuration passed in by the servlet container
*/
public void init(ServletConfig servletConfig) {
OpenShiftProtocolSocketFactory socketFactory = OpenShiftProtocolSocketFactory.getSocketFactory();
Protocol http = new Protocol("http", socketFactory, 80);
Protocol.registerProtocol("http", http);
if (LOG.isDebugEnabled()) {
LOG.debug("Registered OpenShiftProtocolSocketFactory Protocol for http: " + Protocol.getProtocol("http").getSocketFactory());
}
}
/**
* Performs an HTTP GET request
*
* @param httpServletRequest The {@link HttpServletRequest} object passed
* in by the servlet engine representing the
* client request to be proxied
* @param httpServletResponse The {@link HttpServletResponse} object by which
* we can send a proxied response to the client
*/
public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws IOException, ServletException {
// Create a GET request
ProxyDetails proxyDetails = new ProxyDetails(httpServletRequest);
if (!proxyDetails.isValid()) {
httpServletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Context-Path should contain the proxy hostname to use");
} else {
GetMethod getMethodProxyRequest = new GetMethod(proxyDetails.getStringProxyURL());
// Forward the request headers
setProxyRequestHeaders(proxyDetails, httpServletRequest, getMethodProxyRequest);
// Execute the proxy request
this.executeProxyRequest(proxyDetails, getMethodProxyRequest, httpServletRequest, httpServletResponse);
}
}
/**
* Performs an HTTP POST request
*
* @param httpServletRequest The {@link HttpServletRequest} object passed
* in by the servlet engine representing the
* client request to be proxied
* @param httpServletResponse The {@link HttpServletResponse} object by which
* we can send a proxied response to the client
*/
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws IOException, ServletException {
// Create a standard POST request
ProxyDetails proxyDetails = new ProxyDetails(httpServletRequest);
if (!proxyDetails.isValid()) {
httpServletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Context-Path should contain the proxy hostname to use");
} else {
PostMethod postMethodProxyRequest = new PostMethod(proxyDetails.getStringProxyURL());
// Forward the request headers
setProxyRequestHeaders(proxyDetails, httpServletRequest, postMethodProxyRequest);
// Check if this is a mulitpart (file upload) POST
if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
this.handleMultipartPost(postMethodProxyRequest, httpServletRequest);
} else {
this.handleStandardPost(postMethodProxyRequest, httpServletRequest);
}
// Execute the proxy request
this.executeProxyRequest(proxyDetails, postMethodProxyRequest, httpServletRequest, httpServletResponse);
}
}
/**
* Sets up the given {@link PostMethod} to send the same multipart POST
* data as was sent in the given {@link HttpServletRequest}
*
* @param postMethodProxyRequest The {@link PostMethod} that we are
* configuring to send a multipart POST request
* @param httpServletRequest The {@link HttpServletRequest} that contains
* the mutlipart POST data to be sent via the {@link PostMethod}
*/
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
throws ServletException {
// Create a factory for disk-based file items
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// Set factory constraints
diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
// Create a new file upload handler
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// Parse the request
try {
// Get the multipart items as a list
List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
// Create a list to hold all of the parts
List<Part> listParts = new ArrayList<Part>();
// Iterate the multipart items list
for (FileItem fileItemCurrent : listFileItems) {
// If the current item is a form field, then create a string part
if (fileItemCurrent.isFormField()) {
StringPart stringPart = new StringPart(
fileItemCurrent.getFieldName(), // The field name
fileItemCurrent.getString() // The field value
);
// Add the part to the list
listParts.add(stringPart);
} else {
// The item is a file upload, so we create a FilePart
FilePart filePart = new FilePart(
fileItemCurrent.getFieldName(), // The field name
new ByteArrayPartSource(
fileItemCurrent.getName(), // The uploaded file name
fileItemCurrent.get() // The uploaded file contents
)
);
// Add the part to the list
listParts.add(filePart);
}
}
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
listParts.toArray(new Part[]{}),
postMethodProxyRequest.getParams()
);
postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
// The current content-type header (received from the client) IS of
// type "multipart/form-data", but the content-type header also
// contains the chunk boundary string of the chunks. Currently, this
// header is using the boundary of the client request, since we
// blindly copied all headers from the client request to the proxy
// request. However, we are creating a new request with a new chunk
// boundary string, so it is necessary that we re-set the
// content-type string to reflect the new chunk boundary string
postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType());
} catch (FileUploadException fileUploadException) {
throw new ServletException(fileUploadException);
}
}
/**
* Sets up the given {@link PostMethod} to send the same standard POST
* data as was sent in the given {@link HttpServletRequest}
*
* @param postMethodProxyRequest The {@link PostMethod} that we are
* configuring to send a standard POST request
* @param httpServletRequest The {@link HttpServletRequest} that contains
* the POST data to be sent via the {@link PostMethod}
*/
@SuppressWarnings("unchecked")
private void handleStandardPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws IOException {
// Get the client POST data as a Map
Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap();
// Create a List to hold the NameValuePairs to be passed to the PostMethod
List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>();
// Iterate the parameter names
for (String stringParameterName : mapPostParameters.keySet()) {
// Iterate the values for each parameter name
String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName);
for (String stringParamterValue : stringArrayParameterValues) {
// Create a NameValuePair and store in list
NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue);
listNameValuePairs.add(nameValuePair);
}
}
RequestEntity entity = null;
String contentType = httpServletRequest.getContentType();
if (contentType != null) {
contentType = contentType.toLowerCase();
if (contentType.contains("json") || contentType.contains("xml") || contentType.contains("application") || contentType.contains("text")) {
String body = IOHelper.readFully(httpServletRequest.getReader());
entity = new StringRequestEntity(body, contentType, httpServletRequest.getCharacterEncoding());
postMethodProxyRequest.setRequestEntity(entity);
}
}
NameValuePair[] parameters = listNameValuePairs.toArray(new NameValuePair[]{});
if (entity != null) {
// TODO add as URL parameters?
//postMethodProxyRequest.addParameters(parameters);
} else {
// Set the proxy request POST data
postMethodProxyRequest.setRequestBody(parameters);
}
}
/**
* Executes the {@link HttpMethod} passed in and sends the proxy response
* back to the client via the given {@link HttpServletResponse}
*
* @param proxyDetails
* @param httpMethodProxyRequest An object representing the proxy request to be made
* @param httpServletResponse An object by which we can send the proxied
* response back to the client
* @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
* @throws ServletException Can be thrown to indicate that another error has occurred
*/
private void executeProxyRequest(
ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse)
throws IOException, ServletException {
httpMethodProxyRequest.setFollowRedirects(false);
// Create a default HttpClient
HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest);
// Execute the request
int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
// Check if the proxy response is a redirect
// The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
// Hooray for open source software
if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
&& intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
String stringStatusCode = Integer.toString(intProxyResponseCode);
String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
if (stringLocation == null) {
throw new ServletException("Received status code: " + stringStatusCode
+ " but no " + STRING_LOCATION_HEADER + " header was found in the response");
}
// Modify the redirect to go to this proxy servlet rather that the proxied host
String stringMyHostName = httpServletRequest.getServerName();
if (httpServletRequest.getServerPort() != 80) {
stringMyHostName += ":" + httpServletRequest.getServerPort();
}
stringMyHostName += httpServletRequest.getContextPath();
httpServletResponse.sendRedirect(stringLocation.replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName));
return;
} else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
// 304 needs special handling. See:
// http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
// We get a 304 whenever passed an 'If-Modified-Since'
// header and the data on disk has not changed; server
// responds w/ a 304 saying I'm not going to send the
// body because the file has not changed.
httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
// Pass the response code back to the client
httpServletResponse.setStatus(intProxyResponseCode);
// Pass response headers back to the client
Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
for (Header header : headerArrayResponse) {
httpServletResponse.setHeader(header.getName(), header.getValue());
}
// check if we got data, that is either the Content-Length > 0
// or the response code != 204
int code = httpMethodProxyRequest.getStatusCode();
boolean noData = code == HttpStatus.SC_NO_CONTENT;
if (!noData) {
String length = httpMethodProxyRequest.getResponseHeader(STRING_CONTENT_LENGTH_HEADER_NAME).getValue();
if (length != null) {
int ilength = Integer.parseInt(length);
if (ilength <= 2) {
// unmapped web contexts in OSGi do not return 404, but empty (or containing \r\n) pages
noData = true;
}
}
}
LOG.trace("Response has data? {}", !noData);
if (!noData) {
// Send the content to the client
InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
int intNextByte;
while ((intNextByte = bufferedInputStream.read()) != -1) {
outputStreamClientResponse.write(intNextByte);
}
} else {
httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
httpServletResponse.setHeader("Content-Type", "text/plain");
String remoteUrl = proxyDetails.getHostAndPort() + proxyDetails.getPath();
byte[] emptyResponse = ("{message: \"No content retrieved from " + remoteUrl + "\"}").getBytes();
httpServletResponse.setHeader(STRING_CONTENT_LENGTH_HEADER_NAME, Integer.toString(emptyResponse.length));
httpServletResponse.getOutputStream().write(emptyResponse);
}
}
public String getServletInfo() {
return "Jason's Proxy Servlet";
}
/**
* Retrieves all of the headers from the servlet request and sets them on
* the proxy request
*
* @param proxyDetails
* @param httpServletRequest The request object representing the client's
* request to the servlet engine
* @param httpMethodProxyRequest The request that we are about to send to
*/
private void setProxyRequestHeaders(ProxyDetails proxyDetails, HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
// Get an Enumeration of all of the header names sent by the client
Enumeration<?> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
while (enumerationOfHeaderNames.hasMoreElements()) {
String stringHeaderName = (String) enumerationOfHeaderNames.nextElement();
if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME) ||
stringHeaderName.equalsIgnoreCase("Authorization") ||
stringHeaderName.equalsIgnoreCase("Origin"))
continue;
// As per the Java Servlet API 2.5 documentation:
// Some headers, such as Accept-Language can be sent by clients
// as several headers each with a different value rather than
// sending the header as a comma separated list.
// Thus, we get an Enumeration of the header values sent by the client
Enumeration<?> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);
while (enumerationOfHeaderValues.hasMoreElements()) {
String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement();
// In case the proxy host is running multiple virtual servers,
// rewrite the Host header to ensure that we get content from
// the correct virtual server
if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME)) {
stringHeaderValue = proxyDetails.getProxyHostAndPort();
}
Header header = new Header(stringHeaderName, stringHeaderValue);
// Set the same header on the proxy request
httpMethodProxyRequest.setRequestHeader(header);
}
}
}
private int getMaxFileUploadSize() {
return this.intMaxFileUploadSize;
}
private void setMaxFileUploadSize(int intMaxFileUploadSizeNew) {
this.intMaxFileUploadSize = intMaxFileUploadSizeNew;
}
} |
package org.jetel.graph;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.Future;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.io.filefilter.AbstractFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.graph.runtime.EngineInitializer;
import org.jetel.graph.runtime.GraphRuntimeContext;
import org.jetel.main.runGraph;
import org.jetel.test.CloverTestCase;
import org.jetel.util.file.FileUtils;
import org.jetel.util.string.StringUtils;
public class ResetTest extends CloverTestCase {
private final static String SCENARIOS_RELATIVE_PATH = "../cloveretl.test.scenarios/";
private final static String[] EXAMPLE_PATH = {
"../cloveretl.examples/SimpleExamples/",
"../cloveretl.examples/AdvancedExamples/",
"../cloveretl.examples/CTL1FunctionsTutorial/",
"../cloveretl.examples/CTL2FunctionsTutorial/",
"../cloveretl.examples/DataProfiling/",
"../cloveretl.examples/DataSampling/",
"../cloveretl.examples/ExtExamples/",
"../cloveretl.test.scenarios/",
"../cloveretl.examples.commercial/",
"../cloveretl.examples/CompanyTransactionsTutorial/"
};
private final static String[] NEEDS_SCENARIOS_CONNECTION = {
"graphRevenues.grf",
"graphDBExecuteMsSql.grf",
"graphDBExecuteMySql.grf",
"graphDBExecuteOracle.grf",
"graphDBExecutePostgre.grf",
"graphDBExecuteSybase.grf",
"graphInfobrightDataWriterRemote.grf",
"graphLdapReaderWriter.grf"
};
private final static String[] NEEDS_SCENARIOS_LIB = {
"graphDBExecuteOracle.grf",
"graphDBExecuteSybase.grf",
"graphLdapReaderWriter.grf"
};
private final static String GRAPHS_DIR = "graph";
private final static String TRANS_DIR = "trans";
private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"};
private final String basePath;
private final File graphFile;
private final boolean batchMode;
private boolean cleanUp = true;
private static Log logger = LogFactory.getLog(ResetTest.class);
public static Test suite() {
final TestSuite suite = new TestSuite();
for (int i = 0; i < EXAMPLE_PATH.length; i++) {
logger.info("Testing graphs in " + EXAMPLE_PATH[i]);
final File graphsDir = new File(EXAMPLE_PATH[i], GRAPHS_DIR);
if(!graphsDir.exists()){
throw new IllegalStateException("Graphs directory " + graphsDir.getAbsolutePath() +" not found");
}
IOFileFilter fileFilter = new AbstractFileFilter() {
@Override
public boolean accept(File file) {
return file.getName().endsWith(".grf")
&& !file.getName().startsWith("TPCH")// ok, performance tests - last very long
&& !file.getName().contains("Performance")// ok, performance tests - last very long
&& !file.getName().equals("graphJoinData.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created
&& !file.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created
&& !file.getName().equals("conversionNum2num.grf") // ok, should fail
&& !file.getName().equals("outPortWriting.grf") // ok, should fail
&& !file.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client
&& !file.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client
&& !file.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client
&& !file.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client
&& !file.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client
&& !file.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server
&& !file.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server
&& !file.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows
&& !file.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server
&& !file.getName().equals("graphSequenceChecker.grf") // ok, is to fail
&& !file.getName().equals("FixedData.grf") // ok, is to fail
&& !file.getName().equals("xpathReaderStates.grf") // ok, is to fail
&& !file.getName().equals("graphDataPolicy.grf") // ok, is to fail
&& !file.getName().equals("conversionDecimal2integer.grf") // ok, is to fail
&& !file.getName().equals("conversionDecimal2long.grf") // ok, is to fail
&& !file.getName().equals("conversionDouble2integer.grf") // ok, is to fail
&& !file.getName().equals("conversionDouble2long.grf") // ok, is to fail
&& !file.getName().equals("conversionLong2integer.grf") // ok, is to fail
&& !file.getName().equals("nativeSortTestGraph.grf") // ok, invalid paths
&& !file.getName().equals("mountainsInformix.grf") // see issue 2550
&& !file.getName().equals("SystemExecuteWin_EchoFromFile.grf") // graph for windows
&& !file.getName().equals("XLSEncryptedFail.grf") // ok, is to fail
&& !file.getName().equals("XLSXEncryptedFail.grf") // ok, is to fail
&& !file.getName().equals("XLSInvalidFile.grf") // ok, is to fail
&& !file.getName().equals("XLSReaderOrderMappingFail.grf") // ok, is to fail
&& !file.getName().equals("XLSXReaderOrderMappingFail.grf") // ok, is to fail
&& !file.getName().equals("XLSWildcardStrict.grf") // ok, is to fail
&& !file.getName().equals("XLSXWildcardStrict.grf") // ok, is to fail
&& !file.getName().equals("XLSWildcardControlled1.grf") // ok, is to fail
&& !file.getName().equals("XLSXWildcardControlled1.grf") // ok, is to fail
&& !file.getName().equals("XLSWildcardControlled7.grf") // ok, is to fail
&& !file.getName().equals("XLSXWildcardControlled7.grf") // ok, is to fail
&& !file.getName().equals("SSWRITER_MultilineInsertIntoTemplate.grf") // uses graph parameter definition from after-commit.ts
&& !file.getName().equals("SSWRITER_FormatInMetadata.grf") // uses graph parameter definition from after-commit.ts
&& !file.getName().equals("WSC_NamespaceBindingsDefined.grf") // ok, is to fail
&& !file.getName().equals("FailingGraph.grf") // ok, is to fail
&& !file.getName().equals("RunGraph_FailWhenUnderlyingGraphFails.grf") // probably should fail, recheck after added to after-commit.ts
&& !file.getName().equals("DataIntersection_order_check_A.grf") // ok, is to fail
&& !file.getName().equals("DataIntersection_order_check_B.grf") // ok, is to fail
&& !file.getName().equals("UDR_Logging_SFTP_CL1469.grf") // ok, is to fail
&& !file.getName().startsWith("AddressDoctor") //wrong path to db file, try to fix when AD installed on jenkins machines
&& !file.getName().equals("EmailReader_Local.grf") // remove after CL-2167 solved
&& !file.getName().equals("EmailReader_Server.grf") // remove after CLD-3437 solved (or mail.javlin.eu has valid certificate)
&& !file.getName().contains("firebird") // remove after CL-2170 solved
&& !file.getName().startsWith("ListOfRecords_Functions_02_") // remove after CL-2173 solved
&& !file.getName().equals("UDR_FileURL_OneZipMultipleFilesUnspecified.grf") // remove after CL-2174 solved
&& !file.getName().equals("UDR_FileURL_OneZipOneFileUnspecified.grf") // remove after CL-2174 solved
&& !file.getName().startsWith("MapOfRecords_Functions_01_Compiled_") // remove after CL-2175 solved
&& !file.getName().startsWith("MapOfRecords_Functions_01_Interpreted_") // remove after CL-2176 solved
&& !file.getName().equals("packedDecimal.grf") // remove after CL-1811 solved
&& !file.getName().equals("SimpleZipWrite.grf") // used by ArchiveFlushTest.java, doesn't make sense to run it separately
&& !file.getName().equals("XMLExtract_TKLK_003_Back.grf") // needs output from XMLWriter_LKTW_003.grf
&& !file.getName().equals("SQLDataParser_precision_CL2187.grf") // ok, is to fail
&& !file.getName().equals("incrementalReadingDB_explicitMapping.grf") // remove after CL-2239 solved
&& !file.getName().equals("HTTPConnector_get_bodyparams.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_error_unknownhost.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_error_unknownprotocol.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_inputfield.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_inputfileURL.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_get_requestcontent.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_post_error_unknownhost.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_post_error_unknownprotocol.grf") // ok, is to fail
&& !file.getName().equals("HTTPConnector_inputmapping_null_values.grf") // ok, is to fail
&& !file.getName().equals("HttpConnector_errHandlingNoRedir.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_fileURL_not_xml.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_charset_invalid.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_mappingURL_missing.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_fileURL_not_exists.grf") // ok, is to fail
&& !file.getName().equals("XMLExtract_charset_not_default_fail.grf") // ok, is to fail
&& !file.getName().equals("RunGraph_differentOutputMetadataFail.grf") // ok, is to fail
&& !file.getName().equals("LUTPersistent_wrong_metadata.grf") // ok, is to fail
&& !file.getName().equals("UDW_nonExistingDir_fail_CL-2478.grf") // ok, is to fail
&& !file.getName().equals("CTL_lookup_put_fail.grf") // ok, is to fail
&& !file.getName().equals("SystemExecute_printBatchFile.grf") // ok, is to fail
&& !file.getName().equals("JoinMergeIssue_FailWhenMasterUnsorted.grf") // ok, is to fail
&& !file.getName().startsWith("Proxy_") // allowed to run only on virt-cyan as proxy tests
&& !file.getName().equals("SandboxOperationHandlerTest.grf") // runs only on server
&& !file.getName().equals("DenormalizerWithoutInputFile.grf") // probably subgraph not supposed to be executed separately
&& !file.getName().equals("SimpleSequence_longValue.grf") // needs the sequence to be reset on start
&& !file.getName().equals("BeanWriterReader_employees.grf"); // remove after CL-2474 solved
}
};
IOFileFilter dirFilter = new AbstractFileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory() && file.getName().equals("hadoop");
}
};
@SuppressWarnings("unchecked")
Collection<File> filesCollection = org.apache.commons.io.FileUtils.listFiles(graphsDir, fileFilter, dirFilter);
File[] graphFiles = filesCollection.toArray(new File[0]);
Arrays.sort(graphFiles);
for(int j = 0; j < graphFiles.length; j++){
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], false, false));
suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], true, j == graphFiles.length - 1 ? true : false));
}
}
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
initEngine();
}
protected static String getTestName(String basePath, File graphFile, boolean batchMode) {
final StringBuilder ret = new StringBuilder();
final String n = graphFile.getName();
int lastDot = n.lastIndexOf('.');
if (lastDot == -1) {
ret.append(n);
} else {
ret.append(n.substring(0, lastDot));
}
if (batchMode) {
ret.append("-batch");
} else {
ret.append("-nobatch");
}
return ret.toString();
}
protected ResetTest(String basePath, File graphFile, boolean batchMode, boolean cleanup) {
super(getTestName(basePath, graphFile, batchMode));
this.basePath = basePath;
this.graphFile = graphFile;
this.batchMode = batchMode;
this.cleanUp = cleanup;
}
@Override
protected void runTest() throws Throwable {
final String baseAbsolutePath = new File(basePath).getAbsolutePath().replace('\\', '/');
logger.info("Project dir: " + baseAbsolutePath);
logger.info("Analyzing graph " + graphFile.getPath());
logger.info("Batch mode: " + batchMode);
final GraphRuntimeContext runtimeContext = new GraphRuntimeContext();
runtimeContext.setUseJMX(false);
runtimeContext.setContextURL(FileUtils.getFileURL(FileUtils.appendSlash(baseAbsolutePath))); // context URL should be absolute
// absolute path in PROJECT parameter is required for graphs using Derby database
runtimeContext.addAdditionalProperty("PROJECT", baseAbsolutePath);
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_CONNECTION) != -1) {
final String connDir = new File(SCENARIOS_RELATIVE_PATH + "conn").getAbsolutePath();
runtimeContext.addAdditionalProperty("CONN_DIR", connDir);
logger.info("CONN_DIR set to " + connDir);
}
if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_LIB) != -1) {// set LIB_DIR to jdbc drivers directory
final String libDir = new File(SCENARIOS_RELATIVE_PATH + "lib").getAbsolutePath();
runtimeContext.addAdditionalProperty("LIB_DIR", libDir);
logger.info("LIB_DIR set to " + libDir);
}
// for scenarios graphs, add the TRANS dir to the classpath
if (basePath.contains("cloveretl.test.scenarios")) {
runtimeContext.setRuntimeClassPath(new URL[] {FileUtils.getFileURL(FileUtils.appendSlash(baseAbsolutePath) + TRANS_DIR + "/")});
runtimeContext.setCompileClassPath(runtimeContext.getRuntimeClassPath());
}
runtimeContext.setBatchMode(batchMode);
final TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(graphFile), runtimeContext);
try {
graph.setDebugMode(false);
EngineInitializer.initGraph(graph);
for (int i = 0; i < 3; i++) {
final Future<Result> futureResult = runGraph.executeGraph(graph, runtimeContext);
Result result = Result.N_A;
result = futureResult.get();
switch (result) {
case FINISHED_OK:
// everything O.K.
logger.info("Execution of graph successful !");
break;
case ABORTED:
// execution was ABORTED !!
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
break;
default:
logger.info("Execution of graph failed !");
fail("Execution of graph failed !");
}
}
} catch (Throwable e) {
throw new IllegalStateException("Error executing grap " + graphFile, e);
} finally {
if (cleanUp) {
cleanupData();
}
logger.info("Transformation graph is freeing.\n");
graph.free();
}
}
private void cleanupData() {
for (String outDir : OUT_DIRS) {
File outDirFile = new File(basePath, outDir);
File[] file = outDirFile.listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isFile();
}
});
for (int i = 0; i < file.length; i++) {
final boolean drt = file[i].delete();
if (drt) {
logger.info("Cleanup: deleted file " + file[i].getAbsolutePath());
} else {
logger.info("Cleanup: error delete file " + file[i].getAbsolutePath());
}
}
}
}
} |
package edu.utexas.cycic;
import java.util.ArrayList;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Shape;
import javafx.scene.text.Text;
/**
* This class is built to handle all of the functions used in building the forms for CYCIC.
* @author Robert
*
*/
public class FormBuilderFunctions {
/**
* This method is used to read and create the forms associated with each facility.
* @param facArray ArrayList<Object> that contains the facility prototype information structure for the facility opened with this view.
* @param dataArray ArrayList<Object> containing all of the data associated with the facility opened with this view.
*/
@SuppressWarnings("unchecked")
public static void formArrayBuilder(ArrayList<Object> facArray, ArrayList<Object> dataArray){
Boolean test = true;
String defaultValue = "";
for (int i = 0; i < facArray.size(); i++){
if (facArray.get(i) instanceof ArrayList){
test = false;
dataArray.add(new ArrayList<Object>());
formArrayBuilder((ArrayList<Object>)facArray.get(i), (ArrayList<Object>)dataArray.get(dataArray.size()-1));
} else if (i == 0){
defaultValue = (String) facArray.get(5);
}
}
if (test == true) {
if(facArray.get(5) != null){
dataArray.add(defaultValue);
} else {
dataArray.add("");
}
}
}
/**
* A function used to copy the internal structure of an ArrayList<Object>.
* @param baseList The ArrayList<Object> the new copy list will be added to.
* @param copyList The ArrayList<Object> being copied to the baseList.
*/
@SuppressWarnings("unchecked")
public static void arrayListCopy(ArrayList<Object> baseList, ArrayList<Object> copyList){
ArrayList<Object> addedArray = new ArrayList<Object>();
for(int i = 0; i < copyList.size(); i++){
if(copyList.get(i) instanceof ArrayList){
arrayListCopy(addedArray, (ArrayList<Object>)copyList.get(i));
} else {
addedArray.add(copyList.get(i));
}
}
baseList.add(addedArray);
}
/**
* A function used to create the generic text fields inputs.
* @param array The ArrayList<Object> used to store the information in the TextField.
* @return A TextField tied via a listener to the value of this input field.
*/
static TextField textFieldBuilder(final ArrayList<Object> facArray, final ArrayList<Object> defaultValue){
TextField textField = new TextField();
textField.setText(defaultValue.get(0).toString());
textField.setPromptText(facArray.get(2).toString());
textField.textProperty().addListener(new ChangeListener<Object>(){
public void changed(ObservableValue<?> observable, Object oldValue, Object newValue){
defaultValue.set(0, newValue);
}
});
return textField;
}
/**
* Special function used for the name flag in a facility.
* @param node The facility node that is currently being worked on
* @param dataArray The ArrayList<Object> that contains the name field data for the facility.
* @return TextField that controls the input of this field.
*/
static TextField nameFieldBuilder(final facilityNode node){
TextField textField = new TextField();
textField.setText((String)node.name);
textField.textProperty().addListener(new ChangeListener<String>(){
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
node.name = newValue;
node.cycicCircle.text.setText(newValue);
node.sorterCircle.text.setText(newValue);
node.cycicCircle.tooltip.setText(newValue);
node.sorterCircle.tooltip.setText(newValue);
}
});
return textField;
}
/***
* Function designed for the naming of a marketCircle. Updates name and text of the marketCircle node.
* @param node The marketCircle associated with the form that calls this function.
* @return TextField linked to the name and text of the marketCircle node.
*/
static TextField marketNameBuilder(final MarketCircle node){
TextField textField = new TextField();
textField.setText((String) node.name);
textField.textProperty().addListener(new ChangeListener<String>(){
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
node.name = (String) newValue;
node.text.setText(newValue);
}
});
return textField;
}
/**
* Function used to create a TextField for the naming of a regionNode.
* @param node regionNode associated with the form that calls this function.
* @param dataArray ArrayList<Object> that contains the name field for this regionNode.
* @return TextField linked to the name of a regionNode.
*/
static TextField regionNameBuilder(final regionNode node){
TextField textField = new TextField();
RegionCorralView.workingRegion = node;
textField.setText((String) node.name);
textField.textProperty().addListener(new ChangeListener<String>(){
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
node.name = (String) newValue;
node.regionCircle.name.equals(newValue);
node.regionCircle.text.setText(newValue);
node.regionCircle.rgbColor = VisFunctions.stringToColor(newValue);
node.regionCircle.setFill(Color.rgb(node.regionCircle.rgbColor.get(0), node.regionCircle.rgbColor.get(1), node.regionCircle.rgbColor.get(2)));
// Setting font color for visibility //
if(VisFunctions.colorTest(node.regionCircle.rgbColor) == true){
node.regionCircle.text.setFill(Color.BLACK);
}else{
node.regionCircle.text.setFill(Color.WHITE);
}
}
});
return textField;
}
static TextField institNameBuilder(final instituteNode node){
TextField textField = new TextField();
textField.textProperty().addListener(new ChangeListener<String>(){
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
node.name = (String) newValue;
}
});
return textField;
}
static Slider sliderBuilder(String string, String defaultValue){
final Slider slider = new Slider();
slider.setMin(Double.parseDouble(string.split("[...]")[0]));
slider.setMax(Double.parseDouble(string.split("[...]")[3]));
slider.setShowTickLabels(true);
slider.setShowTickMarks(true);
slider.setMajorTickUnit(slider.getMax()/5);
slider.setValue(Double.parseDouble(defaultValue));
return slider;
}
/**
* A function to create a text field used to visualize a given slider.
* @param slider The slider that the text field is used to describe.
* @param defaultValue The current value of the slider passed to the function.
* @return A text field used to interact with the slider.
*/
static TextField sliderTextFieldBuilder(final Slider slider, final ArrayList<Object> defaultValue){
final TextField textField = new TextField();
textField.setText((String) defaultValue.get(0));
textField.setText(String.format("%.2f", slider.getValue()));
textField.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent action){
if(Double.parseDouble(textField.getText()) <= slider.getMax() && Double.parseDouble(textField.getText()) >= slider.getMin()){
slider.setValue(Double.parseDouble(textField.getText()));
}
}
});
textField.textProperty().addListener(new ChangeListener<String>(){
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
if (slider.getMax() < 9000 && Double.parseDouble(newValue) > 9000){
textField.setText("IT'S OVER 9000!!!!!");
} else {
defaultValue.set(0, textField.getText());
}
}
});
slider.valueProperty().addListener(new ChangeListener<Number>(){
public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val) {
textField.setText(String.format("%.2f", new_val));
defaultValue.set(0, textField.getText());
}
});
return textField;
}
/**
* Creates a ComboBox used to build the drop down menus for discrete value ranges or lists.
* @param string The string containing the discrete values in the form of "v1,v2,v3,v4,v5,...,vN"
* @param defaultValue ArrayList<Object> that contains the default or current value of the comboBox being initiated.
* @return Returns a ComboBox to be used in the creation of the form.
*/
static ComboBox<String> comboBoxBuilder(String string, final ArrayList<Object> defaultValue){
final ComboBox<String> cb = new ComboBox<String>();
for(String value : string.split(",")){
cb.getItems().add(value.trim());
}
cb.setPromptText("Select value");
cb.setValue(defaultValue.get(0).toString());
cb.valueProperty().addListener(new ChangeListener<String>(){
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
defaultValue.set(0, cb.getValue());
}
});
return cb;
}
/**
* This function applies the units for the forms.
* @param units A string that contains the unit "type". Ex. "kg", "MW", etc.
* @return returns a label with this string
*/
static Label unitsBuilder(String units){
Label unitsLabel = new Label();
unitsLabel.setText(units);
return unitsLabel;
}
/**
* This function is used to instruct the CYCIC pane that a new link must be added to represent the linking of a facility to a market.
* In this case material is flowing into the facility. This function is only used for the "incommodity" of a facilityCircle.
* @param facNode The facilityCircle that the current form is being used to represent.
* @param defaultValue The ArrayList<Object> that contains the default value of this input field for the facilityCircle.
* @return ComboBox containing all of the commodities currently linked to markets, with the value shown being the current incommodity for the facNode.
*/
static ComboBox<String> comboBoxInCommod(final facilityNode facNode, final ArrayList<Object> defaultValue){
// Create and fill the comboBox
final ComboBox<String> cb = new ComboBox<String>();
cb.setMinWidth(80);
cb.setOnMousePressed(new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
cb.getItems().clear();
for (MarketCircle circle: CycicScenarios.workingCycicScenario.marketNodes){
cb.getItems().add(circle.commodity);
}
cb.getItems().add("New Commodity");
if ( defaultValue.get(0) != "") {
cb.setValue((String) defaultValue.get(0));
}
}
});
cb.setPromptText("Select a commodity");
cb.valueProperty().addListener(new ChangeListener<String>(){
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
MarketCircle marketCircle = null;
if (newValue == "New Commodity"){
// Tell Commodity Window to add a new commodity
} else {
for (MarketCircle circle: CycicScenarios.workingCycicScenario.marketNodes){
if (newValue == circle.commodity){
marketCircle = circle;
}
}
if (marketCircle != null){
VisFunctions.linkMarketFac(marketCircle, facNode.cycicCircle);
defaultValue.set(0, newValue);
facNode.cycicCircle.incommods.add(newValue);
for (int i = 0; i < facNode.cycicCircle.incommods.size(); i++) {
if (facNode.cycicCircle.incommods.get(i) == (String) oldValue){
facNode.cycicCircle.incommods.remove(i);
i
}
}
for (int i = 0; i < facNode.cycicCircle.incommods.size(); i++) {
System.out.println(facNode.cycicCircle.incommods.get(i));
}
VisFunctions.reloadPane();
}
}
}
});
return cb;
}
/**
* This function is used to instruct the CYCIC pane that a new link must be added to represent the linking of a facility to a market.
* In this case material is flowing out of the facility. This function is only used for the "outcommodity" of a facilityCircle.
* @param facNode The facilityCircle that the current form is being used to represent.
* @param defaultValue The ArrayList<Object> that contains the default value of this input field for the facilityCircle.
* @return ComboBox containing all of the commodities currently linked to markets, with the value shown being the current outcommodity for the facNode.
*/
static ComboBox<String> comboBoxOutCommod(final facilityNode facNode, final ArrayList<Object> defaultValue){
// Create and fill the comboBox
final ComboBox<String> cb = new ComboBox<String>();
cb.setMinWidth(80);
cb.setOnMousePressed(new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
cb.getItems().clear();
for (MarketCircle circle: CycicScenarios.workingCycicScenario.marketNodes){
cb.getItems().add(circle.commodity);
}
cb.getItems().add("New Commodity");
if ( defaultValue.get(0) != "") {
cb.setValue((String) defaultValue.get(0));
}
}
});
if ( defaultValue.get(0) != "") {
cb.setValue((String) defaultValue.get(0));
}
cb.valueProperty().addListener(new ChangeListener<String>(){
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
MarketCircle marketCircle = null;
if (newValue == "New Commodity"){
} else {
for (MarketCircle circle: CycicScenarios.workingCycicScenario.marketNodes){
if (newValue == circle.commodity){
marketCircle = circle;
}
}
if (marketCircle != null){
VisFunctions.linkFacMarket(facNode.cycicCircle, marketCircle);
facNode.cycicCircle.outcommods.add(newValue);
for (int i = 0; i < facNode.cycicCircle.outcommods.size(); i++) {
if (facNode.cycicCircle.outcommods.get(i) == (String) oldValue){
facNode.cycicCircle.outcommods.remove(i);
i
}
}
/*for (int i = 0; i < facNode.cycicCircle.outcommods.size(); i++) {
System.out.println(facNode.cycicCircle.outcommods.get(i));
}*/
defaultValue.set(0, newValue);
VisFunctions.reloadPane();
}
}
}
});
return cb;
}
/**
* Function used to link a recipe to a facility.
* @param facNode facilityCircle that was used to construct the form.
* @param defaultValue ArrayList<Object> containing the data for a "recipe" field in the facilityCircle.
* @return ComboBox containing all of the recipes currently available in the simulation, tied to the value of this recipe field.
*/
static ComboBox<String> recipeComboBox(facilityNode facNode, final ArrayList<Object> defaultValue){
final ComboBox<String> cb = new ComboBox<String>();
cb.setValue((String) defaultValue.get(0));
cb.setOnMousePressed(new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
cb.getItems().clear();
for (Nrecipe recipe: CycicScenarios.workingCycicScenario.Recipes) {
cb.getItems().add(recipe.Name);
}
}
});
cb.valueProperty().addListener(new ChangeListener<String>(){
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){
defaultValue.set(0, newValue);
}
});
return cb;
}
/**
* Creates a ComboBox that contains the list of commodities in the current working scenario.
* @param defaultValue ArrayList of containing the default value of this field.
* @return ComboBox containing the list of commodities in the scenario.
*/
static ComboBox<String> comboBoxCommod(final ArrayList<Object> defaultValue){
// Create and fill the comboBox
final ComboBox<String> cb = new ComboBox<String>();
cb.setMinWidth(80);
cb.setPromptText("Select a commodity");
cb.setOnMousePressed(new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
cb.getItems().clear();
for (MarketCircle circle: CycicScenarios.workingCycicScenario.marketNodes){
cb.getItems().add(circle.commodity);
}
cb.getItems().add("New Commodity");
}
});
return cb;
}
} |
package dr.evomodel.sitemodel;
import dr.evomodel.substmodel.FrequencyModel;
import dr.evomodel.substmodel.SubstitutionModel;
import dr.inference.model.AbstractModel;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.math.GammaDistribution;
import dr.xml.*;
import java.util.logging.Logger;
/**
* GammaSiteModel - A SiteModel that has a gamma distributed rates across sites.
*
* @version $Id: GammaSiteModel.java,v 1.31 2005/09/26 14:27:38 rambaut Exp $
*
* @author Andrew Rambaut
*/
public class GammaSiteModel extends AbstractModel
implements SiteModel {
public static final String SITE_MODEL = "siteModel";
public static final String SUBSTITUTION_MODEL = "substitutionModel";
public static final String MUTATION_RATE = "mutationRate";
public static final String RELATIVE_RATE = "relativeRate";
public static final String GAMMA_SHAPE = "gammaShape";
public static final String GAMMA_CATEGORIES = "gammaCategories";
public static final String PROPORTION_INVARIANT = "proportionInvariant";
/**
* Constructor for gamma+invar distributed sites. Either shapeParameter or
* invarParameter (or both) can be null to turn off that feature.
*/
public GammaSiteModel( SubstitutionModel substitutionModel,
Parameter muParameter,
Parameter shapeParameter, int gammaCategoryCount,
Parameter invarParameter )
{
super(SITE_MODEL);
this.substitutionModel = substitutionModel;
addModel(substitutionModel);
this.muParameter = muParameter;
if (muParameter != null) {
addParameter(muParameter);
muParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1));
}
this.shapeParameter = shapeParameter;
if (shapeParameter != null) {
this.categoryCount = gammaCategoryCount;
addParameter(shapeParameter);
shapeParameter.addBounds(new Parameter.DefaultBounds(1.0E3, 0.0, 1));
} else {
this.categoryCount = 1;
}
this.invarParameter = invarParameter;
if (invarParameter != null) {
this.categoryCount += 1;
addParameter(invarParameter);
invarParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1));
}
categoryRates = new double[this.categoryCount];
categoryProportions = new double[this.categoryCount];
ratesKnown = false;
}
/**
* set mu
*/
public void setMu(double mu)
{
muParameter.setParameterValue(0, mu);
}
/**
* @return mu
*/
public final double getMu() { return muParameter.getParameterValue(0); }
/**
* set alpha
*/
public void setAlpha(double alpha)
{
shapeParameter.setParameterValue(0, alpha);
ratesKnown = false;
}
/**
* @return alpha
*/
public final double getAlpha() { return shapeParameter.getParameterValue(0); }
public Parameter getMutationRateParameter() { return muParameter; }
public Parameter getAlphaParameter() { return shapeParameter; }
public Parameter getPInvParameter() { return invarParameter; }
public void setMutationRateParameter(Parameter parameter) {
if (muParameter != null) removeParameter(muParameter);
muParameter = parameter;
if (muParameter != null) addParameter(muParameter);
}
public void setAlphaParameter(Parameter parameter) {
if (shapeParameter != null) removeParameter(shapeParameter);
shapeParameter = parameter;
if (shapeParameter != null) addParameter(shapeParameter);
}
public void setPInvParameter(Parameter parameter) {
if (invarParameter != null) removeParameter(invarParameter);
invarParameter = parameter;
if (invarParameter != null) addParameter(invarParameter);
}
// Interface SiteModel
public boolean integrateAcrossCategories() { return true; }
public int getCategoryCount() { return categoryCount; }
public int getCategoryOfSite(int site) {
throw new IllegalArgumentException("Integrating across categories");
}
public void getTransitionProbabilitiesForCategory(int category, double time, double[] matrix) {
double substitutions = getSubstitutionsForCategory(category, time);
getTransitionProbabilities(substitutions, matrix);
}
public double getRateForCategory(int category) {
synchronized(this) {
if (!ratesKnown) {
calculateCategoryRates();
}
}
return categoryRates[category];
}
public double getSubstitutionsForCategory(int category, double time) {
synchronized(this) {
if (!ratesKnown) {
calculateCategoryRates();
}
}
double mu = 1.0;
if (muParameter != null) {
mu = muParameter.getParameterValue(0);
}
return time * mu * categoryRates[category];
}
public void getTransitionProbabilities(double substitutions, double[] matrix) {
substitutionModel.getTransitionProbabilities(substitutions, matrix);
}
/**
* Get the expected proportion of sites in this category.
* @param category the category number
* @return the proportion.
*/
public double getProportionForCategory(int category) {
synchronized(this) {
if (!ratesKnown) {
calculateCategoryRates();
}
}
return categoryProportions[category];
}
/**
* Get an array of the expected proportion of sites in this category.
* @return an array of the proportion.
*/
public double[] getCategoryProportions() {
synchronized(this) {
if (!ratesKnown) {
calculateCategoryRates();
}
}
return categoryProportions;
}
/**
* Get an array of the expected proportion of sites in this category.
* @return an array of the proportion.
*/
public double[] getCategoryRates() {
synchronized(this) {
if (!ratesKnown) {
calculateCategoryRates();
}
}
return categoryRates;
}
/**
* discretization of gamma distribution with equal proportions in each
* category
*/
private void calculateCategoryRates() {
double propVariable = 1.0;
int cat = 0;
if (invarParameter != null) {
categoryRates[0] = 0.0;
categoryProportions[0] = invarParameter.getParameterValue(0);
propVariable = 1.0 - categoryProportions[0];
cat = 1;
}
if (shapeParameter != null) {
final double a = shapeParameter.getParameterValue(0);
double mean = 0.0;
final int gammaCatCount = categoryCount - cat;
for (int i = 0; i < gammaCatCount; i++) {
categoryRates[i + cat] = GammaDistribution.quantile((2.0*i+1.0)/(2.0*gammaCatCount), a, 1.0/a);
mean += categoryRates[i + cat];
categoryProportions[i + cat] = propVariable / gammaCatCount;
}
mean = (propVariable * mean) / gammaCatCount;
for (int i = 0; i < gammaCatCount; i++) {
categoryRates[i + cat] /= mean;
}
} else {
categoryRates[cat] = 1.0 / propVariable;
categoryProportions[cat] = propVariable;
}
ratesKnown = true;
}
/**
* Get the frequencyModel for this SiteModel.
* @return the frequencyModel.
*/
public FrequencyModel getFrequencyModel() { return substitutionModel.getFrequencyModel(); }
/**
* Get the substitutionModel for this SiteModel.
* @return the substitutionModel.
*/
public SubstitutionModel getSubstitutionModel() { return substitutionModel; }
// Interface ModelComponent
protected void handleModelChangedEvent(Model model, Object object, int index) {
// Substitution model has changed so fire model changed event
listenerHelper.fireModelChanged(this, object, index);
}
public void handleParameterChangedEvent(Parameter parameter, int index) {
if (parameter == shapeParameter) {
ratesKnown = false;
} else if (parameter == invarParameter) {
ratesKnown = false;
} else {
// is the muParameter and nothing needs to be done
}
listenerHelper.fireModelChanged(this, parameter, index);
}
protected void storeState() {} // no additional state needs storing
protected void restoreState() {
ratesKnown = false;
}
protected void acceptState() {} // no additional state needs accepting
protected void adoptState(Model source) {
ratesKnown = false;
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() { return SITE_MODEL; }
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
SubstitutionModel substitutionModel = (SubstitutionModel)xo.getSocketChild(SUBSTITUTION_MODEL);
String msg = "";
Parameter muParam = null;
if (xo.hasSocket(MUTATION_RATE)) {
muParam = (Parameter)xo.getSocketChild(MUTATION_RATE);
msg += "\n with initial substitution rate = " + muParam.getParameterValue(0);
} else if (xo.hasSocket(RELATIVE_RATE)) {
muParam = (Parameter)xo.getSocketChild(RELATIVE_RATE);
msg += "\n with initial relative rate = " + muParam.getParameterValue(0);
}
Parameter shapeParam = null;
int catCount = 4;
if (xo.hasSocket(GAMMA_SHAPE)) {
XMLObject cxo = (XMLObject)xo.getChild(GAMMA_SHAPE);
catCount = cxo.getIntegerAttribute(GAMMA_CATEGORIES);
shapeParam = (Parameter)cxo.getChild(Parameter.class);
msg += "\n " + catCount + " category discrete gamma with initial shape = " + shapeParam.getParameterValue(0);
}
Parameter invarParam = null;
if (xo.hasSocket(PROPORTION_INVARIANT)) {
invarParam = (Parameter)xo.getSocketChild(PROPORTION_INVARIANT);
msg += "\n initial proportion of invariant sites = " + invarParam.getParameterValue(0);
}
if (msg.length() > 0) {
Logger.getLogger("dr.evomodel").info("Creating site model: " + msg);
} else {
Logger.getLogger("dr.evomodel").info("Creating site model.");
}
return new GammaSiteModel(substitutionModel, muParam, shapeParam, catCount, invarParam);
}
/** the substitution model for these sites */
/** mutation rate parameter */
/** shape parameter */
/** invariant sites parameter */ |
package dr.inference.operators;
import dr.inference.model.Bounds;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import dr.math.MathUtils;
import dr.xml.*;
import java.util.logging.Logger;
/**
* A generic scale operator for use with a multi-dimensional parameters.
* Either scale all dimentions at once or scale one dimention at a time.
* An optional bit vector and a threshold is used to vary the rate of the individual dimentions according
* to their on/off status. For example a threshold of 1 means pick only "on" dimentions.
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: ScaleOperator.java,v 1.20 2005/06/14 10:40:34 rambaut Exp $
*/
public class ScaleOperator extends AbstractCoercableOperator {
public static final String SCALE_OPERATOR = "scaleOperator";
public static final String SCALE_ALL = "scaleAll";
public static final String SCALE_ALL_IND = "scaleAllIndependently";
public static final String SCALE_FACTOR = "scaleFactor";
public static final String DEGREES_OF_FREEDOM = "df";
public static final String INDICATORS = "indicators";
public static final String PICKONEPROB = "pickoneprob";
private Parameter indicator;
private double indicatorOnProb;
public ScaleOperator(Variable variable, double scale) {
this(variable, scale, CoercionMode.COERCION_ON, 1.0);
}
public ScaleOperator(Variable<Double> variable, double scale, CoercionMode mode, double weight) {
this(variable, false, 0, scale, mode, null, 1.0, false);
setWeight(weight);
}
public ScaleOperator(Variable<Double> variable, boolean scaleAll, int degreesOfFreedom, double scale,
CoercionMode mode, Parameter indicator, double indicatorOnProb, boolean scaleAllInd) {
super(mode);
this.variable = variable;
this.indicator = indicator;
this.indicatorOnProb = indicatorOnProb;
this.scaleAll = scaleAll;
this.scaleAllIndependently = scaleAllInd;
this.scaleFactor = scale;
this.degreesOfFreedom = degreesOfFreedom;
}
/**
* @return the parameter this operator acts on.
*/
public Variable getVariable() {
return variable;
}
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() throws OperatorFailedException {
final double scale = (scaleFactor + (MathUtils.nextDouble() * ((1.0 / scaleFactor) - scaleFactor)));
double logq;
final Bounds<Double> bounds = variable.getBounds();
final int dim = variable.getSize();
if (scaleAllIndependently) {
// update all dimensions independently.
logq = 0;
for (int i = 0; i < dim; i++) {
final double scaleOne = (scaleFactor + (MathUtils.nextDouble() * ((1.0 / scaleFactor) - scaleFactor)));
final double value = scaleOne * variable.getValue(i);
logq -= Math.log(scaleOne);
if (value < bounds.getLowerLimit(i) || value > bounds.getUpperLimit(i)) {
throw new OperatorFailedException("proposed value outside boundaries");
}
variable.setValue(i, value);
}
} else if (scaleAll) {
// update all dimensions
// hasting ratio is dim-2 times of 1dim case. would be nice to have a reference here
// for the proof. It is supposed to be somewhere in an Alexei/Nicholes article.
if (degreesOfFreedom > 0)
// For parameters with non-uniform prior on only one dimension
logq = -degreesOfFreedom * Math.log(scale);
else
logq = (dim - 2) * Math.log(scale);
// Must first set all parameters first and check for boundaries later for the operator to work
// correctly with dependent parameters such as tree node heights.
for (int i = 0; i < dim; i++) {
variable.setValue(i, variable.getValue(i) * scale);
}
for (int i = 0; i < dim; i++) {
if (variable.getValue(i) < variable.getBounds().getLowerLimit(i) ||
variable.getValue(i) > variable.getBounds().getUpperLimit(i)) {
throw new OperatorFailedException("proposed value outside boundaries");
}
}
} else {
logq = -Math.log(scale);
// which bit to scale
int index;
if (indicator != null) {
final int idim = indicator.getDimension();
final boolean impliedOne = idim == (dim - 1);
// available bit locations
int[] loc = new int[idim + 1];
int nLoc = 0;
// choose active or non active ones?
final boolean takeOne = indicatorOnProb >= 1.0 || MathUtils.nextDouble() < indicatorOnProb;
if (impliedOne && takeOne) {
loc[nLoc] = 0;
++nLoc;
}
for (int i = 0; i < idim; i++) {
final double value = indicator.getStatisticValue(i);
if (takeOne == (value > 0)) {
loc[nLoc] = i + (impliedOne ? 1 : 0);
++nLoc;
}
}
if (nLoc > 0) {
final int rand = MathUtils.nextInt(nLoc);
index = loc[rand];
} else {
throw new OperatorFailedException("no active indicators");
}
} else {
// any is good
index = MathUtils.nextInt(dim);
}
final double oldValue = variable.getValue(index);
if (oldValue == 0) {
Logger.getLogger("dr.inference").warning("The " + SCALE_OPERATOR +
" for " +
variable.getVariableName()
+ " has failed since the parameter has a value of 0.0." +
"\nTo fix this problem, initalize the value of " +
variable.getVariableName() + " to be a positive real number"
);
throw new OperatorFailedException("");
}
final double newValue = scale * oldValue;
if (newValue < bounds.getLowerLimit(index) || newValue > bounds.getUpperLimit(index)) {
throw new OperatorFailedException("proposed value outside boundaries");
}
variable.setValue(index, newValue);
// provides a hook for subclasses
cleanupOperation(newValue, oldValue);
}
return logq;
}
/**
* This method should be overridden by operators that need to do something just before the return of doOperation.
*
* @param newValue the proposed parameter value
* @param oldValue the old parameter value
*/
void cleanupOperation(double newValue, double oldValue) {
// DO NOTHING
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return "scale(" + variable.getVariableName() + ")";
}
public double getCoercableParameter() {
return Math.log(1.0 / scaleFactor - 1.0);
}
public void setCoercableParameter(double value) {
scaleFactor = 1.0 / (Math.exp(value) + 1.0);
}
public double getRawParameter() {
return scaleFactor;
}
public double getScaleFactor() {
return scaleFactor;
}
public double getTargetAcceptanceProbability() {
return 0.234;
}
public final String getPerformanceSuggestion() {
double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
double targetProb = getTargetAcceptanceProbability();
dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(5);
double sf = OperatorUtils.optimizeScaleFactor(scaleFactor, prob, targetProb);
if (prob < getMinimumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else if (prob > getMaximumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else return "";
}
public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
public String getParserName() {
return SCALE_OPERATOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final boolean scaleAll = xo.getAttribute(SCALE_ALL, false);
final boolean scaleAllInd = xo.getAttribute(SCALE_ALL_IND, false);
final int degreesOfFreedom = xo.getAttribute(DEGREES_OF_FREEDOM, 0);
final CoercionMode mode = CoercionMode.parseMode(xo);
final double weight = xo.getDoubleAttribute(WEIGHT);
final double scaleFactor = xo.getDoubleAttribute(SCALE_FACTOR);
if (scaleFactor <= 0.0 || scaleFactor >= 1.0) {
throw new XMLParseException("scaleFactor must be between 0.0 and 1.0");
}
final Parameter parameter = (Parameter) xo.getChild(Parameter.class);
Parameter indicator = null;
double indicatorOnProb = 1.0;
final XMLObject inds = xo.getChild(INDICATORS);
if (inds != null) {
indicator = (Parameter) inds.getChild(Parameter.class);
if (inds.hasAttribute(PICKONEPROB)) {
indicatorOnProb = inds.getDoubleAttribute(PICKONEPROB);
if (!(0 <= indicatorOnProb && indicatorOnProb <= 1)) {
throw new XMLParseException("pickoneprob must be between 0.0 and 1.0");
}
}
}
ScaleOperator operator = new ScaleOperator(parameter, scaleAll,
degreesOfFreedom, scaleFactor,
mode, indicator, indicatorOnProb,
scaleAllInd);
operator.setWeight(weight);
return operator;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.