answer stringlengths 17 10.2M |
|---|
package org.sourcepit.common.testing;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
/**
* @author Bernd
*/
public final class Environment
{
private static final Map<String, Environment> environments = new HashMap<String, Environment>();
public static Environment getSystem()
{
return get(null);
}
public static Environment get(String path)
{
synchronized (environments)
{
Environment environment = environments.get(path);
if (environment == null)
{
environment = newEnvironment(path);
environments.put(path, environment);
}
return environment;
}
}
public static Environment newEnvironment(String path)
{
final Properties properties = new Properties();
properties.putAll(System.getProperties());
if (path != null)
{
properties.putAll(loadProperties(path));
}
return newEnvironment(new LinkedHashMap<String, String>(System.getenv()), properties);
}
public static Environment newEnvironment(final Map<String, String> envs, final Properties properties)
{
for (Entry<Object, Object> entry : properties.entrySet())
{
String key = entry.getKey().toString();
if (key.startsWith("env.") && key.length() > 4)
{
key = key.substring(4);
final Object value = entry.getValue();
envs.put(key, value == null ? null : value.toString());
}
}
return new Environment(envs, properties);
}
private final Map<String, String> envs;
private final Properties properties;
private static Properties loadProperties(String path)
{
Properties properties = new Properties();
ClassLoader cl = Environment.class.getClassLoader();
InputStream is = cl.getResourceAsStream(path);
if (is != null)
{
try
{
try
{
properties.load(is);
}
finally
{
is.close();
}
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
return properties;
}
private Environment(Map<String, String> envs, Properties properties)
{
this.envs = envs;
this.properties = properties;
}
public Map<String, String> newEnvs()
{
final Map<String, String> envs = new LinkedHashMap<String, String>(this.envs);
final String javaagent = properties.getProperty("javaagent");
if (javaagent != null)
{
String mvnOpts = envs.get("MAVEN_OPTS");
if (mvnOpts == null)
{
mvnOpts = javaagent;
}
else
{
mvnOpts = (mvnOpts + " " + javaagent).trim();
}
envs.put("MAVEN_OPTS", mvnOpts);
}
return envs;
}
public Properties newProperties()
{
final Properties props = new Properties();
props.putAll(properties);
return props;
}
public String getProperty(String name)
{
return properties.getProperty(name);
}
public String getProperty(String name, String defaultValue)
{
return properties.getProperty(name, defaultValue);
}
public String getProperty(String name, boolean required)
{
final String value = properties.getProperty(name);
if (required && value == null)
{
throw new IllegalStateException("Property " + name + " is required but not set.");
}
return value;
}
public File getPropertyAsFile(String name)
{
final String path = getProperty(name, false);
if (path == null)
{
return null;
}
return new File(path);
}
public File getPropertyAsFile(String name, boolean required)
{
return new File(getProperty(name, required));
}
public File getUserHome()
{
return getPropertyAsFile("user.home", true);
}
public File getBuildDir()
{
return getPropertyAsFile("build.dir", true);
}
public File getResourcesDir()
{
return getPropertyAsFile("resources.dir", true);
}
public File getMavenHome()
{
String mvnHome = getProperty("maven.home");
if (mvnHome != null)
{
return new File(mvnHome);
}
mvnHome = getEnv("M3_HOME", "M2_HOME", "MVN_HOME", "MAVEN_HOME");
if (mvnHome != null)
{
return new File(mvnHome);
}
final String paths = envs.get("PATH");
if (paths != null)
{
final File mavenHome = getMavenHome(paths);
if (mavenHome != null)
{
return mavenHome;
}
}
return null;
}
private String getEnv(String... names)
{
for (String name : names)
{
String env = envs.get(name);
if (env != null)
{
return env;
}
}
return null;
}
private File getMavenHome(String paths)
{
final File m2ConfFile = findFileInPaths(paths, "m2.conf");
return m2ConfFile == null ? null : m2ConfFile.getParentFile().getParentFile();
}
private File findFileInPaths(String paths, final String name)
{
for (String path : paths.split(File.pathSeparator))
{
final File file = new File(path, name);
if (file.exists())
{
return file;
}
}
return null;
}
public boolean isDebugAllowed()
{
return Boolean.TRUE.toString().equals(getProperty("debug.allowed"));
}
public File getJavaHome()
{
return getPropertyAsFile("java.home", false);
}
} |
package reciter.database.dynamodb;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import org.apache.commons.lang3.StringUtils;
import org.socialsignin.spring.data.dynamodb.repository.config.EnableDynamoDBRepositories;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableDynamoDBRepositories
(basePackages = "reciter.database.dynamodb.repository")
public class DynamoDbConfig {
private String amazonDynamoDBEndpoint = System.getenv("AMAZON_DYNAMODB_ENDPOINT");
private String amazonAWSAccessKey = System.getenv("AMAZON_AWS_ACCESS_KEY");
private String amazonAWSSecretKey = System.getenv("AMAZON_AWS_SECRET_KEY");
@Bean
public AmazonDynamoDB amazonDynamoDB() {
AmazonDynamoDB amazonDynamoDB = new AmazonDynamoDBClient(amazonAWSCredentials());
if (!StringUtils.isEmpty(amazonDynamoDBEndpoint)) {
amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint);
}
return amazonDynamoDB;
}
@Bean
public AWSCredentials amazonAWSCredentials() {
return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey);
}
} |
package se.purplescout.pong.gui.server;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import se.purplescout.pong.game.Paddle;
import se.purplescout.pong.gui.client.paddle.classselector.PaddleCache;
import se.purplescout.pong.server.autofight.AutoFight;
import java.util.*;
public class HighScore extends GridPane {
public static final Font FONT = new Font(null, 30);
public static final int ROWS_PER_COL = 10;
private List<AutoFight> fights;
private OnPaddleRemovedListener onPaddleRemovedListener;
public HighScore() {
this.setVgap(10);
showNoFightsMessage();
}
public void setOnPaddleRemovedListener(OnPaddleRemovedListener onPaddleRemovedListener) {
this.onPaddleRemovedListener = onPaddleRemovedListener;
}
public void setFights(List<AutoFight> fights) {
this.fights = fights;
if (fights.isEmpty()) {
showNoFightsMessage();
} else {
SortedMap<Paddle, Integer> scores = calculateAndSortScoresForEachPaddle(fights);
renderPaddlesAndScores(scores);
}
}
private void showNoFightsMessage() {
Label noFightsMessage = new Label("Not enough paddles yet. Bring it ooooon!");
noFightsMessage.setFont(FONT);
noFightsMessage.setTextFill(Color.WHITE);
this.getChildren().clear();
this.getChildren().add(noFightsMessage);
}
private SortedMap<Paddle, Integer> calculateAndSortScoresForEachPaddle(Iterable<AutoFight> fights) {
Map<Paddle, Integer> unsortedScores = new HashMap<>();
for (AutoFight fight : fights) {
Integer leftScore = unsortedScores.get(fight.getLeftPaddle());
Integer rightScore = unsortedScores.get(fight.getRightPaddle());
if (leftScore == null) {
leftScore = 0;
}
if (rightScore == null) {
rightScore = 0;
}
leftScore += fight.getLeftScore();
rightScore += fight.getRightScore();
unsortedScores.put(fight.getLeftPaddle(), leftScore);
unsortedScores.put(fight.getRightPaddle(), rightScore);
}
SortedMap<Paddle, Integer> sortedScores = new TreeMap<>(new ValueComparator(unsortedScores));
sortedScores.putAll(unsortedScores);
return sortedScores;
}
private void renderPaddlesAndScores(SortedMap<Paddle, Integer> scores) {
this.getChildren().clear();
this.getRowConstraints().clear();
int x = 0;
int y = 0;
int place = 1;
for (final Map.Entry<Paddle, Integer> entry : scores.entrySet()) {
Label placeLabel = buildPlaceLabel(FONT, place);
Label name = buildTeamNameLabel(FONT, place, entry);
Label totalNumberOfWins = buildScoreLabel(FONT, entry);
Region fightDetails = buildFightDetailsFor(entry.getKey(), (removedPaddle) -> {
if (onPaddleRemovedListener != null) {
this.getChildren().clear();
onPaddleRemovedListener.paddleRemoved(entry.getKey());
}
});
final double realPref = fightDetails.getPrefHeight();
final RowConstraints fightDetailsRow = new RowConstraints(0);
fightDetails.setVisible(false);
name.setOnMouseClicked((event) -> {
fightDetails.setVisible(!fightDetails.isVisible());
if (fightDetails.isVisible()) {
fightDetailsRow.setPrefHeight(realPref);
} else {
fightDetailsRow.setPrefHeight(0);
}
});
this.add(placeLabel, x, y);
this.add(name, x + 1, y);
this.add(totalNumberOfWins, x + 2, y);
this.add(fightDetails, x, y + 1);
this.getRowConstraints().add(new RowConstraints());
this.getRowConstraints().add(fightDetailsRow);
GridPane.setColumnSpan(fightDetails, 3);
GridPane.setHalignment(placeLabel, HPos.RIGHT);
GridPane.setHgrow(placeLabel, Priority.ALWAYS);
GridPane.setHgrow(name, Priority.NEVER);
GridPane.setHgrow(totalNumberOfWins, Priority.ALWAYS);
y += 2;
if (false && y == ROWS_PER_COL) {
y = 0;
x += 3;
}
place++;
}
}
private Label buildPlaceLabel(Font font, int place) {
Label placeLabel = new Label("#" + place);
placeLabel.setTextFill(Color.GRAY);
placeLabel.setFont(font);
return placeLabel;
}
private Label buildTeamNameLabel(Font font, int place, Map.Entry<Paddle, Integer> entry) {
String teamName = entry.getKey().getTeamName();
Label name = new Label(teamName);
name.setTextFill(Color.WHITE);
name.setFont(font);
name.setStyle("-fx-padding: 0 1cm 0 5mm");
if (place == 1) {
name.setGraphic(new ImageView("se/purplescout/pong/gui/server/medal_gold.png"));
} else if (place == 2) {
name.setGraphic(new ImageView("se/purplescout/pong/gui/server/medal_silver.png"));
} else if (place == 3) {
name.setGraphic(new ImageView("se/purplescout/pong/gui/server/medal_bronze.png"));
}
return name;
}
private Label buildScoreLabel(Font font, Map.Entry<Paddle, Integer> entry) {
Label totalNumberOfWins = new Label(String.valueOf(entry.getValue()));
totalNumberOfWins.setTextFill(Color.WHITE);
totalNumberOfWins.setFont(font);
return totalNumberOfWins;
}
private Region buildFightDetailsFor(Paddle pov, OnPaddleRemovedListener onPaddleRemovedListener) {
GridPane fightGrid = new GridPane();
fightGrid.setAlignment(Pos.CENTER);
int column = 0;
// TODO: Sort fights according to something?
for (int i = 0; i < fights.size(); i++) {
AutoFight fight = fights.get(i);
if (fight.getLeftPaddle() == pov || fight.getRightPaddle() == pov) {
Paddle opponent = getOpponent(fight, pov);
Label opponentName = new Label(PaddleCache.getTeamName(opponent.getClass()));
opponentName.setTextFill(Color.WHITE);
Region result = getNodeFromFightState(fight, pov, opponent);
String resultRightBorderWidth = "0";
if (isPartOfRemainingFights(pov, i)) {
opponentName.setStyle("-fx-border-width: 0 0.5mm 0 0; -fx-border-style: solid; -fx-border-color: white;");
resultRightBorderWidth = "0.5mm";
}
opponentName.setStyle(opponentName.getStyle() + "-fx-padding: 1mm;");
result.setStyle("-fx-border-width: 0.5mm " +resultRightBorderWidth+ " 0 0; -fx-border-style: solid; -fx-border-color: white; -fx-padding: 1mm;");
GridPane.setHalignment(opponentName, HPos.CENTER);
GridPane.setHalignment(result, HPos.CENTER);
fightGrid.add(opponentName, column, 0);
fightGrid.add(result, column, 1);
column++;
}
}
alignCellWidths(fightGrid);
Label removeButton = new Label(null, new ImageView("se/purplescout/pong/gui/server/delete.png"));
removeButton.setOnMouseClicked((e) -> onPaddleRemovedListener.paddleRemoved(pov));
removeButton.setStyle("-fx-padding: 0 0 0 10mm;");
BorderPane root = new BorderPane(fightGrid);
root.setRight(removeButton);
return root;
}
private Label whiteLabel(String text) {
Label label = new Label(text);
label.setTextFill(Color.WHITE);
return label;
}
private boolean isPartOfRemainingFights(Paddle pov, int fromIndexExclusive) {
for (int i = fromIndexExclusive+1; i < fights.size(); i++) {
AutoFight fight = fights.get(i);
if (fight.getLeftPaddle() == pov || fight.getRightPaddle() == pov) {
return true;
}
}
return false;
}
private void alignCellWidths(GridPane grid) {
for (Node n: grid.getChildren()) {
if (n instanceof Control) {
Control control = (Control) n;
control.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
control.setStyle(control.getStyle() + "-fx-alignment: center;");
}
if (n instanceof Pane) {
Pane pane = (Pane) n;
pane.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
pane.setStyle(pane.getStyle() + "-fx-alignment: center;");
}
}
}
private Paddle getOpponent(AutoFight fight, Paddle pov) {
if (fight.getLeftPaddle() == pov) {
return fight.getRightPaddle();
} else {
return fight.getLeftPaddle();
}
}
private Region getNodeFromFightState(AutoFight fight, Paddle pov, Paddle opponent) {
switch (fight.getState()) {
case BEFORE_FIGHT:
return whiteLabel("Not fighting yet");
case FIGHTING:
return whiteLabel("Fighting...");
case DONE_FIGHTING:
return döneFajtäng(fight, pov, opponent);
}
return whiteLabel("?");
}
private Region döneFajtäng(AutoFight fight, Paddle pov, Paddle opponent) {
boolean povIsLeft = fight.getLeftPaddle() == pov;
switch (fight.getResult()) {
case FIGHT_TOOK_TOO_LONG:
return whiteLabel("Fight took too long");
case LEFT_PADDLE_THREW_EXCEPTION:
if (povIsLeft) {
return whiteLabel("You threw an exception");
} else {
return whiteLabel("Opponent threw an exception");
}
case LEFT_PADDLE_TOOK_TOO_LONG:
if (povIsLeft) {
return whiteLabel("You were too slow");
} else {
return whiteLabel("Opponent was too slow");
}
case RIGHT_PADDLE_THREW_EXCEPTION:
if (povIsLeft) {
return whiteLabel("Opponent threw an exception");
} else {
return whiteLabel("You threw an exception");
}
case RIGHT_PADDLE_TOOK_TOO_LONG:
if (povIsLeft) {
return whiteLabel("Opponent was too slow");
} else {
return whiteLabel("You were too slow");
}
case SUCCESS:
String s;
if (povIsLeft) {
s = fight.getLeftScore() + " - " + fight.getRightScore();
} else {
s = fight.getRightScore() + " - " + fight.getLeftScore();
}
return whiteLabel(s);
case UNDETERMINED:
// Only valid if fight.getState() != DONE_FIGHTING which is handled in getNodeFromFightState
return whiteLabel("N/A");
case UNKNOWN_ERROR:
return whiteLabel("Unknown error");
}
return whiteLabel("??");
}
private static class ValueComparator implements Comparator<Paddle> {
Map<Paddle, Integer> base;
public ValueComparator(Map<Paddle, Integer> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(Paddle a, Paddle b) {
Integer valueA = base.get(a);
Integer valueB = base.get(b);
if (valueA == null) {
return 1;
}
if (valueB == null) {
return -1;
}
int scoreDiff = valueB - valueA;
if (scoreDiff == 0) {
return PaddleCache.getTeamName(a.getClass()).compareTo(PaddleCache.getTeamName(b.getClass()));
}
return scoreDiff;
}
}
public static interface OnPaddleRemovedListener {
void paddleRemoved(Paddle paddle);
}
} |
package se.su.it.svc.server.log;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.RequestLog;
import org.eclipse.jetty.server.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CommonRequestLog implements RequestLog {
static final Logger logger = LoggerFactory.getLogger("RequestLog");
boolean started = false;
@Override
public void log(Request request, Response response) {
StringBuilder buf = new StringBuilder();
buf.append(request.getServerName());
buf.append(" ");
String addr = request.getHeader(HttpHeaders.X_FORWARDED_FOR);
if (addr == null)
addr = request.getRemoteAddr();
buf.append(addr);
buf.append(" - ");
buf.append(getUserPrincipal(request));
buf.append(" [").append(request.getTimeStampBuffer().toString()).append("] ");
buf.append("\"");
buf.append(request.getMethod());
buf.append(' ');
buf.append(request.getUri().toString());
buf.append(' ');
buf.append(request.getProtocol());
buf.append("\" ");
buf.append(getStatus(request, response));
buf.append(" ").append(getResponseLength(response)).append(" ");
logger.info(buf.toString());
}
protected String getUserPrincipal(Request request) {
String user = "-";
Authentication authentication = request.getAuthentication();
if (authentication instanceof Authentication.User)
user = ((Authentication.User) authentication).getUserIdentity().getUserPrincipal().getName();
return user;
}
protected String getStatus(Request request, Response response) {
StringBuilder buf = new StringBuilder();
if (request.getAsyncContinuation().isInitial()) {
int status = response.getStatus();
if (status <= 0)
status = 404;
buf.append((char) ('0' + ((status / 100) % 10)));
buf.append((char) ('0' + ((status / 10) % 10)));
buf.append((char) ('0' + (status % 10)));
} else
buf.append("Async");
return buf.toString();
}
protected String getResponseLength(Response response) {
StringBuilder buf = new StringBuilder();
long responseLength = response.getContentCount();
if (responseLength >= 0)
buf.append(responseLength);
else
buf.append("-");
return buf.toString();
}
@Override
public void start() throws Exception {
started = true;
}
@Override
public void stop() throws Exception {
started = false;
}
@Override
public boolean isRunning() {
return started;
}
@Override
public boolean isStarted() {
return started;
}
@Override
public boolean isStarting() {
return false;
}
@Override
public boolean isStopping() {
return false;
}
@Override
public boolean isStopped() {
return !started;
}
@Override
public boolean isFailed() {
return false;
}
@Override
public void addLifeCycleListener(Listener listener) {
// Not yet implemented
}
@Override
public void removeLifeCycleListener(Listener listener) {
// Not yet implemented
}
} |
package seedu.address.logic.commands;
import java.util.logging.Logger;
import seedu.address.commons.core.EventsCenter;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.item.Item;
import seedu.address.model.item.ReadOnlyItem;
import seedu.address.model.item.UniquePersonList;
import seedu.address.model.item.UniquePersonList.PersonNotFoundException;
/**
* Edits an item identified using it's last displayed index from the task manager.
*/
public class EditCommand extends Command {
private static final Logger logger = LogsCenter.getLogger(EditCommand.class);
public static final String COMMAND_WORD = "edit";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Edits the item identified by the index number used in the last item listing.\n"
+ "Parameters: INDEX (must be a positive integer)" + " n/NAME" + "\n"
+ "Example: " + COMMAND_WORD + " 1" + " n/buy milk";
public static final String MESSAGE_EDIT_ITEM_SUCCESS = "Edited Item: %1$s";
public final int targetIndex;
public final String newName;
public final String newEndDate;
public EditCommand(int targetIndex, String name, String startDate, String startTime, String endDate, String endTime)
throws IllegalValueException {
this.targetIndex = targetIndex;
this.newName = name;
this.newEndDate = endDate;
logger.info("EditCommand object successfully created!");
}
@Override
public CommandResult execute() {
UnmodifiableObservableList<ReadOnlyItem> lastShownList = model.getFilteredPersonList();
if (lastShownList.size() < targetIndex) {
indicateAttemptToExecuteIncorrectCommand();
return new CommandResult(Messages.MESSAGE_INVALID_ITEM_DISPLAYED_INDEX);
}
ReadOnlyItem itemToEdit = lastShownList.get(targetIndex - 1);
Item itemToReplace = new Item(itemToEdit);
try {
if (newName != null) {
itemToReplace.setName(newName);
} else if (newEndDate != null) {
itemToReplace.setEndDate(newEndDate);
}
} catch (IllegalValueException ive) {
return new CommandResult(ive.getMessage());
}
try {
model.replaceItem(itemToEdit, itemToReplace);
} catch (PersonNotFoundException pnfe) {
assert false : "The target item cannot be missing";
} catch (UniquePersonList.DuplicatePersonException e) {
return new CommandResult(MESSAGE_DUPLICATE_ITEM);
}
return new CommandResult(String.format(MESSAGE_EDIT_ITEM_SUCCESS, itemToReplace));
}
} |
package seedu.address.logic.commands;
/**
* Lists all tasks in the uTask to the user.
*/
public class ListCommand extends Command {
public static final String COMMAND_WORD = "list";
public static final String MESSAGE_SUCCESS = "Listed all tasks";
@Override
public CommandResult execute() {
model.updateFilteredListToShowAll();
return new CommandResult(MESSAGE_SUCCESS);
}
} |
package seedu.emeraldo.model.task;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
//@@author A0139749L
/**
* Parses the date and time, and check for the validity of the inputs
*/
public class DateTimeParser {
public static final String ON_KEYWORD_VALIDATION_REGEX = "on "
+ "(?<day>(0?[1-9]|[12][0-9]|3[01]))"
+ "(?:( |/|-))"
+ "(?<monthInNumbers>([0][1-9]|[1][0-2])?)"
+ "(?<monthInWords>([\\p{Alpha}]{3,})?)"
+ "(?<year>(( |/|-)(([0-9][0-9])?[0-9][0-9]))?)";
public static final String BY_KEYWORD_VALIDATION_REGEX = "by "
+ "(?<day>(0?[1-9]|[12][0-9]|3[01]))"
+ "(?:( |/|-))"
+ "(?<monthInNumbers>([0][1-9]|[1][0-2])?)"
+ "(?<monthInWords>([\\p{Alpha}]{3,})?)"
+ "(?<year>(( |/|-)(([0-9][0-9])?[0-9][0-9]))?)"
+ "(\\s*,\\s*(?<hour>([01][0-9]|[2][0-3])))"
+ "(:(?<minute>([0-5][0-9])))";
public static final String FROM_KEYWORD_VALIDATION_REGEX = "from "
+ "(?<day>(0?[1-9]|[12][0-9]|3[01]))"
+ "(?:( |/|-))"
+ "(?<monthInNumbers>([0][1-9]|[1][0-2])?)"
+ "(?<monthInWords>([\\p{Alpha}]{3,})?)"
+ "(?<year>(( |/|-)(([0-9][0-9])?[0-9][0-9]))?)"
+ "(\\s*,\\s*(?<hour>([01][0-9]|[2][0-3])))"
+ "(:(?<minute>([0-5][0-9])))"
+ "( (?<aftKeyword>(to )))"
+ "(?<dayEnd>(0?[1-9]|[12][0-9]|3[01]))"
+ "(?:( |/|-))"
+ "(?<monthEndInNumbers>([0][1-9]|[1][0-2])?)"
+ "(?<monthEndInWords>([\\p{Alpha}]{3,})?)"
+ "(?<yearEnd>(( |/|-)(([0-9][0-9])?[0-9][0-9]))?)"
+ "(\\s*,\\s*(?<hourEnd>([01][0-9]|[2][0-3])))"
+ "(:(?<minuteEnd>([0-5][0-9])))";
public static final Pattern DATETIME_VALIDATION_REGEX = Pattern.compile(
"(?<preKeyword>((by )|(on )|(from )))"
+ "(?<day>(0?[1-9]|[12][0-9]|3[01]))"
+ "(?:( |/|-))"
+ "(?<monthInNumbers>([0][1-9]|[1][0-2])?)"
+ "(?<monthInWords>([\\p{Alpha}]{3,})?)"
+ "(?<year>(( |/|-)(([0-9][0-9])?[0-9][0-9]))?)"
+ "(\\s*,\\s*(?<hour>([01][0-9]|[2][0-3])))?"
+ "(:(?<minute>([0-5][0-9])))?"
+ "( (?<aftKeyword>(to )))?"
+ "(?<dayEnd>(0?[1-9]|[12][0-9]|3[01]))?"
+ "(?:( |/|-)?)"
+ "(?<monthEndInNumbers>([0][1-9]|[1][0-2])?)"
+ "(?<monthEndInWords>([\\p{Alpha}]{3,})?)"
+ "(?<yearEnd>(( |/|-)(([0-9][0-9])?[0-9][0-9]))?)"
+ "(\\s*,\\s*(?<hourEnd>([01][0-9]|[2][0-3])))?"
+ "(:(?<minuteEnd>([0-5][0-9])))?"
);
private static final String MESSAGE_INVALID_MONTH_IN_WORDS = "Invalid month! Check your spelling";
/*
* TODO: LocalDate.of() throws DateTimeException for out of range field and invalid
* day-of-month for the month-year
*
* Format the date for creation of LocalDate object
*/
public static LocalDate valueDateFormatter(Matcher matcher, String keyword) throws IllegalValueException{
String day = matcher.group("day");
String month = matcher.group("monthInNumbers");
String year = matcher.group("year");
int yearParsed;
int monthParsed;
int dayParsed;
if(keyword.equals("to")){
day = matcher.group("dayEnd");
month = matcher.group("monthEndInNumbers");
year = matcher.group("yearEnd");
}
//TODO: catch monthWords and monthEndWords that are shorter than 3 characters
if(month.isEmpty()){
month = matcher.group("monthInWords").toLowerCase().substring(0,3);
if(keyword.equals("to"))
month = matcher.group("monthEndInWords").toLowerCase().substring(0,3);
month = convertMonthFromWordsToNumbers(month);
}
if(year.isEmpty())
yearParsed = LocalDate.now().getYear();
else{
year = year.substring(1);
if(Integer.parseInt(year) < 100) //For years that are input with only the last 2 digits
yearParsed = Integer.parseInt(String.valueOf(LocalDate.now().getYear()).substring(0, 2) + year);
else
yearParsed = Integer.parseInt(year);
}
monthParsed = Integer.parseInt(month);
dayParsed = Integer.parseInt(day);
return LocalDate.of(yearParsed, monthParsed, dayParsed);
}
/*
* TODO: LocalTime.of() throws DateTimeException for out of range field
* i.e. hours from 0 to 23 and min from 0 to 59
*
* Format the time for creating a LocalTime object
*/
public static LocalTime valueTimeFormatter(Matcher matcher, String keyword){
String hour = matcher.group("hour");
String minute = matcher.group("minute");
if(keyword.equals("to")){
hour = matcher.group("hourEnd");
minute = matcher.group("minuteEnd");
}
int hourParsed = Integer.parseInt(hour);
int minuteParsed = Integer.parseInt(minute);
return LocalTime.of(hourParsed, minuteParsed);
}
/*
* Formats the date and time for display
*/
public static String valueFormatter(Matcher matcher, String keyword) throws IllegalValueException{
String day = matcher.group("day");
String month = matcher.group("monthInNumbers");
String year = matcher.group("year");
String hour = matcher.group("hour");
String minute = matcher.group("minute");
if(keyword.equals("to")){
day = matcher.group("dayEnd");
month = matcher.group("monthEndInNumbers");
year = matcher.group("yearEnd");
hour = matcher.group("hourEnd");
minute = matcher.group("minuteEnd");
}
//Append the leading '0' if not present
if(Integer.parseInt(day) < 10 && day.length() == 1)
day = "0" + day;
//Check for month in words when month not in numbers
if(month.isEmpty()){
month = matcher.group("monthInWords").toLowerCase().substring(0,3);
if(keyword.equals("to"))
month = matcher.group("monthEndInWords").toLowerCase().substring(0,3);
month = convertMonthFromWordsToNumbers(month);
}
int monthParsed = Integer.parseInt(month);
//If no year is read in, the year will be current year
if(year.isEmpty())
year = String.valueOf(LocalDate.now().getYear());
else
year = year.substring(1);
if (Integer.parseInt(year) < 100) //For years that are input with only the last 2 digits
year = String.valueOf(LocalDate.now().getYear()).substring(0, 2) + year;
if(keyword.equals("on"))
return keyword + " " + day + " " + convertMonthFromIntToWords(monthParsed) + " " + year;
else{
return keyword + " " + day + " " + convertMonthFromIntToWords(monthParsed) + " "
+ year + ", " + hour + ":" + minute;
}
}
private static String convertMonthFromIntToWords(int monthParsed){
String monthInWords;
switch(monthParsed){
case 1:
monthInWords = "Jan";
break;
case 2:
monthInWords = "Feb";
break;
case 3:
monthInWords = "Mar";
break;
case 4:
monthInWords = "Apr";
break;
case 5:
monthInWords = "May";
break;
case 6:
monthInWords = "Jun";
break;
case 7:
monthInWords = "Jul";
break;
case 8:
monthInWords = "Aug";
break;
case 9:
monthInWords = "Sep";
break;
case 10:
monthInWords = "Oct";
break;
case 11:
monthInWords = "Nov";
break;
case 12:
monthInWords = "Dec";
break;
default: monthInWords = "Invalid month";
}
return monthInWords;
}
//TODO: throws exception if month is not of a valid form
private static String convertMonthFromWordsToNumbers(String monthInWords) throws IllegalValueException{
String monthInNumbers;
switch(monthInWords){
case "jan":
monthInNumbers = "1";
break;
case "feb":
monthInNumbers = "2";
break;
case "mar":
monthInNumbers = "3";
break;
case "apr":
monthInNumbers = "4";
break;
case "may":
monthInNumbers = "5";
break;
case "jun":
monthInNumbers = "6";
break;
case "jul":
monthInNumbers = "7";
break;
case "aug":
monthInNumbers = "8";
break;
case "sep":
monthInNumbers = "9";
break;
case "oct":
monthInNumbers = "10";
break;
case "nov":
monthInNumbers = "11";
break;
case "dec":
monthInNumbers = "12";
break;
default:
throw new IllegalValueException(MESSAGE_INVALID_MONTH_IN_WORDS);
}
return monthInNumbers;
}
} |
package com.malhartech.util;
import java.io.Serializable;
public class Pair<F, S> implements Serializable
{
private static final long serialVersionUID = 731157267102567944L;
public final F first;
public final S second;
@Override
public int hashCode()
{
int hash = 7;
hash = 41 * hash + (this.first != null ? this.first.hashCode() : 0);
hash = 41 * hash + (this.second != null ? this.second.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj)
{
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("unchecked")
final Pair<F, S> other = (Pair<F, S>)obj;
if (this.first != other.first && (this.first == null || !this.first.equals(other.first))) {
return false;
}
if (this.second != other.second && (this.second == null || !this.second.equals(other.second))) {
return false;
}
return true;
}
public Pair(F first, S second)
{
this.first = first;
this.second = second;
}
public F getFirst()
{
return first;
}
public S getSecond()
{
return second;
}
@Override
public String toString()
{
return "[" + first + "," + second + "]";
}
} |
package seedu.ezdo.commons.util;
import java.util.Optional;
import java.util.Set;
import seedu.ezdo.model.todo.Priority;
import seedu.ezdo.model.todo.TaskDate;
//@@author A0141010L
public class SearchParameters {
private Set<String> namesToCompare;
private Optional<Priority> priorityToCompare;
private Optional<TaskDate> startDateToCompare;
private Optional<TaskDate> dueDateToCompare;
private Set<String> tagsToCompare;
private boolean startBefore = false;
private boolean dueBefore = false;
private boolean startAfter = false;
private boolean dueAfter = false;
public Set<String> getNames() {
return namesToCompare;
}
public Optional<Priority> getPriority() {
return priorityToCompare;
}
public Optional<TaskDate> getStartDate() {
return startDateToCompare;
}
public Optional<TaskDate> getDueDate() {
return dueDateToCompare;
}
public Set<String> getTags() {
return tagsToCompare;
}
public boolean getStartBefore() {
return startBefore;
}
public boolean getdueBefore() {
return dueBefore;
}
public boolean getStartAfter() {
return startAfter;
}
public boolean getDueAfter() {
return dueAfter;
}
public static class Builder {
private Set<String> namesToCompare;
private Optional<Priority> priorityToCompare;
private Optional<TaskDate> startDateToCompare;
private Optional<TaskDate> dueDateToCompare;
private Set<String> tagsToCompare;
private boolean startBefore = false;
private boolean dueBefore = false;
private boolean startAfter = false;
private boolean dueAfter = false;
public Builder() {
}
public Builder name(Set<String> names) {
namesToCompare = names;
return this;
}
public Builder priority(Optional<Priority> priority) {
priorityToCompare = priority;
return this;
}
public Builder startDate(Optional<TaskDate> findStartDate) {
startDateToCompare = findStartDate;
return this;
}
public Builder dueDate(Optional<TaskDate> dueDate) {
dueDateToCompare = dueDate;
return this;
}
public Builder tags(Set<String> tags) {
tagsToCompare = tags;
return this;
}
public Builder startBefore(boolean before) {
startBefore = before;
return this;
}
public Builder dueBefore(boolean before) {
dueBefore = before;
return this;
}
public Builder startAfter(boolean after) {
startAfter = after;
return this;
}
public Builder dueAfter(boolean after) {
dueAfter = after;
return this;
}
public SearchParameters build() {
return new SearchParameters(this);
}
}
private SearchParameters(Builder builder) {
namesToCompare = builder.namesToCompare;
priorityToCompare = builder.priorityToCompare;
startDateToCompare = builder.startDateToCompare;
dueDateToCompare = builder.dueDateToCompare;
tagsToCompare = builder.tagsToCompare;
startBefore = builder.startBefore;
dueBefore = builder.dueBefore;
startAfter = builder.startAfter;
dueAfter = builder.dueAfter;
}
} |
package seedu.malitio.logic.commands;
import java.util.Set;
//@@author a0126633j
/**
* Finds and lists tasks from the last shown list whose name or tags or date/time contains any of the argument keywords.
* Keyword matching is case insensitive.
*/
public class FindCommand extends Command {
public static final String COMMAND_WORD = "find";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds [specified] tasks whose names contain any of "
+ "the specified keywords and displays them as a list with index numbers.\n"
+ "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
+ "Example: " + COMMAND_WORD + " [f/d/e] adjust bring chill";
private static final String FLOATING_TASK_KEYWORD = "f";
private static final String DEADLINE_KEYWORD = "d";
private static final String EVENT_KEYWORD = "e";
private final Set<String> keywords;
private final String typeOfTask;
public FindCommand(String type, Set<String> keywords) {
this.keywords = keywords;
this.typeOfTask = type;
}
@Override
public CommandResult execute() {
switch (typeOfTask) {
case FLOATING_TASK_KEYWORD:
model.updateFilteredTaskList(keywords);
return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredFloatingTaskList().size()));
case DEADLINE_KEYWORD:
model.updateFilteredDeadlineList(keywords);
return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredDeadlineList().size()));
case EVENT_KEYWORD:
model.updateFilteredEventList(keywords);
return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredEventList().size()));
default: //find in all lists
model.updateFilteredTaskList(keywords);
model.updateFilteredDeadlineList(keywords);
model.updateFilteredEventList(keywords);
return new CommandResult(getMessageForTaskListShownSummary(
model.getFilteredFloatingTaskList().size() +
model.getFilteredDeadlineList().size() +
model.getFilteredEventList().size()));
}
}
} |
package org.apache.jmeter.gui.action;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import org.apache.jmeter.gui.GuiPackage;
import org.apache.jmeter.swing.HtmlPane;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.gui.ComponentUtil;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
public class Help implements Command
{
transient private static Logger log = LoggingManager.getLoggerForClass();
public final static String HELP = "help";
private static Set commands = new HashSet();
public static final String HELP_PAGE =
"file:
+ JMeterUtils.getJMeterHome()
+ "/printable_docs/usermanual/component_reference.html";
private static JDialog helpWindow;
private static HtmlPane helpDoc;
private static JScrollPane scroller;
private static String currentPage;
static
{
commands.add(HELP);
helpDoc = new HtmlPane();
scroller = new JScrollPane(helpDoc);
helpDoc.setEditable(false);
try
{
helpDoc.setPage(HELP_PAGE);
currentPage = HELP_PAGE;
}
catch (IOException err)
{
String msg = "Couldn't load help file " + err.toString();
log.error(msg);
helpDoc.setText(msg);
currentPage="";// Avoid NPE in resetPage()
}
}
/**
* @see org.apache.jmeter.gui.action.Command#doAction(ActionEvent)
*/
public void doAction(ActionEvent e)
{
if (helpWindow == null)
{
helpWindow =
new JDialog(
new Frame(),// independent frame to allow it to be overlaid by the main frame
JMeterUtils.getResString("help"),//$NON-NLS-1$
false);
helpWindow.getContentPane().setLayout(new GridLayout(1, 1));
ComponentUtil.centerComponentInWindow(helpWindow, 60);
}
helpWindow.getContentPane().removeAll();
helpWindow.getContentPane().add(scroller);
helpWindow.show();
if (e.getSource() instanceof String[])
{
String[] source = (String[]) e.getSource();
resetPage(source[0]);
helpDoc.scrollToReference(source[1]);
}
else
{
resetPage(HELP_PAGE);
helpDoc.scrollToReference(
GuiPackage
.getInstance()
.getTreeListener()
.getCurrentNode()
.getStaticLabel()
.replace(' ', '_'));
}
}
private void resetPage(String source)
{
if (!currentPage.equals(source))
{
if (currentPage.length()==0){
helpDoc = new HtmlPane();// setText seems to mangle the old one
scroller.setViewportView(helpDoc);
helpDoc.setEditable(false);
//TODO: still does not recover completely, but is usable
// and unlikely to be needed now that HELP_PAGE is shared string
}
try
{
helpDoc.setPage(source);
currentPage = source;
}
catch (IOException err)
{
String msg = "Couldn't load page " + source + " " + err.toString();
log.error(msg);
helpDoc.setText(msg);
currentPage="";
}
}
}
/**
* @see org.apache.jmeter.gui.action.Command#getActionNames()
*/
public Set getActionNames()
{
return commands;
}
} |
package seedu.tasklist.logic.commands;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import seedu.tasklist.commons.exceptions.IllegalValueException;
import seedu.tasklist.logic.commands.exceptions.CommandException;
import seedu.tasklist.model.tag.Tag;
import seedu.tasklist.model.tag.UniqueTagList;
import seedu.tasklist.model.task.Comment;
import seedu.tasklist.model.task.FloatingTask;
import seedu.tasklist.model.task.Name;
import seedu.tasklist.model.task.Priority;
import seedu.tasklist.model.task.Status;
import seedu.tasklist.model.task.Task;
import seedu.tasklist.model.task.UniqueTaskList;
/**
* Adds a task to the task list.
*/
public class AddCommand extends Command {
public static final String COMMAND_WORD = "add";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a task to the task list. "
+ "Parameters: TASK NAME c/COMMENT [t/TAG]...\n"
+ "Example: " + COMMAND_WORD
+ " Do this c/updated comment here t/friends t/owesMoney";
public static final String MESSAGE_SUCCESS = "New task added: %1$s";
public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the task list";
private final Task toAdd;
public AddCommand(String name, List<Date> dates, Optional<String> comment,
Optional<String> priority, Set<String> tags) throws IllegalValueException {
final Set<Tag> tagSet = new HashSet<>();
for (String tagName : tags) {
tagSet.add(new Tag(tagName));
}
//Checks if it is a FloatingTask
if (isDateEmpty(dates)) {
this.toAdd = new FloatingTask(
new Name(name),
new Comment(comment),
new Priority(priority),
new Status(),
new UniqueTagList(tagSet)
);
} else {
//Temporary to remove errors before deadlines and events are added
this.toAdd = null;
}
}
/**
* Returns true if dates are present. Used to check for FloatingTask
*/
public boolean isDateEmpty(List<Date> dates) {
return dates.isEmpty();
}
@Override
public CommandResult execute() throws CommandException {
assert model != null;
try {
model.addTask(toAdd);
return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd));
} catch (UniqueTaskList.DuplicateTaskException e) {
throw new CommandException(MESSAGE_DUPLICATE_TASK);
}
}
} |
package selling.sunshine.schedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import selling.sunshine.service.RefundService;
public class RefundSchedule {
private Logger logger = LoggerFactory.getLogger(PoolSchedule.class);
@Autowired
private RefundService refundService;
public void schedule() {
refundService.refund();
}
} |
package sib.swiss.swissprot;
import org.openjdk.jmh.annotations.*;
import java.nio.ByteBuffer;
import java.util.Random;
@State(Scope.Thread)
public class MyBenchmark {
private static final int size = 2 * 1024 * 1024;
private ByteBuffer dna;
@Setup
public void setUp(){
dna = ByteBuffer.allocateDirect(size);
Random random = new Random();
for (int i=0;i<size;i++) {
float next = random.nextFloat();
if (next < 0.3) {
dna.put((byte) 'a');
} else if (next < 0.3) {
dna.put((byte) 't');
} else if (next < 0.8) {
dna.put((byte) 'c');
} else if (next < 0.99) {
dna.put((byte) 'g');
} else {
dna.put((byte) 'n');
}
}
}
@TearDown
public void tearDown(){
dna=null;
}
@Benchmark
public int testMethod() {
int a=0,c=0,g=0,t =0,n =0;
for (int i=0;i<size;i++)
{
char nucleotide = (char) dna.get(i);
if (nucleotide == 'a')
a++;
if (nucleotide == 'c')
c++;
if (nucleotide == 't')
t++;
if (nucleotide == 'g')
g++;
if (nucleotide == 'n')
n++;
}
return a+c+g+t+n;
}
@Benchmark
public int testUsingArray() {
int []nucleotides=new int[256];
for (int i=0;i<size;i++)
{
byte nucleotide = dna.get(i);
nucleotides[nucleotide]++;
}
return nucleotides['a']+nucleotides['c']+nucleotides['g']+nucleotides['t']+nucleotides['n'];
}
} |
package top.quantic.sentry.service.util;
import de.androidpit.colorthief.ColorThief;
import de.androidpit.colorthief.MMCQ;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URL;
import static top.quantic.sentry.service.util.Inflection.pluralize;
import static top.quantic.sentry.service.util.Inflection.singularize;
public class MiscUtil {
private static final Logger log = LoggerFactory.getLogger(MiscUtil.class);
public static String humanizeBytes(long bytes) {
int unit = 1000; // 1024 for non-SI units
if (bytes < unit)
return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), "kMGTPE".charAt(exp - 1));
}
public static String inflect(long value, String label) {
return value + " " + (value == 1 ? singularize(label) : pluralize(label));
}
public static Color getDominantColor(String urlStr, Color fallback) {
try {
return getDominantColor(ImageIO.read(new URL(urlStr.replace(".webp", ".jpg")))); // hack for now
} catch (Exception e) {
log.debug("Could not process {}: {}", urlStr, e.toString());
}
return fallback;
}
public static Color getDominantColor(InputStream input, Color fallback) {
try {
return getDominantColor(ImageIO.read(input));
} catch (Exception e) {
log.debug("Could not process from stream: {}", e.toString());
}
return fallback;
}
public static Color getDominantColor(BufferedImage image) {
MMCQ.CMap result = ColorThief.getColorMap(image, 5);
MMCQ.VBox vBox = result.vboxes.get(0);
int[] rgb = vBox.avg(false);
return new Color(rgb[0], rgb[1], rgb[2]);
}
public static InetSocketAddress getSourceServerAddress(String address) {
int port = 0;
if (address.indexOf(':') >= 0) {
String[] tmpAddress = address.split(":", 2);
port = Integer.parseInt(tmpAddress[1]);
address = tmpAddress[0];
}
if (port == 0) {
port = 27015;
}
return new InetSocketAddress(address, port);
}
public static String getIPAddress(String address) {
if (address.indexOf(':') >= 0) {
String[] tmpAddress = address.split(":", 2);
address = tmpAddress[0];
}
return address;
}
private MiscUtil() {
}
} |
package de.jungblut.math.cuda;
import java.util.Random;
import jcuda.Pointer;
import jcuda.Sizeof;
import jcuda.jcublas.JCublas2;
import jcuda.jcublas.cublasHandle;
import jcuda.jcublas.cublasOperation;
import jcuda.jcublas.cublasPointerMode;
import jcuda.runtime.JCuda;
import jcuda.runtime.cudaDeviceProp;
import jcuda.runtime.cudaMemcpyKind;
import de.jungblut.math.DenseDoubleMatrix;
// -Djava.library.path="/lib/;${env_var:PATH}" must be added to the running VM
public class JCUDAMatrixUtils {
public static boolean CUDA_AVAILABLE = false;
static {
try {
// Disable exceptions and omit subsequent error checks
JCublas2.setExceptionsEnabled(true);
JCuda.setExceptionsEnabled(true);
cudaDeviceProp cudaDeviceProp = new cudaDeviceProp();
JCuda.cudaGetDeviceProperties(cudaDeviceProp, 0);
// actually here is only cublas2 available.
if (Integer.parseInt(cudaDeviceProp.getName().replaceAll("[^\\d]", "")) > 400) {
JCublas2.initialize();
CUDA_AVAILABLE = true;
System.out
.println("Using device " + cudaDeviceProp.getName()
+ " with total RAM of " + cudaDeviceProp.totalGlobalMem
+ " bytes!");
}
} catch (Throwable e) {
// e.printStackTrace();
System.out.println(e.getLocalizedMessage());
}
}
// TODO transpose can be actually done on GPU as well
public static DenseDoubleMatrix multiply(DenseDoubleMatrix a,
DenseDoubleMatrix b) {
Pointer matrixPointerA = memcpyMatrix(a);
Pointer matrixPointerB = memcpyMatrix(b);
// Prepare the pointer for the result in DEVICE memory
Pointer deviceResultPointer = new Pointer();
int resMatrixSize = a.getRowCount() * b.getColumnCount();
JCuda.cudaMalloc(deviceResultPointer, Sizeof.DOUBLE * resMatrixSize);
Pointer alpha = new Pointer();
JCuda.cudaMalloc(alpha, Sizeof.DOUBLE);
JCuda.cudaMemcpy(alpha, Pointer.to(new double[] { 1.0d }), Sizeof.DOUBLE,
cudaMemcpyKind.cudaMemcpyHostToDevice);
Pointer beta = new Pointer();
JCuda.cudaMalloc(beta, Sizeof.DOUBLE);
JCuda.cudaMemcpy(beta, Pointer.to(new double[] { 0.0d }), Sizeof.DOUBLE,
cudaMemcpyKind.cudaMemcpyHostToDevice);
cublasHandle handle = new cublasHandle();
JCublas2.cublasCreate(handle);
JCublas2.cublasSetPointerMode(handle,
cublasPointerMode.CUBLAS_POINTER_MODE_DEVICE);
JCublas2.cublasDgemm(handle, cublasOperation.CUBLAS_OP_N,
cublasOperation.CUBLAS_OP_N, a.getRowCount(), b.getColumnCount(),
a.getColumnCount(), alpha, matrixPointerA, a.getRowCount(),
matrixPointerB, b.getRowCount(), beta, deviceResultPointer,
a.getRowCount());
System.out.println(JCuda.cudaGetErrorString(JCuda.cudaGetLastError()));
JCuda.cudaDeviceSynchronize();
DenseDoubleMatrix matrix = getMatrix(deviceResultPointer, a.getRowCount(),
b.getColumnCount());
freePointer(matrixPointerA);
freePointer(matrixPointerB);
freePointer(deviceResultPointer);
cublasDestroy(handle);
return matrix;
}
private static Pointer memcpyMatrix(DenseDoubleMatrix a) {
int matrixSizeA = a.getColumnCount() * a.getRowCount();
double[] matrix = new double[matrixSizeA];
// store in column major format
for (int i = 0; i < a.getColumnCount(); i++) {
double[] column = a.getColumn(i);
System.arraycopy(column, 0, matrix, i * column.length, column.length);
}
Pointer deviceMatrixA = new Pointer();
JCuda.cudaMalloc(deviceMatrixA, matrixSizeA * Sizeof.DOUBLE);
JCublas2.cublasSetMatrix(a.getRowCount(), a.getColumnCount(),
Sizeof.DOUBLE, Pointer.to(matrix), a.getRowCount(), deviceMatrixA,
a.getRowCount());
return deviceMatrixA;
}
private static DenseDoubleMatrix getMatrix(Pointer src, int rows, int columns) {
double[] raw = new double[rows * columns];
Pointer dst = Pointer.to(raw);
JCublas2
.cublasGetMatrix(rows, columns, Sizeof.DOUBLE, src, rows, dst, rows);
return new DenseDoubleMatrix(raw, rows, columns);
}
// seems to have problems with latest CUDA?
private static final void cublasDestroy(cublasHandle handle) {
JCublas2.cublasDestroy(handle);
}
private static void freePointer(Pointer p) {
JCuda.cudaFree(p);
}
public static void main(String[] args) {
for (int i = 2; i < 300; i++) {
DenseDoubleMatrix a = new DenseDoubleMatrix(i, i, new Random());
DenseDoubleMatrix b = new DenseDoubleMatrix(i, i, new Random());
CUDA_AVAILABLE = false;
DenseDoubleMatrix multiplyCPU = a.multiply(b);
CUDA_AVAILABLE = true;
DenseDoubleMatrix multiplyGPU = multiply(a, b);
System.out.println(i + " "
+ DenseDoubleMatrix.error(multiplyCPU, multiplyGPU));
}
}
} |
package de.mycrobase.ssim.ed.app;
import com.jme3.app.Application;
import com.jme3.app.state.AppStateManager;
import com.jme3.audio.AudioNode;
import com.jme3.scene.Node;
import de.mycrobase.ssim.ed.weather.Weather;
import de.mycrobase.ssim.ed.weather.ext.PrecipitationType;
public class AudioAppState extends BasicAppState {
private static final float UpdateInterval = 0.1f; // in seconds
// exists only while AppState is attached
private Node envAudio;
private AudioNode wind;
private AudioNode rainMedium;
private AudioNode rainHeavy;
public AudioAppState() {
super(UpdateInterval);
}
@Override
public void initialize(AppStateManager stateManager, Application baseApp) {
super.initialize(stateManager, baseApp);
envAudio = new Node("EnvAudio");
getApp().getRootNode().attachChild(envAudio);
// wind = new AudioNode(getApp().getAssetManager(), "audio/wind-01.wav", false);
// wind.setLooping(true);
// wind.setPositional(false);
// envAudio.attachChild(wind);
// updateWind();
rainMedium = loadEnvSound("audio/rain-medium.ogg");
rainHeavy = loadEnvSound("audio/rain-heavy.ogg");
envAudio.attachChild(rainMedium);
envAudio.attachChild(rainHeavy);
updateRain();
}
// TODO: pause active sounds on GameMode.Paused?
@Override
public void update(float dt) {
super.update(dt);
// update listener (OpenAL term for ears) by camera position
getApp().getListener().setLocation(getApp().getCamera().getLocation());
getApp().getListener().setRotation(getApp().getCamera().getRotation());
}
@Override
protected void intervalUpdate(float dt) {
updateWind();
updateRain();
}
@Override
public void cleanup() {
super.cleanup();
// wind.stop();
rainMedium.stop();
rainHeavy.stop();
getApp().getRootNode().detachChild(envAudio);
envAudio = null;
wind = null;
rainMedium = null;
rainHeavy = null;
}
private Weather getWeather() {
return getState(WeatherAppState.class).getWeather();
}
private void updateWind() {
//wind.setVolume(getWeather().getFloat("wind.strength")/10f);
//wind.setVolume(getApp().getSettingsManager().getFloat("sound.effect.volume"));
}
private void updateRain() {
rainMedium.setVolume(getApp().getSettingsManager().getFloat("sound.effect.volume"));
rainHeavy.setVolume(getApp().getSettingsManager().getFloat("sound.effect.volume"));
PrecipitationType curType =
PrecipitationType.fromId(getWeather().getInt("precipitation.form"));
float intensity = getWeather().getFloat("precipitation.intensity");
if(curType == PrecipitationType.Rain) {
if(intensity >= 0.75f) {
rainMedium.stop();
rainHeavy.play();
} else {
rainHeavy.stop();
rainMedium.play();
}
} else {
// one of those is currently playing
rainMedium.stop();
rainHeavy.stop();
}
}
private AudioNode loadEnvSound(String file) {
AudioNode a = new AudioNode(
getApp().getAssetManager(), file, false);
a.setLooping(true);
a.setPositional(false);
return a;
}
} |
package de.wolfi.minopoly.commands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import de.wolfi.minopoly.Main;
import de.wolfi.minopoly.components.Minopoly;
import de.wolfi.minopoly.components.Player;
public class MoveCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender paramCommandSender, Command arg1, String arg2, String[] args) {
final org.bukkit.entity.Player sender = (org.bukkit.entity.Player) paramCommandSender;
if (!Main.getMain().isMinopolyWorld(sender.getWorld())) {
sender.sendMessage("command.wrongworld");
return true;
}
final Minopoly game = Main.getMain().getMinopoly(sender.getWorld());
if (args.length < 2) {
paramCommandSender.sendMessage("args.missing");
return true;
}
final org.bukkit.entity.Player playername = Bukkit.getPlayer(args[0]);
if (playername == null) {
sender.sendMessage("player.missing");
return true;
}
final Player p = game.getByBukkitPlayer(playername);
if (p == null) {
sender.sendMessage("player.missing.game");
return true;
}
int steps = 0;
try {
steps = Integer.parseInt(args[1]);
} catch (final Exception e) {
sender.sendMessage(ChatColor.DARK_RED + e.getMessage());
}
p.move(steps);
return true;
}
} |
package uk.nhs.ciao.camel;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.camel.spring.Main;
import org.apache.camel.util.IOHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.AbstractApplicationContext;
import uk.nhs.ciao.exceptions.CIAOConfigurationException;
/**
* Main runner for starting a Camel spring application via spring
* <p>
* Extends the default {@link Main} class to support creating a parent
* application context (specified by the application)
*
* @see Main
* @see CamelApplication#createParentApplicationContext()
*/
public class CamelApplicationRunner extends Main {
private static final Logger LOGGER = LoggerFactory.getLogger(CamelApplicationRunner.class);
/**
* The default path of the spring application context resource to load
*/
public static final String DEFAULT_APPLICATION_CONTEXT_URI = "META-INF/spring/beans.xml";
private static volatile CamelApplicationRunner instance;
/**
* Runs the specified camel application
* <p>
* The application will run with hang-up support enabled
* <p>
* This method blocks the calling thread until the application has terminated
*
* @param application The application to run
* @throws Exception If the application could not be started
* @see #getInstance()
*/
public static void runApplication(final CamelApplication application) throws Exception {
try {
final CamelApplicationRunner main = new CamelApplicationRunner(application);
Main.instance = main;
instance = main;
main.enableHangupSupport();
main.run(application.getArguments());
} finally {
Main.instance = null;
instance = null;
}
}
/**
* Runs the specified camel application via an executor
* <p>
* The application will run without hang-up support enabled
* <p>
* This method will return once the application has started unless an exception is thrown. The returned
* AsyncExecution can be used to examine/stop the application or to examine exception thrown after
* the application started
*
* @param application The application to run
* @param executorService The executorService to use when running the application
* @return The async execution associated with the running application
*/
public static AsyncExecution runApplication(final CamelApplication application,
final ExecutorService executorService) throws Exception {
// A reference to the runner - all construction is handled in the worker thread
final AtomicReference<CamelApplicationRunner> runnerRef = new AtomicReference<CamelApplicationRunner>();
// If an exception is thrown - marshal it into the calling thread
final AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
// Block until either an exception is thrown or the application has started
final CountDownLatch latch = new CountDownLatch(1);
// Watches for application started
final LifecycleListener lifecycleListener = new LifecycleListener() {
public void onStarted() {
super.onStarted();
latch.countDown();
};
};
// Task to run the application
final Callable<Void> task = new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
final CamelApplicationRunner main = new CamelApplicationRunner(application,
lifecycleListener);
runnerRef.set(main);
Main.instance = main;
instance = main;
main.run(application.getArguments());
} catch (Throwable e) {
LOGGER.error("Exception while running CamelApplication", e);
causeRef.set(e);
latch.countDown();
throw exception(e);
}
finally {
Main.instance = null;
instance = null;
}
return null;
}
};
// Start the application
final Future<Void> future = executorService.submit(task);
// Wait until running or failure (whichever comes first)
latch.await();
final Throwable cause = causeRef.get();
if (cause != null) {
throw exception(cause);
}
return new AsyncExecution(runnerRef.get(), future);
}
/**
* Represents the execution of a camel application in another thread
*/
public static class AsyncExecution {
private final CamelApplicationRunner runner;
private final Future<Void> future;
private AsyncExecution(final CamelApplicationRunner runner, final Future<Void> future) {
this.runner = runner;
this.future = future;
}
/**
* The application runner
*/
public CamelApplicationRunner getRunner() {
return runner;
}
/**
* The future associated with the aync execution.
* <p>
* The future can be examined to see whether the application is running,
* wait for termination, or retrieve application excceptions that were thrown
* during the run
*/
public Future<Void> getFuture() {
return future;
}
}
// a little syntactic sugar to simplify re-throwing Throwables
private static Exception exception(final Throwable throwable) {
if (throwable instanceof Exception) {
return (Exception)throwable;
} else {
throw (Error)throwable;
}
}
/**
* Listens to lifecycle events while running an application
*/
public static class LifecycleListener {
/**
* Invoked when the application is starting
*/
public void onStarting() {
// Default is NOOP - free for subclasses to override
}
/**
* Invoked when the application has started
*/
public void onStarted() {
// Default is NOOP - free for subclasses to override
}
/**
* Invoked when the application is stopping
*/
public void onStopping() {
// Default is NOOP - free for subclasses to override
}
/**
* Invoked when the application has stopped
*/
public void onStopped() {
// Default is NOOP - free for subclasses to override
}
}
/**
* The system-wide application instance
*
* @see Main#getInstance()
*/
public static CamelApplicationRunner getInstance() {
return instance;
}
private final CamelApplication application;
private final LifecycleListener lifecycleListener;
/**
* Creates a new main to run the specified application
*/
public CamelApplicationRunner(final CamelApplication application, final LifecycleListener lifecycleListener) {
super();
this.application = application;
this.lifecycleListener = lifecycleListener;
// The default wild-card expression can make the loading of a main file
// unpredictable (especially with a test classpath)
setApplicationContextUri(DEFAULT_APPLICATION_CONTEXT_URI);
}
/**
* Creates a new main to run the specified application
*/
public CamelApplicationRunner(final CamelApplication application) {
this(application, new LifecycleListener());
}
/**
* The contained application
*/
public CamelApplication getApplication() {
return application;
}
/**
* {@inheritDoc}
*/
@Override
protected void doStart() throws Exception {
lifecycleListener.onStarting();
final AbstractApplicationContext parentContext = getOrCreateParentApplicationContext();
parentContext.refresh();
parentContext.start();
super.doStart();
}
/**
* {@inheritDoc}
*/
@Override
protected void afterStart() throws Exception {
super.afterStart();
lifecycleListener.onStarted();
}
/**
* {@inheritDoc}
*/
@Override
protected void beforeStop() throws Exception {
lifecycleListener.onStopping();
super.beforeStop();
}
/**
* {@inheritDoc}
*/
@Override
protected void doStop() throws Exception {
try {
super.doStop();
} finally {
IOHelper.close(getParentApplicationContext());
}
lifecycleListener.onStopped();
}
/**
* Returns the parent application context, creating a new instance if required.
*/
private AbstractApplicationContext getOrCreateParentApplicationContext() throws CIAOConfigurationException {
AbstractApplicationContext parentContext = getParentApplicationContext();
if (parentContext == null) {
parentContext = application.createParentApplicationContext();
setParentApplicationContext(parentContext);
}
return parentContext;
}
} |
package xyz.tiltmaster.listener;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import xyz.tiltmaster.util.Observer;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class KeyboardListener extends Observer implements NativeKeyListener {
private static String message;
private static Properties properties;
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + /*NativeKeyEvent.getKeyText*/(e.getKeyCode()));
message = properties.getProperty(NativeKeyEvent.getKeyText(e.getKeyCode()));
this.fire(() -> message);
System.out.println(message);
}
public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
}
public void nativeKeyPressed(NativeKeyEvent e) {
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}
public static void main(String[] args) {
properties = new Properties();
BufferedInputStream stream = null;
try {
stream = new BufferedInputStream(new FileInputStream("../keymap.properties"));
properties.load(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
GlobalScreen.addNativeKeyListener(new KeyboardListener());
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);
}
} |
package org.deidentifier.arx.algorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Stack;
import org.deidentifier.arx.criteria.KAnonymity;
import org.deidentifier.arx.framework.check.INodeChecker;
import org.deidentifier.arx.framework.check.history.History;
import org.deidentifier.arx.framework.check.history.History.PruningStrategy;
import org.deidentifier.arx.framework.lattice.Lattice;
import org.deidentifier.arx.framework.lattice.Node;
/**
* This class provides a reference implementation of the ARX algorithm.
*
* @author Prasser, Kohlmayer
*/
public class FLASHAlgorithm extends AbstractAlgorithm {
/** Potential traverse types */
private static enum TraverseType {
FIRST_PHASE_ONLY,
FIRST_AND_SECOND_PHASE,
SECOND_PHASE_ONLY
}
/** The stack. */
private final Stack<Node> stack;
/** The heap. */
private final PriorityQueue<Node> pqueue;
/** The current path. */
private final ArrayList<Node> path;
/** Are the pointers for a node with id 'index' already sorted?. */
private final boolean[] sorted;
/** The strategy. */
private final FLASHStrategy strategy;
/** Traverse type of 2PF */
private TraverseType traverseType;
/** The history*/
private History history;
/**
* Creates a new instance of the ARX algorithm.
*
* @param lattice
* The lattice
* @param history
* The history
* @param checker
* The checker
* @param metric
* The metric
*/
public FLASHAlgorithm(final Lattice lattice,
final INodeChecker checker,
final FLASHStrategy metric) {
super(lattice, checker);
strategy = metric;
pqueue = new PriorityQueue<Node>(11, strategy);
sorted = new boolean[lattice.getSize()];
path = new ArrayList<Node>();
stack = new Stack<Node>();
this.history = checker.getHistory();
// IF we assume practical monotonicity then we assume
// monotonicity for both criterion AND metric!
// We assume monotonicity for everything with 0% suppression
if ((checker.getConfiguration().getAbsoluteMaxOutliers() == 0) ||
(checker.getConfiguration().isCriterionMonotonic() && checker.getMetric()
.isMonotonic()) ||
(checker.getConfiguration().isPracticalMonotonicity())) {
traverseType = TraverseType.FIRST_PHASE_ONLY;
history.setPruningStrategy(PruningStrategy.ANONYMOUS);
} else {
if (checker.getConfiguration().getMinimalGroupSize() != Integer.MAX_VALUE) {
traverseType = TraverseType.FIRST_AND_SECOND_PHASE;
history.setPruningStrategy(PruningStrategy.K_ANONYMOUS);
} else {
traverseType = TraverseType.SECOND_PHASE_ONLY;
history.setPruningStrategy(PruningStrategy.CHECKED);
}
}
}
/**
* Check a node during the first phase
*
* @param node
*/
protected void checkNode1(final Node node) {
checker.check(node);
if (listener != null) {
listener.nodeChecked(lattice.getSize());
}
switch (traverseType) { // SECOND_PHASE_ONLY not needed, as in this case
// checkNode1 would never been called
case FIRST_PHASE_ONLY:
lattice.tagAnonymous(node, node.isAnonymous());
break;
case FIRST_AND_SECOND_PHASE:
lattice.tagKAnonymous(node, node.isKAnonymous());
break;
default:
throw new RuntimeException("Not implemented!");
}
}
/**
* Check a node during the second phase
*
* @param node
*/
protected void checkNode2(final Node node) {
if (!node.isChecked()) {
// TODO: revisit var1 & var2 !!
final boolean var1 = !checker.getMetric().isMonotonic() &&
checker.getConfiguration()
.isCriterionMonotonic();
final boolean var2 = !checker.getMetric().isMonotonic() &&
!checker.getConfiguration()
.isCriterionMonotonic() &&
checker.getConfiguration()
.isPracticalMonotonicity();
// BEWARE: Might return non-anonymous result as optimum, when
// 1. the criterion is not monotonic, and
// 2. practical monotonicity is assumed, and
// 3. the metric is non-monotonic BUT independent.
// -> Such a metric does currently not exist
if (checker.getMetric().isIndependent() && (var1 || var2)) {
checker.getMetric().evaluate(node, null);
} else {
checker.check(node);
if (listener != null) {
listener.nodeChecked(lattice.getSize());
}
}
}
// in case metric is monotone it can be tagged if the node is anonymous
if (checker.getMetric().isMonotonic() && node.isAnonymous()) {
lattice.tagAnonymous(node, node.isAnonymous());
} else {
node.setTagged();
lattice.untaggedCount[node.getLevel()]
}
}
/**
* Checks a path binary.
*
* @param path
* The path
*/
private final Node checkPathBinary(final List<Node> path) {
int low = 0;
int high = path.size() - 1;
Node lastAnonymousNode = null;
while (low <= high) {
final int mid = (low + high) >>> 1;
final Node node = path.get(mid);
if (!node.isTagged()) {
checkNode1(node);
if (!isNodeAnonymous(node)) { // put only non-anonymous nodes in
// pqueue, as potetnially a
// snaphsot is avaliable
for (final Node up : node.getSuccessors()) {
if (!up.isTagged()) { // only unknown nodes are
// nesessary
pqueue.add(up);
}
}
}
}
if (isNodeAnonymous(node)) {
lastAnonymousNode = node;
high = mid - 1;
} else {
low = mid + 1;
}
}
return lastAnonymousNode;
}
/**
* Checks a path sequentially.
*
* @param path
* The path
*/
private final void checkPathExhaustive(final List<Node> path) {
for (final Node node : path) {
if (!node.isTagged()) {
checkNode2(node);
// Put all untagged nodes on the stack
for (final Node up : node.getSuccessors()) {
if (!up.isTagged()) {
stack.push(up);
}
}
}
}
}
/**
* Greedy find path.
*
* @param current
* The current
* @return the list
*/
private final List<Node> findPath(Node current) {
path.clear();
path.add(current);
boolean found = true;
while (found) {
found = false;
this.sort(current);
for (final Node candidate : current.getSuccessors()) {
if (!candidate.isTagged()) {
current = candidate;
path.add(candidate);
found = true;
break;
}
}
}
return path;
}
/**
* Is the node anonymous according to the first run of the algorithm
*
* @param node
* @param traverseType
* @return
*/
private boolean isNodeAnonymous(final Node node) {
// SECOND_PHASE_ONLY not needed, as isNodeAnonymous is only used during the first phase
switch (traverseType) {
case FIRST_PHASE_ONLY:
return node.isAnonymous();
case FIRST_AND_SECOND_PHASE:
return node.isKAnonymous();
default:
throw new RuntimeException("Not implemented!");
}
}
/**
* Sorts a level.
*
* @param level
* The level
* @return the node[]
*/
private final Node[] sort(final int level) {
final Node[] result = new Node[lattice.getUntaggedCount(level)];
if (result.length == 0) { return result; }
int index = 0;
final Node[] nlevel = lattice.getLevels()[level];
for (final Node n : nlevel) {
if (!n.isTagged()) {
result[index++] = n;
}
}
this.sort(result);
return result;
}
/**
* Sorts upwards pointers of a node.
*
* @param current
* The current
*/
private final void sort(final Node current) {
if (!sorted[current.id]) {
this.sort(current.getSuccessors());
sorted[current.id] = true;
}
}
/**
* Sorts a node array.
*
* @param array
* The array
*/
protected final void sort(final Node[] array) {
Arrays.sort(array, strategy);
}
/*
* (non-Javadoc)
*
* @see org.deidentifier.ARX.algorithm.AbstractAlgorithm#traverse()
*/
@Override
public void traverse() {
pqueue.clear();
stack.clear();
// check first node
for (final Node[] level : lattice.getLevels()) {
if (level.length != 0) {
if (level.length == 1) {
checker.check(level[0]);
break;
} else {
throw new RuntimeException("Multiple bottom nodes!");
}
}
}
// For each node
final int length = lattice.getLevels().length;
for (int i = 0; i < length; i++) {
Node[] level;
level = this.sort(i);
for (final Node node : level) {
if (!node.isTagged()) {
pqueue.add(node);
while (!pqueue.isEmpty()) {
Node head = pqueue.poll();
// if anonymity is unknown
if (!head.isTagged()) {
// If first phase is needed
if (traverseType == TraverseType.FIRST_PHASE_ONLY ||
traverseType == TraverseType.FIRST_AND_SECOND_PHASE) {
findPath(head);
head = checkPathBinary(path);
}
// if second phase needed, process path
if (head != null &&
(traverseType == TraverseType.FIRST_AND_SECOND_PHASE || traverseType == TraverseType.SECOND_PHASE_ONLY)) {
// Change strategy
final PruningStrategy pruning = history.getPruningStrategy();
history.setPruningStrategy(PruningStrategy.CHECKED);
// Untag all nodes above first anonymous node if they have already been tagged by first phase;
// They will all be tagged again by StackFlash
if (traverseType == TraverseType.FIRST_AND_SECOND_PHASE) {
lattice.doUnTagUpwards(head);
}
stack.push(head);
while (!stack.isEmpty()) {
final Node start = stack.pop();
if (!start.isTagged()) {
findPath(start);
checkPathExhaustive(path);
}
}
// Switch back to previous strategy
history.setPruningStrategy(pruning);
}
}
}
}
}
}
}
} |
package tlc2.tool.fp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ShortDiskFPSetTest extends AbstractFPSetTest {
private static final boolean runKnownFailures = Boolean
.getBoolean(ShortDiskFPSetTest.class.getName() + ".runKnown");
/* (non-Javadoc)
* @see tlc2.tool.fp.AbstractFPSetTest#getFPSet(int)
*/
protected FPSet getFPSet(int freeMemory) throws IOException {
final DiskFPSet fpSet = new DiskFPSet(freeMemory);
fpSet.init(1, tmpdir, filename);
return fpSet;
}
/**
* Tests if {@link DiskFPSet#diskLookup(long)} returns true for zero fp
* @throws IOException
*/
public void testWithoutZeroFP() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse("Succeeded to look up 0 fp", fpSet.contains(0l));
}
/**
* Tests if {@link DiskFPSet#diskLookup(long)} returns true for min fp
* @throws IOException
*/
public void testWithoutMinFP() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse("Succeeded to look up 0 fp", fpSet.contains(Long.MIN_VALUE));
}
/**
* Tests if {@link DiskFPSet#diskLookup(long)} returns true for max fp
* @throws IOException
*/
public void testWithoutMaxFP() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse("Succeeded to look up 0 fp", fpSet.contains(Long.MAX_VALUE));
}
/**
* Tests if {@link DiskFPSet#diskLookup(long)} accepts a 0 fp
* @throws IOException
*/
public void testZeroFP() throws IOException {
// skip known failures which aren't likely to be fixed anytime soon
if(!runKnownFailures) {
System.out
.println("Skipping test failing due to https://bugzilla.tlaplus.net/show_bug.cgi?id=213");
return;
}
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse(fpSet.put(0l));
assertTrue("Failed to look up 0 fp", fpSet.contains(0l));
}
/**
* Tests if {@link DiskFPSet#diskLookup(long)} accepts a min fp
* @throws IOException
*/
public void testMinFP() throws IOException {
// skip known failures which aren't likely to be fixed anytime soon
if(!runKnownFailures) {
System.out
.println("Skipping test failing due to https://bugzilla.tlaplus.net/show_bug.cgi?id=213");
return;
}
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
// zeroing the msb in DiskFPSet turns Long.Min_Value into 0
assertFalse(fpSet.put(Long.MIN_VALUE));
assertTrue("Failed to look up min fp", fpSet.contains(Long.MIN_VALUE));
}
/**
* Tests if {@link DiskFPSet#diskLookup(long)} accepts a min - 1 fp
* @throws IOException
*/
public void testMinMin1FP() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
// zeroing the msb in DiskFPSet turns Long.Min_Value into 0
assertFalse(fpSet.put(Long.MIN_VALUE - 1l));
assertTrue("Failed to look up min fp", fpSet.contains(Long.MIN_VALUE - 1l));
}
/**
* Tests if {@link DiskFPSet#diskLookup(long)} accepts a -1 fp
* @throws IOException
*/
public void testNeg1FP() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse(fpSet.put(-1l));
assertTrue("Failed to look up min fp", fpSet.contains(-1l));
}
/**
* Tests if {@link DiskFPSet#diskLookup(long)} accepts a +1 fp
* @throws IOException
*/
public void testPos1FP() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse(fpSet.put(1l));
assertTrue("Failed to look up min fp", fpSet.contains(1l));
}
/**
* Tests if {@link DiskFPSet#diskLookup(long)} accepts a max fp
* @throws IOException
*/
public void testMaxFP() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse(fpSet.put(Long.MAX_VALUE));
assertTrue("Failed to look up max fp", fpSet.contains(Long.MAX_VALUE));
}
/**
* Tries to call
* {@link DiskFPSet#calculateMidEntry(long, long, double, long, long)} with
* values causing a negative midEntry to be calculated.
*
* @throws IOException
*/
public void testValues() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
final List<Long> loVals = new ArrayList<Long>();
// no negative values (MSB stripped in DiskFPSet)
// loVals.add(Long.MIN_VALUE);
// loVals.add(Long.MIN_VALUE - 1l);
// loVals.add(Long.MIN_VALUE / 2l);
// loVals.add(-1l);
loVals.add(0l); // zero valid fp
loVals.add(1l);
loVals.add(Long.MAX_VALUE / 2l);
loVals.add(Long.MAX_VALUE - 1l);
loVals.add(Long.MAX_VALUE);
final List<Long> hiVals = new ArrayList<Long>();
// no negative values (MSB stripped in DiskFPSet)
// hiVals.add(Long.MIN_VALUE);
// hiVals.add(Long.MIN_VALUE - 1l);
// hiVals.add(Long.MIN_VALUE / 2l);
// hiVals.add(-1l);
hiVals.add(0l); // zero valid fp
hiVals.add(1l);
hiVals.add(Long.MAX_VALUE / 2l);
hiVals.add(Long.MAX_VALUE - 1l);
hiVals.add(Long.MAX_VALUE);
final List<Long> fps = new ArrayList<Long>();
// no negative values (MSB stripped in DiskFPSet)
// fps.add(Long.MIN_VALUE);
// fps.add(Long.MIN_VALUE - 1l);
// fps.add(Long.MIN_VALUE / 2l);
// fps.add(-1l);
fps.add(0l);
fps.add(1l);
fps.add(Long.MAX_VALUE / 2l);
fps.add(Long.MAX_VALUE - 1l);
fps.add(Long.MAX_VALUE);
final List<Long> loEntries = new ArrayList<Long>();
loEntries.add(0l);
loEntries.add(1l);
// possible maximum due to impl. detail in DiskFPSet
// (array index Integer.Max_Value)
loEntries.add((long) Integer.MAX_VALUE * 1024);
// theoretically loEntry can go up to Long.MAX_VALUE
// loEntries.add(Long.MAX_VALUE - 1l);
// loEntries.add(Long.MAX_VALUE);
final List<Long> hiEntries = new ArrayList<Long>();
hiEntries.add(0l);
hiEntries.add(1l);
// possible maximum due to impl. detail in DiskFPSet
// (array index Integer.Max_Value)
hiEntries.add((long) Integer.MAX_VALUE * 1024);
// theoretically hiEntry can go up to Long.MAX_VALUE
// hiEntries.add(Long.MAX_VALUE - 1l);
// hiEntries.add(Long.MAX_VALUE);
// loVals
for (final Iterator<Long> itr0 = loVals.iterator(); itr0.hasNext();) {
final Long loVal = (Long) itr0.next();
// hiVals
for (final Iterator<Long> itr1 = hiVals.iterator(); itr1.hasNext();) {
final Long hiVal = (Long) itr1.next();
// fps
for (final Iterator<Long> itr2 = fps.iterator(); itr2.hasNext();) {
final Long fp = (Long) itr2.next();
// loEntry
for (final Iterator<Long> itr3 = loEntries.iterator(); itr3.hasNext();) {
final Long loEntry = (Long) itr3.next();
// hiEntry
for (final Iterator<Long> itr4 = hiEntries.iterator(); itr4.hasNext();) {
final Long hiEntry = (Long) itr4.next();
testCalculateMidEntry(fpSet, loVal, hiVal, fp, loEntry, hiEntry);
}
}
}
}
}
}
private void testCalculateMidEntry(DiskFPSet fpSet, long loVal, long hiVal, long fp, long loEntry, long hiEntry)
throws IOException {
if (!isInvalidInput(loVal, hiVal, fp, loEntry, hiEntry)) {
try {
long midEntry = fpSet.calculateMidEntry(loVal, hiVal, fp, loEntry, hiEntry);
assertTrue(getMessage("Negative mid entry", loVal, hiVal, fp, loEntry, hiEntry, midEntry),
midEntry >= 0);
assertTrue(getMessage("Not within lower bound", loVal, hiVal, fp, loEntry, hiEntry, midEntry),
midEntry >= loEntry);
assertTrue(getMessage("Not within upper bound", loVal, hiVal, fp, loEntry, hiEntry, midEntry),
midEntry <= hiEntry);
// DiskFPSet#diskLookup uses long addressing and thus has to multiply by 8
assertTrue(getMessage("midEntry turned negative", loVal, hiVal, fp, loEntry, hiEntry, midEntry),
(midEntry * 8) >= 0);
} catch (RuntimeException e) {
fail("failed to calculate for valid input (loVal, hiVal, fp, loEntry, hiEntry): " + loVal + ", "
+ hiVal + ", " + fp + ", " + loEntry + ", " + hiEntry);
}
}
}
private String getMessage(String txt, long loVal, long hiVal, long fp, long loEntry, long hiEntry, long midEntry) {
return txt + " (loVal, hiVal, fp, loEntry, hiEntry, midEntry): " + loVal + ", "
+ hiVal + ", " + fp + ", " + loEntry + ", " + hiEntry + ", " + midEntry;
}
private boolean isInvalidInput(long loVal, long hiVal, long fp, long loEntry, long hiEntry) {
return loVal > hiVal || loVal > fp || hiVal < fp || loEntry >= hiEntry;
}
/**
* Tests if {@link DiskFPSet#diskLookup(long)} returns true for a fp that is
* first fp in first page
*
* page size hard-coded in {@link DiskFPSet} to be 1024
*
* @throws IOException
*/
public void testDiskLookupWithFpOnLoPage() throws IOException {
int freeMemory = 1000; // causes 16 in memory entries
final DiskFPSet fpSet = (DiskFPSet) getFPSet(freeMemory);
// add enough fps to cause 3 disk writes
final long fp = 1l;
for (long i = 0; i < 1024 * 3; i++) {
assertFalse(fpSet.put(fp + i));
assertTrue(fpSet.contains(fp + i));
}
assertTrue("Failed to lookup fp on first page", fpSet.diskLookup(fp));
}
/**
* Tests how {@link DiskFPSet#memLookup(long)} handles zeros
*
* @throws IOException
*/
public void testMemLookupWithZeros() throws IOException {
// skip known failures which aren't likely to be fixed anytime soon
if(!runKnownFailures) {
System.out
.println("Skipping test failing due to https://bugzilla.tlaplus.net/show_bug.cgi?id=213");
return;
}
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse(fpSet.memInsert(0l));
assertFalse(fpSet.diskLookup(0l));
assertTrue(fpSet.memLookup(0l));
}
/**
* Tests how {@link DiskFPSet#memLookup(long)} handles Long.Min_VALUE
*
* @throws IOException
*/
public void testMemLookupWithMin() throws IOException {
// skip known failures which aren't likely to be fixed anytime soon
if(!runKnownFailures) {
System.out
.println("Skipping test failing due to https://bugzilla.tlaplus.net/show_bug.cgi?id=213");
return;
}
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse(fpSet.memInsert(Long.MIN_VALUE & 0x7FFFFFFFFFFFFFFFL));
assertFalse(fpSet.diskLookup(Long.MIN_VALUE & 0x7FFFFFFFFFFFFFFFL));
assertTrue(fpSet.memLookup(Long.MIN_VALUE & 0x7FFFFFFFFFFFFFFFL));
}
/**
* Tests how {@link DiskFPSet#memLookup(long)} handles MAx_Value
*
* @throws IOException
*/
public void testMemLookupWithMax() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse(fpSet.memInsert(Long.MAX_VALUE));
assertFalse(fpSet.diskLookup(Long.MAX_VALUE));
assertTrue(fpSet.memLookup(Long.MAX_VALUE));
}
/**
* Tests how {@link DiskFPSet#memLookup(long)} handles zeros
*
* @throws IOException
*/
public void testDiskLookupWithZeros() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse(fpSet.memInsert(0l));
assertFalse(fpSet.diskLookup(0l));
fpSet.flushTable();
assertTrue(fpSet.diskLookup(0l));
// undefined behavior
// assertTrue(fpSet.memLookup(0l));
}
/**
* Tests how {@link DiskFPSet#memLookup(long)} handles Long.Min_VALUE
*
* @throws IOException
*/
public void testDiskLookupWithMin() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse(fpSet.memInsert(Long.MIN_VALUE & 0x7FFFFFFFFFFFFFFFL));
assertFalse(fpSet.diskLookup(Long.MIN_VALUE & 0x7FFFFFFFFFFFFFFFL));
fpSet.flushTable();
assertTrue(fpSet.diskLookup(Long.MIN_VALUE & 0x7FFFFFFFFFFFFFFFL));
// undefined behavior
// assertTrue(fpSet.memLookup(Long.MIN_VALUE & 0x7FFFFFFFFFFFFFFFL));
}
/**
* Tests how {@link DiskFPSet#memLookup(long)} handles MAx_Value
*
* @throws IOException
*/
public void testDiskLookupWithMax() throws IOException {
final DiskFPSet fpSet = (DiskFPSet) getFPSet(getFreeMemory());
assertFalse(fpSet.memInsert(Long.MAX_VALUE));
assertFalse(fpSet.diskLookup(Long.MAX_VALUE));
fpSet.flushTable();
assertTrue(fpSet.diskLookup(Long.MAX_VALUE));
assertTrue(fpSet.memLookup(Long.MAX_VALUE));
}
/**
* Tests how {@link DiskFPSet#diskLookup(long)} handles max on pages
*
* @throws IOException
*/
public void testDiskLookupWithMaxOnPage() throws IOException {
testDiskLookupOnPage(Long.MAX_VALUE);
}
/**
* Tests how {@link DiskFPSet#diskLookup(long)} handles zeros on pages
*
* @throws IOException
*/
public void testDiskLookupWithZerosOnPage() throws IOException {
// skip known failures which aren't likely to be fixed anytime soon
if(!runKnownFailures) {
System.out
.println("Skipping test failing due to https://bugzilla.tlaplus.net/show_bug.cgi?id=213");
return;
}
testDiskLookupOnPage(0l);
}
/**
* Tests how {@link DiskFPSet#diskLookup(long)} handles Long#Min_Value on pages
*
* @throws IOException
*/
public void testDiskLookupWithLongMinValueOnPage() throws IOException {
// skip known failures which aren't likely to be fixed anytime soon
if(!runKnownFailures) {
System.out
.println("Skipping test failing due to https://bugzilla.tlaplus.net/show_bug.cgi?id=213");
return;
}
testDiskLookupOnPage(Long.MIN_VALUE);
}
private void testDiskLookupOnPage(final long fp) throws IOException {
int freeMemory = 1000; // causes 16 in memory entries
final DiskFPSet fpSet = (DiskFPSet) getFPSet(freeMemory);
// add enough fps to cause 2 disk writes
assertFalse(fpSet.put(fp));
for (long i = 1; i < 1024 * 2; i++) {
assertTrue("Failed to add fingerprint", fpSet.put(fp));
assertTrue(fpSet.contains(fp));
}
final long fp0 = fp & 0x7FFFFFFFFFFFFFFFL;
assertTrue(fpSet.memLookup(fp));
assertFalse(fpSet.diskLookup(fp0));
}
} |
package dr.app.beauti.generator;
import dr.app.beast.BeastVersion;
import dr.app.beauti.BeautiFrame;
import dr.app.beauti.components.ComponentFactory;
import dr.app.beauti.components.marginalLikelihoodEstimation.MarginalLikelihoodEstimationOptions;
import dr.app.beauti.options.*;
import dr.app.beauti.types.*;
import dr.app.beauti.util.XMLWriter;
import dr.app.util.Arguments;
import dr.evolution.alignment.Alignment;
import dr.evolution.alignment.Patterns;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Microsatellite;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import dr.evolution.util.Units;
import dr.evomodelxml.speciation.MultiSpeciesCoalescentParser;
import dr.evomodelxml.speciation.SpeciationLikelihoodParser;
import dr.evoxml.AlignmentParser;
import dr.evoxml.DateParser;
import dr.evoxml.TaxaParser;
import dr.evoxml.TaxonParser;
import dr.inferencexml.distribution.MixedDistributionLikelihoodParser;
import dr.inferencexml.model.CompoundLikelihoodParser;
import dr.inferencexml.model.CompoundParameterParser;
import dr.inferencexml.operators.SimpleOperatorScheduleParser;
import dr.util.Attribute;
import dr.util.Version;
import dr.xml.AttributeParser;
import dr.xml.XMLParser;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* This class holds all the data for the current BEAUti Document
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @author Walter Xie
* @version $Id: BeastGenerator.java,v 1.4 2006/09/05 13:29:34 rambaut Exp $
*/
public class BeastGenerator extends Generator {
private final static Version version = new BeastVersion();
private static final String MESSAGE_CAL_YULE = "Calibrated Yule requires 1 calibrated internal node \n" +
"with a proper prior and monophyly enforced for each tree.";
private final String MESSAGE_CAL = "\nas another element (taxon, sequence, taxon set, species, etc.):\nAll ids should be unique.";
private final AlignmentGenerator alignmentGenerator;
private final PatternListGenerator patternListGenerator;
private final TreePriorGenerator treePriorGenerator;
private final TreeLikelihoodGenerator treeLikelihoodGenerator;
private final SubstitutionModelGenerator substitutionModelGenerator;
private final InitialTreeGenerator initialTreeGenerator;
private final TreeModelGenerator treeModelGenerator;
private final BranchRatesModelGenerator branchRatesModelGenerator;
private final OperatorsGenerator operatorsGenerator;
private final ParameterPriorGenerator parameterPriorGenerator;
private final LogGenerator logGenerator;
// private final DiscreteTraitGenerator discreteTraitGenerator;
private final STARBEASTGenerator starBeastGenerator;
private final TMRCAStatisticsGenerator tmrcaStatisticsGenerator;
public BeastGenerator(BeautiOptions options, ComponentFactory[] components) {
super(options, components);
alignmentGenerator = new AlignmentGenerator(options, components);
patternListGenerator = new PatternListGenerator(options, components);
tmrcaStatisticsGenerator = new TMRCAStatisticsGenerator(options, components);
substitutionModelGenerator = new SubstitutionModelGenerator(options, components);
treePriorGenerator = new TreePriorGenerator(options, components);
treeLikelihoodGenerator = new TreeLikelihoodGenerator(options, components);
initialTreeGenerator = new InitialTreeGenerator(options, components);
treeModelGenerator = new TreeModelGenerator(options, components);
branchRatesModelGenerator = new BranchRatesModelGenerator(options, components);
operatorsGenerator = new OperatorsGenerator(options, components);
parameterPriorGenerator = new ParameterPriorGenerator(options, components);
logGenerator = new LogGenerator(options, components);
// this has moved into the component system...
// discreteTraitGenerator = new DiscreteTraitGenerator(options, components);
starBeastGenerator = new STARBEASTGenerator(options, components);
}
public void checkOptions() throws GeneratorException {
//++++++++++++++ Microsatellite +++++++++++++++
// this has to execute before all checking below
// mask all ? from microsatellite data for whose tree only has 1 data partition
try{
if (options.contains(Microsatellite.INSTANCE)) {
// clear all masks
for (PartitionPattern partitionPattern : options.getPartitionPattern()) {
partitionPattern.getPatterns().clearMask();
}
// set mask
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// if a tree only has 1 data partition, which mostly mean unlinked trees
if (options.getDataPartitions(model).size() == 1) {
PartitionPattern partition = (PartitionPattern) options.getDataPartitions(model).get(0);
Patterns patterns = partition.getPatterns();
for (int i = 0; i < patterns.getTaxonCount(); i++) {
int state = patterns.getPatternState(i, 0);
// mask ? from data
if (state < 0) {
patterns.addMask(i);
}
}
// System.out.println("mask set = " + patterns.getMaskSet() + " in partition " + partition.getName());
}
}
}
} catch (Exception e) {
throw new GeneratorException(e.getMessage());
}
//++++++++++++++++ Taxon List ++++++++++++++++++
TaxonList taxonList = options.taxonList;
Set<String> ids = new HashSet<String>();
ids.add(TaxaParser.TAXA);
ids.add(AlignmentParser.ALIGNMENT);
ids.add(TraitData.TRAIT_SPECIES);
if (taxonList != null) {
if (taxonList.getTaxonCount() < 2) {
throw new GeneratorException("BEAST requires at least two taxa to run.");
}
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
if (ids.contains(taxon.getId())) {
throw new GeneratorException("A taxon has the same id," + taxon.getId() + MESSAGE_CAL);
}
ids.add(taxon.getId());
}
}
//++++++++++++++++ Taxon Sets ++++++++++++++++++
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// should be only 1 calibrated internal node with a proper prior and monophyletic for each tree at moment
if (model.getPartitionTreePrior().getNodeHeightPrior() == TreePriorType.YULE_CALIBRATION) {
if (options.treeModelOptions.isNodeCalibrated(model) < 0) // invalid node calibration
throw new GeneratorException(MESSAGE_CAL_YULE);
if (options.treeModelOptions.isNodeCalibrated(model) > 0) { // internal node calibration
List taxonSetsList = options.getKeysFromValue(options.taxonSetsTreeModel, model);
if (taxonSetsList.size() != 1 || !options.taxonSetsMono.get(taxonSetsList.get(0))) { // 1 tmrca per tree && monophyletic
throw new GeneratorException(MESSAGE_CAL_YULE, BeautiFrame.TAXON_SETS);
}
}
}
}
for (Taxa taxa : options.taxonSets) {
// AR - we should allow single taxon taxon sets...
if (taxa.getTaxonCount() < 1 // && !options.taxonSetsIncludeStem.get(taxa)
) {
throw new GeneratorException(
"Taxon set, " + taxa.getId() + ", should contain \n" +
"at least one taxa. Please go back to Taxon Sets \n" +
"panel to correct this.", BeautiFrame.TAXON_SETS);
}
if (ids.contains(taxa.getId())) {
throw new GeneratorException("A taxon set has the same id," + taxa.getId() +
MESSAGE_CAL, BeautiFrame.TAXON_SETS);
}
ids.add(taxa.getId());
}
//++++++++++++++++ *BEAST ++++++++++++++++++
if (options.useStarBEAST) {
if (!options.traitExists(TraitData.TRAIT_SPECIES))
throw new GeneratorException("A trait labelled \"species\" is required for *BEAST species designations." +
"\nPlease create or import the species designations in the Traits table.", BeautiFrame.TRAITS);
//++++++++++++++++ Species Sets ++++++++++++++++++
// should be only 1 calibrated internal node with monophyletic at moment
if (options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_YULE_CALIBRATION) {
if (options.speciesSets.size() != 1 || !options.speciesSetsMono.get(options.speciesSets.get(0))) {
throw new GeneratorException(MESSAGE_CAL_YULE, BeautiFrame.TAXON_SETS);
}
}
for (Taxa species : options.speciesSets) {
if (species.getTaxonCount() < 2) {
throw new GeneratorException("Species set, " + species.getId() + ",\n should contain" +
"at least two species. \nPlease go back to Species Sets panel to select included species.", BeautiFrame.TAXON_SETS);
}
if (ids.contains(species.getId())) {
throw new GeneratorException("A species set has the same id," + species.getId() +
MESSAGE_CAL, BeautiFrame.TAXON_SETS);
}
ids.add(species.getId());
}
int tId = options.starBEASTOptions.getEmptySpeciesIndex();
if (tId >= 0) {
throw new GeneratorException("The taxon " + options.taxonList.getTaxonId(tId) +
" has NULL value for \"species\" trait", BeautiFrame.TRAITS);
}
}
//++++++++++++++++ Traits ++++++++++++++++++
// missing data is not necessarily an issue...
// for (TraitData trait : options.traits) {
// for (int i = 0; i < trait.getTaxaCount(); i++) {
//// System.out.println("Taxon " + trait.getTaxon(i).getId() + " : [" + trait.getTaxon(i).getAttribute(trait.getName()) + "]");
// if (!trait.hasValue(i))
// " has no value for Trait " + trait.getName());
//++++++++++++++++ Tree Prior ++++++++++++++++++
// if (options.isShareSameTreePrior()) {
if (options.getPartitionTreeModels().size() > 1) { //TODO not allowed multi-prior yet
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
if (prior.getNodeHeightPrior() == TreePriorType.GMRF_SKYRIDE) {
throw new GeneratorException("For the Skyride, tree model/tree prior combination not implemented by BEAST." +
"\nThe Skyride is only available for a single tree model partition in this release.", BeautiFrame.TREES);
}
}
}
//+++++++++++++++ Starting tree ++++++++++++++++
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
if (model.getStartingTreeType() == StartingTreeType.USER) {
if (model.getUserStartingTree() == null) {
throw new GeneratorException("Please select a starting tree in " + BeautiFrame.TREES + " panel, " +
"\nwhen choosing user specified starting tree option.", BeautiFrame.TREES);
}
}
}
//++++++++++++++++ Random local clock model validation ++++++++++++++++++
for (PartitionClockModel model : options.getPartitionClockModels()) {
// 1 random local clock CANNOT have different tree models
if (model.getClockType() == ClockType.RANDOM_LOCAL_CLOCK) { // || AUTOCORRELATED_LOGNORMAL
PartitionTreeModel treeModel = null;
for (AbstractPartitionData pd : options.getDataPartitions(model)) { // only the PDs linked to this tree model
if (treeModel != null && treeModel != pd.getPartitionTreeModel()) {
throw new GeneratorException("A single random local clock cannot be applied to multiple trees.", BeautiFrame.CLOCK_MODELS);
}
treeModel = pd.getPartitionTreeModel();
}
}
}
//++++++++++++++++ Tree Model ++++++++++++++++++
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
int numOfTaxa = -1;
for (AbstractPartitionData pd : options.getDataPartitions(model)) {
if (pd.getTaxonCount() > 0) {
if (numOfTaxa > 0) {
if (numOfTaxa != pd.getTaxonCount()) {
throw new GeneratorException("Partitions with different taxa cannot share the same tree.", BeautiFrame.DATA_PARTITIONS);
}
} else {
numOfTaxa = pd.getTaxonCount();
}
}
}
}
//++++++++++++++++ Prior Bounds ++++++++++++++++++
for (Parameter param : options.selectParameters()) {
if (param.initial != Double.NaN) {
if (param.isTruncated && (param.initial < param.truncationLower || param.initial > param.truncationUpper)) {
throw new GeneratorException("Parameter \"" + param.getName() + "\":" +
"\ninitial value " + param.initial + " is NOT in the range [" + param.truncationLower + ", " + param.truncationUpper + "]," +
"\nor this range is wrong. Please check the Prior panel.", BeautiFrame.PRIORS);
} else if (param.priorType == PriorType.UNIFORM_PRIOR && (param.initial < param.uniformLower || param.initial > param.uniformUpper)) {
throw new GeneratorException("Parameter \"" + param.getName() + "\":" +
"\ninitial value " + param.initial + " is NOT in the range [" + param.uniformLower + ", " + param.uniformUpper + "]," +
"\nor this range is wrong. Please check the Prior panel.", BeautiFrame.PRIORS);
}
if (param.isNonNegative && param.initial < 0.0) {
throw new GeneratorException("Parameter \"" + param.getName() + "\":" +
"\ninitial value " + param.initial + " should be non-negative. Please check the Prior panel.", BeautiFrame.PRIORS);
}
if (param.isZeroOne && (param.initial < 0.0 || param.initial > 1.0)) {
throw new GeneratorException("Parameter \"" + param.getName() + "\":" +
"\ninitial value " + param.initial + " should lie in the interval [0, 1]. Please check the Prior panel.", BeautiFrame.PRIORS);
}
}
}
MarginalLikelihoodEstimationOptions mleOptions = (MarginalLikelihoodEstimationOptions)options.getComponentOptions(MarginalLikelihoodEstimationOptions.class);
if (mleOptions.performMLE) {
for (Parameter param : options.selectParameters()) {
if (param.isPriorImproper() || param.priorType == PriorType.ONE_OVER_X_PRIOR) {
throw new GeneratorException("Parameter \"" + param.getName() + "\":" +
"\nhas an improper prior and will not sample correctly when estimating " +
"the marginal likelihood. " +
"\nPlease check the Prior panel.", BeautiFrame.PRIORS);
}
}
}
// add other tests and warnings here
// Speciation model with dated tips
// Sampling rates without dated tips or priors on rate or nodes
}
/**
* Generate a beast xml file from these beast options
*
* @param file File
* @throws java.io.IOException IOException
* @throws dr.app.util.Arguments.ArgumentException
* ArgumentException
*/
public void generateXML(File file) throws GeneratorException, IOException, Arguments.ArgumentException {
XMLWriter writer = new XMLWriter(new BufferedWriter(new FileWriter(file)));
writer.writeText("<?xml version=\"1.0\" standalone=\"yes\"?>");
writer.writeComment("Generated by BEAUTi " + version.getVersionString(),
" by Alexei J. Drummond, Andrew Rambaut and Marc A. Suchard",
" Department of Computer Science, University of Auckland and",
" Institute of Evolutionary Biology, University of Edinburgh",
" David Geffen School of Medicine, University of California, Los Angeles",
" http://beast.bio.ed.ac.uk/");
writer.writeOpenTag("beast");
writer.writeText("");
// this gives any added implementations of the 'Component' interface a
// chance to generate XML at this point in the BEAST file.
generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_TAXA, writer);
if (options.originDate != null) {
// Create a dummy taxon whose job is to specify the origin date
Taxon originTaxon = new Taxon("originTaxon");
options.originDate.setUnits(options.units);
originTaxon.setDate(options.originDate);
writeTaxon(originTaxon, true, false, writer);
}
//++++++++++++++++ Taxon List ++++++++++++++++++
try {
// write complete taxon list
writeTaxa(options.taxonList, writer);
writer.writeText("");
if (!options.hasIdenticalTaxa()) {
// write all taxa in each gene tree regarding each data partition,
for (AbstractPartitionData partition : options.dataPartitions) {
if (partition.getTaxonList() != null) {
writeDifferentTaxa(partition, writer);
}
}
} else {
// microsat
for (PartitionPattern partitionPattern : options.getPartitionPattern()) {
if (partitionPattern.getTaxonList() != null && partitionPattern.getPatterns().hasMask()) {
writeDifferentTaxa(partitionPattern, writer);
}
}
}
} catch (Exception e) {
System.err.println(e);
throw new GeneratorException("Taxon list generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Taxon Sets ++++++++++++++++++
List<Taxa> taxonSets = options.taxonSets;
try {
if (taxonSets != null && taxonSets.size() > 0 && !options.useStarBEAST) {
tmrcaStatisticsGenerator.writeTaxonSets(writer, taxonSets);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Taxon sets generation has failed:\n" + e.getMessage());
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TAXA, writer);
//++++++++++++++++ Alignments ++++++++++++++++++
List<Alignment> alignments = new ArrayList<Alignment>();
try {
for (AbstractPartitionData partition : options.dataPartitions) {
Alignment alignment = null;
if (partition instanceof PartitionData) { // microsat has no alignment
alignment = ((PartitionData) partition).getAlignment();
}
if (alignment != null && !alignments.contains(alignment)) {
alignments.add(alignment);
}
}
if (alignments.size() > 0) {
alignmentGenerator.writeAlignments(alignments, writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Alignments generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Pattern Lists ++++++++++++++++++
try {
if (!options.samplePriorOnly) {
List<Microsatellite> microsatList = new ArrayList<Microsatellite>();
for (AbstractPartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
if (partition.getTaxonList() != null) {
switch (partition.getDataType().getType()) {
case DataType.NUCLEOTIDES:
case DataType.AMINO_ACIDS:
case DataType.CODONS:
case DataType.COVARION:
case DataType.TWO_STATES:
patternListGenerator.writePatternList((PartitionData) partition, writer);
break;
case DataType.GENERAL:
case DataType.CONTINUOUS:
// no patternlist for trait data - discrete (general) data type uses an
// attribute patterns which is generated next bit of this method.
break;
case DataType.MICRO_SAT:
// microsat does not have alignment
patternListGenerator.writePatternList((PartitionPattern) partition, microsatList, writer);
break;
default:
throw new IllegalArgumentException("Unsupported data type");
}
writer.writeText("");
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Pattern lists generation has failed:\n" + e.getMessage());
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
//++++++++++++++++ Tree Prior Model ++++++++++++++++++
try {
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeTreePriorModel(prior, writer);
writer.writeText("");
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Tree prior model generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Starting Tree ++++++++++++++++++
try {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
initialTreeGenerator.writeStartingTree(model, writer);
writer.writeText("");
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Starting tree generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Tree Model +++++++++++++++++++
try {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
treeModelGenerator.writeTreeModel(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_MODEL, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Tree model generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Statistics ++++++++++++++++++
try {
if (taxonSets != null && taxonSets.size() > 0 && !options.useStarBEAST) {
tmrcaStatisticsGenerator.writeTMRCAStatistics(writer);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("TMRCA statistics generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Tree Prior Likelihood ++++++++++++++++++
try {
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
treePriorGenerator.writePriorLikelihood(model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeMultiLociTreePriors(prior, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_PRIOR, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Tree prior likelihood generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Branch Rates Model ++++++++++++++++++
try {
for (PartitionClockModel model : options.getPartitionClockModels()) {
branchRatesModelGenerator.writeBranchRatesModel(model, writer);
writer.writeText("");
}
// write allClockRate for fix mean option in clock model panel
for (ClockModelGroup clockModelGroup : options.clockModelOptions.getClockModelGroups()) {
if (clockModelGroup.getRateTypeOption() == FixRateType.FIX_MEAN) {
writer.writeOpenTag(CompoundParameterParser.COMPOUND_PARAMETER,
new Attribute[]{new Attribute.Default<String>(XMLParser.ID, clockModelGroup.getName())});
for (PartitionClockModel model : options.getPartitionClockModels(clockModelGroup)) {
branchRatesModelGenerator.writeAllClockRateRefs(model, writer);
}
writer.writeCloseTag(CompoundParameterParser.COMPOUND_PARAMETER);
writer.writeText("");
}
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Branch rates model generation is failed:\n" + e.getMessage());
}
//++++++++++++++++ Substitution Model & Site Model ++++++++++++++++++
try {
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeSubstitutionSiteModel(model, writer);
substitutionModelGenerator.writeAllMus(model, writer); // allMus
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SUBSTITUTION_MODEL, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Substitution model or site model generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Site Model ++++++++++++++++++
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// substitutionModelGenerator.writeSiteModel(model, writer); // site model
// substitutionModelGenerator.writeAllMus(model, writer); // allMus
// writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SITE_MODEL, writer);
//++++++++++++++++ Tree Likelihood ++++++++++++++++++
try {
for (AbstractPartitionData partition : options.dataPartitions) {
// generate tree likelihoods for alignment data partitions
if (partition.getTaxonList() != null) {
if (partition instanceof PartitionData) {
if (partition.getDataType().getType() != DataType.GENERAL &&
partition.getDataType().getType() != DataType.CONTINUOUS) {
treeLikelihoodGenerator.writeTreeLikelihood((PartitionData) partition, writer);
writer.writeText("");
}
} else if (partition instanceof PartitionPattern) { // microsat
treeLikelihoodGenerator.writeTreeLikelihood((PartitionPattern) partition, writer);
writer.writeText("");
} else {
throw new GeneratorException("Find unrecognized partition:\n" + partition.getName());
}
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_LIKELIHOOD, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Tree likelihood generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ *BEAST ++++++++++++++++++
if (options.useStarBEAST) {
//++++++++++++++++ species ++++++++++++++++++
try {
starBeastGenerator.writeSpecies(writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("*BEAST species section generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Species Sets ++++++++++++++++++
List<Taxa> speciesSets = options.speciesSets;
try {
if (speciesSets != null && speciesSets.size() > 0) {
tmrcaStatisticsGenerator.writeTaxonSets(writer, speciesSets);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Species sets generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ trees ++++++++++++++++++
try {
if (speciesSets != null && speciesSets.size() > 0) {
starBeastGenerator.writeStartingTreeForCalibration(writer);
}
starBeastGenerator.writeSpeciesTree(writer, speciesSets != null && speciesSets.size() > 0);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("*BEAST trees generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ Statistics ++++++++++++++++++
try {
if (speciesSets != null && speciesSets.size() > 0) {
tmrcaStatisticsGenerator.writeTMRCAStatistics(writer);
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("*BEAST TMRCA statistics generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ prior and likelihood ++++++++++++++++++
try {
starBeastGenerator.writeSTARBEAST(writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("*BEAST trees section generation has failed:\n" + e.getMessage());
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TRAITS, writer);
//++++++++++++++++ Operators ++++++++++++++++++
try {
List<Operator> operators = options.selectOperators();
operatorsGenerator.writeOperatorSchedule(operators, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_OPERATORS, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("Operators generation has failed:\n" + e.getMessage());
}
//++++++++++++++++ MCMC ++++++++++++++++++
try {
// XMLWriter writer, List<PartitionSubstitutionModel> models,
writeMCMC(writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_MCMC, writer);
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("MCMC or log generation has failed:\n" + e.getMessage());
}
try {
writeTimerReport(writer);
writer.writeText("");
if (options.performTraceAnalysis) {
writeTraceAnalysis(writer);
}
if (options.generateCSV) {
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPAnalysisToCSVfile(prior, writer);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new GeneratorException("The last part of XML generation has failed:\n" + e.getMessage());
}
writer.writeCloseTag("beast");
writer.flush();
writer.close();
}
/**
* Generate a taxa block from these beast options
*
* @param writer the writer
* @param taxonList the taxon list to write
* @throws dr.app.util.Arguments.ArgumentException
* ArgumentException
*/
private void writeTaxa(TaxonList taxonList, XMLWriter writer) throws Arguments.ArgumentException {
// -1 (single taxa), 0 (1st gene of multi-taxa)
writer.writeComment("The list of taxa to be analysed (can also include dates/ages).",
"ntax=" + taxonList.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, TaxaParser.TAXA)});
boolean hasAttr = options.traits.size() > 0;
boolean firstDate = true;
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
boolean hasDate = false;
if (options.clockModelOptions.isTipCalibrated()) {
hasDate = TaxonList.Utils.hasAttribute(taxonList, i, dr.evolution.util.Date.DATE);
}
if (hasDate) {
dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE);
if (firstDate) {
options.units = date.getUnits();
firstDate = false;
} else {
if (options.units != date.getUnits()) {
System.err.println("Error: Units in dates do not match.");
}
}
}
writeTaxon(taxon, hasDate, hasAttr, writer);
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* Generate a taxa block from these beast options
*
* @param writer the writer
* @param taxon the taxon to write
* @throws dr.app.util.Arguments.ArgumentException
* ArgumentException
*/
private void writeTaxon(Taxon taxon, boolean hasDate, boolean hasAttr, XMLWriter writer) throws Arguments.ArgumentException {
writer.writeTag(TaxonParser.TAXON, new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, taxon.getId())},
!(hasDate || hasAttr)); // false if any of hasDate or hasAttr is true
if (hasDate) {
dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE);
Attribute[] attributes;
if (date.getPrecision() > 0.0) {
attributes = new Attribute[] {
new Attribute.Default<Double>(DateParser.VALUE, date.getTimeValue()),
new Attribute.Default<String>(DateParser.DIRECTION, date.isBackwards() ? DateParser.BACKWARDS : DateParser.FORWARDS),
new Attribute.Default<String>(DateParser.UNITS, Units.Utils.getDefaultUnitName(options.units)),
new Attribute.Default<Double>(DateParser.PRECISION, date.getPrecision())
};
} else {
attributes = new Attribute[] {
new Attribute.Default<Double>(DateParser.VALUE, date.getTimeValue()),
new Attribute.Default<String>(DateParser.DIRECTION, date.isBackwards() ? DateParser.BACKWARDS : DateParser.FORWARDS),
new Attribute.Default<String>(DateParser.UNITS, Units.Utils.getDefaultUnitName(options.units))
//new Attribute.Default("origin", date.getOrigin()+"")
};
}
writer.writeTag(dr.evolution.util.Date.DATE, attributes, true);
}
for (TraitData trait : options.traits) {
// there is no harm in allowing the species trait to be listed in the taxa
// if (!trait.getName().equalsIgnoreCase(TraitData.TRAIT_SPECIES)) {
writer.writeOpenTag(AttributeParser.ATTRIBUTE, new Attribute[]{
new Attribute.Default<String>(Attribute.NAME, trait.getName())});
// denotes missing data using '?'
writer.writeText(taxon.containsAttribute(trait.getName()) ? taxon.getAttribute(trait.getName()).toString() : "?");
writer.writeCloseTag(AttributeParser.ATTRIBUTE);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TAXON, taxon, writer);
if (hasDate || hasAttr) writer.writeCloseTag(TaxonParser.TAXON);
}
public void writeDifferentTaxa(AbstractPartitionData dataPartition, XMLWriter writer) {
TaxonList taxonList = dataPartition.getTaxonList();
String name = dataPartition.getName();
writer.writeComment("gene name = " + name + ", ntax= " + taxonList.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, name + "." + TaxaParser.TAXA)});
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
if ( !(dataPartition instanceof PartitionPattern && ((PartitionPattern) dataPartition).getPatterns().isMasked(i) ) ) {
final Taxon taxon = taxonList.getTaxon(i);
writer.writeIDref(TaxonParser.TAXON, taxon.getId());
}
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* Write the timer report block.
*
* @param writer the writer
*/
public void writeTimerReport(XMLWriter writer) {
writer.writeOpenTag("report");
writer.writeOpenTag("property", new Attribute.Default<String>("name", "timer"));
writer.writeIDref("mcmc", "mcmc");
writer.writeCloseTag("property");
writer.writeCloseTag("report");
}
/**
* Write the trace analysis block.
*
* @param writer the writer
*/
public void writeTraceAnalysis(XMLWriter writer) {
writer.writeTag(
"traceAnalysis",
new Attribute[]{
new Attribute.Default<String>("fileName", options.logFileName)
},
true
);
}
/**
* Write the MCMC block.
*
* @param writer XMLWriter
*/
public void writeMCMC(XMLWriter writer) {
writer.writeComment("Define MCMC");
List<Attribute> attributes = new ArrayList<Attribute>();
attributes.add(new Attribute.Default<String>(XMLParser.ID, "mcmc"));
attributes.add(new Attribute.Default<Integer>("chainLength", options.chainLength));
attributes.add(new Attribute.Default<String>("autoOptimize", options.autoOptimize ? "true" : "false"));
if (options.operatorAnalysis) {
attributes.add(new Attribute.Default<String>("operatorAnalysis", options.operatorAnalysisFileName));
}
writer.writeOpenTag("mcmc", attributes);
if (options.hasData()) {
writer.writeOpenTag(CompoundLikelihoodParser.POSTERIOR, new Attribute.Default<String>(XMLParser.ID, "posterior"));
}
// write prior block
writer.writeOpenTag(CompoundLikelihoodParser.PRIOR, new Attribute.Default<String>(XMLParser.ID, "prior"));
if (options.useStarBEAST) { // species
// coalescent prior
writer.writeIDref(MultiSpeciesCoalescentParser.SPECIES_COALESCENT, TraitData.TRAIT_SPECIES + "." + COALESCENT);
// prior on population sizes
// if (options.speciesTreePrior == TreePriorType.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihoodParser.DISTRIBUTION_LIKELIHOOD, SPOPS);
// } else {
// writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
// prior on species tree
writer.writeIDref(SpeciationLikelihoodParser.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
}
parameterPriorGenerator.writeParameterPriors(writer, options.useStarBEAST);
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior = model.getPartitionTreePrior();
treePriorGenerator.writePriorLikelihoodReference(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeMultiLociLikelihoodReference(prior, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_PRIOR, writer);
writer.writeCloseTag(CompoundLikelihoodParser.PRIOR);
if (options.hasData()) {
// write likelihood block
writer.writeOpenTag(CompoundLikelihoodParser.LIKELIHOOD, new Attribute.Default<String>(XMLParser.ID, "likelihood"));
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
branchRatesModelGenerator.writeClockLikelihoodReferences(writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_LIKELIHOOD, writer);
writer.writeCloseTag(CompoundLikelihoodParser.LIKELIHOOD);
writer.writeCloseTag(CompoundLikelihoodParser.POSTERIOR);
}
writer.writeIDref(SimpleOperatorScheduleParser.OPERATOR_SCHEDULE, "operators");
// write log to screen
logGenerator.writeLogToScreen(writer, branchRatesModelGenerator, substitutionModelGenerator);
// write log to file
logGenerator.writeLogToFile(writer, treePriorGenerator, branchRatesModelGenerator,
substitutionModelGenerator, treeLikelihoodGenerator);
// write tree log to file
logGenerator.writeTreeLogToFile(writer);
writer.writeCloseTag("mcmc");
}
} |
package dr.app.beauti.options;
import java.util.ArrayList;
import java.util.List;
import dr.app.beauti.enumTypes.OperatorType;
import dr.app.beauti.enumTypes.PriorScaleType;
import dr.app.beauti.enumTypes.TreePriorType;
import dr.app.beauti.generator.Generator;
import dr.evolution.util.Taxon;
import dr.evomodel.coalescent.GMRFFixedGridImportanceSampler;
import dr.evomodel.operators.TreeNodeSlide;
import dr.evomodel.speciation.SpeciesTreeModel;
import dr.evomodelxml.BirthDeathModelParser;
import dr.evomodelxml.YuleModelParser;
/**
* @author Walter Xie
* @version $Id$
*/
public class STARBEASTOptions extends ModelOptions {
// Instance variables
private final BeautiOptions options;
public final String POP_MEAN = "popMean";
public final String SPECIES_TREE_FILE_NAME = TraitGuesser.Traits.TRAIT_SPECIES
+ "." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME; // species.trees
public STARBEASTOptions(BeautiOptions options) {
this.options = options;
initSpeciesParametersAndOperators();
}
private void initSpeciesParametersAndOperators() {
double spWeights = 5.0;
double spTuning = 0.9;
createParameterJeffreysPrior(TraitGuesser.Traits.TRAIT_SPECIES + "." + POP_MEAN, "Species tree: population hyper-parameter operator",
PriorScaleType.TIME_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY);
// species tree Yule
createParameterJeffreysPrior(TraitGuesser.Traits.TRAIT_SPECIES + "." + YuleModelParser.YULE + "." + YuleModelParser.BIRTH_RATE,
"Speices tree: Yule process birth rate", PriorScaleType.BIRTH_RATE_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY);
// species tree Birth Death
createParameterJeffreysPrior(TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME,
"Speices tree: Birth Death model mean growth rate", PriorScaleType.BIRTH_RATE_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY);
createParameterUniformPrior(TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME,
"Speices tree: Birth Death model relative death rate", PriorScaleType.BIRTH_RATE_SCALE, 0.5, 0.0, 1.0);
createParameterJeffreysPrior(SpeciesTreeModel.SPECIES_TREE + "." + Generator.SPLIT_POPS, "Species tree: population size operator",
PriorScaleType.TIME_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY);
createParameter(TraitGuesser.Traits.TRAIT_SPECIES + "." + TreeNodeSlide.TREE_NODE_REHEIGHT, "Species tree: tree node operator");
createScaleOperator(TraitGuesser.Traits.TRAIT_SPECIES + "." + POP_MEAN, spTuning, spWeights);
createScaleOperator(TraitGuesser.Traits.TRAIT_SPECIES + "." + YuleModelParser.YULE + "." + YuleModelParser.BIRTH_RATE, demoTuning, demoWeights);
createScaleOperator(TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME, demoTuning, demoWeights);
createScaleOperator(TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME, demoTuning, demoWeights);
createScaleOperator(SpeciesTreeModel.SPECIES_TREE + "." + Generator.SPLIT_POPS, 0.5, 94);
createOperator(TraitGuesser.Traits.TRAIT_SPECIES + "." + TreeNodeSlide.TREE_NODE_REHEIGHT, OperatorType.NODE_REHIGHT, demoTuning, 94);
//TODO: more
for (PartitionClockModel model : options.getPartitionClockModels()) {
model.iniClockRateStarBEAST();
}
}
/**
* return a list of parameters that are required
*
* @param params the parameter list
*/
public void selectParameters(List<Parameter> params) {
params.add(getParameter(TraitGuesser.Traits.TRAIT_SPECIES + "." + POP_MEAN));
if (options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_BIRTH_DEATH) {
params.add(getParameter(TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME));
params.add(getParameter(TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME));
} else if (options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_YULE) {
params.add(getParameter(TraitGuesser.Traits.TRAIT_SPECIES + "." + YuleModelParser.YULE + "." + YuleModelParser.BIRTH_RATE));
}
// params.add(getParameter(SpeciesTreeModel.SPECIES_TREE + "." + Generator.SPLIT_POPS));
//TODO: more
}
/**
* return a list of operators that are required
*
* @param ops the operator list
*/
public void selectOperators(List<Operator> ops) {
ops.add(getOperator(TraitGuesser.Traits.TRAIT_SPECIES + "." + POP_MEAN));
if (options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_BIRTH_DEATH) {
ops.add(getOperator(TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME));
ops.add(getOperator(TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME));
// ops.add(getOperator("upDownBirthDeathSpeciesTree"));
// ops.add(getOperator("upDownBirthDeathSTPop"));
// for (PartitionTreeModel tree : getPartitionTreeModels()) {
// ops.add(getOperator(tree.getPrefix() + "upDownBirthDeathGeneTree"));
} else if (options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.SPECIES_YULE) {
ops.add(getOperator(TraitGuesser.Traits.TRAIT_SPECIES + "." + YuleModelParser.YULE + "." + YuleModelParser.BIRTH_RATE));
// ops.add(getOperator("upDownYuleSpeciesTree"));
// ops.add(getOperator("upDownYuleSTPop"));
// for (PartitionTreeModel tree : getPartitionTreeModels()) {
// ops.add(getOperator(tree.getPrefix() + "upDownYuleGeneTree"));
}
ops.add(getOperator(SpeciesTreeModel.SPECIES_TREE + "." + Generator.SPLIT_POPS));
ops.add(getOperator(TraitGuesser.Traits.TRAIT_SPECIES + "." + TreeNodeSlide.TREE_NODE_REHEIGHT));
//TODO: more
}
public boolean isSpeciesAnalysis() {
return options.traitOptions.containTrait(TraitGuesser.Traits.TRAIT_SPECIES.toString());
}
public List<String> getSpeciesList() {
List<String> species = new ArrayList<String>();
String sp;
if (options.taxonList != null) {
for (int i = 0; i < options.taxonList.getTaxonCount(); i++) {
Taxon taxon = options.taxonList.getTaxon(i);
sp = (String) taxon.getAttribute(TraitGuesser.Traits.TRAIT_SPECIES.toString());
if (sp == null) return null;
if (!species.contains(sp)) {
species.add(sp);
}
}
return species;
} else {
return null;
}
}
} |
package dr.evolution.alignment;
import dr.app.bss.XMLExporter;
import dr.app.tools.NexusExporter;
import dr.evolution.datatype.Codons;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.GeneralDataType;
import dr.evolution.sequence.Sequence;
import dr.evolution.sequence.Sequences;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import dr.util.NumberFormatter;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collections;
import java.util.List;
/**
* A simple alignment class that implements gaps by characters in the sequences.
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: SimpleAlignment.java,v 1.46 2005/06/21 16:25:15 beth Exp $
*/
@SuppressWarnings("serial")
public class SimpleAlignment extends Sequences implements Alignment, dr.util.XHTMLable {
// INSTANCE VARIABLES
private OutputType outputType = OutputType.FASTA;
private DataType dataType = null;
private int siteCount = 0;
private boolean siteCountKnown = false;
private boolean countStatistics = !(dataType instanceof Codons) && !(dataType instanceof GeneralDataType);
// private enum outputTypes {
// FASTA, NEXUS, XML
// SimpleAlignment METHODS
/**
* parameterless constructor.
*/
public SimpleAlignment() {
}
/**
* Constructs a sub alignment based on the provided taxa.
*
* @param a
* @param taxa
*/
public SimpleAlignment(Alignment a, TaxonList taxa) {
for (int i = 0; i < taxa.getTaxonCount(); i++) {
Taxon taxon = taxa.getTaxon(i);
Sequence sequence = a.getSequence(a.getTaxonIndex(taxon));
addSequence(sequence);
}
}
// public void setNexusOutput() {
// outputType = OutputType.NEXUS;
// public void setFastaOutput() {
// outputType = OutputType.FASTA;
// public void setXMLOutput() {
// outputType = OutputType.XML;
public void setOutputType(OutputType out) {
outputType = out;
}
public List<Sequence> getSequences() {
return Collections.unmodifiableList(sequences);
}
/**
* Calculates the siteCount by finding the longest sequence.
*/
public void updateSiteCount() {
siteCount = 0;
int i, len, n = getSequenceCount();
for (i = 0; i < n; i++) {
len = getSequence(i).getLength();
if (len > siteCount)
siteCount = len;
}
siteCountKnown = true;
}
// Alignment IMPLEMENTATION
/**
* Sets the dataType of this alignment. This should be the same as
* the sequences.
*/
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
/**
* @return number of sites
*/
public int getSiteCount(DataType dataType) {
return getSiteCount();
}
/**
* sequence character at (sequence, site)
*/
public char getChar(int sequenceIndex, int siteIndex) {
return getSequence(sequenceIndex).getChar(siteIndex);
}
/**
* Returns string representation of single sequence in
* alignment with gap characters included.
*/
public String getAlignedSequenceString(int sequenceIndex) {
return getSequence(sequenceIndex).getSequenceString();
}
/**
* Returns string representation of single sequence in
* alignment with gap characters excluded.
*/
public String getUnalignedSequenceString(int sequenceIndex) {
StringBuffer unaligned = new StringBuffer();
for (int i = 0, n = getSiteCount(); i < n; i++) {
int state = getState(sequenceIndex, i);
if (!dataType.isGapState(state)) {
unaligned.append(dataType.getChar(state));
}
}
return unaligned.toString();
}
// Sequences METHODS
/**
* Add a sequence to the sequence list
*/
public void addSequence(Sequence sequence) {
if (dataType == null) {
if (sequence.getDataType() == null) {
dataType = sequence.guessDataType();
sequence.setDataType(dataType);
} else {
setDataType(sequence.getDataType());
}
} else if (sequence.getDataType() == null) {
sequence.setDataType(dataType);
} else if (dataType != sequence.getDataType()) {
throw new IllegalArgumentException("Sequence's dataType does not match the alignment's");
}
int invalidCharAt = getInvalidChar(sequence.getSequenceString(), dataType);
if (invalidCharAt >= 0)
throw new IllegalArgumentException("Sequence of " + sequence.getTaxon().getId()
+ " contains invalid char \'" + sequence.getChar(invalidCharAt) + "\' at index " + invalidCharAt);
super.addSequence(sequence);
updateSiteCount();
}
/**
* Insert a sequence to the sequence list at position
*/
public void insertSequence(int position, Sequence sequence) {
if (dataType == null) {
if (sequence.getDataType() == null) {
dataType = sequence.guessDataType();
sequence.setDataType(dataType);
} else {
setDataType(sequence.getDataType());
}
} else if (sequence.getDataType() == null) {
sequence.setDataType(dataType);
} else if (dataType != sequence.getDataType()) {
throw new IllegalArgumentException("Sequence's dataType does not match the alignment's");
}
int invalidCharAt = getInvalidChar(sequence.getSequenceString(), dataType);
if (invalidCharAt >= 0)
throw new IllegalArgumentException("Sequence of " + sequence.getTaxon().getId()
+ " contains invalid char \'" + sequence.getChar(invalidCharAt) + "\' at index " + invalidCharAt);
super.insertSequence(position, sequence);
}
/**
* search invalid character in the sequence by given data type, and return its index
*/
protected int getInvalidChar(String sequence, DataType dataType) {
final char[] validChars = dataType.getValidChars();
if (validChars != null) {
String validString = new String(validChars);
for (int i = 0; i < sequence.length(); i++) {
char c = sequence.charAt(i);
if (validString.indexOf(c) < 0) return i;
}
}
return -1;
}
// SiteList IMPLEMENTATION
/**
* @return number of sites
*/
public int getSiteCount() {
if (!siteCountKnown)
updateSiteCount();
return siteCount;
}
/**
* Gets the pattern of site as an array of state numbers (one per sequence)
*
* @return the site pattern at siteIndex
*/
public int[] getSitePattern(int siteIndex) {
Sequence seq;
int i, n = getSequenceCount();
int[] pattern = new int[n];
for (i = 0; i < n; i++) {
seq = getSequence(i);
if (siteIndex >= seq.getLength())
pattern[i] = dataType.getGapState();
else
pattern[i] = seq.getState(siteIndex);
}
return pattern;
}
/**
* Gets the pattern index at a particular site
*
* @return the patternIndex
*/
public int getPatternIndex(int siteIndex) {
return siteIndex;
}
/**
* @return the sequence state at (taxon, site)
*/
public int getState(int taxonIndex, int siteIndex) {
Sequence seq = getSequence(taxonIndex);
if (siteIndex >= seq.getLength()) {
return dataType.getGapState();
}
return seq.getState(siteIndex);
}
public void setState(int taxonIndex, int siteIndex, int state) {
Sequence seq = getSequence(taxonIndex);
if (siteIndex >= seq.getLength()) {
throw new IllegalArgumentException();
}
seq.setState(siteIndex, state);
}
// PatternList IMPLEMENTATION
/**
* @return number of patterns
*/
public int getPatternCount() {
return getSiteCount();
}
/**
* @return number of invariant sites
*/
public int getInvariantCount() {
int invariantSites = 0;
for (int i = 0; i < getSiteCount(); i++) {
int[] pattern = getSitePattern(i);
if (Patterns.isInvariant(pattern)) {
invariantSites++;
}
}
return invariantSites;
}
public int getUniquePatternCount() {
Patterns patterns = new Patterns(this);
return patterns.getPatternCount();
}
public int getInformativeCount() {
Patterns patterns = new Patterns(this);
int informativeCount = 0;
for (int i = 0; i < patterns.getPatternCount(); i++) {
int[] pattern = patterns.getPattern(i);
if (isInformative(pattern)) {
informativeCount += patterns.getPatternWeight(i);
}
}
return informativeCount;
}
public int getSingletonCount() {
Patterns patterns = new Patterns(this);
int singletonCount = 0;
for (int i = 0; i < patterns.getPatternCount(); i++) {
int[] pattern = patterns.getPattern(i);
if (!Patterns.isInvariant(pattern) && !isInformative(pattern)) {
singletonCount += patterns.getPatternWeight(i);
}
}
return singletonCount;
}
private boolean isInformative(int[] pattern) {
int[] stateCounts = new int[getStateCount()];
for (int j = 0; j < pattern.length; j++) {
stateCounts[pattern[j]]++;
}
boolean oneStateGreaterThanOne = false;
boolean secondStateGreaterThanOne = false;
for (int j = 0; j < stateCounts.length; j++) {
if (stateCounts[j] > 1) {
if (!oneStateGreaterThanOne) {
oneStateGreaterThanOne = true;
} else {
secondStateGreaterThanOne = true;
}
}
}
return secondStateGreaterThanOne;
}
/**
* @return number of states for this siteList
*/
public int getStateCount() {
return getDataType().getStateCount();
}
/**
* Gets the length of the pattern strings which will usually be the
* same as the number of taxa
*
* @return the length of patterns
*/
public int getPatternLength() {
return getSequenceCount();
}
/**
* Gets the pattern as an array of state numbers (one per sequence)
*
* @return the pattern at patternIndex
*/
public int[] getPattern(int patternIndex) {
return getSitePattern(patternIndex);
}
/**
* @return state at (taxonIndex, patternIndex)
*/
public int getPatternState(int taxonIndex, int patternIndex) {
return getState(taxonIndex, patternIndex);
}
/**
* Gets the weight of a site pattern (always 1.0)
*/
public double getPatternWeight(int patternIndex) {
return 1.0;
}
/**
* @return the array of pattern weights
*/
public double[] getPatternWeights() {
double[] weights = new double[siteCount];
for (int i = 0; i < siteCount; i++)
weights[i] = 1.0;
return weights;
}
/**
* @return the DataType of this siteList
*/
public DataType getDataType() {
return dataType;
}
/**
* @return the frequency of each state
*/
public double[] getStateFrequencies() {
return PatternList.Utils.empiricalStateFrequencies(this);
}
public void setReportCountStatistics(boolean report) {
countStatistics = report;
}
public String toString() {
return outputType.makeOutputString(this); // generic delegation to ease extensibility
}// END: toString
public String toXHTML() {
String xhtml = "<p><em>Alignment</em> data type = ";
xhtml += getDataType().getDescription();
xhtml += ", no. taxa = ";
xhtml += getTaxonCount();
xhtml += ", no. sites = ";
xhtml += getSiteCount();
xhtml += "</p>";
xhtml += "<pre>";
int length, maxLength = 0;
for (int i = 0; i < getTaxonCount(); i++) {
length = getTaxonId(i).length();
if (length > maxLength)
maxLength = length;
}
for (int i = 0; i < getTaxonCount(); i++) {
length = getTaxonId(i).length();
xhtml += getTaxonId(i);
for (int j = length; j <= maxLength; j++)
xhtml += " ";
xhtml += getAlignedSequenceString(i) + "\n";
}
xhtml += "</pre>";
return xhtml;
}
public enum OutputType {
FASTA("fasta", "fsa") {
@Override
public String makeOutputString(SimpleAlignment alignment) {
NumberFormatter formatter = new NumberFormatter(6);
StringBuffer buffer = new StringBuffer();
// boolean countStatistics = !(dataType instanceof Codons) && !(dataType instanceof GeneralDataType);
if (alignment.countStatistics) {
buffer.append("Site count = ").append(alignment.getSiteCount()).append("\n");
buffer.append("Invariant sites = ").append(alignment.getInvariantCount()).append("\n");
buffer.append("Singleton sites = ").append(alignment.getSingletonCount()).append("\n");
buffer.append("Parsimony informative sites = ").append(alignment.getInformativeCount()).append("\n");
buffer.append("Unique site patterns = ").append(alignment.getUniquePatternCount()).append("\n\n");
}
for (int i = 0; i < alignment.getSequenceCount(); i++) {
String name = formatter.formatToFieldWidth(alignment.getTaxonId(i), 10);
buffer.append(">" + name + "\n");
buffer.append(alignment.getAlignedSequenceString(i) + "\n");
}
return buffer.toString();
}
},
NEXUS("nexus", "nxs") {
@Override
public String makeOutputString(SimpleAlignment alignment) {
StringBuffer buffer = new StringBuffer();
// PrintStream ps = new PrintStream();
try {
File tmp = File.createTempFile("tempfile", ".tmp");
PrintStream ps = new PrintStream(tmp);
NexusExporter nexusExporter = new NexusExporter(ps);
buffer.append(nexusExporter.exportAlignment(alignment));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}// END: toNexus
},
XML("xml", "xml") {
@Override
public String makeOutputString(SimpleAlignment alignment) {
StringBuffer buffer = new StringBuffer();
try {
XMLExporter xmlExporter = new XMLExporter();
buffer.append(xmlExporter.exportAlignment(alignment));
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return buffer.toString();
}// END: toXML
};
private final String text;
private final String extension;
private OutputType(String text, String extension) {
this.text = text;
this.extension = extension;
}
public String getText() {
return text;
}
public String getExtension() {
return extension;
}
public abstract String makeOutputString(SimpleAlignment alignment);
public static OutputType parseFromString(String text) {
for (OutputType type : OutputType.values()) {
if (type.getText().compareToIgnoreCase(text) == 0) {
return type;
}
}
return null;
}
public static OutputType parseFromExtension(String extension) {
for (OutputType type : OutputType.values()) {
if (type.getExtension().compareToIgnoreCase(extension) == 0) {
return type;
}
}
return null;
}
}
}// END: class |
package dr.evomodel.operators;
import dr.evolution.tree.MutableTree;
import dr.evolution.tree.NodeRef;
import dr.evomodel.tree.TreeModel;
import dr.inference.operators.MCMCOperator;
import dr.inference.operators.OperatorFailedException;
import dr.inference.operators.SimpleMCMCOperator;
import dr.math.MathUtils;
import dr.xml.*;
/**
* Implements branch exchange operations.
* There is a NARROW and WIDE variety.
* The narrow exchange is very similar to a rooted-tree
* nearest-neighbour interchange but with the restriction
* that node height must remain consistent.
* <p/>
* KNOWN BUGS: WIDE operator cannot be used on trees with 4 or less tips!
*/
public class ExchangeOperator extends SimpleMCMCOperator {
public static final String NARROW_EXCHANGE = "narrowExchange";
public static final String WIDE_EXCHANGE = "wideExchange";
public static final String INTERMEDIATE_EXCHANGE = "intermediateExchange";
public static final int NARROW = 0;
public static final int WIDE = 1;
public static final int INTERMEDIATE = 2;
private static final int MAX_TRIES = 10000;
private int mode = NARROW;
private TreeModel tree;
private double[] distances;
public ExchangeOperator(int mode, TreeModel tree, double weight) {
this.mode = mode;
this.tree = tree;
setWeight(weight);
}
public double doOperation() throws OperatorFailedException {
int tipCount = tree.getExternalNodeCount();
double hastingsRatio = 0;
switch (mode) {
case NARROW:
narrow();
break;
case WIDE:
wide();
break;
case INTERMEDIATE:
hastingsRatio = intermediate();
break;
}
if (tree.getExternalNodeCount() != tipCount) {
throw new RuntimeException("Lost some tips in " + ((mode == NARROW) ? "NARROW mode." : "WIDE mode."));
}
return hastingsRatio;
}
/**
* WARNING: Assumes strictly bifurcating tree.
*/
public void narrow() throws OperatorFailedException {
final int nNodes = tree.getNodeCount();
final NodeRef root = tree.getRoot();
for (int tries = 0; tries < MAX_TRIES; ++tries) {
NodeRef i = tree.getNode(MathUtils.nextInt(nNodes));
while (root == i || tree.getParent(i) == root) {
i = tree.getNode(MathUtils.nextInt(nNodes));
}
final NodeRef iParent = tree.getParent(i);
final NodeRef iGrandParent = tree.getParent(iParent);
NodeRef iUncle = tree.getChild(iGrandParent, 0);
if (iUncle == iParent) {
iUncle = tree.getChild(iGrandParent, 1);
}
assert tree.getNodeHeight(i) < tree.getNodeHeight(iGrandParent);
if (tree.getNodeHeight(iUncle) < tree.getNodeHeight(iParent)) {
eupdate(i, iUncle, iParent, iGrandParent);
tree.pushTreeChangedEvent(iParent);
tree.pushTreeChangedEvent(iGrandParent);
return;
}
}
//System.out.println("tries = " + tries);
throw new OperatorFailedException("Couldn't find valid narrow move on this tree!!");
}
/**
* WARNING: Assumes strictly bifurcating tree.
*/
public void wide() throws OperatorFailedException {
final int nodeCount = tree.getNodeCount();
final NodeRef root = tree.getRoot();
// I don't know how to prove this but it seems that there are exactly k(k-1) permissable pairs for k+1
// contemporaneous tips, and since the total is 2k * (2k-1) / 2, so the average number of tries is 2.
// With serial data the average number of tries can be made arbitrarily high as tree becomes less balanced.
for (int tries = 0; tries < MAX_TRIES; ++tries) {
NodeRef i = root; // tree.getNode(MathUtils.nextInt(nodeCount));
while (root == i) {
i = tree.getNode(MathUtils.nextInt(nodeCount));
}
NodeRef j = i; //tree.getNode(MathUtils.nextInt(nodeCount));
while (j == i || j == root) {
j = tree.getNode(MathUtils.nextInt(nodeCount));
}
final NodeRef iP = tree.getParent(i);
final NodeRef jP = tree.getParent(j);
if ((iP != jP) && (i != jP) && (j != iP) &&
(tree.getNodeHeight(j) < tree.getNodeHeight(iP)) &&
(tree.getNodeHeight(i) < tree.getNodeHeight(jP))) {
eupdate(i, j, iP, jP);
//System.out.println("tries = " + tries+1);
return;
}
}
throw new OperatorFailedException("Couldn't find valid wide move on this tree!");
}
/**
* WARNING: Assumes strictly bifurcating tree.
*/
public double intermediate() throws OperatorFailedException {
final int nodeCount = tree.getNodeCount();
final NodeRef root = tree.getRoot();
for(int tries = 0; tries < MAX_TRIES; ++tries) {
NodeRef i, j;
NodeRef[] possibleNodes;
do {
// get a random node
i = root; // tree.getNode(MathUtils.nextInt(nodeCount));
// if (root != i) {
// possibleNodes = tree.getNodes();
// check if we got the root
while (root == i) {
// if so get another one till we haven't got anymore the root
i = tree.getNode(MathUtils.nextInt(nodeCount));
// if (root != i) {
// possibleNodes = tree.getNodes();
}
possibleNodes = tree.getNodes();
// get another random node
// NodeRef j = tree.getNode(MathUtils.nextInt(nodeCount));
j = getRandomNode(possibleNodes, i);
// check if they are the same and if the new node is the root
} while (j == null || j == i || j == root);
double forward = getWinningChance(indexOf(possibleNodes, j));
// possibleNodes = getPossibleNodes(j);
calcDistances(possibleNodes, j);
forward += getWinningChance(indexOf(possibleNodes, i));
// get the parent of both of them
final NodeRef iP = tree.getParent(i);
final NodeRef jP = tree.getParent(j);
// check if both parents are equal -> we are siblings :) (this
// wouldnt effect a change og topology)
// check if I m your parent or vice versa (this would destroy the
// tree)
// check if you are younger then my father
// check if I m younger then your father
if ((iP != jP) && (i != jP) && (j != iP)
&& (tree.getNodeHeight(j) < tree.getNodeHeight(iP))
&& (tree.getNodeHeight(i) < tree.getNodeHeight(jP))) {
// if 1 & 2 are false and 3 & 4 are true then we found a valid
// candidate
exchangeNodes(tree, i, j, iP, jP);
// possibleNodes = getPossibleNodes(i);
calcDistances(possibleNodes, i);
double backward = getWinningChance(indexOf(possibleNodes, j));
// possibleNodes = getPossibleNodes(j);
calcDistances(possibleNodes, j);
backward += getWinningChance(indexOf(possibleNodes, i));
// System.out.println("tries = " + tries+1);
return Math.log(Math.min(1, (backward) / (forward)));
// return 0.0;
}
}
throw new OperatorFailedException("Couldn't find valid wide move on this tree!");
}
/* why not use Arrays.asList(a).indexOf(n) ? */
private int indexOf(NodeRef [] a, NodeRef n) {
for (int i=0; i<a.length; i++){
if (a[i] == n){
return i;
}
}
return -1;
}
private double getWinningChance(int index) {
double sum = 0;
for (int i = 0; i < distances.length; i++) {
sum += (1.0 / distances[i]);
}
return (1.0 / distances[index]) / sum;
}
private void calcDistances(NodeRef [] nodes, NodeRef ref) {
distances = new double[nodes.length];
for (int i = 0; i < nodes.length; i++) {
distances[i] = getNodeDistance(ref, nodes[i]) + 1;
}
}
private NodeRef getRandomNode(NodeRef [] nodes, NodeRef ref) {
calcDistances(nodes, ref);
double sum = 0;
for (int i = 0; i < distances.length; i++) {
sum += 1.0 / distances[i];
}
double randomValue = MathUtils.nextDouble() * sum;
NodeRef n = null;
for (int i = 0; i < distances.length; i++) {
randomValue -= 1.0 / distances[i];
if (randomValue <= 0) {
n = nodes[i];
break;
}
}
return n;
}
private int getNodeDistance(NodeRef i, NodeRef j) {
int count = 0;
while (i != j) {
count++;
if (tree.getNodeHeight(i) < tree.getNodeHeight(j)) {
i = tree.getParent(i);
} else {
j = tree.getParent(j);
}
}
return count;
}
public int getMode() {
return mode;
}
public String getOperatorName() {
return ((mode == NARROW) ? "Narrow" : "Wide") + " Exchange";
}
/* exchange subtrees whose root are i and j */
private void eupdate(NodeRef i, NodeRef j, NodeRef iP, NodeRef jP) throws OperatorFailedException {
tree.beginTreeEdit();
tree.removeChild(iP, i);
tree.removeChild(jP, j);
tree.addChild(jP, i);
tree.addChild(iP, j);
try {
tree.endTreeEdit();
} catch (MutableTree.InvalidTreeException ite) {
throw new OperatorFailedException(ite.toString());
}
}
public double getMinimumAcceptanceLevel() {
if (mode == NARROW) return 0.05;
else return 0.01;
}
public double getMinimumGoodAcceptanceLevel() {
if (mode == NARROW) return 0.05;
else return 0.01;
}
public String getPerformanceSuggestion() {
if (MCMCOperator.Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) {
return "";
} else if (MCMCOperator.Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()) {
return "";
} else {
return "";
}
}
public static XMLObjectParser NARROW_EXCHANGE_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return NARROW_EXCHANGE;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
double weight = xo.getDoubleAttribute("weight");
return new ExchangeOperator(NARROW, treeModel, weight);
} |
package edu.jhu.thrax.hadoop.tools;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import edu.jhu.thrax.ThraxConfig;
import edu.jhu.thrax.util.ConfFileParser;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.features.mapred.MapReduceFeature;
import java.util.Map;
public class FeatureTool extends Configured implements Tool
{
public int run(String [] argv) throws Exception
{
if (argv.length < 2) {
System.err.println("usage: FeatureTool <conf file> <feature>");
return 1;
}
String confFile = argv[0];
String featureName = argv[1];
MapReduceFeature f = FeatureJobFactory.get(featureName);
if (!(f instanceof MapReduceFeature)) {
System.err.println("Not a MapReduceFeature: " + featureName);
return 1;
}
Configuration conf = getConf();
Map<String,String> options = ConfFileParser.parse(confFile);
for (String opt : options.keySet()) {
conf.set("thrax." + opt, options.get(opt));
}
String workDir = conf.get("thrax.work-dir");
if (workDir == null) {
System.err.println("set work-dir key in conf file " + confFile + "!");
return 1;
}
if (!workDir.endsWith(Path.SEPARATOR)) {
workDir += Path.SEPARATOR;
conf.set("thrax.work-dir", workDir);
}
Job job = new Job(conf, String.format("thrax-%s", featureName));
job.setJarByClass(f.getClass());
job.setMapperClass(f.mapperClass());
job.setCombinerClass(f.combinerClass());
job.setSortComparatorClass(f.sortComparatorClass());
job.setPartitionerClass(f.partitionerClass());
job.setReducerClass(f.reducerClass());
job.setInputFormatClass(SequenceFileInputFormat.class);
job.setMapOutputKeyClass(RuleWritable.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(RuleWritable.class);
job.setOutputValueClass(IntWritable.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.setInputPaths(job, new Path(workDir + "rules"));
FileOutputFormat.setOutputPath(job, new Path(workDir + featureName));
job.submit();
return 0;
}
public static void main(String [] argv) throws Exception
{
int exitCode = ToolRunner.run(null, new FeatureTool(), argv);
return;
}
} |
import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.model.GeocodingResult;
public class Hello {
public static void main(String[] args) throws Exception {
GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyCL9BI_9U8ba_Zf_ldHd9KrYFtBtK7cTzI");
GeocodingResult[] results = GeocodingApi.geocode(context,"Lviv").await();
System.out.println(results[0].formattedAddress);
}
} |
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class ADBInterface {
private String OS_NAME;
private int OS; // int representing OS
private String FS; // file separator. '/' or '\'
private String PWD; // no trailing slash
private String ADBPATH;
private final int WINDOWS = 1;
private final int MAC = 2;
private final int LINUX = 3;
private final int OTHER = 4;
public final int DEVICE_NOT_FOUND = 1;
public final int OUTPUT_EMPTY = 2;
public final int FAILED = 4;
public final int NO_SUCH_FILE = 5;
ADBInterface() {
this.OS_NAME = System.getProperty("os.name");
this.FS = System.getProperty("file.separator");
PWD = new File("").getAbsolutePath();
if (OS_NAME.contains("Windows")) {
OS = WINDOWS;
ADBPATH = PWD+FS+"ADB"+FS+"adb.exe";
} else if (OS_NAME.contains("Mac")) {
OS = MAC;
ADBPATH = PWD+FS+"ADB"+FS+"adbmac";
} else if (OS_NAME.contains("Linux")) {
OS = LINUX;
ADBPATH = PWD+FS+"ADB"+FS+"adblinux";
} else {
OS = OTHER;
ADBPATH = PWD+FS+"ADB"+FS+"adblinux"; // default to Linux, so we have minimal support for Unix, BSD, etc.
}
}
// not done
public int startDaemon() {
// LINUX
if (OS == LINUX) {
execute(new String[] { ADBPATH, "kill-server" }); // kill any unprivileged instances of ADB
execute(new String[]{"killall", "adblinux"}); // kill any unprivileged instances of ADB
execute(new String[]{"killall", "adb"}); // kill any unprivileged instances of ADB
//output = execute(new String[]{"gksudo", "--description", "gksudo.config", pwd + "/ADB/adblinux", "devices"}).toLowerCase();
//output2 = execute(new String[]{"gksudo", "--description", "gksudo.config", pwd + "/ADB/adblinux", "push", "bootanimation.zip", "/data/local/"}).toLowerCase();
} // WINDOWS
else if (OS == WINDOWS) {
execute(new String[]{"taskkill", "/f", "/IM", "adb.exe"});
//output = execute(new String[]{pwd + "\\ADB\\adb.exe", "devices"}, "daemon not running").toLowerCase();
System.out.println("BEGIN FLASH");
//output2 = execute(new String[]{pwd + "\\ADB\\adb.exe", "push", "bootanimation.zip", "/data/local/"}).toLowerCase();
}
else { return 3; }
return 0;
}
public int push(String sourceFile, String destFile) {
String output = null;
switch (OS) {
case LINUX:
output = execute(new String[] { "gksudo", "--description", "gksudo.config", ADBPATH, "push", sourceFile, destFile });
break;
case WINDOWS:
output = execute(new String[] { ADBPATH, "push", sourceFile, destFile });
break;
case MAC:
output = execute(new String[] { ADBPATH, "push", sourceFile, destFile });
break;
default:
output = execute(new String[] { ADBPATH, "push", sourceFile, destFile });
break;
}
int result = parseOutput(output);
return result;
}
public int pull(String sourceFile, String destFile) {
String output = null;
switch (OS) {
case LINUX:
output = execute(new String[] { "gksudo", "--description", "gksudo.config", ADBPATH, "pull", sourceFile, destFile });
break;
case WINDOWS:
output = execute(new String[] { ADBPATH, "pull", sourceFile, destFile });
break;
case MAC:
output = execute(new String[] { ADBPATH, "pull", sourceFile, destFile });
break;
default:
output = execute(new String[] { ADBPATH, "pull", sourceFile, destFile });
break;
}
int result = parseOutput(output);
return result;
}
private int parseOutput(String output) {
output = output.toLowerCase();
if ( output.contains("device not found") ) { return DEVICE_NOT_FOUND; }
else if ( removeWhitespace(output).isEmpty() ) { return OUTPUT_EMPTY; }
else if ( output.contains("failed") ) { return FAILED; }
else if ( output.contains("no such file or directory") ) { return NO_SUCH_FILE; }
else { return 0; }
}
// sometimes things don't return, so we make them return with this sentinel value
String execute(String[] strings, String sentinel) {
String output = "";
try {
ProcessBuilder builder = new ProcessBuilder(strings);
builder.redirectErrorStream(true);
Process proc = builder.start();
InputStream processOutput = proc.getInputStream();
int c = 0;
byte[] buffer = new byte[2048];
while((c = processOutput.read(buffer)) != -1 ) {
output += new String(buffer);
if (output.toLowerCase().contains(sentinel)) { return output; }
System.out.write(buffer, 0, c);
}
} catch (IOException e) { e.printStackTrace(); }
return output;
}
private static String execute(String[] strings) {
String output = "";
try {
ProcessBuilder builder = new ProcessBuilder(strings);
builder.redirectErrorStream(true);
Process proc = builder.start();
InputStream processOutput = proc.getInputStream();
int c = 0;
byte[] buffer = new byte[2048];
while((c = processOutput.read(buffer)) != -1 ) {
output += new String(buffer);
System.out.write(buffer, 0, c);
}
} catch (IOException e) { e.printStackTrace(); }
return output;
}
private static String removeWhitespace(String output) {
return output.replaceAll(" ", "").replaceAll("\n", "").replaceAll("\t", "");
}
} |
package com.kuxhausen.huemore;
import com.google.gson.Gson;
import com.kuxhausen.huemore.state.HueState;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class MoodManualPagingFragment extends Fragment {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments representing each object in a collection. We use a
* {@link android.support.v4.app.FragmentStatePagerAdapter} derivative,
* which will destroy and re-create fragments as needed, saving and
* restoring their state in the process. This is important to conserve
* memory and is a best practice when allowing navigation between objects in
* a potentially large collection.
*/
MoodManualPagerAdapter mMoodManualPagerAdapter;
private static final int MOOD_LOCATION = 1;
private static final int MANUAL_LOCATION = 0;
/**
* The {@link android.support.v4.view.ViewPager} that will display the
* object collection.
*/
ViewPager mViewPager;
SeekBar brightnessBar;
public Context parrentActivity;
int brightness;
// The container Activity must implement this interface so the frag can
// deliver messages
public interface OnMoodManualSelectedListener {
/** Called by HeadlinesFragment when a list item is selected */
public void onMoodManualSelected(String jSon);
}
public void reset() {
((MoodsFragment) (mMoodManualPagerAdapter.getItem(MOOD_LOCATION)))
.updateGroupView();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
parrentActivity = this.getActivity();
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.moodmanual_pager, container,
false);
Bundle args = getArguments();
// Create an adapter that when requested, will return a fragment
// representing an object in
// the collection.
// ViewPager and its adapters use support library fragments, so we must
// use
// getSupportFragmentManager.
mMoodManualPagerAdapter = new MoodManualPagerAdapter(this);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) myView.findViewById(R.id.pager);
mViewPager.setAdapter(mMoodManualPagerAdapter);
brightnessBar = (SeekBar) myView.findViewById(R.id.brightnessBar);
brightnessBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
HueState hs = new HueState();
hs.bri = brightness;
hs.on = true;
Gson gs = new Gson();
String[] brightnessState = { gs.toJson(hs) };
// TODO deal with off?
((MainActivity) parrentActivity)
.onBrightnessChanged(brightnessState);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
brightness = progress;
}
});
return myView;
}
/**
* A {@link android.support.v4.app.FragmentStatePagerAdapter} that returns a
* fragment representing an object in the collection.
*/
public static class MoodManualPagerAdapter extends FragmentPagerAdapter {
public MoodManualPagerAdapter(android.support.v4.app.Fragment fragment) {
super(fragment.getChildFragmentManager());
// write your code here
}
@Override
public Fragment getItem(int i) {
switch (i) {
case MOOD_LOCATION:
// TODO cache somewhere
return new MoodsFragment();
case MANUAL_LOCATION:
return new NewColorHueFragment();
default:
return null;
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case MOOD_LOCATION:
return "MOODS";// TODO figure out how to make static references
// to strings.xml
case MANUAL_LOCATION:
return "MANUAL";
}
return "";
}
}
} |
package com.cky.learnandroiddetails;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.widget.LinearLayout;
public class MyLayout extends LinearLayout {
/*
*Scroller
* */
public MyLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//return super.onInterceptTouchEvent(ev);
return false;
}
/*
*VelocityTracker
* */
@Override
public boolean onTouchEvent(MotionEvent event) {
VelocityTracker velocityTracker = VelocityTracker.obtain();
velocityTracker.addMovement(event);
velocityTracker.computeCurrentVelocity(1000);// 1000ms
int xVelocity = (int) velocityTracker.getXVelocity();
int yVelocity = (int) velocityTracker.getYVelocity();
velocityTracker.clear();
velocityTracker.recycle();
return super.onTouchEvent(event);
}
} |
package com.coomweather.android;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void get(){
Log.d("MainActivity.class","");
}
} |
package com.emsilabs.emsitether;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "USB Tether Notification. ", Snackbar.LENGTH_LONG)
.setAction("GO", new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent ngintent = new Intent();
ngintent.setAction(Intent.ACTION_MAIN);
ComponentName com = new ComponentName("com.android.settings", "com.android.settings.TetherSettings");
ngintent.setComponent(com);
startActivity(ngintent);
}
})
.show();
}
});
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
} |
package com.samourai.wallet.util;
import android.util.Patterns;
import com.samourai.wallet.SamouraiWallet;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.segwit.bech32.Bech32;
import com.samourai.wallet.segwit.bech32.SegwitAddress;
import org.apache.commons.lang3.tuple.Pair;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.Base58;
import org.bitcoinj.core.WrongNetworkException;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.uri.BitcoinURI;
import org.bitcoinj.uri.BitcoinURIParseException;
import org.bouncycastle.util.encoders.Hex;
import java.nio.ByteBuffer;
import java.util.regex.Pattern;
//import android.util.Log;
public class FormatsUtil {
private Pattern emailPattern = Patterns.EMAIL_ADDRESS;
private Pattern phonePattern = Pattern.compile("(\\+[1-9]{1}[0-9]{1,2}+|00[1-9]{1}[0-9]{1,2}+)[\\(\\)\\.\\-\\s\\d]{6,16}");
public static final String XPUB = "^xpub[1-9A-Za-z][^OIl]+$";
public static final String HEX = "^[0-9A-Fa-f]+$";
private static FormatsUtil instance = null;
private FormatsUtil() { ; }
public static FormatsUtil getInstance() {
if(instance == null) {
instance = new FormatsUtil();
}
return instance;
}
public String validateBitcoinAddress(final String address) {
if(isValidBitcoinAddress(address)) {
return address;
}
else {
String addr = uri2BitcoinAddress(address);
if(addr != null) {
return addr;
}
else {
return null;
}
}
}
public boolean isBitcoinUri(final String s) {
boolean ret = false;
BitcoinURI uri = null;
try {
uri = new BitcoinURI(s);
ret = true;
}
catch(BitcoinURIParseException bupe) {
ret = false;
}
return ret;
}
public String getBitcoinUri(final String s) {
String ret = null;
BitcoinURI uri = null;
try {
uri = new BitcoinURI(s);
ret = uri.toString();
}
catch(BitcoinURIParseException bupe) {
ret = null;
}
return ret;
}
public String getBitcoinAddress(final String s) {
String ret = null;
BitcoinURI uri = null;
try {
uri = new BitcoinURI(s);
ret = uri.getAddress().toString();
}
catch(BitcoinURIParseException bupe) {
ret = null;
}
return ret;
}
public String getBitcoinAmount(final String s) {
String ret = null;
BitcoinURI uri = null;
try {
uri = new BitcoinURI(s);
if(uri.getAmount() != null) {
ret = uri.getAmount().toString();
}
else {
ret = "0.0000";
}
}
catch(BitcoinURIParseException bupe) {
ret = null;
}
return ret;
}
public boolean isValidBitcoinAddress(final String address) {
boolean ret = false;
Address addr = null;
if((!SamouraiWallet.getInstance().isTestNet() && (address.startsWith("bc") || address.startsWith("BC"))
|| (SamouraiWallet.getInstance().isTestNet() && (address.startsWith("tb") || address.startsWith("TB"))))) {
try {
Pair<Byte, byte[]> pair = SegwitAddress.decode(address.substring(0, 2), address);
if(pair.getLeft() == null || pair.getRight() == null) {
;
}
else {
ret = true;
}
}
catch(Exception e) {
;
}
}
else {
try {
addr = new Address(SamouraiWallet.getInstance().getCurrentNetworkParams(), address);
if(addr != null) {
ret = true;
}
}
catch(WrongNetworkException wne) {
ret = false;
}
catch(AddressFormatException afe) {
ret = false;
}
}
return ret;
}
public boolean isValidBech32(final String address) {
boolean ret = false;
try {
Pair<String, byte[]> pair0 = Bech32.bech32Decode(address);
if(pair0.getLeft() == null || pair0.getRight() == null) {
ret = false;
}
else {
Pair<Byte, byte[]> pair1 = SegwitAddress.decode(address.substring(0, 2), address);
if(pair1.getLeft() == null || pair1.getRight() == null) {
ret = false;
}
else {
ret = true;
}
}
}
catch(Exception e) {
ret = false;
}
return ret;
}
private String uri2BitcoinAddress(final String address) {
String ret = null;
BitcoinURI uri = null;
try {
uri = new BitcoinURI(address);
ret = uri.getAddress().toString();
}
catch(BitcoinURIParseException bupe) {
ret = null;
}
return ret;
}
public boolean isValidXpub(String xpub){
try {
byte[] xpubBytes = Base58.decodeChecked(xpub);
ByteBuffer byteBuffer = ByteBuffer.wrap(xpubBytes);
int version = byteBuffer.getInt();
if(version != 0x0488B21E && version != 0x043587CF) {
throw new AddressFormatException("invalid version: " + xpub);
}
else {
byte[] chain = new byte[32];
byte[] pub = new byte[33];
// depth:
byteBuffer.get();
// parent fingerprint:
byteBuffer.getInt();
// child no.
byteBuffer.getInt();
byteBuffer.get(chain);
byteBuffer.get(pub);
ByteBuffer pubBytes = ByteBuffer.wrap(pub);
int firstByte = pubBytes.get();
if(firstByte == 0x02 || firstByte == 0x03){
return true;
}else{
return false;
}
}
}
catch(Exception e) {
return false;
}
}
public boolean isValidPaymentCode(String pcode){
try {
PaymentCode paymentCode = new PaymentCode(pcode);
return paymentCode.isValid();
}
catch(Exception e) {
return false;
}
}
public boolean isValidBIP47OpReturn(String op_return){
byte[] buf = Hex.decode(op_return);
if(buf.length == 80 && buf[0] == 0x01 && buf[1] == 0x00 && (buf[2] == 0x02 || buf[2] == 0x03)) {
return true;
}
else {
return false;
}
}
} |
package com.tlongdev.bktf;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.text.Html;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.tlongdev.bktf.data.PriceListContract.PriceEntry;
import com.tlongdev.bktf.data.UserBackpackContract.UserBackpackEntry;
import java.io.IOException;
import java.io.InputStream;
/**
* The (dialog) activity for showing info about an item in a backpack.
*/
public class ItemDetailActivity extends Activity {
public static final String LOG_TAG = ItemDetailActivity.class.getSimpleName();
//Keys for the extra data in the intent
public static final String EXTRA_ITEM_ID = "id";
public static final String EXTRA_GUEST = "guest";
public static final String EXTRA_ITEM_NAME = "name";
public static final String EXTRA_ITEM_TYPE = "type";
public static final String EXTRA_PROPER_NAME = "proper";
//Indexes for the columns below
public static final int COL_BACKPACK_DEFI = 1;
public static final int COL_BACKPACK_QUAL = 2;
public static final int COL_BACKPACK_CRFN = 3; // TODO
public static final int COL_BACKPACK_TRAD = 4;
public static final int COL_BACKPACK_CRAF = 5;
public static final int COL_BACKPACK_INDE = 6;
public static final int COL_BACKPACK_PAINT = 7;
public static final int COL_BACKPACK_AUS = 8;
public static final int COL_BACKPACK_CRAFTER = 9;
public static final int COL_BACKPACK_GIFTER = 10;
public static final int COL_BACKPACK_CUSTOM_NAME = 11;
public static final int COL_BACKPACK_CUSTOM_DESC = 12;
public static final int COL_BACKPACK_LEVEL = 13;
public static final int COL_BACKPACK_EQUIP = 14; // TODO
public static final int COL_BACKPACK_ORIGIN = 15;
//Query columns for querying the price
public static final String[] QUERY_COLUMNS_PRICE = {
PriceEntry.TABLE_NAME + "." + PriceEntry._ID,
PriceEntry.COLUMN_ITEM_PRICE,
PriceEntry.COLUMN_ITEM_PRICE_MAX,
PriceEntry.COLUMN_ITEM_PRICE_CURRENCY
};
//Indexes for the columns above
public static final int COL_PRICE_LIST_PRICE = 1;
public static final int COL_PRICE_LIST_PMAX = 2;
public static final int COL_PRICE_LIST_CURRENCY = 3;
//Query columns for querying info of the item
private static final String[] QUERY_COLUMNS = {
UserBackpackEntry.TABLE_NAME + "." + UserBackpackEntry._ID,
UserBackpackEntry.COLUMN_DEFINDEX,
UserBackpackEntry.COLUMN_QUALITY,
UserBackpackEntry.COLUMN_CRAFT_NUMBER,
UserBackpackEntry.COLUMN_FLAG_CANNOT_TRADE,
UserBackpackEntry.COLUMN_FLAG_CANNOT_CRAFT,
UserBackpackEntry.COLUMN_ITEM_INDEX,
UserBackpackEntry.COLUMN_PAINT,
UserBackpackEntry.COLUMN_AUSTRALIUM,
UserBackpackEntry.COLUMN_CREATOR_NAME,
UserBackpackEntry.COLUMN_GIFTER_NAME,
UserBackpackEntry.COLUMN_CUSTOM_NAME,
UserBackpackEntry.COLUMN_CUSTOM_DESCRIPTION,
UserBackpackEntry.COLUMN_LEVEL,
UserBackpackEntry.COLUMN_EQUIPPED,
UserBackpackEntry.COLUMN_ORIGIN
};
private static final String[] QUERY_COLUMNS_GUEST = {
UserBackpackEntry.TABLE_NAME_GUEST + "." + UserBackpackEntry._ID,
UserBackpackEntry.COLUMN_DEFINDEX,
UserBackpackEntry.COLUMN_QUALITY,
UserBackpackEntry.COLUMN_CRAFT_NUMBER,
UserBackpackEntry.COLUMN_FLAG_CANNOT_TRADE,
UserBackpackEntry.COLUMN_FLAG_CANNOT_CRAFT,
UserBackpackEntry.COLUMN_ITEM_INDEX,
UserBackpackEntry.COLUMN_PAINT,
UserBackpackEntry.COLUMN_AUSTRALIUM,
UserBackpackEntry.COLUMN_CREATOR_NAME,
UserBackpackEntry.COLUMN_GIFTER_NAME,
UserBackpackEntry.COLUMN_CUSTOM_NAME,
UserBackpackEntry.COLUMN_CUSTOM_DESCRIPTION,
UserBackpackEntry.COLUMN_LEVEL,
UserBackpackEntry.COLUMN_EQUIPPED,
UserBackpackEntry.COLUMN_ORIGIN
};
//This decides which table to load data from.
private boolean isGuest;
//This is the id of the item in the database table
private int id;
//Rerefernces to all the textviews in the view
private TextView name;
private TextView level;
private TextView effect;
private TextView customName;
private TextView customDesc;
private TextView crafterName;
private TextView gifterName;
private TextView origin;
private TextView paint;
private TextView price;
//References to the imageview
private ImageView icon;
private ImageView background;
//Store the intent that came
private Intent mIntent;
/**
* {@inheritDoc}
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
//Store the intent
mIntent = getIntent();
//Get extra data
isGuest = mIntent.getBooleanExtra(EXTRA_GUEST, false);
id = mIntent.getIntExtra(EXTRA_ITEM_ID, 0);
//Scale the icon, so the width of the image view is on third of the screen's width
int screenWidth = getResources().getDisplayMetrics().widthPixels;
FrameLayout layout = (FrameLayout) findViewById(R.id.relative_layout_image);
layout.getLayoutParams().width = screenWidth / 3;
layout.getLayoutParams().height = screenWidth / 3;
layout.requestLayout();
//Cardview which makes it look like a dialog
final CardView cardView = (CardView) findViewById(R.id.card_view);
//Return to the previous activity if the user taps utside te dialog.
((View) cardView.getParent()).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 21)
finishAfterTransition();
else
finish();
}
});
//Do nathing if the user taps on the cardview itself
cardView.setOnClickListener(null);
//Find all the views
name = (TextView) findViewById(R.id.text_view_name);
level = (TextView) findViewById(R.id.text_view_level);
effect = (TextView) findViewById(R.id.text_view_effect_name);
customName = (TextView) findViewById(R.id.text_view_custom_name);
customDesc = (TextView) findViewById(R.id.text_view_custom_desc);
crafterName = (TextView) findViewById(R.id.text_view_crafted);
gifterName = (TextView) findViewById(R.id.text_view_gifted);
origin = (TextView) findViewById(R.id.text_view_origin);
paint = (TextView) findViewById(R.id.text_view_paint);
price = (TextView) findViewById(R.id.text_view_price);
icon = (ImageView) findViewById(R.id.image_view_item_icon);
background = (ImageView) findViewById(R.id.image_view_item_background);
queryItemDetails();
}
/**
* Query all the necessary data out of the database and show them to de user.
*/
private void queryItemDetails() {
//Variables needed for querying
Uri uri;
String[] columns;
String selection;
if (isGuest) {
//The user is a guest user
uri = UserBackpackEntry.CONTENT_URI_GUEST;
columns = QUERY_COLUMNS_GUEST;
selection = UserBackpackEntry.TABLE_NAME_GUEST + "." +
UserBackpackEntry._ID + " = ?";
} else {
//The user is the main user
uri = UserBackpackEntry.CONTENT_URI;
columns = QUERY_COLUMNS;
selection = UserBackpackEntry.TABLE_NAME + "." +
UserBackpackEntry._ID + " = ?";
}
//Query
Cursor itemCursor = getContentResolver().query(
uri,
columns,
selection,
new String[]{"" + id},
null
);
int defindex;
int priceIndex;
int tradable;
int craftable;
int quality;
int isAus;
if (itemCursor.moveToFirst()) {
//Store all the data
defindex = itemCursor.getInt(COL_BACKPACK_DEFI);
priceIndex = itemCursor.getInt(COL_BACKPACK_INDE);
tradable = Math.abs(itemCursor.getInt(COL_BACKPACK_TRAD) - 1);
craftable = Math.abs(itemCursor.getInt(COL_BACKPACK_CRAF) - 1);
quality = itemCursor.getInt(COL_BACKPACK_QUAL);
isAus = itemCursor.getInt(COL_BACKPACK_AUS);
String customName = itemCursor.getString(COL_BACKPACK_CUSTOM_NAME);
String customDescription = itemCursor.getString(COL_BACKPACK_CUSTOM_DESC);
String crafter = itemCursor.getString(COL_BACKPACK_CRAFTER);
String gifter = itemCursor.getString(COL_BACKPACK_GIFTER);
int paintNumber = itemCursor.getInt(COL_BACKPACK_PAINT);
//Set the name of the item
name.setText(Utility.formatSimpleItemName(
mIntent.getStringExtra(EXTRA_ITEM_NAME),
quality,
priceIndex,
mIntent.getIntExtra(EXTRA_PROPER_NAME, 0) == 1));
//Set the level of the item, get the type from the intent
level.setText("Level " + itemCursor.getInt(COL_BACKPACK_LEVEL) + " " +
mIntent.getStringExtra(EXTRA_ITEM_TYPE));
//Set the origin of the item. Get the origin from the string array resource
origin.setText("Origin: " + getResources().getStringArray(R.array.array_origins)
[itemCursor.getInt(COL_BACKPACK_ORIGIN)]);
//Set the effect of the item (if any)
if (priceIndex != 0 && (quality == 5 || quality == 7 || quality == 9)) {
effect.setText("Effect: " + Utility.getUnusualEffectName(priceIndex));
effect.setVisibility(View.VISIBLE);
}
//set the custom name of the item (if any)
if (customName != null) {
this.customName.setText(Html.fromHtml("Custom name: <i>" + customName + "</i>"));
this.customName.setVisibility(View.VISIBLE);
}
//Set the custom description of the item (if any)
if (customDescription != null) {
customDesc.setText(Html.fromHtml("Custom description: <i>" + customDescription + "</i>"));
customDesc.setVisibility(View.VISIBLE);
}
//Set the crafter's name (if any)
if (crafter != null) {
crafterName.setText(Html.fromHtml("Crafted by: <i>" + crafter + "</i>"));
crafterName.setVisibility(View.VISIBLE);
}
//Set the gifter's name (if any)
if (gifter != null) {
gifterName.setText(Html.fromHtml("Gifted by: <i>" + gifter + "</i>"));
gifterName.setVisibility(View.VISIBLE);
}
//Set the paint text (if any)
if (paintNumber != 0) {
paint.setText("Paint: " + Utility.getPaintName(paintNumber));
paint.setVisibility(View.VISIBLE);
}
//Set the icon and the background
setIconImage(this, icon, Utility.getIconIndex(defindex), priceIndex,
quality, paintNumber, isAus == 1);
background.setBackgroundDrawable(Utility.getItemBackground(this,
quality, tradable, craftable));
} else {
//Crash the app if there is no item with the id (should never happen)
throw new RuntimeException("Item with id " + id + " not found (selection: " + selection + ")");
}
//Start querying the price
uri = PriceEntry.CONTENT_URI;
columns = QUERY_COLUMNS_PRICE;
//Proper condition for searching for australum items.
String ausCondition;
if (isAus == 1 || defindex == 5037) {
ausCondition = PriceEntry.COLUMN_ITEM_NAME + " LIKE ?";
} else {
ausCondition = PriceEntry.COLUMN_ITEM_NAME + " NOT LIKE ?";
}
//Exact selection, should return only one match
selection = PriceEntry.TABLE_NAME + "." +
PriceEntry.COLUMN_DEFINDEX + " = ? AND " +
PriceEntry.COLUMN_ITEM_QUALITY + " = ? AND " +
PriceEntry.COLUMN_ITEM_TRADABLE + " = ? AND " +
PriceEntry.COLUMN_ITEM_CRAFTABLE + " = ? AND " +
PriceEntry.COLUMN_PRICE_INDEX + " = ? AND " +
ausCondition;
//Query
Cursor priceCursor = getContentResolver().query(
uri,
columns,
selection,
new String[]{"" + defindex, "" + quality, "" + tradable, "" + craftable, "" + priceIndex, "%australium%"},
null
);
if (priceCursor.moveToFirst()) {
//Show the price
price.setVisibility(View.VISIBLE);
price.setText("Suggested price: " + Utility.formatPrice(this, priceCursor.getDouble(COL_PRICE_LIST_PRICE),
priceCursor.getDouble(COL_PRICE_LIST_PMAX), priceCursor.getString(COL_PRICE_LIST_CURRENCY),
priceCursor.getString(COL_PRICE_LIST_CURRENCY), false));
}
//Close the cursors
itemCursor.close();
priceCursor.close();
}
/**
* Create and set the items icon according to it's properties
*
* @param context context for accessing assets
* @param icon the ImageView to set the drawable to
* @param defindex defindex of the item
* @param index price index of the item
* @param quality quality of the item
* @param paint paint index of the item
* @param isAustralium whether the item is australium or not
*/
private void setIconImage(Context context, ImageView icon, int defindex, int index, int quality, int paint, boolean isAustralium) {
try {
InputStream ims;
AssetManager assetManager = context.getAssets();
Drawable d;
//Load the item icon
if (isAustralium) {
ims = assetManager.open("items/" + defindex + "aus.png");
} else {
ims = assetManager.open("items/" + defindex + ".png");
}
Drawable iconDrawable = Drawable.createFromStream(ims, null);
if (index != 0 && Utility.canHaveEffects(defindex, quality)) {
//Load the effect image
ims = assetManager.open("effects/" + index + "_188x188.png");
Drawable effectDrawable = Drawable.createFromStream(ims, null);
//Layer the two drawables on top of each other
d = new LayerDrawable(new Drawable[]{effectDrawable, iconDrawable});
} else {
//No effects
d = iconDrawable;
}
if (Utility.isPaint(paint)) {
//Load the paint indicator dot
ims = assetManager.open("paint/" + paint + ".png");
Drawable paintDrawable = Drawable.createFromStream(ims, null);
//Layer the two drawables on top of each other
d = new LayerDrawable(new Drawable[]{d, paintDrawable});
}
// set the drawable to ImageView
icon.setImageDrawable(d);
} catch (IOException e) {
Toast.makeText(context, "bptf: " + e.getMessage(), Toast.LENGTH_LONG).show();
if (Utility.isDebugging(context))
e.printStackTrace();
}
}
} |
package com.yubico.yubikitold;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.Nullable;
import com.yubico.yubikitold.transport.OnYubiKeyListener;
import com.yubico.yubikitold.transport.nfc.NfcDeviceManager;
import com.yubico.yubikitold.transport.usb.UsbDeviceManager;
import java.util.concurrent.SynchronousQueue;
/**
* Manages the connection to YubiKeys over both NFC and USB.
* <p>
* This class is typically instantiated from within your Activity, and should be used from within
* that Activity's lifecycle.
*/
public final class YubiKitManager {
private final Handler handler;
private final UsbDeviceManager usbDeviceManager;
private final NfcDeviceManager nfcDeviceManager;
private OnYubiKeyListener listener = null;
private boolean paused = true;
public YubiKitManager(Activity activity) {
this(activity, null, null);
}
public YubiKitManager(Activity activity, Handler handler) {
this(activity, handler, null);
}
/**
* Instantiates a YubiKitManager for the given Activity.
*
* @param activity The Activity to connect the YubiKitManager to.
* @param handler Optional Handler used to dispatch YubiKey events on. This should NOT be using the Main Thread.
* @param nfcDispatcher Optional NfcDispatcher to use instead of the default implementation for NFC communication.
*/
public YubiKitManager(Activity activity, @Nullable Handler handler, @Nullable com.yubico.yubikitold.transport.nfc.NfcDeviceManager.NfcDispatcher nfcDispatcher) {
if (handler == null) {
handler = new Handler(YkIoWorker.getLooper());
}
this.handler = handler;
usbDeviceManager = new com.yubico.yubikitold.transport.usb.UsbDeviceManager(activity, handler);
nfcDeviceManager = new com.yubico.yubikitold.transport.nfc.NfcDeviceManager(activity, handler, nfcDispatcher);
}
/**
* Get the Handler used for event dispatch.
*
* @return The Handler instance provided when creating the YubiKitManager.
*/
public Handler getHandler() {
return handler;
}
/**
* Get the UsbDeviceHandler for direct manipulation.
*
* @return The UsbDeviceHandler which communicates with YubiKeys over USB.
*/
public UsbDeviceManager getUsbDeviceManager() {
return usbDeviceManager;
}
/**
* Get the NfcDeviceHandler for direct manipulation.
*
* @return The NfcDeviceHandler which communicates with YubiKeys over NFC.
*/
public NfcDeviceManager getNfcDeviceManager() {
return nfcDeviceManager;
}
/**
* Set a listener used to react to YubiKey connection/disconnection events.
*
* @param listener An OnYubiKeyListener to set, or null to unset the listener and stop listening.
*/
public void setOnYubiKeyListener(@Nullable OnYubiKeyListener listener) {
this.listener = listener;
if (!paused) {
resume();
}
}
/**
* Call this to stop listening for YubiKey events. This method should be called prior to the Activity pausing in a listener is set, for example in the onPause() method.
*/
public void pause() {
paused = true;
usbDeviceManager.setOnYubiKeyListener(null);
nfcDeviceManager.setOnYubiKeyListener(null);
}
/**
* Call this to resume listening for YubiKey events after the Activity has been paused, for example in the onResume() method.
*/
public void resume() {
paused = false;
usbDeviceManager.setOnYubiKeyListener(listener);
nfcDeviceManager.setOnYubiKeyListener(listener);
}
/**
* Causes the OnYubiKeyListener currently set to be invoked with the currently connected YubiKey,
* if one is connected.
*/
public void triggerOnYubiKey() {
usbDeviceManager.triggerOnYubiKey();
}
private enum YkIoWorker {
INSTANCE;
private final Looper looper;
YkIoWorker() {
final SynchronousQueue<Looper> looperQueue = new SynchronousQueue<>();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
try {
looperQueue.put(Looper.myLooper());
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
Looper.loop();
}
}, "YubiKit IO thread");
t.start();
try {
looper = looperQueue.take();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
private static Looper getLooper() {
return INSTANCE.looper;
}
}
} |
package edu.rutgers.css.Rutgers;
import java.util.ArrayList;
import org.jdeferred.android.AndroidDoneCallback;
import org.jdeferred.android.AndroidExecutionScope;
import org.jdeferred.android.AndroidFailCallback;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.content.res.Resources.NotFoundException;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.AQUtility;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import edu.rutgers.css.Rutgers.api.ChannelManager;
import edu.rutgers.css.Rutgers.api.ComponentFactory;
import edu.rutgers.css.Rutgers.api.Request;
import edu.rutgers.css.Rutgers.auxiliary.LocationClientProvider;
import edu.rutgers.css.Rutgers.auxiliary.RMenuAdapter;
import edu.rutgers.css.Rutgers.auxiliary.RMenuPart;
import edu.rutgers.css.Rutgers.auxiliary.SlideMenuHeader;
import edu.rutgers.css.Rutgers.auxiliary.SlideMenuItem;
import edu.rutgers.css.Rutgers.fragments.DTable;
import edu.rutgers.css.Rutgers.fragments.MainScreen;
import edu.rutgers.css.Rutgers.fragments.WebDisplay;
import edu.rutgers.css.Rutgers.location.LocationUtils;
import edu.rutgers.css.Rutgers2.R;
/**
* RU Mobile main activity
*
*/
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationClientProvider {
private static final String TAG = "MainActivity";
private static final String SC_API = "https://rumobile.rutgers.edu/1/shortcuts.txt";
private ChannelManager mChannelManager;
private LocationClient mLocationClient;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private ActionBarDrawerToggle mDrawerToggle;
private RMenuAdapter mDrawerAdapter;
/**
* For providing the location client to fragments
*/
@Override
public LocationClient getLocationClient() {
return mLocationClient;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
Log.v(TAG, "UUID: " + AppUtil.getUUID(this));
/*
* Set default settings the first time the app is run
*/
PreferenceManager.setDefaultValues(this, R.xml.pref_general, false);
/*
* Connect to Google Play location services
*/
mLocationClient = new LocationClient(this, this, this);
/*
* Set up channel manager
*/
mChannelManager = new ChannelManager();
/*
* Set up nav drawer
*/
//Enable drawer icon
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
ArrayList<RMenuPart> menuArray = new ArrayList<RMenuPart>();
mDrawerAdapter = new RMenuAdapter(this, R.layout.main_drawer_item, R.layout.main_drawer_header, menuArray);
mDrawerListView = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
//getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
//getActionBar().setTitle(mDrawerTitle);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerListView.setAdapter(mDrawerAdapter);
mDrawerListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(view.isEnabled() == false) return;
SlideMenuItem clickedItem = (SlideMenuItem) parent.getAdapter().getItem(position);
if(clickedItem == null) {
Log.e("SlidingMenu", "Failed sliding menu click, index " + position);
mDrawerLayout.closeDrawer(mDrawerListView);
return;
}
Bundle clickedArgs = clickedItem.getArgs();
clickedArgs.putBoolean("topLevel", true); // This is a top level menu press
// Launch component
ComponentFactory.getInstance().switchFragments(clickedArgs);
//mDrawerAdapter.setSelectedPos(position);
mDrawerListView.invalidateViews();
mDrawerLayout.closeDrawer(mDrawerListView); // Close menu after a click
}
});
/*
* Load nav drawer items
*/
// Set up channel items in drawer
loadChannels();
// Set up web shortcut items in drawer
loadWebShortcuts();
/*
* Set up main screen
*/
ComponentFactory.getInstance().mMainActivity = this;
FrameLayout contentFrame = (FrameLayout) findViewById(R.id.main_content_frame);
//contentFrame.removeAllViews();
FragmentManager fm = getSupportFragmentManager();
if(fm.getBackStackEntryCount() == 0) {
fm.beginTransaction()
.replace(R.id.main_content_frame, new MainScreen(), "mainfrag")
.commit();
}
}
@Override
protected void onStart() {
super.onStart();
// Connect to location services when activity becomes visible
mLocationClient.connect();
}
@Override
protected void onStop() {
// Disconnect from location services when activity is no longer visible
mLocationClient.disconnect();
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
// Clear AQuery cache on exit
if(isTaskRoot()) {
AQUtility.cleanCacheAsync(this);
}
}
@Override
public void onBackPressed() {
// If web display is active, send back button presses to it for navigating browser history
Fragment webView = getSupportFragmentManager().findFragmentByTag("www");
if (webView != null) {
if(((WebDisplay) webView).backPress() == false) super.onBackPressed();
}
else super.onBackPressed();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
//TODO Save state
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
//TODO Restore state
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// See if ActionBarDrawerToggle will handle event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle event here or pass it on
switch(item.getItemId()) {
// Start the Settings activity
case R.id.action_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
* Location service calls
*/
@Override
public void onConnected(Bundle dataBundle) {
Log.d(LocationUtils.APPTAG, "Connected to Google Play services");
servicesConnected();
/* if(mLocationClient != null) {
// Mock location testing
//mLocationClient.setMockMode(false);
Location currentLocation = mLocationClient.getLastLocation();
if(currentLocation != null) {
Log.d(LocationUtils.APPTAG, currentLocation.toString());
}
}*/
}
@Override
public void onDisconnected() {
Log.d(LocationUtils.APPTAG, "Disconnected from Google Play services");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if(connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (SendIntentException e) {
Log.e(LocationUtils.APPTAG, Log.getStackTraceString(e));
}
}
else {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this, 0);
if (dialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(dialog);
errorFragment.show(getSupportFragmentManager(), LocationUtils.APPTAG);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Choose what to do based on the request code
switch (requestCode) {
// If the request code matches the code sent in onConnectionFailed
case LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST :
switch (resultCode) {
// If Google Play services resolved the problem
case Activity.RESULT_OK:
Log.d(LocationUtils.APPTAG, "resolved by google play");
break;
// If any other result was returned by Google Play services
default:
Log.d(LocationUtils.APPTAG, "not resolved by google play");
break;
}
// If any other request code was received
default:
// Report that this Activity received an unknown requestCode
Log.d(LocationUtils.APPTAG, "unknown request code " + requestCode);
break;
}
}
/**
* Check if Google Play services is connected.
* @return True if connected, false if not.
*/
public boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resultCode == ConnectionResult.SUCCESS) {
Log.v(TAG, "Google Play services available.");
return true;
}
else {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0);
if (dialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(dialog);
errorFragment.show(getSupportFragmentManager(), LocationUtils.APPTAG);
}
return false;
}
}
public static class ErrorDialogFragment extends DialogFragment {
private Dialog mDialog;
public ErrorDialogFragment() {
super();
mDialog = null;
}
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
/*
* Nav drawer helpers
*/
/**
* Add native channel items to the menu.
*/
private void loadChannels() {
mChannelManager.loadChannelsFromResource(getResources(), R.raw.channels);
addMenuSection(getResources().getString(R.string.drawer_channels), mChannelManager.getChannels("main"));
}
/**
* Grab web links and add them to the menu.
*/
private void loadWebShortcuts() {
Request.jsonArray(SC_API, Request.EXPIRE_ONE_HOUR).done(new AndroidDoneCallback<JSONArray>() {
@Override
public void onDone(JSONArray shortcutsArray) {
mChannelManager.loadChannelsFromJSONArray(shortcutsArray, "shortcuts");
addMenuSection(getResources().getString(R.string.drawer_shortcuts), mChannelManager.getChannels("shortcuts"));
}
@Override
public AndroidExecutionScope getExecutionScope() {
return AndroidExecutionScope.UI;
}
}).fail(new AndroidFailCallback<AjaxStatus>() {
@Override
public void onFail(AjaxStatus status) {
Log.e(TAG, "loadWebShortcuts(): " + status.getMessage());
}
@Override
public AndroidExecutionScope getExecutionScope() {
return AndroidExecutionScope.UI;
}
});
}
/**
* Create section header and load menu items from JSON.
* @param category Section title
* @param items Menu items JSON
*/
private void addMenuSection(String category, JSONArray items) {
mDrawerAdapter.add(new SlideMenuHeader(category));
for(int i = 0; i < items.length(); i++) {
try {
// Create menu item
JSONObject cur = items.getJSONObject(i);
Bundle itemArgs = new Bundle();
// Set title - may be a multi-title object
itemArgs.putString("title", AppUtil.getLocalTitle(this, cur.get("title")));
// Set component to launch. Default to WWW for web shortcuts
if(cur.optString("view").isEmpty() && !cur.optString("url").isEmpty()) {
itemArgs.putString("component", "www");
}
else {
itemArgs.putString("component", cur.getString("view"));
}
// Set URL if available
if(!cur.optString("url").isEmpty()) itemArgs.putString("url", cur.getString("url"));
// Set data (JSON Array) if available
if(cur.optJSONArray("data") != null) itemArgs.putString("data", cur.getJSONArray("data").toString());
SlideMenuItem newSMI = new SlideMenuItem(itemArgs);
// Try to find icon for this item and set it
if(!cur.optString("handle").isEmpty()) {
newSMI.setDrawable(AppUtil.getIcon(getResources(), cur.getString("handle")));
}
// Add the item to the drawer
mDrawerAdapter.add(newSMI);
} catch (JSONException e) {
Log.w(TAG, "loadChannels(): " + e.getMessage());
}
}
}
} |
package me.ykrank.s1next.data.api.model;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v4.util.SimpleArrayMap;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Objects;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import me.ykrank.s1next.data.SameItem;
import me.ykrank.s1next.data.db.BlackListDbWrapper;
import me.ykrank.s1next.data.db.dbmodel.BlackList;
import me.ykrank.s1next.util.L;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
public final class Post implements Cloneable, SameItem {
private static final String TAG = Post.class.getSimpleName();
private static final SimpleArrayMap<String, String> COLOR_NAME_MAP;
static {
COLOR_NAME_MAP = new SimpleArrayMap<>();
COLOR_NAME_MAP.put("sienna", "#A0522D");
COLOR_NAME_MAP.put("darkolivegreen", "#556B2F");
COLOR_NAME_MAP.put("darkgreen", "#006400");
COLOR_NAME_MAP.put("darkslateblue", "#483D8B");
COLOR_NAME_MAP.put("indigo", "#4B0082");
COLOR_NAME_MAP.put("darkslategray", "#2F4F4F");
COLOR_NAME_MAP.put("darkred", "#8B0000");
COLOR_NAME_MAP.put("darkorange", "#FF8C00");
COLOR_NAME_MAP.put("slategray", "#708090");
COLOR_NAME_MAP.put("dimgray", "#696969");
COLOR_NAME_MAP.put("sandybrown", "#F4A460");
COLOR_NAME_MAP.put("yellowgreen", "#9ACD32");
COLOR_NAME_MAP.put("seagreen", "#2E8B57");
COLOR_NAME_MAP.put("mediumturquoise", "#48D1CC");
COLOR_NAME_MAP.put("royalblue", "#4169E1");
COLOR_NAME_MAP.put("orange", "#FFA500");
COLOR_NAME_MAP.put("deepskyblue", "#00BFFF");
COLOR_NAME_MAP.put("darkorchid", "#9932CC");
COLOR_NAME_MAP.put("pink", "#FFC0CB");
COLOR_NAME_MAP.put("wheat", "#F5DEB3");
COLOR_NAME_MAP.put("lemonchiffon", "#FFFACD");
COLOR_NAME_MAP.put("palegreen", "#98FB98");
COLOR_NAME_MAP.put("paleturquoise", "#AFEEEE");
COLOR_NAME_MAP.put("lightblue", "#ADD8E6");
COLOR_NAME_MAP.put("white", "#FFFFFF");
}
@JsonProperty("pid")
private String id;
@JsonProperty("author")
private String authorName;
@JsonProperty("authorid")
private String authorId;
@JsonProperty("message")
private String reply;
@JsonProperty("number")
private String count;
@JsonProperty("dbdateline")
private long datetime;
@JsonProperty("attachments")
private Map<Integer, Attachment> attachmentMap;
/**
* is in blacklist
*/
@JsonIgnore
private boolean hide = false;
@JsonIgnore
private String remark;
public Post() {
}
/**
* {@link Color} doesn't support all HTML color names.
* So {@link android.text.Html#fromHtml(String)} won't
* map some color names for replies in S1.
* We need to map these color names to their hex value.
*/
private static String mapColors(String reply) {
// example: color="sienna"
// matcher.group(0): color="sienna"
// matcher.group(1): sienna
Matcher matcher = Pattern.compile("color=\"([a-zA-Z]+)\"").matcher(reply);
StringBuffer stringBuffer = new StringBuffer();
String color;
while (matcher.find()) {
// get color hex value for its color name
color = COLOR_NAME_MAP.get(matcher.group(1).toLowerCase(Locale.US));
if (color == null) {
continue;
}
// append part of the string and its color hex value
matcher.appendReplacement(stringBuffer, "color=\"" + color + "\"");
}
matcher.appendTail(stringBuffer);
return stringBuffer.toString();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public String getAuthorId() {
return authorId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
@Nullable
public String getReply() {
return reply;
}
public void setReply(String reply) {
reply = hideBlackListQuote(reply);
reply = replaceBilibiliTag(reply);
// Replaces "imgwidth" with "img width",
// because some img tags in S1 aren't correct.
// This may be the best way to deal with it though
// we may replace something wrong by accident.
// Also maps some colors, see mapColors(String).
this.reply = mapColors(reply).replaceAll("<imgwidth=\"", "<img width=\"");
processAttachment();
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public long getDatetime() {
return datetime;
}
public void setDatetime(long datetime) {
// convert seconds to milliseconds
this.datetime = TimeUnit.SECONDS.toMillis(datetime);
}
public void setAttachmentMap(Map<Integer, Attachment> attachmentMap) {
this.attachmentMap = attachmentMap;
processAttachment();
}
public boolean isHide() {
return hide;
}
public void setHide(boolean hide) {
this.hide = hide;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Post post = (Post) o;
return Objects.equal(datetime, post.datetime) &&
Objects.equal(id, post.id) &&
Objects.equal(authorName, post.authorName) &&
Objects.equal(authorId, post.authorId) &&
Objects.equal(reply, post.reply) &&
Objects.equal(count, post.count) &&
Objects.equal(attachmentMap, post.attachmentMap) &&
Objects.equal(hide, post.hide) &&
Objects.equal(remark, post.remark);
}
@Override
public int hashCode() {
return Objects.hashCode(id, authorName, authorId, reply, count, datetime, attachmentMap, hide, remark);
}
@Override
public Post clone() {
Post o = null;
try {
o = (Post) super.clone();
} catch (CloneNotSupportedException e) {
L.e(TAG, e);
} catch (ClassCastException e) {
L.e(TAG, e);
}
return o;
}
@Override
public boolean isSameItem(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Post post = (Post) o;
return Objects.equal(id, post.id) &&
Objects.equal(authorName, post.authorName) &&
Objects.equal(authorId, post.authorId);
}
/**
*
*
* @param reply
* @return
*/
private String hideBlackListQuote(String reply) {
String quoteName = findBlockQuoteName(reply);
if (quoteName != null) {
reply = replaceQuoteBr(reply);
BlackList blackList = BlackListDbWrapper.getInstance().getBlackListDefault(-1, quoteName);
if (blackList != null && blackList.getPost() != BlackList.NORMAL) {
return replaceBlockQuoteContent(reply, blackList.getRemark());
}
}
return reply;
}
/**
*
*
* @param reply
* @return
*/
private String findBlockQuoteName(String reply) {
String name = null;
Pattern pattern = Pattern.compile("<blockquote>[\\s\\S]*</blockquote>");
Matcher matcher = pattern.matcher(reply);
if (matcher.find()) {
String quote = matcher.group(0);
pattern = Pattern.compile("<font color=\"#999999\">(.+?) ");
matcher = pattern.matcher(quote);
if (matcher.find()) {
name = matcher.group(1);
}
}
return name;
}
/**
* <br/>
*
* @param reply
* @return
*/
private String replaceQuoteBr(String reply) {
return reply.replace("</blockquote></div><br />", "</blockquote></div>");
}
/**
*
*
* @param reply
* @param remark
* @return
*/
private String replaceBlockQuoteContent(String reply, String remark) {
Pattern pattern = Pattern.compile("</font></a>[\\s\\S]*</blockquote>");
Matcher matcher = pattern.matcher(reply);
String reText;
if (matcher.find()) {
reText = "</font></a><br />\r\n[]</blockquote>";
return reply.replaceFirst("</font></a>[\\s\\S]*</blockquote>", reText);
} else {
pattern = Pattern.compile("</font><br />[\\s\\S]*</blockquote>");
matcher = pattern.matcher(reply);
if (matcher.find()) {
reText = "</font><br />\r\n[]</blockquote>";
return reply.replaceFirst("</font><br />[\\s\\S]*</blockquote>", reText);
}
}
return reply;
}
private String replaceBilibiliTag(String reply) {
Pattern pattern = Pattern.compile("\\[thgame_biliplay.*?\\[/thgame_biliplay\\]");
Matcher matcher = pattern.matcher(reply);
while (matcher.find()) {
try {
String content = matcher.group(0);
//find av number
Pattern avPattern = Pattern.compile("\\{,=av\\}[0-9]+");
Matcher avMatcher = avPattern.matcher(content);
if (!avMatcher.find()) {
continue;
}
int avNum = Integer.valueOf(avMatcher.group().substring(6));
//find page
int page = 1;
Pattern pagePattern = Pattern.compile("\\{,=page\\}[0-9]+");
Matcher pageMatcher = pagePattern.matcher(content);
if (pageMatcher.find()) {
page = Integer.valueOf(pageMatcher.group().substring(8));
}
String tagString = String.format(Locale.getDefault(),
"<bilibili>http:
reply = reply.replace(content, tagString);
} catch (Exception e) {
L.report("replaceBilibiliTag error", e);
}
}
return reply;
}
private void processAttachment() {
if (reply == null || attachmentMap == null) {
return;
}
for (Map.Entry<Integer, Post.Attachment> entry : attachmentMap.entrySet()) {
Post.Attachment attachment = entry.getValue();
String imgTag = "<img src=\"" + attachment.getUrl() + "\" />";
String replyCopy = reply;
// get the original string if there is nothing to replace
reply = reply.replace("[attach]" + entry.getKey() + "[/attach]", imgTag);
//noinspection StringEquality
if (reply == replyCopy) {
// concat the missing img tag
reply = reply + imgTag;
}
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static final class Attachment {
@JsonIgnore
private final String url;
@JsonCreator
public Attachment(@JsonProperty("url") String urlPrefix,
@JsonProperty("attachment") String urlSuffix) {
this.url = urlPrefix + urlSuffix;
}
public String getUrl() {
return url;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Attachment that = (Attachment) o;
return Objects.equal(url, that.url);
}
@Override
public int hashCode() {
return Objects.hashCode(url);
}
}
} |
package org.stepic.droid.web;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import com.squareup.okhttp.Authenticator;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.yandex.metrica.YandexMetrica;
import org.stepic.droid.base.MainApplication;
import org.stepic.droid.configuration.IConfig;
import org.stepic.droid.core.ScreenManager;
import org.stepic.droid.model.Course;
import org.stepic.droid.model.EnrollmentWrapper;
import org.stepic.droid.preferences.SharedPreferenceHelper;
import org.stepic.droid.preferences.UserPreferences;
import org.stepic.droid.social.SocialManager;
import org.stepic.droid.store.operations.DatabaseManager;
import org.stepic.droid.util.AppConstants;
import org.stepic.droid.util.FileUtil;
import org.stepic.droid.util.JsonHelper;
import org.stepic.droid.util.RWLocks;
import java.io.IOException;
import java.net.ProtocolException;
import java.net.Proxy;
import javax.inject.Inject;
import javax.inject.Singleton;
import retrofit.Call;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
@Singleton
public class RetrofitRESTApi implements IApi {
@Inject
SharedPreferenceHelper mSharedPreference;
@Inject
ScreenManager screenManager;
@Inject
DatabaseManager mDbManager;
@Inject
IConfig mConfig;
@Inject
UserPreferences userPreferences;
private StepicRestLoggedService mLoggedService;
private StepicRestOAuthService mOAuthService;
public RetrofitRESTApi() {
MainApplication.component().inject(this);
makeOauthServiceWithNewAuthHeader(mSharedPreference.isLastTokenSocial() ? TokenType.social : TokenType.loginPassword);
OkHttpClient okHttpClient = new OkHttpClient();
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
try {
Request newRequest = chain.request();
AuthenticationStepicResponse response = mSharedPreference.getAuthResponseFromStore();
if (response != null) {
newRequest = chain.request().newBuilder().addHeader("Authorization", getAuthHeaderValue()).build();
}
return chain.proceed(newRequest);
} catch (ProtocolException t) {
// FIXME: 17.12.15 IT IS NOT NORMAL BEHAVIOUR, NEED TO REPAIR CODE.
YandexMetrica.reportError(AppConstants.NOT_VALID_ACCESS_AND_REFRESH, t);
mSharedPreference.deleteAuthInfo();
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
FileUtil.cleanDirectory(userPreferences.getDownloadFolder());
mDbManager.dropDatabase();
return null;
}
};
task.execute();
screenManager.showLaunchScreen(MainApplication.getAppContext(), false);
throw t;
}
}
};
okHttpClient.networkInterceptors().add(interceptor);
setAuthForLoggedService(okHttpClient);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mConfig.getBaseUrl())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
mLoggedService = retrofit.create(StepicRestLoggedService.class);
}
@Override
public Call<AuthenticationStepicResponse> authWithLoginPassword(String login, String password) {
YandexMetrica.reportEvent("Api:auth with login password");
makeOauthServiceWithNewAuthHeader(TokenType.loginPassword);
return mOAuthService.authWithLoginPassword(mConfig.getGrantType(TokenType.loginPassword), login, password);
}
@Override
public Call<AuthenticationStepicResponse> authWithCode(String code) {
YandexMetrica.reportEvent("Api:auth with social account");
makeOauthServiceWithNewAuthHeader(TokenType.social);
return mOAuthService.getTokenByCode(mConfig.getGrantType(TokenType.social), code, mConfig.getRedirectUri());
}
private void makeOauthServiceWithNewAuthHeader(final TokenType type) {
mSharedPreference.storeLastTokenType(type == TokenType.social ? true : false);
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
try {
Request newRequest = chain.request();
String credential = Credentials.basic(mConfig.getOAuthClientId(type), mConfig.getOAuthClientSecret(type));
newRequest = chain.request().newBuilder().addHeader("Authorization", credential).build();
return chain.proceed(newRequest);
} catch (ProtocolException t) {
// FIXME: 17.12.15 IT IS NOT NORMAL BEHAVIOUR, NEED TO REPAIR CODE.
YandexMetrica.reportError(AppConstants.NOT_VALID_ACCESS_AND_REFRESH, t);
mSharedPreference.deleteAuthInfo();
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
FileUtil.cleanDirectory(userPreferences.getDownloadFolder());
mDbManager.dropDatabase();
return null;
}
};
task.execute();
screenManager.showLaunchScreen(MainApplication.getAppContext(), false);
throw t;
}
}
};
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.networkInterceptors().add(interceptor);
setAuthenticatorClientIDAndPassword(okHttpClient, mConfig.getOAuthClientId(type), mConfig.getOAuthClientSecret(type)); // just insurance.
Retrofit notLogged = new Retrofit.Builder()
.baseUrl(mConfig.getBaseUrl())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
mOAuthService = notLogged.create(StepicRestOAuthService.class);
}
@Override
public Call<IStepicResponse> signUp(String firstName, String secondName, String email, String password) {
throw new RuntimeException("not implemented");
}
public Call<CoursesStepicResponse> getEnrolledCourses(int page) {
YandexMetrica.reportEvent("Api: get enrolled courses");
return mLoggedService.getEnrolledCourses(true, page);
}
public Call<CoursesStepicResponse> getFeaturedCourses(int page) {
YandexMetrica.reportEvent("Api:get featured courses)");
return mLoggedService.getFeaturedCourses(true, page);
}
@Override
public Call<StepicProfileResponse> getUserProfile() {
YandexMetrica.reportEvent("Api:get user profile");
return mLoggedService.getUserProfile();
}
@Override
public Call<UserStepicResponse> getUsers(long[] userIds) {
YandexMetrica.reportEvent("Api:get users");
return mLoggedService.getUsers(userIds);
}
@Override
public Call<Void> tryJoinCourse(Course course) {
YandexMetrica.reportEvent("Api:try join to course", JsonHelper.toJson(course));
EnrollmentWrapper enrollmentWrapper = new EnrollmentWrapper(course.getCourseId());
return mLoggedService.joinCourse(enrollmentWrapper);
}
@Override
public Call<SectionsStepicResponse> getSections(long[] sectionsIds) {
YandexMetrica.reportEvent("Api:get sections", JsonHelper.toJson(sectionsIds));
return mLoggedService.getSections(sectionsIds);
}
@Override
public Call<UnitStepicResponse> getUnits(long[] units) {
YandexMetrica.reportEvent("Api:get units", JsonHelper.toJson(units));
return mLoggedService.getUnits(units);
}
@Override
public Call<LessonStepicResponse> getLessons(long[] lessons) {
YandexMetrica.reportEvent("Api:get lessons", JsonHelper.toJson(lessons));
return mLoggedService.getLessons(lessons);
}
@Override
public Call<StepResponse> getSteps(long[] steps) {
YandexMetrica.reportEvent("Api:get steps", JsonHelper.toJson(steps));
return mLoggedService.getSteps(steps);
}
@Override
public Call<Void> dropCourse(long courseId) {
YandexMetrica.reportEvent("Api: " + AppConstants.METRICA_DROP_COURSE, JsonHelper.toJson(courseId));
return mLoggedService.dropCourse(courseId);
}
@Override
public Call<ProgressesResponse> getProgresses(String[] progresses) {
YandexMetrica.reportEvent("Api: " + AppConstants.METRICA_GET_PROGRESSES);
return mLoggedService.getProgresses(progresses);
}
@Override
public Call<AssignmentResponse> getAssignments(long[] assignmentsIds) {
YandexMetrica.reportEvent("Api: " + AppConstants.METRICA_GET_ASSIGNMENTS);
return mLoggedService.getAssignments(assignmentsIds);
}
@Override
public Call<Void> postViewed(ViewAssignment stepAssignment) {
return mLoggedService.postViewed(new ViewAssignmentWrapper(stepAssignment.getAssignment(), stepAssignment.getStep()));
}
public void loginWithSocial(Context context, SocialManager.SocialType type) {
String socialIdentifier = type.getIdentifier();
String url = mConfig.getBaseUrl() + "/accounts/" + socialIdentifier + "/login?next=/oauth2/authorize/?" + Uri.encode("client_id=" + mConfig.getOAuthClientId(TokenType.social) + "&response_type=code");
Uri uri = Uri.parse(url);
final Intent intent = new Intent(Intent.ACTION_VIEW).setData(uri);
context.startActivity(intent);
}
private void setAuthenticatorClientIDAndPassword(OkHttpClient httpClient, final String client_id, final String client_password) {
httpClient.setAuthenticator(new Authenticator() {
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
// if (mCounter++ > 0) {
// throw new AuthException();
YandexMetrica.reportEvent("Never invoked auth");
// FIXME: 28.12.15 IT IS NEVER INVOKED. REMOVE
String credential = Credentials.basic(client_id, client_password);
return response.request().newBuilder().header("Authorization", credential).build();
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
});
}
private void setAuthForLoggedService(OkHttpClient httpClient) {
httpClient.setAuthenticator(new Authenticator() {
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
//IT WILL BE INVOKED WHEN Access token will expire (should, but server doesn't handle 401.)
//it is not be invoked on get courses for example.
RWLocks.AuthLock.writeLock().lock();
try {
AuthenticationStepicResponse authData = mSharedPreference.getAuthResponseFromStore();
if (response != null) {
authData = mOAuthService.updateToken(mConfig.getRefreshGrantType(), authData.getRefresh_token()).execute().body();
mSharedPreference.storeAuthInfo(authData);
return response.request().newBuilder().addHeader("Authorization", getAuthHeaderValue()).build();
}
} catch (ProtocolException t) {
// FIXME: 17.12.15 IT IS NOT NORMAL BEHAVIOUR, NEED TO REPAIR CODE.
YandexMetrica.reportError(AppConstants.NOT_VALID_ACCESS_AND_REFRESH, t);
mSharedPreference.deleteAuthInfo();
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
FileUtil.cleanDirectory(userPreferences.getDownloadFolder());
mDbManager.dropDatabase();
return null;
}
};
task.execute();
screenManager.showLaunchScreen(MainApplication.getAppContext(), false);
throw t;
} finally {
RWLocks.AuthLock.writeLock().unlock();
}
return null;
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
});
}
private String getAuthHeaderValue() {
try {
AuthenticationStepicResponse resp = mSharedPreference.getAuthResponseFromStore();
String access_token = resp.getAccess_token();
String type = resp.getToken_type();
return type + " " + access_token;
} catch (Exception ex) {
YandexMetrica.reportError("retrofitAuth", ex);
Log.e("retrofitAuth", ex.getMessage());
// FIXME: 19.11.15 It not should happen
mSharedPreference.deleteAuthInfo();
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
mDbManager.clearCacheCourses(DatabaseManager.Table.enrolled);
return null;
}
};
task.execute();
screenManager.showLaunchScreen(MainApplication.getAppContext(), false);
// FIXME: 19.11.15 ^^^^^^
return "";
}
}
} |
package org.commcare.activities;
import static org.commcare.activities.DispatchActivity.SESSION_ENDPOINT_ARGUMENTS_BUNDLE;
import static org.commcare.activities.DispatchActivity.SESSION_ENDPOINT_ARGUMENTS_LIST;
import static org.commcare.activities.DispatchActivity.SESSION_ENDPOINT_ID;
import static org.commcare.activities.DriftHelper.getCurrentDrift;
import static org.commcare.activities.DriftHelper.getDriftDialog;
import static org.commcare.activities.DriftHelper.shouldShowDriftWarning;
import static org.commcare.activities.DriftHelper.updateLastDriftWarningTime;
import static org.commcare.appupdate.AppUpdateController.IN_APP_UPDATE_REQUEST_CODE;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.widget.AdapterView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;
import com.google.android.play.core.install.model.InstallErrorCode;
import org.apache.commons.lang3.StringUtils;
import org.commcare.CommCareApplication;
import org.commcare.activities.components.FormEntryConstants;
import org.commcare.activities.components.FormEntryInstanceState;
import org.commcare.activities.components.FormEntrySessionWrapper;
import org.commcare.android.database.app.models.UserKeyRecord;
import org.commcare.android.database.user.models.FormRecord;
import org.commcare.android.database.user.models.SessionStateDescriptor;
import org.commcare.android.logging.ReportingUtils;
import org.commcare.appupdate.AppUpdateControllerFactory;
import org.commcare.appupdate.AppUpdateState;
import org.commcare.appupdate.FlexibleAppUpdateController;
import org.commcare.core.process.CommCareInstanceInitializer;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.google.services.ads.AdMobManager;
import org.commcare.google.services.analytics.AnalyticsParamValue;
import org.commcare.google.services.analytics.FirebaseAnalyticsUtil;
import org.commcare.heartbeat.UpdatePromptHelper;
import org.commcare.interfaces.CommCareActivityUIController;
import org.commcare.models.AndroidSessionWrapper;
import org.commcare.models.database.SqlStorage;
import org.commcare.preferences.AdvancedActionsPreferences;
import org.commcare.preferences.DevSessionRestorer;
import org.commcare.preferences.DeveloperPreferences;
import org.commcare.preferences.HiddenPreferences;
import org.commcare.preferences.MainConfigurablePreferences;
import org.commcare.recovery.measures.RecoveryMeasuresHelper;
import org.commcare.session.CommCareSession;
import org.commcare.session.SessionFrame;
import org.commcare.session.SessionNavigationResponder;
import org.commcare.session.SessionNavigator;
import org.commcare.suite.model.Endpoint;
import org.commcare.suite.model.EntityDatum;
import org.commcare.suite.model.Entry;
import org.commcare.suite.model.FormEntry;
import org.commcare.suite.model.Menu;
import org.commcare.suite.model.PostRequest;
import org.commcare.suite.model.RemoteRequestEntry;
import org.commcare.suite.model.SessionDatum;
import org.commcare.suite.model.StackFrameStep;
import org.commcare.suite.model.Text;
import org.commcare.tasks.DataPullTask;
import org.commcare.tasks.FormLoaderTask;
import org.commcare.tasks.FormRecordCleanupTask;
import org.commcare.tasks.ResultAndError;
import org.commcare.util.LogTypes;
import org.commcare.utils.AndroidCommCarePlatform;
import org.commcare.utils.AndroidInstanceInitializer;
import org.commcare.utils.AndroidUtil;
import org.commcare.utils.ChangeLocaleUtil;
import org.commcare.utils.CommCareUtil;
import org.commcare.utils.ConnectivityStatus;
import org.commcare.utils.CrashUtil;
import org.commcare.utils.EntityDetailUtils;
import org.commcare.utils.GlobalConstants;
import org.commcare.utils.SessionUnavailableException;
import org.commcare.views.UserfacingErrorHandling;
import org.commcare.views.dialogs.CommCareAlertDialog;
import org.commcare.views.dialogs.DialogChoiceItem;
import org.commcare.views.dialogs.DialogCreationHelpers;
import org.commcare.views.dialogs.PaneledChoiceDialog;
import org.commcare.views.dialogs.StandardAlertDialog;
import org.commcare.views.notifications.NotificationMessage;
import org.commcare.views.notifications.NotificationMessageFactory;
import org.javarosa.core.model.User;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathTypeMismatchException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Vector;
/**
* Manages all of the shared (mostly non-UI) components of a CommCare home screen: activity
* lifecycle, implementation of available actions, session navigation, etc.
*/
public abstract class HomeScreenBaseActivity<T> extends SyncCapableCommCareActivity<T>
implements SessionNavigationResponder {
/**
* Request code for launching a menu list or menu grid
*/
public static final int GET_COMMAND = 1;
/**
* Request code for launching EntitySelectActivity (to allow user to select a case), or
* EntityDetailActivity (to allow user to confirm an auto-selected case)
*/
protected static final int GET_CASE = 2;
protected static final int GET_REMOTE_DATA = 3;
/**
* Request code for launching FormEntryActivity
*/
protected static final int MODEL_RESULT = 4;
protected static final int MAKE_REMOTE_POST = 5;
public static final int GET_INCOMPLETE_FORM = 6;
protected static final int PREFERENCES_ACTIVITY = 7;
protected static final int ADVANCED_ACTIONS_ACTIVITY = 8;
protected static final int CREATE_PIN = 9;
protected static final int AUTHENTICATION_FOR_PIN = 10;
private static final String KEY_PENDING_SESSION_DATA = "pending-session-data-id";
private static final String KEY_PENDING_SESSION_DATUM_ID = "pending-session-datum-id";
/**
* Restart is a special CommCare activity result code which means that the session was
* invalidated in the calling activity and that the current session should be resynced
*/
public static final int RESULT_RESTART = 3;
private int mDeveloperModeClicks = 0;
private SessionNavigator sessionNavigator;
private boolean sessionNavigationProceedingAfterOnResume;
private boolean loginExtraWasConsumed;
private static final String EXTRA_CONSUMED_KEY = "login_extra_was_consumed";
private boolean isRestoringSession = false;
// The API allows for external calls. When this occurs, redispatch to their
// activity instead of commcare.
private boolean wasExternal = false;
private static final String WAS_EXTERNAL_KEY = "was_external";
// Indicates if 1 of the checks we performed in onCreate resulted in redirecting to a
// different activity or starting a UI-blocking task
private boolean redirectedInOnCreate = false;
private FlexibleAppUpdateController appUpdateController;
private static final String APP_UPDATE_NOTIFICATION = "app_update_notification";
protected boolean showCommCareUpdateMenu = false;
private static final int MAX_CC_UPDATE_CANCELLATION = 3;
@Override
public void onCreateSessionSafe(Bundle savedInstanceState) {
super.onCreateSessionSafe(savedInstanceState);
loadInstanceState(savedInstanceState);
CrashUtil.registerAppData();
AdMobManager.initAdsForCurrentConsumerApp(getApplicationContext());
updateLastSuccessfulCommCareVersion();
sessionNavigator = new SessionNavigator(this);
processFromExternalLaunch(savedInstanceState);
processFromShortcutLaunch();
processFromLoginLaunch();
appUpdateController = AppUpdateControllerFactory.create(this::handleAppUpdate,
getApplicationContext());
appUpdateController.register();
}
private void updateLastSuccessfulCommCareVersion() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(
CommCareApplication.instance());
SharedPreferences.Editor editor = preferences.edit();
editor.putString(HiddenPreferences.LAST_SUCCESSFUL_CC_VERSION,
ReportingUtils.getCommCareVersionString());
editor.apply();
}
private void loadInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
loginExtraWasConsumed = savedInstanceState.getBoolean(EXTRA_CONSUMED_KEY);
wasExternal = savedInstanceState.getBoolean(WAS_EXTERNAL_KEY);
}
}
/**
* Set state that signifies activity was launch from external app
*/
private void processFromExternalLaunch(Bundle savedInstanceState) {
if (savedInstanceState == null && getIntent().hasExtra(DispatchActivity.WAS_EXTERNAL)) {
wasExternal = true;
if (processSessionEndpoint()) {
sessionNavigator.startNextSessionStep();
}
}
}
/**
* @return If we are launched with a session endpoint, returns whether the endpoint was
* successfully processed without errors. If this was not an external launch using session
* endpoint, returns true
*/
private boolean processSessionEndpoint() {
if (getIntent().hasExtra(SESSION_ENDPOINT_ID)) {
Endpoint endpoint = validateIntentForSessionEndpoint(getIntent());
if (endpoint != null) {
Bundle intentArgumentsAsBundle = getIntent().getBundleExtra(
SESSION_ENDPOINT_ARGUMENTS_BUNDLE);
ArrayList<String> intentArgumentsAsList = getIntent().getStringArrayListExtra(
SESSION_ENDPOINT_ARGUMENTS_LIST);
// Reset the Session to make sure we don't carry forward any session state to the
// endpoint launch
CommCareApplication.instance().getCurrentSessionWrapper().reset();
try {
if (intentArgumentsAsBundle != null) {
CommCareApplication.instance().getCurrentSessionWrapper()
.executeEndpointStack(endpoint,
AndroidUtil.bundleAsMap(intentArgumentsAsBundle));
} else if (intentArgumentsAsList != null) {
CommCareApplication.instance().getCurrentSessionWrapper()
.executeEndpointStack(endpoint, intentArgumentsAsList);
}
return true;
} catch (Endpoint.InvalidEndpointArgumentsException e) {
String invalidEndpointArgsError =
org.commcare.utils.StringUtils.getStringRobust(
this,
R.string.session_endpoint_invalid_arguments,
new String[]{
endpoint.getId(),
intentArgumentsAsBundle != null ?
StringUtils.join(intentArgumentsAsBundle, ",") :
String.valueOf(intentArgumentsAsList.size()),
StringUtils.join(endpoint.getArguments(), ",")});
UserfacingErrorHandling.createErrorDialog(this, invalidEndpointArgsError, true);
}
}
return false;
}
return true;
}
private Endpoint validateIntentForSessionEndpoint(Intent intent) {
String sessionEndpointId = intent.getStringExtra(SESSION_ENDPOINT_ID);
Endpoint endpoint = CommCareApplication.instance().getCommCarePlatform().getEndpoint(
sessionEndpointId);
if (endpoint == null) {
Hashtable<String, Endpoint> allEndpoints =
CommCareApplication.instance().getCommCarePlatform().getAllEndpoints();
String invalidEndpointError = org.commcare.utils.StringUtils.getStringRobust(
this,
R.string.session_endpoint_unavailable,
new String[]{
sessionEndpointId,
StringUtils.join(allEndpoints.keySet(), ",")});
UserfacingErrorHandling.createErrorDialog(this, invalidEndpointError, true);
return null;
}
return endpoint;
}
private void processFromShortcutLaunch() {
if (getIntent().getBooleanExtra(DispatchActivity.WAS_SHORTCUT_LAUNCH, false)) {
sessionNavigator.startNextSessionStep();
}
}
private void processFromLoginLaunch() {
if (getIntent().getBooleanExtra(DispatchActivity.START_FROM_LOGIN, false) &&
!loginExtraWasConsumed) {
getIntent().removeExtra(DispatchActivity.START_FROM_LOGIN);
loginExtraWasConsumed = true;
try {
redirectedInOnCreate = doLoginLaunchChecksInOrder();
} finally {
// make sure this happens no matter what
clearOneTimeLoginActionFlags();
}
}
}
/**
* The order of operations in this method is very deliberate, and the logic for it is as
* follows: - If we're in demo mode, then we don't want to do any of the other checks because
* they're not relevant - Form and session restorations need to happen before we try to sync,
* because once we sync it could invalidate those states - Restoring a form that was interrupted
* by session expiration comes before restoring a saved session because it is of higher
* importance - Check for a post-update sync before doing a standard background form-send, since
* a sync action will include a form-send action - Check if we need to show an Update Prompt -
* Once we're past that point, starting a background form-send process is safe, and we can
* safely do checkForPinLaunchConditions() at the same time
*/
private boolean doLoginLaunchChecksInOrder() {
if (isDemoUser()) {
showDemoModeWarning();
return false;
}
if (showUpdateInfoForm()) {
return true;
}
if (tryRestoringFormFromSessionExpiration()) {
return true;
}
if (tryRestoringSession()) {
return true;
}
if (CommCareApplication.instance().isPostUpdateSyncNeeded()
|| UpdateActivity.isUpdateBlockedOnSync()) {
HiddenPreferences.setPostUpdateSyncNeeded(false);
triggerSync(false);
return true;
}
if (UpdatePromptHelper.promptForUpdateIfNeeded(this)) {
return true;
}
checkForPinLaunchConditions();
checkForDrift();
return false;
}
private void checkForDrift() {
if (shouldShowDriftWarning()) {
if (getCurrentDrift() != 0) {
showAlertDialog(getDriftDialog(this));
updateLastDriftWarningTime();
}
}
}
// Open the update info form if available
private boolean showUpdateInfoForm() {
if (HiddenPreferences.shouldShowXformUpdateInfo()) {
HiddenPreferences.setShowXformUpdateInfo(false);
String updateInfoFormXmlns =
CommCareApplication.instance().getCommCarePlatform().getUpdateInfoFormXmlns();
if (!StringUtils.isEmpty(updateInfoFormXmlns)) {
CommCareSession session = CommCareApplication.instance().getCurrentSession();
FormEntry formEntry = session.getEntryForNameSpace(updateInfoFormXmlns);
if (formEntry != null) {
session.setCommand(formEntry.getCommandID());
startNextSessionStepSafe();
return true;
}
}
}
return false;
}
/**
* Regardless of what action(s) we ended up executing in doLoginLaunchChecksInOrder(), we don't
* want to end up trying the actions associated with these flags again at a later point. They
* either need to happen the first time on login, or not at all.
*/
private void clearOneTimeLoginActionFlags() {
HiddenPreferences.setPostUpdateSyncNeeded(false);
HiddenPreferences.clearInterruptedSSD();
}
private boolean tryRestoringFormFromSessionExpiration() {
SessionStateDescriptor existing =
AndroidSessionWrapper.getFormStateForInterruptedUserSession();
if (existing != null) {
AndroidSessionWrapper state = CommCareApplication.instance().getCurrentSessionWrapper();
state.loadFromStateDescription(existing);
formEntry(CommCareApplication.instance().getCommCarePlatform()
.getFormDefId(state.getSession().getForm()), state.getFormRecord(),
null, true);
return true;
}
return false;
}
private boolean tryRestoringSession() {
CommCareSession session = CommCareApplication.instance().getCurrentSession();
if (session.getCommand() != null) {
// Restore the session state if there is a command. This is for debugging and
// occurs when a serialized session was stored by a previous user session
isRestoringSession = true;
sessionNavigator.startNextSessionStep();
return true;
}
return false;
}
/**
* See if we should launch either the pin choice dialog, or the create pin activity directly
*/
private void checkForPinLaunchConditions() {
LoginMode loginMode = (LoginMode)getIntent().getSerializableExtra(LoginActivity.LOGIN_MODE);
if (loginMode == LoginMode.PRIMED) {
launchPinCreateScreen(loginMode);
} else if (loginMode == LoginMode.PASSWORD
&& DeveloperPreferences.shouldOfferPinForLogin()) {
boolean userManuallyEnteredPasswordMode = getIntent()
.getBooleanExtra(LoginActivity.MANUAL_SWITCH_TO_PW_MODE, false);
boolean alreadyDismissedPinCreation =
CommCareApplication.instance().getCurrentApp().getAppPreferences()
.getBoolean(HiddenPreferences.HAS_DISMISSED_PIN_CREATION, false);
if (!alreadyDismissedPinCreation || userManuallyEnteredPasswordMode) {
showPinChoiceDialog(loginMode);
}
}
}
private void showPinChoiceDialog(final LoginMode loginMode) {
String promptMessage;
UserKeyRecord currentUserRecord = CommCareApplication.instance().getRecordForCurrentUser();
if (currentUserRecord.hasPinSet()) {
promptMessage = Localization.get("pin.dialog.prompt.reset");
} else {
promptMessage = Localization.get("pin.dialog.prompt.set");
}
final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, promptMessage);
DialogChoiceItem createPinChoice = new DialogChoiceItem(
Localization.get("pin.dialog.yes"), -1, v -> {
dismissAlertDialog();
launchPinCreateScreen(loginMode);
});
DialogChoiceItem nextTimeChoice = new DialogChoiceItem(
Localization.get("pin.dialog.not.now"), -1, v -> dismissAlertDialog());
DialogChoiceItem notAgainChoice = new DialogChoiceItem(
Localization.get("pin.dialog.never"), -1, v -> {
dismissAlertDialog();
CommCareApplication.instance().getCurrentApp().getAppPreferences()
.edit()
.putBoolean(HiddenPreferences.HAS_DISMISSED_PIN_CREATION, true)
.apply();
showPinFutureAccessDialog();
});
dialog.setChoiceItems(
new DialogChoiceItem[]{createPinChoice, nextTimeChoice, notAgainChoice});
dialog.addCollapsibleInfoPane(Localization.get("pin.dialog.extra.info"));
showAlertDialog(dialog);
}
private void showPinFutureAccessDialog() {
StandardAlertDialog.getBasicAlertDialog(this,
Localization.get("pin.dialog.set.later.title"),
Localization.get("pin.dialog.set.later.message"), null).showNonPersistentDialog();
}
protected void launchPinAuthentication() {
Intent i = new Intent(this, PinAuthenticationActivity.class);
startActivityForResult(i, AUTHENTICATION_FOR_PIN);
}
private void launchPinCreateScreen(LoginMode loginMode) {
Intent i = new Intent(this, CreatePinActivity.class);
i.putExtra(LoginActivity.LOGIN_MODE, loginMode);
startActivityForResult(i, CREATE_PIN);
}
protected void showLocaleChangeMenu(final CommCareActivityUIController uiController) {
final PaneledChoiceDialog dialog =
new PaneledChoiceDialog(this, Localization.get("home.menu.locale.select"));
AdapterView.OnItemClickListener listClickListener = (parent, view, position, id) -> {
String[] localeCodes = ChangeLocaleUtil.getLocaleCodes();
if (position >= localeCodes.length) {
Localization.setLocale("default");
} else {
String selectedLocale = localeCodes[position];
Localization.setLocale(selectedLocale);
MainConfigurablePreferences.setCurrentLocale(selectedLocale);
}
// rebuild home buttons in case language changed;
if (uiController != null) {
uiController.setupUI();
}
rebuildOptionsMenu();
dismissAlertDialog();
};
dialog.setChoiceItems(buildLocaleChoices(), listClickListener);
showAlertDialog(dialog);
}
private static DialogChoiceItem[] buildLocaleChoices() {
String[] locales = ChangeLocaleUtil.getLocaleNames();
DialogChoiceItem[] choices = new DialogChoiceItem[locales.length];
for (int i = 0; i < choices.length; i++) {
choices[i] = DialogChoiceItem.nonListenerItem(locales[i]);
}
return choices;
}
protected void goToFormArchive(boolean incomplete) {
goToFormArchive(incomplete, null);
}
protected void goToFormArchive(boolean incomplete, FormRecord record) {
FirebaseAnalyticsUtil.reportViewArchivedFormsList(incomplete);
Intent i = new Intent(getApplicationContext(), FormRecordListActivity.class);
if (incomplete) {
i.putExtra(FormRecord.META_STATUS, FormRecord.STATUS_INCOMPLETE);
}
if (record != null) {
i.putExtra(FormRecordListActivity.KEY_INITIAL_RECORD_ID, record.getID());
}
startActivityForResult(i, GET_INCOMPLETE_FORM);
}
protected void userTriggeredLogout() {
CommCareApplication.instance().closeUserSession();
setResult(RESULT_OK);
finish();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(WAS_EXTERNAL_KEY, wasExternal);
outState.putBoolean(EXTRA_CONSUMED_KEY, loginExtraWasConsumed);
}
@Override
public void onActivityResultSessionSafe(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_RESTART) {
sessionNavigator.startNextSessionStep();
} else {
// if handling new return code (want to return to home screen) but a return at the
// end of your statement
switch (requestCode) {
case PREFERENCES_ACTIVITY:
if (resultCode == AdvancedActionsPreferences.RESULT_DATA_RESET) {
finish();
} else if (resultCode == DeveloperPreferences.RESULT_SYNC_CUSTOM) {
performCustomRestore();
}
return;
case ADVANCED_ACTIONS_ACTIVITY:
handleAdvancedActionResult(resultCode, intent);
return;
case GET_INCOMPLETE_FORM:
//TODO: We might need to load this from serialized state?
if (resultCode == RESULT_CANCELED) {
refreshUI();
return;
} else if (resultCode == RESULT_OK) {
int record = intent.getIntExtra("FORMRECORDS", -1);
if (record == -1) {
//Hm, what to do here?
break;
}
FormRecord r = CommCareApplication.instance().getUserStorage(
FormRecord.class).read(record);
//Retrieve and load the appropriate ssd
SqlStorage<SessionStateDescriptor> ssdStorage =
CommCareApplication.instance().getUserStorage(
SessionStateDescriptor.class);
Vector<Integer> ssds = ssdStorage.getIDsForValue(
SessionStateDescriptor.META_FORM_RECORD_ID, r.getID());
AndroidSessionWrapper currentState =
CommCareApplication.instance().getCurrentSessionWrapper();
if (ssds.size() == 1) {
currentState.loadFromStateDescription(
ssdStorage.read(ssds.firstElement()));
} else {
currentState.setFormRecordId(r.getID());
}
AndroidCommCarePlatform platform =
CommCareApplication.instance().getCommCarePlatform();
formEntry(platform.getFormDefId(r.getFormNamespace()), r);
return;
}
break;
case GET_COMMAND:
boolean continueWithSessionNav =
processReturnFromGetCommand(resultCode, intent);
if (!continueWithSessionNav) {
return;
}
break;
case GET_CASE:
continueWithSessionNav = processReturnFromGetCase(resultCode, intent);
if (!continueWithSessionNav) {
return;
}
break;
case MODEL_RESULT:
if (intent != null && intent.getBooleanExtra(FormEntryConstants.WAS_INTERRUPTED,
false)) {
tryRestoringFormFromSessionExpiration();
return;
}
continueWithSessionNav = processReturnFromFormEntry(resultCode, intent);
if (!continueWithSessionNav) {
return;
}
if (!CommCareApplication.instance().getSession().appHealthChecksCompleted()) {
// If we haven't done these checks yet in this user session, try to
if (checkForPendingAppHealthActions()) {
// If we kick one off, abandon the session navigation that we were
// going to proceed with, because it may be invalid now
return;
}
}
break;
case AUTHENTICATION_FOR_PIN:
if (resultCode == RESULT_OK) {
launchPinCreateScreen(LoginMode.PASSWORD);
}
return;
case CREATE_PIN:
boolean choseRememberPassword = intent != null && intent.getBooleanExtra(
CreatePinActivity.CHOSE_REMEMBER_PASSWORD, false);
if (choseRememberPassword) {
CommCareApplication.instance().closeUserSession();
} else if (resultCode == RESULT_OK) {
Toast.makeText(this, Localization.get("pin.set.success"),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, Localization.get("pin.not.set"),
Toast.LENGTH_SHORT).show();
}
return;
case MAKE_REMOTE_POST:
stepBackIfCancelled(resultCode);
if (resultCode == RESULT_OK) {
CommCareApplication.instance().getCurrentSessionWrapper().terminateSession();
}
break;
case GET_REMOTE_DATA:
stepBackIfCancelled(resultCode);
break;
case IN_APP_UPDATE_REQUEST_CODE:
if (resultCode == RESULT_CANCELED
&& appUpdateController.availableVersionCode() != null) {
// An update was available for CommCare but user denied updating.
HiddenPreferences.incrementCommCareUpdateCancellationCounter(
String.valueOf(appUpdateController.availableVersionCode()));
// User might be busy right now, so let's not ask him again in this session.
CommCareApplication.instance().getSession().hideInAppUpdate();
}
return;
}
sessionNavigationProceedingAfterOnResume = true;
startNextSessionStepSafe();
}
}
private void performCustomRestore() {
try {
String filePath = DeveloperPreferences.getCustomRestoreDocLocation();
if (filePath != null && !filePath.isEmpty()) {
File f = new File(filePath);
if (f.exists()) {
formAndDataSyncer.performCustomRestoreFromFile(this, f);
} else {
Toast.makeText(this, Localization.get("custom.restore.file.not.exist"),
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, Localization.get("custom.restore.file.not.set"),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, Localization.get("custom.restore.error"),
Toast.LENGTH_LONG).show();
}
}
private boolean processReturnFromGetCase(int resultCode, Intent intent) {
if (resultCode == RESULT_CANCELED) {
return processCanceledGetCommandOrCase();
} else if (resultCode == RESULT_OK) {
return processSuccessfulGetCase(intent);
}
return false;
}
public boolean processReturnFromGetCommand(int resultCode, Intent intent) {
if (resultCode == RESULT_CANCELED) {
return processCanceledGetCommandOrCase();
} else if (resultCode == RESULT_OK) {
return processSuccessfulGetCommand(intent);
}
return true;
}
private boolean processSuccessfulGetCommand(Intent intent) {
AndroidSessionWrapper currentState =
CommCareApplication.instance().getCurrentSessionWrapper();
CommCareSession session = currentState.getSession();
if (sessionStateUnchangedSinceCallout(session, intent)) {
// Get our command, set it, and continue forward
String command = intent.getStringExtra(SessionFrame.STATE_COMMAND_ID);
session.setCommand(command);
return true;
} else {
clearSessionAndExit(currentState, true);
return false;
}
}
private boolean processSuccessfulGetCase(Intent intent) {
AndroidSessionWrapper asw = CommCareApplication.instance().getCurrentSessionWrapper();
CommCareSession currentSession = asw.getSession();
if (sessionStateUnchangedSinceCallout(currentSession, intent)) {
String sessionDatumId = currentSession.getNeededDatum().getDataId();
String chosenCaseId = intent.getStringExtra(SessionFrame.STATE_DATUM_VAL);
currentSession.setDatum(sessionDatumId, chosenCaseId);
return true;
} else {
clearSessionAndExit(asw, true);
return false;
}
}
private boolean processCanceledGetCommandOrCase() {
AndroidSessionWrapper currentState =
CommCareApplication.instance().getCurrentSessionWrapper();
String currentCommand = currentState.getSession().getCommand();
if (currentCommand == null || currentCommand.equals(Menu.TRAINING_MENU_ROOT)) {
// We're stepping back from either the root module menu or the training root menu, so
// go home
currentState.reset();
refreshUI();
return false;
} else {
currentState.getSession().stepBack(currentState.getEvaluationContext());
return true;
}
}
private void handleAdvancedActionResult(int resultCode, Intent intent) {
if (resultCode == AdvancedActionsPreferences.RESULT_FORMS_PROCESSED) {
int formProcessCount = intent.getIntExtra(
AdvancedActionsPreferences.FORM_PROCESS_COUNT_KEY, 0);
String localizationKey = intent.getStringExtra(
AdvancedActionsPreferences.FORM_PROCESS_MESSAGE_KEY);
displayToast(Localization.get(localizationKey, new String[]{"" + formProcessCount}));
refreshUI();
}
}
private static void stepBackIfCancelled(int resultCode) {
if (resultCode == RESULT_CANCELED) {
AndroidSessionWrapper asw = CommCareApplication.instance().getCurrentSessionWrapper();
CommCareSession currentSession = asw.getSession();
currentSession.stepBack(asw.getEvaluationContext());
}
}
public void startNextSessionStepSafe() {
try {
sessionNavigator.startNextSessionStep();
} catch (CommCareInstanceInitializer.FixtureInitializationException e) {
sessionNavigator.stepBack();
if (isDemoUser()) {
// most likely crashing due to data not being available in demo mode
UserfacingErrorHandling.createErrorDialog(this,
Localization.get("demo.mode.feature.unavailable"),
false);
} else {
UserfacingErrorHandling.createErrorDialog(this, e.getMessage(), false);
}
}
}
/**
* @return If the nature of the data that the session is waiting for has not changed since the
* callout that we are returning from was made
*/
private boolean sessionStateUnchangedSinceCallout(CommCareSession session, Intent intent) {
EvaluationContext evalContext =
CommCareApplication.instance().getCurrentSessionWrapper().getEvaluationContext();
String pendingSessionData = intent.getStringExtra(KEY_PENDING_SESSION_DATA);
String sessionNeededData = session.getNeededData(evalContext);
boolean neededDataUnchanged = (pendingSessionData == null && sessionNeededData == null)
|| (pendingSessionData != null && pendingSessionData.equals(sessionNeededData));
String intentDatum = intent.getStringExtra(KEY_PENDING_SESSION_DATUM_ID);
boolean datumIdsUnchanged = intentDatum == null || intentDatum.equals(
session.getNeededDatum().getDataId());
return neededDataUnchanged && datumIdsUnchanged;
}
/**
* Process user returning home from the form entry activity. Triggers form submission cycle,
* cleans up some session state.
*
* @param resultCode exit code of form entry activity
* @param intent The intent of the returning activity, with the saved form provided as the
* intent URI data. Null if the form didn't exit cleanly
* @return Flag signifying that caller should fetch the next activity in the session to launch.
* If false then caller should exit or spawn home activity.
*/
private boolean processReturnFromFormEntry(int resultCode, Intent intent) {
// TODO: We might need to load this from serialized state?
AndroidSessionWrapper currentState =
CommCareApplication.instance().getCurrentSessionWrapper();
// This is the state we were in when we _Started_ form entry
FormRecord current = currentState.getFormRecord();
if (current == null) {
// somehow we lost the form record for the current session
Toast.makeText(this,
"Error while trying to save the form!",
Toast.LENGTH_LONG).show();
Logger.log(LogTypes.TYPE_ERROR_WORKFLOW,
"Form Entry couldn't save because of corrupt state.");
clearSessionAndExit(currentState, true);
return false;
}
// TODO: This should be the default unless we're in some "Uninit" or "incomplete" state
if ((intent != null && intent.getBooleanExtra(FormEntryConstants.IS_ARCHIVED_FORM, false))
||
FormRecord.STATUS_COMPLETE.equals(current.getStatus()) ||
FormRecord.STATUS_SAVED.equals(current.getStatus())) {
// Viewing an old form, so don't change the historical record
// regardless of the exit code
currentState.reset();
if (wasExternal ||
(intent != null && intent.getBooleanExtra(
FormEntryActivity.KEY_IS_RESTART_AFTER_EXPIRATION, false))) {
setResult(RESULT_CANCELED);
this.finish();
} else {
// Return to where we started
goToFormArchive(false, current);
}
return false;
}
if (resultCode == RESULT_OK) {
String formRecordStatus = current.getStatus();
// was the record marked complete?
boolean complete = FormRecord.STATUS_COMPLETE.equals(formRecordStatus)
|| FormRecord.STATUS_UNSENT.equals(formRecordStatus);
// The form is either ready for processing, or not, depending on how it was saved
if (complete) {
startUnsentFormsTask(false, false);
refreshUI();
if (wasExternal) {
currentState.reset();
setResult(RESULT_CANCELED);
this.finish();
return false;
}
// Before we can terminate the session, we need to know that the form has been
// processed in case there is state that depends on it.
boolean terminateSuccessful;
try {
terminateSuccessful = currentState.terminateSession();
} catch (XPathException e) {
UserfacingErrorHandling.logErrorAndShowDialog(this, e, true);
return false;
}
if (!terminateSuccessful) {
// If we didn't find somewhere to go, we're gonna stay here
return false;
}
// Otherwise, we want to keep proceeding in order
// to keep running the workflow
} else {
clearSessionAndExit(currentState, false);
return false;
}
} else if (resultCode == RESULT_CANCELED) {
// Nothing was saved during the form entry activity
Logger.log(LogTypes.TYPE_FORM_ENTRY, "Form Entry Cancelled");
// If the form was unstarted, we want to wipe the record.
if (current.getStatus().equals(FormRecord.STATUS_UNSTARTED)) {
// Entry was cancelled.
FormRecordCleanupTask.wipeRecord(currentState);
}
if (wasExternal) {
currentState.reset();
setResult(RESULT_CANCELED);
this.finish();
return false;
} else if (current.getStatus().equals(FormRecord.STATUS_INCOMPLETE) &&
intent != null && !intent.getBooleanExtra(
FormEntryActivity.KEY_IS_RESTART_AFTER_EXPIRATION, false)) {
currentState.reset();
// We should head back to the incomplete forms screen
goToFormArchive(true, current);
return false;
} else {
// If we cancelled form entry from a normal menu entry
// we want to go back to where were were right before we started
// entering the form.
currentState.getSession().stepBack(currentState.getEvaluationContext());
currentState.setFormRecordId(-1);
}
}
return true;
}
private void clearSessionAndExit(AndroidSessionWrapper currentState, boolean shouldWarnUser) {
currentState.reset();
if (wasExternal) {
setResult(RESULT_CANCELED);
this.finish();
}
refreshUI();
if (shouldWarnUser) {
showSessionRefreshWarning();
}
}
private void showSessionRefreshWarning() {
showAlertDialog(StandardAlertDialog.getBasicAlertDialog(this,
Localization.get("session.refresh.error.title"),
Localization.get("session.refresh.error.message"), null));
}
private void showDemoModeWarning() {
StandardAlertDialog d = StandardAlertDialog.getBasicAlertDialogWithIcon(this,
Localization.get("demo.mode.warning.title"),
Localization.get("demo.mode.warning.main"),
android.R.drawable.ic_dialog_info, null);
d.addEmphasizedMessage(Localization.get("demo.mode.warning.emphasized"));
showAlertDialog(d);
}
private void createErrorDialog(String errorMsg, AlertDialog.OnClickListener errorListener) {
showAlertDialog(StandardAlertDialog.getBasicAlertDialogWithIcon(this,
Localization.get("app.handled.error.title"), errorMsg,
android.R.drawable.ic_dialog_info, errorListener));
}
@Override
public void processSessionResponse(int statusCode) {
AndroidSessionWrapper asw = CommCareApplication.instance().getCurrentSessionWrapper();
switch (statusCode) {
case SessionNavigator.ASSERTION_FAILURE:
handleAssertionFailureFromSessionNav(asw);
break;
case SessionNavigator.NO_CURRENT_FORM:
handleNoFormFromSessionNav(asw);
break;
case SessionNavigator.START_FORM_ENTRY:
startFormEntry(asw);
break;
case SessionNavigator.GET_COMMAND:
handleGetCommand(asw);
break;
case SessionNavigator.START_ENTITY_SELECTION:
launchEntitySelect(asw.getSession());
break;
case SessionNavigator.LAUNCH_CONFIRM_DETAIL:
launchConfirmDetail(asw);
break;
case SessionNavigator.PROCESS_QUERY_REQUEST:
launchQueryMaker();
break;
case SessionNavigator.START_SYNC_REQUEST:
launchRemoteSync(asw);
break;
case SessionNavigator.XPATH_EXCEPTION_THROWN:
UserfacingErrorHandling
.logErrorAndShowDialog(this, sessionNavigator.getCurrentException(), false);
asw.reset();
break;
case SessionNavigator.REPORT_CASE_AUTOSELECT:
FirebaseAnalyticsUtil.reportFeatureUsage(
AnalyticsParamValue.FEATURE_CASE_AUTOSELECT);
break;
}
}
@Override
public CommCareSession getSessionForNavigator() {
return CommCareApplication.instance().getCurrentSession();
}
@Override
public EvaluationContext getEvalContextForNavigator() {
return CommCareApplication.instance().getCurrentSessionWrapper().getEvaluationContext();
}
private void handleAssertionFailureFromSessionNav(final AndroidSessionWrapper asw) {
EvaluationContext ec = asw.getEvaluationContext();
Text text = asw.getSession().getCurrentEntry().getAssertions().getAssertionFailure(ec);
createErrorDialog(text.evaluate(ec), (dialog, i) -> {
dismissAlertDialog();
asw.getSession().stepBack(asw.getEvaluationContext());
HomeScreenBaseActivity.this.sessionNavigator.startNextSessionStep();
});
}
private void handleNoFormFromSessionNav(AndroidSessionWrapper asw) {
boolean terminateSuccesful;
try {
terminateSuccesful = asw.terminateSession();
} catch (XPathTypeMismatchException e) {
UserfacingErrorHandling.logErrorAndShowDialog(this, e, true);
return;
}
if (terminateSuccesful) {
sessionNavigator.startNextSessionStep();
} else {
refreshUI();
}
}
private void handleGetCommand(AndroidSessionWrapper asw) {
Intent i = new Intent(this, MenuActivity.class);
String command = asw.getSession().getCommand();
i.putExtra(SessionFrame.STATE_COMMAND_ID, command);
addPendingDataExtra(i, asw.getSession());
startActivityForResult(i, GET_COMMAND);
}
private void launchRemoteSync(AndroidSessionWrapper asw) {
String command = asw.getSession().getCommand();
Entry commandEntry = CommCareApplication.instance().getCommCarePlatform().getEntry(command);
if (commandEntry instanceof RemoteRequestEntry) {
PostRequest postRequest = ((RemoteRequestEntry)commandEntry).getPostRequest();
Intent i = new Intent(getApplicationContext(), PostRequestActivity.class);
i.putExtra(PostRequestActivity.URL_KEY, postRequest.getUrl());
i.putExtra(PostRequestActivity.PARAMS_KEY,
new HashMap<>(postRequest.getEvaluatedParams(asw.getEvaluationContext())));
startActivityForResult(i, MAKE_REMOTE_POST);
} else {
// expected a sync entry; clear session and show vague 'session error' message to user
clearSessionAndExit(asw, true);
}
}
private void launchQueryMaker() {
Intent i = new Intent(getApplicationContext(), QueryRequestActivity.class);
startActivityForResult(i, GET_REMOTE_DATA);
}
private void launchEntitySelect(CommCareSession session) {
startActivityForResult(getSelectIntent(session), GET_CASE);
}
private Intent getSelectIntent(CommCareSession session) {
Intent i = new Intent(getApplicationContext(), EntitySelectActivity.class);
i.putExtra(SessionFrame.STATE_COMMAND_ID, session.getCommand());
StackFrameStep lastPopped = session.getPoppedStep();
if (lastPopped != null && SessionFrame.STATE_DATUM_VAL.equals(lastPopped.getType())) {
i.putExtra(EntitySelectActivity.EXTRA_ENTITY_KEY, lastPopped.getValue());
}
addPendingDataExtra(i, session);
addPendingDatumIdExtra(i, session);
return i;
}
public void launchUpdateActivity(boolean autoProceedUpdateInstall) {
Intent i = new Intent(getApplicationContext(), UpdateActivity.class);
i.putExtra(UpdateActivity.KEY_PROCEED_AUTOMATICALLY, autoProceedUpdateInstall);
startActivity(i);
}
void enterTrainingModule() {
CommCareApplication.instance().getCurrentSession().setCommand(
org.commcare.suite.model.Menu.TRAINING_MENU_ROOT);
startNextSessionStepSafe();
}
// Launch an intent to load the confirmation screen for the current selection
private void launchConfirmDetail(AndroidSessionWrapper asw) {
CommCareSession session = asw.getSession();
SessionDatum selectDatum = session.getNeededDatum();
if (selectDatum instanceof EntityDatum) {
EntityDatum entityDatum = (EntityDatum)selectDatum;
TreeReference contextRef = sessionNavigator.getCurrentAutoSelection();
if (this.getString(R.string.panes).equals("two")
&& getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// Large tablet in landscape: send to entity select activity
// (awesome mode, with case pre-selected) instead of entity detail
Intent i = getSelectIntent(session);
String caseId = EntityDatum.getCaseIdFromReference(
contextRef, entityDatum, asw.getEvaluationContext());
i.putExtra(EntitySelectActivity.EXTRA_ENTITY_KEY, caseId);
startActivityForResult(i, GET_CASE);
} else {
// Launch entity detail activity
Intent detailIntent = new Intent(getApplicationContext(),
EntityDetailActivity.class);
EntityDetailUtils.populateDetailIntent(
detailIntent, contextRef, entityDatum, asw);
addPendingDataExtra(detailIntent, session);
addPendingDatumIdExtra(detailIntent, session);
startActivityForResult(detailIntent, GET_CASE);
}
}
}
protected static void addPendingDataExtra(Intent i, CommCareSession session) {
EvaluationContext evalContext =
CommCareApplication.instance().getCurrentSessionWrapper().getEvaluationContext();
i.putExtra(KEY_PENDING_SESSION_DATA, session.getNeededData(evalContext));
}
private static void addPendingDatumIdExtra(Intent i, CommCareSession session) {
i.putExtra(KEY_PENDING_SESSION_DATUM_ID, session.getNeededDatum().getDataId());
}
/**
* Create (or re-use) a form record and pass it to the form entry activity launcher. If there is
* an existing incomplete form that uses the same case, ask the user if they want to edit or
* delete that one.
*
* @param state Needed for FormRecord manipulations
*/
private void startFormEntry(AndroidSessionWrapper state) {
if (state.getFormRecordId() == -1) {
if (HiddenPreferences.isIncompleteFormsEnabled()) {
// Are existing (incomplete) forms using the same case?
SessionStateDescriptor existing =
state.getExistingIncompleteCaseDescriptor();
if (existing != null) {
// Ask user if they want to just edit existing form that
// uses the same case.
createAskUseOldDialog(state, existing);
return;
}
}
// Generate a stub form record and commit it
state.commitStub();
} else {
Logger.log(LogTypes.TYPE_FORM_ENTRY,
"Somehow ended up starting form entry with old state?");
}
FormRecord record = state.getFormRecord();
AndroidCommCarePlatform platform = CommCareApplication.instance().getCommCarePlatform();
formEntry(platform.getFormDefId(record.getFormNamespace()), record,
CommCareActivity.getTitle(this, null), false);
}
private void formEntry(int formDefId, FormRecord r) {
formEntry(formDefId, r, null, false);
}
private void formEntry(int formDefId, FormRecord r, String headerTitle,
boolean isRestartAfterSessionExpiration) {
Logger.log(LogTypes.TYPE_FORM_ENTRY, "Form Entry Starting|" +
(r.getInstanceID() == null ? "" : r.getInstanceID() + "|") +
r.getFormNamespace());
//TODO: This is... just terrible. Specify where external instance data should come from
FormLoaderTask.iif = new AndroidInstanceInitializer(
CommCareApplication.instance().getCurrentSession());
// Create our form entry activity callout
Intent i = new Intent(getApplicationContext(), FormEntryActivity.class);
i.setAction(Intent.ACTION_EDIT);
i.putExtra(FormEntryInstanceState.KEY_FORM_RECORD_DESTINATION,
CommCareApplication.instance().getCurrentApp().fsPath(
(GlobalConstants.FILE_CC_FORMS)));
// See if there's existing form data that we want to continue entering
if (!StringUtils.isEmpty(r.getFilePath())) {
i.putExtra(FormEntryActivity.KEY_FORM_RECORD_ID, r.getID());
} else {
i.putExtra(FormEntryActivity.KEY_FORM_DEF_ID, formDefId);
}
i.putExtra(FormEntryActivity.KEY_RESIZING_ENABLED, HiddenPreferences.getResizeMethod());
i.putExtra(FormEntryActivity.KEY_INCOMPLETE_ENABLED,
HiddenPreferences.isIncompleteFormsEnabled());
i.putExtra(FormEntryActivity.KEY_AES_STORAGE_KEY,
Base64.encodeToString(r.getAesKey(), Base64.DEFAULT));
i.putExtra(FormEntrySessionWrapper.KEY_RECORD_FORM_ENTRY_SESSION,
DeveloperPreferences.isSessionSavingEnabled());
i.putExtra(FormEntryActivity.KEY_IS_RESTART_AFTER_EXPIRATION,
isRestartAfterSessionExpiration);
if (headerTitle != null) {
i.putExtra(FormEntryActivity.KEY_HEADER_STRING, headerTitle);
}
if (isRestoringSession) {
isRestoringSession = false;
SharedPreferences prefs =
CommCareApplication.instance().getCurrentApp().getAppPreferences();
String formEntrySession = prefs.getString(DevSessionRestorer.CURRENT_FORM_ENTRY_SESSION,
"");
if (!"".equals(formEntrySession)) {
i.putExtra(FormEntrySessionWrapper.KEY_FORM_ENTRY_SESSION, formEntrySession);
}
}
startActivityForResult(i, MODEL_RESULT);
}
private void triggerSync(boolean triggeredByAutoSyncPending) {
if (triggeredByAutoSyncPending) {
long lastUploadSyncAttempt = HiddenPreferences.getLastUploadSyncAttempt();
String footer = lastUploadSyncAttempt == 0 ? "never" :
SimpleDateFormat.getDateTimeInstance().format(lastUploadSyncAttempt);
Logger.log(LogTypes.TYPE_USER, "autosync triggered. Last Sync|" + footer);
}
refreshUI();
sendFormsOrSync(false);
}
@Override
public void onResumeSessionSafe() {
if (!redirectedInOnCreate && !sessionNavigationProceedingAfterOnResume) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
refreshActionBar();
}
attemptDispatchHomeScreen();
}
// reset these
redirectedInOnCreate = false;
sessionNavigationProceedingAfterOnResume = false;
}
private void attemptDispatchHomeScreen() {
try {
CommCareApplication.instance().getSession();
} catch (SessionUnavailableException e) {
// User was logged out somehow, so we want to return to dispatch activity
setResult(RESULT_OK);
this.finish();
return;
}
if (!checkForPendingAppHealthActions()) {
// Display the home screen!
refreshUI();
}
}
/**
* @return true if we kicked off any foreground processes
*/
private boolean checkForPendingAppHealthActions() {
boolean kickedOff = false;
if (RecoveryMeasuresHelper.recoveryMeasuresPending()) {
finishWithExecutionIntent();
kickedOff = true;
} else if (UpdateActivity.isUpdateBlockedOnSync()
&& UpdateActivity.sBlockedUpdateWorkflowInProgress) {
triggerSync(true);
kickedOff = true;
} else if (CommCareApplication.instance().isSyncPending()) {
triggerSync(true);
kickedOff = true;
}
// Trigger background log submission if required
String userId = CommCareApplication.instance().getSession().getLoggedInUser().getUniqueId();
if (HiddenPreferences.shouldForceLogs(userId)) {
CommCareUtil.triggerLogSubmission(CommCareApplication.instance(), true);
}
CommCareApplication.instance().getSession().setAppHealthChecksCompleted();
return kickedOff;
}
@Override
public void handlePullTaskResult(ResultAndError<DataPullTask.PullTaskResult> resultAndError,
boolean userTriggeredSync, boolean formsToSend, boolean usingRemoteKeyManagement) {
super.handlePullTaskResult(resultAndError, userTriggeredSync, formsToSend,
usingRemoteKeyManagement);
if (UpdateActivity.sBlockedUpdateWorkflowInProgress) {
Intent i = new Intent(getApplicationContext(), UpdateActivity.class);
i.putExtra(UpdateActivity.KEY_PROCEED_AUTOMATICALLY, true);
if (resultAndError.data == DataPullTask.PullTaskResult.DOWNLOAD_SUCCESS) {
i.putExtra(UpdateActivity.KEY_PRE_UPDATE_SYNC_SUCCEED, true);
} else {
i.putExtra(UpdateActivity.KEY_PRE_UPDATE_SYNC_SUCCEED, false);
}
startActivity(i);
}
}
private void finishWithExecutionIntent() {
Intent i = new Intent();
i.putExtra(DispatchActivity.EXECUTE_RECOVERY_MEASURES, true);
setResult(RESULT_OK, i);
finish();
}
private void createAskUseOldDialog(final AndroidSessionWrapper state,
final SessionStateDescriptor existing) {
final AndroidCommCarePlatform platform =
CommCareApplication.instance().getCommCarePlatform();
String title = Localization.get("app.workflow.incomplete.continue.title");
String msg = Localization.get("app.workflow.incomplete.continue");
StandardAlertDialog d = new StandardAlertDialog(this, title, msg);
DialogInterface.OnClickListener listener = (dialog, i) -> {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
// use the old form instance and load the it's state from the descriptor
state.loadFromStateDescription(existing);
formEntry(platform.getFormDefId(state.getSession().getForm()),
state.getFormRecord());
break;
case DialogInterface.BUTTON_NEGATIVE:
// delete the old incomplete form
FormRecordCleanupTask.wipeRecord(existing);
// fallthrough to new now that old record is gone
case DialogInterface.BUTTON_NEUTRAL:
// create a new form record and begin form entry
state.commitStub();
formEntry(platform.getFormDefId(state.getSession().getForm()),
state.getFormRecord());
}
dismissAlertDialog();
};
d.setPositiveButton(Localization.get("option.yes"), listener);
d.setNegativeButton(Localization.get("app.workflow.incomplete.continue.option.delete"),
listener);
d.setNeutralButton(Localization.get("option.no"), listener);
showAlertDialog(d);
}
protected static boolean isDemoUser() {
try {
User u = CommCareApplication.instance().getSession().getLoggedInUser();
return (User.TYPE_DEMO.equals(u.getUserType()));
} catch (SessionUnavailableException e) {
// Default to a normal user: this should only happen if session
// expires and hasn't redirected to login.
return false;
}
}
public static void createPreferencesMenu(AppCompatActivity activity) {
Intent i = new Intent(activity, SessionAwarePreferenceActivity.class);
i.putExtra(CommCarePreferenceActivity.EXTRA_PREF_TYPE,
CommCarePreferenceActivity.PREF_TYPE_COMMCARE);
activity.startActivityForResult(i, PREFERENCES_ACTIVITY);
}
protected void showAdvancedActionsPreferences() {
Intent intent = new Intent(this, SessionAwarePreferenceActivity.class);
intent.putExtra(CommCarePreferenceActivity.EXTRA_PREF_TYPE,
CommCarePreferenceActivity.PREF_TYPE_ADVANCED_ACTIONS);
startActivityForResult(intent, ADVANCED_ACTIONS_ACTIVITY);
}
protected void showAboutCommCareDialog() {
CommCareAlertDialog dialog = DialogCreationHelpers.buildAboutCommCareDialog(this);
dialog.makeCancelable();
dialog.setOnDismissListener(dialog1 -> handleDeveloperModeClicks());
showAlertDialog(dialog);
}
private void handleDeveloperModeClicks() {
mDeveloperModeClicks++;
if (mDeveloperModeClicks == 4) {
DeveloperPreferences.setSuperuserEnabled(true);
Toast.makeText(this, Localization.get("home.developer.options.enabled"),
Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean isBackEnabled() {
return false;
}
/**
* For Testing purposes only
*/
public SessionNavigator getSessionNavigator() {
if (BuildConfig.DEBUG) {
return sessionNavigator;
} else {
throw new RuntimeException("On principal of design, only meant for testing purposes");
}
}
/**
* For Testing purposes only
*/
public void setFormAndDataSyncer(FormAndDataSyncer formAndDataSyncer) {
if (BuildConfig.DEBUG) {
this.formAndDataSyncer = formAndDataSyncer;
} else {
throw new RuntimeException("On principal of design, only meant for testing purposes");
}
}
abstract void refreshUI();
abstract void refreshCCUpdateOption();
@Override
protected void onDestroy() {
if (appUpdateController != null) {
appUpdateController.unregister();
}
super.onDestroy();
}
protected void startCommCareUpdate() {
appUpdateController.startUpdate(this);
}
private void handleAppUpdate() {
AppUpdateState state = appUpdateController.getStatus();
switch (state) {
case UNAVAILABLE:
if (ConnectivityStatus.isNetworkAvailable(this)) {
// We just queried and found that no update is available.
// Let's check again in next session.
CommCareApplication.instance().getSession().hideInAppUpdate();
}
break;
case AVAILABLE:
if (HiddenPreferences.getCommCareUpdateCancellationCounter(
String.valueOf(appUpdateController.availableVersionCode()))
> MAX_CC_UPDATE_CANCELLATION) {
showCommCareUpdateMenu = true;
refreshCCUpdateOption();
return;
}
startCommCareUpdate();
break;
case DOWNLOADING:
// Native downloads app gives a notification regarding the current download in
// progress.
NotificationMessage message = NotificationMessageFactory.message(
NotificationMessageFactory.StockMessages.InApp_Update,
APP_UPDATE_NOTIFICATION);
CommCareApplication.notificationManager().reportNotificationMessage(message);
if (showCommCareUpdateMenu) {
// Once downloading is started, we shouldn't show the update menu anymore.
showCommCareUpdateMenu = false;
refreshCCUpdateOption();
}
break;
case DOWNLOADED:
CommCareApplication.notificationManager().clearNotifications(
APP_UPDATE_NOTIFICATION);
StandardAlertDialog dialog = StandardAlertDialog.getBasicAlertDialog(this,
Localization.get("in.app.update.installed.title"),
Localization.get("in.app.update.installed.detail"),
null);
dialog.setPositiveButton(Localization.get("in.app.update.dialog.restart"),
(dialog1, which) -> {
appUpdateController.completeUpdate();
dismissAlertDialog();
});
dialog.setNegativeButton(Localization.get("in.app.update.dialog.cancel"),
(dialog1, which) -> {
dismissAlertDialog();
});
showAlertDialog(dialog);
FirebaseAnalyticsUtil.reportInAppUpdateResult(true,
AnalyticsParamValue.IN_APP_UPDATE_SUCCESS);
break;
case FAILED:
String errorReason = "in.app.update.error.unknown";
switch (appUpdateController.getErrorCode()) {
case InstallErrorCode.ERROR_INSTALL_NOT_ALLOWED:
errorReason = "in.app.update.error.not.allowed";
break;
case InstallErrorCode.NO_ERROR_PARTIALLY_ALLOWED:
errorReason = "in.app.update.error.partially.allowed";
break;
case InstallErrorCode.ERROR_UNKNOWN:
errorReason = "in.app.update.error.unknown";
break;
case InstallErrorCode.ERROR_PLAY_STORE_NOT_FOUND:
errorReason = "in.app.update.error.playstore";
break;
case InstallErrorCode.ERROR_INVALID_REQUEST:
errorReason = "in.app.update.error.invalid.request";
break;
case InstallErrorCode.ERROR_INTERNAL_ERROR:
errorReason = "in.app.update.error.internal.error";
break;
}
Logger.log(LogTypes.TYPE_CC_UPDATE,
"CommCare In App Update failed because : " + errorReason);
CommCareApplication.notificationManager().clearNotifications(
APP_UPDATE_NOTIFICATION);
Toast.makeText(this, Localization.get(errorReason), Toast.LENGTH_LONG).show();
FirebaseAnalyticsUtil.reportInAppUpdateResult(false, errorReason);
break;
}
}
} |
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class GUIframe implements Engine.EngineClient {
boolean DEBUG = true;
private JFrame window;
private JPanel mainPanel; // the main Panel will have sub panels
private JPanel canvasPanel;
private JPanel buttonsPanel;
BufferedImage image;
private MyCanvas canvas;
String suffices[];
private Engine engine;
private JButton startFilter;
private JButton pauseFilter;
public GUIframe(int width, int height) throws FileNotFoundException,
IOException {
window = new JFrame("Dot Vinci");
window.setSize(width, height);
// add canvasPanel objects
canvas = new MyCanvas();
canvas.setSize(width, height);
canvas.setBounds(0, 0, 300, 300);
canvas.setBackground(Color.WHITE);
// intialize engine
engine = new Engine();
engine.setEngineClient(this);
if (DEBUG) {
image = ImageIO.read(new FileInputStream("sample.jpg"));
engine.setImage(image);
System.out.println(String.format("Size is width: %d height: %d", image.getWidth(), image.getHeight()));
}
// add buttonsPanel objects
// - add buttons
JButton openImage = new JButton("Open Image");
openImage.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (engine.isTimerRunning()) {
// Pause drawing on canvas to load image
for(ActionListener a: pauseFilter.getActionListeners()) {
a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null) {
});
}
}
// open a JFilesChooser when the open button is clicked
JFileChooser chooser = new JFileChooser();
// Get array of available formats (only once)
if (suffices == null) {
suffices = ImageIO.getReaderFileSuffixes();
// Add a file filter for each one
for (int i = 0; i < suffices.length; i++) {
FileNameExtensionFilter filter = new FileNameExtensionFilter(
suffices[i] + " files", suffices[i]);
chooser.addChoosableFileFilter(filter);
}
}
chooser.setFileFilter(new ImageFilter());
chooser.setAcceptAllFileFilterUsed(false);
int ret = chooser.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
// add the selected file to the canvas
File file = chooser.getSelectedFile();
try {
image = ImageIO.read(new FileInputStream(file
.toString()));
engine.loadImageFromFile(file);
canvas.repaint();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println(file);
}
}
});
JButton saveImage = new JButton("Save Image");
// - add filters
JLabel filterText = new JLabel("Filters:");
final JRadioButton noFilter = new JRadioButton("None");
noFilter.setSelected(true);
final JRadioButton sepiaFilter = new JRadioButton("Sepia");
final JRadioButton grayscaleFilter = new JRadioButton("Gray Scale");
final JRadioButton negativeFilter = new JRadioButton("Negative");
//prevent user from unchecking a radio button
noFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (noFilter.isSelected() == false) {
noFilter.setSelected(true);
engine.setFilter(Engine.Filter.NORMAL);
}
}
});
sepiaFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (sepiaFilter.isSelected() == false) {
sepiaFilter.setSelected(true);
engine.setFilter(Engine.Filter.SEPIA);
}
}
});
negativeFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (negativeFilter.isSelected() == false) {
negativeFilter.setSelected(true);
engine.setFilter(Engine.Filter.NEGATIVE);
}
}
});
grayscaleFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (grayscaleFilter.isSelected() == false) {
grayscaleFilter.setSelected(true);
engine.setFilter(Engine.Filter.GRAYSCALE);
}
}
});
//uncheck all other radio buttons when the user checks a radio button
noFilter.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (noFilter.isSelected() == true) {
sepiaFilter.setSelected(false);
grayscaleFilter.setSelected(false);
negativeFilter.setSelected(false);
}
}
});
sepiaFilter.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (sepiaFilter.isSelected() == true) {
noFilter.setSelected(false);
grayscaleFilter.setSelected(false);
negativeFilter.setSelected(false);
}
}
});
negativeFilter.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (negativeFilter.isSelected() == true) {
sepiaFilter.setSelected(false);
grayscaleFilter.setSelected(false);
noFilter.setSelected(false);
}
}
});
grayscaleFilter.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (grayscaleFilter.isSelected() == true) {
sepiaFilter.setSelected(false);
noFilter.setSelected(false);
negativeFilter.setSelected(false);
}
}
});
// - add slider
JLabel renderSpeedText = new JLabel("Render Speed:");
final JSlider renderSpeed_slider = new JSlider(1, 100);
final JTextField renderSpeed_value = new JTextField(3);
Dimension dim = new Dimension(40, 30);
renderSpeed_value.setSize(20, 20);
renderSpeed_value.setMaximumSize(dim);
renderSpeed_value.setText("50%");
renderSpeed_slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
renderSpeed_value.setText(String.valueOf(renderSpeed_slider
.getValue() + "%"));
}
});
// setup the panels
mainPanel = new JPanel();
canvasPanel = new JPanel();
buttonsPanel = new JPanel();
// buttonsPanel.setBounds(0, 0, 300, 300);
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
canvas.setBounds(0, 0, 800, 1024);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
// setup the button panel
Container contentPane = window.getContentPane();
buttonsPanel.add(openImage);
buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10)));
buttonsPanel.add(saveImage);
buttonsPanel.add(Box.createRigidArea(new Dimension(5, 20)));
buttonsPanel.add(filterText);
buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10)));
JPanel filterPanel = new JPanel();
filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.X_AXIS));
filterPanel.add(Box.createRigidArea(new Dimension(10, 20)));
filterPanel.add(filterText);
filterPanel.add(Box.createRigidArea(new Dimension(10, 20)));
filterPanel.add(noFilter);
filterPanel.add(sepiaFilter);
filterPanel.add(grayscaleFilter);
filterPanel.add(negativeFilter);
buttonsPanel.add(filterPanel);
buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10)));
buttonsPanel.add(renderSpeedText);
buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10)));
buttonsPanel.add(renderSpeed_slider);
buttonsPanel.add(Box.createRigidArea(new Dimension(5, 10)));
buttonsPanel.add(renderSpeed_value);
startFilter = new JButton("Start filter");
buttonsPanel.add(startFilter);
startFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (image == null) {
JOptionPane.showMessageDialog(window,
"Cannot start timer without an image open");
return;
}
engine.startTimer(renderSpeed_slider.getValue());
pauseFilter.setVisible(true);
startFilter.setVisible(false);
}
});
pauseFilter = new JButton("Pause filter");
buttonsPanel.add(pauseFilter);
pauseFilter.setVisible(false);
startFilter.setVisible(true);
pauseFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pauseFilter.setVisible(false);
startFilter.setVisible(true);
/*
* TODO: Add actions to pause drawing here
*/
}
});
canvasPanel.add(canvas);
mainPanel.add(buttonsPanel);
mainPanel.add(canvasPanel);
// add the main panel to the window
window.add(mainPanel);
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setResizable(true);
window.setVisible(true);
}
class MyCanvas extends Canvas {
@Override
public void paint(Graphics g) {
engine.updateOutput(g, this);
}
}
@Override
public void onTimerTick() {
canvas.repaint();
}
} |
package com.sun.star.wizards.db;
// import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.beans.*;
// import com.sun.star.container.NoSuchElementException;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XNameAccess;
import com.sun.star.sdbcx.XColumnsSupplier;
// import com.sun.star.sdb.XColumn;
import com.sun.star.sdb.XSingleSelectQueryComposer;
import com.sun.star.sdb.XSingleSelectQueryAnalyzer;
import com.sun.star.ui.dialogs.XExecutableDialog;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.sdbc.SQLException;
import com.sun.star.lang.XInitialization;
import com.sun.star.awt.XWindow;
import com.sun.star.sdb.SQLFilterOperator;
import com.sun.star.wizards.common.*;
import java.util.ArrayList;
public class SQLQueryComposer
{
public XColumnsSupplier xColSuppl;
// XSQLQueryComposer xSQLQueryComposer;
QueryMetaData CurDBMetaData;
// String m_sSelectClause;
// String m_sFromClause;
public XSingleSelectQueryAnalyzer m_xQueryAnalyzer;
ArrayList<CommandName> composedCommandNames = new ArrayList<CommandName>(1);
private XSingleSelectQueryComposer m_queryComposer;
XMultiServiceFactory xMSF;
boolean bincludeGrouping = true;
public SQLQueryComposer(QueryMetaData _CurDBMetaData)
{
try
{
this.CurDBMetaData = _CurDBMetaData;
xMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, CurDBMetaData.DBConnection);
final Object oQueryComposer = xMSF.createInstance("com.sun.star.sdb.SingleSelectQueryComposer");
m_xQueryAnalyzer = UnoRuntime.queryInterface(XSingleSelectQueryAnalyzer.class, oQueryComposer);
m_queryComposer = UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, m_xQueryAnalyzer);
}
catch (Exception exception)
{
exception.printStackTrace(System.out);
}
}
private boolean addtoSelectClause(String DisplayFieldName) throws SQLException
{
return !(bincludeGrouping && CurDBMetaData.xDBMetaData.supportsGroupByUnrelated() && CurDBMetaData.GroupFieldNames != null && JavaTools.FieldInList(CurDBMetaData.GroupFieldNames, DisplayFieldName) > -1);
}
public String getSelectClause(boolean _baddAliasFieldNames) throws SQLException
{
String sSelectBaseClause = "SELECT ";
String sSelectClause = sSelectBaseClause;
for (int i = 0; i < CurDBMetaData.FieldColumns.length; i++)
{
if (addtoSelectClause(CurDBMetaData.FieldColumns[i].getDisplayFieldName()))
{
int iAggregate = CurDBMetaData.getAggregateIndex(CurDBMetaData.FieldColumns[i].getDisplayFieldName());
if (iAggregate > -1)
{
sSelectClause += CurDBMetaData.AggregateFieldNames[iAggregate][1] + "(" + getComposedAliasFieldName(CurDBMetaData.AggregateFieldNames[iAggregate][0]) + ")";
if (_baddAliasFieldNames)
{
sSelectClause += getAliasFieldNameClause(CurDBMetaData.AggregateFieldNames[iAggregate][0]);
}
}
else
{
sSelectClause += getComposedAliasFieldName(CurDBMetaData.FieldColumns[i].getDisplayFieldName());
if (_baddAliasFieldNames)
{
sSelectClause += getAliasFieldNameClause(CurDBMetaData.FieldColumns[i].getDisplayFieldName());
}
}
sSelectClause += ", ";
}
}
// TODO: little bit unhandy version of remove the append 'comma' at the end
if (sSelectClause.equals(sSelectBaseClause))
{
sSelectClause = sSelectClause.substring(0, sSelectClause.length() - 1);
}
else
{
sSelectClause = sSelectClause.substring(0, sSelectClause.length() - 2);
}
return sSelectClause;
}
public String getAliasFieldNameClause(String _FieldName)
{
String FieldTitle = CurDBMetaData.getFieldTitle(_FieldName);
if (!FieldTitle.equals(_FieldName))
{
return " AS " + CommandName.quoteName(FieldTitle, CurDBMetaData.getIdentifierQuote());
}
else
{
return "";
}
}
public void appendFilterConditions() throws SQLException
{
try
{
for (int i = 0; i < CurDBMetaData.getFilterConditions().length; i++)
{
m_queryComposer.setStructuredFilter(CurDBMetaData.getFilterConditions());
}
}
catch (Exception exception)
{
exception.printStackTrace(System.out);
}
}
public void prependSortingCriteria() throws SQLException
{
XIndexAccess xColumnIndexAccess = m_xQueryAnalyzer.getOrderColumns();
m_queryComposer.setOrder("");
for (int i = 0; i < CurDBMetaData.getSortFieldNames().length; i++)
{
appendSortingCriterion(i, false);
}
for (int i = 0; i < xColumnIndexAccess.getCount(); i++)
{
try
{
XPropertySet xColumnPropertySet = UnoRuntime.queryInterface(XPropertySet.class, xColumnIndexAccess.getByIndex(i));
String sName = (String) xColumnPropertySet.getPropertyValue(PropertyNames.PROPERTY_NAME);
if (JavaTools.FieldInTable(CurDBMetaData.getSortFieldNames(), sName) == -1)
{
boolean bascend = AnyConverter.toBoolean(xColumnPropertySet.getPropertyValue("IsAscending"));
m_queryComposer.appendOrderByColumn(xColumnPropertySet, bascend);
}
}
catch (Exception e)
{
e.printStackTrace(System.out);
}
}
}
private void appendSortingCriterion(int _SortIndex, boolean _baddAliasFieldNames) throws SQLException
{
String sSortValue = CurDBMetaData.getSortFieldNames()[_SortIndex][0];
XPropertySet xColumn = CurDBMetaData.getColumnObjectByFieldName(sSortValue, _baddAliasFieldNames);
String sSort = CurDBMetaData.getSortFieldNames()[_SortIndex][1];
boolean bascend = (sSort.equals("ASC"));
m_queryComposer.appendOrderByColumn(xColumn, bascend);
}
public void appendSortingcriteria(boolean _baddAliasFieldNames) throws SQLException
{
String sOrder = "";
m_queryComposer.setOrder("");
for (int i = 0; i < CurDBMetaData.getSortFieldNames().length; i++)
{
String sSortValue = CurDBMetaData.getSortFieldNames()[i][0];
int iAggregate = CurDBMetaData.getAggregateIndex(sSortValue);
if (iAggregate > -1)
{
sOrder = m_xQueryAnalyzer.getOrder();
if (sOrder.length() > 0)
{
sOrder += ", ";
}
sOrder += CurDBMetaData.AggregateFieldNames[iAggregate][1] + "(" + CurDBMetaData.AggregateFieldNames[iAggregate][0] + ")";
sOrder += " " + CurDBMetaData.getSortFieldNames()[i][1];
m_queryComposer.setOrder(sOrder);
}
else
{
appendSortingCriterion(i, _baddAliasFieldNames);
}
sOrder = m_xQueryAnalyzer.getOrder();
}
// just for debug!
sOrder = m_queryComposer.getOrder();
}
public void appendGroupByColumns(boolean _baddAliasFieldNames) throws SQLException
{
for (int i = 0; i < CurDBMetaData.GroupFieldNames.length; i++)
{
XPropertySet xColumn = CurDBMetaData.getColumnObjectByFieldName(CurDBMetaData.GroupFieldNames[i], _baddAliasFieldNames);
m_queryComposer.appendGroupByColumn(xColumn);
}
}
public void setDBMetaData(QueryMetaData _oDBMetaData)
{
this.CurDBMetaData = _oDBMetaData;
}
private PropertyValue[][] replaceConditionsByAlias(PropertyValue _filterconditions[][])
{
XColumnsSupplier columnSup = UnoRuntime.queryInterface(XColumnsSupplier.class, m_xQueryAnalyzer);
XNameAccess columns = columnSup.getColumns();
for (int n = 0; n < _filterconditions.length; n++)
{
for (int m = 0; m < _filterconditions[n].length; m++)
{
// _filterconditions[n][m].Name = getComposedAliasFieldName(_filterconditions[n][m].Name);
final String aliasName = getComposedAliasFieldName(_filterconditions[n][m].Name);
if ( columns.hasByName(aliasName))
_filterconditions[n][m].Name = aliasName;
}
}
return _filterconditions;
}
public String getQuery()
{
return m_xQueryAnalyzer.getQuery();
}
public StringBuilder getFromClause()
{
StringBuilder sFromClause = new StringBuilder("FROM");
composedCommandNames.clear();
String[] sCommandNames = CurDBMetaData.getIncludedCommandNames();
for (int i = 0; i < sCommandNames.length; i++)
{
CommandName curCommandName = new CommandName(CurDBMetaData, sCommandNames[i]); //(setComposedCommandName)
curCommandName.setAliasName(getuniqueAliasName(curCommandName.getTableName()));
sFromClause.append(" ").append(curCommandName.getComposedName()).append(" ").append(quoteName(curCommandName.getAliasName()));
if (i < sCommandNames.length - 1)
{
sFromClause.append(", ");
}
// fill composedCommandNames
composedCommandNames.add(curCommandName);
}
return sFromClause;
}
public boolean setQueryCommand(XWindow _xParentWindow, boolean _bincludeGrouping, boolean _baddAliasFieldNames)
{
return setQueryCommand(_xParentWindow, _bincludeGrouping, _baddAliasFieldNames, true);
}
public boolean setQueryCommand(XWindow _xParentWindow, boolean _bincludeGrouping, boolean _baddAliasFieldNames, boolean addQuery)
{
try
{
bincludeGrouping = _bincludeGrouping;
if (addQuery)
{
StringBuilder fromClause = getFromClause();
String sSelectClause = getSelectClause(_baddAliasFieldNames);
StringBuilder queryclause = new StringBuilder(sSelectClause).append(" ").append(fromClause);
m_xQueryAnalyzer.setQuery(queryclause.toString());
if (CurDBMetaData.getFilterConditions() != null && CurDBMetaData.getFilterConditions().length > 0)
{
CurDBMetaData.setFilterConditions(replaceConditionsByAlias(CurDBMetaData.getFilterConditions()));
m_queryComposer.setStructuredFilter(CurDBMetaData.getFilterConditions());
}
}
if (_bincludeGrouping)
{
appendGroupByColumns(_baddAliasFieldNames);
if (CurDBMetaData.GroupByFilterConditions.length > 0)
{
m_queryComposer.setStructuredHavingClause(CurDBMetaData.GroupByFilterConditions);
}
}
appendSortingcriteria(_baddAliasFieldNames);
return true;
}
catch (Exception exception)
{
exception.printStackTrace(System.out);
displaySQLErrorDialog(exception, _xParentWindow);
return false;
}
}
private String getComposedAliasFieldName(String _fieldname)
{
FieldColumn CurFieldColumn = CurDBMetaData.getFieldColumnByDisplayName(_fieldname);
CommandName curComposedCommandName = getComposedCommandByDisplayName(CurFieldColumn.getCommandName());
if (curComposedCommandName == null)
{
return _fieldname;
}
String curAliasName = curComposedCommandName.getAliasName();
return quoteName(curAliasName) + "." + quoteName(CurFieldColumn.getFieldName());
}
private CommandName getComposedCommandByAliasName(String _AliasName)
{
if (composedCommandNames != null)
{
for (CommandName commandName : composedCommandNames)
{
if (commandName.getAliasName().equals(_AliasName))
{
return commandName;
}
}
}
return null;
}
public CommandName getComposedCommandByDisplayName(String _DisplayName)
{
if (composedCommandNames != null)
{
for (CommandName commandName : composedCommandNames)
{
if (commandName.getDisplayName().equals(_DisplayName))
{
return commandName;
}
}
}
return null;
}
public String getuniqueAliasName(String _TableName)
{
int a = 0;
String AliasName = "";
boolean bAliasNameexists = true;
String locAliasName = _TableName;
while (bAliasNameexists)
{
bAliasNameexists = (getComposedCommandByAliasName(locAliasName) != null);
if (bAliasNameexists)
{
a++;
locAliasName = _TableName + "_" + String.valueOf(a);
}
else
{
AliasName = locAliasName;
}
}
return AliasName;
}
private String quoteName(String _sname)
{
return CommandName.quoteName(_sname, CurDBMetaData.getIdentifierQuote());
}
public void displaySQLErrorDialog(Exception _exception, XWindow _xParentWindow)
{
try
{
Object oErrorDialog = CurDBMetaData.xMSF.createInstance("com.sun.star.sdb.ErrorMessageDialog");
XInitialization xInitialize = UnoRuntime.queryInterface(XInitialization.class, oErrorDialog);
XExecutableDialog xExecute = UnoRuntime.queryInterface(XExecutableDialog.class, oErrorDialog);
PropertyValue[] rDispatchArguments = new PropertyValue[3];
rDispatchArguments[0] = Properties.createProperty(PropertyNames.PROPERTY_TITLE, Configuration.getProductName(CurDBMetaData.xMSF) + " Base");
rDispatchArguments[1] = Properties.createProperty("ParentWindow", _xParentWindow);
rDispatchArguments[2] = Properties.createProperty("SQLException", _exception);
xInitialize.initialize(rDispatchArguments);
xExecute.execute();
//TODO dispose???
}
catch (Exception typeexception)
{
typeexception.printStackTrace(System.out);
}
}
/**
* retrieves a normalized structured filter
*
* <p>XSingleSelectQueryComposer.getStructuredFilter has a strange habit of returning the predicate (equal, not equal, etc)
* effectively twice: Once as SQLFilterOperator, and once in the value. That is, if you have a term "column <> 3", then
* you'll get an SQLFilterOperator.NOT_EQUAL (which is fine), <strong>and</strong> the textual value of the condition
* will read "<> 3". The latter is strange enough, but even more strange is that this behavior is not even consistent:
* for SQLFilterOperator.EQUAL, the "=" sign is not include in the textual value.</p>
*
* <p>To abstract from this weirdness, use this function here, which strips the unwanted tokens from the textual value
* representation.</p>
*/
public PropertyValue[][] getNormalizedStructuredFilter()
{
final PropertyValue[][] structuredFilter = m_queryComposer.getStructuredFilter();
for (int i = 0; i < structuredFilter.length; ++i)
{
for (int j = 0; j < structuredFilter[i].length; ++j)
{
if (!(structuredFilter[i][j].Value instanceof String))
{
continue;
}
final StringBuffer textualValue = new StringBuffer((String) structuredFilter[i][j].Value);
switch (structuredFilter[i][j].Handle)
{
case SQLFilterOperator.EQUAL:
break;
case SQLFilterOperator.NOT_EQUAL:
case SQLFilterOperator.LESS_EQUAL:
case SQLFilterOperator.GREATER_EQUAL:
textualValue.delete(0, 2);
break;
case SQLFilterOperator.LESS:
case SQLFilterOperator.GREATER:
textualValue.delete(0, 1);
break;
case SQLFilterOperator.NOT_LIKE:
textualValue.delete(0, 8);
break;
case SQLFilterOperator.LIKE:
textualValue.delete(0, 4);
break;
case SQLFilterOperator.SQLNULL:
textualValue.delete(0, 7);
break;
case SQLFilterOperator.NOT_SQLNULL:
textualValue.delete(0, 11);
break;
}
structuredFilter[i][j].Value = textualValue.toString().trim();
}
}
return structuredFilter;
}
public XSingleSelectQueryComposer getQueryComposer()
{
return m_queryComposer;
}
} |
package netspy.components.gui.components.frame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Collections;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import netspy.components.config.ConfigPropertiesManager;
import netspy.components.filehandling.manager.FileManager;
import netspy.components.gui.components.frame.components.Logbox;
import netspy.components.gui.components.listeners.BlacklistActionListener;
import netspy.components.gui.components.listeners.NetSpyActionListener;
import netspy.components.gui.components.listeners.NetSpyListSelectionListener;
/**
* The Class MyJFrame.
*/
public class NetSpyFrame extends JFrame {
/** The Constant FRAME_INSETS. */
private static final Insets GBC_INSETS = new Insets(5, 5, 5, 5);
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -2357381332647405895L;
/** The Constant APPLICATION_TITLE. */
private static final String APPLICATION_TITLE = "NetSpy 2";
/** The Constant INPUT_ID_LOG_PATH. */
private static final String INPUT_ID_LOG_PATH = "input_log_path";
/** The Constant INPUT_ID_MAIL_PATH. */
private static final String INPUT_ID_MAIL_PATH = "input_mail_path";
/** The Constant INPUT_ID_BLACKWORD_PATH. */
private static final String INPUT_ID_BLACKWORD_PATH = "input_blackword_path";
/** The Constant INPUT_ID_QUARANTINE_PATH. */
private static final String INPUT_ID_QUARANTINE_PATH = "input_quarantine_path";
/** The Constant LABEL_QUARANTAENE_PATH. */
private static final String LABEL_QUARANTAENE_PATH = "Quarantäne-Verzeichnis:";
/** The Constant LABEL_LOG_PATH. */
private static final String LABEL_LOG_PATH = "Log-Verzeichnis:";
/** The Constant LABEL_BLACKWORD_PATH. */
private static final String LABEL_BLACKWORD_PATH = "Blackword-Datei:";
/** The Constant LABEL_MAIL_PATH. */
private static final String LABEL_MAIL_PATH = "Mail-Verzeichnis:";
/** The Constant BUTTON_LABEL_CLEAR_LOGBOX. */
private static final String BUTTON_LABEL_CLEAR_LOGBOX = "Log leeren";
/** The Constant BUTTON_LABEL_START_SCAN. */
private static final String BUTTON_LABEL_START_SCAN = "Starte Scan";
/** The Constant BUTTON_LABEL_SHOW_LOG. */
private static final String BUTTON_LABEL_SHOW_LOG = "Öffne Logdatei";
/** The Constant BUTTON_LABEL_SEARCH_FILE. */
private static final String BUTTON_LABEL_SEARCH_FILE = "Durchsuchen";
/** The Constant BUTTON_LABEL_BLACKWORD_ADD. */
private static final String BUTTON_LABEL_BLACKWORD_ADD = "Hinzufügen";
/** The Constant BUTTON_LABEL_BLACKWORD_ADD. */
private static final String BUTTON_LABEL_BLACKWORD_DELETE = "Löschen";
/** The Constant BUTTON_LABEL_BLACKWORD_DELETE_ALL. */
private static final String BUTTON_LABEL_BLACKWORD_DELETE_ALL = "Alle löschen";
/** The Constant BUTTON_LABEL_BLACKWORD_ADD. */
private static final String BUTTON_LABEL_BLACKWORD_EDIT = "Ändern";
/** The Constant BUTTON_ID_MAIL_PATH. */
public static final String BUTTON_ID_MAIL_PATH = "button_mail_path";
/** The Constant BUTTON_ID_BLACKWORD_ADD . */
public static final String BUTTON_ID_BLACKWORD_ADD = "button_blackword_add";
/** The Constant BUTTON_ID_BLACKWORD_DELETE . */
public static final String BUTTON_ID_BLACKWORD_DELETE = "button_blackword_delete";
/** The Constant BUTTON_ID_BLACKWORD_DELETE_ALL. */
public static final String BUTTON_ID_BLACKWORD_DELETE_ALL = "button_blackword_delete_all";
/** The Constant BUTTON_ID_BLACKWORD_DELETE . */
public static final String BUTTON_ID_BLACKWORD_EDIT = "button_blackword_edit";
/** The Constant BUTTON_ID_BLACKWORD_PATH. */
public static final String BUTTON_ID_BLACKWORD_PATH = "button_blackword_path";
/** The Constant BUTTON_ID_QUARANTINE_PATH. */
public static final String BUTTON_ID_QUARANTINE_PATH = "button_quarantine_path";
/** The Constant BUTTON_ID_LOG_PATH. */
public static final String BUTTON_ID_LOG_PATH = "button_log_path";
/** The Constant BUTTON_ID_START_SCAN. */
public static final String BUTTON_ID_START_SCAN = "button_start_scan";
/** The Constant BUTTON_ID_SHOW_LOG. */
public static final String BUTTON_ID_SHOW_LOG = "button_show_log";
/** The Constant BUTTON_ID_TOGGLE_LOG_BOX. */
public static final String BUTTON_ID_TOGGLE_LOGBOX = "toggle_logbox";
/** The Constant BUTTON_ID_CLEAR_LOGBOX. */
public static final String BUTTON_ID_CLEAR_LOGBOX = "clear_logbox";
/** The Constant DIMENSION_TEXTFIELD_SIZE. */
private static final Dimension DIMENSION_TEXTFIELD_SIZE = new Dimension(250, 25);
/** The Constant DIMENSION_LABEL_SIZE. */
private static final Dimension DIMENSION_LABEL_SIZE = new Dimension(50, 25);
/** The Constant DIMENSION_BUTTON_SIZE. */
private static final Dimension DIMENSION_BUTTON_SIZE = new Dimension(120, 25);
/** The dlm action listener. */
private BlacklistActionListener dlmActionListener;
/** The action listener. */
private NetSpyActionListener actionListener = new NetSpyActionListener(this);
/** The list selection listener. */
private NetSpyListSelectionListener listSelectionListener = new NetSpyListSelectionListener(this);
/** The Input mail path. */
private JTextField inputMailPath;
/** The Input blackword path. */
private JTextField inputBlackwordPath;
/** The Input quarantine path. */
private JTextField inputQuarantinePath;
/** The Input log path. */
private JTextField inputLogPath;
/** The log box. */
private Logbox logbox = new Logbox();
/** The main panel. */
private JPanel mainPanel = new JPanel();
/** The empty row. */
private JPanel emptyRow = new JPanel();
/** The gbc. */
private GridBagConstraints gbc = new GridBagConstraints();
/** The prop conf. */
private ConfigPropertiesManager propConf;
/** The blacklist scroll pane. */
private JScrollPane blacklistScrollPane;
/** The btn add black word. */
private JButton btnAddBlackWord;
/** The btn edit black word. */
private JButton btnEditBlackWord;
/** The btn delete black word. */
private JButton btnDeleteBlackword;
/** The btn delete all blackwords. */
private JButton btnDeleteAllBlackwords;
/** The blackword list. */
private JList<String> blackwordList;
/** The dlm black word. */
private DefaultListModel<String> dlmBlackWord;
/** The btn show log. */
private JButton btnShowLog;
/**
* Instantiates a new my j frame.
*/
public NetSpyFrame() {
super();
initConf();
initialize();
}
/**
* Inits the conf.
*/
private void initConf() {
propConf = new ConfigPropertiesManager(logbox);
propConf.init();
}
/**
* Initialize.
*/
private void initialize() {
// general configuration of frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(APPLICATION_TITLE);
setResizable(false);
// Application Icon
ImageIcon appIcon = new ImageIcon(System.getProperty("user.dir") + "/resources/img/system_search.png");
setIconImage(appIcon.getImage());
// Layout
mainPanel.setLayout(new GridBagLayout());
gbc.insets = GBC_INSETS;
// Background color
mainPanel.setBackground(Color.WHITE);
// create content
setTitlePanel();
setFormLayout();
setBlackWordBox();
setInfoBox();
add(mainPanel);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
/**
* Sets the title panel.
*/
private void setTitlePanel() {
// y = 0, x = 0-16, centered
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 17;
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.HORIZONTAL;
final JPanel titlePanel = new JPanel();
titlePanel.setBackground(Color.WHITE);
titlePanel.add(new JLabel(APPLICATION_TITLE));
mainPanel.add(titlePanel, gbc);
gbc.fill = GridBagConstraints.NONE;
}
/**
* Sets the form layout.
*/
private void setFormLayout() {
// MAIL PATH
// LABEL
// y = 1, x = 0-1, fill none
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 2;
gbc.anchor = GridBagConstraints.LINE_START;
final JLabel labelMailPath = new JLabel(LABEL_MAIL_PATH);
labelMailPath.setSize(DIMENSION_LABEL_SIZE);
mainPanel.add(labelMailPath, gbc);
// INPUT
// y = 1, x = 2-5, fill horizontal
gbc.gridx = 2;
gbc.gridy = 1;
gbc.gridwidth = 4;
inputMailPath = new JTextField();
inputMailPath.setText(propConf.getInboxPath());
inputMailPath.setPreferredSize(DIMENSION_TEXTFIELD_SIZE);
inputMailPath.setEditable(false);
inputMailPath.setName(INPUT_ID_MAIL_PATH);
inputMailPath.setToolTipText("Wähle eine konkrete .eml-Datei oder ein\n"
+ " Verzeichnis, in dem alle .eml-Dateien durchsucht werden sollen.");
mainPanel.add(inputMailPath, gbc);
// BUTTON FOR CHOOSER
// y = 1, x = 6-7, fill horizontal
gbc.gridx = 6;
gbc.gridy = 1;
gbc.gridwidth = 2;
final JButton btnOpenMailPathChooser = new JButton(BUTTON_LABEL_SEARCH_FILE);
btnOpenMailPathChooser.setName(BUTTON_ID_MAIL_PATH);
btnOpenMailPathChooser.addActionListener(actionListener);
btnOpenMailPathChooser.setPreferredSize(DIMENSION_BUTTON_SIZE);
mainPanel.add(btnOpenMailPathChooser, gbc);
// BLACKWORD PATH
// LABEL
// y = 2, x = 0-1, fill none
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
final JLabel lblBlackword = new JLabel(LABEL_BLACKWORD_PATH);
lblBlackword.setSize(DIMENSION_LABEL_SIZE);
mainPanel.add(lblBlackword, gbc);
// INPUT
// y = 2, x = 2-5, fill horizontal
gbc.gridx = 2;
gbc.gridy = 2;
gbc.gridwidth = 4;
inputBlackwordPath = new JTextField();
inputBlackwordPath.setText(propConf.getBlackwordPath());
inputBlackwordPath.setPreferredSize(DIMENSION_TEXTFIELD_SIZE);
inputBlackwordPath.setEditable(false);
inputBlackwordPath.setName(INPUT_ID_BLACKWORD_PATH);
inputBlackwordPath.setToolTipText("Wähle die blacklist.txt-Datei aus, anhand "
+ "welcher die Emails überprüft werden sollen.");
mainPanel.add(inputBlackwordPath, gbc);
// BUTTON FOR CHOOSER
// y = 2, x = 6-7, fill horizontal
gbc.gridx = 6;
gbc.gridy = 2;
gbc.gridwidth = 2;
final JButton btnOpenBlackwordPathChooser = new JButton((BUTTON_LABEL_SEARCH_FILE));
btnOpenBlackwordPathChooser.setName(BUTTON_ID_BLACKWORD_PATH);
btnOpenBlackwordPathChooser.addActionListener(actionListener);
btnOpenBlackwordPathChooser.setPreferredSize(DIMENSION_BUTTON_SIZE);
mainPanel.add(btnOpenBlackwordPathChooser, gbc);
// LOG PATH
// LABEL
// y = 3, x = 0-1, fill none
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
final JLabel lblLogPath = new JLabel(LABEL_LOG_PATH);
lblLogPath.setSize(DIMENSION_LABEL_SIZE);
mainPanel.add(lblLogPath, gbc);
// INPUT
// y = 3, x = 2-5, fill horizontal
gbc.gridx = 2;
gbc.gridy = 3;
gbc.gridwidth = 4;
inputLogPath = new JTextField();
inputLogPath.setText(propConf.getLogPath());
inputLogPath.setEditable(false);
inputLogPath.setName(INPUT_ID_LOG_PATH);
inputLogPath.setPreferredSize(DIMENSION_TEXTFIELD_SIZE);
inputLogPath.setToolTipText("Wähle das Log-Verzeichnis aus. "
+ "Dort werden die Informationen über verdächtige Emails gespeichert.");
mainPanel.add(inputLogPath, gbc);
// BUTTON FOR CHOOSER
// y = 3, x = 6-7, fill horizontal
gbc.gridx = 6;
gbc.gridy = 3;
gbc.gridwidth = 2;
final JButton btnOpenLogPathChooser = new JButton(BUTTON_LABEL_SEARCH_FILE);
btnOpenLogPathChooser.setName(BUTTON_ID_LOG_PATH);
btnOpenLogPathChooser.addActionListener(actionListener);
btnOpenLogPathChooser.setPreferredSize(DIMENSION_BUTTON_SIZE);
mainPanel.add(btnOpenLogPathChooser, gbc);
// QUARANTINE PATH
// LABEL
// y = 4, x = 0-1, fill none
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 2;
gbc.anchor = GridBagConstraints.BASELINE;
final JLabel lblQuarantine = new JLabel(LABEL_QUARANTAENE_PATH);
lblQuarantine.setSize(DIMENSION_LABEL_SIZE);
mainPanel.add(lblQuarantine, gbc);
// INPUT
// y = 4, x = 2-5, fill horizontal
gbc.gridx = 2;
gbc.gridy = 4;
gbc.gridwidth = 4;
inputQuarantinePath = new JTextField();
inputQuarantinePath.setText(propConf.getQuarantinePath());
inputQuarantinePath.setEditable(false);
inputQuarantinePath.setName(INPUT_ID_QUARANTINE_PATH);
inputQuarantinePath.setPreferredSize(DIMENSION_TEXTFIELD_SIZE);
inputQuarantinePath.setToolTipText("Wähle das Quarantäne-Verzeichnis aus, "
+ "in welches die verdächtigen Emails gespeichert werden.");
mainPanel.add(inputQuarantinePath, gbc);
// BUTTON FOR CHOOSER
// y = 4, x = 6-7, fill horizontal
gbc.gridx = 6;
gbc.gridy = 4;
gbc.gridwidth = 2;
final JButton btnOpenQuarantinePathChooser = new JButton((BUTTON_LABEL_SEARCH_FILE));
btnOpenQuarantinePathChooser.setName(BUTTON_ID_QUARANTINE_PATH);
btnOpenQuarantinePathChooser.addActionListener(actionListener);
btnOpenQuarantinePathChooser.setPreferredSize(DIMENSION_BUTTON_SIZE);
mainPanel.add(btnOpenQuarantinePathChooser, gbc);
// EMPTY ROW
// let row with index 5 empty: workaround
// y = 5, x = 0-9, fill none
gbc.gridy = 5;
gbc.gridx = 0;
gbc.gridwidth = 10;
gbc.fill = GridBagConstraints.HORIZONTAL;
emptyRow = new JPanel();
emptyRow.setSize(new Dimension(0, 10));
emptyRow.setBackground(Color.WHITE);
mainPanel.add(emptyRow, gbc);
// BUTTON CLEAR LOGBOX
// y = 6, x = 0-1, fill horizontal
gbc.gridx = 0;
gbc.gridy = 6;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
final JButton btnClearLogBox = new JButton(BUTTON_LABEL_CLEAR_LOGBOX);
btnClearLogBox.setName(BUTTON_ID_CLEAR_LOGBOX);
btnClearLogBox.setPreferredSize(DIMENSION_BUTTON_SIZE);
btnClearLogBox.addActionListener(actionListener);
mainPanel.add(btnClearLogBox, gbc);
// y = 6, x = 2-5, free space
// BUTTON START SCAN
// y = 6, x = 6-7, fill horizontal
gbc.gridx = 6;
gbc.gridy = 6;
gbc.gridwidth = 2;
gbc.anchor = GridBagConstraints.EAST;
final JButton btnStartScan = new JButton(BUTTON_LABEL_START_SCAN);
btnStartScan.setName(BUTTON_ID_START_SCAN);
btnStartScan.addActionListener(actionListener);
btnStartScan.setPreferredSize(DIMENSION_BUTTON_SIZE);
mainPanel.add(btnStartScan, gbc);
// BUTTON SHOW LOG
// y = 6, x = 8-9, fill none
gbc.gridx = 8;
gbc.gridy = 6;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
btnShowLog = new JButton(BUTTON_LABEL_SHOW_LOG);
btnShowLog.setName(BUTTON_ID_SHOW_LOG);
btnShowLog.setPreferredSize(DIMENSION_BUTTON_SIZE);
btnShowLog.addActionListener(actionListener);
btnShowLog.setToolTipText("Sofern eine Logdatei von dem aktuellen Tag existiert,"
+ " wird diese mit Ihrem Standard-Text-Editor geöffnet.");
mainPanel.add(btnShowLog, gbc);
}
/**
* Sets the info box.
*/
private void setInfoBox() {
// y = 7-12, x = 0-11, fill both
gbc.gridx = 0;
gbc.gridy = 7;
gbc.gridwidth = 12;
gbc.gridheight = 6;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.CENTER;
final JScrollPane infoBoxScrollable = new JScrollPane(logbox);
infoBoxScrollable.setPreferredSize(new Dimension(0, 150));
infoBoxScrollable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
infoBoxScrollable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
mainPanel.add(infoBoxScrollable, gbc);
}
/**
* Sets the black word box.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private void setBlackWordBox(){
// DEFAULT LIST MODEL
dlmBlackWord = new DefaultListModel<String>();
blackwordList = new JList(dlmBlackWord);
blackwordList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
loadBlackwordBox(dlmBlackWord);
// y = 1-4, x = 10-11, fill none
gbc.gridx = 10;
gbc.gridy = 1;
gbc.gridwidth = 2;
gbc.gridheight = 6;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.NORTHWEST;
blackwordList.setBackground(Color.WHITE);
blacklistScrollPane = new JScrollPane(blackwordList);
blacklistScrollPane.setPreferredSize(new Dimension(150, 187));
blacklistScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
blacklistScrollPane.setViewportView(blackwordList);
// initialize action listener for default list model
dlmActionListener = new BlacklistActionListener(blackwordList, dlmBlackWord, logbox);
mainPanel.add(blacklistScrollPane, gbc);
// BUTTON ADD BLACKWORD
// y = 2, x = 8-9, fill horizontal
gbc.gridx = 8;
gbc.gridy = 1;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.BASELINE;
btnAddBlackWord = new JButton(BUTTON_LABEL_BLACKWORD_ADD);
btnAddBlackWord.setName(BUTTON_ID_BLACKWORD_ADD);
btnAddBlackWord.addActionListener(dlmActionListener);
btnAddBlackWord.setPreferredSize(DIMENSION_BUTTON_SIZE);
mainPanel.add(btnAddBlackWord, gbc);
// BUTTON EDIT BLACKWORD
// y = 2, x = 8-9, fill horizontal
gbc.gridx = 8;
gbc.gridy = 2;
gbc.gridwidth = 2;
btnEditBlackWord = new JButton(BUTTON_LABEL_BLACKWORD_EDIT);
btnEditBlackWord.setName(BUTTON_ID_BLACKWORD_EDIT);
btnEditBlackWord.addActionListener(dlmActionListener);
btnEditBlackWord.setPreferredSize(DIMENSION_BUTTON_SIZE);
mainPanel.add(btnEditBlackWord, gbc);
// BUTTON DELETE BLACKWORD
// y = 3, x = 8-9, fill horizontal
gbc.gridx = 8;
gbc.gridy = 3;
gbc.gridwidth = 2;
btnDeleteBlackword = new JButton(BUTTON_LABEL_BLACKWORD_DELETE);
btnDeleteBlackword.setName(BUTTON_ID_BLACKWORD_DELETE);
btnDeleteBlackword.addActionListener(dlmActionListener);
btnDeleteBlackword.setPreferredSize(DIMENSION_BUTTON_SIZE);
mainPanel.add(btnDeleteBlackword, gbc);
// BUTTON DELETE ALL BLACKWORDS
// y = 4, x = 8-9, fill horizontal
gbc.gridx = 8;
gbc.gridy = 4;
gbc.gridwidth = 2;
btnDeleteAllBlackwords = new JButton(BUTTON_LABEL_BLACKWORD_DELETE_ALL);
btnDeleteAllBlackwords.setName(BUTTON_ID_BLACKWORD_DELETE_ALL);
btnDeleteAllBlackwords.addActionListener(dlmActionListener);
btnDeleteAllBlackwords.setPreferredSize(DIMENSION_BUTTON_SIZE);
mainPanel.add(btnDeleteAllBlackwords, gbc);
// add list selection listener to JList and select first entry
blackwordList.addListSelectionListener(listSelectionListener);
if (dlmBlackWord.size() > 0) {
blackwordList.setSelectedIndex(0);
} else {
btnEditBlackWord.setEnabled(false);
btnDeleteBlackword.setEnabled(false);
btnDeleteAllBlackwords.setEnabled(false);
}
}
/**
* Fill black word box.
*
* @param dlm the dlm_ black word
* @return the array list
*/
private void loadBlackwordBox(DefaultListModel<String> dlm) {
List<String> blacklist = new FileManager().getBlacklist();
if (blacklist != null) {
Collections.sort(blacklist, String.CASE_INSENSITIVE_ORDER);
for(String blackword: blacklist){
dlm.addElement(blackword.toLowerCase());
}
}
}
/**
* Gets the input mail path.
*
* @return the input mail path
*/
public JTextField getInputMailPath() {
return inputMailPath;
}
/**
* Gets the input blackword path.
*
* @return the input blackword path
*/
public JTextField getInputBlackwordPath() {
return inputBlackwordPath;
}
/**
* Gets the input log path.
*
* @return the input log path
*/
public JTextField getInputLogPath() {
return inputLogPath;
}
/**
* Gets the input quarantine path.
*
* @return the input quarantine path
*/
public JTextField getInputQuarantinePath() {
return inputQuarantinePath;
}
/**
* Gets the log box.
*
* @return the log box
*/
public Logbox getLogBox() {
return logbox;
}
/**
* Gets the btn delete black word.
*
* @return the btn delete black word
*/
public JButton getBtnDeleteBlackWord() {
return btnDeleteBlackword;
}
/**
* Gets the btn edit black word.
*
* @return the btn edit black word
*/
public JButton getBtnEditBlackWord() {
return btnEditBlackWord;
}
/**
* Gets the btn delete all blackwords.
*
* @return the btn delete all blackwords
*/
public JButton getBtnDeleteAllBlackwords() {
return btnDeleteAllBlackwords;
}
/**
* Gets the dlm black word.
*
* @return the dlm black word
*/
public DefaultListModel<String> getDlmBlackWord() {
return dlmBlackWord;
}
} |
package org.hyperic.sigar.jmx;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.ReflectionException;
import org.hyperic.sigar.Sigar;
public class ReflectedMBean extends AbstractMBean {
private Method method;
private Map methods;
private String type;
protected String getType() {
return this.type;
}
protected Class getMBeanClass() {
try {
return getMethod().getReturnType();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected ReflectedMBean(Sigar sigar, String type) {
super(sigar, CACHELESS);
this.type = type;
}
public String getObjectName() {
return
SigarInvokerJMX.DOMAIN_NAME + ":" +
MBEAN_ATTR_TYPE + "=" + getType();
}
protected Method getMethod() throws Exception {
if (this.method == null) {
String getName = "get" + getType();
Class[] params = getMethodParamTypes();
this.method =
this.sigarImpl.getClass().getDeclaredMethod(getName,
params);
}
return this.method;
}
protected Class[] getMethodParamTypes() {
return new Class[0];
}
private Object getReflectedAttribute(String name)
throws Exception {
Method method = getMethod();
Object obj =
method.invoke(this.sigarImpl,
getMethodParamTypes());
Method attr =
obj.getClass().getMethod("get" + name, new Class[0]);
return attr.invoke(obj, new Object[0]);
}
public Object getAttribute(String name)
throws AttributeNotFoundException,
MBeanException, ReflectionException {
try {
return getReflectedAttribute(name);
} catch (Exception e) {
throw new ReflectionException(e);
}
}
private Map getMethods() {
if (this.methods != null) {
return this.methods;
}
this.methods = new LinkedHashMap();
Method[] methods = getMBeanClass().getDeclaredMethods();
for (int i=0; i<methods.length; i++) {
String name = methods[i].getName();
if (!name.startsWith("get")) {
continue;
}
name = name.substring(3);
this.methods.put(name, methods[i]);
}
return this.methods;
}
protected MBeanAttributeInfo[] getAttributeInfo() {
Map methods = getMethods();
MBeanAttributeInfo[] attrs =
new MBeanAttributeInfo[methods.size()];
int i=0;
for (Iterator it=methods.entrySet().iterator();
it.hasNext();)
{
Map.Entry entry = (Map.Entry)it.next();
String name = (String)entry.getKey();
Method method = (Method)entry.getValue();
attrs[i++] =
new MBeanAttributeInfo(name,
method.getReturnType().getName(),
name + " MBean",
true, // isReadable
false, // isWritable
false); // isIs
}
return attrs;
}
public MBeanInfo getMBeanInfo() {
MBeanInfo info =
new MBeanInfo(getMBeanClass().getName(),
"",
getAttributeInfo(),
null, //constructors
null, //operations
null); //notifications
return info;
}
} |
package org.intermine.bio.ontology;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.collections.map.MultiValueMap;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.obo.dataadapter.OBOAdapter;
import org.obo.dataadapter.OBOFileAdapter;
import org.obo.dataadapter.OBOSerializationEngine;
import org.obo.dataadapter.SimpleLinkFileAdapter;
import org.obo.datamodel.OBOSession;
/**
* @author Thomas Riley
* @author Peter Mclaren - 5/6/05 - added some functionality to allow terms to find all their parent
* @author Xavier Watkins - 06/01/09 - refactored model
* terms.
*/
public class OboParser
{
private static final Logger LOG = Logger.getLogger(OboParser.class);
// private static File temp = null;
private final Pattern synPattern = Pattern.compile("\\s*\"(.+?[^\\\\])\".*");
private final Matcher synMatcher = synPattern.matcher("");
private Set<String> oboXrefs = new HashSet<String>();
private static final String PROP_FILE = "obo_xrefs.properties";
/**
* All terms.
*/
protected Map<String, OboTerm> terms = new HashMap<String, OboTerm>();
/**
* All relations
*/
protected List<OboRelation> relations = new ArrayList<OboRelation>();
/**
* All relation types
*/
protected Map<String, OboTypeDefinition> types = new HashMap<String, OboTypeDefinition>();
/**
* Default namespace.
*/
protected String defaultNS = "";
/**
* Parse an OBO file to produce a set of OboTerms.
* @param in with text in OBO format
* @throws Exception if anything goes wrong
*/
public void processOntology(Reader in) throws Exception {
readConfig();
readTerms(new BufferedReader(in));
}
/**
* Parses config file for valid prefixes, eg. FBbt FMA. Only valid xrefs will be processed,
* eg. FBbt:0000001
*/
protected void readConfig() {
Properties props = new Properties();
try {
props.load(getClass().getClassLoader().getResourceAsStream(PROP_FILE));
} catch (IOException e) {
throw new RuntimeException("Problem loading properties '" + PROP_FILE + "'", e);
}
Enumeration<?> propNames = props.propertyNames();
while (propNames.hasMoreElements()) {
String xref = (String) propNames.nextElement();
oboXrefs.add(xref);
}
}
/**
* Parse the relations file generated by the OboEdit reasoner (calculates transitivity)
*
* @param dagFileName the name of the obo file to read from
* @throws Exception if something goes wrong
*/
@SuppressWarnings("unchecked")
public void processRelations(String dagFileName) throws Exception {
File temp = null;
File f = new File("build");
if (!f.exists()) {
temp = File.createTempFile("obo", ".tmp");
} else {
temp = File.createTempFile("obo", ".tmp", f);
}
// Copied from OBO2Linkfile.convertFiles(OBOAdapterConfiguration, OBOAdapterConfiguration,
// List); OBOEDIT code
// TODO OBO will soon release the file containing all transitive closures calculated
// by obo2linkfile so we can get rid of the code below and just use the downloaded file.
long startTime = System.currentTimeMillis();
OBOFileAdapter.OBOAdapterConfiguration readConfig =
new OBOFileAdapter.OBOAdapterConfiguration();
readConfig.setBasicSave(false);
readConfig.getReadPaths().add(dagFileName);
OBOFileAdapter.OBOAdapterConfiguration writeConfig =
new OBOFileAdapter.OBOAdapterConfiguration();
writeConfig.setBasicSave(false);
OBOSerializationEngine.FilteredPath path = new OBOSerializationEngine.FilteredPath();
path.setUseSessionReasoner(false);
path.setImpliedType(OBOSerializationEngine.SAVE_ALL);
path.setPath(temp.getCanonicalPath());
writeConfig.getSaveRecords().add(path);
writeConfig.setSerializer("OBO_1_2");
OBOFileAdapter adapter = new OBOFileAdapter();
OBOSession session = adapter.doOperation(OBOAdapter.READ_ONTOLOGY, readConfig, null);
SimpleLinkFileAdapter writer = new SimpleLinkFileAdapter();
writer.doOperation(OBOAdapter.WRITE_ONTOLOGY, writeConfig, session);
LOG.info("PROGRESS:" + writer.getProgressString());
// END OF OBO2EDIT code
readRelations(new BufferedReader(new FileReader(temp.getCanonicalPath())));
temp.delete();
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Processed transitive closure of OBO file, took: " + timeTaken + " ms");
}
/**
* Parse an OBO file to produce a map from ontology term id to name.
*
* @param in text in OBO format
* @return a map from ontology term identifier to name
* @throws IOException if anything goes wrong
*/
public Map<String, String> getTermIdNameMap(Reader in)
throws IOException {
readTerms(new BufferedReader(in));
Map<String, String> idNames = new HashMap<String, String>();
for (OboTerm ot : terms.values()) {
idNames.put(ot.getId(), ot.getName());
}
return idNames;
}
/**
* @return a set of DagTerms
*/
public Set<OboTerm> getOboTerms() {
return new HashSet<OboTerm>(terms.values());
}
/**
* @return a list of OboRelations
*/
public List<OboRelation> getOboRelations() {
return relations;
}
/**
* Read DAG input line by line to generate hierarchy of DagTerms.
*
* @param in text in DAG format
* @throws IOException if anything goes wrong
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void readTerms(BufferedReader in) throws IOException {
String line;
Map<String, String> tagValues = new MultiValueMap();
List<Map> termTagValuesList = new ArrayList<Map>();
List<Map> typeTagValuesList = new ArrayList<Map>();
Pattern tagValuePattern = Pattern.compile("(.+?[^\\\\]):(.+)");
Pattern stanzaHeadPattern = Pattern.compile("\\s*\\[(.+)\\]\\s*");
Matcher tvMatcher = tagValuePattern.matcher("");
Matcher headMatcher = stanzaHeadPattern.matcher("");
while ((line = in.readLine()) != null) {
// First strip off any comments
if (line.indexOf('!') >= 0) {
line = line.substring(0, line.indexOf('!'));
}
tvMatcher.reset(line);
headMatcher.reset(line);
if (headMatcher.matches()) {
String stanzaType = headMatcher.group(1);
tagValues = new MultiValueMap(); // cut loose
if ("Term".equals(stanzaType)) {
termTagValuesList.add(tagValues);
LOG.debug("recorded term with " + tagValues.size() + " tag values");
} else
if ("Typedef".equals(stanzaType)) {
typeTagValuesList.add(tagValues);
LOG.debug("recorded type with " + tagValues.size() + " tag values");
} else {
LOG.warn("Ignoring " + stanzaType + " stanza");
}
LOG.debug("matched stanza " + stanzaType);
} else if (tvMatcher.matches()) {
String tag = tvMatcher.group(1).trim();
String value = tvMatcher.group(2).trim();
tagValues.put(tag, value);
LOG.debug("matched tag \"" + tag + "\" with value \"" + value + "\"");
if ("default-namespace".equals(tag)) {
defaultNS = value;
LOG.info("default-namespace is \"" + value + "\"");
}
}
}
in.close();
// Build the OboTypeDefinition objects
OboTypeDefinition oboType = new OboTypeDefinition("is_a", "is_a", true);
types.put(oboType.getId() , oboType);
for (Iterator<Map> iter = typeTagValuesList.iterator(); iter.hasNext();) {
Map<?, ?> tvs = iter.next();
String id = (String) ((List<?>) tvs.get("id")).get(0);
String name = "";
List<?> names = (List<?>) tvs.get("name");
if (names != null && !names.isEmpty()) {
name = (String) names.get(0);
} else {
//throw new BuildException("Ontology term did not have a name:" + id);
}
boolean isTransitive = isTrue(tvs, "is_transitive");
oboType = new OboTypeDefinition(id, name, isTransitive);
types.put(oboType.getId() , oboType);
}
// Just build all the OboTerms disconnected
for (Iterator<Map> iter = termTagValuesList.iterator(); iter.hasNext();) {
Map<?, ?> tvs = iter.next();
String id = (String) ((List<?>) tvs.get("id")).get(0);
String name;
List<?> names = (List<?>) tvs.get("name");
if (names != null && !names.isEmpty()) {
name = (String) names.get(0);
} else {
throw new BuildException("Ontology term did not have a name:" + id);
}
OboTerm term = new OboTerm(id, name);
term.setObsolete(isTrue(tvs, "is_obsolete"));
terms.put(term.getId(), term);
}
// Now connect them all together
for (Iterator<Map> iter = termTagValuesList.iterator(); iter.hasNext();) {
Map<?, ?> tvs = iter.next();
if (!isTrue(tvs, "is_obsolete")) {
configureDagTerm(tvs);
}
}
}
/**
* Configure dag terms with values from one entry.
*
* @param tagValues term config
*/
protected void configureDagTerm(Map<?, ?> tagValues) {
String id = (String) ((List<?>) tagValues.get("id")).get(0);
OboTerm term = terms.get(id);
if (term != null) {
term.setTagValues(tagValues);
List<?> synonyms = (List<?>) tagValues.get("synonym");
if (synonyms != null) {
addSynonyms(term, synonyms, "synonym");
}
synonyms = (List<?>) tagValues.get("related_synonym");
if (synonyms != null) {
addSynonyms(term, synonyms, "related_synonym");
}
synonyms = (List<?>) tagValues.get("exact_synonym");
if (synonyms != null) {
addSynonyms(term, synonyms, "exact_synonym");
}
synonyms = (List<?>) tagValues.get("broad_synonym");
if (synonyms != null) {
addSynonyms(term, synonyms, "broad_synonym");
}
synonyms = (List<?>) tagValues.get("narrow_synonym");
if (synonyms != null) {
addSynonyms(term, synonyms, "narrow_synonym");
}
List<?> altIds = (List<?>) tagValues.get("alt_id");
if (altIds != null) {
addSynonyms(term, altIds, "alt_id");
}
List<?> xrefs = (List<?>) tagValues.get("xref");
if (xrefs != null) {
addXrefs(term, xrefs);
}
// Set namespace
List<?> nsl = (List<?>) tagValues.get("namespace");
if (nsl != null && nsl.size() > 0) {
term.setNamespace((String) nsl.get(0));
} else {
term.setNamespace(defaultNS);
}
// Set description
List<?> defl = (List<?>) tagValues.get("def");
String def = null;
if (defl != null && defl.size() > 0) {
def = (String) defl.get(0);
synMatcher.reset(def);
if (synMatcher.matches()) {
term.setDescription(unescape(synMatcher.group(1)));
}
} else {
LOG.warn("Failed to parse def of term " + id + " def: " + def);
}
} else {
LOG.warn("OboParser.configureDagTerm() - no term found for id:" + id);
}
}
/**
* Given the tag+value map for a term, return whether it's true or false
*
* @param tagValues map of tag name to value for a single term
* @param tagValue the term to look for in the map
* @return true if the term is marked true, false if not
*/
public static boolean isTrue(Map<?, ?> tagValues, String tagValue) {
List<?> vals = (List<?>) tagValues.get(tagValue);
if (vals != null && vals.size() > 0) {
if (vals.size() > 1) {
LOG.warn("Term: " + tagValues + " has more than one (" + vals.size()
+ ") is_obsolete values - just using first");
}
return ((String) vals.get(0)).equalsIgnoreCase("true");
}
return false;
}
/**
* Add synonyms to a DagTerm.
*
* @param term the DagTerm
* @param synonyms List of synonyms (Strings)
* @param type synonym type
*/
protected void addSynonyms(OboTerm term, List<?> synonyms, String type) {
for (Iterator<?> iter = synonyms.iterator(); iter.hasNext();) {
String line = (String) iter.next();
synMatcher.reset(line);
if (synMatcher.matches()) {
term.addSynonym(new OboTermSynonym(unescape(synMatcher.group(1)), type));
} else if ("alt_id".equals(type)) {
term.addSynonym(new OboTermSynonym(line, type));
} else {
LOG.warn("Could not match synonym value from: " + line);
}
}
}
/**
* Add xrefs to a DagTerm.
* eg. xref: FBbt:00005137
* xref: FMA:5884
* xref: MA:0002406
*
* @param term the DagTerm
* @param xrefs List of xrefs (Strings)
*/
protected void addXrefs(OboTerm term, List<?> xrefs) {
for (Iterator<?> iter = xrefs.iterator(); iter.hasNext();) {
String identifier = (String) iter.next();
if (identifier.contains(":")) {
String[] bits = identifier.split(":");
String prefix = bits[0]; // eg FBbt
if (bits.length > 1 && prefix != null && oboXrefs.contains(prefix)) {
term.addXref(new OboTerm(identifier));
}
}
}
}
/**
* This method reads relations calculated by the GO2Link script in OBOEdit.
*
* @param in the reader for the Go2Link file
* @throws IOException an exception
*/
protected void readRelations(BufferedReader in) throws IOException {
String line;
while ((line = in.readLine()) != null) {
String[] bits = line.split("\t");
OboTypeDefinition type = types.get(bits[1].replaceAll("OBO_REL:", ""));
if (type != null) {
String id1 = null, id2 = null;
boolean asserted = false, redundant = false;
for (int i = 0; i < bits.length; i++) {
switch (i) {
case 0:// id1
{
id1 = bits[i];
break;
}
case 1:// type
{
// already initialised
break;
}
case 2:// id2
{
id2 = bits[i];
break;
}
case 3:// asserted
{
asserted = (bits[i]).matches("asserted");
break;
}
case 4:
{
// do nothing
break;
}
case 5:// redundant
{
redundant = (bits[i]).matches("redundant");
break;
}
default:
break;
}
}
OboRelation relation = new OboRelation(id1, id2, type);
relation.setDirect(asserted);
relation.setRedundant(redundant);
relations.add(relation);
} else {
LOG.info("Unsupported type:" + bits[1]);
}
}
in.close();
}
/**
* Perform OBO unescaping.
*
* @param string the escaped string
* @return the corresponding unescaped string
*/
protected String unescape(String string) {
int sz = string.length();
StringBuffer out = new StringBuffer(sz);
boolean hadSlash = false;
for (int i = 0; i < sz; i++) {
char ch = string.charAt(i);
if (hadSlash) {
switch (ch) {
case 'n':
out.append('\n');
break;
case 't':
out.append('\t');
break;
case 'W':
out.append(' ');
break;
default:
out.append(ch);
break;
}
hadSlash = false;
} else if (ch == '\\') {
hadSlash = true;
} else {
out.append(ch);
}
}
return out.toString();
}
} |
package nu.validator.xml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.cybozu.labs.langdetect.Detector;
import com.cybozu.labs.langdetect.DetectorFactory;
import com.cybozu.labs.langdetect.LangDetectException;
import com.cybozu.labs.langdetect.Language;
import com.ibm.icu.util.ULocale;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.LocatorImpl;
import org.apache.log4j.Logger;
public final class LanguageDetectingXMLReaderWrapper
implements XMLReader, ContentHandler {
private static final Logger log4j = Logger.getLogger(
LanguageDetectingXMLReaderWrapper.class);
private static final String languageList = "nu/validator/localentities/files/"
+ "language-profiles-list.txt";
private static final String profilesDir = "nu/validator/localentities/files/"
+ "language-profiles/";
private static List<String> profiles = new ArrayList<>();
private static List<String> languageTags = new ArrayList<>();
public static void initialize() throws LangDetectException {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
LanguageDetectingXMLReaderWrapper.class.getClassLoader().getResourceAsStream(
languageList)));
String languageTagAndName = br.readLine();
while (languageTagAndName != null) {
languageTags.add(languageTagAndName.split("\t")[0]);
languageTagAndName = br.readLine();
}
for (String languageTag : languageTags) {
profiles.add((new BufferedReader(new InputStreamReader(
LanguageDetectingXMLReaderWrapper.class.getClassLoader().getResourceAsStream(
profilesDir + languageTag)))).readLine());
}
DetectorFactory.clear();
DetectorFactory.loadProfile(profiles);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private final XMLReader wrappedReader;
private ContentHandler contentHandler;
private ErrorHandler errorHandler;
private HttpServletRequest request;
private String systemId;
private Locator locator = null;
private Locator htmlStartTagLocator;
private StringBuilder elementContent;
private StringBuilder documentContent;
private String httpContentLangHeader;
private String langAttrValue;
private boolean hasLang;
private String dirAttrValue;
private boolean hasDir;
private boolean inBody;
private boolean loggedStyleInBody;
private boolean collectingCharacters;
private int nonWhitespaceCharacterCount;
private static final int MAX_CHARS = 30720;
private static final int MIN_CHARS = 1024;
private static final double MIN_PROBABILITY = .90;
private static final String[] RTL_LANGS = { "ar", "azb", "ckb", "dv", "fa",
"he", "pnb", "ps", "sd", "ug", "ur" };
private static final String[] COMMON_LANGS = { "ar", "bg", "ca", "cs", "da",
"de", "el", "en", "es", "et", "fa", "fi", "fr", "he", "hi", "hu",
"id", "it", "ja", "ka", "ko", "lt", "lv", "ms", "nl", "no", "pl",
"pt", "ro", "ru", "sk", "sq", "sv", "th", "tr", "uk", "vi",
"zh-hans", "zh-hant" };
public LanguageDetectingXMLReaderWrapper(XMLReader wrappedReader,
HttpServletRequest request, ErrorHandler errorHandler,
String httpContentLangHeader, String systemId) {
this.wrappedReader = wrappedReader;
this.contentHandler = wrappedReader.getContentHandler();
this.errorHandler = errorHandler;
this.request = request;
this.systemId = systemId;
this.htmlStartTagLocator = null;
this.inBody = false;
this.loggedStyleInBody = false;
this.collectingCharacters = false;
this.nonWhitespaceCharacterCount = 0;
this.elementContent = new StringBuilder();
this.documentContent = new StringBuilder();
this.httpContentLangHeader = httpContentLangHeader;
this.hasLang = false;
this.langAttrValue = "";
this.hasDir = false;
this.dirAttrValue = "";
wrappedReader.setContentHandler(this);
}
/**
* @see org.xml.sax.helpers.XMLFilterImpl#characters(char[], int, int)
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (contentHandler == null) {
return;
}
if (collectingCharacters && nonWhitespaceCharacterCount < MAX_CHARS) {
for (int i = start; i < start + length; i++) {
switch (ch[i]) {
case ' ':
case '\t':
case '\r':
case '\n':
continue;
default:
nonWhitespaceCharacterCount++;
}
}
elementContent.append(ch, start, length);
}
contentHandler.characters(ch, start, length);
}
/**
* @see org.xml.sax.helpers.XMLFilterImpl#endElement(java.lang.String,
* java.lang.String, java.lang.String)
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (contentHandler == null) {
return;
}
if (nonWhitespaceCharacterCount < MAX_CHARS) {
documentContent.append(elementContent);
elementContent.setLength(0);
}
if ("body".equals(localName)) {
inBody = false;
collectingCharacters = false;
}
if (inBody && ("script".equals(localName) || "style".equals(localName)
|| "pre".equals(localName) || "a".equals(localName)
|| "td".equals(localName) || "select".equals(localName)
|| "ul".equals(localName) || "nav".equals(localName)
|| "form".equals(localName))) {
collectingCharacters = true;
}
contentHandler.endElement(uri, localName, qName);
}
/**
* @see org.xml.sax.helpers.XMLFilterImpl#startDocument()
*/
@Override
public void startDocument() throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.startDocument();
}
/**
* @see org.xml.sax.helpers.XMLFilterImpl#startElement(java.lang.String,
* java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if (contentHandler == null) {
return;
}
if ("html".equals(localName)) {
htmlStartTagLocator = new LocatorImpl(locator);
for (int i = 0; i < atts.getLength(); i++) {
if ("lang".equals(atts.getLocalName(i))) {
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/lang-found",
true);
}
hasLang = true;
langAttrValue = atts.getValue(i);
} else if ("dir".equals(atts.getLocalName(i))) {
hasDir = true;
dirAttrValue = atts.getValue(i);
}
}
} else if (inBody && "style".equals(localName) && !loggedStyleInBody) {
loggedStyleInBody = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/style-in-body-found",
true);
}
} else if ("body".equals(localName)) {
inBody = true;
collectingCharacters = true;
}
if ("script".equals(localName) || "style".equals(localName)
|| "pre".equals(localName) || "a".equals(localName)
|| "td".equals(localName) || "select".equals(localName)
|| "ul".equals(localName) || "nav".equals(localName)
|| "form".equals(localName)) {
collectingCharacters = false;
}
contentHandler.startElement(uri, localName, qName, atts);
}
/**
* @see org.xml.sax.helpers.XMLFilterImpl#setDocumentLocator(org.xml.sax.Locator)
*/
@Override
public void setDocumentLocator(Locator locator) {
if (contentHandler == null) {
return;
}
this.locator = locator;
contentHandler.setDocumentLocator(locator);
}
@Override
public ContentHandler getContentHandler() {
return contentHandler;
}
/**
* @throws SAXException
* @see org.xml.sax.ContentHandler#endDocument()
*/
@Override
public void endDocument() throws SAXException {
if (contentHandler == null) {
return;
}
detectLanguageAndCheckAgainstDeclaredLanguage();
contentHandler.endDocument();
}
private void detectLanguageAndCheckAgainstDeclaredLanguage()
throws SAXException {
try {
if (nonWhitespaceCharacterCount < MIN_CHARS) {
contentHandler.endDocument();
return;
}
if ("zxx".equals(new ULocale(langAttrValue).getLanguage())) {
return;
}
String textContent = documentContent.toString();
String detectedLanguage = "";
Detector detector = DetectorFactory.create();
detector.append(textContent);
detector.getProbabilities();
ArrayList<String> possibileLanguages = new ArrayList<>();
ArrayList<Language> possibilities = detector.getProbabilities();
for (Language possibility : possibilities) {
possibileLanguages.add(possibility.lang);
ULocale plocale = new ULocale(possibility.lang);
if (Arrays.binarySearch(COMMON_LANGS, possibility.lang) < 0
&& systemId != null) {
log4j.info(
String.format("%s %s %s", plocale.getDisplayName(),
possibility.prob, systemId));
}
if (possibility.prob > MIN_PROBABILITY) {
detectedLanguage = possibility.lang;
setDocumentLanguage(detectedLanguage);
} else if ((possibileLanguages.contains("hr")
&& (possibileLanguages.contains("sr-latn")
|| possibileLanguages.contains("bs")))
|| (possibileLanguages.contains("sr-latn")
&& (possibileLanguages.contains("hr")
|| possibileLanguages.contains("bs")))
|| (possibileLanguages.contains("bs")
&& (possibileLanguages.contains("hr")
|| possibileLanguages.contains(
"sr-latn")))) {
if (hasLang || systemId != null) {
detectedLanguage = getDetectedLanguageSerboCroatian();
setDocumentLanguage(detectedLanguage);
}
if ("sh".equals(detectedLanguage)) {
checkLangAttributeSerboCroatian();
return;
}
}
}
if ("".equals(detectedLanguage)) {
if (!hasLang && errorHandler != null) {
String message = "Consider adding a \u201Clang\u201D"
+ " attribute to the \u201Chtml\u201D"
+ " start tag to declare the language"
+ " of this document.";
SAXParseException spe = new SAXParseException(message,
htmlStartTagLocator);
errorHandler.warning(spe);
}
contentHandler.endDocument();
return;
}
String detectedLanguageName = "";
String preferredLanguageCode = "";
ULocale locale = new ULocale(detectedLanguage);
String detectedLanguageCode = locale.getLanguage();
if ("no".equals(detectedLanguage)) {
checkLangAttributeNorwegian();
checkContentLanguageHeaderNorwegian(detectedLanguage,
detectedLanguageName, detectedLanguageCode);
return;
}
if ("zh-hans".equals(detectedLanguage)) {
detectedLanguageName = "Simplified Chinese";
preferredLanguageCode = "zh-hans";
} else if ("zh-hant".equals(detectedLanguage)) {
detectedLanguageName = "Traditional Chinese";
preferredLanguageCode = "zh-hant";
} else if ("mhr".equals(detectedLanguage)) {
detectedLanguageName = "Meadow Mari";
preferredLanguageCode = "mhr";
} else if ("mrj".equals(detectedLanguage)) {
detectedLanguageName = "Hill Mari";
preferredLanguageCode = "mrj";
} else if ("nah".equals(detectedLanguage)) {
detectedLanguageName = "Nahuatl";
preferredLanguageCode = "nah";
} else if ("pnb".equals(detectedLanguage)) {
detectedLanguageName = "Western Panjabi";
preferredLanguageCode = "pnb";
} else if ("sr-cyrl".equals(detectedLanguage)) {
detectedLanguageName = "Serbian";
preferredLanguageCode = "sr";
} else if ("sr-latn".equals(detectedLanguage)) {
detectedLanguageName = "Serbian";
preferredLanguageCode = "sr";
} else if ("uz-cyrl".equals(detectedLanguage)) {
detectedLanguageName = "Uzbek";
preferredLanguageCode = "uz";
} else if ("uz-latn".equals(detectedLanguage)) {
detectedLanguageName = "Uzbek";
preferredLanguageCode = "uz";
} else if ("zxx".equals(detectedLanguage)) {
detectedLanguageName = "Lorem ipsum text";
preferredLanguageCode = "zxx";
} else {
detectedLanguageName = locale.getDisplayName();
preferredLanguageCode = detectedLanguageCode;
}
checkLangAttribute(detectedLanguage, detectedLanguageName,
detectedLanguageCode, preferredLanguageCode);
checkDirAttribute(detectedLanguage, detectedLanguageName,
detectedLanguageCode, preferredLanguageCode);
checkContentLanguageHeader(detectedLanguage, detectedLanguageName,
detectedLanguageCode, preferredLanguageCode);
} catch (LangDetectException e) {
}
}
private void setDocumentLanguage(String languageTag) {
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/document-language",
languageTag);
}
}
private String getDetectedLanguageSerboCroatian() throws SAXException {
String declaredLangCode = new ULocale(langAttrValue).getLanguage();
if ("hr".equals(declaredLangCode)
|| (systemId != null && systemId.endsWith(".hr"))) {
return "hr";
}
if ("sr".equals(declaredLangCode)
|| (systemId != null && systemId.endsWith(".rs"))) {
return "sr-latn";
}
if ("bs".equals(declaredLangCode)
|| (systemId != null && systemId.endsWith(".ba"))) {
return "bs";
}
return "sh";
}
private void checkLangAttributeSerboCroatian() throws SAXException {
String lowerCaseLang = langAttrValue.toLowerCase();
String declaredLangCode = new ULocale(langAttrValue).getLanguage();
String langWarning = "";
if (!hasLang) {
langWarning = "This document appears to be written in either"
+ " Croatian, Serbian, or Bosnian. Consider adding either"
+ " \u201Clang=\"hr\"\u201D, \u201Clang=\"sr\"\u201D, or"
+ " \u201Clang=\"bs\"\u201D to the"
+ " \u201Chtml\u201D start tag.";
} else if (!("hr".equals(declaredLangCode)
|| "sr".equals(declaredLangCode)
|| "bs".equals(declaredLangCode))) {
langWarning = String.format(
"This document appears to be written in either Croatian,"
+ " Serbian, or Bosnian, but the \u201Chtml\u201D"
+ " start tag has %s. Consider using either"
+ " \u201Clang=\"hr\"\u201D,"
+ " \u201Clang=\"sr\"\u201D, or"
+ " \u201Clang=\"bs\"\u201D instead.",
getAttValueExpr("lang", lowerCaseLang));
}
if (!"".equals(langWarning)) {
warn(langWarning);
}
}
private void checkLangAttributeNorwegian() throws SAXException {
String lowerCaseLang = langAttrValue.toLowerCase();
String declaredLangCode = new ULocale(langAttrValue).getLanguage();
String langWarning = "";
if (!hasLang) {
langWarning = "This document appears to be written in Norwegian"
+ " Consider adding either"
+ " \u201Clang=\"nn\"\u201D or \u201Clang=\"nb\"\u201D"
+ " (or variant) to the \u201Chtml\u201D start tag.";
} else if (!("no".equals(declaredLangCode)
|| "nn".equals(declaredLangCode)
|| "nb".equals(declaredLangCode))) {
langWarning = String.format(
"This document appears to be written in Norwegian, but the"
+ " \u201Chtml\u201D start tag has %s. Consider"
+ " using either \u201Clang=\"nn\"\u201D or"
+ " \u201Clang=\"nb\"\u201D (or variant) instead.",
getAttValueExpr("lang", lowerCaseLang));
}
if (!"".equals(langWarning)) {
warn(langWarning);
}
}
private void checkContentLanguageHeaderNorwegian(String detectedLanguage,
String detectedLanguageName, String detectedLanguageCode)
throws SAXException {
if ("".equals(httpContentLangHeader)
|| httpContentLangHeader.contains(",")) {
return;
}
String lowerCaseContentLang = httpContentLangHeader.toLowerCase();
String contentLangCode = new ULocale(
lowerCaseContentLang).getLanguage();
if (!("no".equals(contentLangCode) || "nn".equals(contentLangCode)
|| "nb".equals(contentLangCode))) {
warn("This document appears to be written in Norwegian but the"
+ " value of the HTTP \u201CContent-Language\u201D header"
+ " is \u201C" + lowerCaseContentLang + "\u201D. Consider"
+ " changing it to \u201Cnn\u201D or \u201Cnn\u201D"
+ " (or variant) instead.");
}
}
private void checkLangAttribute(String detectedLanguage,
String detectedLanguageName, String detectedLanguageCode,
String preferredLanguageCode) throws SAXException {
String langWarning = "";
String lowerCaseLang = langAttrValue.toLowerCase();
String declaredLangCode = new ULocale(langAttrValue).getLanguage();
if (!hasLang) {
langWarning = String.format(
"This document appears to be written in %s."
+ " Consider adding \u201Clang=\"%s\"\u201D"
+ " (or variant) to the \u201Chtml\u201D"
+ " start tag.",
detectedLanguageName, preferredLanguageCode);
} else {
if (request != null) {
if ("".equals(lowerCaseLang)) {
request.setAttribute(
"http://validator.nu/properties/lang-empty", true);
} else {
request.setAttribute(
"http://validator.nu/properties/lang-value",
lowerCaseLang);
}
}
if ("tl".equals(detectedLanguageCode)
&& ("ceb".equals(declaredLangCode)
|| "ilo".equals(declaredLangCode)
|| "pag".equals(declaredLangCode)
|| "war".equals(declaredLangCode))) {
return;
}
if ("id".equals(detectedLanguageCode)
&& "min".equals(declaredLangCode)) {
return;
}
if ("ms".equals(detectedLanguageCode)
&& "min".equals(declaredLangCode)) {
return;
}
if ("hr".equals(detectedLanguageCode)
&& ("sr".equals(declaredLangCode)
|| "bs".equals(declaredLangCode)
|| "sh".equals(declaredLangCode))) {
return;
}
if ("sr".equals(detectedLanguageCode)
&& ("hr".equals(declaredLangCode)
|| "bs".equals(declaredLangCode)
|| "sh".equals(declaredLangCode))) {
return;
}
if ("bs".equals(detectedLanguageCode)
&& ("hr".equals(declaredLangCode)
|| "sr".equals(declaredLangCode)
|| "sh".equals(declaredLangCode))) {
return;
}
if ("de".equals(detectedLanguageCode)
&& ("bar".equals(declaredLangCode)
|| "gsw".equals(declaredLangCode)
|| "lb".equals(declaredLangCode))) {
return;
}
if ("zh".equals(detectedLanguageCode)
&& "yue".equals(lowerCaseLang)) {
return;
}
if ("es".equals(detectedLanguageCode)
&& ("an".equals(declaredLangCode)
|| "ast".equals(declaredLangCode))) {
return;
}
if ("it".equals(detectedLanguageCode)
&& ("co".equals(declaredLangCode)
|| "pms".equals(declaredLangCode)
|| "vec".equals(declaredLangCode)
|| "lmo".equals(declaredLangCode)
|| "scn".equals(declaredLangCode)
|| "nap".equals(declaredLangCode))) {
return;
}
if ("rw".equals(detectedLanguageCode)
&& "rn".equals(declaredLangCode)) {
return;
}
if ("mhr".equals(detectedLanguageCode)
&& ("chm".equals(declaredLangCode)
|| "mrj".equals(declaredLangCode))) {
return;
}
if ("mrj".equals(detectedLanguageCode)
&& ("chm".equals(declaredLangCode)
|| "mhr".equals(declaredLangCode))) {
return;
}
String message = "This document appears to be written in %s"
+ " but the \u201Chtml\u201D start tag has %s. Consider"
+ " using \u201Clang=\"%s\"\u201D (or variant) instead.";
if (zhSubtagMismatch(detectedLanguage, lowerCaseLang)
|| !declaredLangCode.equals(detectedLanguageCode)) {
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/lang-wrong", true);
}
langWarning = String.format(message, detectedLanguageName,
getAttValueExpr("lang", langAttrValue),
preferredLanguageCode);
}
}
if (!"".equals(langWarning)) {
warn(langWarning);
}
}
private void checkContentLanguageHeader(String detectedLanguage,
String detectedLanguageName, String detectedLanguageCode,
String preferredLanguageCode) throws SAXException {
if ("".equals(httpContentLangHeader)
|| httpContentLangHeader.contains(",")) {
return;
}
String message = "";
String lowerCaseContentLang = httpContentLangHeader.toLowerCase();
String contentLangCode = new ULocale(
lowerCaseContentLang).getLanguage();
if ("tl".equals(detectedLanguageCode) && ("ceb".equals(contentLangCode)
|| "ilo".equals(contentLangCode)
|| "pag".equals(contentLangCode)
|| "war".equals(contentLangCode))) {
return;
}
if ("id".equals(detectedLanguageCode)
&& "min".equals(contentLangCode)) {
return;
}
if ("ms".equals(detectedLanguageCode)
&& "min".equals(contentLangCode)) {
return;
}
if ("hr".equals(detectedLanguageCode) && ("sr".equals(contentLangCode)
|| "bs".equals(contentLangCode)
|| "sh".equals(contentLangCode))) {
return;
}
if ("sr".equals(detectedLanguageCode) && ("hr".equals(contentLangCode)
|| "bs".equals(contentLangCode)
|| "sh".equals(contentLangCode))) {
return;
}
if ("bs".equals(detectedLanguageCode) && ("hr".equals(contentLangCode)
|| "sr".equals(contentLangCode)
|| "sh".equals(contentLangCode))) {
return;
}
if ("de".equals(detectedLanguageCode) && ("bar".equals(contentLangCode)
|| "gsw".equals(contentLangCode)
|| "lb".equals(contentLangCode))) {
return;
}
if ("zh".equals(detectedLanguageCode)
&& "yue".equals(lowerCaseContentLang)) {
return;
}
if ("es".equals(detectedLanguageCode) && ("an".equals(contentLangCode)
|| "ast".equals(contentLangCode))) {
return;
}
if ("it".equals(detectedLanguageCode) && ("co".equals(contentLangCode)
|| "pms".equals(contentLangCode)
|| "vec".equals(contentLangCode)
|| "lmo".equals(contentLangCode)
|| "scn".equals(contentLangCode)
|| "nap".equals(contentLangCode))) {
return;
}
if ("rw".equals(detectedLanguageCode)
&& "rn".equals(contentLangCode)) {
return;
}
if ("mhr".equals(detectedLanguageCode) && ("chm".equals(contentLangCode)
|| "mrj".equals(contentLangCode))) {
return;
}
if ("mrj".equals(detectedLanguageCode) && ("chm".equals(contentLangCode)
|| "mhr".equals(contentLangCode))) {
return;
}
if (zhSubtagMismatch(detectedLanguage, lowerCaseContentLang)
|| !contentLangCode.equals(detectedLanguageCode)) {
message = "This document appears to be written in %s but the value"
+ " of the HTTP \u201CContent-Language\u201D header is"
+ " \u201C%s\u201D. Consider changing it to"
+ " \u201C%s\u201D (or variant).";
String warning = String.format(message, detectedLanguageName,
lowerCaseContentLang, preferredLanguageCode,
preferredLanguageCode);
if (errorHandler != null) {
SAXParseException spe = new SAXParseException(warning, null);
errorHandler.warning(spe);
}
}
if (hasLang) {
message = "The value of the HTTP \u201CContent-Language\u201D"
+ " header is \u201C%s\u201D but it will be ignored because"
+ " the \u201Chtml\u201D start tag has %s.";
String lowerCaseLang = langAttrValue.toLowerCase();
String declaredLangCode = new ULocale(langAttrValue).getLanguage();
if (hasLang) {
if (zhSubtagMismatch(lowerCaseContentLang, lowerCaseLang)
|| !contentLangCode.equals(declaredLangCode)) {
warn(String.format(message, httpContentLangHeader,
getAttValueExpr("lang", langAttrValue)));
}
}
}
}
private void checkDirAttribute(String detectedLanguage,
String detectedLanguageName, String detectedLanguageCode,
String preferredLanguageCode) throws SAXException {
if (Arrays.binarySearch(RTL_LANGS, detectedLanguageCode) < 0) {
return;
}
String dirWarning = "";
if (!hasDir) {
dirWarning = String.format(
"This document appears to be written in %s."
+ " Consider adding \u201Cdir=\"rtl\"\u201D"
+ " to the \u201Chtml\u201D start tag.",
detectedLanguageName, preferredLanguageCode);
} else if (!"rtl".equals(dirAttrValue)) {
String message = "This document appears to be written in %s"
+ " but the \u201Chtml\u201D start tag has %s."
+ " Consider using \u201Cdir=\"rtl\"\u201D instead.";
dirWarning = String.format(message, detectedLanguageName,
getAttValueExpr("dir", dirAttrValue));
}
if (!"".equals(dirWarning)) {
warn(dirWarning);
}
}
private boolean zhSubtagMismatch(String expectedLanguage,
String declaredLanguage) {
return (("zh-hans".equals(expectedLanguage)
&& (declaredLanguage.contains("zh-tw")
|| declaredLanguage.contains("zh-hant")))
|| ("zh-hant".equals(expectedLanguage)
&& (declaredLanguage.contains("zh-cn")
|| declaredLanguage.contains("zh-hans"))));
}
private String getAttValueExpr(String attName, String attValue) {
if ("".equals(attValue)) {
return String.format("an empty \u201c%s\u201d attribute", attName);
} else {
return String.format("\u201C%s=\"%s\"\u201D", attName, attValue);
}
}
private void warn(String message) throws SAXException {
if (errorHandler != null) {
SAXParseException spe = new SAXParseException(message,
htmlStartTagLocator);
errorHandler.warning(spe);
}
}
/**
* @param prefix
* @throws SAXException
* @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String)
*/
@Override
public void endPrefixMapping(String prefix) throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.endPrefixMapping(prefix);
}
/**
* @param ch
* @param start
* @param length
* @throws SAXException
* @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)
*/
@Override
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.ignorableWhitespace(ch, start, length);
}
/**
* @param target
* @param data
* @throws SAXException
* @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String,
* java.lang.String)
*/
@Override
public void processingInstruction(String target, String data)
throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.processingInstruction(target, data);
}
/**
* @param name
* @throws SAXException
* @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String)
*/
@Override
public void skippedEntity(String name) throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.skippedEntity(name);
}
/**
* @param prefix
* @param uri
* @throws SAXException
* @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String,
* java.lang.String)
*/
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.startPrefixMapping(prefix, uri);
}
/**
* @return
* @see org.xml.sax.XMLReader#getDTDHandler()
*/
@Override
public DTDHandler getDTDHandler() {
return wrappedReader.getDTDHandler();
}
/**
* @return
* @see org.xml.sax.XMLReader#getEntityResolver()
*/
@Override
public EntityResolver getEntityResolver() {
return wrappedReader.getEntityResolver();
}
/**
* @return
* @see org.xml.sax.XMLReader#getErrorHandler()
*/
@Override
public ErrorHandler getErrorHandler() {
return errorHandler;
}
/**
* @param name
* @return
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
* @see org.xml.sax.XMLReader#getFeature(java.lang.String)
*/
@Override
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
return wrappedReader.getFeature(name);
}
/**
* @param name
* @return
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
* @see org.xml.sax.XMLReader#getProperty(java.lang.String)
*/
@Override
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
return wrappedReader.getProperty(name);
}
/**
* @param input
* @throws IOException
* @throws SAXException
* @see org.xml.sax.XMLReader#parse(org.xml.sax.InputSource)
*/
@Override
public void parse(InputSource input) throws IOException, SAXException {
wrappedReader.parse(input);
}
/**
* @param systemId
* @throws IOException
* @throws SAXException
* @see org.xml.sax.XMLReader#parse(java.lang.String)
*/
@Override
public void parse(String systemId) throws IOException, SAXException {
wrappedReader.parse(systemId);
}
/**
* @param handler
* @see org.xml.sax.XMLReader#setContentHandler(org.xml.sax.ContentHandler)
*/
@Override
public void setContentHandler(ContentHandler handler) {
contentHandler = handler;
}
/**
* @param handler
* @see org.xml.sax.XMLReader#setDTDHandler(org.xml.sax.DTDHandler)
*/
@Override
public void setDTDHandler(DTDHandler handler) {
wrappedReader.setDTDHandler(handler);
}
/**
* @param resolver
* @see org.xml.sax.XMLReader#setEntityResolver(org.xml.sax.EntityResolver)
*/
@Override
public void setEntityResolver(EntityResolver resolver) {
wrappedReader.setEntityResolver(resolver);
}
/**
* @param handler
* @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler)
*/
@Override
public void setErrorHandler(ErrorHandler handler) {
wrappedReader.setErrorHandler(handler);
}
/**
* @param name
* @param value
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
* @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
*/
@Override
public void setFeature(String name, boolean value)
throws SAXNotRecognizedException, SAXNotSupportedException {
wrappedReader.setFeature(name, value);
}
/**
* @param name
* @param value
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
* @see org.xml.sax.XMLReader#setProperty(java.lang.String,
* java.lang.Object)
*/
@Override
public void setProperty(String name, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException {
wrappedReader.setProperty(name, value);
}
} |
package biz.aQute.resolve;
import static org.osgi.framework.namespace.BundleNamespace.BUNDLE_NAMESPACE;
import static org.osgi.framework.namespace.IdentityNamespace.IDENTITY_NAMESPACE;
import static org.osgi.resource.Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE;
import static org.osgi.resource.Namespace.RESOLUTION_OPTIONAL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Formatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import org.apache.felix.resolver.reason.ReasonException;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.resource.Capability;
import org.osgi.resource.Namespace;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.resource.Wire;
import org.osgi.service.log.LogService;
import org.osgi.service.resolver.ResolutionException;
import org.osgi.service.resolver.ResolveContext;
import org.osgi.service.resolver.Resolver;
import aQute.bnd.build.Project;
import aQute.bnd.build.model.BndEditModel;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.resource.CapReqBuilder;
import aQute.bnd.osgi.resource.ResourceUtils;
import aQute.bnd.osgi.resource.WireImpl;
import aQute.bnd.service.Registry;
import aQute.lib.strings.Strings;
import aQute.libg.generics.Create;
import aQute.libg.tuple.Pair;
public class ResolveProcess {
private static final String ARROW = " ⇒ ";
private Map<Resource, List<Wire>> required;
private Map<Resource, List<Wire>> optional;
private ResolutionException resolutionException;
public Map<Resource, List<Wire>> resolveRequired(BndEditModel inputModel, Registry plugins, Resolver resolver,
Collection<ResolutionCallback> callbacks, LogService log) throws ResolutionException {
try {
return resolveRequired(inputModel.getProperties(), inputModel.getProject(), plugins, resolver, callbacks,
log);
} catch (Exception e) {
if (e instanceof ResolutionException) {
throw (ResolutionException) e;
}
throw new ResolutionException(e);
}
}
public Map<Resource, List<Wire>> resolveRequired(Processor properties, Project project, Registry plugins,
Resolver resolver, Collection<ResolutionCallback> callbacks, LogService log) throws ResolutionException {
required = new HashMap<>();
optional = new HashMap<>();
BndrunResolveContext rc = new BndrunResolveContext(properties, project, plugins, log);
rc.addCallbacks(callbacks);
// 1. Resolve initial requirements
Map<Resource, List<Wire>> wirings;
try {
wirings = resolver.resolve(rc);
} catch (ResolutionException re) {
throw augment(rc, re);
}
// 2. Save initial requirement resolution
Pair<Resource, List<Wire>> initialRequirement = null;
for (Map.Entry<Resource, List<Wire>> wiring : wirings.entrySet()) {
if (rc.getInputResource() == wiring.getKey()) {
initialRequirement = new Pair<>(wiring.getKey(), wiring.getValue());
break;
}
}
// 3. Save the resolved root resources
final List<Resource> resources = new ArrayList<>();
for (Resource r : rc.getMandatoryResources()) {
reqs: for (Requirement req : r.getRequirements(null)) {
for (Resource found : wirings.keySet()) {
String filterStr = req.getDirectives()
.get(Namespace.REQUIREMENT_FILTER_DIRECTIVE);
try {
org.osgi.framework.Filter filter = filterStr != null
? org.osgi.framework.FrameworkUtil.createFilter(filterStr)
: null;
for (Capability c : found.getCapabilities(req.getNamespace())) {
if (filter != null && filter.matches(c.getAttributes())) {
resources.add(found);
continue reqs;
}
}
} catch (InvalidSyntaxException e) {}
}
}
}
// 4. Add any 'osgi.wiring.bundle' requirements
List<Resource> wiredBundles = new ArrayList<>();
for (Resource resource : resources) {
addWiredBundle(wirings, resource, wiredBundles);
}
for (Resource resource : wiredBundles) {
if (!resources.contains(resource)) {
resources.add(resource);
}
}
final Map<Resource, List<Wire>> discoveredOptional = new LinkedHashMap<>();
// 5. Resolve the rest
BndrunResolveContext rc2 = new BndrunResolveContext(properties, project, plugins, log) {
@Override
public Collection<Resource> getMandatoryResources() {
return resources;
}
@Override
public boolean isInputResource(Resource resource) {
for (Resource r : resources) {
if (AbstractResolveContext.resourceIdentityEquals(r, resource)) {
return true;
}
}
return false;
}
@Override
public List<Capability> findProviders(Requirement requirement) {
List<Capability> toReturn = super.findProviders(requirement);
if (toReturn.isEmpty() && isEffective(requirement)
&& RESOLUTION_OPTIONAL.equals(requirement.getDirectives()
.get(REQUIREMENT_RESOLUTION_DIRECTIVE))) {
// We have an effective optional requirement that is
// unmatched
// AbstractResolveContext deliberately does not include
// optionals,
// so we force a repo check here so that we can populate
// the optional
// map
for (Capability cap : findProvidersFromRepositories(requirement, new LinkedHashSet<>())) {
Resource optionalRes = cap.getResource();
List<Wire> list = discoveredOptional.get(optionalRes);
if (list == null) {
list = new ArrayList<>();
discoveredOptional.put(optionalRes, list);
}
WireImpl candidateWire = new WireImpl(cap, requirement);
if (!list.contains(candidateWire))
list.add(candidateWire);
}
}
return toReturn;
}
};
rc2.addCallbacks(callbacks);
try {
wirings = resolver.resolve(rc2);
} catch (ResolutionException re) {
throw augment(rc2, re);
}
if (initialRequirement != null) {
wirings.put(initialRequirement.getFirst(), initialRequirement.getSecond());
}
Map<Resource, List<Wire>> result = invertWirings(wirings, rc2);
removeFrameworkAndInputResources(result, rc2);
required.putAll(result);
optional = tidyUpOptional(wirings, discoveredOptional, log);
return result;
}
/*
* The Felix resolver reports an initial resource as unresolved if one of
* its requirements cannot be found, even though it is in the repo. This
* method will (try to) analyze what is actually missing. This is not
* perfect but should give some more diagnostics in most cases.
*/
public static ResolutionException augment(AbstractResolveContext context, ResolutionException re) {
Set<Requirement> unresolved = Create.set();
unresolved.addAll(re.getUnresolvedRequirements());
unresolved.addAll(context.getFailed());
return augment(unresolved, context, re);
}
public static ResolutionException augment(ResolveContext context, ResolutionException re)
throws ResolutionException {
return augment(re.getUnresolvedRequirements(), context, re);
}
/**
* Produce a 'chain of responsibility' for the resolution failure, including
* optional requirements.
*
* @param re the resolution exception
* @return the report
*/
public static String format(ResolutionException re) {
return format(re, true);
}
/**
* Produce a 'chain of responsibility' for the resolution failure.
*
* @param re the resolution exception
* @param reportOptional if true, optional requirements are listed in the
* output
* @return the report
*/
public static String format(ResolutionException re, boolean reportOptional) {
List<Requirement> chain = new ArrayList<>();
Throwable cause = re;
while (cause != null) {
if (cause instanceof ReasonException) {
ReasonException mre = (ReasonException) cause;
// there will only be one entry here
chain.addAll(mre.getUnresolvedRequirements());
}
cause = cause.getCause();
}
Map<Boolean, List<Requirement>> requirements = re.getUnresolvedRequirements()
.stream()
.filter(req -> !chain.contains(req))
.collect(Collectors.partitioningBy(ResolveProcess::isOptional));
try (Formatter f = new Formatter()) {
f.format("Resolution failed. Capabilities satisfying the following requirements could not be found:");
String prefix = " ";
for (Requirement req : chain) {
f.format("%n%s[%s]", prefix, req.getResource());
if (" ".equals(prefix))
prefix = ARROW;
else
prefix = " " + prefix;
format(f, prefix, req);
prefix = " " + prefix;
}
requirements.get(Boolean.FALSE)
.stream()
.collect(Collectors.groupingBy(Requirement::getResource))
.forEach(formatGroup(f));
List<Requirement> optional = requirements.get(Boolean.TRUE);
if (!optional.isEmpty() && reportOptional) {
f.format("%nThe following requirements are optional:");
optional.stream()
.collect(Collectors.groupingBy(Requirement::getResource))
.forEach(formatGroup(f));
}
return f.toString();
}
}
static BiConsumer<? super Resource, ? super List<Requirement>> formatGroup(Formatter f) {
return (resource, list) -> {
f.format("%n [%s]", resource);
list.forEach(req -> {
format(f, ARROW, req);
});
};
}
static void format(Formatter f, String prefix, Requirement req) {
String filter = req.getDirectives()
.get("filter");
f.format("%n%s%s: %s", prefix, req.getNamespace(), filter);
}
public static String format(Collection<Requirement> requirements) {
Set<Requirement> mandatory = new HashSet<>();
Set<Requirement> optional = new HashSet<>();
for (Requirement req : requirements) {
if (isOptional(req))
optional.add(req);
else
mandatory.add(req);
}
try (Formatter f = new Formatter()) {
f.format("%n Mandatory:");
for (Requirement req : mandatory) {
f.format("%n [%-19s] %s", req.getNamespace(), req);
}
f.format("%n Optional:");
for (Requirement req : optional) {
f.format("%n [%-19s] %s", req.getNamespace(), req);
}
return f.toString();
}
}
private static boolean isOptional(Requirement req) {
String resolution = req.getDirectives()
.get(Constants.RESOLUTION);
if (resolution == null) {
return false;
}
return Constants.OPTIONAL.equals(resolution);
}
private static ResolutionException augment(Collection<Requirement> unresolved, ResolveContext context,
ResolutionException re) {
if (unresolved.isEmpty()) {
return re;
}
long deadline = System.currentTimeMillis() + 1000L;
Set<Requirement> list = new HashSet<>(unresolved);
Set<Resource> resources = new HashSet<>();
try {
for (Requirement r : unresolved) {
Requirement find = missing(context, r, resources, deadline);
if (find != null) {
list.add(find);
}
}
} catch (TimeoutException toe) {}
return new ResolutionException(re.getMessage(), re, list);
}
/*
* Recursively traverse all requirement's resource requirement's
*/
private static Requirement missing(ResolveContext context, Requirement rq, Set<Resource> resources, long deadline)
throws TimeoutException {
resources.add(rq.getResource());
if (deadline < System.currentTimeMillis())
throw new TimeoutException();
List<Capability> providers = context.findProviders(rq);
// This requirement cannot be found
if (providers.isEmpty())
return rq;
// We first search breadth first for a capability that
// satisfies our requirement and its 1st level requirements.
Set<Resource> candidates = new HashSet<>();
Requirement missing = null;
caps: for (Capability cap : providers) {
for (Requirement sub : cap.getResource()
.getRequirements(null)) {
List<Capability> subProviders = context.findProviders(sub);
if (subProviders.isEmpty()) {
if (missing == null)
missing = sub;
// this cap lacks its 1st level requirement
// so try next capability
continue caps;
}
}
// We found a capability for our requirement
// that matches, of course its resource might fail
// later
candidates.add(cap.getResource());
}
// If we have no candidates, then we fail ...
// missing is set then since at least 1 cap must have failed
// and set missing since #providers > 0. I.e. our requirement
// found a candidate, but no candidate succeeded to be satisfied.
// Missing then contains the first missing requirement
if (candidates.isEmpty()) {
assert missing != null;
return missing;
}
Requirement initialMissing = missing;
missing = null;
// candidates now contains the resources that are potentially
// able to satisfy our requirements.
candidates.removeAll(resources);
resources.addAll(candidates);
resource: for (Resource resource : candidates) {
for (Requirement requirement : resource.getRequirements(null)) {
Requirement r1 = missing(context, requirement, resources, deadline);
if (r1 != null && missing != null) {
missing = r1;
continue resource;
}
}
// A Fully matching resource
return null;
}
// None of the resources was resolvable
return missing == null ? initialMissing : missing;
}
private void addWiredBundle(Map<Resource, List<Wire>> wirings, Resource resource, List<Resource> result) {
List<Requirement> reqs = resource.getRequirements(BUNDLE_NAMESPACE);
for (Requirement req : reqs) {
List<Wire> wrs = wirings.get(resource);
for (Wire w : wrs) {
if (w.getRequirement()
.equals(req)) {
Resource res = w.getProvider();
if (res != null) {
if (!result.contains(res)) {
result.add(res);
addWiredBundle(wirings, res, result);
}
}
}
}
}
}
/*
* private void processOptionalRequirements(BndrunResolveContext
* resolveContext) { optionalReasons = new
* HashMap<URI,Map<Capability,Collection<Requirement>>>(); for
* (Entry<Requirement,List<Capability>> entry :
* resolveContext.getOptionalRequirements().entrySet()) { Requirement req =
* entry.getKey(); Resource requirer = req.getResource(); if
* (requiredReasons.containsKey(getResourceURI(requirer))) {
* List<Capability> caps = entry.getValue(); for (Capability cap : caps) {
* Resource providerResource = cap.getResource(); URI resourceUri =
* getResourceURI(providerResource); if (requirer != providerResource) { //
* && !requiredResources.containsKey(providerResource))
* Map<Capability,Collection<Requirement>> resourceReasons =
* optionalReasons.get(cap.getResource()); if (resourceReasons == null) {
* resourceReasons = new HashMap<Capability,Collection<Requirement>>();
* optionalReasons.put(resourceUri, resourceReasons);
* urisToResources.put(resourceUri, providerResource); }
* Collection<Requirement> capRequirements = resourceReasons.get(cap); if
* (capRequirements == null) { capRequirements = new
* LinkedList<Requirement>(); resourceReasons.put(cap, capRequirements); }
* capRequirements.add(req); } } } } }
*/
private static void removeFrameworkAndInputResources(Map<Resource, List<Wire>> resourceMap,
AbstractResolveContext rc) {
resourceMap.keySet()
.removeIf(rc::isSystemResource);
}
/**
* Inverts the wiring map from the resolver. Whereas the resolver returns a
* map of resources and the list of wirings FROM each resource, we want to
* know the list of wirings TO that resource. This is in order to show the
* user the reasons for each resource being present in the result.
*/
private static Map<Resource, List<Wire>> invertWirings(Map<Resource, ? extends Collection<Wire>> wirings,
AbstractResolveContext rc) {
Map<Resource, List<Wire>> inverted = new HashMap<>();
for (Entry<Resource, ? extends Collection<Wire>> entry : wirings.entrySet()) {
Resource requirer = entry.getKey();
for (Wire wire : entry.getValue()) {
Resource provider = findResolvedProvider(wire, wirings.keySet(), rc);
// Filter out self-capabilities, i.e. requirer and provider are
// same
if (provider == requirer)
continue;
List<Wire> incoming = inverted.get(provider);
if (incoming == null) {
incoming = new LinkedList<>();
inverted.put(provider, incoming);
}
incoming.add(wire);
}
}
return inverted;
}
private static Resource findResolvedProvider(Wire wire, Set<Resource> resources, AbstractResolveContext rc) {
// Make sure not to add new resources into the result. The resolver
// already created the closure of all the needed resources. We need to
// find the key in the result that already provides the capability
// defined by this wire.
Capability capability = wire.getCapability();
Resource resource = capability.getResource();
if (rc.isSystemResource(resource) || (ResourceUtils.isFragment(resource) && resources.contains(resource))) {
return resource;
}
for (Resource resolved : resources) {
for (Capability resolvedCap : resolved.getCapabilities(capability.getNamespace())) {
if (ResourceUtils.matches(wire.getRequirement(), resolvedCap)) {
return resolved;
}
}
}
// It shouldn't be possible to arrive here!
throw new IllegalStateException(
Strings.format("The capability for wire %s was not associated with a resource in the resolution", wire));
}
private static Map<Resource, List<Wire>> tidyUpOptional(Map<Resource, List<Wire>> required,
Map<Resource, List<Wire>> discoveredOptional, LogService log) {
Map<Resource, List<Wire>> toReturn = new HashMap<>();
Set<Capability> requiredIdentities = new HashSet<>();
for (Resource r : required.keySet()) {
Capability normalisedIdentity = toPureIdentity(r, log);
if (normalisedIdentity != null) {
requiredIdentities.add(normalisedIdentity);
}
}
Set<Capability> acceptedIdentities = new HashSet<>();
for (Entry<Resource, List<Wire>> entry : discoveredOptional.entrySet()) {
// If we're required we are not also optional
Resource optionalResource = entry.getKey();
if (required.containsKey(optionalResource)) {
continue;
}
// If another resource with the same identity is required
// then we defer to it, otherwise we will get the an optional
// resource showing up from a different repository
Capability optionalIdentity = toPureIdentity(optionalResource, log);
if (requiredIdentities.contains(optionalIdentity)) {
continue;
}
// Only wires to required resources should kept
List<Wire> validWires = new ArrayList<>();
optional: for (Wire optionalWire : entry.getValue()) {
Resource requirer = optionalWire.getRequirer();
Capability requirerIdentity = toPureIdentity(requirer, log);
if (required.containsKey(requirer)) {
Requirement req = optionalWire.getRequirement();
// Somebody does require this - do they have a match
// already?
List<Wire> requiredWires = required.get(requirer);
for (Wire requiredWire : requiredWires) {
if (req.equals(requiredWire.getRequirement())) {
continue optional;
}
}
validWires.add(optionalWire);
}
}
// If there is at least one valid wire then we want the optional
// resource, but only if we don't already have one for that identity
// This can happen if the same resource is in multiple repos
if (!validWires.isEmpty()) {
if (acceptedIdentities.add(optionalIdentity)) {
toReturn.put(optionalResource, validWires);
} else {
log.log(LogService.LOG_INFO, "Discarding the optional resource " + optionalResource
+ " because another optional resource with the identity " + optionalIdentity
+ " has already been selected. This usually happens when the same bundle is present in multiple repositories.");
}
}
}
return toReturn;
}
private static Capability toPureIdentity(Resource r, LogService log) {
List<Capability> capabilities = r.getCapabilities(IDENTITY_NAMESPACE);
if (capabilities.size() != 1) {
log.log(LogService.LOG_WARNING,
"The resource " + r + " has the wrong number of identity capabilities " + capabilities.size());
return null;
}
try {
return CapReqBuilder.copy(capabilities.get(0), null);
} catch (Exception e) {
log.log(LogService.LOG_ERROR, "Unable to copy the capability " + capabilities.get(0));
return null;
}
}
public ResolutionException getResolutionException() {
return resolutionException;
}
public Collection<Resource> getRequiredResources() {
if (required == null)
return Collections.emptyList();
return Collections.unmodifiableCollection(required.keySet());
}
public Collection<Resource> getOptionalResources() {
if (optional == null)
return Collections.emptyList();
return Collections.unmodifiableCollection(optional.keySet());
}
public Collection<Wire> getRequiredReasons(Resource resource) {
Collection<Wire> wires = required.get(resource);
if (wires == null)
wires = Collections.emptyList();
return wires;
}
public Collection<Wire> getOptionalReasons(Resource resource) {
Collection<Wire> wires = optional.get(resource);
if (wires == null)
wires = Collections.emptyList();
return wires;
}
} |
package btools.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.zip.GZIPOutputStream;
import btools.router.OsmNodeNamed;
import btools.router.OsmTrack;
import btools.router.RoutingContext;
import btools.router.RoutingEngine;
import btools.server.request.ProfileUploadHandler;
import btools.server.request.RequestHandler;
import btools.server.request.ServerHandler;
import btools.util.StackSampler;
public class RouteServer extends Thread
{
public static final String PROFILE_UPLOAD_URL = "/brouter/profile";
public ServiceContext serviceContext;
private Socket clientSocket = null;
private RoutingEngine cr = null;
private volatile boolean terminated;
public void stopRouter()
{
RoutingEngine e = cr;
if ( e != null ) e.terminate();
}
private static DateFormat tsFormat = new SimpleDateFormat( "dd.MM.yy HH:mm", new Locale( "en", "US" ) );
private static String formattedTimestamp()
{
synchronized( tsFormat )
{
return tsFormat.format( new Date( System.currentTimeMillis() ) );
}
}
public void run()
{
BufferedReader br = null;
BufferedWriter bw = null;
try
{
br = new BufferedReader( new InputStreamReader( clientSocket.getInputStream() , "UTF-8") );
bw = new BufferedWriter( new OutputStreamWriter( clientSocket.getOutputStream(), "UTF-8" ) );
// first line
String getline = null;
String agent = null;
String encodings = null;
// more headers until first empty line
for(;;)
{
// headers
String line = br.readLine();
if ( line == null )
{
return;
}
if ( line.length() == 0 )
{
break;
}
if ( getline == null )
{
getline = line;
}
if ( line.startsWith( "User-Agent: " ) )
{
agent = line.substring( "User-Agent: ".length() );
}
if ( line.startsWith( "Accept-Encoding: " ) )
{
encodings = line.substring( "Accept-Encoding: ".length() );
}
}
String excludedAgents = System.getProperty( "excludedAgents" );
if ( agent != null && excludedAgents != null )
{
StringTokenizer tk = new StringTokenizer( excludedAgents, "," );
while( tk.hasMoreTokens() )
{
if ( agent.indexOf( tk.nextToken() ) >= 0 )
{
writeHttpHeader( bw );
bw.write( "Bad agent: " + agent );
bw.flush();
return;
}
}
}
if ( getline.startsWith("GET /favicon.ico") )
{
return;
}
if ( getline.startsWith("GET /robots.txt") )
{
writeHttpHeader( bw );
bw.write( "User-agent: *\n" );
bw.write( "Disallow: /\n" );
bw.flush();
return;
}
InetAddress ip = clientSocket.getInetAddress();
System.out.println( formattedTimestamp() + " ip=" + (ip==null ? "null" : ip.toString() ) + " -> " + getline );
String url = getline.split(" ")[1];
HashMap<String,String> params = getUrlParams(url);
long maxRunningTime = getMaxRunningTime();
RequestHandler handler;
if ( params.containsKey( "lonlats" ) && params.containsKey( "profile" ) )
{
handler = new ServerHandler( serviceContext, params );
}
else if ( url.startsWith( PROFILE_UPLOAD_URL ) )
{
if ( getline.startsWith("OPTIONS") )
{
// handle CORS preflight request (Safari)
String corsHeaders = "Access-Control-Allow-Methods: GET, POST\n"
+ "Access-Control-Allow-Headers: Content-Type\n";
writeHttpHeader( bw, "text/plain", null, corsHeaders );
bw.flush();
return;
}
else
{
writeHttpHeader(bw, "application/json");
String profileId = null;
if ( url.length() > PROFILE_UPLOAD_URL.length() + 1 )
{
// e.g. /brouter/profile/custom_1400767688382
profileId = url.substring(PROFILE_UPLOAD_URL.length() + 1);
}
ProfileUploadHandler uploadHandler = new ProfileUploadHandler( serviceContext );
uploadHandler.handlePostRequest( profileId, br, bw );
bw.flush();
return;
}
}
else if ( url.startsWith( "/brouter/suspects" ) )
{
writeHttpHeader(bw, url.endsWith( ".json" ) ? "application/json" : "text/html");
SuspectManager.process( url, bw );
return;
}
else
{
throw new IllegalArgumentException( "unknown request syntax: " + getline );
}
RoutingContext rc = handler.readRoutingContext();
List<OsmNodeNamed> wplist = handler.readWayPointList();
if ( wplist.size() < 10 )
{
NearRecentWps.add( wplist );
}
for( Map.Entry<String,String> e : params.entrySet() )
{
if ( "timode".equals( e.getKey() ) )
{
rc.turnInstructionMode = Integer.parseInt( e.getValue() );
}
else if ( "heading".equals( e.getKey() ) )
{
rc.startDirection = Integer.valueOf( Integer.parseInt( e.getValue() ) );
rc.forceUseStartDirection = true;
}
else if ( e.getKey().startsWith( "profile:" ) )
{
if ( rc.keyValues == null )
{
rc.keyValues = new HashMap<String,String>();
}
rc.keyValues.put( e.getKey().substring( 8 ), e.getValue() );
}
}
cr = new RoutingEngine( null, null, serviceContext.segmentDir, wplist, rc );
cr.quite = true;
cr.doRun( maxRunningTime );
if ( cr.getErrorMessage() != null )
{
writeHttpHeader(bw);
bw.write( cr.getErrorMessage() );
bw.write( "\n" );
}
else
{
OsmTrack track = cr.getFoundTrack();
String headers = encodings == null || encodings.indexOf( "gzip" ) < 0 ? null : "Content-Encoding: gzip\n";
writeHttpHeader(bw, handler.getMimeType(), handler.getFileName(), headers );
if ( track != null )
{
if ( headers != null ) // compressed
{
java.io.ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter( new GZIPOutputStream( baos ), "UTF-8" );
w.write( handler.formatTrack(track) );
w.close();
bw.flush();
clientSocket.getOutputStream().write( baos.toByteArray() );
}
else
{
bw.write( handler.formatTrack(track) );
}
}
}
bw.flush();
}
catch (Throwable e)
{
System.out.println("RouteServer got exception (will continue): "+e);
e.printStackTrace();
}
finally
{
cr = null;
if ( br != null ) try { br.close(); } catch( Exception e ) {}
if ( bw != null ) try { bw.close(); } catch( Exception e ) {}
if ( clientSocket != null ) try { clientSocket.close(); } catch( Exception e ) {}
terminated = true;
}
}
public static void main(String[] args) throws Exception
{
System.out.println("BRouter 1.4.11 / 02042018");
if ( args.length != 5 && args.length != 6)
{
System.out.println("serve BRouter protocol");
System.out.println("usage: java RouteServer <segmentdir> <profiledir> <customprofiledir> <port> <maxthreads> [bindaddress]");
return;
}
ServiceContext serviceContext = new ServiceContext();
serviceContext.segmentDir = args[0];
serviceContext.profileDir = args[1];
System.setProperty( "profileBaseDir", serviceContext.profileDir );
String dirs = args[2];
StringTokenizer tk = new StringTokenizer( dirs, "," );
serviceContext.customProfileDir = tk.nextToken();
serviceContext.sharedProfileDir = tk.hasMoreTokens() ? tk.nextToken() : serviceContext.customProfileDir;
int maxthreads = Integer.parseInt( args[4] );
TreeMap<Long,RouteServer> threadMap = new TreeMap<Long,RouteServer>();
ServerSocket serverSocket = args.length > 5 ? new ServerSocket(Integer.parseInt(args[3]),50,InetAddress.getByName(args[5])) : new ServerSocket(Integer.parseInt(args[3]));
// stacksample for performance profiling
// ( caution: start stacksampler only after successfully creating the server socket
// because that thread prevents the process from terminating, so the start-attempt
// by the watchdog cron would create zombies )
File stackLog = new File( "stacks.txt" );
if ( stackLog.exists() )
{
StackSampler stackSampler = new StackSampler( stackLog, 1000 );
stackSampler.start();
System.out.println( "*** sampling stacks into stacks.txt *** ");
}
long last_ts = 0;
for (;;)
{
Socket clientSocket = serverSocket.accept();
RouteServer server = new RouteServer();
server.serviceContext = serviceContext;
server.clientSocket = clientSocket;
// cleanup thread list
for(;;)
{
boolean removedItem = false;
for (Map.Entry<Long,RouteServer> e : threadMap.entrySet())
{
if ( e.getValue().terminated )
{
threadMap.remove( e.getKey() );
removedItem = true;
break;
}
}
if ( !removedItem ) break;
}
// kill thread if limit reached
if ( threadMap.size() >= maxthreads )
{
Long k = threadMap.firstKey();
RouteServer victim = threadMap.get( k );
threadMap.remove( k );
victim.stopRouter();
}
long ts = System.currentTimeMillis();
while ( ts <= last_ts ) ts++;
threadMap.put( Long.valueOf( ts ), server );
last_ts = ts;
server.start();
}
}
private static HashMap<String,String> getUrlParams( String url ) throws UnsupportedEncodingException
{
HashMap<String,String> params = new HashMap<String,String>();
String decoded = URLDecoder.decode( url, "UTF-8" );
StringTokenizer tk = new StringTokenizer( decoded, "?&" );
while( tk.hasMoreTokens() )
{
String t = tk.nextToken();
StringTokenizer tk2 = new StringTokenizer( t, "=" );
if ( tk2.hasMoreTokens() )
{
String key = tk2.nextToken();
if ( tk2.hasMoreTokens() )
{
String value = tk2.nextToken();
params.put( key, value );
}
}
}
return params;
}
private static long getMaxRunningTime() {
long maxRunningTime = 60000;
String sMaxRunningTime = System.getProperty( "maxRunningTime" );
if ( sMaxRunningTime != null )
{
maxRunningTime = Integer.parseInt( sMaxRunningTime ) * 1000;
}
return maxRunningTime;
}
private static void writeHttpHeader( BufferedWriter bw ) throws IOException
{
writeHttpHeader( bw, "text/plain" );
}
private static void writeHttpHeader( BufferedWriter bw, String mimeType ) throws IOException
{
writeHttpHeader( bw, mimeType, null );
}
private static void writeHttpHeader( BufferedWriter bw, String mimeType, String fileName ) throws IOException
{
writeHttpHeader( bw, mimeType, fileName, null);
}
private static void writeHttpHeader( BufferedWriter bw, String mimeType, String fileName, String headers ) throws IOException
{
// http-header
bw.write( "HTTP/1.1 200 OK\n" );
bw.write( "Connection: close\n" );
bw.write( "Content-Type: " + mimeType + "; charset=utf-8\n" );
if ( fileName != null )
{
bw.write( "Content-Disposition: attachment; filename=\"" + fileName + "\"\n" );
}
bw.write( "Access-Control-Allow-Origin: *\n" );
if ( headers != null )
{
bw.write( headers );
}
bw.write( "\n" );
}
} |
package org.clapper.curn.output.script;
import org.clapper.curn.Constants;
import org.clapper.curn.CurnConfig;
import org.clapper.curn.ConfiguredOutputHandler;
import org.clapper.curn.CurnException;
import org.clapper.curn.FeedInfo;
import org.clapper.curn.Version;
import org.clapper.curn.output.FileOutputHandler;
import org.clapper.curn.parser.RSSChannel;
import org.clapper.curn.parser.RSSItem;
import org.clapper.util.config.ConfigurationException;
import org.clapper.util.config.NoSuchSectionException;
import org.clapper.util.io.FileUtil;
import org.clapper.util.logging.Logger;
import org.clapper.util.text.TextUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.bsf.BSFException;
import org.apache.bsf.BSFEngine;
import org.apache.bsf.BSFManager;
* """
* Initialize a new TextOutputHandler object.
* """
* """
* Process the channels passed in through the Bean Scripting Framework.
* """
public class ScriptOutputHandler extends FileOutputHandler
{
/**
* Wraps an RSSChannel object and its FeedInfo object.
*/
public class ChannelWrapper
{
private RSSChannel channel;
private FeedInfo feedInfo;
ChannelWrapper (RSSChannel channel, FeedInfo feedInfo)
{
this.channel = channel;
this.feedInfo = feedInfo;
}
public RSSChannel getChannel()
{
return this.channel;
}
public FeedInfo getFeedInfo()
{
return this.feedInfo;
}
}
/**
* Type alias
*/
private class ChannelList extends ArrayList<ChannelWrapper>
{
ChannelList()
{
super();
}
}
/**
* Container for the objects exported to the script.
*/
public class CurnScriptObjects
{
public Collection channels = null;
public String outputPath = null;
public CurnConfig config = null;
public String configSection = null;
public Logger logger = null;
String mimeType = null;
public void setMIMEType (String mimeType)
{
this.mimeType = mimeType;
}
public String getVersion()
{
return Version.getFullVersion();
}
}
private BSFManager bsfManager = null;
private CurnConfig config = null;
private Collection<ChannelWrapper> channels = new ChannelList();
private String scriptPath = null;
private String scriptString = null;
private StringWriter mimeTypeBuffer = null;
private String language = null;
private Logger scriptLogger = null;
private CurnScriptObjects scriptObjects = null;
private boolean allowEmbeddedHTML = false;
/**
* For logging
*/
private static Logger log = new Logger (ScriptOutputHandler.class);
/**
* Construct a new <tt>ScriptOutputHandler</tt>.
*/
public ScriptOutputHandler()
{
}
/**
* Initializes the output handler for another set of RSS channels.
*
* @param config the parsed <i>curn</i> configuration data
* @param cfgHandler the <tt>ConfiguredOutputHandler</tt> wrapper
* containing this object; the wrapper has some useful
* metadata, such as the object's configuration section
* name and extra variables.
*
* @throws ConfigurationException configuration error
* @throws CurnException some other initialization error
*/
public final void initOutputHandler (CurnConfig config,
ConfiguredOutputHandler cfgHandler)
throws ConfigurationException,
CurnException
{
this.config = config;
// Parse handler-specific configuration variables
String section = cfgHandler.getSectionName();
try
{
if (section != null)
{
scriptPath = config.getConfigurationValue (section, "Script");
language = config.getConfigurationValue (section, "Language");
allowEmbeddedHTML =
config.getOptionalBooleanValue
(section,
CurnConfig.CFG_ALLOW_EMBEDDED_HTML,
false);
}
}
catch (NoSuchSectionException ex)
{
throw new ConfigurationException (ex);
}
// Verify that the script exists.
File scriptFile = new File (scriptPath);
if (! scriptFile.exists())
{
scriptPath = null;
throw new ConfigurationException (section,
"Script file \""
+ scriptFile.getPath()
+ "\" does not exist.");
}
if (! scriptFile.isFile())
{
scriptPath = null;
throw new ConfigurationException (section,
"Script file \""
+ scriptFile.getPath()
+ "\" is not a regular file.");
}
// Call the registerAdditionalScriptingEngines() method, which
// subclasses can override to provide their own bindings.
registerAdditionalScriptingEngines();
// Allocate a new BSFManager. This must happen after all the extra
// scripting engines are registered.
bsfManager = new BSFManager();
// Register some additional scripting languages.
BSFManager.registerScriptingEngine ("ObjectScript",
"oscript.bsf.ObjectScriptEngine",
new String[] {"os"});
BSFManager.registerScriptingEngine ("groovy",
"org.codehaus.groovy.bsf.GroovyEngine",
new String[] {"groovy", "gy"});
BSFManager.registerScriptingEngine ("beanshell",
"bsh.util.BeanShellBSFEngine",
new String[] {"bsh"});
// Set up a logger for the script. The logger name can't have dots
// in it, because the underlying logging API strips them out,
// thinking they're class/package delimiters. That means we have to
// strip the extension or change it to something else. Since the
// extension conveys information (i.e., the language), we just
// convert it to an underscore.
StringBuffer scriptLoggerName = new StringBuffer();
String scriptName = scriptFile.getName();
scriptLoggerName.append (FileUtil.getFileNameNoExtension (scriptName));
scriptLoggerName.append ("_");
scriptLoggerName.append (FileUtil.getFileNameExtension (scriptName));
scriptLogger = new Logger (scriptLoggerName.toString());
// Declare the script object. We'll fill it partially now; the rest
// will be filled later. Also, for backward compatibility, register
// BSF beans.
this.scriptObjects = new CurnScriptObjects();
try
{
bsfManager.declareBean ("curn",
scriptObjects,
CurnScriptObjects.class);
}
catch (BSFException ex)
{
throw new CurnException ("Can't register script 'curn' object",
ex);
}
scriptObjects.config = config;
scriptObjects.configSection = section;
scriptObjects.logger = scriptLogger;
mimeTypeBuffer = new StringWriter();
bsfManager.registerBean ("mimeType", new PrintWriter (mimeTypeBuffer));
bsfManager.registerBean ("config", scriptObjects.config);
bsfManager.registerBean ("configSection", scriptObjects.configSection);
bsfManager.registerBean ("logger", scriptObjects.logger);
bsfManager.registerBean ("version", scriptObjects.getVersion());
// Load the contents of the script into an in-memory buffer.
scriptString = loadScript (scriptFile);
channels.clear();
}
/**
* Display the list of <tt>RSSItem</tt> news items to whatever output
* is defined for the underlying class. This handler simply buffers up
* the channel, so that {@link #flush} can pass all the channels to the
* script.
*
* @param channel The channel containing the items to emit. The method
* should emit all the items in the channel; the caller
* is responsible for clearing out any items that should
* not be seen.
* @param feedInfo Information about the feed, from the configuration
*
* @throws CurnException unable to write output
*/
public final void displayChannel (RSSChannel channel,
FeedInfo feedInfo)
throws CurnException
{
// Save the channel.
if (! allowEmbeddedHTML)
channel.stripHTML();
channels.add (new ChannelWrapper (channel, feedInfo));
}
/**
* Flush any buffered-up output.
*
* @throws CurnException unable to write output
*/
public final void flush() throws CurnException
{
try
{
// Load the scripting engine
BSFEngine scriptEngine = bsfManager.loadScriptingEngine (language);
// Register the remaining bean (backward compatibility), and set
// the remaining exported object fields.
scriptObjects.channels = channels;
scriptObjects.outputPath = getOutputFile().getPath();
bsfManager.registerBean ("channels", scriptObjects.channels);
bsfManager.registerBean ("outputPath", scriptObjects.outputPath);
// Run the script
log.debug ("Invoking " + scriptPath);
scriptEngine.exec (scriptPath, 0, 0, scriptString);
// Handle the MIME type, backward-compatibly.
String mimeType = scriptObjects.mimeType;
if (mimeType != null)
mimeTypeBuffer.write (mimeType);
}
catch (BSFException ex)
{
Throwable realException = ex.getTargetException();
log.error ("Error interacting with Bean Scripting Framework",
realException);
throw new CurnException (Constants.BUNDLE_NAME,
"ScriptOutputHandler.bsfError",
"Error interacting with Bean Scripting "
+ "Framework: {0}",
new Object[] {ex.getMessage()},
realException);
}
}
/**
* Get the content (i.e., MIME) type for output produced by this output
* handler.
*
* @return the content type
*/
public final String getContentType()
{
return mimeTypeBuffer.toString().trim();
}
/**
* Register additional scripting language engines that are not
* supported by this class. By default, this method does nothing.
* Subclasses that wish to register additional BSF scripting engine
* bindings should override this method and use
* <tt>BSFManager.registerScriptingEngine()</tt> to register the
* engined. See the class documentation, above, for additional details.
*
* @throws CurnException on error
*/
public void registerAdditionalScriptingEngines()
throws CurnException
{
}
/**
* Load the contents of the external script (any file, really) into an
* in-memory buffer.
*
* @param scriptFile the script file
*
* @return the string representing the loaded script
*
* @throws CurnException on error
*/
private String loadScript (File scriptFile)
throws CurnException
{
try
{
Reader r = new BufferedReader (new FileReader (scriptFile));
StringWriter w = new StringWriter();
int c;
while ((c = r.read()) != -1)
w.write (c);
r.close();
return w.toString();
}
catch (IOException ex)
{
throw new CurnException (Constants.BUNDLE_NAME,
"ScriptOutputHandler.cantLoadScript",
"Failed to load script \"{0}\" into "
+ "memory.",
new Object[] {scriptFile.getPath()},
ex);
}
}
} |
package org.eigenbase.enki.hibernate;
import java.io.*;
import java.lang.ref.*;
import java.lang.reflect.*;
import java.sql.*;
import java.util.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import java.util.logging.*;
import javax.jmi.model.*;
import javax.jmi.reflect.*;
import javax.management.ObjectName;
import javax.management.JMException;
import javax.naming.*;
import javax.sql.*;
import org.eigenbase.enki.codegen.*;
import org.eigenbase.enki.hibernate.codegen.*;
import org.eigenbase.enki.hibernate.config.*;
import org.eigenbase.enki.hibernate.jmi.*;
import org.eigenbase.enki.hibernate.mbean.*;
import org.eigenbase.enki.hibernate.storage.*;
import org.eigenbase.enki.jmi.impl.*;
import org.eigenbase.enki.jmi.model.init.*;
import org.eigenbase.enki.mbean.*;
import org.eigenbase.enki.mdr.*;
import org.eigenbase.enki.mdr.EnkiChangeEventThread.*;
import org.eigenbase.enki.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.criterion.*;
import org.hibernate.dialect.*;
import org.hibernate.dialect.resolver.*;
import org.hibernate.stat.*;
import org.hibernate.tool.hbm2ddl.*;
import org.netbeans.api.mdr.*;
import org.netbeans.api.mdr.events.*;
/**
* HibernateMDRepository implements {@link MDRepository} and
* {@link EnkiMDRepository} for Hibernate-based metamodel storage. In
* addition, it acts as a {@link ListenerSource source} of
* {@link MDRChangeEvent} instances.
*
* <p>Storage properties. Set the
* <code>org.eigenbase.enki.implementationType</code> storage property to
* {@link MdrProvider#ENKI_HIBERNATE} to enable the Hibernate
* MDR implementation. Additional storage properties of note are listed
* in the following table.
*
* <table border="1">
* <caption><b>Hibernate-specific Storage Properties</b></caption>
* <tr>
* <th align="left">Name</th>
* <th align="left">Description</th>
* </tr>
* <tr>
* <td align="left">{@value #PROPERTY_STORAGE_ALLOW_IMPLICIT_SESSIONS}</td>
* <td align="left">
* Controls whether or not implicit sessions are allowed. Defaults to
* {@value DEFAULT_ALLOW_IMPLICIT_SESSIONS}.
* </td>
* </tr>
* <tr>
* <td align="left">{@value #PROPERTY_STORAGE_TRACK_SESSIONS}</td>
* <td align="left">
* Controls whether session begin/end pairs are tracked with a unique
* identifier. Useful for determining where a particular session begins
* and ends when sessions are unexpectedly nested. Note that the
* generated identifiers are only unique within a repository instance.
* Defaults to {@value #DEFAULT_TRACK_SESSIONS}.
* </td>
* </tr>
* <tr>
* <td align="left">{@value #PROPERTY_STORAGE_TYPE_LOOKUP_FLUSH_SIZE}</td>
* <td align="left">
* Controls whether or not and how frequently insertions into the MOF
* ID/type lookup table are flushed. Defaults to the value of
* {@value #PROPERTY_STORAGE_HIBERNATE_JDBC_BATCH_SIZE}.
* </td>
* </tr>
* <tr>
* <td align="left">{@value #PROPERTY_STORAGE_CONNECTION_DATASOURCE}</td>
* <td align="left">
* See {@link #PROPERTY_STORAGE_CONNECTION_DATASOURCE} for a discussion
* of this storage property.
* </td>
* </tr>
* <tr>
* <td align="left">{@value #PROPERTY_STORAGE_CONNECTION_DATASOURCE}</td>
* <td align="left">
* See {@link #PROPERTY_STORAGE_CONNECTION_DATASOURCE} for a discussion
* of this storage property. Defaults to
* {@value #PROPERTY_STORAGE_DEFAULT_CONNECTION_DATASOURCE}.
* </td>
* </tr>
* <tr>
* <td align="left">
* {@value #PROPERTY_STORAGE_CONNECTION_DRIVER_CLASS}
* {@value #PROPERTY_STORAGE_CONNECTION_URL}
* {@value #PROPERTY_STORAGE_CONNECTION_USERNAME}
* {@value #PROPERTY_STORAGE_CONNECTION_PASSWORD}
* {@value #PROPERTY_STORAGE_CONNECTION_MAX_IDLE}
* </td>
* <td align="left">
* See {@link #PROPERTY_STORAGE_CONNECTION_DATASOURCE} for a discussion
* of these storage properties. The property
* {@value #PROPERTY_STORAGE_CONNECTION_MAX_IDLE} defaults to
* {@value #DEFAULT_CONNECTION_MAX_IDLE}.
* </td>
* </tr>
* <tr>
* <td align="left">{@value #PROPERTY_STORAGE_JNDI_PREFIX}</td>
* <td align="left">
* All sorage properties staring with this prefix are used to construct
* a JNDI {@link InitialContext}. See
* {@link #PROPERTY_STORAGE_JNDI_PREFIX}.
* </td>
* </tr>
* <tr>
* <td align="left">
* {@value #PROPERTY_STORAGE_JNDI_INITIAL_CONTEXT_FACTORY_CLASS}
* </td>
* <td align="left">
* Initial JNDI context factory class.
* See {@link #PROPERTY_STORAGE_JNDI_INITIAL_CONTEXT_FACTORY_CLASS}.
* </td>
* </tr>
* <tr>
* <td align="left">
* {@value #PROPERTY_STORAGE_JNDI_PROVIDER_URL}
* </td>
* <td align="left">
* JNDI provider URL for JNDI {@link InitialContext}.
* See {@link #PROPERTY_STORAGE_JNDI_PROVIDER_URL}.
* </td>
* </tr>
* <tr>
* <td align="left">{@value #PROPERTY_STORAGE_PERIODIC_STATS}</td>
* <td align="left">
* Enables periodic logging of session factory statistics. Set to a
* positive number to enable. Default value is
* {@link #DEFAULT_PERIODIC_STATS_INTERVAL}.
* </td>
* </tr>
* <tr>
* <td align="left">{@value #PROPERTY_STORAGE_MEM_STATS}</td>
* <td align="left">
* Controls whether periodic statistics logging includes details on
* second-level cache memory usage. This is an expensive operation.
* {@link #PROPERTY_STORAGE_PERIODIC_STATS} must be enabled or this
* setting is ignored. Default value is {@value #DEFAULT_MEM_STATS}.
* </td>
* </tr>
* <tr>
* <td align="left">{@value #PROPERTY_STORAGE_CREATE_SCHEMA}</td>
* <td align="left">
* Controls Enki/Hibernate's behavior with respect to missing or invalid
* database schemas. See {@link #PROPERTY_STORAGE_CREATE_SCHEMA}.
* Defaults to {@value #DEFAULT_CREATE_SCHEMA}.
* </td>
* </tr>
* <tr>
* <td align="left">{@value #PROPERTY_STORAGE_TABLE_PREFIX}</td>
* <td align="left">
* Controls the table prefix used for all tables accessed by this
* repository instance. Defaults to no prefix. Extents create with
* different prefixes are ignored by this repository instance.
* </td>
* </tr>
* <tr>
* <td align="left">hibernate.*</td>
* <td align="left">
* All these properties are passed to Hibernate's {@link Configuration}
* without modification, except some connection-related properties.
* See {@link #PROPERTY_STORAGE_CONNECTION_DATASOURCE}. Note that the
* property {@value #PROPERTY_STORAGE_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE}
* controls batch fetch size for lazy associations.
* </td>
* </tr>
* </table>
*
* <p>Logging Notes. Session and transactions boundaries are logged at level
* {@link Level#FINE}. If level is set to {@link Level#FINEST}, stack traces
* are logged for each session and transaction boundary.
*
* @author Stephan Zuercher
*/
public class HibernateMDRepository
implements MDRepository, EnkiMDRepository,
EnkiChangeEventThread.ListenerSource
{
/**
* The name of the metamodel-specific Hibernate mapping file. Stored in
* the <code>META-INF/enki</code> directory of an Enki model JAR file.
*/
public static final String MAPPING_XML = "mapping.xml";
/**
* The name of a metamodel-specific Hibernate mapping file that contains
* only <database-object> entries for special indexes.
*/
public static final String INDEX_MAPPING_XML = "indexMapping.xml";
/**
* The name of the HibernateMDRepository metamodel provider DDL file.
* Stored in the <code>META-INF/enki</code> directory of an Enki
* model JAR file.
*/
public static final String PROVIDER_DDL = "provider.sql";
/**
* The name of the HibernateMDRepository metamodel creation DDL file.
* Stored in the <code>META-INF/enki</code> directory of an Enki
* model JAR file.
*/
public static final String MODEL_CREATE_DDL = "create.sql";
/**
* The name of the HibernateMDRepository metamodel deletion DDL file.
* Stored in the <code>META-INF/enki</code> directory of an Enki
* model JAR file.
*/
public static final String MODEL_DROP_DDL = "drop.sql";
/**
* Path to the resource that contains a Hibernate mapping file for
* persistent entities used across metamodels.
*/
public static final String HIBERNATE_STORAGE_MAPPING_XML =
"/org/eigenbase/enki/hibernate/storage/hibernate-storage-mapping.xml";
/**
* Configuration file property that contains the name of the
* {@link MetamodelInitializer} class used to initialize the metamodel.
*/
public static final String PROPERTY_MODEL_INITIALIZER =
"enki.model.initializer";
/**
* Configuration file property that indicates whether this model is a
* plug-in or a base model. Valid values are true or false.
*/
public static final String PROPERTY_MODEL_PLUGIN =
"enki.model.plugin";
/**
* Configuration file property that specifies a packaging version for
* the model's schema. This value may change from release to release.
* Compatibility between versions will be documented elsewhere.
*/
public static final String PROPERTY_MODEL_PACKAGE_VERSION =
"enki.model.packageVersion";
/**
* Current packaging version. The current packaging version is {@value}.
*/
public static final String PACKAGE_VERSION = "1.0";
/**
* Storage property that configures the JNDI name of the {@link DataSource}
* that Enki/Hibernate should use. If no DataSource exists with this
* name, Enki/Hibernate will attempt to create and bind one using the
* {@link #PROPERTY_STORAGE_CONNECTION_DRIVER_CLASS},
* {@link #PROPERTY_STORAGE_CONNECTION_URL},
* {@link #PROPERTY_STORAGE_CONNECTION_USERNAME},and
* {@link #PROPERTY_STORAGE_CONNECTION_PASSWORD} properties. If the driver
* class and URL properties are not set, Enki/Hibernate will assume that
* Hibernate-specific properties have been used to configure a database
* connection.
*
* Note that in the event that Enki/Hibernate creates and binds its own
* DataSource, following Hibernate properties will be modified or cleared:
* <ul>
* <li>hibernate.connection.datasource</li>
* <li>hibernate.connection.driver_class</li>
* <li>hibernate.connection.url</li>
* <li>hibernate.connection.username</li>
* <li>hibernate.connection.password</li>
* <li>hibernate.connection.pool_size</li>
* </ul>
*/
public static final String PROPERTY_STORAGE_CONNECTION_DATASOURCE =
"org.eigenbase.enki.hibernate.connection.datasource";
/**
* The default value for the
* {@link #PROPERTY_STORAGE_CONNECTION_DATASOURCE} property is {@value}.
*/
public static final String PROPERTY_STORAGE_DEFAULT_CONNECTION_DATASOURCE =
"java:ENKI_DATASOURCE";
/**
* Storage property containing the name of JDBC driver class to use for
* creating a {@link DataSource} object.
* See {@link #PROPERTY_STORAGE_CONNECTION_DATASOURCE}.
*/
public static final String PROPERTY_STORAGE_CONNECTION_DRIVER_CLASS =
"org.eigenbase.enki.hibernate.connection.driver_class";
/**
* Storage property containing the name of JDBC URL to use for
* creating a {@link DataSource} object.
* See {@link #PROPERTY_STORAGE_CONNECTION_DATASOURCE}.
*/
public static final String PROPERTY_STORAGE_CONNECTION_URL =
"org.eigenbase.enki.hibernate.connection.url";
/**
* Storage property containing the name of JDBC username to use for
* creating a {@link DataSource} object.
* See {@link #PROPERTY_STORAGE_CONNECTION_DATASOURCE}.
*/
public static final String PROPERTY_STORAGE_CONNECTION_USERNAME =
"org.eigenbase.enki.hibernate.connection.username";
/**
* Storage property containing the name of JDBC password to use for
* creating a {@link DataSource} object.
* See {@link #PROPERTY_STORAGE_CONNECTION_DATASOURCE}.
*/
public static final String PROPERTY_STORAGE_CONNECTION_PASSWORD =
"org.eigenbase.enki.hibernate.connection.password";
/**
* Storage property containing the maximum number of idle connections to
* keep open if Enki/Hibernate constructs its own DataSource.
* See {@link #PROPERTY_STORAGE_CONNECTION_DATASOURCE}.
*/
public static final String PROPERTY_STORAGE_CONNECTION_MAX_IDLE =
"org.eigenbase.enki.hibernate.connection.max_idle";
/**
* Default setting for the {@link #PROPERTY_STORAGE_CONNECTION_MAX_IDLE}
* storage property. The default value is {@value}.
*/
public static final int DEFAULT_CONNECTION_MAX_IDLE = 1;
/**
* Storage property JNDI prefix. When creating a {@link DataSource} any
* storage properties starting with this string are used to construct
* a JNDI {@link InitialContext}. These properties (excluding both
* {@link #PROPERTY_STORAGE_JNDI_INITIAL_CONTEXT_FACTORY_CLASS} and
* {@link #PROPERTY_STORAGE_JNDI_PROVIDER_URL}) are passed to the
* InitialContext constructor with the prefix stripped.
*
* Note: The prefix value does not contain the substring "hibernate.jndi"
* because Hibernate 3.1 mistakenly uses those values, while incorrectly
* assuming that "hibernate.jndi" appears at the start of the string.
*/
public static final String PROPERTY_STORAGE_JNDI_PREFIX =
"org.eigenbase.enki.hibernatejndi.";
/**
* Storage property specifying the name of the JNDI initial context factory
* class. Passed to the JNDI {@link InitialContext} constructor using
* the property name {@value javax.naming.Context#INITIAL_CONTEXT_FACTORY}.
*/
public static final String PROPERTY_STORAGE_JNDI_INITIAL_CONTEXT_FACTORY_CLASS =
PROPERTY_STORAGE_JNDI_PREFIX + "initial_context_factory_class";
/**
* Storage property specifying the name of the JNDI provider URL. Passed
* to the JNDI {@link InitialContext} constructor using the property name
* {@value javax.naming.Context#PROVIDER_URL}.
*/
public static final String PROPERTY_STORAGE_JNDI_PROVIDER_URL =
PROPERTY_STORAGE_JNDI_PREFIX + "provider_url";
/**
* Storage property that configures the behavior of implicit sessions.
* Values are converted to boolean via {@link Boolean#valueOf(String)}.
* If the value evaluates to true, implicit sessions are allowed (and are
* closed when the first transaction within the session is committed or
* rolled back).
*/
public static final String PROPERTY_STORAGE_ALLOW_IMPLICIT_SESSIONS =
"org.eigenbase.enki.hibernate.allowImplicitSessions";
/**
* Contains the default value for the
* {@link #PROPERTY_STORAGE_ALLOW_IMPLICIT_SESSIONS} storage property.
* The default is {@value}.
*/
public static final boolean DEFAULT_ALLOW_IMPLICIT_SESSIONS = false;
/**
* Storage property that configures whether sessions are tracked. Session
* tracking allows matching of the begin/end session API calls in the
* log file. If the value evaluates to true, sessions are tracked with
* identifiers that are unique within this repository instance.
*/
public static final String PROPERTY_STORAGE_TRACK_SESSIONS =
"org.eigenbase.enki.hibernate.trackSessions";
/**
* Contains the default value for the
* {@link #PROPERTY_STORAGE_TRACK_SESSIONS} storage property.
* The default is {@value}.
*/
public static final boolean DEFAULT_TRACK_SESSIONS = false;
/**
* Storage property that controls whether and how frequently the Hibernate
* session is flushed while inserting entires into the MOF ID/type lookup
* table. Defaults to the value of the
* {@value #PROPERTY_STORAGE_HIBERNATE_JDBC_BATCH_SIZE} property. Values
* less than or equal to 0 disable flushing.
*/
public static final String PROPERTY_STORAGE_TYPE_LOOKUP_FLUSH_SIZE =
"org.eigenbase.enki.hibernate.typeLookupFlushSize";
/**
* Hibernate property re-used as a storage property to control the default
* size of MOF ID/type mapping flushes during transaction commit in
* addition to its normal Hibernate behavior.
*/
public static final String PROPERTY_STORAGE_HIBERNATE_JDBC_BATCH_SIZE =
"hibernate.jdbc.batch_size";
/**
* Hibernate property re-used as a storage property to control lazy
* association batch size in addition to its normal Hibernate behavior.
*/
public static final String PROPERTY_STORAGE_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE =
"hibernate.default_batch_fetch_size";
/**
* Storage property that configures whether session factory statistics
* are periodically logged. Values of zero or less disable statistics
* logging. Larger values indicate the number of seconds between log
* messages. Default value is {@link #DEFAULT_PERIODIC_STATS_INTERVAL}.
*/
public static final String PROPERTY_STORAGE_PERIODIC_STATS =
"org.eigenbase.enki.hibernate.periodicStats";
/**
* Contains the default value for {@link #PROPERTY_STORAGE_PERIODIC_STATS}
* storage property. The default is {@value}.
*/
public static final int DEFAULT_PERIODIC_STATS_INTERVAL = 0;
/**
* Storage property that configures periodic session factory statistics
* logging to include information about the size (in bytes) of Hibernate
* caches. Computing cache memory size requires serializing all cached
* objects, which can be very slow. Valid values are true or false.
* Defaults to {@link #DEFAULT_MEM_STATS}.
* {@link #PROPERTY_STORAGE_PERIODIC_STATS} must be enabled for memory
* statistics logging to occur.
*/
public static final String PROPERTY_STORAGE_MEM_STATS =
"org.eigenbase.enki.hibernate.periodicStats.memStats";
/**
* Contains the default value of {@link #PROPERTY_STORAGE_MEM_STATS}.
* The default is {@value}.
*/
public static final boolean DEFAULT_MEM_STATS = false;
/**
* Storage property that controls whether Enki/Hibernate will create the
* necessary schema in its database. The following values are allowed:
*
* <table>
* <tr>
* <td>Value</td>
* <td>Description</td>
* </tr>
* <tr>
* <td>{@value #CREATE_SCHEMA_AUTO}</td>
* <td>Enki/Hibernate will validate the schema and then create or update
* it as necessary to match its model definitions.</td>
* </tr>
* <tr>
* <td>{@value #CREATE_SCHEMA_AUTO_VIEW}</td>
* <td>Like AUTO, but all-of-class and all-of-type views are created
* in addition to the storage tables.</td>
* </tr>
* <tr>
* <td>{@value #CREATE_SCHEMA_VIEW}</td>
* <td>Causes all-of-class and all-of-type views to be created.</td>
* </tr>
* <tr>
* <td>{@value #CREATE_SCHEMA_DISABLED}</td>
* <td>Enki/Hibernate will validate the schema, and if it does not match
* the model definition (extraneous tables and views are ignored),
* it will throw an exception.</td>
* </tr>
* <table>
*
* Defaults to {@link #DEFAULT_CREATE_SCHEMA}.
*/
public static final String PROPERTY_STORAGE_CREATE_SCHEMA =
"org.eigenbase.enki.hibernate.createSchema";
public static final String CREATE_SCHEMA_AUTO = "AUTO";
public static final String CREATE_SCHEMA_AUTO_VIEW = "AUTO_VIEW";
public static final String CREATE_SCHEMA_VIEW = "VIEW";
public static final String CREATE_SCHEMA_DISABLED = "DISABLED";
/**
* The default value of {@link #PROPERTY_STORAGE_CREATE_SCHEMA}.
* The default is {@value}.
*/
public static final String DEFAULT_CREATE_SCHEMA = "DISABLED";
/**
* Storage property that controls the table prefix used for tables in
* this repository's storage. efaults to {@link #DEFAULT_TABLE_PREFIX}.
*/
public static final String PROPERTY_STORAGE_TABLE_PREFIX =
"org.eigenbase.enki.hibernate.tablePrefix";
/**
* The default value of {@link #PROPERTY_STORAGE_TABLE_PREFIX}.
* The default is {@value}.
*/
public static final String DEFAULT_TABLE_PREFIX = "";
/**
* Identifier for the built-in MOF extent.
*/
public static final String MOF_EXTENT = "MOF";
private static final MdrSessionStack sessionStack = new MdrSessionStack();
private final ReadWriteLock txnLock;
private final AtomicInteger sessionCount;
private final AtomicInteger sessionIdGenerator;
/** Storage configuration properties. */
private final Properties storageProperties;
/** Configuration generator. */
private final HibernateConfigurator configurator;
/** Given default class loader, if any. */
private final ClassLoader classLoader;
/** Map of extent names to ExtentDescriptor instances. */
private final Map<String, ExtentDescriptor> extentMap;
/** Value of {@link #PROPERTY_STORAGE_TYPE_LOOKUP_FLUSH_SIZE}. */
final int typeLookupFlushSize;
/** Value of hibernate.default.batch_fetch_size. */
private final int defaultBatchFetchSize;
private final boolean allowImplicitSessions;
private final boolean trackSessions;
private final int periodicStatsInterval;
private final boolean logMemStats;
private final boolean createSchema;
private final boolean createViews;
/**
* Whether {@link #enableInterThreadSessions} has been called.
*/
private static boolean interThreadSessionsEnabled;
/**
* Only used when interThreadSessionsEnabled=true.
*/
private static final LinkedList<MdrSession> globalSessionStack
= new LinkedList<MdrSession>();
static final Logger log =
Logger.getLogger(HibernateMDRepository.class.getName());
/**
* Whether {@link #enableMultipleExtentsForSameModel} has been called.
*/
private boolean multipleExtentsEnabled;
private final DataSourceConfigurator dataSourceConfigurator;
private Timer periodicStatsTimer;
/** The Hibernate {@link SessionFactory} for this repository. */
private SessionFactory sessionFactory;
/** The {@link MofIdGenerator} for this repository. */
private MofIdGenerator mofIdGenerator;
/** The {@link EnkiChangeEventThread} for this repository. */
private EnkiChangeEventThread thread;
/**
* Map of {@link MDRChangeListener} instances to
* {@link EnkiMaskedMDRChangeListener} instances.
*/
private Map<MDRChangeListener, EnkiMaskedMDRChangeListener> listeners;
/** Map of unique class identifier to HibernateRefClass. */
private final HashMap<String, HibernateRefClass> classRegistry;
/** Map of unique association identifier to HibernateRefAssociation. */
private final HashMap<String, HibernateRefAssociation> assocRegistry;
/** The SQL dialect in use by the configured database. */
private Dialect sqlDialect;
/** The prefix for all tables in this repository. */
private final String tablePrefix;
private boolean previewDelete;
private ObjectName mbeanName;
public HibernateMDRepository(
List<Properties> modelProperties,
Properties storageProperties,
ClassLoader classLoader)
{
this.txnLock = new ReentrantReadWriteLock();
this.storageProperties = storageProperties;
this.classLoader = classLoader;
this.extentMap = new HashMap<String, ExtentDescriptor>();
this.thread = null;
this.listeners =
new IdentityHashMap<MDRChangeListener, EnkiMaskedMDRChangeListener>();
this.classRegistry = new HashMap<String, HibernateRefClass>();
this.assocRegistry = new HashMap<String, HibernateRefAssociation>();
int jdbcBatchSize =
readStorageProperty(
PROPERTY_STORAGE_HIBERNATE_JDBC_BATCH_SIZE, -1, Integer.class);
this.typeLookupFlushSize =
readStorageProperty(
PROPERTY_STORAGE_TYPE_LOOKUP_FLUSH_SIZE,
jdbcBatchSize,
Integer.class);
this.defaultBatchFetchSize =
readStorageProperty(
PROPERTY_STORAGE_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE,
-1,
Integer.class);
this.allowImplicitSessions =
readStorageProperty(
PROPERTY_STORAGE_ALLOW_IMPLICIT_SESSIONS,
DEFAULT_ALLOW_IMPLICIT_SESSIONS,
Boolean.class);
this.trackSessions =
readStorageProperty(
PROPERTY_STORAGE_TRACK_SESSIONS,
DEFAULT_TRACK_SESSIONS,
Boolean.class);
this.periodicStatsInterval =
readStorageProperty(
PROPERTY_STORAGE_PERIODIC_STATS,
DEFAULT_PERIODIC_STATS_INTERVAL,
Integer.class);
this.logMemStats =
readStorageProperty(
PROPERTY_STORAGE_MEM_STATS,
DEFAULT_MEM_STATS,
Boolean.class);
String createSchemaSetting =
readStorageProperty(
PROPERTY_STORAGE_CREATE_SCHEMA,
DEFAULT_CREATE_SCHEMA,
String.class).toUpperCase();
if (createSchemaSetting.equals(CREATE_SCHEMA_AUTO)) {
this.createSchema = true;
this.createViews = false;
} else if (createSchemaSetting.equals(CREATE_SCHEMA_AUTO_VIEW)) {
this.createSchema = true;
this.createViews = true;
} else if (createSchemaSetting.equals(CREATE_SCHEMA_VIEW)) {
this.createSchema = false;
this.createViews = true;
} else {
if (!createSchemaSetting.equals(CREATE_SCHEMA_DISABLED)) {
log.warning(
"Value '" + createSchemaSetting + "' for property "
+ PROPERTY_STORAGE_CREATE_SCHEMA
+ " is invalid; defaulting to " + CREATE_SCHEMA_DISABLED);
}
this.createSchema = false;
this.createViews = false;
}
this.tablePrefix =
readStorageProperty(
PROPERTY_STORAGE_TABLE_PREFIX,
DEFAULT_TABLE_PREFIX,
String.class);
// Initialize our data source as necessary.
this.dataSourceConfigurator =
new DataSourceConfigurator(storageProperties);
this.dataSourceConfigurator.initDataSource();
this.configurator =
new HibernateConfigurator(storageProperties, modelProperties);
initModelExtent(MOF_EXTENT, false);
initStorage();
this.sessionCount = new AtomicInteger(0);
this.sessionIdGenerator = new AtomicInteger(0);
try {
mbeanName =
EnkiMBeanUtil.registerRepositoryMBean(
HibernateMDRepositoryMBeanFactory.create(this));
} catch (JMException e) {
throw new ProviderInstantiationException(
"Unable to register mbean", e);
}
}
private <T> T readStorageProperty(
String name, T defaultValue, Class<T> cls)
{
return PropertyUtil.readStorageProperty(
storageProperties,
log,
name,
defaultValue,
cls);
}
public void finalize()
{
if (mbeanName != null) {
EnkiMBeanUtil.unregisterRepositoryMBean(mbeanName);
}
}
public MdrProvider getProviderType()
{
return MdrProvider.ENKI_HIBERNATE;
}
public EnkiMDSession detachSession()
{
if (sessionStack.isEmpty()) {
return null;
}
MdrSession mdrSession = sessionStack.pop();
return mdrSession;
}
public void reattachSession(EnkiMDSession session)
{
MdrSession existingSession = sessionStack.peek(this);
if (existingSession != null) {
throw new EnkiHibernateException(
"must end current session before re-attach");
}
if (session == null) {
// nothing to do
return;
}
if (!(session instanceof MdrSession)) {
throw new EnkiHibernateException(
"invalid session object; wrong type");
}
sessionStack.push((MdrSession)session);
}
public void beginSession()
{
MdrSession mdrSession = sessionStack.peek(this);
if (mdrSession != null) {
logStack(
Level.FINE,
"begin re-entrant repository session",
mdrSession.sessionId);
mdrSession.refCount++;
return;
}
beginSessionImpl(false);
}
private MdrSession beginSessionImpl(boolean implicit)
{
int sessionId = -1;
if (trackSessions) {
sessionId = sessionIdGenerator.incrementAndGet();
}
if (implicit) {
if (!allowImplicitSessions) {
throw new InternalMdrError("implicit session");
}
logStack(
Level.WARNING,
"begin implicit repository session",
sessionId);
} else {
logStack(Level.FINE, "begin repository session", sessionId);
}
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.COMMIT);
MdrSession mdrSession = new MdrSession(session, implicit, sessionId);
mdrSession.refCount++;
sessionStack.push(mdrSession);
int count = sessionCount.incrementAndGet();
assert(count > 0);
return mdrSession;
}
public void endSession()
{
MdrSession mdrSession = sessionStack.peek(this);
if (mdrSession == null) {
throw new EnkiHibernateException(
"session never opened/already closed");
}
if (--mdrSession.refCount != 0) {
logStack(
Level.FINE,
"end re-entrant repository session",
mdrSession.sessionId);
return;
}
endSessionImpl(mdrSession);
}
private void endSessionImpl(MdrSession mdrSession)
{
if (mdrSession.refCount != 0) {
throw new InternalMdrError(
"bad ref count: " + mdrSession.refCount);
}
LinkedList<Context> contexts = mdrSession.context;
if (!contexts.isEmpty()) {
// More than 1 txn context implies at least one explicit txn.
if (contexts.size() > 1 || !contexts.getFirst().isImplicit) {
throw new EnkiHibernateException(
"attempted to close session while txn remains open: "
+ contexts.size());
}
// End the remaining implicit txn
endTransImpl(false);
}
if (mdrSession.isImplicit) {
logStack(
Level.WARNING,
"end implicit repository session",
mdrSession.sessionId);
} else {
logStack(
Level.FINE, "end repository session", mdrSession.sessionId);
}
mdrSession.close();
sessionStack.pop();
int count = sessionCount.decrementAndGet();
assert(count >= 0);
}
/**
* Turns on inter-thread session mode. By default (with this mode
* disabled), each thread gets its own session stack. Enabling
* inter-thread sessions causes all threads to share a common session stack
* (with locking disabled at the Enki level, implying that the application
* should take care of its own synchronization around Enki). If this
* method is called at all, it should be called before the first session
* is created. This method has global effect on all repository instances.
*
* @param enabled true to enable this mode
*
* @deprecated This is an experimental mode and is likely to
* be removed or replaced in the future.
*/
@Deprecated
public static void enableInterThreadSessions(boolean enabled)
{
interThreadSessionsEnabled = enabled;
}
/**
* Turns on the ability to create multiple instance extents for
* the same model extent. By default, this is disabled since
* most of the necessary support doesn't actually exist yet.
* In particular, objects don't know which extent they are part of,
* and neither do class instances, so methods such as
* {@link RefClass#refAllOfClass} will return object instances
* from all extents sharing the same model.
*
* @deprecated This is an experimental mode and is likely to
* become the default in the future once the necessary
* support is working, at which time this method will no
* longer be necessary.
*/
@Deprecated
public void enableMultipleExtentsForSameModel()
{
multipleExtentsEnabled = true;
}
public void beginTrans(boolean write)
{
beginTransImpl(write, false);
}
private Context beginTransImpl(boolean write, boolean implicit)
{
assert(!write || !implicit): "Cannot support implicit write txn";
if (log.isLoggable(Level.FINEST)) {
logStack(
Level.FINEST,
"begin txn; "
+ (write ? "write; " : "read; ")
+ (implicit ? "implicit" : "explicit"));
}
MdrSession mdrSession = sessionStack.peek(this);
if (mdrSession == null) {
mdrSession = beginSessionImpl(true);
}
if (implicit) {
log.fine("begin implicit repository transaction");
} else {
log.fine("begin repository transaction");
}
LinkedList<Context> contexts = mdrSession.context;
// Nested txns are okay, but the outermost txn is the only one that
// commits/rollsback. So bar writes nested in explicit reads.
boolean isCommitter = false;
boolean beginTrans = false;
if (contexts.isEmpty()) {
isCommitter = true;
beginTrans = true;
} else {
isCommitter = contexts.getLast().isImplicit;
}
if (write && !isCommitter && !isNestedWriteTransaction(mdrSession)) {
throw new EnkiHibernateException(
"cannot start write transaction within read transaction");
}
Transaction trans;
if (beginTrans) {
if (write) {
mdrSession.obtainWriteLock();
} else {
mdrSession.obtainReadLock();
}
trans = mdrSession.session.beginTransaction();
} else {
trans = contexts.getLast().transaction;
}
Context context = new Context(trans, write, implicit, isCommitter);
contexts.add(context);
if (write) {
mdrSession.containsWrites = true;
}
if (write) {
enqueueBeginTransEvent(mdrSession);
}
return context;
}
public void endTrans()
{
endTrans(false);
}
public void endTrans(boolean rollback)
{
MdrSession mdrSession = endTransImpl(rollback);
if (mdrSession.isImplicit && mdrSession.context.isEmpty()) {
mdrSession.refCount
endSessionImpl(mdrSession);
}
}
private MdrSession endTransImpl(boolean rollback)
{
if (log.isLoggable(Level.FINEST)) {
logStack(
Level.FINEST,
"end txn; "
+ (rollback ? "rollback" : "commit"));
}
MdrSession mdrSession = sessionStack.peek(this);
if (mdrSession == null) {
throw new EnkiHibernateException(
"No repository session associated with this thread");
}
LinkedList<Context> contexts = mdrSession.context;
if (contexts.isEmpty()) {
throw new EnkiHibernateException(
"No repository transactions associated with this thread");
}
Context context = contexts.removeLast();
if (context.isImplicit) {
log.fine("end implicit repository transaction");
} else {
log.fine("end repository transaction");
}
if (!context.isCommitter) {
// If any txn in the nested stack rolled back, then the outermost
// txn rolls back even if the user requests commit.
if (rollback || context.forceRollback) {
contexts.getLast().forceRollback = true;
}
return mdrSession;
}
Transaction txn = context.transaction;
if (context.isWrite) {
enqueueEndTransEvent(mdrSession);
}
try {
// Note that even if "commit" is requested, we'll rollback if no
// writing was possible.
if (rollback || context.forceRollback) {
txn.rollback();
fireCanceledChanges(mdrSession);
if (mdrSession.containsWrites) {
mdrSession.session.clear();
mdrSession.reset();
}
// Throw this after the rollback has happened.
if (rollback && !context.isWrite) {
throw new EnkiHibernateException(
"Cannot rollback read transactions");
}
} else {
try {
Session session = mdrSession.session;
if (mdrSession.containsWrites) {
session.flush();
if (!mdrSession.mofIdDeleteSet.isEmpty()) {
// Update enki type mapping
Query query =
session.getNamedQuery("TypeMappingDeleteByMofId");
// Do this in chunks or else feel the wrath of
int flushSize = typeLookupFlushSize;
if (flushSize <= 0) {
flushSize = 100;
}
List<Long> chunk = new ArrayList<Long>();
for(Long mofId: mdrSession.mofIdDeleteSet) {
chunk.add(mofId);
if (chunk.size() >= flushSize) {
query.setParameterList("mofIds", chunk);
query.executeUpdate();
chunk.clear();
}
}
if (!chunk.isEmpty()) {
query.setParameterList("mofIds", chunk);
query.executeUpdate();
chunk.clear();
}
mdrSession.mofIdCreateMap.keySet().removeAll(
mdrSession.mofIdDeleteSet);
mdrSession.mofIdDeleteSet.clear();
}
if (!mdrSession.mofIdCreateMap.isEmpty()) {
int i = 0;
int flushSize = typeLookupFlushSize;
boolean flush = flushSize > 0;
for(Map.Entry<Long, Class<? extends RefObject>> entry:
mdrSession.mofIdCreateMap.entrySet())
{
if (flush && i++ % flushSize == 0) {
session.flush();
session.clear();
}
MofIdTypeMapping mapping = new MofIdTypeMapping();
mapping.setMofId(entry.getKey());
mapping.setTablePrefix(tablePrefix);
mapping.setTypeName(entry.getValue().getName());
mdrSession.session.save(mapping);
}
mdrSession.mofIdCreateMap.clear();
}
}
// TODO: check for constraint violations
if (false) {
ArrayList<String> constraintErrors =
new ArrayList<String>();
boolean foundConstraintError = false;
if (foundConstraintError) {
txn.rollback();
throw new HibernateConstraintViolationException(
constraintErrors);
}
}
if (!mdrSession.containsWrites) {
txn.rollback();
} else {
txn.commit();
}
fireChanges(mdrSession);
} catch(HibernateException e) {
fireCanceledChanges(mdrSession);
throw e;
} finally {
mdrSession.reset();
}
}
} finally {
mdrSession.releaseLock();
}
if (!contexts.isEmpty()) {
if (contexts.size() != 1) {
throw new InternalMdrError(
"ended nested txn with multiple containers");
}
Context implicitContext = contexts.getFirst();
if (!implicitContext.isImplicit) {
throw new InternalMdrError(
"ended nested txn but containing txn is not implicit");
}
// Start a new transaction for the containing implicit read.
implicitContext.transaction =
mdrSession.session.beginTransaction();
mdrSession.containsWrites = false;
}
return mdrSession;
}
public RefPackage createExtent(String name)
throws CreationFailedException
{
return createExtent(name, null, null);
}
public RefPackage createExtent(String name, RefObject metaPackage)
throws CreationFailedException
{
return createExtent(name, metaPackage, null);
}
public RefPackage createExtent(
String name,
RefObject metaPackage,
RefPackage[] existingInstances)
throws CreationFailedException
{
synchronized(extentMap) {
ExtentDescriptor extentDesc = extentMap.get(name);
if (extentDesc != null) {
throw new EnkiCreationFailedException(
"Extent '" + name + "' already exists");
}
if (!multipleExtentsEnabled && (metaPackage != null)) {
ModelDescriptor modelDesc = findModelDescriptor(metaPackage);
for (ExtentDescriptor ed : extentMap.values()) {
if (ed.modelDescriptor == modelDesc) {
throw new EnkiCreationFailedException(
"Metamodel '" + modelDesc.name
+ "' has already been instantiated");
}
}
}
enqueueEvent(
getMdrSession(),
new ExtentEvent(
this,
ExtentEvent.EVENT_EXTENT_CREATE,
name,
metaPackage,
Collections.unmodifiableCollection(
new ArrayList<String>(extentMap.keySet())),
true));
try {
extentDesc =
createExtentStorage(name, metaPackage, existingInstances);
return extentDesc.extent;
}
catch(ProviderInstantiationException e) {
throw new EnkiCreationFailedException(
"could not create extent '" + name + "'", e);
}
}
}
public void dropExtentStorage(String extent) throws EnkiDropFailedException
{
synchronized(extentMap) {
ExtentDescriptor extentDesc = extentMap.get(extent);
if (extentDesc == null) {
return;
}
dropExtentStorage(extentDesc);
}
}
public void dropExtentStorage(RefPackage refPackage)
throws EnkiDropFailedException
{
synchronized(extentMap) {
for(ExtentDescriptor extentDesc: extentMap.values()) {
if (extentDesc.extent.equals(refPackage)) {
dropExtentStorage(extentDesc);
return;
}
}
}
}
private void dropExtentStorage(ExtentDescriptor extentDesc)
throws EnkiDropFailedException
{
MdrSession mdrSession = getMdrSession();
if (!mdrSession.context.isEmpty()) {
throw new EnkiHibernateException(
"No repository transactions may be open while dropping extent storage");
}
enqueueEvent(
mdrSession,
new ExtentEvent(
this,
ExtentEvent.EVENT_EXTENT_DELETE,
extentDesc.name,
null,
Collections.unmodifiableCollection(
new ArrayList<String>(extentMap.keySet()))));
extentMap.remove(extentDesc.name);
Session session = mdrSession.session;
Transaction trans = session.beginTransaction();
boolean rollback = true;
try {
HibernateMassDeletionUtil msdu =
new HibernateMassDeletionUtil(this);
msdu.massDeleteAll(session, extentDesc.extent);
Query query = session.getNamedQuery("ExtentByName");
query.setString(0, extentDesc.name);
Extent dbExtent = (Extent)query.uniqueResult();
session.delete(dbExtent);
trans.commit();
fireChanges(mdrSession);
rollback = false;
} catch(HibernateException e) {
throw new EnkiDropFailedException(
"Could not delete extent table entry", e);
} finally {
try {
if (rollback) {
trans.rollback();
fireCanceledChanges(mdrSession);
}
} finally {
mdrSession.reset();
}
}
if (createSchema) {
// If we're in charge of schema creation, we also do schema
// deletion.
dropModelStorage(extentDesc.modelDescriptor);
}
}
public int getBatchSize()
{
return defaultBatchFetchSize;
}
public RefObject getByMofId(String mofId, RefClass cls)
{
Long mofIdLong = MofIdUtil.parseMofIdStr(mofId);
return getByMofId(mofIdLong, cls, mofId);
}
public RefObject getByMofId(long mofId, RefClass cls)
{
return getByMofId(mofId, cls, null);
}
public Collection<RefObject> getByMofId(List<Long> mofIds, RefClass cls)
{
if (mofIds.isEmpty()) {
return Collections.emptyList();
} else if (mofIds.size() == 1) {
RefObject obj = getByMofId(mofIds.get(0), cls);
if (obj == null) {
return Collections.emptyList();
}
return Collections.singletonList(obj);
}
HibernateRefClass hibRefCls = (HibernateRefClass)cls;
Class<? extends RefObject> instanceClass =
hibRefCls.getInstanceClass();
MdrSession mdrSession = getMdrSession();
// We use a set here because certain types of objects (those with
// an attribute of type collection-of-primitive) cause Hibernate to
// return duplicate results. It performs a left outer join to load
// the objects with their collections and fails to return each
// instance only once. Probably a Hibernate bug.
Set<RefObject> result = new HashSet<RefObject>();
List<Long> criteriaMofIdList = new ArrayList<Long>();
for(Long mofId: mofIds) {
// Ignore deleted objects.
if (mdrSession.mofIdDeleteSet.contains(mofId)) {
continue;
}
// Handle cached objects: this may find some objects that are
// also known to mdrSession.mofIdCreateMap, but should be faster.
RefObject obj = (RefObject)lookupByMofId(mdrSession, mofId);
if (obj != null) {
result.add(obj);
continue;
}
// Handle objects that are new in this txn
Class<? extends RefObject> c =
mdrSession.mofIdCreateMap.get(mofId);
if (c != null) {
result.add(getByMofId(mdrSession, mofId, c));
continue;
}
// Depend on Hibernate to only query for those objects that are
// not already in the session.
criteriaMofIdList.add(mofId);
}
if (!criteriaMofIdList.isEmpty()) {
Criteria criteria =
getCurrentSession().createCriteria(instanceClass)
.add(Restrictions.in("id", criteriaMofIdList))
.setCacheable(true);
for(RefObjectBase rob:
GenericCollections.asTypedList(
criteria.list(), RefObjectBase.class))
{
result.add(rob);
storeByMofId(mdrSession, rob.getMofId(), rob);
}
}
return result;
}
/**
* Loads a RefObject by MOF ID. The string version of the MOF ID is
* optional, but if non-null must match <code>mofIdLong</code>. If
* null, mofIdLong is converted to a string if needed (it usually is not).
*
* @param mofIdLong MOF ID of the object to load
* @param cls {@link RefClass} representing the object's concrete type
* @param mofId optional string version of MOF ID
* @return the object requested or null if not found or already deleted
*/
private RefObject getByMofId(Long mofIdLong, RefClass cls, String mofId)
{
MdrSession mdrSession = getMdrSession();
RefBaseObject cachedResult =
(RefBaseObject)lookupByMofId(mdrSession, mofIdLong);
if (cachedResult != null) {
return convertToRefObject(cls, cachedResult);
}
if (isMetamodelMofId(mofIdLong)) {
if (mofId == null) {
mofId = MofIdUtil.makeMofIdStr(mofIdLong);
}
RefBaseObject result = findMetaByMofId(mofId);
return convertToRefObject(cls, result);
}
if (mdrSession.mofIdDeleteSet.contains(mofIdLong)) {
return null;
}
Class<? extends RefObject> instanceClass =
((HibernateRefClass)cls).getInstanceClass();
return getByMofId(mdrSession, mofIdLong, instanceClass);
}
private RefObject getByMofId(
MdrSession mdrSession,
Long mofIdLong,
Class<? extends RefObject> instanceClass)
{
Session session = mdrSession.session;
RefObject result = (RefObject)session.get(instanceClass, mofIdLong);
if (result != null) {
storeByMofId(mdrSession, mofIdLong, result);
}
return result;
}
private boolean isMetamodelMofId(long mofId)
{
return (mofId & MetamodelInitializer.METAMODEL_MOF_ID_MASK) != 0;
}
private RefObject convertToRefObject(
RefClass cls,
RefBaseObject cachedResult)
{
if (!(cachedResult instanceof RefObject)) {
return null;
}
RefObject cachedResultObj = (RefObject)cachedResult;
if (!cachedResultObj.refClass().equals(cls)) {
return null;
}
return cachedResultObj;
}
public RefBaseObject getByMofId(String mofId)
{
MdrSession mdrSession = getMdrSession();
Long mofIdLong = MofIdUtil.parseMofIdStr(mofId);
RefBaseObject cachedResult = lookupByMofId(mdrSession, mofIdLong);
if (cachedResult != null) {
return cachedResult;
}
RefBaseObject result = null;
if (isMetamodelMofId(mofIdLong)) {
result = findMetaByMofId(mofId);
} else {
if (mdrSession.mofIdDeleteSet.contains(mofIdLong)) {
return null;
}
if (mdrSession.mofIdCreateMap.containsKey(mofIdLong)) {
Class<? extends RefObject> cls =
mdrSession.mofIdCreateMap.get(mofIdLong);
return getByMofId(mdrSession, mofIdLong, cls);
}
Session session = mdrSession.session;
Query query = session.getNamedQuery("TypeMappingByMofId");
query.setLong("mofId", mofIdLong);
MofIdTypeMapping mapping = (MofIdTypeMapping)query.uniqueResult();
if (mapping != null) {
query =
session.getNamedQuery(
mapping.getTypeName() + "." +
HibernateMappingHandler.QUERY_NAME_BYMOFID);
query.setLong("mofId", mofIdLong);
result = (RefBaseObject)query.uniqueResult();
}
}
if (result != null) {
storeByMofId(mdrSession, mofIdLong, result);
}
return result;
}
private RefBaseObject findMetaByMofId(String mofId)
{
synchronized(extentMap) {
for(ExtentDescriptor extentDesc: extentMap.values()) {
// Only search in metamodels
if (extentDesc.modelDescriptor == null ||
extentDesc.modelDescriptor.name.equals(MOF_EXTENT))
{
RefBaseObject result =
extentDesc.initializer.getByMofId(mofId);
if (result != null) {
return result;
}
}
}
}
return null;
}
private RefBaseObject lookupByMofId(MdrSession mdrSession, Long mofId)
{
return softCacheLookup(mdrSession.byMofIdCache, mofId);
}
private <V, K> V softCacheLookup(Map<K, SoftReference<V>> cache, K key)
{
SoftReference<V> ref = cache.get(key);
if (ref == null) {
return null;
}
V value = ref.get();
if (value == null) {
cache.remove(key);
}
return value;
}
private <K, V> void softCacheStore(
Map<K, SoftReference<V>> cache, K key, V value)
{
cache.put(key, new SoftReference<V>(value));
}
private void storeByMofId(
MdrSession mdrSession, Long mofId, RefBaseObject obj)
{
softCacheStore(mdrSession.byMofIdCache, mofId, obj);
}
public void delete(Collection<RefObject> objects)
{
if (objects.isEmpty()) {
return;
}
// TODO: should also check for attribute modifications
MdrSession session = getMdrSession();
if (!session.mofIdCreateMap.isEmpty() ||
!session.mofIdDeleteSet.isEmpty())
{
throw new EnkiHibernateException(
"mass deletion API may not be used in transaction with pending modifications");
}
new HibernateMassDeletionUtil(this).massDelete(objects);
}
public void previewRefDelete(RefObject obj)
{
previewDelete = true;
try {
obj.refDelete();
} finally {
previewDelete = false;
}
}
public boolean supportsPreviewRefDelete()
{
return true;
}
public boolean inPreviewDelete()
{
return previewDelete;
}
public void deleteExtentDescriptor(RefPackage refPackage)
{
synchronized(extentMap) {
for(ExtentDescriptor extentDesc: extentMap.values()) {
if (extentDesc.extent.equals(refPackage)) {
deleteExtentDescriptor(extentDesc);
return;
}
}
}
}
private void deleteExtentDescriptor(ExtentDescriptor extentDesc)
{
extentMap.remove(extentDesc.name);
checkTransaction(true);
Session session = getCurrentSession();
Query query = session.getNamedQuery("ExtentByName");
query.setString(0, extentDesc.name);
Extent extent = (Extent)query.uniqueResult();
session.delete(extent);
}
public RefPackage getExtent(String name)
{
synchronized(extentMap) {
ExtentDescriptor extentDesc = extentMap.get(name);
if (extentDesc == null) {
return null;
}
assert(
extentDesc.modelDescriptor != null ||
extentDesc.name.equals(MOF_EXTENT));
return extentDesc.extent;
}
}
public String[] getExtentNames()
{
synchronized(extentMap) {
return extentMap.keySet().toArray(new String[extentMap.size()]);
}
}
public Dialect getSqlDialect()
{
return sqlDialect;
}
public void shutdown()
{
log.info("repository shut down");
int count = sessionCount.get();
if (count != 0) {
throw new EnkiHibernateException(
"cannot shutdown while " + count + " session(s) are open");
}
EnkiMBeanUtil.unregisterRepositoryMBean(mbeanName);
mbeanName = null;
synchronized(listeners) {
listeners.clear();
}
synchronized(extentMap) {
if (sessionFactory != null) {
try {
thread.shutdown();
}
catch(InterruptedException e) {
log.log(
Level.SEVERE,
"EnkiChangeEventThread interrupted on shutdown",
e);
}
stopPeriodicStats();
if (sessionFactory.getStatistics().isStatisticsEnabled()) {
sessionFactory.getStatistics().logSummary();
}
try {
sessionFactory.close();
sessionFactory = null;
classRegistry.clear();
assocRegistry.clear();
} finally {
dataSourceConfigurator.close();
}
}
}
}
public void addListener(MDRChangeListener listener)
{
addListener(listener, MDRChangeEvent.EVENTMASK_ALL);
}
public void addListener(MDRChangeListener listener, int mask)
{
synchronized(listeners) {
EnkiMaskedMDRChangeListener maskedListener =
listeners.get(listener);
if (maskedListener != null) {
maskedListener.add(mask);
return;
}
maskedListener = new EnkiMaskedMDRChangeListener(listener, mask);
listeners.put(listener, maskedListener);
}
}
public void removeListener(MDRChangeListener listener)
{
synchronized(listeners) {
listeners.remove(listener);
}
}
public void removeListener(MDRChangeListener listener, int mask)
{
synchronized(listeners) {
EnkiMaskedMDRChangeListener maskedListener =
listeners.get(listener);
if (maskedListener != null) {
boolean removedAll = maskedListener.remove(mask);
if (removedAll) {
listeners.remove(listener);
}
}
}
}
// Implement EnkiChangeEventThread.ListenerSource
public Collection<EnkiMaskedMDRChangeListener> getListeners()
{
synchronized(listeners) {
return new ArrayList<EnkiMaskedMDRChangeListener>(
listeners.values());
}
}
// Implement EnkiMDRepository
public boolean isExtentBuiltIn(String name)
{
synchronized(extentMap) {
ExtentDescriptor extentDesc = extentMap.get(name);
if (extentDesc == null) {
return false;
}
assert(extentDesc.modelDescriptor != null);
return extentDesc.builtIn;
}
}
// Implement EnkiMDRepository
public String getAnnotation(String extentName)
{
synchronized(extentMap) {
ExtentDescriptor extentDesc = extentMap.get(extentName);
if (extentDesc == null) {
return null;
}
return extentDesc.annotation;
}
}
// Implement EnkiMDRepository
public void setAnnotation(String extentName, String annotation)
{
checkTransaction(true);
synchronized(extentMap) {
ExtentDescriptor extentDesc = extentMap.get(extentName);
if (extentDesc == null) {
throw new EnkiHibernateException(
"No such extent: " + extentName);
}
extentDesc.annotation = annotation;
Query q =
getMdrSession().session.getNamedQuery("ExtentSetAnnotation");
q.setString("annotation", annotation);
q.setString("extentName", extentName);
int rows = q.executeUpdate();
if (rows != 1) {
throw new EnkiHibernateException(
"incorrect row count on extent update: " + rows);
}
}
}
// Implement EnkiMDRepository
public ClassLoader getDefaultClassLoader()
{
return classLoader;
}
// Implement EnkiMDRepository
public void backupExtent(String extentName, OutputStream stream)
throws EnkiBackupFailedException
{
checkTransaction(true);
ExtentDescriptor extentDesc;
synchronized(extentMap) {
extentDesc = extentMap.get(extentName);
if (extentDesc == null) {
throw new EnkiBackupFailedException(
"No such extent: " + extentName);
}
}
new HibernateBackupRestoreUtil(this).backup(extentDesc, stream);
}
// Implement EnkiMDRepository
public void restoreExtent(
String extentName,
String metaPackageExtentName,
String metaPackageName,
InputStream stream)
throws EnkiRestoreFailedException
{
checkTransaction(true);
ExtentDescriptor extentDesc;
synchronized (extentMap) {
extentDesc = extentMap.get(extentName);
if (extentDesc != null) {
if (!extentDesc.modelDescriptor.name.equals(metaPackageExtentName))
{
throw new EnkiRestoreFailedException(
"Extent '"
+ extentName
+ "' already exists but has a different metamodel extent: "
+ extentDesc.modelDescriptor.name);
}
} else {
RefPackage metaPackage = getExtent(metaPackageExtentName);
try {
createExtent(extentName, metaPackage.refMetaObject());
} catch(CreationFailedException e) {
throw new EnkiRestoreFailedException(e);
}
extentDesc = extentMap.get(extentName);
assert(extentDesc != null);
}
}
new HibernateBackupRestoreUtil(this).restore(
extentDesc,
stream);
}
// Implement EnkiMDRepository
@Deprecated
public void setRestoreExtentXmiFilter(Class<? extends InputStream> cls)
{
// Ignored
}
public SessionFactory getSessionFactory()
{
return sessionFactory;
}
public Properties getStorageProperties()
{
Properties props = new Properties();
props.putAll(storageProperties);
return props;
}
public String getTablePrefix()
{
return tablePrefix;
}
private MdrSession getMdrSession()
{
MdrSession session = sessionStack.peek(this);
if (session != null) {
return session;
}
return beginSessionImpl(true);
}
private Context getContext()
{
MdrSession session = getMdrSession();
if (session.context.isEmpty()) {
return beginTransImpl(false, true);
}
return session.context.getLast();
}
public static HibernateMDRepository getCurrentRepository()
{
MdrSession session = sessionStack.peek();
if (session == null) {
throw new EnkiHibernateException(
"No current session on this thread");
}
return session.getRepos();
}
public Session getCurrentSession()
{
return getMdrSession().session;
}
public void checkTransaction(boolean requireWrite)
{
if (requireWrite) {
MdrSession session = getMdrSession();
if (!isNestedWriteTransaction(session)) {
throw new EnkiHibernateException(
"Operation requires write transaction");
}
} else {
// Make sure a txn exists.
getContext();
}
}
private boolean isNestedWriteTransaction(MdrSession session)
{
LinkedList<Context> contexts = session.context;
ListIterator<Context> iter = contexts.listIterator(contexts.size());
while(iter.hasPrevious()) {
Context context = iter.previous();
if (context.isWrite) {
return true;
}
}
return false;
}
public MofIdGenerator getMofIdGenerator()
{
return getMdrSession().getMofIdGenerator();
}
@SuppressWarnings("unchecked")
public Collection<?> allOfType(HibernateRefClass cls, String queryName)
{
MdrSession mdrSession = getMdrSession();
checkTransaction(false);
Collection<?> simpleResult = mdrSession.allOfTypeCache.get(cls);
if (simpleResult == null) {
Session session = getCurrentSession();
Query query = session.getNamedQuery(queryName);
simpleResult = query.list();
mdrSession.allOfTypeCache.put(cls, simpleResult);
}
Set<RefObject> result = new HashSet<RefObject>();
for(Object obj: simpleResult) {
RefObjectBase b = (RefObjectBase)obj;
if (!mdrSession.mofIdDeleteSet.contains(b.getMofId())) {
result.add(b);
}
}
Class<?> ifaceClass = cls.getInterfaceClass();
for(Map.Entry<Long, Class<? extends RefObject>> e:
mdrSession.mofIdCreateMap.entrySet())
{
Class<? extends RefObject> createdCls = e.getValue();
if (ifaceClass.isAssignableFrom(createdCls)) {
result.add(getByMofId(mdrSession, e.getKey(), createdCls));
}
}
return Collections.unmodifiableSet(result);
}
@SuppressWarnings("unchecked")
public Collection<?> allOfClass(HibernateRefClass cls, String queryName)
{
MdrSession mdrSession = getMdrSession();
checkTransaction(false);
Collection<?> simpleResult= mdrSession.allOfClassCache.get(cls);
if (simpleResult == null) {
Session session = getCurrentSession();
Query query = session.getNamedQuery(queryName);
simpleResult = query.list();
mdrSession.allOfClassCache.put(cls, simpleResult);
}
Set<RefObject> result = new HashSet<RefObject>();
for(Object obj: simpleResult) {
RefObjectBase b = (RefObjectBase)obj;
if (!mdrSession.mofIdDeleteSet.contains(b.getMofId())) {
result.add(b);
}
}
Class<? extends RefObject> instanceClass = cls.getInstanceClass();
for(Map.Entry<Long, Class<? extends RefObject>> e:
mdrSession.mofIdCreateMap.entrySet())
{
if (instanceClass.isAssignableFrom(e.getValue())) {
result.add(getByMofId(e.getKey(), cls));
}
}
return Collections.unmodifiableSet(result);
}
/**
* Find the identified {@link HibernateRefClass}.
*
* @param uid unique {@link HibernateRefClass} identifier
* @return {@link HibernateRefClass} associated with UID
* @throws InternalJmiError if the class is not found
*/
public HibernateRefClass findRefClass(String uid)
{
HibernateRefClass refClass = classRegistry.get(uid);
if (refClass == null) {
throw new InternalJmiError(
"Cannot find HibernateRefClass identified by '" + uid + "'");
}
return refClass;
}
/**
* Register the given {@link HibernateRefClass}.
* @param uid unique identifier for the given {@link HibernateRefClass}
* @param refClass a {@link HibernateRefClass}
* @throws InternalJmiError on duplicate uid
* @throws NullPointerException if either parameter is null
*/
public void registerRefClass(String uid, HibernateRefClass refClass)
{
if (uid == null) {
throw new NullPointerException("uid == null");
}
if (refClass == null) {
throw new NullPointerException("refClass == null");
}
if (multipleExtentsEnabled) {
if (classRegistry.containsKey(uid)) {
return;
}
}
HibernateRefClass prev = classRegistry.put(uid, refClass);
if (prev != null) {
throw new InternalJmiError(
"HibernateRefClass (mofId " + prev.refMofId() + "; class " +
prev.getClass().getName() + ") already identified by '" + uid +
"'; Cannot replace it with HibernateRefClass (mofId " +
refClass.refMofId() + "; class " +
refClass.getClass().getName() + ")");
}
log.finer(
"Registered class " + refClass.getClass().getName() +
", identified by '" + uid + "'");
}
/**
* Unregister a previously
* {@link #registerRefClass(String, HibernateRefClass) registered}
* {@link HibernateRefClass}.
*
* @param uid unique identifier for the HibernateRefClass
*/
public void unregisterRefClass(String uid)
{
if (uid == null) {
throw new NullPointerException("uid == null");
}
if (multipleExtentsEnabled) {
return;
}
HibernateRefClass old = classRegistry.remove(uid);
if (old == null) {
throw new InternalJmiError(
"HibernateRefClass (uid " + uid + ") was never registered");
}
log.finer(
"Unregistered class " + old.getClass().getName() +
", identified by '" + uid + "'");
}
/**
* Find the identified {@link HibernateRefAssociation}.
*
* @param uid unique {@link HibernateRefAssociation} identifier
* @return {@link HibernateRefAssociation} associated with UID
* @throws InternalJmiError if the class is not found
*/
public HibernateRefAssociation findRefAssociation(String uid)
{
HibernateRefAssociation refAssoc = assocRegistry.get(uid);
if (refAssoc == null) {
throw new InternalJmiError(
"Cannot find HibernateRefAssociation identified by '"
+ uid + "'");
}
return refAssoc;
}
/**
* Register the given {@link HibernateRefAssociation}.
* @param uid unique identifier for the given
* {@link HibernateRefAssociation}
* @param refAssoc a {@link HibernateRefAssociation}
* @throws InternalJmiError on duplicate uid
* @throws NullPointerException if either parameter is null
*/
public void registerRefAssociation(
String uid, HibernateRefAssociation refAssoc)
{
if (uid == null) {
throw new NullPointerException("uid == null");
}
if (refAssoc == null) {
throw new NullPointerException("refAssoc == null");
}
if (multipleExtentsEnabled) {
if (assocRegistry.containsKey(uid)) {
return;
}
}
HibernateRefAssociation prev = assocRegistry.put(uid, refAssoc);
if (prev != null) {
throw new InternalJmiError(
"HibernateRefAssociation (mofId " + prev.refMofId() +
"; class " + prev.getClass().getName() +
") already identified by '" + uid +
"'; Cannot replace it with HibernateRefAssociation (mofId " +
refAssoc.refMofId() + "; class " +
refAssoc.getClass().getName() + ")");
}
log.finer(
"Registered assoc " + refAssoc.getClass().getName() +
", identified by '" + uid + "'");
}
/**
* Unregister a previously
* {@link #registerRefAssociation(String, HibernateRefAssociation) registered}
* {@link HibernateRefAssociation}.
*
* @param uid unique identifier for the HibernateRefAssociation
*/
public void unregisterRefAssociation(String uid)
{
if (uid == null) {
throw new NullPointerException("uid == null");
}
if (multipleExtentsEnabled) {
return;
}
HibernateRefAssociation old = assocRegistry.remove(uid);
if (old == null) {
throw new InternalJmiError(
"HibernateRefAssociation (uid " + uid +
") was never registered");
}
log.finer(
"Unregistered assoc " + old.getClass().getName() +
", identified by '" + uid + "'");
}
public void enqueueEvent(MDRChangeEvent event)
{
MdrSession mdrSession = getMdrSession();
if (!isNestedWriteTransaction(mdrSession)) {
throw new IllegalStateException("Not in write transaction");
}
enqueueEvent(mdrSession, event);
}
public void recordObjectCreation(HibernateObject object)
{
MdrSession mdrSession = getMdrSession();
long mofId = object.getMofId();
mdrSession.mofIdCreateMap.put(mofId, object.getClass());
}
public void recordObjectDeletion(HibernateObject object)
{
if (previewDelete) {
return;
}
MdrSession mdrSession = getMdrSession();
long mofId = object.getMofId();
mdrSession.byMofIdCache.remove(mofId);
mdrSession.mofIdDeleteSet.add(mofId);
}
void recordObjectDeletions(Collection<Long> mofIds)
{
MdrSession mdrSession = getMdrSession();
for(Long mofId: mofIds) {
mdrSession.byMofIdCache.remove(mofId);
mdrSession.mofIdDeleteSet.add(mofId);
}
}
/**
* Helper method for generating the extent deletion event from a RefPackage.
*
* @param pkg top-level RefPackage of the extent being deleted
*/
public void enqueueExtentDeleteEvent(RefPackage pkg)
{
synchronized(extentMap) {
String extentName = null;
for(Map.Entry<String, ExtentDescriptor> entry: extentMap.entrySet()) {
if (entry.getValue().extent.equals(pkg)) {
extentName = entry.getKey();
break;
}
}
if (extentName == null) {
throw new InternalMdrError(
"Extent delete event only valid on top-level package");
}
enqueueEvent(
new ExtentEvent(
pkg,
ExtentEvent.EVENT_EXTENT_DELETE,
extentName,
pkg.refMetaObject(),
Collections.unmodifiableCollection(
new ArrayList<String>(extentMap.keySet()))));
}
}
private void enqueueEvent(MdrSession mdrSession, MDRChangeEvent event)
{
// Cache event in Context (we'll need to fire it upon commit even if
// there are no listeners now.) For deletion preview, do not
// enqueue anything, since there's no actual effect to be committed
// or rolled back.
if (!previewDelete) {
mdrSession.queuedEvents.add(event);
}
// Fire as planned change immediately (and from this thread).
synchronized(listeners) {
for(EnkiMaskedMDRChangeListener listener: listeners.values()) {
// Note: EnkiMaskedMDRChangeListener automatically squelches
// RuntimeExceptions as required by the API.
listener.plannedChange(event);
}
}
}
private void enqueueBeginTransEvent(MdrSession mdrSession)
{
enqueueEvent(
mdrSession,
new TransactionEvent(
this, TransactionEvent.EVENT_TRANSACTION_START));
}
private void enqueueEndTransEvent(MdrSession mdrSession)
{
enqueueEvent(
mdrSession,
new TransactionEvent(
this, TransactionEvent.EVENT_TRANSACTION_END));
}
private void fireCanceledChanges(MdrSession mdrSession)
{
synchronized(listeners) {
for(MDRChangeEvent event: mdrSession.queuedEvents) {
for(EnkiMaskedMDRChangeListener listener: listeners.values()) {
listener.changeCancelled(event);
}
}
mdrSession.queuedEvents.clear();
}
}
private void fireChanges(MdrSession mdrSession)
{
synchronized(listeners) {
for(MDRChangeEvent event: mdrSession.queuedEvents) {
thread.enqueueEvent(event);
}
mdrSession.queuedEvents.clear();
}
}
private void loadExistingExtents(List<Extent> extents)
{
// Sort metamodel extents ahead of models.
Collections.sort(
extents,
new Comparator<Extent>() {
public int compare(Extent e1, Extent e2)
{
String modelExtentName1 = e1.getModelExtentName();
String modelExtentName2 = e2.getModelExtentName();
boolean isMof1 = modelExtentName1.equals(MOF_EXTENT);
boolean isMof2 = modelExtentName2.equals(MOF_EXTENT);
int c;
if (isMof1 && isMof2) {
// Both metamodels
c = 0;
} else if (!isMof1 && !isMof2) {
c = modelExtentName1.compareTo(modelExtentName2);
} else if (isMof1) {
return -1;
} else {
return 1;
}
if (c != 0) {
return c;
}
return e1.getExtentName().compareTo(e2.getExtentName());
}
});
for(Extent extent: extents) {
String extentName = extent.getExtentName();
String modelExtentName = extent.getModelExtentName();
String annotation = extent.getAnnotation();
String extentTablePrefix = extent.getTablePrefix();
if (extentTablePrefix != null &&
!tablePrefix.equals(extentTablePrefix))
{
log.warning(
"Ignoring extent '" + extentName + "': wrong prefix");
continue;
}
if (modelExtentName.equals(MOF_EXTENT)) {
initModelExtent(extentName, false);
} else {
ModelDescriptor modelDesc =
configurator.getModelMap().get(modelExtentName);
if (modelDesc == null) {
throw new ProviderInstantiationException(
"Missing model extent '" + modelExtentName +
"' for extent '" + extentName + "'");
}
if (!extentMap.containsKey(modelExtentName)) {
// Should have been initialized previously (due to sorting)
throw new InternalMdrError(
"Missing metamodel extent '" + modelExtentName + "'");
}
ExtentDescriptor modelExtentDesc =
extentMap.get(modelExtentName);
if (modelExtentDesc.initializer == null) {
throw new ProviderInstantiationException(
"Missing initializer for metamodel extent '" +
modelExtentName + "'");
}
ExtentDescriptor extentDesc =
new ExtentDescriptor(extentName);
extentDesc.modelDescriptor = modelDesc;
extentDesc.annotation = annotation;
MetamodelInitializer.setCurrentInitializer(
modelExtentDesc.initializer);
try {
extentDesc.extent =
modelDesc.topLevelPkgCons.newInstance(
(Object)null);
Set<String> pluginNames = extent.getPlugins();
if (pluginNames == null) {
pluginNames = new HashSet<String>();
} else {
pluginNames = new HashSet<String>(pluginNames);
}
log.fine(
"Configured plugins for extent '" + extentName + "': "
+ pluginNames.toString());
Iterator<ModelPluginDescriptor> pluginIter =
modelDesc.plugins.iterator();
Iterator<MetamodelInitializer> initializerIter =
modelExtentDesc.pluginInitializers.iterator();
while(pluginIter.hasNext() && initializerIter.hasNext()) {
ModelPluginDescriptor plugin = pluginIter.next();
MetamodelInitializer init = initializerIter.next();
if (pluginNames.contains(plugin.name)) {
log.fine(
"Stitching plugin '" + plugin.name
+ "' to extent '" + extentName + "'");
init.stitchPackages(extentDesc.extent);
pluginNames.remove(plugin.name);
}
}
// Warn that some plugins that existed during creation
// are now gone.
// REVIEW: SWZ: 2009-01-30: Throw instead?
if (!pluginNames.isEmpty()) {
log.warning(
"Extent '" + extentName
+ "': Missing model plugin(s): " + pluginNames);
}
} catch (Exception e) {
throw new ProviderInstantiationException(
"Cannot load extent '" + extentName + "'", e);
} finally {
MetamodelInitializer.setCurrentInitializer(null);
}
extentMap.put(extentName, extentDesc);
}
}
}
private ModelDescriptor findModelDescriptor(RefObject metaPackage)
throws EnkiCreationFailedException
{
for(Map.Entry<String, ExtentDescriptor> entry: extentMap.entrySet()) {
ExtentDescriptor extentDesc = entry.getValue();
RefPackage extent = extentDesc.extent;
if (extent instanceof ModelPackage) {
ModelPackage extentModelPkg = (ModelPackage)extent;
for(MofPackage extentMofPkg:
GenericCollections.asTypedCollection(
extentModelPkg.getMofPackage().refAllOfClass(),
MofPackage.class))
{
if (extentMofPkg == metaPackage) {
return
configurator.getModelMap().get(extentDesc.name);
}
}
}
}
throw new EnkiCreationFailedException(
"Unknown metapackage");
}
private ExtentDescriptor createExtentStorage(
String name,
RefObject metaPackage,
RefPackage[] existingInstances)
throws EnkiCreationFailedException
{
if (metaPackage == null) {
initModelExtent(name, true);
return extentMap.get(name);
}
ModelDescriptor modelDesc = findModelDescriptor(metaPackage);
initModelStorage(modelDesc);
Set<String> configuredPlugins = new HashSet<String>();
for(ModelPluginDescriptor pluginDesc: modelDesc.plugins) {
configuredPlugins.add(pluginDesc.name);
}
ExtentDescriptor modelExtentDesc = extentMap.get(modelDesc.name);
ExtentDescriptor extentDesc = new ExtentDescriptor(name);
extentDesc.modelDescriptor = modelDesc;
MetamodelInitializer.setCurrentInitializer(
modelExtentDesc.initializer);
try {
if (modelDesc.topLevelPkgCons != null) {
extentDesc.extent =
modelDesc.topLevelPkgCons.newInstance((Object)null);
} else {
extentDesc.extent = modelDesc.topLevelPkgCls.newInstance();
}
for(MetamodelInitializer init:
modelExtentDesc.pluginInitializers)
{
init.stitchPackages(extentDesc.extent);
}
} catch (Exception e) {
throw new ProviderInstantiationException(
"Cannot load extent '" + name + "'", e);
} finally {
MetamodelInitializer.setCurrentInitializer(null);
}
initModelViews(modelDesc, extentDesc.extent);
createExtentRecord(
extentDesc.name,
modelDesc.name,
true,
configuredPlugins);
extentMap.put(name, extentDesc);
return extentDesc;
}
private void createExtentRecord(
String extentName,
String modelExtentName,
boolean setTablePrefix,
Set<String> existingPluginIdentifiers)
{
Session session = getCurrentSession();
Extent extentDbObj = new Extent();
extentDbObj.setExtentName(extentName);
extentDbObj.setModelExtentName(modelExtentName);
extentDbObj.setAnnotation(null);
if (setTablePrefix) {
extentDbObj.setTablePrefix(tablePrefix);
}
extentDbObj.setPlugins(existingPluginIdentifiers);
session.save(extentDbObj);
}
private void initStorage()
{
Configuration config = configurator.newConfiguration(true);
initProviderStorage(config);
configurator.addModelConfigurations(config);
sessionFactory = config.buildSessionFactory();
startPeriodicStats();
mofIdGenerator =
new MofIdGenerator(sessionFactory, config, storageProperties);
mofIdGenerator.configureTable(createSchema);
List<Extent> extents = null;
Session session = sessionFactory.getCurrentSession();
Transaction trans = session.beginTransaction();
try {
Query query = session.getNamedQuery("AllExtents");
extents =
GenericCollections.asTypedList(query.list(), Extent.class);
// NOTE jvs 1-Dec-2008: While loading an existing repository,
// we have to allow for the fact that it may have been created with
// multipleExtentsEnabled=true, since the application hasn't
// had a chance to enable this flag yet.
multipleExtentsEnabled = true;
loadExistingExtents(extents);
multipleExtentsEnabled = false;
} finally {
trans.commit();
}
thread = new EnkiChangeEventThread(this);
thread.start();
}
private void initProviderStorage(Configuration config)
{
SessionFactory tempSessionFactory = config.buildSessionFactory();
Session session = tempSessionFactory.getCurrentSession();
boolean exists = false;
Transaction trans = session.beginTransaction();
try {
try {
DatabaseMetaData dbMetadata =
session.connection().getMetaData();
this.sqlDialect =
DialectFactory.buildDialect(
config.getProperties(),
session.connection());
} catch(Exception e) {
throw new ProviderInstantiationException(
"Unable to determine appropriate SQL dialect", e);
}
try {
// Execute the query
session.getNamedQuery("AllExtents").list();
exists = true;
} catch(HibernateException e) {
// Presume that table doesn't exist.
log.log(Level.FINE, "Extent Query Error", e);
}
} finally {
trans.commit();
tempSessionFactory.close();
}
if (exists) {
if (sqlDialect instanceof HSQLDialect) {
// Validator is broken: doesn't quote properly and always
// fails.
log.warning(
"Skipping validation of provider schema (HSQLDB)");
return;
}
log.info("Validating Enki Hibernate provider schema");
SchemaValidator validator = new SchemaValidator(config);
boolean requiresUpdate = false;
try {
validator.validate();
} catch(HibernateException e) {
if (createSchema) {
log.log(
Level.WARNING,
"Enki Hibernate provider database schema validation failed",
e);
requiresUpdate = true;
} else {
throw new ProviderInstantiationException(
"Enki Hibernate provider database schema validation failed",
e);
}
}
if (requiresUpdate) {
log.info("Updating Enki Hibernate provider schema");
SchemaUpdate update = new SchemaUpdate(config);
try {
update.execute(false, true);
} catch(HibernateException e) {
throw new ProviderInstantiationException(
"Unable to update Enki Hibernate provider schema", e);
}
}
} else if (!createSchema) {
throw new ProviderInstantiationException(
"Unable to query extents from database: "
+ "invalid schema or bad connection");
} else {
log.info("Creating Enki Hibernate Provider schema");
SchemaExport export = new SchemaExport(config);
try {
export.create(false, true);
} catch(HibernateException e) {
throw new ProviderInstantiationException(
"Unable to create Enki Hibernate provider schema", e);
}
}
}
private void initModelStorage(ModelDescriptor modelDesc)
throws EnkiCreationFailedException
{
if (sqlDialect instanceof HSQLDialect) {
// Validator is broken: doesn't quote properly and always fails.
log.warning(
"Skipping validation of schema for model '"
+ modelDesc.name
+ "' (HSQLDB)");
return;
}
ClassLoader contextClassLoader = null;
if (classLoader != null) {
contextClassLoader =
Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
}
try {
Configuration config =
configurator.newModelConfiguration(modelDesc, true);
log.info("Validating schema for model '" + modelDesc.name + "'");
SchemaValidator validator = new SchemaValidator(config);
try {
validator.validate();
return;
} catch(HibernateException e) {
if (createSchema) {
log.log(
Level.FINE,
"Schema validation error for model '"
+ modelDesc.name + "'",
e);
} else {
throw new ProviderInstantiationException(
"Schema validation error for model '"
+ modelDesc.name + "'",
e);
}
}
log.info("Updating schema for model '" + modelDesc.name + "'");
SchemaUpdate update = new SchemaUpdate(config);
update.execute(false, true);
List<?> exceptions = update.getExceptions();
if (exceptions != null && !exceptions.isEmpty()) {
logDdlExceptions(
exceptions, Level.SEVERE, "schema update error");
throw new EnkiCreationFailedException(
"Schema update for model '" + modelDesc.name +
"' failed (see log for errors)");
}
config =
configurator.newModelIndexMappingConfiguration(
modelDesc, false);
log.info("Updating indexes for model '" + modelDesc.name + "'");
SchemaExport export = new SchemaExport(config);
// execute params are:
// script: false (don't write DDL to stdout)
// export: true (send DDL to DB)
// justDrop: true (run only drop statements)
// justCreate: false (don't run create statements)
export.execute(false, true, true, false);
exceptions = export.getExceptions();
if (exceptions != null && !exceptions.isEmpty()) {
// Log drop errors, but don't abort (they'll always fail if
// this is the initial schema creation).
logDdlExceptions(exceptions, Level.FINE, "index drop error");
}
// execute params are:
// script: false (don't write DDL to stdout)
// export: true (send DDL to DB)
// justDrop: false (don't run drop statements)
// justCreate: true (run only create statements)
export.execute(false, true, false, true);
exceptions = export.getExceptions();
if (exceptions != null && !exceptions.isEmpty()) {
logDdlExceptions(
exceptions, Level.SEVERE, "index create error");
throw new EnkiCreationFailedException(
"Index creation for model '" + modelDesc.name +
"' failed (see log for errors)");
}
}
finally {
if (contextClassLoader != null) {
Thread.currentThread().setContextClassLoader(
contextClassLoader);
}
}
}
private void initModelViews(ModelDescriptor modelDesc, RefPackage pkg)
{
if (!createViews) {
return;
}
CodeGenXmlOutputStringBuilder mappingOutput =
new CodeGenXmlOutputStringBuilder();
HibernateViewMappingUtil viewUtil =
new HibernateViewMappingUtil(
mappingOutput,
new Dialect[][] { { sqlDialect }},
tablePrefix);
Set<Classifier> classes = new HashSet<Classifier>();
LinkedList<RefPackage> pkgs = new LinkedList<RefPackage>();
pkgs.add(pkg);
while(!pkgs.isEmpty()) {
RefPackage p = pkgs.removeFirst();
if (CodeGenUtils.isTransient((MofPackage)p.refMetaObject())) {
continue;
}
for(RefClass c:
GenericCollections.asTypedCollection(
p.refAllClasses(), RefClass.class))
{
classes.add((Classifier)c.refMetaObject());
}
Collection<RefPackage> subPkgs =
GenericCollections.asTypedCollection(
p.refAllPackages(), RefPackage.class);
pkgs.addAll(subPkgs);
}
mappingOutput.writeXmlDecl();
mappingOutput.writeDocType(
"hibernate-mapping",
"-//Hibernate/Hibernate Mapping DTD 3.0//EN",
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd");
mappingOutput.newLine();
try {
mappingOutput.startElem("hibernate-mapping");
viewUtil.generateViews(classes);
mappingOutput.endElem("hibernate-mapping");
} catch(GenerationException e) {
throw new HibernateException("Could not generate view mapping", e);
}
String mapping = mappingOutput.getOutput();
Configuration config = configurator.newConfiguration(false);
config.addXML(mapping);
log.info("Updating views for model '" + modelDesc.name + "'");
SchemaExport export = new SchemaExport(config);
// execute params are:
// script: false (don't write DDL to stdout)
// export: true (send DDL to DB)
// justDrop: true (run only drop statements)
// justCreate: false (don't run create statements)
export.execute(false, true, true, false);
List<?> exceptions = export.getExceptions();
if (exceptions != null && !exceptions.isEmpty()) {
// Log drop errors, but don't abort (they'll always fail if
// this is the initial schema creation).
logDdlExceptions(exceptions, Level.FINE, "view drop error");
}
// execute params are:
// script: false (don't write DDL to stdout)
// export: true (send DDL to DB)
// justDrop: false (don't run drop statements)
// justCreate: true (run only create statements)
export.execute(false, true, false, true);
exceptions = export.getExceptions();
if (exceptions != null && !exceptions.isEmpty()) {
logDdlExceptions(
exceptions, Level.SEVERE, "index create error");
throw new HibernateException(
"View creation for model '" + modelDesc.name +
"' failed (see log for errors)");
}
}
private void logDdlExceptions(List<?> exceptions, Level level, String msg)
{
int i = 1;
for(Object o: exceptions) {
Throwable t = (Throwable)o;
log.log(
level,
msg + " (" + i++ + " of " + exceptions.size() + ")",
t);
}
}
private void dropModelStorage(ModelDescriptor modelDesc)
throws EnkiDropFailedException
{
ClassLoader contextClassLoader = null;
if (classLoader != null) {
contextClassLoader =
Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
}
try {
Configuration config =
configurator.newModelConfiguration(modelDesc, false);
log.info("Dropping schema for model '" + modelDesc.name + "'");
SchemaExport export = new SchemaExport(config);
export.drop(false, true);
List<?> exceptions = export.getExceptions();
if (exceptions != null && !exceptions.isEmpty()) {
throw new EnkiDropFailedException(
"Schema drop for model '" + modelDesc.name +
"' failed (cause is first exception)",
(Throwable)exceptions.get(0));
}
}
finally {
if (contextClassLoader != null) {
Thread.currentThread().setContextClassLoader(
contextClassLoader);
}
}
}
private void initModelExtent(String name, boolean isNew)
{
boolean isMof = name.equals(MOF_EXTENT);
ModelDescriptor modelDesc = configurator.getModelMap().get(name);
if (modelDesc == null) {
throw new InternalMdrError(
"Unknown metamodel extent '" + name + "'");
}
ModelDescriptor mofDesc =
isMof ? null : configurator.getModelMap().get(MOF_EXTENT);
log.info("Initializing Extent Descriptor: " + name);
ExtentDescriptor extentDesc = new ExtentDescriptor(name);
extentDesc.modelDescriptor = mofDesc;
MetamodelInitializer init;
ModelPackage metaModelPackage = null;
if (isMof) {
init = new Initializer(MOF_EXTENT);
} else {
init = getInitializer(modelDesc);
ExtentDescriptor mofExtentDesc = extentMap.get(MOF_EXTENT);
metaModelPackage = mofExtentDesc.initializer.getModelPackage();
}
init.setOwningRepository(this);
init.init(metaModelPackage);
for(ModelPluginDescriptor pluginDesc: modelDesc.plugins) {
MetamodelInitializer pluginInit = getInitializer(pluginDesc);
pluginInit.setOwningRepository(this);
pluginInit.initPlugin(metaModelPackage, init);
extentDesc.pluginInitializers.add(pluginInit);
}
extentDesc.extent = init.getModelPackage();
extentDesc.initializer = init;
extentDesc.builtIn = true;
if (isNew && !isMof) {
createExtentRecord(extentDesc.name, MOF_EXTENT, false, null);
}
extentMap.put(name, extentDesc);
log.fine("Initialized Extent Descriptor: " + name);
}
private MetamodelInitializer getInitializer(
AbstractModelDescriptor modelDesc)
{
String initializerName =
modelDesc.properties.getProperty(PROPERTY_MODEL_INITIALIZER);
if (initializerName == null) {
throw new ProviderInstantiationException(
"Initializer name missing from '" + modelDesc.name +
"' model properties");
}
try {
Class<? extends MetamodelInitializer> initCls =
Class.forName(
initializerName,
true,
Thread.currentThread().getContextClassLoader())
.asSubclass(MetamodelInitializer.class);
Constructor<? extends MetamodelInitializer> cons =
initCls.getConstructor(String.class);
return cons.newInstance(modelDesc.name);
} catch (Exception e) {
throw new ProviderInstantiationException(
"Initializer class '" + initializerName +
"' from '" + modelDesc.name +
"' model JAR could not be instantiated", e);
}
}
private void logStack(Level level, String msg)
{
logStack(level, msg, -1);
}
private void logStack(Level level, String msg, int sessionId)
{
Throwable t = null;
if (log.isLoggable(Level.FINEST)) {
t = new RuntimeException("SHOW STACK");
}
if (sessionId != -1) {
StringBuilder b = new StringBuilder(msg);
b.append(" (id: ").append(sessionId).append(')');
msg = b.toString();
}
log.log(level, msg, t);
}
private void startPeriodicStats()
{
if (periodicStatsInterval <= 0) {
return;
}
sessionFactory.getStatistics().setStatisticsEnabled(true);
long delay = (long)periodicStatsInterval * 1000L;
periodicStatsTimer = new Timer("Enki Hibernate Stats Timer", true);
periodicStatsTimer.schedule(
new TimerTask() {
@Override
public void run()
{
logPeriodicStats();
}
},
delay,
delay);
}
private void logPeriodicStats()
{
Statistics stats = sessionFactory.getStatistics();
stats.logSummary();
StringBuilder b = new StringBuilder();
for(String cacheRegion: stats.getSecondLevelCacheRegionNames()) {
SecondLevelCacheStatistics cacheStats =
stats.getSecondLevelCacheStatistics(cacheRegion);
b.setLength(0);
b
.append("stats: cache region: ")
.append(cacheRegion)
.append(": elements: ")
.append(cacheStats.getElementCountInMemory());
if (logMemStats) {
b
.append(" size in memory: ")
.append(cacheStats.getSizeInMemory());
}
log.info(b.toString());
}
}
private void stopPeriodicStats()
{
if (periodicStatsTimer == null) {
return;
}
periodicStatsTimer.cancel();
}
/**
* ExtentDescriptor describes an instantiated model extent.
*/
protected static class ExtentDescriptor
{
protected final String name;
protected ModelDescriptor modelDescriptor;
protected RefPackage extent;
protected MetamodelInitializer initializer;
protected List<MetamodelInitializer> pluginInitializers;
protected boolean builtIn;
protected String annotation;
public ExtentDescriptor(String name)
{
this.name = name;
this.pluginInitializers = new ArrayList<MetamodelInitializer>();
}
}
private class MdrSession implements EnkiMDSession
{
private Session session;
private Lock lock;
private boolean containsWrites;
private boolean isImplicit;
private int refCount;
private final int sessionId;
private final LinkedList<Context> context;
private final Map<HibernateRefClass, Collection<?>> allOfTypeCache;
private final Map<HibernateRefClass, Collection<?>> allOfClassCache;
private final Map<Long, SoftReference<RefBaseObject>> byMofIdCache;
private final Set<Long> mofIdDeleteSet;
private final Map<Long, Class<? extends RefObject>> mofIdCreateMap;
private final List<MDRChangeEvent> queuedEvents;
private MdrSession(Session session, boolean isImplicit, int sessionId)
{
this.session = session;
this.context = new LinkedList<Context>();
this.allOfTypeCache =
new HashMap<HibernateRefClass, Collection<?>>();
this.allOfClassCache =
new HashMap<HibernateRefClass, Collection<?>>();
this.byMofIdCache =
new HashMap<Long, SoftReference<RefBaseObject>>();
this.mofIdDeleteSet = new HashSet<Long>();
this.mofIdCreateMap =
new HashMap<Long, Class<? extends RefObject>>();
this.containsWrites = false;
this.queuedEvents = new LinkedList<MDRChangeEvent>();
this.isImplicit = isImplicit;
this.refCount = 0;
this.sessionId = sessionId;
}
private void obtainWriteLock()
{
if (interThreadSessionsEnabled) {
return;
}
if (lock != null) {
throw new EnkiHibernateException("already locked");
}
lock = txnLock.writeLock();
lock.lock();
}
private void obtainReadLock()
{
if (interThreadSessionsEnabled) {
return;
}
if (lock != null) {
throw new EnkiHibernateException("already locked");
}
Lock l = txnLock.readLock();
l.lock();
lock = l;
}
private void releaseLock()
{
if (interThreadSessionsEnabled) {
return;
}
if (lock == null) {
return;
}
Lock l = lock;
lock = null;
l.unlock();
}
private MofIdGenerator getMofIdGenerator()
{
return HibernateMDRepository.this.mofIdGenerator;
}
private HibernateMDRepository getRepos()
{
return HibernateMDRepository.this;
}
public void reset()
{
allOfTypeCache.clear();
allOfClassCache.clear();
byMofIdCache.clear();
mofIdDeleteSet.clear();
mofIdCreateMap.clear();
}
public void close()
{
if (!context.isEmpty()) {
throw new InternalMdrError("open txns on session");
}
context.clear();
if (!queuedEvents.isEmpty()) {
throw new InternalMdrError("unfired events on session");
}
queuedEvents.clear();
reset();
session.close();
session = null;
}
}
/**
* MdrSessionStack maintains a thread-local stack of {@link MdrSession}
* instances. The stack should only ever contain a single session from
* any HibernateMDRepository. It exists to support a single thread
* accessing multiple repositories.
*/
private static class MdrSessionStack
{
/** Thread-local storage for MDR session contexts. */
private final ThreadLocal<LinkedList<MdrSession>> tls =
new ThreadLocal<LinkedList<MdrSession>>() {
@Override
protected LinkedList<MdrSession> initialValue()
{
if (interThreadSessionsEnabled) {
return globalSessionStack;
} else {
return new LinkedList<MdrSession>();
}
}
};
public MdrSession peek()
{
LinkedList<MdrSession> stack = tls.get();
if (stack.isEmpty()) {
return null;
}
return stack.getFirst();
}
public MdrSession peek(HibernateMDRepository repos)
{
LinkedList<MdrSession> stack = tls.get();
if (stack.isEmpty()) {
return null;
}
MdrSession session = stack.getFirst();
if (session.getRepos() != repos) {
return null;
}
return session;
}
public MdrSession pop()
{
return tls.get().removeFirst();
}
public void push(MdrSession session)
{
tls.get().addFirst(session);
}
public boolean isEmpty()
{
return tls.get().isEmpty();
}
}
/**
* Context represents an implicit or explicit MDR transaction.
*/
private class Context
{
private Transaction transaction;
private boolean isWrite;
private boolean isImplicit;
private boolean isCommitter;
private boolean forceRollback;
private Context(
Transaction transaction,
boolean isWrite,
boolean isImplicit,
boolean isCommitter)
{
this.transaction = transaction;
this.isWrite = isWrite;
this.isImplicit = isImplicit;
this.isCommitter = isCommitter;
this.forceRollback = false;
}
}
}
// End HibernateMDRepository.java |
package jlibs.xml.stream;
import jlibs.xml.sax.AbstractXMLReader;
import jlibs.xml.sax.SAXDelegate;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.EntityDeclaration;
import javax.xml.stream.events.NotationDeclaration;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static javax.xml.stream.XMLStreamConstants.*;
/**
* {@link org.xml.sax.XMLReader} implementation using STAX.
* <p>
* This class also provides handy utility method {@link #fire(javax.xml.stream.XMLStreamReader, jlibs.xml.sax.SAXDelegate) fire(...)}
* to translate STAX events to SAX events.
*
* <pre class="prettyprint">
* XMLStreamReader reader = ...;
* SAXDelegate delegate = new SAXDelegate();
*
* // set any handlers you are interested
* delegate.setContentHandler(myContentHandler);
* delegate.setErrorHandler(myErrorHandler);
*
* STAXXMLReader.fire(reader, delegate);
* </pre>
*
* @author Santhosh Kumar T
*/
public class STAXXMLReader extends AbstractXMLReader{
private XMLInputFactory factory;
public STAXXMLReader(XMLInputFactory factory){
this.factory = factory;
}
public STAXXMLReader(){
this(XMLInputFactory.newInstance());
}
@Override
public void parse(InputSource input) throws IOException, SAXException{
XMLStreamReader reader = null;
try{
if(input.getByteStream()!=null)
reader = factory.createXMLStreamReader(input.getByteStream(), input.getEncoding());
else if(input.getCharacterStream()!=null)
reader = factory.createXMLStreamReader(input.getCharacterStream());
else
reader = factory.createXMLStreamReader(input.getSystemId(), (InputStream)null);
fire(reader, handler);
}catch(XMLStreamException ex){
throw new SAXException(ex);
}finally{
try{
if(reader!=null)
reader.close();
}catch(XMLStreamException ex){
//noinspection ThrowFromFinallyBlock
throw new SAXException(ex);
}
}
}
@Override
public void parse(String systemId) throws IOException, SAXException{
parse(new InputSource(systemId));
}
/**
* Reads data from specified {@code reader}, and delegates translated SAX Events
* to {@code handler}.
* <p>
* <b>Note:</b> The {@code reader} is not closed by this method.
*
* @param reader reader to reads data from
* @param handler the SAXHandler which receives SAX events
*
* @throws SAXException any {@link XMLStreamException} occured is rethrown as {@link SAXException}
*/
@SuppressWarnings({"unchecked"})
public static void fire(XMLStreamReader reader, SAXDelegate handler) throws SAXException{
Attributes attrs = new STAXAttributes(reader);
int eventType = reader.getEventType();
while(true){
switch(eventType){
case START_DOCUMENT:
handler.setDocumentLocator(new STAXLocator(reader));
handler.startDocument();
break;
case START_ELEMENT:{
int nsCount = reader.getNamespaceCount();
for(int i=0; i<nsCount; i++){
String prefix = reader.getNamespacePrefix(i);
String uri = reader.getNamespaceURI(i);
handler.startPrefixMapping(prefix==null?"":prefix, uri==null?"":uri);
}
String localName = reader.getLocalName();
String prefix = reader.getPrefix();
String qname = prefix==null || prefix.length()==0 ? localName : prefix+':'+localName;
String uri = reader.getNamespaceURI();
handler.startElement(uri==null?"":uri, localName, qname, attrs);
break;
}
case CHARACTERS:
handler.characters(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength());
break;
case CDATA:
handler.startCDATA();
handler.characters(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength());
handler.endCDATA();
break;
case COMMENT:
handler.comment(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength());
break;
case PROCESSING_INSTRUCTION:
handler.processingInstruction(reader.getPITarget(), reader.getPIData());
break;
case SPACE:
handler.ignorableWhitespace(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength());
break;
case DTD:
for(NotationDeclaration notation: (List<NotationDeclaration>)reader.getProperty("javax.xml.stream.notations"))
handler.notationDecl(notation.getName(), notation.getPublicId(), notation.getSystemId());
for(EntityDeclaration entity: (List<EntityDeclaration>)reader.getProperty("javax.xml.stream.entities"))
handler.unparsedEntityDecl(entity.getName(), entity.getPublicId(), entity.getSystemId(), entity.getNotationName());
break;
case END_ELEMENT:{
String localName = reader.getLocalName();
String prefix = reader.getPrefix();
String qname = prefix==null || prefix.length()==0 ? localName : prefix+':'+localName;
String uri = reader.getNamespaceURI();
handler.endElement(uri==null?"":uri, localName, qname);
int nsCount = reader.getNamespaceCount();
for(int i=0; i<nsCount; i++){
prefix = reader.getNamespacePrefix(i);
handler.endPrefixMapping(prefix==null?"":prefix);
}
break;
}
case END_DOCUMENT:
handler.endDocument();
return;
}
try{
eventType = reader.next();
}catch(XMLStreamException ex){
throw new SAXException(ex);
}
}
}
} |
package org.esupportail.smsuapi.domain.beans.sms;
import java.io.Serializable;
/**
* Defines a SMS.
* @author PRQD8824
*
*/
public class SMSBroker implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The unique identifier message.
*/
private int id;
/**
* The message recipient.
*/
private String recipient;
/**
* The message itself.
*/
private String message;
/**
* Constructor.
*/
public SMSBroker() {
super();
}
public SMSBroker(final int id, final String recipient, final String message) {
super();
this.id = id;
this.recipient = recipient;
this.message = message;
}
public int getId() {
return id;
}
public String getRecipient() {
return recipient;
}
public String getMessage() {
return message;
}
} |
package org.helioviewer.jhv.camera.annotate;
import javax.annotation.Nullable;
import org.helioviewer.jhv.base.Colors;
import org.helioviewer.jhv.camera.Camera;
import org.helioviewer.jhv.camera.Interaction;
import org.helioviewer.jhv.display.Display;
import org.helioviewer.jhv.display.Viewport;
import org.helioviewer.jhv.math.Quat;
import org.helioviewer.jhv.math.Vec2;
import org.helioviewer.jhv.math.Vec3;
import org.helioviewer.jhv.opengl.BufVertex;
import org.helioviewer.jhv.opengl.GLHelper;
import org.json.JSONObject;
public class AnnotateCircle extends AbstractAnnotateable {
private static final int SUBDIVISIONS = 90;
public AnnotateCircle(JSONObject jo) {
super(jo);
}
private static void drawCircle(Quat q, Viewport vp, Vec3 bp, Vec3 ep, BufVertex buf, byte[] color) {
double cosf = Vec3.dot(bp, ep);
double r = Math.sqrt(1 - cosf * cosf);
// P = center + r cos(A) (bp x ep) + r sin(A) ep
Vec3 center = Vec3.multiply(bp, cosf);
Vec3 u = Vec3.cross(bp, ep);
u.normalize();
Vec3 v = Vec3.cross(bp, u);
Vec3 vx = new Vec3();
Vec2 previous = null;
for (int i = 0; i <= SUBDIVISIONS; i++) {
double t = i * 2. * Math.PI / SUBDIVISIONS;
double cosr = Math.cos(t) * r;
double sinr = Math.sin(t) * r;
vx.x = center.x + cosr * u.x + sinr * v.x;
vx.y = center.y + cosr * u.y + sinr * v.y;
vx.z = center.z + cosr * u.z + sinr * v.z;
if (Display.mode == Display.ProjectionMode.Orthographic) {
if (i == 0) {
putSphere(vx, buf, Colors.Null);
}
putSphere(vx, buf, color);
if (i == SUBDIVISIONS) {
putSphere(vx, buf, Colors.Null);
}
} else {
vx.y = -vx.y;
if (i == 0) {
GLHelper.drawVertex(q, vp, vx, previous, buf, Colors.Null);
}
previous = GLHelper.drawVertex(q, vp, vx, previous, buf, color);
if (i == SUBDIVISIONS) {
GLHelper.drawVertex(q, vp, vx, previous, buf, Colors.Null);
}
}
}
}
@Override
public void draw(Quat q, Viewport vp, boolean active, BufVertex buf) {
boolean dragged = beingDragged();
if ((startPoint == null || endPoint == null) && !dragged)
return;
byte[] color = dragged ? dragColor : (active ? activeColor : baseColor);
Vec3 p0 = dragged ? dragStartPoint : startPoint;
Vec3 p1 = dragged ? dragEndPoint : endPoint;
drawCircle(q, vp, p0, p1, buf, color);
}
@Override
public void mousePressed(Camera camera, int x, int y) {
Vec3 pt = computePoint(camera, x, y);
if (pt != null)
dragStartPoint = pt;
}
@Override
public void mouseDragged(Camera camera, int x, int y) {
Vec3 pt = computePoint(camera, x, y);
if (pt != null)
dragEndPoint = pt;
}
@Override
public void mouseReleased() {
if (beingDragged()) {
startPoint = dragStartPoint;
endPoint = dragEndPoint;
}
dragStartPoint = null;
dragEndPoint = null;
}
@Override
public boolean beingDragged() {
return dragEndPoint != null && dragStartPoint != null;
}
@Override
public boolean isDraggable() {
return true;
}
@Override
public String getType() {
return Interaction.AnnotationMode.Circle.toString();
}
@Nullable
@Override
public Object getData() {
boolean dragged = beingDragged();
if ((startPoint == null || endPoint == null) && !dragged)
return null;
Vec3 bp = dragged ? dragStartPoint : startPoint;
Vec3 ep = dragged ? dragEndPoint : endPoint;
double cosf = Vec3.dot(bp, ep);
return Math.sqrt(1 - cosf * cosf);
}
} |
package com.xpn.xwiki.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
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.Vector;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.oro.text.PatternCache;
import org.apache.oro.text.PatternCacheLRU;
import org.apache.oro.text.perl.Perl5Util;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternMatcherInput;
import org.apache.oro.text.regex.Perl5Matcher;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xwiki.container.Container;
import com.novell.ldap.util.Base64;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.monitor.api.MonitorPlugin;
import com.xpn.xwiki.render.WikiSubstitution;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.web.XWikiRequest;
public class Util
{
private static final Log LOG = LogFactory.getLog(Util.class);
private static PatternCache patterns = new PatternCacheLRU(200);
private Perl5Matcher matcher = new Perl5Matcher();
private Perl5Util p5util = new Perl5Util(getPatterns());
public String substitute(String pattern, String text)
{
return getP5util().substitute(pattern, text);
}
public boolean match(String pattern, String text)
{
return getP5util().match(pattern, text);
}
public boolean matched()
{
return (getP5util().getMatch() != null);
}
public String substitute(String pattern, String substitution, String text)
{
WikiSubstitution subst = new WikiSubstitution(this, pattern);
subst.setSubstitution(substitution);
return subst.substitute(text);
}
public Perl5Matcher getMatcher()
{
return this.matcher;
}
public Perl5Util getP5util()
{
return this.p5util;
}
public List<String> getAllMatches(String content, String spattern, int group) throws MalformedPatternException
{
List<String> list = new ArrayList<String>();
PatternMatcherInput input = new PatternMatcherInput(content);
Pattern pattern = patterns.addPattern(spattern);
while (this.matcher.contains(input, pattern)) {
MatchResult result = this.matcher.getMatch();
String smatch = result.group(group);
list.add(smatch);
}
return list;
}
public List<String> getUniqueMatches(String content, String spattern, int group) throws MalformedPatternException
{
// Remove duplicate entries
Set<String> uniqueMatches = new HashSet<String>();
uniqueMatches.addAll(getAllMatches(content, spattern, group));
List<String> matches = new ArrayList<String>();
matches.addAll(uniqueMatches);
return matches;
}
/**
* @deprecated use {@link #getUniqueMatches(String, String, int)} instead
*/
@Deprecated
public List<String> getMatches(String content, String spattern, int group) throws MalformedPatternException
{
return getUniqueMatches(content, spattern, group);
}
public static String cleanValue(String value)
{
value = StringUtils.replace(value, "\r\r\n", "%_N_%");
value = StringUtils.replace(value, "\r\n", "%_N_%");
value = StringUtils.replace(value, "\n\r", "%_N_%");
value = StringUtils.replace(value, "\r", "\n");
value = StringUtils.replace(value, "\n", "%_N_%");
value = StringUtils.replace(value, "\"", "%_Q_%");
return value;
}
public static String restoreValue(String value)
{
value = StringUtils.replace(value, "%_N_%", "\n");
value = StringUtils.replace(value, "%_Q_%", "\"");
return value;
}
/**
* Create a Map from a string holding a space separated list of key=value pairs. If keys or values must contain
* spaces, they can be placed inside quotes, like <code>"this key"="a larger value"</code>. To use a quote as part
* of a key/value, use <code>%_Q_%</code>.
*
* @param mapString The string that must be parsed.
* @return A Map containing the keys and values. If a key is defined more than once, the last value is used.
*/
public static Hashtable<String, String> keyValueToHashtable(String mapString) throws IOException
{
Hashtable<String, String> result = new Hashtable<String, String>();
StreamTokenizer st = new StreamTokenizer(new BufferedReader(new StringReader(mapString)));
st.resetSyntax();
st.quoteChar('"');
st.wordChars('a', 'z');
st.wordChars('A', 'Z');
st.whitespaceChars(' ', ' ');
st.whitespaceChars('=', '=');
while (st.nextToken() != StreamTokenizer.TT_EOF) {
String key = st.sval;
st.nextToken();
String value = (st.sval != null) ? st.sval : "";
result.put(key, restoreValue(value));
}
return result;
}
public static PatternCache getPatterns()
{
return patterns;
}
public static Map<String, String[]> getObject(XWikiRequest request, String prefix)
{
@SuppressWarnings("unchecked")
Map<String, String[]> parameters = request.getParameterMap();
return getSubMap(parameters, prefix);
}
public static <T> Map<String, T> getSubMap(Map<String, T> map, String prefix)
{
HashMap<String, T> result = new HashMap<String, T>();
for (String name : map.keySet()) {
if (name.startsWith(prefix + "_")) {
String newname = name.substring(prefix.length() + 1);
result.put(newname, map.get(name));
} else if (name.equals(prefix)) {
result.put("", map.get(name));
}
}
return result;
}
public static String getWeb(String fullname)
{
int i = fullname.lastIndexOf(".");
return fullname.substring(0, i);
}
public Vector<String> split(String pattern, String text)
{
Vector<String> results = new Vector<String>();
getP5util().split(results, pattern, text);
return results;
}
public static String getFileContent(File file) throws IOException
{
return FileUtils.readFileToString(file);
}
public static String getFileContent(Reader reader) throws IOException
{
return IOUtils.toString(reader);
}
public static byte[] getFileContentAsBytes(File file) throws IOException
{
return FileUtils.readFileToByteArray(file);
}
public static byte[] getFileContentAsBytes(InputStream is) throws IOException
{
return IOUtils.toByteArray(is);
}
public static boolean contains(String name, String list, String sep)
{
String[] sarray = StringUtils.split(list, sep);
return ArrayUtils.contains(sarray, name);
}
public static String noaccents(String text)
{
String temp = text;
temp = temp.replaceAll("\u00c0", "A");
temp = temp.replaceAll("\u00c1", "A");
temp = temp.replaceAll("\u00c2", "A");
temp = temp.replaceAll("\u00c3", "A");
temp = temp.replaceAll("\u00c4", "A");
temp = temp.replaceAll("\u00c5", "A");
temp = temp.replaceAll("\u0100", "A");
temp = temp.replaceAll("\u0102", "A");
temp = temp.replaceAll("\u0104", "A");
temp = temp.replaceAll("\u01cd", "A");
temp = temp.replaceAll("\u01de", "A");
temp = temp.replaceAll("\u01e0", "A");
temp = temp.replaceAll("\u01fa", "A");
temp = temp.replaceAll("\u0200", "A");
temp = temp.replaceAll("\u0202", "A");
temp = temp.replaceAll("\u0226", "A");
temp = temp.replaceAll("\u00e0", "a");
temp = temp.replaceAll("\u00e1", "a");
temp = temp.replaceAll("\u00e2", "a");
temp = temp.replaceAll("\u00e3", "a");
temp = temp.replaceAll("\u00e4", "a");
temp = temp.replaceAll("\u00e5", "a");
temp = temp.replaceAll("\u0101", "a");
temp = temp.replaceAll("\u0103", "a");
temp = temp.replaceAll("\u0105", "a");
temp = temp.replaceAll("\u01ce", "a");
temp = temp.replaceAll("\u01df", "a");
temp = temp.replaceAll("\u01e1", "a");
temp = temp.replaceAll("\u01fb", "a");
temp = temp.replaceAll("\u0201", "a");
temp = temp.replaceAll("\u0203", "a");
temp = temp.replaceAll("\u0227", "a");
temp = temp.replaceAll("\u00c6", "AE");
temp = temp.replaceAll("\u01e2", "AE");
temp = temp.replaceAll("\u01fc", "AE");
temp = temp.replaceAll("\u00e6", "ae");
temp = temp.replaceAll("\u01e3", "ae");
temp = temp.replaceAll("\u01fd", "ae");
temp = temp.replaceAll("\u008c", "OE");
temp = temp.replaceAll("\u0152", "OE");
temp = temp.replaceAll("\u009c", "oe");
temp = temp.replaceAll("\u0153", "oe");
temp = temp.replaceAll("\u00c7", "C");
temp = temp.replaceAll("\u0106", "C");
temp = temp.replaceAll("\u0108", "C");
temp = temp.replaceAll("\u010a", "C");
temp = temp.replaceAll("\u010c", "C");
temp = temp.replaceAll("\u00e7", "c");
temp = temp.replaceAll("\u0107", "c");
temp = temp.replaceAll("\u0109", "c");
temp = temp.replaceAll("\u010b", "c");
temp = temp.replaceAll("\u010d", "c");
temp = temp.replaceAll("\u00d0", "D");
temp = temp.replaceAll("\u010e", "D");
temp = temp.replaceAll("\u0110", "D");
temp = temp.replaceAll("\u00f0", "d");
temp = temp.replaceAll("\u010f", "d");
temp = temp.replaceAll("\u0111", "d");
temp = temp.replaceAll("\u00c8", "E");
temp = temp.replaceAll("\u00c9", "E");
temp = temp.replaceAll("\u00ca", "E");
temp = temp.replaceAll("\u00cb", "E");
temp = temp.replaceAll("\u0112", "E");
temp = temp.replaceAll("\u0114", "E");
temp = temp.replaceAll("\u0116", "E");
temp = temp.replaceAll("\u0118", "E");
temp = temp.replaceAll("\u011a", "E");
temp = temp.replaceAll("\u0204", "E");
temp = temp.replaceAll("\u0206", "E");
temp = temp.replaceAll("\u0228", "E");
temp = temp.replaceAll("\u00e8", "e");
temp = temp.replaceAll("\u00e9", "e");
temp = temp.replaceAll("\u00ea", "e");
temp = temp.replaceAll("\u00eb", "e");
temp = temp.replaceAll("\u0113", "e");
temp = temp.replaceAll("\u0115", "e");
temp = temp.replaceAll("\u0117", "e");
temp = temp.replaceAll("\u0119", "e");
temp = temp.replaceAll("\u011b", "e");
temp = temp.replaceAll("\u01dd", "e");
temp = temp.replaceAll("\u0205", "e");
temp = temp.replaceAll("\u0207", "e");
temp = temp.replaceAll("\u0229", "e");
temp = temp.replaceAll("\u011c", "G");
temp = temp.replaceAll("\u011e", "G");
temp = temp.replaceAll("\u0120", "G");
temp = temp.replaceAll("\u0122", "G");
temp = temp.replaceAll("\u01e4", "G");
temp = temp.replaceAll("\u01e6", "G");
temp = temp.replaceAll("\u01f4", "G");
temp = temp.replaceAll("\u011d", "g");
temp = temp.replaceAll("\u011f", "g");
temp = temp.replaceAll("\u0121", "g");
temp = temp.replaceAll("\u0123", "g");
temp = temp.replaceAll("\u01e5", "g");
temp = temp.replaceAll("\u01e7", "g");
temp = temp.replaceAll("\u01f5", "g");
temp = temp.replaceAll("\u0124", "H");
temp = temp.replaceAll("\u0126", "H");
temp = temp.replaceAll("\u021e", "H");
temp = temp.replaceAll("\u0125", "h");
temp = temp.replaceAll("\u0127", "h");
temp = temp.replaceAll("\u021f", "h");
temp = temp.replaceAll("\u00cc", "I");
temp = temp.replaceAll("\u00cd", "I");
temp = temp.replaceAll("\u00ce", "I");
temp = temp.replaceAll("\u00cf", "I");
temp = temp.replaceAll("\u0128", "I");
temp = temp.replaceAll("\u012a", "I");
temp = temp.replaceAll("\u012c", "I");
temp = temp.replaceAll("\u012e", "I");
temp = temp.replaceAll("\u0130", "I");
temp = temp.replaceAll("\u01cf", "I");
temp = temp.replaceAll("\u0208", "I");
temp = temp.replaceAll("\u020a", "I");
temp = temp.replaceAll("\u00ec", "i");
temp = temp.replaceAll("\u00ed", "i");
temp = temp.replaceAll("\u00ee", "i");
temp = temp.replaceAll("\u00ef", "i");
temp = temp.replaceAll("\u0129", "i");
temp = temp.replaceAll("\u012b", "i");
temp = temp.replaceAll("\u012d", "i");
temp = temp.replaceAll("\u012f", "i");
temp = temp.replaceAll("\u0131", "i");
temp = temp.replaceAll("\u01d0", "i");
temp = temp.replaceAll("\u0209", "i");
temp = temp.replaceAll("\u020b", "i");
temp = temp.replaceAll("\u0132", "IJ");
temp = temp.replaceAll("\u0133", "ij");
temp = temp.replaceAll("\u0134", "J");
temp = temp.replaceAll("\u0135", "j");
temp = temp.replaceAll("\u0136", "K");
temp = temp.replaceAll("\u01e8", "K");
temp = temp.replaceAll("\u0137", "k");
temp = temp.replaceAll("\u0138", "k");
temp = temp.replaceAll("\u01e9", "k");
temp = temp.replaceAll("\u0139", "L");
temp = temp.replaceAll("\u013b", "L");
temp = temp.replaceAll("\u013d", "L");
temp = temp.replaceAll("\u013f", "L");
temp = temp.replaceAll("\u0141", "L");
temp = temp.replaceAll("\u013a", "l");
temp = temp.replaceAll("\u013c", "l");
temp = temp.replaceAll("\u013e", "l");
temp = temp.replaceAll("\u0140", "l");
temp = temp.replaceAll("\u0142", "l");
temp = temp.replaceAll("\u0234", "l");
temp = temp.replaceAll("\u00d1", "N");
temp = temp.replaceAll("\u0143", "N");
temp = temp.replaceAll("\u0145", "N");
temp = temp.replaceAll("\u0147", "N");
temp = temp.replaceAll("\u014a", "N");
temp = temp.replaceAll("\u01f8", "N");
temp = temp.replaceAll("\u00f1", "n");
temp = temp.replaceAll("\u0144", "n");
temp = temp.replaceAll("\u0146", "n");
temp = temp.replaceAll("\u0148", "n");
temp = temp.replaceAll("\u0149", "n");
temp = temp.replaceAll("\u014b", "n");
temp = temp.replaceAll("\u01f9", "n");
temp = temp.replaceAll("\u0235", "n");
temp = temp.replaceAll("\u00d2", "O");
temp = temp.replaceAll("\u00d3", "O");
temp = temp.replaceAll("\u00d4", "O");
temp = temp.replaceAll("\u00d5", "O");
temp = temp.replaceAll("\u00d6", "O");
temp = temp.replaceAll("\u00d8", "O");
temp = temp.replaceAll("\u014c", "O");
temp = temp.replaceAll("\u014e", "O");
temp = temp.replaceAll("\u0150", "O");
temp = temp.replaceAll("\u01d1", "O");
temp = temp.replaceAll("\u01ea", "O");
temp = temp.replaceAll("\u01ec", "O");
temp = temp.replaceAll("\u01fe", "O");
temp = temp.replaceAll("\u020c", "O");
temp = temp.replaceAll("\u020e", "O");
temp = temp.replaceAll("\u022a", "O");
temp = temp.replaceAll("\u022c", "O");
temp = temp.replaceAll("\u022e", "O");
temp = temp.replaceAll("\u0230", "O");
temp = temp.replaceAll("\u00f2", "o");
temp = temp.replaceAll("\u00f3", "o");
temp = temp.replaceAll("\u00f4", "o");
temp = temp.replaceAll("\u00f5", "o");
temp = temp.replaceAll("\u00f6", "o");
temp = temp.replaceAll("\u00f8", "o");
temp = temp.replaceAll("\u014d", "o");
temp = temp.replaceAll("\u014f", "o");
temp = temp.replaceAll("\u0151", "o");
temp = temp.replaceAll("\u01d2", "o");
temp = temp.replaceAll("\u01eb", "o");
temp = temp.replaceAll("\u01ed", "o");
temp = temp.replaceAll("\u01ff", "o");
temp = temp.replaceAll("\u020d", "o");
temp = temp.replaceAll("\u020f", "o");
temp = temp.replaceAll("\u022b", "o");
temp = temp.replaceAll("\u022d", "o");
temp = temp.replaceAll("\u022f", "o");
temp = temp.replaceAll("\u0231", "o");
temp = temp.replaceAll("\u0156", "R");
temp = temp.replaceAll("\u0158", "R");
temp = temp.replaceAll("\u0210", "R");
temp = temp.replaceAll("\u0212", "R");
temp = temp.replaceAll("\u0157", "r");
temp = temp.replaceAll("\u0159", "r");
temp = temp.replaceAll("\u0211", "r");
temp = temp.replaceAll("\u0213", "r");
temp = temp.replaceAll("\u015a", "S");
temp = temp.replaceAll("\u015c", "S");
temp = temp.replaceAll("\u015e", "S");
temp = temp.replaceAll("\u0160", "S");
temp = temp.replaceAll("\u0218", "S");
temp = temp.replaceAll("\u015b", "s");
temp = temp.replaceAll("\u015d", "s");
temp = temp.replaceAll("\u015f", "s");
temp = temp.replaceAll("\u0161", "s");
temp = temp.replaceAll("\u0219", "s");
temp = temp.replaceAll("\u00de", "T");
temp = temp.replaceAll("\u0162", "T");
temp = temp.replaceAll("\u0164", "T");
temp = temp.replaceAll("\u0166", "T");
temp = temp.replaceAll("\u021a", "T");
temp = temp.replaceAll("\u00fe", "t");
temp = temp.replaceAll("\u0163", "t");
temp = temp.replaceAll("\u0165", "t");
temp = temp.replaceAll("\u0167", "t");
temp = temp.replaceAll("\u021b", "t");
temp = temp.replaceAll("\u0236", "t");
temp = temp.replaceAll("\u00d9", "U");
temp = temp.replaceAll("\u00da", "U");
temp = temp.replaceAll("\u00db", "U");
temp = temp.replaceAll("\u00dc", "U");
temp = temp.replaceAll("\u0168", "U");
temp = temp.replaceAll("\u016a", "U");
temp = temp.replaceAll("\u016c", "U");
temp = temp.replaceAll("\u016e", "U");
temp = temp.replaceAll("\u0170", "U");
temp = temp.replaceAll("\u0172", "U");
temp = temp.replaceAll("\u01d3", "U");
temp = temp.replaceAll("\u01d5", "U");
temp = temp.replaceAll("\u01d7", "U");
temp = temp.replaceAll("\u01d9", "U");
temp = temp.replaceAll("\u01db", "U");
temp = temp.replaceAll("\u0214", "U");
temp = temp.replaceAll("\u0216", "U");
temp = temp.replaceAll("\u00f9", "u");
temp = temp.replaceAll("\u00fa", "u");
temp = temp.replaceAll("\u00fb", "u");
temp = temp.replaceAll("\u00fc", "u");
temp = temp.replaceAll("\u0169", "u");
temp = temp.replaceAll("\u016b", "u");
temp = temp.replaceAll("\u016d", "u");
temp = temp.replaceAll("\u016f", "u");
temp = temp.replaceAll("\u0171", "u");
temp = temp.replaceAll("\u0173", "u");
temp = temp.replaceAll("\u01d4", "u");
temp = temp.replaceAll("\u01d6", "u");
temp = temp.replaceAll("\u01d8", "u");
temp = temp.replaceAll("\u01da", "u");
temp = temp.replaceAll("\u01dc", "u");
temp = temp.replaceAll("\u0215", "u");
temp = temp.replaceAll("\u0217", "u");
temp = temp.replaceAll("\u0174", "W");
temp = temp.replaceAll("\u0175", "w");
temp = temp.replaceAll("\u00dd", "Y");
temp = temp.replaceAll("\u0176", "Y");
temp = temp.replaceAll("\u0178", "Y");
temp = temp.replaceAll("\u0232", "Y");
temp = temp.replaceAll("\u00fd", "y");
temp = temp.replaceAll("\u00ff", "y");
temp = temp.replaceAll("\u0177", "y");
temp = temp.replaceAll("\u0233", "y");
temp = temp.replaceAll("\u0179", "Z");
temp = temp.replaceAll("\u017b", "Z");
temp = temp.replaceAll("\u017d", "Z");
temp = temp.replaceAll("\u017a", "z");
temp = temp.replaceAll("\u017c", "z");
temp = temp.replaceAll("\u017e", "z");
temp = temp.replaceAll("\u00df", "ss");
return temp;
}
public static boolean isAlphaNumeric(String text)
{
return StringUtils.isAlphanumeric(text.replaceAll("-", "a").replaceAll("\\.", "a"));
}
public static String getName(String name)
{
int i0 = name.indexOf(":");
if (i0 != -1) {
name = name.substring(i0 + 1);
return name;
}
if (name.indexOf(".") != -1) {
return name;
} else {
return "XWiki." + name;
}
}
public static String getName(String name, XWikiContext context)
{
String database = null;
int i0 = name.indexOf(":");
if (i0 != -1) {
database = name.substring(0, i0);
name = name.substring(i0 + 1);
context.setDatabase(database);
return name;
}
// This does not make sense
// context.setDatabase(context.getWiki().getDatabase());
if (name.indexOf(".") != -1) {
return name;
} else {
return "XWiki." + name;
}
}
public static Cookie getCookie(String cookieName, XWikiContext context)
{
return getCookie(cookieName, context.getRequest());
}
public static Cookie getCookie(String cookieName, HttpServletRequest request)
{
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
return (cookie);
}
}
}
return null;
}
public static String getHTMLExceptionMessage(XWikiException xe, XWikiContext context)
{
String title;
String text;
title = xe.getMessage();
text = com.xpn.xwiki.XWiki.getFormEncoded(xe.getFullMessage());
String id = (String) context.get("xwikierrorid");
if (id == null) {
id = "1";
} else {
id = "" + (Integer.parseInt(id) + 1);
}
return "<a href=\"\" onclick=\"document.getElementById('xwikierror" + id
+ "').style.display='block'; return false;\">" + title + "</a><div id=\"xwikierror" + id
+ "\" style=\"display: none;\"><pre class=\"xwikierror\">\n" + text + "</pre></div>";
}
public static String secureLaszloCode(String laszlocode) throws XWikiException
{
SAXReader reader = new SAXReader();
Document domdoc;
try {
StringReader in = new StringReader(laszlocode);
domdoc = reader.read(in);
} catch (DocumentException e) {
throw new XWikiException(XWikiException.MODULE_PLUGIN_LASZLO, XWikiException.ERROR_LASZLO_INVALID_XML,
"Invalid Laszlo XML", e);
}
String code = domdoc.asXML();
if (code.indexOf("..") != -1) {
throw new XWikiException(XWikiException.MODULE_PLUGIN_LASZLO, XWikiException.ERROR_LASZLO_INVALID_DOTDOT,
"Invalid content in Laszlo XML");
}
return laszlocode;
}
public static MonitorPlugin getMonitorPlugin(XWikiContext context)
{
try {
if ((context == null) || (context.getWiki() == null)) {
return null;
}
return (MonitorPlugin) context.getWiki().getPlugin("monitor", context);
} catch (Exception e) {
return null;
}
}
/**
* API to obtain a DOM document for the specified string
*
* @param str The parsed text
* @return A DOM document element corresponding to the string, or null on error
*/
public org.w3c.dom.Document getDOMForString(String str)
{
try {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
new InputSource(new StringReader(str)));
} catch (SAXException ex) {
LOG.warn("Cannot parse string:" + str, ex);
} catch (IOException ex) {
LOG.warn("Cannot parse string:" + str, ex);
} catch (ParserConfigurationException ex) {
LOG.warn("Cannot parse string:" + str, ex);
}
return null;
}
/**
* API to get a new DOM document
*
* @return a new DOM document element, or null on error
*/
public org.w3c.dom.Document getDOMDocument()
{
try {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
} catch (ParserConfigurationException ex) {
LOG.warn("Cannot create DOM tree", ex);
}
return null;
}
/**
* API to protect Text from Radeox transformation
*
* @param text
* @return escaped text
*/
public static String escapeText(String text)
{
text = text.replaceAll("http://", "http://");
text = text.replaceAll("ftp://", "ftp://");
text = text.replaceAll("\\-", "&
text = text.replaceAll("\\*", "&
text = text.replaceAll("\\~", "~");
text = text.replaceAll("\\[", "&
text = text.replaceAll("\\]", "&
text = text.replaceAll("\\{", "{");
text = text.replaceAll("\\}", "}");
text = text.replaceAll("\\1", "&
return text;
}
/**
* API to protect URLs from Radeox transformation
*
* @param url
* @return encoded URL
*/
public static String escapeURL(String url)
{
url = url.replaceAll("\\~", "%7E");
url = url.replaceAll("\\[", "%5B");
url = url.replaceAll("\\]", "%5D");
url = url.replaceAll("\\{", "%7B");
url = url.replaceAll("\\}", "%7D");
// We should not encode the following char for non local urls
// since this might not be handle correctly by FF
if (url.indexOf("
url = url.replaceAll("-", "%2D");
url = url.replaceAll("\\*", "%2A");
}
return url;
}
/**
* API to make a text URI compliant
*
* @param text
* @param context
* @return encoded text
*/
public static String encodeURI(String text, XWikiContext context)
{
try {
return URLEncoder.encode(text, context.getWiki().getEncoding());
} catch (Exception e) {
return text;
}
}
/**
* API to make readable an URI compliant text
*
* @param text
* @param context
* @return decoded text
*/
public static String decodeURI(String text, XWikiContext context)
{
try {
// Make sure + is considered as a space
String result = text.replaceAll("\\+", " ");
// It seems Internet Explorer can send us back UTF-8
// instead of ISO-8859-1 for URLs
if (Base64.isValidUTF8(result.getBytes(), false)) {
result = new String(result.getBytes(), "UTF-8");
}
// Still need to decode URLs
return URLDecoder.decode(result, context.getWiki().getEncoding());
} catch (Exception e) {
return text;
}
}
/**
* Removes all non alpha numerical characters from the passed text. First tries to convert accented chars to their
* alpha numeric representation.
*
* @param text the text to convert
* @return the alpha numeric equivalent
*/
public static String convertToAlphaNumeric(String text)
{
// Start by removing accents
String textNoAccents = Util.noaccents(text);
// Now remove all non alphanumeric chars
StringBuffer result = new StringBuffer(textNoAccents.length());
char[] testChars = textNoAccents.toCharArray();
for (char testChar : testChars) {
if (Character.isLetterOrDigit(testChar) && testChar < 128) {
result.append(testChar);
}
}
return result.toString();
}
public static Date getFileLastModificationDate(String path)
{
try {
File f = new File(path);
return (new Date(f.lastModified()));
} catch (Exception ex) {
return new Date();
}
}
/**
* Validate a XML element name. XML elements must follow these naming rules :
* <ul>
* <li>Names can contain letters, numbers, and the following characters [., -, _, :].</li>
* <li>Names must not start with a number or punctuation character.</li>
* <li>Names must not start with the letters xml (or XML, or Xml, etc).</li>
* <li>Names cannot contain spaces.</li>
* </ul>
*
* @param elementName the XML element name to validate
* @return true if the element name is valid, false if it is not
*/
public static boolean isValidXMLElementName(String elementName)
{
if (elementName == null || elementName.equals("") || elementName.matches("(?i)^(xml).*")
|| !elementName.matches("(^[a-zA-Z\\-\\_]+[\\w\\.\\-\\_\\:]*$)")) {
return false;
}
return true;
}
/**
* Load resources from: 1. FileSystem 2. ServletContext 3. ClassPath in this order.
*
* @param resource resource path to load
* @return InputStream of resource or null if not found
*/
public static InputStream getResourceAsStream(String resource)
{
File file = new File(resource);
try {
if (file.exists()) {
return new FileInputStream(file);
}
} catch (Exception e) {
// Probably running under -security, which prevents calling File.exists()
LOG.debug("Failed load resource [" + resource + "] using a file path");
}
try {
Container container = Utils.getComponent(Container.class);
InputStream res = container.getApplicationContext().getResourceAsStream(resource);
if (res != null) {
return res;
}
} catch (Exception e) {
LOG.debug("Failed load resource [" + resource + "] using a application context");
}
return Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
}
} |
package org.nschmidt.ldparteditor.ldraworg;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.nschmidt.ldparteditor.enums.MyLanguage;
import org.nschmidt.ldparteditor.i18n.I18n;
import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow;
import org.nschmidt.ldparteditor.text.UTF8PrintWriter;
import org.nschmidt.ldparteditor.win32appdata.AppData;
public enum CategoriesUtils {
INSTANCE;
public static void downloadCategories() {
final Editor3DWindow win = Editor3DWindow.getWindow();
final List<String> categories = new ArrayList<>();
try {
URL go = new URL("https:
URLConnection uc = go.openConnection();
try (BufferedReader in =
new BufferedReader(
new InputStreamReader(
uc.getInputStream()))) {
String inputLine;
int[] state = new int[]{0};
boolean[] parse = new boolean[]{false};
final StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
inputLine.chars().forEach(c -> {
if (parse[0] && c != '<') {
sb.append((char) c);
}
switch (c) {
case '<':
if (parse[0]) {
String category = sb.toString().trim();
if (category.length() > 0) {
categories.add(category);
}
}
parse[0] = false;
state[0] = 1;
sb.setLength(0);
break;
case 'l':
if (state[0] == 1) {
state[0] = 2;
} else {
state[0] = 0;
}
break;
case 'i':
if (state[0] == 2) {
state[0] = 3;
} else {
state[0] = 0;
}
break;
case '>':
if (state[0] == 3) {
parse[0] = true;
}
state[0] = 0;
break;
default:
if (!parse[0]) {
state[0] = 0;
}
break;
}
});
}
}
} catch (IOException ioe) {
MessageBox messageBoxError = new MessageBox(win.getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.E3D_CantConnectToLDrawOrg);
messageBoxError.open();
return;
}
Object[] messageArguments = {AppData.getPath() + "categories.txt", categories.size()}; //$NON-NLS-1$
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.E3D_ReplaceCategories);
MessageBox messageBoxReplace = new MessageBox(win.getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBoxReplace.setText(I18n.DIALOG_Info);
messageBoxReplace.setMessage(formatter.format(messageArguments));
if (messageBoxReplace.open() != SWT.YES) {
return;
}
try (UTF8PrintWriter out = new UTF8PrintWriter(AppData.getPath() + "categories.txt")) { //$NON-NLS-1$
for (String line : categories) {
out.println(line);
}
out.flush();
} catch (FileNotFoundException | UnsupportedEncodingException ldpe) {
MessageBox messageBoxError = new MessageBox(win.getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.E3D_FileWasReplacedError);
messageBoxError.open();
return;
}
MessageBox messageBoxDone = new MessageBox(win.getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBoxDone.setText(I18n.DIALOG_Info);
messageBoxDone.setMessage(I18n.E3D_FileWasReplaced);
messageBoxDone.open();
}
} |
package org.yamcs;
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.yamcs.api.EventProducer;
import org.yamcs.api.EventProducerFactory;
import org.yamcs.parameter.ParameterConsumer;
import org.yamcs.parameter.ParameterRequestManagerImpl;
import org.yamcs.protobuf.Pvalue.MonitoringResult;
import org.yamcs.utils.StringConvertors;
import org.yamcs.xtce.AlarmReportType;
import org.yamcs.xtce.AlarmType;
import org.yamcs.xtce.Parameter;
import org.yamcs.xtce.ParameterType;
import org.yamcs.xtce.XtceDb;
import org.yamcs.xtceproc.XtceDbFactory;
import com.google.common.util.concurrent.AbstractService;
/**
* Generates realtime alarm events automatically, by subscribing to all relevant
* parameters.
*/
public class AlarmReporter extends AbstractService implements ParameterConsumer {
private EventProducer eventProducer;
private Map<Parameter, ActiveAlarm> activeAlarms=new HashMap<Parameter, ActiveAlarm>();
// Last value of each param (for detecting changes in value)
private Map<Parameter, ParameterValue> lastValuePerParameter=new HashMap<Parameter, ParameterValue>();
final String yamcsInstance;
final String yprocName;
public AlarmReporter(String yamcsInstance) {
this(yamcsInstance, "tm_realtime");
}
public AlarmReporter(String yamcsInstance, String yprocName) {
this.yamcsInstance = yamcsInstance;
this.yprocName = yprocName;
eventProducer=EventProducerFactory.getEventProducer(yamcsInstance);
eventProducer.setSource("AlarmChecker");
}
@Override
public void doStart() {
YProcessor yproc = YProcessor.getInstance(yamcsInstance, yprocName);
if(yproc==null) {
ConfigurationException e = new ConfigurationException("Cannot find a yproc '"+yprocName+"' in instance '"+yamcsInstance+"'");
notifyFailed(e);
return;
}
ParameterRequestManagerImpl prm = yproc.getParameterRequestManager();
prm.getAlarmChecker().enableReporting(this);
// Auto-subscribe to parameters with alarms
Set<Parameter> requiredParameters=new HashSet<Parameter>();
try {
XtceDb xtcedb=XtceDbFactory.getInstance(yamcsInstance);
for (Parameter parameter:xtcedb.getParameters()) {
ParameterType ptype=parameter.getParameterType();
if(ptype!=null && ptype.hasAlarm()) {
requiredParameters.add(parameter);
Set<Parameter> dependentParameters = ptype.getDependentParameters();
if(dependentParameters!=null) {
requiredParameters.addAll(dependentParameters);
}
}
}
} catch(ConfigurationException e) {
notifyFailed(e);
return;
}
if(!requiredParameters.isEmpty()) {
List<Parameter> params=new ArrayList<Parameter>(requiredParameters); // Now that we have uniques..
try {
prm.addRequest(params, this);
} catch(InvalidIdentification e) {
throw new RuntimeException("Could not register dependencies for alarms", e);
}
}
notifyStarted();
}
@Override
public void doStop() {
notifyStopped();
}
@Override
public void updateItems(int subscriptionId, List<ParameterValue> items) {
// Nothing. The real business of sending events, happens while checking the alarms
// because that's where we have easy access to the XTCE definition of the active
// alarm. The PRM is only used to signal the parameter subscriptions.
}
/**
* Sends an event if an alarm condition for the active context has been
* triggered <tt>minViolations</tt> times. This configuration does not
* affect events for parameters that go back to normal, or that change
* severity levels while the alarm is already active.
*/
public void reportNumericParameterEvent(ParameterValue pv, AlarmType alarmType, int minViolations) {
boolean sendUpdateEvent=false;
if(alarmType.getAlarmReportType()==AlarmReportType.ON_VALUE_CHANGE) {
ParameterValue oldPv=lastValuePerParameter.get(pv.def);
if(oldPv!=null && hasChanged(oldPv, pv)) {
sendUpdateEvent=true;
}
lastValuePerParameter.put(pv.def, pv);
}
if(pv.getMonitoringResult()==MonitoringResult.IN_LIMITS) {
if(activeAlarms.containsKey(pv.getParameter())) {
eventProducer.sendInfo("NORMAL", "Parameter "+pv.getParameter().getQualifiedName()+" is back to normal");
activeAlarms.remove(pv.getParameter());
}
} else { // out of limits
MonitoringResult previousMonitoringResult=null;
ActiveAlarm activeAlarm=activeAlarms.get(pv.getParameter());
if(activeAlarm==null || activeAlarm.alarmType!=alarmType) {
activeAlarm=new ActiveAlarm(alarmType, pv.getMonitoringResult());
} else {
previousMonitoringResult=activeAlarm.monitoringResult;
activeAlarm.monitoringResult=pv.getMonitoringResult();
activeAlarm.violations++;
}
if(activeAlarm.violations==minViolations || (activeAlarm.violations>minViolations && previousMonitoringResult!=activeAlarm.monitoringResult)) {
sendUpdateEvent=true;
}
activeAlarms.put(pv.getParameter(), activeAlarm);
}
if(sendUpdateEvent) {
sendValueChangeEvent(pv);
}
}
public void reportEnumeratedParameterEvent(ParameterValue pv, AlarmType alarmType, int minViolations) {
boolean sendUpdateEvent=false;
if(alarmType.getAlarmReportType()==AlarmReportType.ON_VALUE_CHANGE) {
ParameterValue oldPv=lastValuePerParameter.get(pv.def);
if(oldPv!=null && hasChanged(oldPv, pv)) {
sendUpdateEvent=true;
}
lastValuePerParameter.put(pv.def, pv);
}
if(pv.getMonitoringResult()==MonitoringResult.IN_LIMITS) {
if(activeAlarms.containsKey(pv.getParameter())) {
eventProducer.sendInfo("NORMAL", "Parameter "+pv.getParameter().getQualifiedName()+" is back to a normal state ("+pv.getEngValue().getStringValue()+")");
activeAlarms.remove(pv.getParameter());
}
} else { // out of limits
MonitoringResult previousMonitoringResult=null;
ActiveAlarm activeAlarm=activeAlarms.get(pv.getParameter());
if(activeAlarm==null || activeAlarm.alarmType!=alarmType) {
activeAlarm=new ActiveAlarm(alarmType, pv.getMonitoringResult());
} else {
previousMonitoringResult=activeAlarm.monitoringResult;
activeAlarm.monitoringResult=pv.getMonitoringResult();
activeAlarm.violations++;
}
if(activeAlarm.violations==minViolations || (activeAlarm.violations>minViolations&& previousMonitoringResult!=activeAlarm.monitoringResult)) {
sendUpdateEvent=true;
}
activeAlarms.put(pv.getParameter(), activeAlarm);
}
if(sendUpdateEvent) {
sendStateChangeEvent(pv);
}
}
private void sendValueChangeEvent(ParameterValue pv) {
switch(pv.getMonitoringResult()) {
case WATCH_LOW:
case WARNING_LOW:
eventProducer.sendWarning(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" is too low");
break;
case WATCH_HIGH:
case WARNING_HIGH:
eventProducer.sendWarning(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" is too high");
break;
case DISTRESS_LOW:
case CRITICAL_LOW:
case SEVERE_LOW:
eventProducer.sendError(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" is too low");
break;
case DISTRESS_HIGH:
case CRITICAL_HIGH:
case SEVERE_HIGH:
eventProducer.sendError(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" is too high");
break;
case IN_LIMITS:
eventProducer.sendInfo(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" has changed to value "+StringConvertors.toString(pv.getEngValue(), false));
break;
default:
throw new IllegalStateException("Unexpected monitoring result: "+pv.getMonitoringResult());
}
}
private void sendStateChangeEvent(ParameterValue pv) {
switch(pv.getMonitoringResult()) {
case WATCH:
case WARNING:
eventProducer.sendWarning(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" transitioned to state "+pv.getEngValue().getStringValue());
break;
case DISTRESS:
case CRITICAL:
case SEVERE:
eventProducer.sendError(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" transitioned to state "+pv.getEngValue().getStringValue());
break;
case IN_LIMITS:
eventProducer.sendInfo(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" transitioned to state "+pv.getEngValue().getStringValue());
break;
default:
throw new IllegalStateException("Unexpected monitoring result: "+pv.getMonitoringResult());
}
}
private boolean hasChanged(ParameterValue pvOld, ParameterValue pvNew) {
// Crude string value comparison.
return !StringConvertors.toString(pvOld.getEngValue(), false)
.equals(StringConvertors.toString(pvNew.getEngValue(), false));
}
private static class ActiveAlarm {
MonitoringResult monitoringResult;
AlarmType alarmType;
int violations=1;
ParameterValue lastValue;
ActiveAlarm(AlarmType alarmType, MonitoringResult monitoringResult) {
this.alarmType=alarmType;
this.monitoringResult=monitoringResult;
}
}
} |
package org.odk.collect.android.widgets;
import java.util.ArrayList;
import java.util.Vector;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryPrompt;
import android.R;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;
/**
* AutoCompleteWidget handles select-one fields using an autocomplete text box. The user types part
* of the desired selection and suggestions appear in a list below. The full list of possible
* answers is not displayed to the user. The goal is to be more compact; this question type is best
* suited for select one questions with a large number of possible answers. If images, audio, or
* video are specified in the select answers they are ignored.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class AutoCompleteWidget extends QuestionWidget {
AutoCompleteAdapter choices;
AutoCompleteTextView autocomplete;
Vector<SelectChoice> mItems;
// Defines which filter to use to display autocomplete possibilities
String filterType;
// The various filter types
String match_substring = "substring";
String match_prefix = "prefix";
String match_chars = "chars";
public AutoCompleteWidget(Context context, FormEntryPrompt prompt, String filterType) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mPrompt = prompt;
choices = new AutoCompleteAdapter(getContext(), android.R.layout.simple_list_item_1);
autocomplete = new AutoCompleteTextView(getContext());
// Default to matching substring
if (filterType != null) {
this.filterType = filterType;
} else {
this.filterType = match_substring;
}
for (SelectChoice sc : mItems) {
choices.add(prompt.getSelectChoiceText(sc));
}
choices.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
autocomplete.setAdapter(choices);
autocomplete.setTextColor(Color.BLACK);
setGravity(Gravity.LEFT);
// Fill in answer
String s = null;
if (mPrompt.getAnswerValue() != null) {
s = ((Selection) mPrompt.getAnswerValue().getValue()).getValue();
}
for (int i = 0; i < mItems.size(); ++i) {
String sMatch = mItems.get(i).getValue();
if (sMatch.equals(s)) {
autocomplete.setText(sMatch);
}
}
addView(autocomplete);
}
@Override
public IAnswerData getAnswer() {
String response = autocomplete.getText().toString();
for (SelectChoice sc : mItems) {
if (response.equals(mPrompt.getSelectChoiceText(sc))) {
return new SelectOneData(new Selection(sc));
}
}
// If the user has typed text into the autocomplete box that doesn't match any answer, warn
// them that their
// solution didn't count.
if (!response.equals("")) {
Toast.makeText(getContext(),
"Warning: \"" + response + "\" does not match any answers. No answer recorded.",
Toast.LENGTH_LONG).show();
}
return null;
}
@Override
public void clearAnswer() {
autocomplete.setText("");
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
private class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ItemsFilter mFilter;
public ArrayList<String> mItems;
public AutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
mItems = new ArrayList<String>();
}
@Override
public void add(String toAdd) {
super.add(toAdd);
mItems.add(toAdd);
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public String getItem(int position) {
return mItems.get(position);
}
@Override
public int getPosition(String item) {
return mItems.indexOf(item);
}
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemsFilter(mItems);
}
return mFilter;
}
@Override
public long getItemId(int position) {
return position;
}
private class ItemsFilter extends Filter {
final ArrayList<String> mItemsArray;
public ItemsFilter(ArrayList<String> list) {
if (list == null) {
mItemsArray = new ArrayList<String>();
} else {
mItemsArray = new ArrayList<String>(list);
}
}
@Override
protected FilterResults performFiltering(CharSequence prefix) {
// Initiate our results object
FilterResults results = new FilterResults();
// If the adapter array is empty, check the actual items array and use it
if (mItems == null) {
mItems = new ArrayList<String>(mItemsArray);
}
// No prefix is sent to filter by so we're going to send back the original array
if (prefix == null || prefix.length() == 0) {
results.values = mItemsArray;
results.count = mItemsArray.size();
} else {
// Compare lower case strings
String prefixString = prefix.toString().toLowerCase();
// Local to here so we're not changing actual array
final ArrayList<String> items = mItems;
final int count = items.size();
final ArrayList<String> newItems = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
final String item = items.get(i);
String item_compare = item.toLowerCase();
// Match the strings using the filter specified
if (filterType.equals(match_substring)
&& (item_compare.startsWith(prefixString) || item_compare
.contains(prefixString))) {
newItems.add(item);
} else if (filterType.equals(match_prefix)
&& item_compare.startsWith(prefixString)) {
newItems.add(item);
} else if (filterType.equals(match_chars)) {
char[] toMatch = prefixString.toCharArray();
boolean matches = true;
for (int j = 0; j < toMatch.length; j++) {
int index = item_compare.indexOf(toMatch[j]);
if (index > -1) {
item_compare =
item_compare.substring(0, index)
+ item_compare.substring(index + 1);
} else {
matches = false;
break;
}
}
if (matches) {
newItems.add(item);
}
} else {
// Default to substring
if (item_compare.startsWith(prefixString)
|| item_compare.contains(prefixString)) {
newItems.add(item);
}
}
}
// Set and return
results.values = newItems;
results.count = newItems.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mItems = (ArrayList<String>) results.values;
// Let the adapter know about the updated list
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
autocomplete.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
autocomplete.cancelLongPress();
}
} |
package org.openhab.habdroid.ui;
import java.net.MalformedURLException;
import java.net.URL;
import org.openhab.habdroid.R;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
/**
* This is a class to provide preferences activity for application.
*
* @author Victor Belov
*
*/
public class OpenHABPreferencesActivity extends PreferenceActivity {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference urlPreference = getPreferenceScreen().findPreference("default_openhab_url");
Preference altUrlPreference = getPreferenceScreen().findPreference("default_openhab_alturl");
Preference usernamePreference = getPreferenceScreen().findPreference("default_openhab_username");
Preference passwordPreference = getPreferenceScreen().findPreference("default_openhab_password");
Preference versionPreference = getPreferenceScreen().findPreference("default_openhab_appversion");
urlPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d("OpenHABPreferencesActivity", "Validating new url = " + (String)newValue);
String newUrl = (String)newValue;
if (newUrl.length() == 0 || urlIsValid(newUrl)) {
updateTextPreferenceSummary(preference, (String)newValue);
return true;
}
showAlertDialog(getString(R.string.erorr_invalid_url));
return false;
}
});
updateTextPreferenceSummary(urlPreference, null);
altUrlPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String newUrl = (String)newValue;
if (newUrl.length() == 0 || urlIsValid(newUrl)) {
updateTextPreferenceSummary(preference, (String)newValue);
return true;
}
showAlertDialog(getString(R.string.erorr_invalid_url));
return false;
}
});
updateTextPreferenceSummary(altUrlPreference, null);
usernamePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
updateTextPreferenceSummary(preference, (String)newValue);
return true;
}
});
updateTextPreferenceSummary(usernamePreference, null);
passwordPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
updatePasswordPreferenceSummary(preference, (String)newValue);
return true;
}
});
updatePasswordPreferenceSummary(passwordPreference, null);
updateTextPreferenceSummary(versionPreference, null);
setResult(RESULT_OK);
}
private void updateTextPreferenceSummary(Preference textPreference, String newValue) {
if (newValue == null) {
if (textPreference.getSharedPreferences().getString(textPreference.getKey(), "").length() > 0)
textPreference.setSummary(textPreference.getSharedPreferences().getString(textPreference.getKey(), ""));
else
textPreference.setSummary("Not set");
} else {
if (newValue.length() > 0)
textPreference.setSummary(newValue);
else
textPreference.setSummary("Not set");
}
}
private void updatePasswordPreferenceSummary(Preference passwordPreference, String newValue) {
if (newValue == null) {
if (passwordPreference.getSharedPreferences().getString(passwordPreference.getKey(), "").length() > 0)
passwordPreference.setSummary("******");
else
passwordPreference.setSummary("Not set");
} else {
if (newValue.length() > 0)
passwordPreference.setSummary("******");
else
passwordPreference.setSummary("Not set");
}
}
private boolean urlIsValid(String url) {
// As we accept an empty URL, which means it is not configured, length==0 is ok
if (url.length() == 0)
return true;
if (url.contains("\n") || url.contains(" "))
return false;
try {
URL testURL = new URL(url);
} catch (MalformedURLException e) {
return false;
}
return true;
}
private void showAlertDialog(String alertMessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(OpenHABPreferencesActivity.this);
builder.setMessage(alertMessage)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
} |
package org.pentaho.di.job.entries.zipfile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.vfs.FileObject;
import org.eclipse.swt.widgets.Shell;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.w3c.dom.Node;
/**
* This defines a 'zip file' job entry. Its main use would be to
* zip files in a directory and process zipped files (deleted or move)
*
* @author Samatar Hassan
* @since 27-02-2007
*
*/
public class JobEntryZipFile extends JobEntryBase implements Cloneable, JobEntryInterface
{
private String zipFilename;
public int compressionrate;
public int ifzipfileexists;
public int afterzip;
private String wildcard;
private String wildcardexclude;
private String sourcedirectory;
private String movetodirectory;
public JobEntryZipFile(String n)
{
super(n, "");
zipFilename=null;
ifzipfileexists=2;
afterzip=0;
compressionrate=1;
wildcard=null;
wildcardexclude=null;
sourcedirectory=null;
movetodirectory=null;
setID(-1L);
setType(JobEntryInterface.TYPE_JOBENTRY_ZIP_FILE);
}
public JobEntryZipFile()
{
this("");
}
public JobEntryZipFile(JobEntryBase jeb)
{
super(jeb);
}
public Object clone()
{
JobEntryZipFile je = (JobEntryZipFile) super.clone();
return je;
}
public String getXML()
{
StringBuffer retval = new StringBuffer(50);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("zipfilename", zipFilename));
retval.append(" ").append(XMLHandler.addTagValue("compressionrate", compressionrate));
retval.append(" ").append(XMLHandler.addTagValue("ifzipfileexists", ifzipfileexists));
retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard));
retval.append(" ").append(XMLHandler.addTagValue("wildcardexclude", wildcardexclude));
retval.append(" ").append(XMLHandler.addTagValue("sourcedirectory", sourcedirectory));
retval.append(" ").append(XMLHandler.addTagValue("movetodirectory", movetodirectory));
retval.append(" ").append(XMLHandler.addTagValue("afterzip", afterzip));
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, Repository rep)
throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases);
zipFilename = XMLHandler.getTagValue(entrynode, "zipfilename");
compressionrate = Const.toInt(XMLHandler.getTagValue(entrynode, "compressionrate"), -1);
ifzipfileexists = Const.toInt(XMLHandler.getTagValue(entrynode, "ifzipfileexists"), -1);
afterzip = Const.toInt(XMLHandler.getTagValue(entrynode, "afterzip"), -1);
wildcard = XMLHandler.getTagValue(entrynode, "wildcard");
wildcardexclude = XMLHandler.getTagValue(entrynode, "wildcardexclude");
sourcedirectory = XMLHandler.getTagValue(entrynode, "sourcedirectory");
movetodirectory = XMLHandler.getTagValue(entrynode, "movetodirectory");
}
catch(KettleXMLException xe)
{
throw new KettleXMLException("Unable to load job entry of type 'zipfile' from XML node", xe);
}
}
public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases)
throws KettleException
{
try
{
super.loadRep(rep, id_jobentry, databases);
zipFilename = rep.getJobEntryAttributeString(id_jobentry, "zipfilename");
compressionrate=(int) rep.getJobEntryAttributeInteger(id_jobentry, "compressionrate");
ifzipfileexists=(int) rep.getJobEntryAttributeInteger(id_jobentry, "ifzipfileexists");
afterzip=(int) rep.getJobEntryAttributeInteger(id_jobentry, "afterzip");
wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard");
wildcardexclude = rep.getJobEntryAttributeString(id_jobentry, "wildcardexclude");
sourcedirectory = rep.getJobEntryAttributeString(id_jobentry, "sourcedirectory");
movetodirectory = rep.getJobEntryAttributeString(id_jobentry, "movetodirectory");
}
catch(KettleException dbe)
{
throw new KettleException("Unable to load job entry of type 'zipfile' from the repository for id_jobentry="+id_jobentry, dbe);
}
}
public void saveRep(Repository rep, long id_job)
throws KettleException
{
try
{
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "zipfilename", zipFilename);
rep.saveJobEntryAttribute(id_job, getID(), "compressionrate", compressionrate);
rep.saveJobEntryAttribute(id_job, getID(), "ifzipfileexists", ifzipfileexists);
rep.saveJobEntryAttribute(id_job, getID(), "afterzip", afterzip);
rep.saveJobEntryAttribute(id_job, getID(), "wildcard", wildcard);
rep.saveJobEntryAttribute(id_job, getID(), "wildcardexclude", wildcardexclude);
rep.saveJobEntryAttribute(id_job, getID(), "sourcedirectory", sourcedirectory);
rep.saveJobEntryAttribute(id_job, getID(), "movetodirectory", movetodirectory);
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to save job entry of type 'zipfile' to the repository for id_job="+id_job, dbe);
}
}
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
Result result = previousResult;
result.setResult( false );
boolean Fileexists=false;
String realZipfilename = environmentSubstitute(zipFilename);
String realWildcard = environmentSubstitute(wildcard);
String realWildcardExclude = environmentSubstitute(wildcardexclude);
String realTargetdirectory = environmentSubstitute(sourcedirectory);
String realMovetodirectory = environmentSubstitute(movetodirectory);
if (realZipfilename!=null)
{
FileObject fileObject = null;
try {
fileObject = KettleVFS.getFileObject(realZipfilename);
// Check if Zip File exists
if ( fileObject.exists() )
{
Fileexists =true;
log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label")+ realZipfilename
+ Messages.getString("JobZipFiles.Zip_FileExists2.Label"));
}
else
{
Fileexists =false;
}
// Let's start the process now
if (ifzipfileexists==3 && Fileexists)
{
// the zip file exists and user want to Fail
result.setResult( false );
result.setNrErrors(1);
}
else if(ifzipfileexists==2 && Fileexists)
{
// the zip file exists and user want to do nothing
result.setResult( true );
}
else if(afterzip==2 && realMovetodirectory== null)
{
// After Zip, Move files..User must give a destination Folder
result.setResult( false );
result.setNrErrors(1);
log.logError(toString(), Messages.getString("JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label"));
}
else
// After Zip, Move files..User must give a destination Folder
{
if(ifzipfileexists==0 && Fileexists)
{
// the zip file exists and user want to create new one with unique name
//Format Date
DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");
realZipfilename=realZipfilename + "_" + dateFormat.format(new Date())+".zip";
log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileNameChange1.Label") + realZipfilename +
Messages.getString("JobZipFiles.Zip_FileNameChange1.Label"));
}
else if(ifzipfileexists==1 && Fileexists)
{
log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileAppend1.Label") + realZipfilename +
Messages.getString("JobZipFiles.Zip_FileAppend2.Label"));
}
// Get all the files in the directory...
File f = new File(realTargetdirectory);
String [] filelist = f.list();
log.logDetailed(toString(), Messages.getString("JobZipFiles.Files_Found1.Label") +filelist.length+
Messages.getString("JobZipFiles.Files_Found2.Label") + realTargetdirectory +
Messages.getString("JobZipFiles.Files_Found3.Label"));
Pattern pattern = null;
if (!Const.isEmpty(realWildcard))
{
pattern = Pattern.compile(realWildcard);
}
Pattern patternexclude = null;
if (!Const.isEmpty(realWildcardExclude))
{
patternexclude = Pattern.compile(realWildcardExclude);
}
// Prepare Zip File
byte[] buffer = new byte[18024];
FileOutputStream dest = new FileOutputStream(realZipfilename);
BufferedOutputStream buff = new BufferedOutputStream(dest);
ZipOutputStream out = new ZipOutputStream(buff);
// Set the method
out.setMethod(ZipOutputStream.DEFLATED);
// Set the compression level
if (compressionrate==0)
{
out.setLevel(Deflater.NO_COMPRESSION);
}
else if (compressionrate==1)
{
out.setLevel(Deflater.DEFAULT_COMPRESSION);
}
if (compressionrate==2)
{
out.setLevel(Deflater.BEST_COMPRESSION);
}
if (compressionrate==3)
{
out.setLevel(Deflater.BEST_SPEED);
}
// Specify Zipped files (After that we will move,delete them...)
String[] ZippedFiles = new String[filelist.length];
int FileNum=0;
// Get the files in the list...
for (int i=0;i<filelist.length && !parentJob.isStopped();i++)
{
boolean getIt = true;
boolean getItexclude = false;
// First see if the file matches the regular expression!
if (pattern!=null)
{
Matcher matcher = pattern.matcher(filelist[i]);
getIt = matcher.matches();
}
if (patternexclude!=null)
{
Matcher matcherexclude = patternexclude.matcher(filelist[i]);
getItexclude = matcherexclude.matches();
}
// Get processing File
String targetFilename = realTargetdirectory+Const.FILE_SEPARATOR+filelist[i];
File file = new File(targetFilename);
if (getIt && !getItexclude && !file.isDirectory())
{
// We can add the file to the Zip Archive
log.logDebug(toString(), Messages.getString("JobZipFiles.Add_FilesToZip1.Label")+filelist[i]+
Messages.getString("JobZipFiles.Add_FilesToZip2.Label")+realTargetdirectory+
Messages.getString("JobZipFiles.Add_FilesToZip3.Label"));
// Associate a file input stream for the current file
FileInputStream in = new FileInputStream(targetFilename);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filelist[i]));
int len;
while ((len = in.read(buffer)) > 0)
{
out.write(buffer, 0, len);
}
out.closeEntry();
// Close the current file input stream
in.close();
// Get Zipped File
ZippedFiles[FileNum] = filelist[i];
FileNum=FileNum+1;
}
}
// Close the ZipOutPutStream
out.close();
if (afterzip == 1 || afterzip == 2)
{
// iterate through the array of Zipped files
for (int i = 0; i < ZippedFiles.length; i++)
{
if ( ZippedFiles[i] != null)
{
// Delete File
FileObject fileObjectd = KettleVFS.getFileObject(realTargetdirectory+Const.FILE_SEPARATOR+ZippedFiles[i]);
// Here gc() is explicitly called if e.g. createfile is used in the same
// job for the same file. The problem is that after creating the file the
// file object is not properly garbaged collected and thus the file cannot
// be deleted anymore. This is a known problem in the JVM.
System.gc();
// Here we can move, delete files
if (afterzip == 1)
{
// Delete File
boolean deleted = fileObjectd.delete();
if ( ! deleted )
{
result.setResult( false );
result.setNrErrors(1);
log.logError(toString(), Messages.getString("JobZipFiles.Cant_Delete_File1.Label")+
realTargetdirectory+Const.FILE_SEPARATOR+ZippedFiles[i]+
Messages.getString("JobZipFiles.Cant_Delete_File2.Label"));
}
// File deleted
log.logDebug(toString(), Messages.getString("JobZipFiles.File_Deleted1.Label") +
realTargetdirectory+Const.FILE_SEPARATOR+ZippedFiles[i] +
Messages.getString("JobZipFiles.File_Deleted2.Label"));
}
else if(afterzip == 2)
{
// Move File
try
{
FileObject fileObjectm = KettleVFS.getFileObject(realMovetodirectory + Const.FILE_SEPARATOR+ZippedFiles[i]);
fileObjectd.moveTo(fileObjectm);
}
catch (IOException e)
{
log.logError(toString(), Messages.getString("JobZipFiles.Cant_Move_File1.Label") +ZippedFiles[i]+
Messages.getString("JobZipFiles.Cant_Move_File2.Label") + e.getMessage());
result.setResult( false );
result.setNrErrors(1);
}
// File moved
log.logDebug(toString(), Messages.getString("JobZipFiles.File_Moved1.Label") + ZippedFiles[i] +
Messages.getString("JobZipFiles.File_Moved2.Label"));
}
}
}
}
result.setResult( true );
}
}
catch (IOException e)
{
log.logError(toString(), Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") +realZipfilename+
Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage());
result.setResult( false );
result.setNrErrors(1);
}
finally
{
if ( fileObject != null )
{
try
{
fileObject.close();
}
catch ( IOException ex ) {};
}
}
}
else
{
result.setResult( false );
result.setNrErrors(1);
log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label"));
}
return result;
}
public boolean evaluates()
{
return true;
}
public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep) {
return new JobEntryZipFileDialog(shell,this,jobMeta);
}
public void setZipFilename(String zipFilename)
{
this.zipFilename = zipFilename;
}
public void setWildcard(String wildcard)
{
this.wildcard = wildcard;
}
public void setWildcardExclude(String wildcardexclude)
{
this.wildcardexclude = wildcardexclude;
}
public void setSourceDirectory(String sourcedirectory)
{
this.sourcedirectory = sourcedirectory;
}
public void setMoveToDirectory(String movetodirectory)
{
this.movetodirectory = movetodirectory;
}
public String getSourceDirectory()
{
return sourcedirectory;
}
public String getMoveToDirectory()
{
return movetodirectory;
}
public String getZipFilename()
{
return zipFilename;
}
public String getWildcard()
{
return wildcard;
}
public String getWildcardExclude()
{
return wildcardexclude;
}
} |
package heufybot.modules;
import heufybot.utils.FileUtils;
import heufybot.utils.StringUtils;
import java.util.List;
import com.memetix.mst.MicrosoftTranslatorAPI;
import com.memetix.mst.detect.Detect;
import com.memetix.mst.language.Language;
public class Translate extends Module
{
public Translate(String server)
{
super(server);
this.authType = AuthType.Anyone;
this.apiVersion = 60;
this.triggerTypes = new TriggerType[] { TriggerType.Message };
this.trigger = "^" + this.commandPrefix + "(translate)($| .*)";
}
@Override
public String getHelp(String message)
{
return "Commands: "
+ this.commandPrefix
+ "translate (<fromlanguage/)<tolanguage> <sentence> | Translates a sentence to a different language through Bing Translate. Language codes: http://msdn.microsoft.com/en-us/library/hh456380.aspx";
}
@Override
public void processEvent(String source, String message, String triggerUser, List<String> params)
{
if (params.size() == 1)
{
this.bot.getServer(this.server).cmdPRIVMSG(source, "Translate what?");
}
else
{
params.remove(0);
String languageParam = "";
String textToTranslate = "";
try
{
languageParam = params.remove(0).toLowerCase();
textToTranslate = StringUtils.join(params, " ");
}
catch (IndexOutOfBoundsException e)
{
this.bot.getServer(this.server).cmdPRIVMSG(source, "No text to translate.");
return;
}
if (textToTranslate.length() > 149)
{
textToTranslate = textToTranslate.substring(0, 147) + "...";
}
String[] authCredentials = FileUtils.readFile("data/msazurekey.txt").split("\n");
if (authCredentials.length > 1)
{
MicrosoftTranslatorAPI.setClientId(authCredentials[0]);
MicrosoftTranslatorAPI.setClientSecret(authCredentials[1]);
MicrosoftTranslatorAPI.setClientId(authCredentials[0]);
MicrosoftTranslatorAPI.setClientSecret(authCredentials[1]);
}
else
{
this.bot.getServer(this.server).cmdPRIVMSG(source,
"Error: No MS Azure login credentials were provided.");
return;
}
try
{
if (languageParam.contains("/") && languageParam.length() == 5)
{
String fromLanguage = languageParam.substring(0, 2);
String toLanguage = languageParam.substring(3, 5);
String translatedText = com.memetix.mst.translate.Translate.execute(
textToTranslate, Language.fromString(fromLanguage),
Language.fromString(toLanguage));
this.bot.getServer(this.server).cmdPRIVMSG(source,
translatedText + " | Source Language: " + fromLanguage);
}
else
{
Language sourceLanguage = Detect.execute(textToTranslate);
String translatedText = com.memetix.mst.translate.Translate.execute(
textToTranslate, Language.fromString(languageParam));
this.bot.getServer(this.server).cmdPRIVMSG(
source,
translatedText + " | Source Language: Auto-Detect ("
+ sourceLanguage.toString() + ")");
}
}
catch (Exception e)
{
this.bot.getServer(this.server).cmdPRIVMSG(source,
"Text could not be translated. Make sure the language code is correct.");
}
}
}
@Override
public void onLoad()
{
FileUtils.touchFile("data/msazurekey.txt");
}
@Override
public void onUnload()
{
}
} |
package ryhma57.references;
import java.util.EnumSet;
import ryhma57.backend.BibtexReferenceField;
import static ryhma57.backend.BibtexReferenceField.*;
public class Book extends Reference {
private static EnumSet<BibtexReferenceField> existingFields;
private static EnumSet<BibtexReferenceField> requiredFields, optionalFields;
static {
Book.requiredFields = Reference.createFieldSet(AUTHOR,
EDITOR, TITLE, YEAR, PUBLISHER);
Book.optionalFields = Reference.createFieldSet(VOLUME,
NUMBER, SERIES, ADDRESS, EDITION, MONTH, NOTE);
Book.existingFields = Reference.createExistingSet(
Book.requiredFields, Book.optionalFields);
}
public Book() {
super(existingFields, requiredFields, "book");
}
} |
package de.mklinger.tomcat.juli.logging;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.junit.Test;
import de.mklinger.commons.exec.Cmd;
import de.mklinger.commons.exec.CmdBuilder;
import de.mklinger.commons.exec.CmdSettings;
import de.mklinger.commons.exec.CommandLineException;
import de.mklinger.commons.exec.CommandLineUtil;
import de.mklinger.commons.exec.JavaHome;
/**
* @author Marc Klinger - mklinger[at]mklinger[dot]de - klingerm
*/
public class TomcatIT {
@Test
public void test() throws IOException, CommandLineException {
final File catalinaHome = getCatalinaHome();
checkCatalinaHome(catalinaHome);
final int controlPort = getFreePort();
final int httpPort = getFreePort();
final int ajpPort = getFreePort();
//System.out.println("Using ports:\n\tcontrol port: " + controlPort + "\n\thttp port: " + httpPort + "\n\tajp port: " + ajpPort);
final File confDir = new File(catalinaHome, "conf");
final File serverXml = new File(confDir, "server.xml");
final Path bak = Files.createTempFile("server", ".xml");
Files.copy(serverXml.toPath(), bak, StandardCopyOption.REPLACE_EXISTING);
try {
Files.write(serverXml.toPath(),
Files.readAllLines(serverXml.toPath(), StandardCharsets.UTF_8).stream()
.map(line -> line.replace("8005", String.valueOf(controlPort)))
.map(line -> line.replace("8080", String.valueOf(httpPort)))
.map(line -> line.replace("8009", String.valueOf(ajpPort)))
.collect(Collectors.toList()));
//System.out.println("server.xml:\n\n" + new String(Files.readAllBytes(serverXml.toPath()), "UTF-8") + "\n");
final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
final Pattern p = Pattern.compile(Pattern.quote("[main] INFO org.apache.catalina.startup.Catalina - Server startup in [") + "\\d+" + Pattern.quote("] milliseconds"));
final File binDir = new File(catalinaHome, "bin");
final String executableName;
if (CommandLineUtil.isWindows()) {
executableName = "catalina.bat";
} else {
executableName = "catalina.sh";
}
final File executable = new File(binDir, executableName);
final CmdBuilder cmdb = new CmdBuilder(executable)
.arg("run")
.directory(binDir)
.redirectErrorStream(true)
.stdout(stderr)
.destroyForcibly(true)
.destroyOnError(true)
.ping(() -> {
final Matcher m = p.matcher(stderr.toString());
if (m.find()) {
if (CommandLineUtil.isWindows()) {
stopTomcat(catalinaHome, executable);
}
throw new TestSuccessException();
}
})
.timeout(10, TimeUnit.SECONDS);
final CmdSettings cmdSettings = cmdb.toCmdSettings();
setEnvironment(cmdSettings, catalinaHome);
cmdSettings.freeze();
final Cmd cmd = new Cmd(cmdSettings);
try {
cmd.execute();
throw new CommandLineException("Execute returned without matching log");
} catch (final CommandLineException e) {
final Throwable cause = e.getCause();
if (cause == null || !(cause instanceof TestSuccessException)) {
System.err.println("Tomcat stderr:\n" + stderr.toString());
throw e;
}
} finally {
cmd.destroyForcibly();
}
} finally {
Files.move(bak, serverXml.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
private void setEnvironment(final CmdSettings cmdSettings, final File catalinaHome) {
final Map<String, String> environment = new HashMap<>(System.getenv());
for (final Iterator<Map.Entry<String, String>> iterator = environment.entrySet().iterator(); iterator.hasNext();) {
final Map.Entry<String, String> e = iterator.next();
if (e.getKey().contains("CATALINA") || e.getKey().contains("TOMCAT") || e.getKey().contains("JAVA")) {
System.out.println("Removing from environment: " + e.getKey() + " -> " + e.getValue());
iterator.remove();
}
}
environment.put("CATALINA_HOME", catalinaHome.getAbsolutePath());
environment.put("JAVA_HOME", JavaHome.getByRuntime().getJavaHome().getAbsolutePath());
cmdSettings.setEnvironment(environment);
}
private void stopTomcat(final File catalinaHome, final File executable) {
try {
new CmdBuilder(executable)
.arg("stop")
.environment("CATALINA_HOME", catalinaHome.getAbsolutePath())
.environment("JAVA_HOME", JavaHome.getByRuntime().getJavaHome().getAbsolutePath())
.toCmd()
.execute();
} catch (final CommandLineException e) {
throw new RuntimeException("Stop failed");
}
}
private static int getFreePort() throws IOException {
while (true) {
try (ServerSocket ss = new ServerSocket()) {
ss.bind(new InetSocketAddress((int) Math.round(Math.random() * 15_000.0 + 50_000.0)));
return ss.getLocalPort();
} catch (final IOException e) {
// ignore
}
}
}
private static class TestSuccessException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
private void checkCatalinaHome(final File catalinaHome) {
if (!new File(catalinaHome, "bin").isDirectory()) {
throw new IllegalStateException("Invalid catalina home: " + catalinaHome);
}
if (!new File(catalinaHome, "logs").isDirectory()) {
throw new IllegalStateException("Invalid catalina home: " + catalinaHome);
}
if (!new File(catalinaHome, "conf").isDirectory()) {
throw new IllegalStateException("Invalid catalina home: " + catalinaHome);
}
}
private File getCatalinaHome() throws FileNotFoundException {
final String catalinaHomeProp = System.getProperty("catalina.home");
if (catalinaHomeProp != null && !catalinaHomeProp.isEmpty()) {
return new File(catalinaHomeProp);
} else {
final File itestDir = new File("target/itest");
if (!itestDir.isDirectory()) {
throw new FileNotFoundException("ITest directory not found");
}
final File[] files = itestDir.listFiles();
if (files == null || files.length != 1) {
throw new FileNotFoundException("ITest directory not found");
}
return files[0];
}
}
} |
package havarunner.example;
import havarunner.HavaRunner;
import havarunner.annotation.RunSequentially;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(HavaRunner.class)
@RunSequentially
public class SequantialExampleTest {
@Test
void this_test_is_run_in_sequence_with_the_other_tests_in_this_class() {
}
@Test
void this_test_is_also_run_in_sequence_with_the_other_tests_in_this_class() {
}
} |
package hello.controllers;
import static org.hamcrest.core.StringContains.containsString;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import hello.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:db/greetings-init.sql")
@ActiveProfiles("test")
public class GreetingControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void getGreetingHtml() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/greeting/1").accept(MediaType.TEXT_HTML)).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello, World!"))).andExpect(view().name("greeting/show"));
}
@Test
public void getGreetingJson() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/greeting/1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().string(containsString("Hello, World!")));
}
@Test
public void getGreetingNameHtml() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/greeting/1?name=Rob").accept(MediaType.TEXT_HTML))
.andExpect(status().isOk()).andExpect(content().string(containsString("Hello, Rob!")))
.andExpect(view().name("greeting/show"));
}
@Test
public void getGreetingNameJson() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/greeting/1?name=Rob").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().string(containsString("Hello, Rob!")));
}
@Test
public void getNewGreetingHtml() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/greeting/new").accept(MediaType.TEXT_HTML)).andExpect(status().isOk())
.andExpect(view().name("greeting/new"));
}
@Test
public void getNewGreetingJson() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/greeting/new").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotAcceptable());
}
@Test
public void postGreetingHtml() throws Exception {
String greeting = "Howdy, %s!";
String greetingResult = String.format(greeting, "World");
mvc.perform(MockMvcRequestBuilders.post("/greeting").contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("template", greeting).accept(MediaType.TEXT_HTML))
.andExpect(status().isFound()).andExpect(content().string(""))
.andExpect(view().name("redirect:/greeting"));
mvc.perform(MockMvcRequestBuilders.get("/greeting/2").accept(MediaType.TEXT_HTML)).andExpect(status().isOk())
.andExpect(content().string(containsString(greetingResult)));
}
@Test
public void postGreetingJson() throws Exception {
mvc.perform(MockMvcRequestBuilders.post("/greeting").contentType(MediaType.APPLICATION_JSON)
.content("{ \"template\": \"Howdy, %s!\" }").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated()).andExpect(content().string(""))
.andExpect(header().string("Location", containsString("/greeting/2")));
mvc.perform(MockMvcRequestBuilders.get("/greeting/2").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().string(containsString("Howdy, World!")));
}
@Test
public void postLongGreetingHtml() throws Exception {
mvc.perform(MockMvcRequestBuilders.post("/greeting").contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("template", "012345678901234567890123456789A").accept(MediaType.TEXT_HTML))
.andExpect(status().isOk()).andExpect(view().name("greeting/new"));
}
@Test
public void postLongGreetingJson() throws Exception {
mvc.perform(MockMvcRequestBuilders.post("/greeting").contentType(MediaType.APPLICATION_JSON)
.content("{ \"template\": \"012345678901234567890123456789A\" }").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isUnprocessableEntity()).andExpect(content().string(""));
}
@Test
public void postEmptyGreetingHtml() throws Exception {
mvc.perform(MockMvcRequestBuilders.post("/greeting").contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("template", "").accept(MediaType.TEXT_HTML)).andExpect(status().isOk())
.andExpect(view().name("greeting/new"));
}
@Test
public void postEmptyGreetingJson() throws Exception {
mvc.perform(MockMvcRequestBuilders.post("/greeting").contentType(MediaType.APPLICATION_JSON)
.content("{ \"template\": \"\" }").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isUnprocessableEntity()).andExpect(content().string(""));
}
} |
package org.dstadler.commons.svn;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import java.util.logging.Logger;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.dstadler.commons.exec.ExecutionHelper;
import org.dstadler.commons.logging.jdk.LoggerFactory;
import org.dstadler.commons.testing.PrivateConstructorCoverage;
import org.dstadler.commons.testing.TestHelpers;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.xml.sax.SAXException;
public class SVNCommandsTest {
private final static Logger log = LoggerFactory.make();
private static final String USERNAME = "";
private static final String PASSWORD = null;
private static final String BASE_URL;
private static final File svnRepoDir;
private static final File repoDir;
static {
try {
repoDir = File.createTempFile("SVNCommandsTestRepo", ".dir");
} catch (IOException e) {
throw new RuntimeException(e);
}
assertTrue(repoDir.delete());
assertTrue(repoDir.mkdir());
try {
svnRepoDir = File.createTempFile("SVNCommandsTestSVNRepo", ".dir");
} catch (IOException e) {
throw new RuntimeException(e);
}
assertTrue(svnRepoDir.delete());
assertTrue(svnRepoDir.mkdir());
CommandLine cmdLine = new CommandLine("svnadmin");
cmdLine.addArgument("create");
cmdLine.addArgument("project1");
log.info("Creating local svn repository at " + repoDir);
try (InputStream result = ExecutionHelper.getCommandResult(cmdLine, repoDir, 0, 360000)) {
log.info("Svnadmin reported:\n" + SVNCommands.extractResult(result));
} catch (IOException e) {
throw new RuntimeException(e);
}
BASE_URL = (SystemUtils.IS_OS_WINDOWS ? "file:///" : "file://") + repoDir.getAbsolutePath().
// local URL on Windows has limitations
replace("\\", "/").replace("c:/", "/") + "/project1";
log.info("Using baseUrl " + BASE_URL);
try {
// checkout to 2nd directory
try (InputStream result = SVNCommands.checkout(BASE_URL,
svnRepoDir, USERNAME, PASSWORD)) {
log.info("Svn-checkout reported:\n" + SVNCommands.extractResult(result));
}
// add some minimal content
FileUtils.writeStringToFile(new File(svnRepoDir, "README"), "test content", "UTF-8");
cmdLine = new CommandLine(SVNCommands.SVN_CMD);
cmdLine.addArgument("add");
cmdLine.addArgument("README");
try (InputStream result = ExecutionHelper.getCommandResult(cmdLine, svnRepoDir, 0, 360000)) {
log.info("Svn-add reported:\n" + SVNCommands.extractResult(result));
}
cmdLine = new CommandLine(SVNCommands.SVN_CMD);
cmdLine.addArgument("commit");
cmdLine.addArgument("-m");
cmdLine.addArgument("comment");
try (InputStream result = ExecutionHelper.getCommandResult(cmdLine, svnRepoDir, 0, 360000)) {
log.info("Svn-commit reported:\n" + SVNCommands.extractResult(result));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@BeforeClass
public static void setUpClass() {
assumeTrue("Could not execute the SVN-command, skipping tests",
SVNCommands.checkSVNCommand());
}
@AfterClass
public static void tearDownClass() throws IOException {
FileUtils.deleteDirectory(repoDir);
FileUtils.deleteDirectory(svnRepoDir);
}
@Test
public void testGetBranchLogRevisionRevision() throws Exception {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
Map<Long, LogEntry> log = SVNCommands.getBranchLog(new String[]{""}, 0, 1, BASE_URL, USERNAME, PASSWORD);
assertNotNull(log);
assertTrue(log.size() > 0);
final String date = log.values().iterator().next().date;
// depends on actual time of check-in to the temp-repo: assertEquals("2017-04-24T19:54:31.089532Z", date);
assertNotNull(DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.parse(date));
}
@Test
public void testGetBranchLogRevision() throws Exception {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
Map<Long, LogEntry> log = SVNCommands.getBranchLog(new String[]{""}, 0, BASE_URL, USERNAME, PASSWORD);
assertNotNull(log);
assertTrue(log.size() > 0);
final String date = log.values().iterator().next().date;
// depends on actual time of check-in to the temp-repo: assertEquals("2017-04-24T19:54:31.089532Z", date);
assertNotNull(DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.parse(date));
}
@Test
public void testGetBranchLogDate() throws Exception {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
Map<Long, LogEntry> log = SVNCommands.getBranchLog(new String[]{""}, new Date(0),
DateUtils.addDays(new Date(), 1), BASE_URL, USERNAME, PASSWORD);
assertNotNull(log);
assertTrue(log.size() > 0);
final String date = log.values().iterator().next().date;
// depends on actual time of check-in to the temp-repo: assertEquals("2017-04-24T19:54:31.089532Z", date);
assertNotNull(DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.parse(date));
}
@Test
public void testSVNDirectAccess() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
String content = IOUtils.toString(SVNCommands.getRemoteFileContent("/README", 1, BASE_URL, USERNAME, PASSWORD), "UTF-8");
assertNotNull(content);
assertTrue(content.contains("test content"));
}
@Ignore("Does not work currently due to local file repo")
@Test
public void canLoadBranchLogForTimeframe() throws IOException, SAXException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(2015, Calendar.SEPTEMBER, 1, 0, 0, 0);
Date startDate = cal.getTime();
cal.set(2015, Calendar.SEPTEMBER, 2, 0, 0, 0);
Date endDate = cal.getTime();
Map<Long, LogEntry> log = SVNCommands.getBranchLog(new String[]{"/README"}, startDate, endDate, BASE_URL, USERNAME, PASSWORD);
assertNotNull(log);
assertEquals(20, log.size());
}
private boolean serverAvailable() {
// does not work with ssh-url
//return UrlUtils.isAvailable(BASE_URL, false, true, 10000);
return true;
}
@Test
public void testCleanup() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
File tempDir = File.createTempFile("SVNCommandsTest", ".dir");
try {
assertTrue(tempDir.delete());
try (InputStream stream = SVNCommands.checkout(BASE_URL, tempDir, USERNAME, PASSWORD)) {
System.out.println(IOUtils.toString(stream, "UTF-8"));
}
// check that the necessary structures were created
assertTrue("Need to find: " + tempDir, tempDir.exists());
assertTrue("Needs to be a dir: " + tempDir, tempDir.isDirectory());
File svnDir = new File(tempDir, ".svn");
assertTrue("Need to find: " + svnDir, svnDir.exists());
assertTrue("Need to be a dir: " + svnDir, svnDir.isDirectory());
SVNCommands.cleanup(tempDir);
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
@Test
public void testMergeRevision() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
File tempDir = File.createTempFile("SVNCommandsTest", ".dir");
try {
assertTrue(tempDir.delete());
try (InputStream stream = SVNCommands.checkout(BASE_URL, tempDir, USERNAME, PASSWORD)) {
System.out.println(IOUtils.toString(stream, "UTF-8"));
}
// check that the necessary structures were created
assertEquals(SVNCommands.MergeResult.Normal, SVNCommands.mergeRevision(1, tempDir, "", BASE_URL));
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
@Test
public void testGetBranchRevision() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
File tempDir = File.createTempFile("SVNCommandsTest", ".dir");
try {
assertTrue(tempDir.delete());
try (InputStream stream = SVNCommands.checkout(BASE_URL, tempDir, USERNAME, PASSWORD)) {
System.out.println(IOUtils.toString(stream, "UTF-8"));
}
// check that the necessary structures were created
try {
SVNCommands.getBranchRevision("", BASE_URL);
fail("Should throw exception here");
} catch (IOException e) {
// expected here
}
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
@Test
public void testBranchExists() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
File tempDir = File.createTempFile("SVNCommandsTest", ".dir");
try {
assertTrue(tempDir.delete());
try (InputStream stream = SVNCommands.checkout(BASE_URL, tempDir, USERNAME, PASSWORD)) {
System.out.println(IOUtils.toString(stream, "UTF-8"));
}
assertFalse(SVNCommands.branchExists("/not_existing", BASE_URL));
assertTrue(SVNCommands.branchExists("/README", BASE_URL));
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
@Test
public void testCopyBranch() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
File tempDir = File.createTempFile("SVNCommandsTest", ".dir");
try {
assertTrue(tempDir.delete());
try (InputStream stream = SVNCommands.checkout(BASE_URL, tempDir, USERNAME, PASSWORD)) {
System.out.println(IOUtils.toString(stream, "UTF-8"));
}
SVNCommands.copyBranch("/", "/newbranch", 1, BASE_URL);
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
@Test
public void testUpdate() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
File tempDir = File.createTempFile("SVNCommandsTest", ".dir");
try {
assertTrue(tempDir.delete());
try (InputStream stream = SVNCommands.checkout(BASE_URL, tempDir, USERNAME, PASSWORD)) {
System.out.println(IOUtils.toString(stream, "UTF-8"));
}
SVNCommands.update(tempDir);
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
@Test
public void testVerifyNoPendingChanges() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
File tempDir = File.createTempFile("SVNCommandsTest", ".dir");
try {
assertTrue(tempDir.delete());
try (InputStream stream = SVNCommands.checkout(BASE_URL, tempDir, USERNAME, PASSWORD)) {
System.out.println(IOUtils.toString(stream, "UTF-8"));
}
assertFalse(SVNCommands.verifyNoPendingChanges(tempDir));
FileUtils.writeStringToFile(new File(tempDir, "README"), "some other string", "UTF-8");
assertTrue(SVNCommands.verifyNoPendingChanges(tempDir));
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
@Test
public void testRevertAll() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
File tempDir = File.createTempFile("SVNCommandsTest", ".dir");
try {
assertTrue(tempDir.delete());
try (InputStream stream = SVNCommands.checkout(BASE_URL, tempDir, USERNAME, PASSWORD)) {
System.out.println(IOUtils.toString(stream, "UTF-8"));
}
SVNCommands.revertAll(tempDir);
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
@Test
public void testCommitMergeInfo() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
File tempDir = File.createTempFile("SVNCommandsTest", ".dir");
try {
assertTrue(tempDir.delete());
try (InputStream stream = SVNCommands.checkout(BASE_URL, tempDir, USERNAME, PASSWORD)) {
System.out.println(IOUtils.toString(stream, "UTF-8"));
}
SVNCommands.commitMergeInfo("some merge", tempDir);
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
@Test
public void testGetConflicts() throws IOException {
assumeTrue("SVN not available at " + BASE_URL, serverAvailable());
File tempDir = File.createTempFile("SVNCommandsTest", ".dir");
try {
assertTrue(tempDir.delete());
try (InputStream stream = SVNCommands.checkout(BASE_URL, tempDir, USERNAME, PASSWORD)) {
System.out.println(IOUtils.toString(stream, "UTF-8"));
}
assertEquals("", SVNCommands.getConflicts(tempDir));
} finally {
FileUtils.deleteDirectory(tempDir);
}
}
@Test
public void testMergeResult() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
TestHelpers.EnumTest(SVNCommands.MergeResult.Normal, SVNCommands.MergeResult.class,
"Normal");
}
// helper method to get coverage of the unused constructor
@Test
public void testPrivateConstructor() throws Exception {
PrivateConstructorCoverage.executePrivateConstructor(SVNCommands.class);
}
} |
package org.lantern.endpoints;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.lantern.TestingUtils;
import org.lantern.oauth.OauthUtils;
import org.lantern.oauth.RefreshToken;
import org.lantern.state.ClientFriend;
import org.lantern.state.Friend;
import org.lantern.state.Friend.SuggestionReason;
import org.lantern.state.Mode;
import org.lantern.state.Model;
import org.lantern.util.HttpClientFactory;
import org.lantern.util.Stopwatch;
import org.lantern.util.StopwatchManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Tests for the friends syncing REST API.
*/
public class FriendEndpointTest {
private final Logger log = LoggerFactory.getLogger(getClass());
@BeforeClass
public static void setUpOnce() {
//LanternClientConstants.setControllerId("lanternctrl");
}
@AfterClass
public static void tearDownOnce() {
//LanternClientConstants.setControllerId("lanternctrl");
}
@Test
public void testFriendEndpoint() throws Exception {
TestingUtils.doWithGetModeProxy(new Callable<Void>() {
@Override
public Void call() throws Exception {
final HttpClientFactory httpClientFactory =
TestingUtils.newHttClientFactory();
final Model model = TestingUtils.newModel();
model.getSettings().setMode(Mode.give);
final OauthUtils utils = new OauthUtils(httpClientFactory, model, new RefreshToken(model));
final FriendApi api = new FriendApi(utils, model);
// First just clear the existing friends.
List<ClientFriend> friends = realFriends(api.listFriends());
log.debug("Deleting all friends from: {}", friends);
for (final ClientFriend f : friends) {
final Long id = f.getId();
api.removeFriend(id);
// Give the db a chance to sync.
log.debug("Removing friend: {}", f);
//Thread.sleep(50);
}
final ClientFriend friend = new ClientFriend();
friend.setEmail("test@test.com");
friend.setName("Tester");
friend.setReason(SuggestionReason.runningLantern);
api.insertFriend(friend);
final Stopwatch friendsWatch =
StopwatchManager.getStopwatch("friends-api",
"org.lantern", "listFriends");
friends = null;
for (int i = 0; i < 2; i++) {
friendsWatch.start();
friends = realFriends(api.listFriends());
friendsWatch.stop();
log.debug("Deleting all friends from: {}", friends);
for (final ClientFriend f : friends) {
final Long id = f.getId();
api.removeFriend(id);
// Give the db a chance to sync.
log.debug("Removing friend: {}", f);
//Thread.sleep(200);
}
friendsWatch.logSummary();
}
friendsWatch.logSummary();
StopwatchManager.logSummaries("org.lantern");
/*
log.debug("Deleting all friends from: {}", friends);
for (final ClientFriend f : friends) {
final Long id = f.getId();
api.removeFriend(id);
// Give the db a chance to sync.
log.debug("Removing friend: {}", f);
Thread.sleep(2000);
}
*/
//Thread.sleep(2000);
final List<ClientFriend> postDelete = realFriends(api.listFriends());
assertEquals("Did not successfully delete friends?", 0, postDelete.size());
final ClientFriend inserted = api.insertFriend(friend);
final String updatedName = "brandnew@email.com";
inserted.setEmail(updatedName);
final Friend updated = api.updateFriend(inserted);
//Thread.sleep(4000);
assertEquals(updatedName, updated.getEmail());
final List<ClientFriend> newList = realFriends(api.listFriends());
for (final ClientFriend f : newList) {
assertEquals(updatedName, f.getEmail());
final Long id = f.getId();
final Friend get = api.getFriend(id);
assertEquals(id, get.getId());
api.removeFriend(id);
// Give the db a chance to sync.
//Thread.sleep(100);
}
final List<ClientFriend> empty = realFriends(api.listFriends());
assertEquals(0, empty.size());
return null;
}
});
}
private static List<ClientFriend> realFriends(ClientFriend[] friends) {
List<ClientFriend> realFriends = new ArrayList<ClientFriend>();
for (ClientFriend friend : friends) {
if (!friend.isFreeToFriend()) {
realFriends.add(friend);
}
}
return realFriends;
}
} |
package seedu.taskboss.testutil;
import seedu.taskboss.commons.exceptions.IllegalValueException;
import seedu.taskboss.logic.commands.AddCommand;
import seedu.taskboss.model.TaskBoss;
import seedu.taskboss.model.task.Task;
import seedu.taskboss.model.task.UniqueTaskList;
public class TypicalTestTasks {
public TestTask taskA, taskB, taskC, taskD, taskE, taskF, taskG, taskH, taskI, taskJ, taskK;
public TypicalTestTasks() {
try {
taskA = new TaskBuilder().withName("Attend wedding")
.withInformation("123, Jurong West Ave 6, #08-111")
.withPriorityLevel("Yes")
.withStartDateTime("Feb 18, 2017 5pm")
.withEndDateTime("Mar 28, 2017 5pm")
.withCategories(AddCommand.DEFAULT, "friends").build();
taskB = new TaskBuilder().withName("Birthday party")
.withInformation("311, Clementi Ave 2, #02-25")
.withPriorityLevel("No")
.withStartDateTime("Feb 23, 2017 10pm")
.withEndDateTime("Jun 28, 2017 5pm")
.withCategories("owesMoney", "friends").build();
taskC = new TaskBuilder().withName("Clean house").withPriorityLevel("Yes")
.withStartDateTime("Feb 19, 2017 11pm")
.withEndDateTime("Feb 28, 2017 5pm")
.withInformation("wall street").build();
taskD = new TaskBuilder().withName("Debug code").withPriorityLevel("Yes")
.withStartDateTime("Feb 20, 2017 11.30pm")
.withEndDateTime("Apr 28, 2017 3pm")
.withInformation("10th street").build();
taskE = new TaskBuilder().withName("Ensure code quality").withPriorityLevel("No")
.withStartDateTime("Feb 22, 2017 5pm")
.withEndDateTime("Feb 28, 2017 5pm")
.withInformation("michegan ave").build();
taskF = new TaskBuilder().withName("Fix errors in report").withPriorityLevel("No")
.withStartDateTime("Feb 21, 2017 1pm")
.withEndDateTime("Dec 10, 2017 5pm")
.withInformation("little tokyo").build();
taskG = new TaskBuilder().withName("Game project player testing").withPriorityLevel("Yes")
.withStartDateTime("Jan 1, 2017 5pm")
.withEndDateTime("Nov 28, 2017 5pm")
.withInformation("4th street").build();
// Manually added
taskH = new TaskBuilder().withName("Having dinner with Hoon Meier").withPriorityLevel("Yes")
.withStartDateTime("Feb 19, 2018 5pm")
.withEndDateTime("Feb 28, 2018 5pm")
.withInformation("little india")
.withCategories(AddCommand.DEFAULT).build();
taskI = new TaskBuilder().withName("Invite friends home").withPriorityLevel("Yes")
.withStartDateTime("Feb 19, 2019 5pm")
.withEndDateTime("Feb 28, 2019 5pm")
.withInformation("chicago ave")
.withCategories(AddCommand.DEFAULT).build();
taskJ = new TaskBuilder().withName("Join Leader Group").withPriorityLevel("Yes")
.withStartDateTime("next sat 5pm")
.withEndDateTime("tomorrow")
.withInformation("Silicon Valley")
.withCategories(AddCommand.DEFAULT).build();
taskK = new TaskBuilder().withName("Kelvin Koo party").withPriorityLevel("Yes")
.withStartDateTime("Dec 20 2019")
.withEndDateTime("Dec 21 2019")
.withInformation("clementi ave 2")
.withCategories(AddCommand.DEFAULT).build();
} catch (IllegalValueException e) {
e.printStackTrace();
assert false : "not possible";
}
}
public static void loadTaskBossWithSampleData(TaskBoss ab) {
for (TestTask task : new TypicalTestTasks().getTypicalTasks()) {
try {
ab.addTask(new Task(task));
} catch (UniqueTaskList.DuplicateTaskException e) {
assert false : "not possible";
}
}
}
public TestTask[] getTypicalTasks() {
return new TestTask[]{taskC, taskE, taskA, taskD, taskB, taskG, taskF};
}
public TaskBoss getTypicalTaskBoss() {
TaskBoss ab = new TaskBoss();
loadTaskBossWithSampleData(ab);
return ab;
}
} |
package seedu.tasklist.testutil;
import seedu.tasklist.commons.exceptions.IllegalValueException;
import seedu.tasklist.model.TaskList;
import seedu.tasklist.model.task.*;
public class TypicalTestTasks {
public static TestTask task1, task2, task3, task4, task5, task6, task7, task8, task9;
public TypicalTestTasks() {
try {
task1 = new TaskBuilder().withTaskDetails("Buy Eggs").withUniqueID(1)
.withEndTime("").withStartTime("5pm")
.withPriority("high").build();
task2 = new TaskBuilder().withTaskDetails("Study for Midterms").withUniqueID(2)
.withEndTime("9pm").withStartTime("6pm")
.withPriority("high").build();
task3 = new TaskBuilder().withTaskDetails("Do laundry").withStartTime("").withEndTime("7pm").withUniqueID(3).withPriority("high").build();
task4 = new TaskBuilder().withTaskDetails("Complete Project Manual").withStartTime("").withEndTime("11pm").withUniqueID(4).withPriority("low").build();
task5 = new TaskBuilder().withTaskDetails("Visit Singapore Zoo").withStartTime("12pm").withEndTime("2pm").withUniqueID(5).withPriority("med").build();
task6 = new TaskBuilder().withTaskDetails("Complete PC1432 Lab Assignment").withStartTime("").withEndTime("10pm").withUniqueID(6).withPriority("high").build();
task7 = new TaskBuilder().withTaskDetails("Start working on GES1025 essay").withStartTime("9am").withEndTime("").withUniqueID(7).withPriority("low").build();
//Manually added
task8 = new TaskBuilder().withTaskDetails("Work on CS2103T Project").withStartTime("6pm").withEndTime("9pm").withUniqueID(8).withPriority("high").build();
task9 = new TaskBuilder().withTaskDetails("Buy groceries").withStartTime("5pm").withEndTime("").withUniqueID(9).withPriority("med").build();
} catch (IllegalValueException e) {
e.printStackTrace();
assert false : "not possible";
}
}
public static void loadTaskListWithSampleData(TaskList ab) {
try {
ab.addTask(new Task(task1));
ab.addTask(new Task(task2));
ab.addTask(new Task(task3));
ab.addTask(new Task(task4));
ab.addTask(new Task(task5));
ab.addTask(new Task(task6));
ab.addTask(new Task(task7));
} catch (UniqueTaskList.DuplicateTaskException e) {
assert false : "Some of the tasks could not be added!";
}
}
public TestTask[] getTypicalTasks() {
return new TestTask[]{task1, task2, task3, task4, task5, task6, task7};
}
public TaskList getTypicalTaskList(){
TaskList tl = new TaskList();
loadTaskListWithSampleData(tl);
return tl;
}
} |
package uk.gov.register.db;
import org.skife.jdbi.v2.ResultIterator;
import org.skife.jdbi.v2.sqlobject.Bind;
import uk.gov.register.core.Entry;
import uk.gov.register.store.postgres.BindEntry;
import java.time.Instant;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
public class InMemoryEntryQueryDAO implements EntryQueryDAO, EntryDAO {
private final List<Entry> entries;
private int currentEntryNumber = 0;
public InMemoryEntryQueryDAO(List<Entry> entries) {
this.entries = entries;
}
@Override
public Optional<Entry> findByEntryNumber(int entryNumber) {
if (entryNumber > entries.size()) {
return Optional.empty();
}
return Optional.of(entries.get(entryNumber - 1));
}
@Override
public Optional<Instant> getLastUpdatedTime() {
if (entries.isEmpty()) {
return Optional.empty();
}
return Optional.of(entries.get(entries.size()-1).getTimestamp());
}
@Override
public int getTotalEntries() {
return currentEntryNumber;
}
@Override
public Collection<Entry> getAllEntriesNoPagination() {
return entries;
}
@Override
public Collection<Entry> getEntries(int start, int limit) {
return entries.subList(start-1, start-1+limit);
}
@Override
public ResultIterator<Entry> entriesIteratorFrom(int entryNumber) {
return new FakeResultIterator(entries.subList(entryNumber-1, entries.size()).iterator());
}
@Override
public Iterator<Entry> getIterator() {
return entries.iterator();
}
@Override
public Iterator<Entry> getIterator(int totalEntries1, int totalEntries2) {
return entries.subList(totalEntries1, totalEntries2).iterator();
}
@Override
public void insertInBatch(@BindEntry Iterable<Entry> entries) {
for (Entry entry : entries) {
this.entries.add(entry);
}
}
@Override
public int currentEntryNumber() {
return currentEntryNumber;
}
@Override
public void setEntryNumber(@Bind("entryNumber") int currentEntryNumber) {
this.currentEntryNumber = currentEntryNumber;
}
private class FakeResultIterator implements ResultIterator<Entry> {
private final Iterator<Entry> iterator;
public FakeResultIterator(Iterator<Entry> iterator) {
this.iterator = iterator;
}
@Override
public void close() {
// ignored
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Entry next() {
return iterator.next();
}
}
} |
package website.automate.jwebrobot;
import com.google.inject.AbstractModule;
import com.google.inject.util.Modules;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import website.automate.jwebrobot.config.*;
import website.automate.jwebrobot.config.logger.LoggerModule;
import website.automate.jwebrobot.context.GlobalExecutionContext;
import website.automate.jwebrobot.executor.ScenarioExecutor;
import website.automate.jwebrobot.executor.WebDriverProvider;
import website.automate.jwebrobot.loader.ScenarioLoader;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class JWebRobotTest extends AbstractTest {
@Captor
private ArgumentCaptor<GlobalExecutionContext> globalExecutionContextArgumentCaptor;
@Before
public void setUp() {
injector = GuiceInjector.recreateInstance(Modules.combine(
new LoggerModule(),
new ElementFilterModule(),
new ActionExecutorModule(),
new ExpressionEvaluatorModule(),
new ContextValidatorModule(),
new ExecutionEventListenerModule(),
new MockScenarioExecutorModule(),
new MockScenarioLoaderModule()
));
}
@Test
public void browserShouldBeSelectable(){
ScenarioExecutor scenarioExecutor = injector.getInstance(ScenarioExecutor.class);
JWebRobot.main(new String [] {"-" + JWebRobotIT.BROWSER_PARAM_NAME, "chrome", "-" + JWebRobotIT.SCENARIO_PATH_PARAM_NAME, JWebRobotIT.ROOT_PACKAGE_DIRECTORY_PATH});
verify(scenarioExecutor).execute(globalExecutionContextArgumentCaptor.capture());
assertThat(globalExecutionContextArgumentCaptor.getValue().getOptions().getWebDriverType(), is(WebDriverProvider.Type.CHROME));
}
private class MockScenarioExecutorModule extends AbstractModule {
@Override
protected void configure() {
bind(ScenarioExecutor.class).toInstance(Mockito.mock(ScenarioExecutor.class));
}
}
private class MockScenarioLoaderModule extends AbstractModule {
@Override
protected void configure() {
bind(ScenarioLoader.class).toInstance(Mockito.mock(ScenarioLoader.class));
}
}
} |
package com.intellij.psi;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.ClassExtension;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
/**
* @author peter
*/
public class ElementManipulators extends ClassExtension<ElementManipulator> {
@NonNls public static final String EP_NAME = "com.intellij.lang.elementManipulator";
public static final ElementManipulators INSTANCE = new ElementManipulators();
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.ElementManipulators");
private ElementManipulators() {
super(EP_NAME);
}
/**
* @see #getNotNullManipulator(PsiElement)
*/
public static <T extends PsiElement> ElementManipulator<T> getManipulator(@NotNull T element) {
//noinspection unchecked
return INSTANCE.forClass(element.getClass());
}
public static int getOffsetInElement(@NotNull PsiElement element) {
final ElementManipulator<PsiElement> manipulator = getNotNullManipulator(element);
return getManipulatorRange(manipulator, element).getStartOffset();
}
@NotNull
public static <T extends PsiElement> ElementManipulator<T> getNotNullManipulator(@NotNull T element) {
final ElementManipulator<T> manipulator = getManipulator(element);
LOG.assertTrue(manipulator != null, element.getClass().getName());
return manipulator;
}
@NotNull
public static TextRange getValueTextRange(@NotNull PsiElement element) {
final ElementManipulator<PsiElement> manipulator = getManipulator(element);
return manipulator == null ? TextRange.from(0, element.getTextLength()) : getManipulatorRange(manipulator, element);
}
@NotNull
public static String getValueText(@NotNull PsiElement element) {
final TextRange valueTextRange = getValueTextRange(element);
if (valueTextRange.isEmpty()) return "";
final String text = element.getText();
if (valueTextRange.getEndOffset() > text.length()) {
LOG.error("Wrong range for " + element + " text: " + text + " range " + valueTextRange);
}
return valueTextRange.substring(text);
}
public static <T extends PsiElement> T handleContentChange(@NotNull T element, String text) {
final ElementManipulator<T> manipulator = getNotNullManipulator(element);
return manipulator.handleContentChange(element, text);
}
@NotNull
private static TextRange getManipulatorRange(@NotNull ElementManipulator<PsiElement> manipulator, @NotNull PsiElement element) {
TextRange rangeInElement = manipulator.getRangeInElement(element);
TextRange elementRange = TextRange.from(0, element.getTextLength());
if (!elementRange.contains(rangeInElement)) {
LOG.error("Element range: " + elementRange + ";\n" +
"manipulator range: " + rangeInElement + ";\n" +
"element: " + element.getClass() + ";\n" +
"manipulator: " + manipulator.getClass() + ".");
}
return rangeInElement;
}
} |
package com.intellij.ide.util;
import com.intellij.codeInsight.generation.*;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.ui.ColoredTreeCellRenderer;
import com.intellij.ui.NonFocusableCheckBox;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.TreeToolTipHandler;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.Icons;
import com.intellij.util.SmartList;
import com.intellij.util.containers.Convertor;
import com.intellij.util.containers.FactoryMap;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
public class MemberChooser<T extends ClassMember> extends DialogWrapper implements TypeSafeDataProvider {
protected Tree myTree;
private DefaultTreeModel myTreeModel;
private JCheckBox myCopyJavadocCheckbox;
private JCheckBox myInsertOverrideAnnotationCheckbox;
private final ArrayList<MemberNode> mySelectedNodes = new ArrayList<MemberNode>();
private boolean mySorted = false;
private boolean myShowClasses = true;
private boolean myAllowEmptySelection = false;
private boolean myAllowMultiSelection;
private final Project myProject;
private final boolean myIsInsertOverrideVisible;
private final JComponent myHeaderPanel;
private T[] myElements;
private final HashMap<MemberNode,ParentNode> myNodeToParentMap = new HashMap<MemberNode, ParentNode>();
private final HashMap<ClassMember, MemberNode> myElementToNodeMap = new HashMap<ClassMember, MemberNode>();
private final ArrayList<ContainerNode> myContainerNodes = new ArrayList<ContainerNode>();
private LinkedHashSet<T> mySelectedElements;
@NonNls private static final String PROP_SORTED = "MemberChooser.sorted";
@NonNls private static final String PROP_SHOWCLASSES = "MemberChooser.showClasses";
@NonNls private static final String PROP_COPYJAVADOC = "MemberChooser.copyJavadoc";
public MemberChooser(T[] elements,
boolean allowEmptySelection,
boolean allowMultiSelection,
@NotNull Project project) {
this(elements, allowEmptySelection, allowMultiSelection, project, false);
}
public MemberChooser(T[] elements,
boolean allowEmptySelection,
boolean allowMultiSelection,
@NotNull Project project,
boolean isInsertOverrideVisible) {
this(elements, allowEmptySelection, allowMultiSelection, project, isInsertOverrideVisible, null);
}
public MemberChooser(T[] elements,
boolean allowEmptySelection,
boolean allowMultiSelection,
@NotNull Project project,
boolean isInsertOverrideVisible,
JComponent headerPanel
) {
super(project, true);
myAllowEmptySelection = allowEmptySelection;
myAllowMultiSelection = allowMultiSelection;
myProject = project;
myIsInsertOverrideVisible = isInsertOverrideVisible;
myHeaderPanel = headerPanel;
myTree = new Tree(new DefaultTreeModel(new DefaultMutableTreeNode()));
resetElements(elements);
init();
}
public void resetElements(T[] elements) {
myElements = elements;
mySelectedNodes.clear();
myNodeToParentMap.clear();
myElementToNodeMap.clear();
myContainerNodes.clear();
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
myTreeModel = buildModel();
}
});
myTree.setModel(myTreeModel);
myTree.setRootVisible(false);
doSort();
TreeUtil.expandAll(myTree);
myCopyJavadocCheckbox = new NonFocusableCheckBox(IdeBundle.message("checkbox.copy.javadoc"));
if (myIsInsertOverrideVisible) {
myInsertOverrideAnnotationCheckbox = new NonFocusableCheckBox(IdeBundle.message("checkbox.insert.at.override"));
}
myTree.doLayout();
}
/**
* should be invoked in read action
*/
private DefaultTreeModel buildModel() {
final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
final Ref<Integer> count = new Ref<Integer>(0);
final FactoryMap<MemberChooserObject,ParentNode> map = new FactoryMap<MemberChooserObject,ParentNode>() {
protected ParentNode create(final MemberChooserObject key) {
ParentNode node = null;
if (key instanceof PsiElementMemberChooserObject) {
final ContainerNode containerNode = new ContainerNode(rootNode, key, count);
node = containerNode;
myContainerNodes.add(containerNode);
}
if (node == null) {
node = new ParentNode(rootNode, key, count);
}
return node;
}
};
for (T object : myElements) {
final ParentNode parentNode = map.get(object.getParentNodeDelegate());
final MemberNode elementNode = new MemberNode(parentNode, object, count);
myNodeToParentMap.put(elementNode, parentNode);
myElementToNodeMap.put(object, elementNode);
}
return new DefaultTreeModel(rootNode);
}
public void selectElements(ClassMember[] elements) {
ArrayList<TreePath> selectionPaths = new ArrayList<TreePath>();
for (ClassMember element : elements) {
MemberNode treeNode = myElementToNodeMap.get(element);
if (treeNode != null) {
selectionPaths.add(new TreePath(treeNode.getPath()));
}
}
myTree.setSelectionPaths(selectionPaths.toArray(new TreePath[selectionPaths.size()]));
}
protected Action[] createActions() {
if (myAllowEmptySelection) {
return new Action[]{getOKAction(), new SelectNoneAction(), getCancelAction()};
}
else {
return new Action[]{getOKAction(), getCancelAction()};
}
}
protected void doHelpAction() {
}
protected List<JComponent> customizeOptionsPanel() {
final SmartList<JComponent> list = new SmartList<JComponent>();
if (myIsInsertOverrideVisible) {
CodeStyleSettings styleSettings = CodeStyleSettingsManager.getInstance(myProject).getCurrentSettings();
myInsertOverrideAnnotationCheckbox.setSelected(styleSettings.INSERT_OVERRIDE_ANNOTATION);
list.add(myInsertOverrideAnnotationCheckbox);
}
myCopyJavadocCheckbox.setSelected(PropertiesComponent.getInstance().isTrueValue(PROP_COPYJAVADOC));
list.add(myCopyJavadocCheckbox);
return list;
}
protected JComponent createSouthPanel() {
JPanel panel = new JPanel(new GridBagLayout());
JPanel optionsPanel = new JPanel(new VerticalFlowLayout());
for (final JComponent component : customizeOptionsPanel()) {
optionsPanel.add(component);
}
panel.add(
optionsPanel,
new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 5), 0, 0)
);
if (myElements == null || myElements.length == 0) {
setOKActionEnabled(false);
}
panel.add(
super.createSouthPanel(),
new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.SOUTH, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0)
);
return panel;
}
@Override
protected JComponent createNorthPanel() {
return myHeaderPanel;
}
protected JComponent createCenterPanel() {
JPanel panel = new JPanel(new BorderLayout());
// Toolbar
DefaultActionGroup group = new DefaultActionGroup();
fillToolbarActions(group);
group.addSeparator();
ExpandAllAction expandAllAction = new ExpandAllAction();
expandAllAction.registerCustomShortcutSet(
new CustomShortcutSet(
KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, SystemInfo.isMac ? InputEvent.META_MASK : InputEvent.CTRL_MASK)),
myTree);
group.add(expandAllAction);
CollapseAllAction collapseAllAction = new CollapseAllAction();
collapseAllAction.registerCustomShortcutSet(
new CustomShortcutSet(
KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, SystemInfo.isMac ? InputEvent.META_MASK : InputEvent.CTRL_MASK)),
myTree);
group.add(collapseAllAction);
panel.add(ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true).getComponent(),
BorderLayout.NORTH);
// Tree
myTree.setCellRenderer(new ColoredTreeCellRenderer() {
public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
if (value instanceof ElementNode) {
((ElementNode) value).getDelegate().renderTreeNode(this, tree);
}
}
}
);
UIUtil.setLineStyleAngled(myTree);
myTree.setRootVisible(false);
myTree.setShowsRootHandles(true);
myTree.addKeyListener(new TreeKeyListener());
myTree.addTreeSelectionListener(new MyTreeSelectionListener());
if (!myAllowMultiSelection) {
myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
}
if (getRootNode().getChildCount() > 0) {
myTree.expandRow(0);
myTree.setSelectionRow(1);
}
TreeUtil.expandAll(myTree);
new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {
@Nullable
public String convert(TreePath path) {
final MemberChooserObject delegate = ((ElementNode)path.getLastPathComponent()).getDelegate();
return delegate.getText();
}
});
myTree.addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
if (myTree.getPathForLocation(e.getX(), e.getY()) != null) {
doOKAction();
}
}
}
}
);
TreeToolTipHandler.install(myTree);
TreeUtil.installActions(myTree);
JScrollPane scrollPane = new JScrollPane(myTree);
scrollPane.setPreferredSize(new Dimension(350, 450));
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
protected void fillToolbarActions(DefaultActionGroup group) {
SortEmAction sortAction = new SortEmAction();
sortAction.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.ALT_MASK)), myTree);
setSorted(PropertiesComponent.getInstance().isTrueValue(PROP_SORTED));
group.add(sortAction);
ShowContainersAction showContainersAction = getShowContainersAction();
showContainersAction.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.ALT_MASK)), myTree);
setShowClasses(PropertiesComponent.getInstance().isTrueValue(PROP_SHOWCLASSES));
group.add(showContainersAction);
}
protected String getDimensionServiceKey() {
return "#com.intellij.ide.util.MemberChooser";
}
public JComponent getPreferredFocusedComponent() {
return myTree;
}
@Nullable
private LinkedHashSet<T> getSelectedElementsList() {
return getExitCode() == OK_EXIT_CODE ? mySelectedElements : null;
}
@Nullable
public List<T> getSelectedElements() {
final LinkedHashSet<T> list = getSelectedElementsList();
return list == null ? null : new ArrayList<T>(list);
}
@Nullable
public T[] getSelectedElements(T[] a) {
LinkedHashSet<T> list = getSelectedElementsList();
if (list == null) return null;
return list.toArray(a);
}
protected final boolean areElementsSelected() {
return mySelectedElements != null && !mySelectedElements.isEmpty();
}
public void setCopyJavadocVisible(boolean state) {
myCopyJavadocCheckbox.setVisible(state);
}
public boolean isCopyJavadoc() {
return myCopyJavadocCheckbox.isSelected();
}
public boolean isInsertOverrideAnnotation () {
return myIsInsertOverrideVisible && myInsertOverrideAnnotationCheckbox.isSelected();
}
private boolean isSorted() {
return mySorted;
}
private void setSorted(boolean sorted) {
if (mySorted == sorted) return;
mySorted = sorted;
doSort();
}
private void doSort() {
Pair<ElementNode,List<ElementNode>> pair = storeSelection();
Enumeration<ParentNode> children = getRootNodeChildren();
while (children.hasMoreElements()) {
ParentNode classNode = children.nextElement();
sortNode(classNode, mySorted);
myTreeModel.nodeStructureChanged(classNode);
}
restoreSelection(pair);
}
private static void sortNode(ParentNode node, boolean sorted) {
ArrayList<MemberNode> arrayList = new ArrayList<MemberNode>();
Enumeration<MemberNode> children = node.children();
while (children.hasMoreElements()) {
arrayList.add(children.nextElement());
}
Collections.sort(arrayList, sorted ? new AlphaComparator() : new OrderComparator());
replaceChildren(node, arrayList);
}
private static void replaceChildren(final DefaultMutableTreeNode node, final Collection<? extends ElementNode> arrayList) {
node.removeAllChildren();
for (ElementNode child : arrayList) {
node.add(child);
}
}
private void setShowClasses(boolean showClasses) {
myShowClasses = showClasses;
Pair<ElementNode,List<ElementNode>> selection = storeSelection();
DefaultMutableTreeNode root = getRootNode();
if (!myShowClasses || myContainerNodes.isEmpty()) {
List<ParentNode> otherObjects = new ArrayList<ParentNode>();
Enumeration<ParentNode> children = getRootNodeChildren();
ParentNode newRoot = new ParentNode(null, new MemberChooserObjectBase(getAllContainersNodeName()), new Ref<Integer>(0));
while (children.hasMoreElements()) {
final ParentNode nextElement = children.nextElement();
if (nextElement instanceof ContainerNode) {
final ContainerNode containerNode = (ContainerNode)nextElement;
Enumeration<MemberNode> memberNodes = containerNode.children();
List<MemberNode> memberNodesList = new ArrayList<MemberNode>();
while (memberNodes.hasMoreElements()) {
memberNodesList.add(memberNodes.nextElement());
}
for (MemberNode memberNode : memberNodesList) {
newRoot.add(memberNode);
}
} else {
otherObjects.add(nextElement);
}
}
replaceChildren(root, otherObjects);
sortNode(newRoot, mySorted);
if (newRoot.children().hasMoreElements()) root.add(newRoot);
}
else {
Enumeration<ParentNode> children = getRootNodeChildren();
if (children.hasMoreElements()) {
ParentNode allClassesNode = children.nextElement();
Enumeration<MemberNode> memberNodes = allClassesNode.children();
ArrayList<MemberNode> arrayList = new ArrayList<MemberNode>();
while (memberNodes.hasMoreElements()) {
arrayList.add(memberNodes.nextElement());
}
for (MemberNode memberNode : arrayList) {
myNodeToParentMap.get(memberNode).add(memberNode);
}
}
replaceChildren(root, myContainerNodes);
}
myTreeModel.nodeStructureChanged(root);
TreeUtil.expandAll(myTree);
restoreSelection(selection);
}
protected String getAllContainersNodeName() {
return IdeBundle.message("node.memberchooser.all.classes");
}
private Enumeration<ParentNode> getRootNodeChildren() {
return getRootNode().children();
}
private DefaultMutableTreeNode getRootNode() {
return (DefaultMutableTreeNode)myTreeModel.getRoot();
}
private Pair<ElementNode,List<ElementNode>> storeSelection() {
List<ElementNode> selectedNodes = new ArrayList<ElementNode>();
TreePath[] paths = myTree.getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
selectedNodes.add((ElementNode)path.getLastPathComponent());
}
}
TreePath leadSelectionPath = myTree.getLeadSelectionPath();
return Pair.create(leadSelectionPath != null ? (ElementNode)leadSelectionPath.getLastPathComponent() : null, selectedNodes);
}
private void restoreSelection(Pair<ElementNode,List<ElementNode>> pair) {
List<ElementNode> selectedNodes = pair.second;
DefaultMutableTreeNode root = getRootNode();
ArrayList<TreePath> toSelect = new ArrayList<TreePath>();
for (ElementNode node : selectedNodes) {
if (root.isNodeDescendant(node)) {
toSelect.add(new TreePath(node.getPath()));
}
}
if (!toSelect.isEmpty()) {
myTree.setSelectionPaths(toSelect.toArray(new TreePath[toSelect.size()]));
}
ElementNode leadNode = pair.first;
if (leadNode != null) {
myTree.setLeadSelectionPath(new TreePath(leadNode.getPath()));
}
}
public void dispose() {
PropertiesComponent instance = PropertiesComponent.getInstance();
instance.setValue(PROP_SORTED, Boolean.toString(isSorted()));
instance.setValue(PROP_SHOWCLASSES, Boolean.toString(myShowClasses));
instance.setValue(PROP_COPYJAVADOC, Boolean.toString(myCopyJavadocCheckbox.isSelected()));
getContentPane().removeAll();
mySelectedNodes.clear();
myElements = null;
super.dispose();
}
public void calcData(final DataKey key, final DataSink sink) {
if (key.equals(LangDataKeys.PSI_ELEMENT)) {
if (mySelectedElements != null && !mySelectedElements.isEmpty()) {
T selectedElement = mySelectedElements.iterator().next();
if (selectedElement instanceof ClassMemberWithElement) {
sink.put(LangDataKeys.PSI_ELEMENT, ((ClassMemberWithElement) selectedElement).getElement());
}
}
}
}
private class MyTreeSelectionListener implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent e) {
TreePath[] paths = e.getPaths();
if (paths == null) return;
for (int i = 0; i < paths.length; i++) {
Object node = paths[i].getLastPathComponent();
if (node instanceof MemberNode) {
final MemberNode memberNode = (MemberNode)node;
if (e.isAddedPath(i)) {
if (!mySelectedNodes.contains(memberNode)) {
mySelectedNodes.add(memberNode);
}
}
else {
mySelectedNodes.remove(memberNode);
}
}
}
mySelectedElements = new LinkedHashSet<T>();
for (MemberNode selectedNode : mySelectedNodes) {
mySelectedElements.add((T)selectedNode.getDelegate());
}
}
}
private abstract static class ElementNode extends DefaultMutableTreeNode {
private final int myOrder;
private final MemberChooserObject myDelegate;
public ElementNode(@Nullable DefaultMutableTreeNode parent, MemberChooserObject delegate, Ref<Integer> order) {
myOrder = order.get();
order.set(myOrder + 1);
myDelegate = delegate;
if (parent != null) {
parent.add(this);
}
}
public MemberChooserObject getDelegate() {
return myDelegate;
}
public int getOrder() {
return myOrder;
}
}
private static class MemberNode extends ElementNode {
public MemberNode(ParentNode parent, ClassMember delegate, Ref<Integer> order) {
super(parent, delegate, order);
}
}
private static class ParentNode extends ElementNode {
public ParentNode(@Nullable DefaultMutableTreeNode parent, MemberChooserObject delegate, Ref<Integer> order) {
super(parent, delegate, order);
}
}
private static class ContainerNode extends ParentNode {
public ContainerNode(DefaultMutableTreeNode parent, MemberChooserObject delegate, Ref<Integer> order) {
super(parent, delegate, order);
}
}
private class SelectNoneAction extends AbstractAction {
public SelectNoneAction() {
super(IdeBundle.message("action.select.none"));
}
public void actionPerformed(ActionEvent e) {
myTree.clearSelection();
doOKAction();
}
}
private class TreeKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
TreePath path = myTree.getLeadSelectionPath();
if (path == null) return;
final Object lastComponent = path.getLastPathComponent();
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (lastComponent instanceof ParentNode) return;
doOKAction();
e.consume();
}
else if (e.getKeyCode() == KeyEvent.VK_INSERT) {
if (lastComponent instanceof ElementNode) {
final ElementNode node = (ElementNode)lastComponent;
if (!mySelectedNodes.contains(node)) {
if (node.getNextNode() != null) {
myTree.setSelectionPath(new TreePath(node.getNextNode().getPath()));
}
}
else {
if (node.getNextNode() != null) {
myTree.removeSelectionPath(new TreePath(node.getPath()));
myTree.setSelectionPath(new TreePath(node.getNextNode().getPath()));
myTree.repaint();
}
}
e.consume();
}
}
}
}
private class SortEmAction extends ToggleAction {
public SortEmAction() {
super(IdeBundle.message("action.sort.alphabetically"),
IdeBundle.message("action.sort.alphabetically"), IconLoader.getIcon("/objectBrowser/sorted.png"));
}
public boolean isSelected(AnActionEvent event) {
return isSorted();
}
public void setSelected(AnActionEvent event, boolean flag) {
setSorted(flag);
}
}
protected ShowContainersAction getShowContainersAction() {
return new ShowContainersAction(IdeBundle.message("action.show.classes"), Icons.CLASS_ICON);
}
protected class ShowContainersAction extends ToggleAction {
public ShowContainersAction(final String text, final Icon icon) {
super(text, text, icon);
}
public boolean isSelected(AnActionEvent event) {
return myShowClasses;
}
public void setSelected(AnActionEvent event, boolean flag) {
setShowClasses(flag);
}
public void update(AnActionEvent e) {
super.update(e);
Presentation presentation = e.getPresentation();
presentation.setEnabled(myContainerNodes.size() > 1);
}
}
private class ExpandAllAction extends AnAction {
public ExpandAllAction() {
super(IdeBundle.message("action.expand.all"), IdeBundle.message("action.expand.all"),
IconLoader.getIcon("/actions/expandall.png"));
}
public void actionPerformed(AnActionEvent e) {
TreeUtil.expandAll(myTree);
}
}
private class CollapseAllAction extends AnAction {
public CollapseAllAction() {
super(IdeBundle.message("action.collapse.all"), IdeBundle.message("action.collapse.all"),
IconLoader.getIcon("/actions/collapseall.png"));
}
public void actionPerformed(AnActionEvent e) {
TreeUtil.collapseAll(myTree, 1);
}
}
private static class AlphaComparator implements Comparator<ElementNode> {
public int compare(ElementNode n1, ElementNode n2) {
return n1.getDelegate().getText().compareToIgnoreCase(n2.getDelegate().getText());
}
}
private static class OrderComparator implements Comparator<ElementNode> {
public int compare(ElementNode n1, ElementNode n2) {
if (n1.getDelegate() instanceof ClassMemberWithElement
&& n2.getDelegate() instanceof ClassMemberWithElement) {
return ((ClassMemberWithElement)n1.getDelegate()).getElement().getTextOffset()
- ((ClassMemberWithElement)n2.getDelegate()).getElement().getTextOffset();
}
return n1.getOrder() - n2.getOrder();
}
}
} |
package com.intellij.openapi.util;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.Debug;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @deprecated use {@link com.intellij.util.containers.MultiMap} directly.
* <p></p>On migration please note that MultiMap has few differences:<ul>
* <li>{@link MultiMap#get(java.lang.Object)} method returns non-null value. In case there is no value for the key - empty collection is returned.</li>
* <li>{@link MultiMap#values} method returns a real values collection, not a copy. Be careful with modifications.</li>
* <li>Default implementations of {@link MultiMap} may not permit null keys and/or null values</li>
* </ul></p>
*/
@Debug.Renderer(text = "\"size = \" + myBaseMap.size()", hasChildren = "!isEmpty()", childrenArray = "entrySet().toArray()")
@Deprecated
public class MultiValuesMap<K, V>{
private final MultiMap<K, V> myDelegate;
private final boolean myOrdered;
/**
* @deprecated Use {@link MultiMap#createSet()}
*/
@Deprecated
public MultiValuesMap() {
this(false);
}
public MultiValuesMap(boolean ordered) {
myOrdered = ordered;
if (ordered) {
myDelegate = MultiMap.createLinkedSet();
}
else {
myDelegate = new MultiMap<K, V>() {
@NotNull
@Override
protected Map<K, Collection<V>> createMap() {
return new HashMap<>();
}
@NotNull
@Override
protected Map<K, Collection<V>> createMap(int initialCapacity, float loadFactor) {
return new HashMap<>(initialCapacity, loadFactor);
}
@NotNull
@Override
protected Collection<V> createCollection() {
return new HashSet<>();
}
@NotNull
@Override
protected Collection<V> createEmptyCollection() {
return Collections.emptySet();
}
};
}
}
public void putAll(K key, @NotNull Collection<? extends V> values) {
for (V value : values) {
put(key, value);
}
}
public void putAll(K key, @NotNull V... values) {
for (V value : values) {
put(key, value);
}
}
public void put(K key, V value) {
myDelegate.putValue(key, value);
}
@Nullable
public Collection<V> get(K key){
Collection<V> collection = myDelegate.get(key);
return collection.isEmpty() ? null : collection;
}
@NotNull
public Set<K> keySet() {
return myDelegate.keySet();
}
@NotNull
public Collection<V> values() {
return myOrdered ? new LinkedHashSet<>(myDelegate.values()) : new HashSet<>(myDelegate.values());
}
public void remove(K key, V value) {
myDelegate.remove(key, value);
}
public void clear() {
myDelegate.clear();
}
@Nullable
public Collection<V> removeAll(final K key) {
return myDelegate.remove(key);
}
@NotNull
public Set<Map.Entry<K, Collection<V>>> entrySet() {
return myDelegate.entrySet();
}
public boolean isEmpty() {
return myDelegate.isEmpty();
}
public boolean containsKey(final K key) {
return myDelegate.containsKey(key);
}
@Nullable
public V getFirst(final K key) {
Collection<V> values = myDelegate.get(key);
return values.isEmpty() ? null : values.iterator().next();
}
} |
package com.googlecode.goclipse.editors;
import java.util.ResourceBundle;
import melnorme.lang.ide.ui.LangUIPlugin;
import melnorme.lang.ide.ui.editor.AbstractLangEditor;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.IDocumentExtension3;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.source.DefaultCharacterPairMatcher;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import com.googlecode.goclipse.ui.GoUIPreferenceConstants;
import com.googlecode.goclipse.ui.editor.GoEditorSourceViewerConfiguration;
public class GoEditor extends AbstractLangEditor {
private static final String BUNDLE_ID = "com.googlecode.goclipse.editors.GoEditorMessages";
private static ResourceBundle editorResourceBundle = ResourceBundle.getBundle(BUNDLE_ID);
private DefaultCharacterPairMatcher matcher;
private EditorImageUpdater imageUpdater;
private GoEditorOutlinePage outlinePage;
public GoEditor() {
super();
}
@Override
protected GoEditorSourceViewerConfiguration createSourceViewerConfiguration() {
return new GoEditorSourceViewerConfiguration(getPreferenceStore(),
LangUIPlugin.getInstance().getColorManager(), this);
}
@Override
protected void setTitleImage(Image image) {
super.setTitleImage(image);
}
@Override
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (outlinePage == null) {
outlinePage = new GoEditorOutlinePage(getDocumentProvider(), this);
}
return outlinePage;
}
return super.getAdapter(required);
}
@Override
protected final void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (input instanceof IFileEditorInput) {
imageUpdater = new EditorImageUpdater(this);
}
}
@Override
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
super.configureSourceViewerDecorationSupport(support);
char[] matchChars = {'(', ')', '[', ']', '{', '}'}; //which brackets to match
matcher = new DefaultCharacterPairMatcher(matchChars, IDocumentExtension3.DEFAULT_PARTITIONING);
support.setCharacterPairMatcher(matcher);
support.setMatchingCharacterPainterPreferenceKeys(
GoUIPreferenceConstants.EDITOR_MATCHING_BRACKETS,
GoUIPreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR);
}
@Override
protected void createActions() {
super.createActions();
IAction action;
action = new ToggleCommentAction(editorResourceBundle, "ToggleComment.", this);
action.setActionDefinitionId("com.googlecode.goclipse.actions.ToggleComment");
setAction("ToggleComment", action);
markAsStateDependentAction("ToggleComment", true);
configureToggleCommentAction();
}
public DefaultCharacterPairMatcher getPairMatcher() {
return matcher;
}
public String getText() {
return getSourceViewer().getDocument().get();
}
public void replaceText(String newText) {
ISelection sel = getSelectionProvider().getSelection();
int topIndex = getSourceViewer().getTopIndex();
getSourceViewer().getDocument().set(newText);
if (sel != null) {
getSelectionProvider().setSelection(sel);
}
if (topIndex != -1) {
getSourceViewer().setTopIndex(topIndex);
}
}
@Override
public void dispose() {
if (imageUpdater != null) {
imageUpdater.dispose();
}
super.dispose();
}
private void configureToggleCommentAction() {
IAction action = getAction("ToggleComment");
if (action instanceof ToggleCommentAction) {
ISourceViewer sourceViewer = getSourceViewer();
SourceViewerConfiguration configuration = getSourceViewerConfiguration();
((ToggleCommentAction) action).configure(sourceViewer, configuration);
}
}
protected void handleReconcilation(IRegion partition) {
if (outlinePage != null) {
outlinePage.handleEditorReconcilation();
}
}
public IProject getCurrentProject() {
if (getEditorInput() instanceof IFileEditorInput) {
IFileEditorInput input = (IFileEditorInput) getEditorInput();
IFile file = input.getFile();
if (file != null) {
return file.getProject();
}
}
return null;
}
@Override
protected boolean isTabsToSpacesConversionEnabled() {
return false;
}
} |
package edu.umd.cs.findbugs;
/**
* Version number and release date information.
*/
public class Version {
/**
* Major version number.
*/
public static final int MAJOR = 0;
/**
* Minor version number.
*/
public static final int MINOR = 9;
/**
* Patch level.
*/
public static final int PATCHLEVEL = 5;
/**
* Development version or release candidate?
*/
public static final boolean IS_DEVELOPMENT = false;
/**
* Release candidate number.
* "0" indicates that the version is not a release candidate.
*/
public static final int RELEASE_CANDIDATE = 0;
private static final String RELEASE_SUFFIX_WORD =
(RELEASE_CANDIDATE > 0 ? "rc" + RELEASE_CANDIDATE : "dev");
/**
* Release version string.
*/
public static final String RELEASE =
MAJOR + "." + MINOR + "." + PATCHLEVEL + (IS_DEVELOPMENT ? "-" + RELEASE_SUFFIX_WORD : "");
/**
* Release date.
*/
public static final String DATE = "February 17, 2006";
/**
* Version of Eclipse plugin.
*/
public static final String ECLIPSE_UI_VERSION =
"0.0.19" + (IS_DEVELOPMENT ? "." + RELEASE_SUFFIX_WORD: "");
/**
* FindBugs website.
*/
public static final String WEBSITE = "http://findbugs.sourceforge.net";
/**
* Downloads website.
*/
public static final String DOWNLOADS_WEBSITE = "http://prdownloads.sourceforge.net/findbugs";
/**
* Support email.
*/
public static final String SUPPORT_EMAIL = "http://findbugs.sourceforge.net/reportingBugs.html";
public static void main(String[] argv) {
if (argv.length != 1)
usage();
String arg = argv[0];
if (arg.equals("-release"))
System.out.println(RELEASE);
else if (arg.equals("-date"))
System.out.println(DATE);
else if (arg.equals("-props")) {
System.out.println("release.number=" + RELEASE);
System.out.println("release.date=" + DATE);
System.out.println("eclipse.ui.version=" + ECLIPSE_UI_VERSION);
System.out.println("findbugs.website=" + WEBSITE);
System.out.println("findbugs.downloads.website=" + DOWNLOADS_WEBSITE);
} else {
usage();
System.exit(1);
}
}
private static void usage() {
System.err.println("Usage: " + Version.class.getName() +
" (-release|-date|-props)");
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
/**
* Version number and release date information.
*/
public class Version {
/**
* Major version number.
*/
public static final int MAJOR = 1;
/**
* Minor version number.
*/
public static final int MINOR = 3;
/**
* Patch level.
*/
public static final int PATCHLEVEL = 5;
/**
* Development version or release candidate?
*/
public static final boolean IS_DEVELOPMENT = true;
/**
* Release candidate number.
* "0" indicates that the version is not a release candidate.
*/
public static final int RELEASE_CANDIDATE = 3;
/**
* Release date.
*/
public static final String COMPUTED_DATE;
public static final String DATE;
public static final String COMPUTED_ECLIPSE_DATE;
public static final String ECLIPSE_DATE;
static {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss z, dd MMMM, yyyy");
SimpleDateFormat eclipseDateFormat = new SimpleDateFormat("yyyyMMdd");
COMPUTED_DATE = dateFormat.format(new Date());
COMPUTED_ECLIPSE_DATE = eclipseDateFormat.format(new Date()) ;
}
/**
* Preview release number.
* "0" indicates that the version is not a preview release.
*/
public static final int PREVIEW = 0;
private static final String RELEASE_SUFFIX_WORD =
(RELEASE_CANDIDATE > 0
? "rc" + RELEASE_CANDIDATE
: (PREVIEW > 0 ? "preview" + PREVIEW : "dev-" + COMPUTED_ECLIPSE_DATE));
public static final String RELEASE_BASE = MAJOR + "." + MINOR + "." + PATCHLEVEL ;
/**
* Release version string.
*/
public static final String COMPUTED_RELEASE =
RELEASE_BASE + (IS_DEVELOPMENT ? "-" + RELEASE_SUFFIX_WORD : "");
/**
* Release version string.
*/
public static final String RELEASE;
/**
* Version of Eclipse plugin.
*/
public static final String COMPUTED_ECLIPSE_UI_VERSION =
MAJOR + "." + MINOR + "." + PATCHLEVEL + "." + COMPUTED_ECLIPSE_DATE;
public static final String ECLIPSE_UI_VERSION;
static {
InputStream in = null;
String release, eclipse_ui_version, date, eclipseDate;
try {
Properties versionProperties = new Properties();
in = Version.class.getResourceAsStream("version.properties");
versionProperties.load(in);
release = (String) versionProperties.get("release.number");
eclipse_ui_version = (String) versionProperties.get("eclipse.ui.version");
date = (String) versionProperties.get("release.date");
eclipseDate = (String) versionProperties.get("eclipse.date");
if (release == null)
release = COMPUTED_RELEASE;
if (eclipse_ui_version == null)
eclipse_ui_version = COMPUTED_ECLIPSE_UI_VERSION;
if (date == null)
date = COMPUTED_DATE;
if (eclipseDate == null)
eclipseDate = COMPUTED_ECLIPSE_DATE;
} catch (RuntimeException e) {
release = COMPUTED_RELEASE;
eclipse_ui_version = COMPUTED_ECLIPSE_UI_VERSION;
date = COMPUTED_DATE;
eclipseDate = COMPUTED_ECLIPSE_DATE;
} catch (IOException e) {
release = COMPUTED_RELEASE;
eclipse_ui_version = COMPUTED_ECLIPSE_UI_VERSION;
date = COMPUTED_DATE;
eclipseDate = COMPUTED_ECLIPSE_DATE;
} finally {
try {
if (in != null) in.close();
} catch (IOException e) {
assert true; // nothing to do here
}
}
RELEASE = release;
ECLIPSE_UI_VERSION = eclipse_ui_version;
DATE = date;
ECLIPSE_DATE = eclipseDate;
}
/**
* FindBugs website.
*/
public static final String WEBSITE = "http://findbugs.sourceforge.net";
/**
* Downloads website.
*/
public static final String DOWNLOADS_WEBSITE = "http://prdownloads.sourceforge.net/findbugs";
/**
* Support email.
*/
public static final String SUPPORT_EMAIL = "http://findbugs.sourceforge.net/reportingBugs.html";
public static void main(String[] argv) {
if (argv.length != 1)
usage();
String arg = argv[0];
if (!IS_DEVELOPMENT && RELEASE_CANDIDATE != 0) {
throw new IllegalStateException("Non developmental version, but is release candidate " + RELEASE_CANDIDATE);
}
if (arg.equals("-release"))
System.out.println(RELEASE);
else if (arg.equals("-date"))
System.out.println(DATE);
else if (arg.equals("-props")) {
System.out.println("release.number=" + COMPUTED_RELEASE);
System.out.println("release.date=" + COMPUTED_DATE);
System.out.println("eclipse.date=" + COMPUTED_ECLIPSE_DATE);
System.out.println("eclipse.ui.version=" + COMPUTED_ECLIPSE_UI_VERSION);
System.out.println("findbugs.website=" + WEBSITE);
System.out.println("findbugs.downloads.website=" + DOWNLOADS_WEBSITE);
} else {
usage();
System.exit(1);
}
}
private static void usage() {
System.err.println("Usage: " + Version.class.getName() +
" (-release|-date|-props)");
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs;
/**
* Version number and release date information.
*/
public class Version {
/**
* Major version number.
*/
public static final int MAJOR = 0;
/**
* Minor version number.
*/
public static final int MINOR = 9;
/**
* Patch level.
*/
public static final int PATCHLEVEL = 5;
/**
* Development version or release candidate?
*/
public static final boolean IS_DEVELOPMENT = true;
/**
* Release candidate number.
* "0" indicates that the version is not a release candidate.
*/
public static final int RELEASE_CANDIDATE = 0;
private static final String RELEASE_SUFFIX_WORD =
(RELEASE_CANDIDATE > 0 ? "rc" + RELEASE_CANDIDATE : "dev");
/**
* Release version string.
*/
public static final String RELEASE =
MAJOR + "." + MINOR + "." + PATCHLEVEL + (IS_DEVELOPMENT ? "-" + RELEASE_SUFFIX_WORD : "");
/**
* Release date.
*/
public static final String DATE = "January 19, 2006";
/**
* Version of Eclipse plugin.
*/
public static final String ECLIPSE_UI_VERSION =
"0.0.17" + (IS_DEVELOPMENT ? "." + RELEASE_SUFFIX_WORD: "");
/**
* FindBugs website.
*/
public static final String WEBSITE = "http://findbugs.sourceforge.net";
/**
* Downloads website.
*/
public static final String DOWNLOADS_WEBSITE = "http://prdownloads.sourceforge.net/findbugs";
/**
* Support email.
*/
public static final String SUPPORT_EMAIL = "http://findbugs.sourceforge.net/reportingBugs.html";
public static void main(String[] argv) {
if (argv.length != 1)
usage();
String arg = argv[0];
if (arg.equals("-release"))
System.out.println(RELEASE);
else if (arg.equals("-date"))
System.out.println(DATE);
else if (arg.equals("-props")) {
System.out.println("release.number=" + RELEASE);
System.out.println("release.date=" + DATE);
System.out.println("eclipse.ui.version=" + ECLIPSE_UI_VERSION);
System.out.println("findbugs.website=" + WEBSITE);
System.out.println("findbugs.downloads.website=" + DOWNLOADS_WEBSITE);
} else {
usage();
System.exit(1);
}
}
private static void usage() {
System.err.println("Usage: " + Version.class.getName() +
" (-release|-date|-props)");
}
}
// vim:ts=4 |
package edu.umd.cs.findbugs;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.CheckForNull;
import edu.umd.cs.findbugs.cloud.CloudPlugin;
import edu.umd.cs.findbugs.updates.UpdateChecker;
import edu.umd.cs.findbugs.util.FutureValue;
import edu.umd.cs.findbugs.util.Util;
/**
* Version number and release date information.
*/
public class Version {
/**
* Major version number.
*/
public static final int MAJOR = 2;
/**
* Minor version number.
*/
public static final int MINOR = 0;
/**
* Patch level.
*/
public static final int PATCHLEVEL = 2;
/**
* Development version or release candidate?
*/
public static final boolean IS_DEVELOPMENT = true;
/**
* Release candidate number. "0" indicates that the version is not a release
* candidate.
*/
public static final int RELEASE_CANDIDATE = 0;
public static final String SVN_REVISION = System.getProperty("svn.revision", "Unknown");
/**
* Release date.
*/
private static final String COMPUTED_DATE;
public static final String DATE;
public static final String CORE_PLUGIN_RELEASE_DATE;
private static final String COMPUTED_ECLIPSE_DATE;
private static final String COMPUTED_PLUGIN_RELEASE_DATE;
private static String applicationName = "";
private static String applicationVersion = "";
static {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss z, dd MMMM, yyyy", Locale.ENGLISH);
SimpleDateFormat eclipseDateFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
SimpleDateFormat releaseDateFormat = new SimpleDateFormat(UpdateChecker.PLUGIN_RELEASE_DATE_FMT, Locale.ENGLISH);
Date now = new Date();
COMPUTED_DATE = dateFormat.format(now);
COMPUTED_ECLIPSE_DATE = eclipseDateFormat.format(now);
String tmp = releaseDateFormat.format(now);
COMPUTED_PLUGIN_RELEASE_DATE = tmp;
}
/**
* Preview release number. "0" indicates that the version is not a preview
* release.
*/
public static final int PREVIEW = 0;
private static final String RELEASE_SUFFIX_WORD;
static {
String suffix;
if (RELEASE_CANDIDATE > 0)
suffix = "rc" + RELEASE_CANDIDATE;
else if (PREVIEW > 0)
suffix = "preview" + PREVIEW;
else {
suffix = "dev-" + COMPUTED_ECLIPSE_DATE;
if (!SVN_REVISION.equals("Unknown"))
suffix += "-r" + SVN_REVISION;
}
RELEASE_SUFFIX_WORD = suffix;
}
public static final String RELEASE_BASE = MAJOR + "." + MINOR + "." + PATCHLEVEL;
/**
* Release version string.
*/
public static final String COMPUTED_RELEASE = RELEASE_BASE + (IS_DEVELOPMENT ? "-" + RELEASE_SUFFIX_WORD : "");
/**
* Release version string.
*/
public static final String RELEASE;
/**
* Version of Eclipse plugin.
*/
private static final String COMPUTED_ECLIPSE_UI_VERSION = RELEASE_BASE + "." + COMPUTED_ECLIPSE_DATE;
static {
Class<Version> c = Version.class;
URL u = c.getResource(c.getSimpleName() + ".class");
boolean fromFile = u.getProtocol().equals("file");
InputStream in = null;
String release = null;
String date = null;
String plugin_release_date = null;
if (!fromFile)
try {
Properties versionProperties = new Properties();
in = Version.class.getResourceAsStream("version.properties");
if (in != null) {
versionProperties.load(in);
release = (String) versionProperties.get("release.number");
date = (String) versionProperties.get("release.date");
plugin_release_date = (String) versionProperties.get("plugin.release.date");
}
} catch (Exception e) {
assert true; // ignore
} finally {
Util.closeSilently(in);
}
if (release == null)
release = COMPUTED_RELEASE;
if (date == null)
date = COMPUTED_DATE;
if (plugin_release_date == null)
plugin_release_date = COMPUTED_PLUGIN_RELEASE_DATE;
RELEASE = release;
DATE = date;
CORE_PLUGIN_RELEASE_DATE = plugin_release_date;
Date parsedDate;
try {
SimpleDateFormat fmt = new SimpleDateFormat(UpdateChecker.PLUGIN_RELEASE_DATE_FMT, Locale.ENGLISH);
parsedDate = fmt.parse(CORE_PLUGIN_RELEASE_DATE);
} catch (ParseException e) {
if (SystemProperties.ASSERTIONS_ENABLED)
e.printStackTrace();
parsedDate = null;
}
releaseDate = parsedDate;
}
/**
* FindBugs website.
*/
public static final String WEBSITE = "http://findbugs.sourceforge.net";
/**
* Downloads website.
*/
public static final String DOWNLOADS_WEBSITE = "http://prdownloads.sourceforge.net/findbugs";
/**
* Support email.
*/
public static final String SUPPORT_EMAIL = "http://findbugs.sourceforge.net/reportingBugs.html";
private static Date releaseDate;
public static void registerApplication(String name, String version) {
applicationName = name;
applicationVersion = version;
}
public static @CheckForNull String getApplicationName() {
return applicationName;
}
public static @CheckForNull String getApplicationVersion() {
return applicationVersion;
}
public static void main(String[] argv) throws InterruptedException {
if (!IS_DEVELOPMENT && RELEASE_CANDIDATE != 0) {
throw new IllegalStateException("Non developmental version, but is release candidate " + RELEASE_CANDIDATE);
}
if (argv.length == 0) {
printVersion(false);
return;
}
String arg = argv[0];
if (arg.equals("-release"))
System.out.println(RELEASE);
else if (arg.equals("-date"))
System.out.println(DATE);
else if (arg.equals("-props")) {
System.out.println("release.base=" + RELEASE_BASE);
System.out.println("release.number=" + COMPUTED_RELEASE);
System.out.println("release.date=" + COMPUTED_DATE);
System.out.println("plugin.release.date=" + COMPUTED_PLUGIN_RELEASE_DATE);
System.out.println("eclipse.ui.version=" + COMPUTED_ECLIPSE_UI_VERSION);
System.out.println("findbugs.website=" + WEBSITE);
System.out.println("findbugs.downloads.website=" + DOWNLOADS_WEBSITE);
System.out.println("findbugs.svn.revision=" + SVN_REVISION);
} else if (arg.equals("-plugins")) {
DetectorFactoryCollection.instance();
for(Plugin p : Plugin.getAllPlugins()) {
System.out.println("Plugin: " + p.getPluginId());
System.out.println(" description: " + p.getShortDescription());
System.out.println(" provider: " + p.getProvider());
String version = p.getVersion();
if (version != null && version.length() > 0)
System.out.println(" version: " + version);
String website = p.getWebsite();
if (website != null && website.length() > 0)
System.out.println(" website: " + website);
System.out.println();
}
} else if (arg.equals("-configuration")){
printVersion(true);
} else {
usage();
System.exit(1);
}
}
private static void usage() {
System.err.println("Usage: " + Version.class.getName() + " [(-release|-date|-props|-configuration)]");
}
public static String getReleaseWithDateIfDev() {
if (IS_DEVELOPMENT)
return RELEASE + " (" + DATE + ")";
return RELEASE;
}
public static @CheckForNull Date getReleaseDate() {
return releaseDate;
}
/**
* @param justPrintConfiguration
* @throws InterruptedException
*/
public static void printVersion(boolean justPrintConfiguration) throws InterruptedException {
System.out.println("FindBugs " + Version.COMPUTED_RELEASE);
if (justPrintConfiguration) {
for (Plugin plugin : Plugin.getAllPlugins()) {
System.out.printf("Plugin %s, version %s, loaded from %s%n", plugin.getPluginId(), plugin.getVersion(),
plugin.getPluginLoader().getURL());
if (plugin.isCorePlugin())
System.out.println(" is core plugin");
if (plugin.isInitialPlugin())
System.out.println(" is initial plugin");
if (plugin.isEnabledByDefault())
System.out.println(" is enabled by default");
if (plugin.isGloballyEnabled())
System.out.println(" is globally enabled");
Plugin parent = plugin.getParentPlugin();
if (parent != null) {
System.out.println(" has parent plugin " + parent.getPluginId());
}
for (CloudPlugin cloudPlugin : plugin.getCloudPlugins()) {
System.out.printf(" cloud %s%n", cloudPlugin.getId());
System.out.printf(" %s%n", cloudPlugin.getDescription());
}
for (DetectorFactory factory : plugin.getDetectorFactories()) {
System.out.printf(" detector %s%n", factory.getShortName());
}
System.out.println();
}
printPluginUpdates(true, 10);
} else
printPluginUpdates(false, 3);
}
private static void printPluginUpdates(boolean verbose, int secondsToWait) throws InterruptedException {
DetectorFactoryCollection dfc = DetectorFactoryCollection.instance();
if (dfc.getUpdateChecker().updateChecksGloballyDisabled()) {
if (verbose) {
System.out.println();
System.out.print("Update checking globally disabled");
}
return;
}
if (verbose) {
System.out.println();
System.out.print("Checking for plugin updates...");
}
FutureValue<Collection<UpdateChecker.PluginUpdate>>
updateHolder = dfc.getUpdates();
try {
Collection<UpdateChecker.PluginUpdate> updates = updateHolder.get(secondsToWait, TimeUnit.SECONDS);
if (updates.isEmpty()) {
if (verbose)
System.out.println("none!");
} else {
System.out.println();
for (UpdateChecker.PluginUpdate update : updates) {
System.out.println(update);
System.out.println();
}
}
} catch (TimeoutException e) {
if (verbose)
System.out.println("Timeout while trying to get updates");
}
}
}
// vim:ts=4 |
package org.jpos.gl;
import java.util.Arrays;
import java.math.BigDecimal;
import java.text.ParseException;
import org.jdom.Element;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.jpos.iso.ISOUtil;
/**
* GLEntry.
*
* Represents a MiniGL Transaction Entry.
*
* @see GLTransaction
* @see Account
*
* @author <a href="mailto:apr@jpos.org">Alejandro Revilla</a>
*/
public class GLEntry {
private long id;
private String detail;
private String tags;
private boolean credit;
private short layer;
private BigDecimal amount;
private FinalAccount account;
private GLTransaction transaction;
private BigDecimal balance; // non persistent, view helper
public GLEntry () {
super();
}
public GLEntry (Element elem) throws ParseException {
super();
fromXML (elem);
}
/**
* GLEntry id.
*
* @return internal id
*/
public long getId() {
return id;
}
/**
* GLEntry id.
*
* @param id internal id.
*/
public void setId(long id) {
this.id = id;
}
/**
* Account.
* @param account a final account
*/
public void setAccount (FinalAccount account) {
this.account = account;
}
/**
* Account.
* @return final account associated with GLEntry
*/
public FinalAccount getAccount () {
return account;
}
/**
* Transaction.
* @param transaction transaction associated with this GLEntry.
*/
public void setTransaction (GLTransaction transaction) {
this.transaction = transaction;
}
/**
* Transaction.
* @return transaction associated with this GLEntry.
*/
public GLTransaction getTransaction () {
return transaction;
}
/**
* Optional GLEntry Detail.
*
* Although GLTransaction has a detail, MiniGL support additional
* detail information at GLEntry level.
*
* @param detail optional entry level detail
*/
public void setDetail (String detail) {
this.detail = detail;
}
/**
* Optional GLEntry Detail.
*
* Although GLTransaction has a detail, MiniGL support additional
* detail information at GLEntry level.
*
* @return entry level detail (may be null)
*/
public String getDetail () {
return detail;
}
/**
* Tags.
* @param tags transaction tags
*/
public void setTags (String tags) {
this.tags = tags;
}
/**
* Tags.
* @return transaction tags
*/
public String getTags () {
return tags;
}
/**
* Credit.
* calling setCredit(true) automatically sets <code>debit</code> to false.
* @param credit true if this GLEntry is a credit.
*/
public void setCredit (boolean credit) {
this.credit = credit;
}
/**
* Debit.
* calling setDebit(true) automatically sets <code>credit</code> to false.
* @param debit true if this GLEntry is a credit.
*/
public void setDebit (boolean debit) {
this.credit = !debit;
}
/**
* @return true if this entry is a credit.
*/
public boolean isCredit () {
return credit;
}
/**
* @return true if this entry is a debit.
*/
public boolean isDebit () {
return !credit;
}
/**
* Increase value.
*
* @return true if this entry increases the balance of its account.
*/
public boolean isIncrease() {
return
(isDebit() && account.isDebit()) ||
(isCredit() && account.isCredit());
}
/**
* Decrease value.
*
* @return true if this entry decreases the balance of its account.
*/
public boolean isDecrease () {
return !isIncrease();
}
/**
* Amount.
* @param amount the amount.
*/
public void setAmount (BigDecimal amount) {
this.amount = amount;
}
/**
* Amount.
* @return entry's amount.
*/
public BigDecimal getAmount () {
return amount;
}
/**
* Impact on balance.
*
* @return either +amount or -amount based on isIncrease/isDecrease.
*/
public BigDecimal getImpact () {
return isIncrease() ? amount : amount.negate();
}
public void setLayer (short layer) {
this.layer = layer;
}
public short getLayer() {
return layer;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public void fromXML (Element elem) throws ParseException {
setDetail (elem.getChildTextTrim ("detail"));
setTags (elem.getChildTextTrim ("tags"));
setCredit ("credit".equals (elem.getAttributeValue ("type")));
setLayer (toShort(elem.getAttributeValue("layer")));
setAmount (new BigDecimal (elem.getChild ("amount").getText()));
}
public Element toXML (boolean deep) {
Element elem = new Element ("entry");
if (getDetail() != null) {
Element detail = new Element ("detail").setText (getDetail());
elem.addContent (detail);
}
if (getTags () != null) {
Element tags = new Element ("tags").setText (getTags());
elem.addContent (tags);
}
elem.setAttribute ("account", getAccount().getCode());
elem.setAttribute ("type", isCredit() ? "credit" : "debit");
if (layer != 0)
elem.setAttribute ("layer", Integer.toString(layer));
Element amount = new Element ("amount");
amount.setText (getAmount().toString());
elem.addContent (amount);
return elem;
}
public boolean equals(Object other) {
if ( !(other instanceof GLEntry) ) return false;
GLEntry castOther = (GLEntry) other;
return new EqualsBuilder()
.append(this.getId(), castOther.getId())
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(getId())
.toHashCode();
}
public boolean hasLayers (short[] layers) {
for (short l : layers) {
if (l == getLayer())
return true;
}
return false;
}
public void addTag (String tag) {
if (tag != null) {
if (tags == null || tags.length() == 0)
tags = tag;
else if (!hasTag(tag)) {
String[] tt = ISOUtil.commaDecode(tags);
String[] ss = new String[tt.length+1];
System.arraycopy (tt, 0, ss, 0, tt.length);
ss[tt.length] = tag;
Arrays.sort(ss);
tags = ISOUtil.commaEncode(ss);
}
}
}
public boolean removeTag (String tag) {
int removals = 0;
if (tags != null && tag != null) {
String[] tt = ISOUtil.commaDecode(tags);
for (int i=0; i<tt.length; i++) {
if (tt[i].equalsIgnoreCase(tag)) {
tt[i] = null;
removals++;
}
}
if (removals > 0) {
String[] ss = new String[tt.length-removals];
int i = 0;
for (String s : tt) {
if (s != null)
ss[i++] = s;
}
Arrays.sort(ss);
tags = ISOUtil.commaEncode(ss);
}
}
return removals > 0;
}
public void setTags(String[] tt) {
if (tt != null) {
Arrays.sort(tt);
tags = ISOUtil.commaEncode(tt);
}
else
tags = null;
}
public String[] getTagsAsArray() {
return (tags != null) ? ISOUtil.commaDecode(tags) : new String[]{};
}
public boolean hasTag (String tag) {
if (tags != null && tag != null) {
String[] tt = ISOUtil.commaDecode(tags);
for (String s : tt)
if (tag.equalsIgnoreCase(s))
return true;
}
return false;
}
public String toString() {
return new ToStringBuilder(this)
.append("id", getId())
.append("detail", getDetail())
.append("account", getAccount())
.append("tags", getTags())
.toString();
}
private short toShort (String s) {
return s != null ? Short.parseShort (s) : 0;
}
} |
package Ontology.Mappings.Tests;
import java.util.*;
import static org.junit.Assert.*;
/**
* MessageMapTest1 Junit Testcase
* The testfile containing the data of storing all the mappings and further performing some tests for validity checks
* and also for the conversions
* @author tirthmehta
*/
import org.junit.Test;
import Core.BaseMessage;
import Core.Message;
import Core.VHMessage;
import Ontology.OntologyConverter;
import Ontology.Mappings.FieldData;
import Ontology.Mappings.FieldMap;
import Ontology.Mappings.MessageMap;
import Ontology.Mappings.MessageOneWayMap;
import Ontology.Mappings.MessageTemplate;
import Ontology.Mappings.MessageTwoWayMap;
import Ontology.Mappings.MessageType;
import Ontology.Mappings.NestedAtomic;
import Util.StorageToken;
import junit.framework.Assert;
public class MappingTest1 {
@Test
public void test() {
//fail("Not yet implemented");
//CREATED THE INITIAL VHMESSAGE
String first="ScenarioName";
String body="Being Heard (Interview 1)";
float version=0.0f;
HashMap<String,Object> hmap=new HashMap<String, Object>();
VHMessage v1=new VHMessage("100", hmap, first, version, body);
MessageOneWayMap VHT_SuperGLU_CurrentScenario=new MessageOneWayMap();
//CREATED THE 2 ARRAYLISTS USED TO STORE THE DEFAULT MESSAGES FOR THE 2 MESSAGE TEMPLATES
ArrayList<NestedAtomic> supergluArr=new ArrayList<NestedAtomic>();
ArrayList<NestedAtomic> vhMsgArr=new ArrayList<NestedAtomic>();
//CREATED THE DEFAULT FIELDS IN THE SUPERGLUMSG TEMPLATE
List<String> indexsd1=new ArrayList<String>();
List<String> indexsd2=new ArrayList<String>();
List<String> indexsd3=new ArrayList<String>();
List<String> indexsd4=new ArrayList<String>();
indexsd1.add(Message.SPEECH_ACT_KEY);
indexsd2.add(Message.CONTEXT_KEY);
indexsd3.add(Message.RESULT_KEY);
indexsd4.add(Message.ACTOR_KEY);
NestedAtomic SuperGLUDefaultSpeechAct=new NestedAtomic(indexsd1);
SuperGLUDefaultSpeechAct.setFieldData("INFORM_ACT");
NestedAtomic SuperGLUDefaultContextField =new NestedAtomic(indexsd2);
SuperGLUDefaultContextField.setFieldData("");
NestedAtomic SuperGLUDefaultResultField=new NestedAtomic(indexsd3);
SuperGLUDefaultResultField.setFieldData("");
NestedAtomic SuperGLUDefaultActorField=new NestedAtomic(indexsd4);
SuperGLUDefaultActorField.setFieldData("");
supergluArr.add(SuperGLUDefaultSpeechAct);
supergluArr.add(SuperGLUDefaultContextField);
supergluArr.add(SuperGLUDefaultResultField);
supergluArr.add(SuperGLUDefaultActorField);
//STORED THE DATA IN THE SUPERGLU MESSAGE TEMPLATE
MessageTemplate supergluMsgTemp=new MessageTemplate(supergluArr);
//CREATED THE DEFAULT FIELDS IN THE VHMSG TEMPLATE
//STORED THE DATA IN THE VH MESSAGE TEMPLATE
MessageTemplate vhMsgTemp=new MessageTemplate(vhMsgArr);
//CREATING THE NESTED ATOMIC FIELDS THAT HAVE MATCHES (VHT)
List<String> indexvh1=new ArrayList<String>();
List<String> indexvh2=new ArrayList<String>();
indexvh1.add(VHMessage.FIRST_WORD_KEY);
indexvh2.add(VHMessage.BODY_KEY);
NestedAtomic VHT_LabelField=new NestedAtomic(indexvh1);
VHT_LabelField.setFieldData("ScenarioName");
NestedAtomic VHT_BodyField=new NestedAtomic(indexvh2);
//CREATING THE NESTED ATOMIC FIELDS THAT HAVE MATCHES (VHT)
List<String> indexsg1=new ArrayList<String>();
List<String> indexsg2=new ArrayList<String>();
indexsg1.add(Message.OBJECT_KEY);
indexsg2.add(Message.VERB_KEY);
NestedAtomic SuperGLU_ObjectField=new NestedAtomic(indexsg1);
NestedAtomic SuperGLU_VerbField=new NestedAtomic(indexsg2);
//CREATED THE MAPPINGS FOR THE VERB AND BODY FIELDS RESPECTIVELY BELOW
FieldMap VHT_SuperGLU_TopicVerb_FM=new FieldMap();
VHT_SuperGLU_TopicVerb_FM.setInField(VHT_LabelField);
VHT_SuperGLU_TopicVerb_FM.setOutField(SuperGLU_VerbField);
FieldMap VHT_SuperGLU_TopicObject_FM=new FieldMap();
VHT_SuperGLU_TopicObject_FM.setInField(VHT_BodyField);
VHT_SuperGLU_TopicObject_FM.setOutField(SuperGLU_ObjectField);
ArrayList<FieldMap> fieldmappings=new ArrayList<FieldMap>();
fieldmappings.add(VHT_SuperGLU_TopicVerb_FM);
fieldmappings.add(VHT_SuperGLU_TopicObject_FM);
//CREATING A MESSAGE TEMPLATE THAT WILL GO INTO THE DEFAULT MESSAGETEMPLATES (WHICH DOES NOT HAVE MATCHES)
ArrayList<NestedAtomic> supergluArrGeneric=new ArrayList<NestedAtomic>();
ArrayList<NestedAtomic> vhMsgArrGeneric=new ArrayList<NestedAtomic>();
vhMsgArrGeneric.add(VHT_BodyField);
vhMsgArrGeneric.add(VHT_LabelField);
MessageTemplate vhMsgTempGeneric=new MessageTemplate(vhMsgArrGeneric);
supergluArrGeneric.add(SuperGLUDefaultContextField);
supergluArrGeneric.add(SuperGLUDefaultSpeechAct);
supergluArrGeneric.add(SuperGLUDefaultResultField);
supergluArrGeneric.add(SuperGLU_ObjectField);
supergluArrGeneric.add(SuperGLU_VerbField);
supergluArrGeneric.add(SuperGLUDefaultActorField);
MessageTemplate supergluMsgTempGeneric=new MessageTemplate(supergluArrGeneric);
//CREATING THE MESSAGETYPEBASED VHMESSAGE
MessageType VHTMsgV1_8=new MessageType("ScenarioName", 0.0f, 1.1f,vhMsgTempGeneric,"VHMessage");
MessageType SuperGLUMsgV1=new MessageType("SUPERGLUMSG_1",0.0f,1.1f,supergluMsgTempGeneric,"Message");
//CREATING THE INNER FIELDS OF THE MAPPING
VHT_SuperGLU_CurrentScenario.setFieldMappings(fieldmappings);
VHT_SuperGLU_CurrentScenario.setInDefaultMsgType(vhMsgTemp);
VHT_SuperGLU_CurrentScenario.setOutDefaultMsgType(supergluMsgTemp);
VHT_SuperGLU_CurrentScenario.setInMsgType(VHTMsgV1_8);
VHT_SuperGLU_CurrentScenario.setOutMsgType(SuperGLUMsgV1);
//STEP 1: CREATING A TOKEN OF A VHMESSAGE THAT WAS SENT ABOVE
StorageToken ST_FromInputMsg=v1.saveToToken();
System.out.println(ST_FromInputMsg.getClassId());
//System.out.println(ST_FromInputMsg.getItem(v1.FIRST_WORD_KEY));
//STEP 2: CREATING THE ONTOLOGY CONVERTER OBJECT SO THAT WE CAN PASS IN THE MESSAGEMAPS LIST
List<MessageMap> createdList=new ArrayList<MessageMap>();
createdList.add(VHT_SuperGLU_CurrentScenario);
//createdList.add(VHT_SuperGLU_beginAAR);
//createdList.add(VHT_SuperGLU_getNextAgendaItem);
//createdList.add(VHT_SuperGLU_requestCoachingActions);
//OntologyConverter ontconvert=new OntologyConverter(createdList);
MessageMap test1=new MessageMap();
//STEP 3: CALLING THE ISVALIDSOURCEMESSAGE CLASS
String firstword=(String) ST_FromInputMsg.getItem(VHMessage.FIRST_WORD_KEY);
System.out.println("check "+firstword);
boolean result=test1.isValidSourceMsg(ST_FromInputMsg,firstword);
if(result==true)
System.out.println("Yes there is a match and a valid source message");
else
System.out.println("No there is no match and its not a valid source message");
//STEP 4: CALLING THE CONVERT FUNCTION FOR THE ACTUAL CONVERSIONS
BaseMessage convertedMessage=test1.convert(ST_FromInputMsg);
//Assert.assertEquals(expected, actual);
if(convertedMessage!=null)
System.out.println("Conversion Successful!");
else
System.out.println("Conversion Failed");
}
} |
package com.ibm.bi.dml.api;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import java.util.Scanner;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.nimble.configuration.NimbleConfig;
import org.nimble.control.DAGQueue;
import org.nimble.control.PMLDriver;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import com.ibm.bi.dml.lops.Lops;
import com.ibm.bi.dml.packagesupport.PackageRuntimeException;
import com.ibm.bi.dml.parser.DMLProgram;
import com.ibm.bi.dml.parser.DMLQLParser;
import com.ibm.bi.dml.parser.DMLTranslator;
import com.ibm.bi.dml.parser.ParseException;
import com.ibm.bi.dml.runtime.controlprogram.CacheableData;
import com.ibm.bi.dml.runtime.controlprogram.LocalVariableMap;
import com.ibm.bi.dml.runtime.controlprogram.Program;
import com.ibm.bi.dml.runtime.controlprogram.ProgramBlock;
import com.ibm.bi.dml.runtime.controlprogram.WhileProgramBlock;
import com.ibm.bi.dml.runtime.controlprogram.parfor.DataPartitioner;
import com.ibm.bi.dml.runtime.controlprogram.parfor.util.ConfigurationManager;
import com.ibm.bi.dml.runtime.controlprogram.parfor.util.IDHandler;
import com.ibm.bi.dml.runtime.instructions.Instruction.INSTRUCTION_TYPE;
import com.ibm.bi.dml.runtime.matrix.mapred.MRJobConfiguration;
import com.ibm.bi.dml.runtime.util.MapReduceTool;
import com.ibm.bi.dml.sql.sqlcontrolprogram.ExecutionContext;
import com.ibm.bi.dml.sql.sqlcontrolprogram.NetezzaConnector;
import com.ibm.bi.dml.sql.sqlcontrolprogram.SQLProgram;
import com.ibm.bi.dml.utils.DMLException;
import com.ibm.bi.dml.utils.DMLRuntimeException;
import com.ibm.bi.dml.utils.HopsException;
import com.ibm.bi.dml.utils.LanguageException;
import com.ibm.bi.dml.utils.Statistics;
import com.ibm.bi.dml.utils.configuration.DMLConfig;
import com.ibm.bi.dml.utils.visualize.DotGraph;
public class DMLScript {
//TODO: Change these static variables to non-static, and create corresponding access methods
public enum EXECUTION_PROPERTIES {LOG, DEBUG, VISUALIZE, RUNTIME_PLATFORM, CONFIG};
public static boolean DEBUG = false;
public static boolean VISUALIZE = false;
public static boolean LOG = false;
public enum RUNTIME_PLATFORM { HADOOP, SINGLE_NODE, HYBRID, NZ, INVALID };
// We should assume the default value is HYBRID
public static RUNTIME_PLATFORM rtplatform = RUNTIME_PLATFORM.HYBRID;
public static final String _uuid = IDHandler.createDistributedUniqueID();
private String _dmlScriptString;
// stores name of the OPTIONAL config file
private String _optConfig;
// stores optional args to parameterize DML script
private HashMap<String, String> _argVals;
private Logger _mapredLogger;
private Logger _mmcjLogger;
public static final String DEFAULT_SYSTEMML_CONFIG_FILEPATH = "./SystemML-config.xml";
private static final String DEFAULT_MAPRED_LOGGER = "org.apache.hadoop.mapred";
private static final String DEFAULT_MMCJMR_LOGGER = "dml.runtime.matrix.MMCJMR";
private static final String LOG_FILE_NAME = "SystemML.log";
// stores the path to the source
private static final String PATH_TO_SRC = "./";
public static String USAGE = "Usage is " + DMLScript.class.getCanonicalName()
+ " [-f | -s] <filename>" + " -exec <mode>" + " [-d | -debug]?" + " [-l | -log]?" + " (-config=<config_filename>)? (-args)? <args-list>? \n"
+ " -f: <filename> will be interpreted as a filename path + \n"
+ " <filename> prefixed with hdfs: is hdfs file, otherwise it is local file + \n"
+ " -s: <filename> will be interpreted as a DML script string \n"
+ " -exec: <mode> (optional) execution mode (hadoop, singlenode, hybrid)\n"
+ " [-d | -debug]: (optional) output debug info \n"
+ " [-v | -visualize]: (optional) use visualization of DAGs \n"
+ " [-l | -log]: (optional) output log info \n"
+ " -config: (optional) use config file <config_filename> (default: use parameter values in default SystemML-config.xml config file) \n"
+ " <config_filename> prefixed with hdfs: is hdfs file, otherwise it is local file + \n"
+ " -args: (optional) parameterize DML script with contents of [args list], ALL args after -args flag \n"
+ " 1st value after -args will replace $1 in DML script, 2nd value will replace $2 in DML script, and so on."
+ "<args-list>: (optional) args to DML script \n" ;
public DMLScript (){
}
public DMLScript(String dmlScript, boolean debug, boolean log, boolean visualize, RUNTIME_PLATFORM rt, String config, HashMap<String, String> argVals){
_dmlScriptString = dmlScript;
DEBUG = debug;
LOG = log;
VISUALIZE = visualize;
rtplatform = rt;
_optConfig = config;
_argVals = argVals;
_mapredLogger = Logger.getLogger(DEFAULT_MAPRED_LOGGER);
_mmcjLogger = Logger.getLogger(DEFAULT_MMCJMR_LOGGER);
}
/**
* run: The running body of DMLScript execution. This method should be called after execution properties have been correctly set,
* and customized parameters have been put into _argVals
* @throws ParseException
* @throws IOException
* @throws DMLException
*/
private boolean run()throws IOException, ParseException, DMLException {
boolean success = false;
/////////////// set logger level //////////////////////////////////////
if (rtplatform == RUNTIME_PLATFORM.HADOOP || rtplatform == RUNTIME_PLATFORM.HYBRID){
if (DEBUG)
_mapredLogger.setLevel(Level.WARN);
else {
_mapredLogger.setLevel(Level.WARN);
_mmcjLogger.setLevel(Level.WARN);
}
}
////////////// handle log output //////////////////////////
BufferedWriter out = null;
if (LOG && (rtplatform == RUNTIME_PLATFORM.HADOOP || rtplatform == RUNTIME_PLATFORM.HYBRID)) {
// copy the input DML script to ./log folder
// TODO: define the default path to store SystemML.log
String hadoop_home = System.getenv("HADOOP_HOME");
System.out.println("HADOOP_HOME: " + hadoop_home);
File logfile = new File(hadoop_home + "/" + LOG_FILE_NAME);
if (!logfile.exists()) {
success = logfile.createNewFile(); // creates the file
if (success == false)
System.err.println("ERROR: Failed to create log file: " + hadoop_home + "/" + LOG_FILE_NAME);
return success;
}
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logfile, true)));
out.write("BEGIN DMLRun " + getDateTime() + "\n");
out.write("BEGIN DMLScript\n");
// No need to reopen the dml script, just print out dmlScriptString
out.write(_dmlScriptString);
out.write("END DMLScript\n");
}
// optional config specified overwrites/merge into the default config
DMLConfig defaultConfig = null;
DMLConfig optionalConfig = null;
if (_optConfig != null) { // the optional config is specified
try { // try to get the default config first
defaultConfig = new DMLConfig(DEFAULT_SYSTEMML_CONFIG_FILEPATH);
} catch (Exception e) { // it is ok to not have the default
defaultConfig = null;
}
try { // try to get the optional config next
optionalConfig = new DMLConfig(_optConfig);
} catch (Exception e) { // it is not ok as the specification is wrong
optionalConfig = null;
System.err.println("ERROR: Error parsing optional configuration file: " + _optConfig);
//return false;
}
if (defaultConfig != null) {
try {
defaultConfig.merge(optionalConfig);
}
catch(Exception e){
System.err.println("ERROR: failed to merge default ");
//return false;
}
}
else {
defaultConfig = optionalConfig;
}
}
else { // the optional config is not specified
try { // try to get the default config
defaultConfig = new DMLConfig(DEFAULT_SYSTEMML_CONFIG_FILEPATH);
} catch (Exception e) { // it is not OK to not have the default
defaultConfig = null;
System.out.println("ERROR: Error parsing default configuration file: " + DEFAULT_SYSTEMML_CONFIG_FILEPATH);
//System.exit(1);
}
}
ConfigurationManager.setConfig(defaultConfig);
////////////////print config file parameters /////////////////////////////
if (DEBUG){
System.out.println("INFO: ****** DMLConfig parameters *****");
System.out.println("INFO: " + DMLConfig.SCRATCH_SPACE + ": " + ConfigurationManager.getConfig().getTextValue(DMLConfig.SCRATCH_SPACE));
System.out.println("INFO: " + DMLConfig.NUM_REDUCERS + ": " + ConfigurationManager.getConfig().getTextValue(DMLConfig.NUM_REDUCERS));
System.out.println("INFO: " + DMLConfig.DEF_BLOCK_SIZE + ": " + ConfigurationManager.getConfig().getTextValue(DMLConfig.DEF_BLOCK_SIZE));
System.out.println("INFO: " + DMLConfig.NUM_MERGE_TASKS + ": "+ ConfigurationManager.getConfig().getTextValue(DMLConfig.NUM_MERGE_TASKS));
System.out.println("INFO: " + DMLConfig.NUM_SOW_THREADS + ": "+ ConfigurationManager.getConfig().getTextValue(DMLConfig.NUM_SOW_THREADS));
System.out.println("INFO: " + DMLConfig.NUM_REAP_THREADS + ": "+ ConfigurationManager.getConfig().getTextValue(DMLConfig.NUM_REAP_THREADS ));
System.out.println("INFO: " + DMLConfig.SOWER_WAIT_INTERVAL + ": "+ ConfigurationManager.getConfig().getTextValue(DMLConfig.SOWER_WAIT_INTERVAL ));
System.out.println("INFO: " + DMLConfig.REAPER_WAIT_INTERVAL + ": "+ ConfigurationManager.getConfig().getTextValue(DMLConfig.REAPER_WAIT_INTERVAL));
System.out.println("INFO: " + DMLConfig.NIMBLE_SCRATCH + ": "+ ConfigurationManager.getConfig().getTextValue(DMLConfig.NIMBLE_SCRATCH ));
System.out.println("INFO: " + DMLConfig.REAPER_WAIT_INTERVAL + ": "+ ConfigurationManager.getConfig().getTextValue(DMLConfig.REAPER_WAIT_INTERVAL));
}
///////////////////////////////////// parse script ////////////////////////////////////////////
DMLProgram prog = null;
DMLQLParser parser = new DMLQLParser(_dmlScriptString, _argVals);
prog = parser.parse();
if (prog == null){
System.err.println("ERROR: Parsing failed");
success = false;
return success;
}
if (DEBUG) {
System.out.println("********************** PARSER *******************");
System.out.println(prog.toString());
}
///////////////////////////////////// construct HOPS ///////////////////////////////
DMLTranslator dmlt = new DMLTranslator(prog);
dmlt.validateParseTree(prog);
dmlt.liveVariableAnalysis(prog);
if (DEBUG) {
System.out.println("********************** COMPILER *******************");
System.out.println(prog.toString());
}
dmlt.constructHops(prog);
if (DEBUG) {
System.out.println("********************** HOPS DAG (Before Rewrite) *******************");
// print
dmlt.printHops(prog);
dmlt.resetHopsDAGVisitStatus(prog);
// visualize
DotGraph gt = new DotGraph();
// last parameter: the path of DML source directory. If dml source
// is at /path/to/dml/src then it should be /path/to/dml.
gt.drawHopsDAG(prog, "HopsDAG Before Rewrite", 50, 50, PATH_TO_SRC, VISUALIZE);
dmlt.resetHopsDAGVisitStatus(prog);
}
// rewrite HOPs DAGs
if (DEBUG) {
System.out.println("********************** Rewriting HOPS DAG *******************");
}
// defaultConfig contains reconciled information for config
dmlt.rewriteHopsDAG(prog, defaultConfig);
dmlt.resetHopsDAGVisitStatus(prog);
if (DEBUG) {
System.out.println("********************** HOPS DAG (After Rewrite) *******************");
// print
dmlt.printHops(prog);
dmlt.resetHopsDAGVisitStatus(prog);
// visualize
DotGraph gt = new DotGraph();
gt.drawHopsDAG(prog, "HopsDAG After Rewrite", 100, 100, PATH_TO_SRC, VISUALIZE);
dmlt.resetHopsDAGVisitStatus(prog);
}
executeHadoop(dmlt, prog, defaultConfig, out);
success = true;
return success;
}
/**
* executeScript: Execute a DML script, which is provided by the user as a file path to the script file.
* @param scriptPathName Path to the DML script file
* @param scriptArguments Variant arguments provided by the user to run with the DML Script
* @throws ParseException
* @throws IOException
* @throws DMLException
*/
public boolean executeScript (String scriptPathName, String... scriptArguments) throws IOException, ParseException, DMLException{
boolean success = false;
success = executeScript(scriptPathName, (Properties)null, scriptArguments);
return success;
}
/**
* executeScript: Execute a DML script, which is provided by the user as a file path to the script file.
* @param scriptPathName Path to the DML script file
* @param executionProperties DMLScript runtime and debug settings
* @param scriptArguments Variant arguments provided by the user to run with the DML Script
* @throws ParseException
* @throws IOException
* @throws DMLException
*/
public boolean executeScript (String scriptPathName, Properties executionProperties, String... scriptArguments) throws IOException, ParseException, DMLException{
boolean success = false;
DEBUG = false;
VISUALIZE = false;
LOG = false;
_dmlScriptString = null;
_optConfig = null;
_argVals = new HashMap<String, String>();
_mapredLogger = Logger.getLogger(DEFAULT_MAPRED_LOGGER);
_mmcjLogger = Logger.getLogger(DEFAULT_MMCJMR_LOGGER);
//Process the script path, get the content of the script
StringBuilder dmlScriptString = new StringBuilder();
if (scriptPathName == null){
System.err.println("ERROR: script path must be provided!");
success = false;
return success;
}
else {
String s1 = null;
BufferedReader in = null;
//TODO: update this hard coded line
if (scriptPathName.startsWith("hdfs:")){
FileSystem hdfs = FileSystem.get(new Configuration());
Path scriptPath = new Path(scriptPathName);
in = new BufferedReader(new InputStreamReader(hdfs.open(scriptPath)));
}
else { // from local file system
in = new BufferedReader(new FileReader(scriptPathName));
}
while ((s1 = in.readLine()) != null)
dmlScriptString.append(s1 + "\n");
in.close();
}
_dmlScriptString=dmlScriptString.toString();
success = processExecutionProperties(executionProperties);
if (!success){
System.err.println("ERROR: There are invalid execution properties!");
return success;
}
success = processOptionalScriptArgs(scriptArguments);
if (!success){
System.err.println("ERROR: There are invalid script arguments!");
return success;
}
if (DEBUG){
System.out.println("INFO: ****** args to DML Script ****** ");
System.out.println("INFO: UUID: " + getUUID());
System.out.println("INFO: SCRIPT PATH: " + scriptPathName);
System.out.println("INFO: DEBUG: " + DEBUG);
System.out.println("INFO: LOG: " + LOG);
System.out.println("INFO: VISUALIZE: " + VISUALIZE);
System.out.println("INFO: RUNTIME: " + rtplatform);
System.out.println("INFO: BUILTIN CONFIG: " + DEFAULT_SYSTEMML_CONFIG_FILEPATH);
System.out.println("INFO: OPTIONAL CONFIG: " + _optConfig);
if (_argVals.size() > 0)
System.out.println("INFO: Value for script parameter args: ");
for (int i=1; i<= _argVals.size(); i++)
System.out.println("INFO: $" + i + " = " + _argVals.get("$" + i) );
}
success = run();
resetExecutionOptions();
return success;
}
/**
* executeScript: Execute a DML script. The content of the script is provided by the user as an input stream.
* @param script InputStream as the DML script
* @param executionProperties DMLScript runtime and debug settings
* @param scriptArguments Variant arguments provided by the user to run with the DML Script
* @throws ParseException
* @throws IOException
* @throws DMLException
*/
public boolean executeScript (InputStream script, Properties executionProperties, String... scriptArguments) throws IOException, ParseException, DMLException{
boolean success = false;
DEBUG = false;
VISUALIZE = false;
LOG = false;
_dmlScriptString = null;
_optConfig = null;
_argVals = new HashMap<String, String>();
_mapredLogger = Logger.getLogger(DEFAULT_MAPRED_LOGGER);
_mmcjLogger = Logger.getLogger(DEFAULT_MMCJMR_LOGGER);
if (script == null){
System.err.println("ERROR: Script string must be provided!");
success = false;
return success;
}
else {
_dmlScriptString = new Scanner(script).useDelimiter("\\A").next();
}
success = processExecutionProperties(executionProperties);
if (!success){
System.err.println("ERROR: There are invalid execution properties!");
//System.err.println(USAGE);
return success;
}
success = processOptionalScriptArgs(scriptArguments);
if (!success){
System.err.println("ERROR: There are invalid script arguments!");
return success;
}
if (DEBUG){
System.out.println("INFO: ****** args to DML Script ****** ");
System.out.println("INFO: UUID: " + getUUID());
System.out.println("INFO: SCRIPT: " + _dmlScriptString);
System.out.println("INFO: DEBUG: " + DEBUG);
System.out.println("INFO: LOG: " + LOG);
System.out.println("INFO: VISUALIZE: " + VISUALIZE);
System.out.println("INFO: RUNTIME: " + rtplatform);
System.out.println("INFO: BUILTIN CONFIG: " + DEFAULT_SYSTEMML_CONFIG_FILEPATH);
System.out.println("INFO: OPTIONAL CONFIG: " + _optConfig);
if (_argVals.size() > 0)
System.out.println("INFO: Value for script parameter args: ");
for (int i=1; i<= _argVals.size(); i++)
System.out.println("INFO: $" + i + " = " + _argVals.get("$" + i) );
}
success = run();
resetExecutionOptions();
return success;
}
private void resetExecutionOptions(){
DEBUG = false;
VISUALIZE = false;
LOG = false;
rtplatform = RUNTIME_PLATFORM.HYBRID;
_optConfig = null;
}
//Process execution properties
private boolean processExecutionProperties(Properties executionProperties){
boolean success = false;
if (executionProperties != null){
//Make sure that the properties are in the defined property list that can be handled
@SuppressWarnings("unchecked")
Enumeration<String> e = (Enumeration<String>) executionProperties.propertyNames();
while (e.hasMoreElements()){
String key = e.nextElement();
boolean validProperty = false;
for (EXECUTION_PROPERTIES p : EXECUTION_PROPERTIES.values()){
if (p.name().equals(key)){
validProperty = true;
break;
}
}
if (!validProperty){
System.err.println("ERROR: Unknown execution property: " + key);
resetExecutionOptions();
success = false;
return success;
}
}
LOG = Boolean.valueOf(executionProperties.getProperty(EXECUTION_PROPERTIES.LOG.toString(), "false"));
DEBUG = Boolean.valueOf(executionProperties.getProperty(EXECUTION_PROPERTIES.DEBUG.toString(), "false"));
VISUALIZE = Boolean.valueOf(executionProperties.getProperty(EXECUTION_PROPERTIES.VISUALIZE.toString(), "false"));
String runtime_pt = executionProperties.getProperty(EXECUTION_PROPERTIES.RUNTIME_PLATFORM.toString(), "hybrid");
if (runtime_pt.equalsIgnoreCase("hadoop"))
rtplatform = RUNTIME_PLATFORM.HADOOP;
else if ( runtime_pt.equalsIgnoreCase("singlenode"))
rtplatform = RUNTIME_PLATFORM.SINGLE_NODE;
else if ( runtime_pt.equalsIgnoreCase("hybrid"))
rtplatform = RUNTIME_PLATFORM.HYBRID;
else if ( runtime_pt.equalsIgnoreCase("nz"))
rtplatform = RUNTIME_PLATFORM.NZ;
_optConfig = executionProperties.getProperty(EXECUTION_PROPERTIES.CONFIG.toString(), null);
}
else {
resetExecutionOptions();
}
success = true;
return success;
}
//Process the optional script arguments provided by the user to run with the DML script
private boolean processOptionalScriptArgs(String... scriptArguments){
boolean success = false;
if (scriptArguments != null){
int index = 1;
for (String arg : scriptArguments){
if (arg.equalsIgnoreCase("-d") || arg.equalsIgnoreCase("-debug")||
arg.equalsIgnoreCase("-l") || arg.equalsIgnoreCase("-log") ||
arg.equalsIgnoreCase("-v") || arg.equalsIgnoreCase("-visualize")||
arg.equalsIgnoreCase("-exec") ||
arg.startsWith("-config=")){
System.err.println("ERROR: -args must be the final argument for DMLScript!");
resetExecutionOptions();
success = false;
return success;
}
_argVals.put("$"+index ,arg);
index++;
}
}
success = true;
return success;
}
/**
* @param args
* @throws ParseException
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static void main(String[] args) throws IOException, ParseException, DMLException {
// This is a show case how to create a DMLScript object to accept a DML script provided by the user,
// and how to run it.
/////////// if the args is incorrect, print usage /////////////
if (args.length < 2){
//System.err.println(USAGE);
return;
}
////////////process -f | -s to set dmlScriptString ////////////////
else if (!(args[0].equals("-f") || args[0].equals("-s"))){
System.err.println("ERROR: First argument must be either -f or -s");
//System.err.println(USAGE);
return;
}
DMLScript d = new DMLScript();
boolean fromFile = (args[0].equals("-f")) ? true : false;
boolean success = false;
String script = args[1];
Properties executionProperties = new Properties();
String[] scriptArgs = null;
int i = 2;
while (i<args.length){
if (args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("-debug")) {
executionProperties.put(EXECUTION_PROPERTIES.DEBUG.toString(), "true");
} else if (args[i].equalsIgnoreCase("-l") || args[i].equalsIgnoreCase("-log")) {
executionProperties.put(EXECUTION_PROPERTIES.LOG.toString(), "true");
} else if (args[i].equalsIgnoreCase("-v") || args[i].equalsIgnoreCase("-visualize")) {
executionProperties.put(EXECUTION_PROPERTIES.VISUALIZE.toString(), "true");
} else if ( args[i].equalsIgnoreCase("-exec")) {
i++;
if ( args[i].equalsIgnoreCase("hadoop"))
executionProperties.put(EXECUTION_PROPERTIES.RUNTIME_PLATFORM.toString(), "hadoop");
else if ( args[i].equalsIgnoreCase("singlenode"))
executionProperties.put(EXECUTION_PROPERTIES.RUNTIME_PLATFORM.toString(), "singlenode");
else if ( args[i].equalsIgnoreCase("hybrid"))
executionProperties.put(EXECUTION_PROPERTIES.RUNTIME_PLATFORM.toString(), "hybrid");
else if ( args[i].equalsIgnoreCase("nz"))
executionProperties.put(EXECUTION_PROPERTIES.RUNTIME_PLATFORM.toString(), "nz");
else {
System.err.println("ERROR: Unknown runtime platform: " + args[i]);
return;
}
// handle config file
} else if (args[i].startsWith("-config=")){
executionProperties.put(EXECUTION_PROPERTIES.CONFIG.toString(), args[i].substring(8).replaceAll("\"", ""));
}
// handle the args to DML Script -- rest of args will be passed here to
else if (args[i].startsWith("-args")) {
i++;
scriptArgs = new String[args.length - i];
int j = 0;
while( i < args.length){
scriptArgs[j++]=args[i++];
}
}
else {
System.err.println("ERROR: Unknown argument: " + args[i]);
//System.err.println(USAGE);
return;
}
i++;
}
if (fromFile){
success = d.executeScript(script, executionProperties, scriptArgs);
}
else {
InputStream is = new ByteArrayInputStream(script.getBytes());
success = d.executeScript(is, executionProperties, scriptArgs);
}
if (!success){
System.err.println("ERROR: Script cannot be executed!");
return;
}
} ///~ end main
/**
* executeHadoop: Handles execution on the Hadoop Map-reduce runtime
* @param dmlt DML Translator
* @param prog DML Program object from parsed DML script
* @param config read from provided configuration file (e.g., config.xml)
* @param out writer for log output
* @throws ParseException
* @throws IOException
* @throws DMLException
*/
private static void executeHadoop(DMLTranslator dmlt, DMLProgram prog, DMLConfig config, BufferedWriter out) throws ParseException, IOException, DMLException{
/////////////////////// construct the lops ///////////////////////////////////
dmlt.constructLops(prog);
if (DEBUG) {
System.out.println("********************** LOPS DAG *******************");
dmlt.printLops(prog);
dmlt.resetLopsDAGVisitStatus(prog);
DotGraph gt = new DotGraph();
gt.drawLopsDAG(prog, "LopsDAG", 150, 150, PATH_TO_SRC, VISUALIZE);
dmlt.resetLopsDAGVisitStatus(prog);
}
////////////////////// generate runtime program ///////////////////////////////
Program rtprog = prog.getRuntimeProgram(DEBUG, config);
DAGQueue dagQueue = setupNIMBLEQueue(config);
if (DEBUG && config == null){
System.out.println("INFO: config is null -- you may need to verify config file path");
}
if (DEBUG && dagQueue == null){
System.out.println("INFO: dagQueue is not set");
}
rtprog.setDAGQueue(dagQueue);
// Count number compiled MR jobs
int jobCount = 0;
for (ProgramBlock blk : rtprog.getProgramBlocks())
jobCount += countCompiledJobs(blk);
Statistics.setNoOfCompiledMRJobs(jobCount);
if (DEBUG) {
System.out.println("********************** Instructions *******************");
System.out.println(rtprog.toString());
rtprog.printMe();
// visualize
//DotGraph gt = new DotGraph();
//gt.drawInstructionsDAG(rtprog, "InstructionsDAG", 200, 200, path_to_src);
System.out.println("********************** Execute *******************");
}
if (LOG)
out.write("Compile Status OK\n");
/////////////////////////// execute program //////////////////////////////////////
Statistics.startRunTimer();
try
{
//init caching
CacheableData.createCacheDir();
//run execute (w/ exception handling to ensure proper shutdown)
rtprog.execute (new LocalVariableMap (), null);
}
catch(DMLException ex)
{
throw ex;
}
finally //ensure cleanup/shutdown
{
Statistics.stopRunTimer();
//if (DEBUG)
System.out.println(Statistics.display());
if (LOG) {
out.write("END DMLRun " + getDateTime() + "\n");
out.close();
}
//cleanup all nimble threads
if(rtprog.getDAGQueue() != null)
rtprog.getDAGQueue().forceShutDown();
//cleanup scratch space (everything for current uuid)
//(required otherwise export to hdfs would skip assumed unnecessary writes if same name)
MapReduceTool.deleteFileIfExistOnHDFS( config.getTextValue(DMLConfig.SCRATCH_SPACE)+
Lops.FILE_SEPARATOR+Lops.PROCESS_PREFIX+DMLScript.getUUID() );
//cleanup working dirs (hadoop, cache)
MapReduceTool.deleteFileIfExistOnHDFS( DMLConfig.LOCAL_MR_MODE_STAGING_DIR + //staging dir (for local mode only) //TODO: check if this is required at all
Lops.FILE_SEPARATOR + Lops.PROCESS_PREFIX + DMLScript.getUUID() );
MapReduceTool.deleteFileIfExistOnHDFS( MRJobConfiguration.getStagingWorkingDirPrefix() + //staging dir
Lops.FILE_SEPARATOR + Lops.PROCESS_PREFIX + DMLScript.getUUID() );
MapReduceTool.deleteFileIfExistOnHDFS( MRJobConfiguration.getLocalWorkingDirPrefix() + //local dir
Lops.FILE_SEPARATOR + Lops.PROCESS_PREFIX + DMLScript.getUUID() );
MapReduceTool.deleteFileIfExistOnHDFS( MRJobConfiguration.getSystemWorkingDirPrefix() + //system dir
Lops.FILE_SEPARATOR + Lops.PROCESS_PREFIX + DMLScript.getUUID() );
CacheableData.cleanupCacheDir();
DataPartitioner.cleanupWorkingDirectory();
}
} // end executeHadoop
/**
* executeNetezza: handles execution on Netezza runtime
* @param dmlt DML Translator
* @param prog DML program from parsed DML script
* @param config from parsed config file (e.g., config.xml)
* @throws ParseException
* @throws HopsException
* @throws DMLRuntimeException
*/
private static void executeNetezza(DMLTranslator dmlt, DMLProgram prog, DMLConfig config, String fileName)
throws HopsException, LanguageException, ParseException, DMLRuntimeException
{
dmlt.constructSQLLops(prog);
SQLProgram sqlprog = dmlt.getSQLProgram(prog);
String[] split = fileName.split("/");
String name = split[split.length-1].split("\\.")[0];
sqlprog.set_name(name);
dmlt.resetSQLLopsDAGVisitStatus(prog);
DotGraph g = new DotGraph();
g.drawSQLLopsDAG(prog, "SQLLops DAG", 100, 100, PATH_TO_SRC, VISUALIZE);
dmlt.resetSQLLopsDAGVisitStatus(prog);
String sql = sqlprog.generateSQLString();
Program pr = sqlprog.getProgram();
pr.printMe();
if (true) {
System.out.println(sql);
}
NetezzaConnector con = new NetezzaConnector();
try
{
ExecutionContext ec = new ExecutionContext(con);
ec.setDebug(false);
LocalVariableMap vm = new LocalVariableMap ();
ec.set_variables (vm);
con.connect();
long time = System.currentTimeMillis();
pr.execute (vm, ec);
long end = System.currentTimeMillis() - time;
System.out.println("Control program took " + ((double)end / 1000) + " seconds");
con.disconnect();
System.out.println("Done");
}
catch(Exception e)
{
e.printStackTrace();
}
/*
// Code to execute the stored procedure version of the DML script
try
{
con.connect();
con.executeSQL(sql);
long time = System.currentTimeMillis();
con.callProcedure(name);
long end = System.currentTimeMillis() - time;
System.out.println("Stored procedure took " + ((double)end / 1000) + " seconds");
System.out.println(String.format("Procedure %s was executed on Netezza", name));
con.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
}*/
} // end executeNetezza
/**
* Method to setup the NIMBLE task queue.
* This will be used in future external function invocations
* @param dmlCfg DMLConfig object
* @return NIMBLE task queue
*/
static DAGQueue setupNIMBLEQueue(DMLConfig dmlCfg) {
//config not provided
if (dmlCfg == null)
return null;
// read in configuration files
NimbleConfig config = new NimbleConfig();
try {
config.parseSystemDocuments(dmlCfg.getConfig_file_name());
//ensure unique working directory for nimble output
StringBuffer sb = new StringBuffer();
sb.append( dmlCfg.getTextValue(DMLConfig.SCRATCH_SPACE) );
sb.append( Lops.FILE_SEPARATOR );
sb.append( Lops.PROCESS_PREFIX );
sb.append( getUUID() );
sb.append( Lops.FILE_SEPARATOR );
sb.append( dmlCfg.getTextValue(DMLConfig.NIMBLE_SCRATCH) );
((Element)config.getSystemConfig().getParameters().getElementsByTagName(DMLConfig.NIMBLE_SCRATCH).item(0))
.setTextContent( sb.toString() );
} catch (Exception e) {
e.printStackTrace();
throw new PackageRuntimeException ("Error parsing Nimble configuration files");
}
// get threads configuration and validate
int numSowThreads = 1;
int numReapThreads = 1;
numSowThreads = Integer.parseInt
(NimbleConfig.getTextValue(config.getSystemConfig().getParameters(), DMLConfig.NUM_SOW_THREADS));
numReapThreads = Integer.parseInt
(NimbleConfig.getTextValue(config.getSystemConfig().getParameters(), DMLConfig.NUM_REAP_THREADS));
if (numSowThreads < 1 || numReapThreads < 1){
throw new PackageRuntimeException("Illegal values for thread count (must be > 0)");
}
// Initialize an instance of the driver.
PMLDriver driver = null;
try {
driver = new PMLDriver(numSowThreads, numReapThreads, config);
driver.startEmptyDriver(config);
} catch (Exception e) {
e.printStackTrace();
throw new PackageRuntimeException("Problem starting nimble driver");
}
return driver.getDAGQueue();
}
private static String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
private static int countCompiledJobs(ProgramBlock blk) {
int jobCount = 0;
if (blk instanceof WhileProgramBlock){
ArrayList<ProgramBlock> childBlocks = ((WhileProgramBlock) blk).getChildBlocks();
for (ProgramBlock pb : childBlocks){
jobCount += countCompiledJobs(pb);
}
if (blk.getNumInstructions() > 0){
System.out.println("error: while programBlock should not have instructions ");
}
}
else {
for (int i = 0; i < blk.getNumInstructions(); i++)
if (blk.getInstruction(i).getType() == INSTRUCTION_TYPE.MAPREDUCE_JOB)
jobCount++;
}
return jobCount;
}
public void setDMLScriptString(String dmlScriptString){
_dmlScriptString = dmlScriptString;
}
public String getDMLScriptString (){
return _dmlScriptString;
}
public void setOptConfig (String optConfig){
_optConfig = optConfig;
}
public String getOptConfig (){
return _optConfig;
}
public void setArgVals (HashMap<String, String> argVals){
_argVals = argVals;
}
public HashMap<String, String> getArgVals() {
return _argVals;
}
public static String getUUID()
{
return _uuid;
}
/* TODO MB: decide if master UUID should be used for all nodes
* if yes, this is required.
public static void setUUID(String uuid)
{
_uuid = uuid;
}
*/
} ///~ end class |
package com.voxelwind.nbt.io;
import com.voxelwind.nbt.tags.*;
import com.voxelwind.nbt.util.Varints;
import java.io.Closeable;
import java.io.DataInput;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static com.voxelwind.nbt.io.NBTEncoding.MCPE_0_16_NETWORK;
public class NBTReader implements Closeable {
private final DataInput input;
private final NBTEncoding encoding;
private boolean closed = false;
public NBTReader(DataInput input) {
this(input, NBTEncoding.NOTCHIAN);
}
public NBTReader(DataInput input, NBTEncoding encoding) {
this.input = Objects.requireNonNull(input, "input");
this.encoding = Objects.requireNonNull(encoding, "encoding");
}
public Tag<?> readTag() throws IOException {
return readTag(0);
}
private Tag<?> readTag(int depth) throws IOException {
if (closed) {
throw new IllegalStateException("Trying to read from a closed reader!");
}
int typeId = input.readByte() & 0xFF;
TagType type = TagType.fromId(typeId);
if (type == null) {
throw new IOException("Invalid encoding ID " + typeId);
}
return deserialize(type, false, depth);
}
@SuppressWarnings("unchecked")
private Tag<?> deserialize(TagType type, boolean skipName, int depth) throws IOException {
if (depth > 16) {
throw new IllegalArgumentException("NBT compound is too deeply nested");
}
String tagName = null;
if (type != TagType.END && !skipName) {
int length = encoding == MCPE_0_16_NETWORK ? input.readByte() & 0xFF : input.readShort();
byte[] tagNameBytes = new byte[length];
input.readFully(tagNameBytes);
tagName = new String(tagNameBytes, StandardCharsets.UTF_8);
}
switch (type) {
case END:
if (depth == 0) {
throw new IllegalArgumentException("Found a TAG_End in root tag!");
}
return EndTag.INSTANCE;
case BYTE:
byte b = input.readByte();
return new ByteTag(tagName, b);
case SHORT:
short sh = input.readShort();
return new ShortTag(tagName, sh);
case INT:
int in = encoding == MCPE_0_16_NETWORK ? Varints.decodeSigned(input) : input.readInt();
return new IntTag(tagName, in);
case LONG:
return new LongTag(tagName, input.readLong());
case FLOAT:
return new FloatTag(tagName, input.readFloat());
case DOUBLE:
return new DoubleTag(tagName, input.readDouble());
case BYTE_ARRAY:
int arraySz1 = encoding == MCPE_0_16_NETWORK ? Varints.decodeSigned(input) : input.readInt();
byte[] valueBytesBa = new byte[arraySz1];
input.readFully(valueBytesBa);
return new ByteArrayTag(tagName, valueBytesBa);
case STRING:
int length = encoding == MCPE_0_16_NETWORK ? input.readByte() : input.readUnsignedShort();
byte[] valueBytes = new byte[length];
input.readFully(valueBytes);
return new StringTag(tagName, new String(valueBytes, StandardCharsets.UTF_8));
case COMPOUND:
Map<String, Tag<?>> map = new HashMap<>();
Tag<?> inTag1;
while ((inTag1 = readTag(depth + 1)) != EndTag.INSTANCE) {
map.put(inTag1.getName(), inTag1);
}
return new CompoundTag(tagName, map);
case LIST:
int inId = input.readByte() & 0xFF;
TagType listType = TagType.fromId(inId);
if (listType == null) {
String append = tagName == null ? "" : "('" + tagName + "')";
throw new IllegalArgumentException("Found invalid type in TAG_List" + append + ": " + inId);
}
List<Tag<?>> list = new ArrayList<>();
int listLength = encoding == MCPE_0_16_NETWORK ? Varints.decodeSigned(input) : input.readInt();
for (int i = 0; i < listLength; i++) {
list.add(deserialize(listType, true, depth + 1));
}
// Unchecked cast is expected
return new ListTag(tagName, listType.getTagClass(), list);
case INT_ARRAY:
int arraySz2 = encoding == MCPE_0_16_NETWORK ? Varints.decodeSigned(input) : input.readInt();
int[] valueBytesInt = new int[arraySz2];
for (int i = 0; i < arraySz2; i++) {
valueBytesInt[i] = input.readInt();
}
return new IntArrayTag(tagName, valueBytesInt);
}
throw new IllegalArgumentException("Unknown type " + type);
}
@Override
public void close() throws IOException {
if (closed) return;
closed = true;
if (input instanceof Closeable) {
((Closeable) input).close();
}
}
} |
package model;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class FileModel {
private File file;
private ArrayList<String> stringArrayList = new ArrayList<>();// arraylist
protected ListProperty<String> listProperty = new SimpleListProperty<>();
ObservableList<Integer> diffList = FXCollections.observableArrayList();
private SimpleStringProperty statusString;
public FileModel()
{
statusString = new SimpleStringProperty("Ready(No file is loaded)");
}
/**
* Plain Text Path Text .
* @param filePath
* @return boolean
*/
public boolean readFile(String filePath) {
file= new File(filePath);
try {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"UTF-8")));
String tempString = "";
while(in.hasNextLine()) {
tempString = in.nextLine();
if(in.hasNextLine()) tempString +="\n";
stringArrayList.add(tempString);
}
in.close();
listProperty.set(FXCollections.observableArrayList(stringArrayList));
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
statusString.set("File Loaded Successfully");
return true;
}
/**
* String .
* @return String
*/
@Override
public String toString() {
String ret = "";
for(String s : stringArrayList)
ret += s;
return ret;
}
/**
* ArrayList Clone .
* @return file Arraylist clone
*/
public ArrayList<String> getStringArrayList() {
return (ArrayList<String>) stringArrayList.clone();
}
/**
* .
* @param args
*/
public void updateArrayList(String args) {
stringArrayList = new ArrayList<String>();
for(String s : args.split("\n"))
stringArrayList.add(s + "\n");
}
/**
* ArrayList .
* FileNotFoundException .
* @return boolean
*/
public boolean writeFile() {
try( PrintWriter out = new PrintWriter(file.getPath()) ){
String tstring ="";
for (String i : stringArrayList) {
tstring+=i;
}
out.print(tstring);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
statusString.set("File Written successfully");
return true;
}
/**
* Model .
* @return SimpleStringProperty Model
*/
public SimpleStringProperty getStatus() {
//TODO SAFE GETTER CLONE
return statusString;
}
public ListProperty<String> getListProperty(){
return listProperty;
}
/**
* DiffList .
* @return ObservableList diffrence List
*/
public ObservableList<Integer> getList(){
return diffList;
}
} |
package model;
import lombok.Getter;
import lombok.Setter;
import misc.Job;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class MainModel extends Model {
/** The jobs. */
@Getter @Setter private Map<String, Job> jobs = new HashMap<>();
/** Deserializes the jobs map, if the file exists. */
public void loadJobs() {
final String filePath = System.getProperty("user.dir") + "/Jobs.ser";
try (
final FileInputStream fis = new FileInputStream(filePath);
final ObjectInputStream ois = new ObjectInputStream(fis);
) {
final Object object = ois.readObject();
jobs = (Map<String, Job>) object;
} catch (IOException | ClassNotFoundException e) {
final Logger logger = LogManager.getLogger();
logger.error(e);
// Delete the file:
final File file = new File(filePath);
if (file.exists()) {
file.delete();
}
}
}
/** Serializes the jobs map to a file. */
public void saveJobs() {
final String filePath = System.getProperty("user.dir") + "/Jobs.ser";
if (jobs.size() == 0) {
// Delete the file:
final File file = new File(filePath);
if (file.exists()) {
file.delete();
}
return;
}
try (
final FileOutputStream fos = new FileOutputStream(filePath, false);
final ObjectOutputStream oos = new ObjectOutputStream(fos);
) {
oos.writeObject(jobs);
} catch (IOException e) {
final Logger logger = LogManager.getLogger();
logger.error(e);
}
}
} |
package org.ccnx.ccn.test.io;
import java.io.IOException;
import junit.framework.Assert;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.io.CCNInputStream;
import org.ccnx.ccn.io.CCNVersionedInputStream;
import org.ccnx.ccn.profiles.SegmentationProfile;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.test.CCNTestHelper;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
public class PipelineTest {
public static CCNTestHelper testHelper = new CCNTestHelper(PipelineTest.class);
public static ContentName testName;
public static CCNHandle readHandle;
public static CCNHandle writeHandle;
private static CCNInputStream istream;
private static CCNVersionedInputStream vistream;
private static long segments = 20;
private static long bytesWritten;
private static byte[] firstDigest = null;
//need a stream to test with
//need a responder with objects to pipeline
@BeforeClass
public static void setUpBeforeClass() throws Exception {
readHandle = CCNHandle.open();
writeHandle = CCNHandle.open();
ContentName namespace = testHelper.getTestNamespace("pipelineTest");
testName = ContentName.fromNative(namespace, "PipelineSegments");
testName = VersioningProfile.addVersion(testName);
try {
putSegments();
} catch (Exception e) {
System.err.println("failed to put objects for pipeline test: "+e.getMessage());
Assert.fail();
}
}
@After
public void cleanup() {
readHandle.close();
writeHandle.close();
}
//put segments
private static void putSegments() throws Exception{
ContentName segment;
ContentObject object;
long lastMarkerTest = 1;
bytesWritten = 0;
byte[] toWrite;
for (int i = 0; i < segments; i++) {
if (i>0)
lastMarkerTest = segments-1;
segment = SegmentationProfile.segmentName(testName, i);
toWrite = ("this is segment "+i+" of "+segments).getBytes();
bytesWritten = bytesWritten + toWrite.length;
object = ContentObject.buildContentObject(segment, toWrite, null, null, SegmentationProfile.getSegmentNumberNameComponent(lastMarkerTest));
if (i == 0) {
firstDigest = object.digest();
}
writeHandle.put(object);
}
System.out.println("wrote "+bytesWritten+" bytes");
}
//need to ask for objects... start in order
@Test
public void testGetAllSegmentsFromPipeline() {
long received = 0;
byte[] bytes = new byte[1024];
try {
istream = new CCNInputStream(testName, readHandle);
} catch (IOException e1) {
System.err.println("failed to open stream for pipeline test: "+e1.getMessage());
Assert.fail();
}
while (!istream.eof()) {
try {
received += istream.read(bytes);
} catch (IOException e) {
System.err.println("failed to read segments: "+e.getMessage());
Assert.fail();
}
}
System.out.println("read "+received+" from stream");
Assert.assertTrue(received == bytesWritten);
}
//skip
@Test
public void testSkipWithPipeline() {
long received = 0;
byte[] bytes = new byte[100];
boolean skipDone = false;
try {
istream = new CCNInputStream(testName, readHandle);
} catch (IOException e1) {
System.err.println("Failed to get new stream: "+e1.getMessage());
Assert.fail();
}
while (!istream.eof()) {
try {
System.out.println("Read so far: "+received);
if (received > 0 && received < 250 && !skipDone) {
//want to skip some segments
istream.skip(100);
skipDone = true;
}
received += istream.read(bytes);
} catch (IOException e) {
System.err.println("failed to read segments: "+e.getMessage());
Assert.fail();
}
}
System.out.println("read "+received+" from stream");
Assert.assertTrue(received == bytesWritten - 100);
}
//seek
@Test
public void testSeekWithPipeline() {
long received = 0;
byte[] bytes = new byte[100];
boolean seekDone = false;
long skipped = 0;
try {
istream = new CCNInputStream(testName, readHandle);
} catch (IOException e1) {
System.err.println("Failed to seek stream to byte 0: "+e1.getMessage());
Assert.fail();
}
while (!istream.eof()) {
try {
System.out.println("Read so far: "+received);
if (received > 0 && received < 150 && !seekDone) {
//want to skip some segments
istream.seek(200);
seekDone = true;
skipped = 200 - received;
}
received += istream.read(bytes);
} catch (IOException e) {
System.err.println("failed to read segments: "+e.getMessage());
Assert.fail();
}
}
System.out.println("read "+received+" from stream");
Assert.assertTrue(received == bytesWritten - skipped);
}
//restart
@Test
public void testResetWithPipeline() {
long received = 0;
byte[] bytes = new byte[100];
boolean resetDone = false;
long resetBytes = 0;
try {
istream = new CCNInputStream(testName, readHandle);
istream.mark(0);
} catch (IOException e1) {
System.err.println("Failed to get new stream: "+e1.getMessage());
Assert.fail();
}
while (!istream.eof()) {
try {
System.out.println("Read so far: "+received);
if (received > 0 && received < 250 && !resetDone) {
//want to skip some segments
istream.reset();
resetDone = true;
resetBytes = received;
}
received += istream.read(bytes);
} catch (IOException e) {
System.err.println("failed to read segments: "+e.getMessage());
Assert.fail();
}
}
System.out.println("read "+received+" from stream");
Assert.assertTrue(received == bytesWritten + resetBytes);
}
//test interface with versioning
@Test
public void testVersionedNameWithPipeline() {
long received = 0;
byte[] bytes = new byte[1024];
try {
vistream = new CCNVersionedInputStream(VersioningProfile.cutLastVersion(testName), readHandle);
} catch (IOException e1) {
System.err.println("failed to open stream for pipeline test: "+e1.getMessage());
Assert.fail();
}
while (!vistream.eof()) {
try {
received += vistream.read(bytes);
} catch (IOException e) {
System.err.println("failed to read segments: "+e.getMessage());
Assert.fail();
}
}
System.out.println("read "+received+" from stream");
Assert.assertTrue(received == bytesWritten);
}
@Test
public void testGetFirstDigest() {
long received = 0;
byte[] bytes = new byte[1024];
try {
istream = new CCNInputStream(testName, readHandle);
} catch (IOException e1) {
System.err.println("failed to open stream for pipeline test: "+e1.getMessage());
Assert.fail();
}
try {
Assert.assertTrue(DataUtils.arrayEquals(firstDigest, istream.getFirstDigest()));
} catch (IOException e3) {
System.err.println("failed to get first digest for pipeline test:");
Assert.fail();
}
try {
istream.close();
} catch (IOException e2) {
System.err.println("failed to close stream for pipeline test: "+e2.getMessage());
Assert.fail();
}
System.out.println("start first segment digest "+firstDigest);
try {
istream = new CCNInputStream(testName, readHandle);
} catch (IOException e1) {
System.err.println("failed to open stream for pipeline test: "+e1.getMessage());
Assert.fail();
}
while (!istream.eof()) {
try {
received += istream.read(bytes);
} catch (IOException e) {
System.err.println("failed to read segments: "+e.getMessage());
Assert.fail();
}
}
Assert.assertTrue(received == bytesWritten);
try {
Assert.assertTrue(DataUtils.arrayEquals(firstDigest, istream.getFirstDigest()));
} catch (IOException e) {
System.err.println("failed to get first digest after reading in pipeline test:");
Assert.fail();
}
System.out.println("end first segment digest "+firstDigest);
}
} |
package me.eddiep;
import net.minecraft.server.v1_8_R3.*;
import org.bukkit.Material;
public class ChunkEdit {
public World world;
public ChunkEdit(World w) {
this.world = w;
}
public void setBlock(int x, int y, int z, Material type, byte data) {
int columnX = x >> 4;
int columnZ = z >> 4;
int chunkY = y >> 4;
int blockX = x % 16;
int blockY = y % 16;
int blockZ = z % 16;
if (blockX < 0)
blockX += 16;
if (blockX > 15) {
blockX = blockX % 16;
columnX++;
}
if (blockY < 0)
blockY += 16;
if (blockY > 15) {
blockY = blockY % 16;
chunkY++;
}
if (blockZ < 0)
blockZ += 16;
if (blockZ > 15) {
blockZ = blockZ % 16;
columnZ++;
}
Chunk c = this.world.getChunkAt(columnX, columnZ);
ChunkSection[] sections = c.getSections();
ChunkSection section = sections[chunkY];
if (section == null)
section = new ChunkSection(chunkY, true);
NibbleArray blockLight;
NibbleArray skyLight;
try {
blockLight = section.getEmittedLightArray();
} catch (Exception e) {
blockLight = new NibbleArray();
}
try {
skyLight = section.getSkyLightArray();
} catch (Exception e) {
skyLight = new NibbleArray();
}
IBlockData d = Block.getByCombinedId(type.getId() + (data << 12));
BlockPosition pos = new BlockPosition(x, y, z);
TileEntity tileEntity = this.world.getTileEntity(pos);
if (tileEntity != null)
c.a(new BlockPosition(x, y, z), d);
else
section.setType(blockX, blockY, blockZ, d);
blockLight.a(blockX, blockY, blockZ, getLight(type));
skyLight.a(blockX, blockY, blockZ, getSkyLight(x, y, z));
section.a(blockLight);
section.b(skyLight);
sections[chunkY] = section;
c.a(sections);
}
public void setBlock(int x, int y, int z, Material type) {
setBlock(x, y, z, type, (byte) 0);
}
private int getSkyLight(int x, int y, int z) {
if (y >= 256)
return 15;
else if (y < 0)
return 0;
org.bukkit.block.Block highest = this.world.getWorld().getHighestBlockAt(x, z);
while (highest.getY() > 0 && highest.getType().isTransparent())
highest = highest.getRelative(0, -1, 0);
return y <= highest.getY() ? 0 : getDayLight();
}
private int getDayLight() {//TODO: Get light more accurately based on time of day and weather
long time = this.world.getTime() % 24000;
//sunlight 15
//sunlight during rain/snow 12
//sunlight during thunderstorm 10
//moonlight 4
if (time > 12000)
return 4;
else//if (time > 0)
return this.world.getWorld().isThundering() ? 10 : 15;
}
private int getLight(Material type) {
switch (type) {
case BEACON: case ENDER_PORTAL: case FIRE: case GLOWSTONE: case JACK_O_LANTERN: case LAVA: case STATIONARY_LAVA: case REDSTONE_LAMP_ON: case SEA_LANTERN:
return 15;
case TORCH:// case END_ROD:
return 14;
case BURNING_FURNACE:
return 13;
case PORTAL:
return 11;
case GLOWING_REDSTONE_ORE:
return 9;
case ENDER_CHEST: case REDSTONE_TORCH_ON:
return 7;
case BREWING_STAND: case BROWN_MUSHROOM: case DRAGON_EGG: case ENDER_PORTAL_FRAME:
return 1;
default:
return 0;
}
}
} |
package org.freeflow.core;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.freeflow.debug.TouchDebugUtils;
import org.freeflow.layouts.AbstractLayout;
import org.freeflow.layouts.animations.DefaultLayoutAnimator;
import org.freeflow.layouts.animations.LayoutAnimator;
import org.freeflow.utils.ViewUtils;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.graphics.Rect;
import android.support.v4.util.SimpleArrayMap;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Pair;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.HapticFeedbackConstants;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Checkable;
public class Container extends AbsLayoutContainer {
private static final String TAG = "Container";
// ViewPool class
protected ViewPool viewpool;
// Not used yet, but we'll probably need to
// prevent layout in <code>layout()</code> method
private boolean preventLayout = false;
protected BaseSectionedAdapter itemAdapter;
protected AbstractLayout layout;
public int viewPortX = 0;
public int viewPortY = 0;
protected int scrollableWidth;
protected int scrollableHeight;
protected View headerView = null;
private VelocityTracker mVelocityTracker = null;
private float deltaX = -1f;
private float deltaY = -1f;
private int maxFlingVelocity;
private int touchSlop;
private Runnable mTouchModeReset;
private Runnable mPerformClick;
private Runnable mPendingCheckForTap;
private Runnable mPendingCheckForLongPress;
// This flag controls whether onTap/onLongPress/onTouch trigger
// the ActionMode
//private boolean mDataChanged = false;
private ContextMenuInfo mContextMenuInfo = null;
private SimpleArrayMap<Position2D, Boolean> mCheckStates = null;
ActionMode mChoiceActionMode;
MultiChoiceModeWrapper mMultiChoiceModeCallback;
/**
* Normal list that does not indicate choices
*/
public static final int CHOICE_MODE_NONE = 0;
/**
* The list allows up to one choice
*/
public static final int CHOICE_MODE_SINGLE = 1;
/**
* The list allows multiple choices
*/
public static final int CHOICE_MODE_MULTIPLE = 2;
/**
* The list allows multiple choices in a modal selection mode
*/
public static final int CHOICE_MODE_MULTIPLE_MODAL = 3;
int mChoiceMode = CHOICE_MODE_NONE;
private LayoutParams params = new LayoutParams(0, 0);
private LayoutAnimator layoutAnimator = new DefaultLayoutAnimator();
private ItemProxy beginTouchAt;
private boolean markLayoutDirty = false;
private boolean markAdapterDirty = false;
private AbstractLayout oldLayout;
public Container(Context context) {
super(context);
}
public Container(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Container(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init(Context context) {
// usedViews = new HashMap<Object, ItemProxy>();
// usedHeaderViews = new HashMap<Object, ItemProxy>();
viewpool = new ViewPool();
frames = new HashMap<Object, ItemProxy>();
maxFlingVelocity = ViewConfiguration.get(context)
.getScaledMaximumFlingVelocity();
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int beforeWidth = getWidth();
int beforeHeight = getHeight();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int afterWidth = MeasureSpec.getSize(widthMeasureSpec);
int afterHeight = MeasureSpec.getSize(heightMeasureSpec);
if (beforeWidth != afterWidth || beforeHeight != afterHeight
|| markLayoutDirty) {
computeLayout(afterWidth, afterHeight);
}
}
public void computeLayout(int w, int h) {
Log.d(TAG, "=== Computing layout ==== ");
if (layout != null) {
layout.setDimensions(w, h);
if (this.itemAdapter != null)
layout.setItems(itemAdapter);
computeViewPort(layout);
HashMap<? extends Object, ItemProxy> oldFrames = frames;
if (markLayoutDirty) {
markLayoutDirty = false;
}
// Create a copy of the incoming values because the source
// Layout
// may change the map inside its own class
frames = new HashMap<Object, ItemProxy>(layout.getItemProxies(
viewPortX, viewPortY));
dispatchLayoutComputed();
animateChanges(getViewChanges(oldFrames, frames));
// for (ItemProxy frameDesc : changeSet.added) {
// addAndMeasureViewIfNeeded(frameDesc);
}
}
private void addAndMeasureViewIfNeeded(ItemProxy frameDesc) {
View view;
if (frameDesc.view == null) {
View convertView = viewpool.getViewFromPool(itemAdapter
.getViewType(frameDesc));
if (frameDesc.isHeader) {
view = itemAdapter.getHeaderViewForSection(
frameDesc.itemSection, convertView, this);
} else {
view = itemAdapter.getViewForSection(frameDesc.itemSection,
frameDesc.itemIndex, convertView, this);
}
if (view instanceof Container)
throw new IllegalStateException(
"A container cannot be a direct child view to a container");
frameDesc.view = view;
prepareViewForAddition(view, frameDesc);
addView(view, getChildCount(), params);
}
view = frameDesc.view;
int widthSpec = MeasureSpec.makeMeasureSpec(frameDesc.frame.width(),
MeasureSpec.EXACTLY);
int heightSpec = MeasureSpec.makeMeasureSpec(frameDesc.frame.height(),
MeasureSpec.EXACTLY);
view.measure(widthSpec, heightSpec);
if (view instanceof StateListener)
((StateListener) view).ReportCurrentState(frameDesc.state);
}
private void prepareViewForAddition(View view, ItemProxy proxy) {
if(view instanceof Checkable){
((Checkable)view).setChecked(isChecked(proxy.itemSection, proxy.itemIndex));
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d(TAG, "== onLayout ==");
//mDataChanged = false;
dispatchLayoutComplete();
}
private void doLayout(ItemProxy proxy) {
View view = proxy.view;
Rect frame = proxy.frame;
view.layout(frame.left - viewPortX, frame.top - viewPortY, frame.left
+ frame.width() - viewPortX, frame.top + frame.height()
- viewPortY);
if (view instanceof StateListener)
((StateListener) view).ReportCurrentState(proxy.state);
}
public void setLayout(AbstractLayout lc) {
if (lc == layout) {
return;
}
oldLayout = layout;
layout = lc;
dispatchLayoutChanging(oldLayout, lc);
dispatchDataChanged();
markLayoutDirty = true;
Log.d(TAG, "=== setting layout ===");
requestLayout();
}
public AbstractLayout getLayout() {
return layout;
}
private void computeViewPort(AbstractLayout newLayout) {
if (layout == null || frames == null || frames.size() == 0) {
viewPortX = 0;
viewPortY = 0;
return;
}
Object data = null;
int lowestSection = 99999;
int lowestPosition = 99999;
for (ItemProxy fd : frames.values()) {
if (fd.itemSection < lowestSection
|| (fd.itemSection == lowestSection && fd.itemIndex < lowestPosition)) {
data = fd.data;
lowestSection = fd.itemSection;
lowestPosition = fd.itemIndex;
}
}
ItemProxy proxy = newLayout.getItemProxyForItem(data);
if (proxy == null) {
viewPortX = 0;
viewPortY = 0;
return;
}
Rect vpFrame = proxy.frame;
viewPortX = vpFrame.left;
viewPortY = vpFrame.top;
scrollableWidth = layout.getContentWidth() - getWidth();
scrollableHeight = layout.getContentHeight() - getHeight();
if (viewPortX > scrollableWidth)
viewPortX = scrollableWidth;
if (viewPortY > scrollableHeight)
viewPortY = scrollableHeight;
}
/**
* Returns the actual frame for a view as its on stage. The ItemProxy's
* frame object always represents the position it wants to be in but actual
* frame may be different based on animation etc.
*
* @param proxy
* The proxy to get the <code>Frame</code> for
* @return The Frame for the proxy or null if that view doesn't exist
*/
public Rect getActualFrame(final ItemProxy proxy) {
View v = proxy.view;
if (v == null) {
return null;
}
Rect of = new Rect();
of.left = (int) (v.getLeft() + v.getTranslationX());
of.top = (int) (v.getTop() + v.getTranslationY());
of.right = of.left + v.getWidth();
of.bottom = of.bottom + v.getHeight();
return of;
}
/**
* TODO:::: This should be renamed to layoutInvalidated, since the layout
* isn't changed
*/
public void layoutChanged() {
Log.d(TAG, "== layoutChanged");
markLayoutDirty = true;
dispatchDataChanged();
requestLayout();
}
protected boolean isAnimatingChanges = false;
private void animateChanges(LayoutChangeSet changeSet) {
if (changeSet.added.size() == 0 && changeSet.removed.size() == 0
&& changeSet.moved.size() == 0) {
return;
}
if (isAnimatingChanges) {
layoutAnimator.cancel();
}
isAnimatingChanges = true;
for (ItemProxy proxy : changeSet.getAdded()) {
addAndMeasureViewIfNeeded(proxy);
doLayout(proxy);
}
Log.d(TAG, "== animating changes: " + changeSet.toString());
dispatchAnimationsStarted();
layoutAnimator.animateChanges(changeSet, this);
// for (Pair<ItemProxy, Rect> item : changeSet.getMoved()) {
// ItemProxy proxy = ItemProxy.clone(item.first);
// View v = proxy.view;
// proxy.view.layout(proxy.frame.left, proxy.frame.top,
// proxy.frame.right, proxy.frame.bottom);
// for (ItemProxy proxy : changeSet.getRemoved()) {
// View v = proxy.view;
// removeView(v);
// returnItemToPoolIfNeeded(proxy);
// requestLayout();
}
public void onLayoutChangeAnimationsCompleted(LayoutAnimator anim) {
// preventLayout = false;
isAnimatingChanges = false;
Log.d(TAG, "=== layout changes complete");
for (ItemProxy proxy : anim.getChangeSet().getRemoved()) {
View v = proxy.view;
removeView(v);
returnItemToPoolIfNeeded(proxy);
}
dispatchAnimationsComplete();
// changeSet = null;
}
public LayoutChangeSet getViewChanges(
HashMap<? extends Object, ItemProxy> oldFrames,
HashMap<? extends Object, ItemProxy> newFrames) {
return getViewChanges(oldFrames, newFrames, false);
}
public LayoutChangeSet getViewChanges(
HashMap<? extends Object, ItemProxy> oldFrames,
HashMap<? extends Object, ItemProxy> newFrames,
boolean moveEvenIfSame) {
// cleanupViews();
LayoutChangeSet change = new LayoutChangeSet();
if (oldFrames == null) {
markAdapterDirty = false;
Log.d(TAG, "old frames is null");
for (ItemProxy proxy : newFrames.values()) {
change.addToAdded(proxy);
}
return change;
}
if (markAdapterDirty) {
Log.d(TAG, "old frames is null");
markAdapterDirty = false;
for (ItemProxy proxy : newFrames.values()) {
change.addToAdded(proxy);
}
for (ItemProxy proxy : oldFrames.values()) {
change.addToDeleted(proxy);
}
return change;
}
Iterator<?> it = newFrames.entrySet().iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
ItemProxy proxy = (ItemProxy) m.getValue();
if (oldFrames.get(m.getKey()) != null) {
ItemProxy old = oldFrames.remove(m.getKey());
proxy.view = old.view;
// if (moveEvenIfSame || !old.compareRect(((ItemProxy)
// m.getValue()).frame)) {
if (moveEvenIfSame
|| !old.frame.equals(((ItemProxy) m.getValue()).frame)) {
change.addToMoved(proxy, getActualFrame(proxy));
}
} else {
change.addToAdded(proxy);
}
}
for (ItemProxy proxy : oldFrames.values()) {
change.addToDeleted(proxy);
}
frames = newFrames;
return change;
}
@Override
public void requestLayout() {
if (!preventLayout) {
Log.d(TAG, "== requesting layout ===");
super.requestLayout();
}
}
/**
* Sets the adapter for the this CollectionView.All view pools will be
* cleared at this point and all views on the stage will be cleared
*
* @param adapter
* The {@link BaseSectionedAdapter} that will populate this
* Collection
*/
public void setAdapter(BaseSectionedAdapter adapter) {
Log.d(TAG, "setting adapter");
markLayoutDirty = true;
markAdapterDirty = true;
this.itemAdapter = adapter;
if (adapter != null)
viewpool.initializeViewPool(adapter.getViewTypes());
requestLayout();
}
public AbstractLayout getLayoutController() {
return layout;
}
/**
* Indicates that we are not in the middle of a touch gesture
*/
public static final int TOUCH_MODE_REST = -1;
/**
* Indicates we just received the touch event and we are waiting to see if
* the it is a tap or a scroll gesture.
*/
public static final int TOUCH_MODE_DOWN = 0;
/**
* Indicates the touch has been recognized as a tap and we are now waiting
* to see if the touch is a longpress
*/
public static final int TOUCH_MODE_TAP = 1;
/**
* Indicates we have waited for everything we can wait for, but the user's
* finger is still down
*/
public static final int TOUCH_MODE_DONE_WAITING = 2;
/**
* Indicates the touch gesture is a scroll
*/
public static final int TOUCH_MODE_SCROLL = 3;
/**
* Indicates the view is in the process of being flung
*/
public static final int TOUCH_MODE_FLING = 4;
/**
* Indicates the touch gesture is an overscroll - a scroll beyond the
* beginning or end.
*/
public static final int TOUCH_MODE_OVERSCROLL = 5;
/**
* Indicates the view is being flung outside of normal content bounds and
* will spring back.
*/
public static final int TOUCH_MODE_OVERFLING = 6;
/**
* One of TOUCH_MODE_REST, TOUCH_MODE_DOWN, TOUCH_MODE_TAP,
* TOUCH_MODE_SCROLL, or TOUCH_MODE_DONE_WAITING
*/
int mTouchMode = TOUCH_MODE_REST;
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
if (layout == null)
return false;
boolean canScroll = false;
if (layout.horizontalDragEnabled()
&& this.layout.getContentWidth() > getWidth()) {
canScroll = true;
}
if (layout.verticalDragEnabled()
&& layout.getContentHeight() > getHeight()) {
canScroll = true;
}
if (mVelocityTracker == null && canScroll) {
mVelocityTracker = VelocityTracker.obtain();
}
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(event);
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
beginTouchAt = ViewUtils.getItemAt(frames,
(int) (viewPortX + event.getX()),
(int) (viewPortY + event.getY()));
if (canScroll) {
deltaX = event.getX();
deltaY = event.getY();
}
mTouchMode = TOUCH_MODE_DOWN;
if (mPendingCheckForTap != null) {
removeCallbacks(mPendingCheckForTap);
mPendingCheckForLongPress = null;
}
if (beginTouchAt != null) {
mPendingCheckForTap = new CheckForTap();
}
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
return true;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (canScroll) {
float xDiff = event.getX() - deltaX;
float yDiff = event.getY() - deltaY;
double distance = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
if (mTouchMode == TOUCH_MODE_DOWN && distance > touchSlop) {
mTouchMode = TOUCH_MODE_SCROLL;
if (mPendingCheckForTap != null) {
Log.d(TAG, "killing check for TAP");
removeCallbacks(mPendingCheckForTap);
mPendingCheckForTap = null;
}
}
if (mTouchMode == TOUCH_MODE_SCROLL) {
moveScreen(event.getX() - deltaX, event.getY() - deltaY);
deltaX = event.getX();
deltaY = event.getY();
}
}
return true;
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
mTouchMode = TOUCH_MODE_REST;
if (canScroll) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
// requestLayout();
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Log.d(TAG, "Touch => " + TouchDebugUtils.getMotionEventString(event.getAction())+" , "+TouchDebugUtils.getTouchModeString(mTouchMode));
if (mTouchMode == TOUCH_MODE_SCROLL) {
Log.d(TAG, "Scroll....");
mVelocityTracker.computeCurrentVelocity(maxFlingVelocity);
// frames = layoutController.getFrameDescriptors(viewPortX,
// viewPortY);
if (Math.abs(mVelocityTracker.getXVelocity()) > 100) {
final float velocityX = mVelocityTracker.getXVelocity();
final float velocityY = mVelocityTracker.getYVelocity();
ValueAnimator animator = ValueAnimator.ofFloat(1, 0);
animator.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int translateX = (int) ((1 - animation
.getAnimatedFraction()) * velocityX / 350);
int translateY = (int) ((1 - animation
.getAnimatedFraction()) * velocityY / 350);
moveScreen(translateX, translateY);
}
});
animator.setDuration(500);
animator.start();
}
mTouchMode = TOUCH_MODE_REST;
Log.d(TAG, "Setting to rest");
}
else if(mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_DONE_WAITING){
//if(mChoiceActionMode != null){
// do nothing
//return;
Log.d(TAG, "Select");
if (mTouchModeReset != null) {
removeCallbacks(mTouchModeReset);
}
if (beginTouchAt != null && beginTouchAt.view != null) {
beginTouchAt.view.setPressed(true);
mTouchModeReset = new Runnable() {
@Override
public void run() {
mTouchModeReset = null;
mTouchMode = TOUCH_MODE_REST;
if (beginTouchAt != null
&& beginTouchAt.view != null) {
Log.d(TAG, "setting pressed back to false in reset");
beginTouchAt.view.setPressed(false);
}
if (mOnItemSelectedListener != null) {
mOnItemSelectedListener.onItemSelected(
Container.this, selectedItemProxy);
}
// setPressed(false);
//if (!mDataChanged) {
mPerformClick = new PerformClick();
mPerformClick.run();
}
};
selectedItemProxy = beginTouchAt;
postDelayed(mTouchModeReset,
ViewConfiguration.getPressedStateDuration());
mTouchMode = TOUCH_MODE_TAP;
}
else {
mTouchMode = TOUCH_MODE_REST;
}
}
return true;
}
return false;
}
public ItemProxy getSelectedItemProxy() {
return selectedItemProxy;
}
private void moveScreen(float movementX, float movementY) {
if (layout.horizontalDragEnabled()) {
viewPortX = (int) (viewPortX - movementX);
} else {
movementX = 0;
}
if (layout.verticalDragEnabled()) {
viewPortY = (int) (viewPortY - movementY);
} else {
movementY = 0;
}
scrollableWidth = layout.getContentWidth() - getWidth();
scrollableHeight = layout.getContentHeight() - getHeight();
if (viewPortX < 0)
viewPortX = 0;
else if (viewPortX > scrollableWidth)
viewPortX = scrollableWidth;
if (viewPortY < 0)
viewPortY = 0;
else if (viewPortY > scrollableHeight)
viewPortY = scrollableHeight;
Log.d("blah", "vpx = " + viewPortX + ", vpy = " + viewPortY);
HashMap<? extends Object, ItemProxy> oldFrames = frames;
frames = new HashMap<Object, ItemProxy>(layout.getItemProxies(
viewPortX, viewPortY));
LayoutChangeSet changeSet = getViewChanges(oldFrames, frames, true);
Log.d("blah", "added = " + changeSet.added.size() + ", moved = "
+ changeSet.moved.size());
for (ItemProxy proxy : changeSet.added) {
addAndMeasureViewIfNeeded(proxy);
doLayout(proxy);
}
for (Pair<ItemProxy, Rect> proxyPair : changeSet.moved) {
doLayout(proxyPair.first);
}
for (ItemProxy proxy : changeSet.removed) {
proxy.view.setAlpha(0.3f);
removeViewInLayout(proxy.view);
returnItemToPoolIfNeeded(proxy);
}
}
protected void returnItemToPoolIfNeeded(ItemProxy proxy) {
View v = proxy.view;
v.setTranslationX(0);
v.setTranslationY(0);
v.setRotation(0);
v.setScaleX(1f);
v.setScaleY(1f);
v.setAlpha(1);
viewpool.returnViewToPool(v);
}
public BaseSectionedAdapter getAdapter() {
return itemAdapter;
}
public void setLayoutAnimator(LayoutAnimator anim) {
layoutAnimator = anim;
}
public LayoutAnimator getLayoutAnimator() {
return layoutAnimator;
}
public HashMap<? extends Object, ItemProxy> getFrames() {
return frames;
}
public void clearFrames() {
removeAllViews();
frames = null;
}
@Override
public boolean shouldDelayChildPressedState() {
return true;
}
public int getCheckedItemCount() {
return mCheckStates.size();
}
public void clearChoices() {
mCheckStates.clear();
}
public void setChoiceMode(int choiceMode) {
mChoiceMode = choiceMode;
if (mChoiceActionMode != null) {
mChoiceActionMode.finish();
mChoiceActionMode = null;
}
if (mChoiceMode != CHOICE_MODE_NONE) {
if (mCheckStates == null) {
Log.d(TAG, "Creating mCheckStates");
mCheckStates = new SimpleArrayMap<Container.Position2D, Boolean>();
}
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
clearChoices();
setLongClickable(true);
}
}
}
boolean isLongClickable = false;
@Override
public void setLongClickable(boolean b) {
isLongClickable = b;
}
@Override
public boolean isLongClickable() {
return isLongClickable;
}
public void setMultiChoiceModeListener(MultiChoiceModeListener listener) {
if (mMultiChoiceModeCallback == null) {
mMultiChoiceModeCallback = new MultiChoiceModeWrapper();
}
mMultiChoiceModeCallback.setWrapped(listener);
}
final class CheckForTap implements Runnable {
@Override
public void run() {
if (mTouchMode == TOUCH_MODE_DOWN) {
mTouchMode = TOUCH_MODE_TAP;
if (beginTouchAt != null && beginTouchAt.view != null) {
beginTouchAt.view.setPressed(true);
// setPressed(true);
}
refreshDrawableState();
final int longPressTimeout = ViewConfiguration
.getLongPressTimeout();
final boolean longClickable = isLongClickable();
if (longClickable) {
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
postDelayed(mPendingCheckForLongPress, longPressTimeout);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
private class CheckForLongPress implements Runnable {
@Override
public void run() {
if (beginTouchAt == null) {
// Assuming child that was being long pressed
// is no longer valid
return;
}
mCheckStates.clear();
final View child = beginTouchAt.view;
if (child != null) {
boolean handled = false;
//if (!mDataChanged) {
handled = performLongPress();
if (handled) {
mTouchMode = TOUCH_MODE_REST;
// setPressed(false);
child.setPressed(false);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
boolean performLongPress() {
Log.d(TAG, "performLongPress");
// CHOICE_MODE_MULTIPLE_MODAL takes over long press.
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
Log.d(TAG, "mChoiceActionMode => " + mChoiceActionMode);
if (mChoiceActionMode == null
&& (mChoiceActionMode = startActionMode(mMultiChoiceModeCallback)) != null) {
setItemChecked(beginTouchAt.itemSection,
beginTouchAt.itemIndex, true);
updateOnScreenCheckedViews();
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return true;
}
boolean handled = false;
final long longPressId = itemAdapter.getItemId(
beginTouchAt.itemSection, beginTouchAt.itemSection);
if (mOnItemLongClickListener != null) {
handled = mOnItemLongClickListener.onItemLongClick(this,
beginTouchAt.view, beginTouchAt.itemSection,
beginTouchAt.itemIndex, longPressId);
}
if (!handled) {
mContextMenuInfo = createContextMenuInfo(beginTouchAt.view,
beginTouchAt.itemSection, beginTouchAt.itemIndex,
longPressId);
handled = super.showContextMenuForChild(this);
}
if (handled) {
updateOnScreenCheckedViews();
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return handled;
}
ContextMenuInfo createContextMenuInfo(View view, int sectionIndex,
int positionInSection, long id) {
return new AbsLayoutContainerContextMenuInfo(view, sectionIndex,
positionInSection, id);
}
class MultiChoiceModeWrapper implements MultiChoiceModeListener {
private MultiChoiceModeListener mWrapped;
public void setWrapped(MultiChoiceModeListener wrapped) {
mWrapped = wrapped;
}
public boolean hasWrappedCallback() {
return mWrapped != null;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
if (mWrapped.onCreateActionMode(mode, menu)) {
// Initialize checked graphic state?
setLongClickable(false);
return true;
}
return false;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return mWrapped.onPrepareActionMode(mode, menu);
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return mWrapped.onActionItemClicked(mode, item);
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mWrapped.onDestroyActionMode(mode);
mChoiceActionMode = null;
// Ending selection mode means deselecting everything.
clearChoices();
// rememberSyncState();
requestLayout();
setLongClickable(true);
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int section,
int position, long id, boolean checked) {
mWrapped.onItemCheckedStateChanged(mode, section, position, id,
checked);
// If there are no items selected we no longer need the selection
// mode.
if (getCheckedItemCount() == 0) {
mode.finish();
}
}
}
public interface MultiChoiceModeListener extends ActionMode.Callback {
/**
* Called when an item is checked or unchecked during selection mode.
*
* @param mode
* The {@link ActionMode} providing the selection mode
* @param position
* Adapter position of the item that was checked or unchecked
* @param id
* Adapter ID of the item that was checked or unchecked
* @param checked
* <code>true</code> if the item is now checked,
* <code>false</code> if the item is now unchecked.
*/
public void onItemCheckedStateChanged(ActionMode mode, int section,
int position, long id, boolean checked);
}
public void setItemChecked(int sectionIndex, int positionInSection,
boolean value) {
if (mChoiceMode == CHOICE_MODE_NONE) {
return;
}
// Start selection mode if needed. We don't need to if we're unchecking
// something.
if (value && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL
&& mChoiceActionMode == null) {
if (mMultiChoiceModeCallback == null
|| !mMultiChoiceModeCallback.hasWrappedCallback()) {
throw new IllegalStateException(
"Container: attempted to start selection mode "
+ "for CHOICE_MODE_MULTIPLE_MODAL but no choice mode callback was "
+ "supplied. Call setMultiChoiceModeListener to set a callback.");
}
mChoiceActionMode = startActionMode(mMultiChoiceModeCallback);
}
if (mChoiceMode == CHOICE_MODE_MULTIPLE
|| mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
Log.d(TAG, "Setting checked: "+sectionIndex+"/"+positionInSection+": "+value);
setChecked(sectionIndex, positionInSection, value);
if (mChoiceActionMode != null) {
final long id = itemAdapter.getItemId(sectionIndex,
positionInSection);
mMultiChoiceModeCallback.onItemCheckedStateChanged(
mChoiceActionMode, sectionIndex, positionInSection, id,
value);
}
} else {
setChecked(sectionIndex, positionInSection, value);
}
// if (!mInLayout && !mBlockLayoutRequests) {
//mDataChanged = true;
// rememberSyncState();
requestLayout();
}
@Override
public boolean performClick() {
Log.d(TAG, "perform click!");
return super.performClick();
}
@Override
public boolean performLongClick() {
Log.d(TAG, "perform long click!");
return super.performLongClick();
}
class Position2D {
public int section;
public int positionInSection;
public Position2D(int section, int position) {
this.section = section;
this.positionInSection = position;
}
@Override
public boolean equals(Object o) {
Log.d(TAG, "checking: "+o);
if (o.getClass() != Position2D.class) {
return false;
}
Position2D p = (Position2D) o;
return ((p.section == section) && (p.positionInSection == positionInSection));
}
@Override
public String toString(){
return "Section: "+section+" index: "+positionInSection;
}
}
@Override
public boolean performItemClick(View view, int section, int position, long id) {
Log.d(TAG, "----> perform item click!");
boolean handled = false;
boolean dispatchItemClick = true;
if (mChoiceMode != CHOICE_MODE_NONE) {
handled = true;
boolean checkedStateChanged = false;
if (mChoiceMode == CHOICE_MODE_MULTIPLE
|| (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode != null)) {
boolean checked = isChecked(section, position);
checked = !checked;
Log.d(TAG, "Setting checked: "+section+"/"+position+": "+checked);
setChecked(section, position, checked);
if (mChoiceActionMode != null) {
mMultiChoiceModeCallback.onItemCheckedStateChanged(
mChoiceActionMode, section, position, id, checked);
dispatchItemClick = false;
}
checkedStateChanged = true;
} else if (mChoiceMode == CHOICE_MODE_SINGLE) {
boolean checked = !isChecked(section, position);
if (checked) {
setChecked(section, position, checked);
}
checkedStateChanged = true;
}
if (checkedStateChanged) {
updateOnScreenCheckedViews();
}
}
if (dispatchItemClick) {
handled |= super.performItemClick(view, section, position, id);
}
return handled;
}
private class PerformClick implements Runnable {
int mClickMotionPosition;
@Override
public void run() {
//if (mDataChanged) return;
final BaseSectionedAdapter adapter = itemAdapter;
final int motionPosition = mClickMotionPosition;
View view = beginTouchAt.view;
// if (adapter != null && mItemCount > 0 &&
// motionPosition != INVALID_POSITION &&
// motionPosition < adapter.getCount() && sameWindow()) {
// final View view = getChildAt(motionPosition - mFirstPosition);
// // If there is no view, something bad happened (the view scrolled off the
// // screen, etc.) and we should cancel the click
if (view != null) {
performItemClick(view, beginTouchAt.itemSection, beginTouchAt.itemIndex, itemAdapter.getItemId(beginTouchAt.itemSection, beginTouchAt.itemIndex));
}
}
}
/**
* Perform a quick, in-place update of the checked or activated state
* on all visible item views. This should only be called when a valid
* choice mode is active.
*/
private void updateOnScreenCheckedViews() {
Log.d(TAG, "--->> updateOnScreenChecked");
Iterator<?> it = frames.entrySet().iterator();
View child = null;
while (it.hasNext()) {
Map.Entry<?, ItemProxy> pairs = (Map.Entry<?, ItemProxy>) it.next();
child = pairs.getValue().view;
boolean isChecked = isChecked(pairs.getValue().itemSection, pairs.getValue().itemIndex);
if (child instanceof Checkable) {
Log.d(TAG, "Setting checked UI : "+pairs.getValue().itemSection+", "+ pairs.getValue().itemIndex+": "+isChecked);
((Checkable) child).setChecked(isChecked);
} else {
child.setActivated(isChecked);
}
}
}
public boolean isChecked(int sectionIndex, int positionInSection){
for(int i=0; i<mCheckStates.size(); i++){
Position2D p = mCheckStates.keyAt(i);
if(p.section == sectionIndex && p.positionInSection == positionInSection){
return true;
}
}
return false;
}
public void setChecked(int sectionIndex, int positionInSection, boolean val){
Log.d(TAG, "sectionIndex: "+sectionIndex+", position: "+positionInSection+": "+val);
int foundAtIndex = -1;
for(int i=0; i<mCheckStates.size(); i++){
Position2D p = mCheckStates.keyAt(i);
if(p.section == sectionIndex && p.positionInSection == positionInSection){
foundAtIndex = i;
break;
}
}
if(foundAtIndex > -1 && val == false){
mCheckStates.removeAt(foundAtIndex);
}
else if (foundAtIndex == -1 && val == true){
Position2D pos = new Position2D(sectionIndex, positionInSection);
mCheckStates.put(pos, true);
}
}
} |
package edu.teco.dnd.graphiti;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.util.Repository;
import org.apache.bcel.util.SyntheticRepository;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
import org.eclipse.graphiti.dt.IDiagramTypeProvider;
import org.eclipse.graphiti.features.IAddFeature;
import org.eclipse.graphiti.features.ICreateConnectionFeature;
import org.eclipse.graphiti.features.ICreateFeature;
import org.eclipse.graphiti.features.IDirectEditingFeature;
import org.eclipse.graphiti.features.IFeature;
import org.eclipse.graphiti.features.ILayoutFeature;
import org.eclipse.graphiti.features.IRemoveFeature;
import org.eclipse.graphiti.features.IUpdateFeature;
import org.eclipse.graphiti.features.context.IAddConnectionContext;
import org.eclipse.graphiti.features.context.IAddContext;
import org.eclipse.graphiti.features.context.ICustomContext;
import org.eclipse.graphiti.features.context.IDirectEditingContext;
import org.eclipse.graphiti.features.context.ILayoutContext;
import org.eclipse.graphiti.features.context.IPictogramElementContext;
import org.eclipse.graphiti.features.context.IRemoveContext;
import org.eclipse.graphiti.features.context.IUpdateContext;
import org.eclipse.graphiti.features.custom.ICustomFeature;
import org.eclipse.graphiti.mm.algorithms.GraphicsAlgorithm;
import org.eclipse.graphiti.mm.pictograms.Connection;
import org.eclipse.graphiti.mm.pictograms.Diagram;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;
import org.eclipse.graphiti.ui.features.DefaultFeatureProvider;
import edu.teco.dnd.blocks.FunctionBlockClass;
import edu.teco.dnd.blocks.FunctionBlockFactory;
import edu.teco.dnd.eclipse.EclipseUtil;
import edu.teco.dnd.graphiti.model.FunctionBlockModel;
import edu.teco.dnd.graphiti.model.OptionModel;
import edu.teco.dnd.meeting.BeamerActorBlock;
import edu.teco.dnd.meeting.BeamerOperatorBlock;
import edu.teco.dnd.meeting.DisplayActorBlock;
import edu.teco.dnd.meeting.DisplayOperatorBlock;
import edu.teco.dnd.meeting.LightSensorBlock;
import edu.teco.dnd.meeting.MeetingOperatorBlock;
import edu.teco.dnd.meeting.OutletActorBlock;
import edu.teco.dnd.meeting.OutletSensorBlock;
import edu.teco.dnd.temperature.TemperatureActorBlock;
import edu.teco.dnd.temperature.TemperatureLogicBlock;
import edu.teco.dnd.temperature.TemperatureSensorBlock;
import edu.teco.dnd.util.ClassScanner;
import edu.teco.dnd.util.StringUtil;
/**
* Provides the features that are used by the editor.
*/
public class DNDFeatureProvider extends DefaultFeatureProvider {
/**
* The logger for this class.
*/
private static final Logger LOGGER = LogManager.getLogger(DNDFeatureProvider.class);
private Resource resource = null;
/**
* Default FunctionBlocks.
*/
private static final Class<?>[] DEFAULT_TYPES = new Class<?>[] { OutletActorBlock.class, BeamerOperatorBlock.class,
DisplayActorBlock.class, DisplayOperatorBlock.class, LightSensorBlock.class, MeetingOperatorBlock.class,
OutletSensorBlock.class, TemperatureActorBlock.class, TemperatureLogicBlock.class,
TemperatureSensorBlock.class, BeamerActorBlock.class };
/**
* Feature factory for block create features.
*/
private final DNDCreateFeatureFactory createFeatureFactory = new DNDCreateFeatureFactory();
/**
* Used to inspect FunctionBlocks.
*/
private FunctionBlockFactory blockFactory;
/**
* Whether or not {@link #createFeatureFactory} was initialised.
*/
private boolean factoryInitialised = false;
/**
* Passes the {@link IDiagramTypeProvider} to the super constructor.
*
* @param dtp
* the diagram type provider this feature provider belongs to
* @throws ClassNotFoundException
*/
public DNDFeatureProvider(final IDiagramTypeProvider dtp) throws ClassNotFoundException {
super(dtp);
LOGGER.info("DNDFeatureProvider created successfully");
}
/**
* Returns the class path for the Eclipse project this diagram is part of.
*
* @return the class path for the enclosing Eclipse project
*/
private Set<IPath> getProjectClassPath() {
final Diagram diagram = getDiagramTypeProvider().getDiagram();
if (diagram == null) {
return Collections.emptySet();
}
IProject project = EclipseUtil.getWorkspaceProject(URI.createURI(EcoreUtil.getURI(diagram).toString()));
Set<URL> urls = new HashSet<URL>();
return EclipseUtil.getAbsoluteBinPaths(project);
}
/**
* Registers default create features at the factory.
*/
@SuppressWarnings("unchecked")
private void registerDefaultTypes() {
final FunctionBlockFactory factory;
try {
factory = new FunctionBlockFactory(SyntheticRepository.getInstance());
} catch (final ClassNotFoundException e) {
LOGGER.catching(Level.WARN, e);
return;
}
for (Class<?> type : DEFAULT_TYPES) {
try {
createFeatureFactory.registerBlockType(factory.getFunctionBlockClass(type));
} catch (final ClassNotFoundException e) {
LOGGER.catching(Level.WARN, e);
}
}
}
/**
* Returns the CreateFeatures for all loaded blocks.
*
* @return CreateFeatures for all loaded blocks
*/
public final synchronized ICreateFeature[] getCreateFeatures() {
initialiseFactory();
return createFeatureFactory.getCreateFeatures(this).toArray(new ICreateFeature[0]);
}
/**
* Used to initialize a Factory.
*/
private synchronized void initialiseFactory() {
if (!factoryInitialised) {
final Set<IPath> ipaths = getProjectClassPath();
try {
blockFactory = new FunctionBlockFactory(StringUtil.joinIterable(ipaths, ":"));
} catch (final ClassNotFoundException e) {
LOGGER.catching(e);
}
registerDefaultTypes();
final Set<File> paths = new HashSet<File>();
for (final IPath ipath : getProjectClassPath()) {
paths.add(ipath.toFile());
}
final ClassScanner scanner = new ClassScanner(blockFactory.getRepository());
for (final JavaClass cls : scanner.getClasses(paths)) {
final FunctionBlockClass blockClass;
try {
blockClass = blockFactory.getFunctionBlockClass(cls.getClassName());
} catch (final ClassNotFoundException e) {
continue;
} catch (final IllegalArgumentException e) {
continue;
}
createFeatureFactory.registerBlockType(blockClass);
}
factoryInitialised = true;
}
}
/**
* Returns the FunctionBlockFactory.
*
* @return the FunctionBlockFactory
*/
public final synchronized FunctionBlockFactory getFunctionBlockFactory() {
initialiseFactory();
return blockFactory;
}
public final Repository getRepository() {
return blockFactory.getRepository();
}
/**
* Returns the AddFeatures for FunctionBlocks and data connections.
*
* @param context
* the context for which to return a feature
* @return a matching AddFeature
*/
@Override
public final IAddFeature getAddFeature(final IAddContext context) {
LOGGER.entry(context);
if (context instanceof IAddConnectionContext) {
return new DNDAddDataConnectionFeature(this);
} else if (context.getNewObject() instanceof FunctionBlockModel) {
return new DNDAddBlockFeature(this);
}
return super.getAddFeature(context);
}
/**
* Returns the LayoutFeature for FunctionBlocks.
*
* @param context
* the context for which to return a feature
* @return the LayoutFeature for FunctionBlocks
*/
@Override
public final ILayoutFeature getLayoutFeature(final ILayoutContext context) {
PictogramElement pictogramElement = context.getPictogramElement();
Object bo = getBusinessObjectForPictogramElement(pictogramElement);
if (bo instanceof FunctionBlockModel) {
return new DNDLayoutBlockFeature(this);
}
return super.getLayoutFeature(context);
}
/**
* Returns the UpdateFeature for FunctionBlocks.
*
* @param context
* the context for which to return a feature
* @return the UpdateFeature for FunctionBlocks
*/
@Override
public final IUpdateFeature getUpdateFeature(final IUpdateContext context) {
PictogramElement pe = context.getPictogramElement();
Object bo = getBusinessObjectForPictogramElement(pe);
if (bo instanceof OptionModel) {
return new DNDUpdateOptionFeature(this);
} else if (bo instanceof FunctionBlockModel) {
GraphicsAlgorithm ga = pe.getGraphicsAlgorithm();
if (TypePropertyUtil.isPositionText(ga)) {
return new DNDUpdatePositionFeature(this);
} else if (TypePropertyUtil.isBlockNameText(ga)) {
return new DNDUpdateBlockNameFeature(this);
} else if (TypePropertyUtil.isBlockShape(ga)) {
return new DNDUpdateBlockFeature(this);
}
}
return super.getUpdateFeature(context);
}
/**
* Returns the CreateConnectionFeatures for data connections.
*
* @return the CreateConnectionFeatures for data connections
*/
@Override
public final ICreateConnectionFeature[] getCreateConnectionFeatures() {
return new ICreateConnectionFeature[] { new DNDCreateDataConnectionFeature(this) };
}
/**
* Returns a DirectEditFeature for Options and positions.
*
* @param context
* the context for which to return a feature
* @return a matching DirectEditFeature
*/
@SuppressWarnings("unchecked")
@Override
public final IDirectEditingFeature getDirectEditingFeature(final IDirectEditingContext context) {
LOGGER.entry(context);
PictogramElement pe = context.getPictogramElement();
Object bo = getBusinessObjectForPictogramElement(pe);
IDirectEditingFeature feature = null;
if (bo instanceof OptionModel) {
feature = new DNDEditOptionFeature(this);
} else if (bo instanceof FunctionBlockModel) {
GraphicsAlgorithm ga = pe.getGraphicsAlgorithm();
if (TypePropertyUtil.isBlockNameText(ga)) {
feature = new DNDEditBlockNameFeature(this);
} else if (TypePropertyUtil.isPositionText(ga)) {
feature = new DNDEditPositionFeature(this);
}
}
if (feature == null) {
feature = super.getDirectEditingFeature(context);
}
LOGGER.exit(feature);
return feature;
}
@Override
public final IRemoveFeature getRemoveFeature(final IRemoveContext context) {
if (context.getPictogramElement() instanceof Connection) {
return new DNDRemoveDataConnectionFeature(this);
}
return super.getRemoveFeature(context);
}
@Override
public final ICustomFeature[] getCustomFeatures(final ICustomContext context) {
return new ICustomFeature[] { new DNDDebugFeature(this), new DNDCustomUpdateFeature(this) };
}
@Override
public final IFeature[] getDragAndDropFeatures(final IPictogramElementContext context) {
return getCreateConnectionFeatures();
}
/**
* Returns the resource containing the desired FunctionBlockModels. Use this method to get to the resource whenever
* you need it (to get to or add FunctionBlockModels) instead of creating a new one or getting it from somewhere
* else. TThat way multiple competitive resources or files can be prevented.
*
* @return the resource containing FunctionBlockModels.
*/
public synchronized Resource getEMFResource() {
if (resource == null) {
Diagram d = getDiagramTypeProvider().getDiagram();
URI uri = d.eResource().getURI();
uri = uri.trimFragment();
uri = uri.trimFileExtension();
uri = uri.appendFileExtension("blocks");
ResourceSet rSet = d.eResource().getResourceSet();
final IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IResource file = workspaceRoot.findMember(uri.toPlatformString(true));
if (file == null || !file.exists()) {
Resource createResource = rSet.createResource(uri);
try {
createResource.save(null);
} catch (IOException e) {
e.printStackTrace();
}
createResource.setTrackingModification(true);
}
resource = rSet.getResource(uri, true);
resource.setTrackingModification(true);
System.out.println("Resource vom Featureprovider erstellt. Trackt? " + resource.isTrackingModification());
}
return resource;
}
/**
* Updates the contents (FunctionBlockModels) of its resource. This can be invoked whenever @getEMFResource()
* returns true, but also works in case nothing changed. This method updates the BlockName and Position of all
* FunctionBlockModel in the resource to be consistent with changes made outside the resource.
*/
public synchronized void updateEMFResource() {
Resource newResource = getNewEMFResource();
Collection<FunctionBlockModel> oldModels = new ArrayList<FunctionBlockModel>();
for (EObject obj : resource.getContents()) {
if (obj instanceof FunctionBlockModel) {
oldModels.add((FunctionBlockModel) obj);
}
}
for (EObject obj : newResource.getContents()) {
if (obj instanceof FunctionBlockModel) {
FunctionBlockModel newModel = (FunctionBlockModel) obj;
for (FunctionBlockModel oldModel : oldModels) {
if (oldModel.getID().equals(newModel.getID())) {
oldModel.setPosition(newModel.getPosition());
oldModel.setBlockName(newModel.getBlockName());
}
}
}
}
}
/**
* Checks whether the FunctionBlockModels contained by the resource have been changed outside this specific
* resource.
*
* @return true if changes happened, false if not.
*/
public synchronized boolean emfResourceChanged() {
Resource newResource = getNewEMFResource();
Collection<FunctionBlockModel> oldModels = new ArrayList<FunctionBlockModel>();
for (EObject obj : resource.getContents()) {
if (obj instanceof FunctionBlockModel) {
oldModels.add((FunctionBlockModel) obj);
}
}
for (EObject obj : newResource.getContents()) {
if (obj instanceof FunctionBlockModel) {
FunctionBlockModel newModel = (FunctionBlockModel) obj;
for (FunctionBlockModel oldModel : oldModels) {
if (oldModel.getID().equals(newModel.getID())
&& !(oldModel.getPosition().equals(newModel.getPosition()) && oldModel.getBlockName()
.equals(newModel.getBlockName()))) {
return true;
}
}
}
}
return false;
}
/**
* Used by updateEMFResource and emfResourceChanged to load the new resource.
*
* @return new Resource.
*/
private Resource getNewEMFResource() {
if (resource == null) {
getEMFResource();
}
Diagram d = getDiagramTypeProvider().getDiagram();
URI uri = d.eResource().getURI();
uri = uri.trimFragment();
uri = uri.trimFileExtension();
uri = uri.appendFileExtension("blocks");
Resource newResource = new XMIResourceImpl(uri);
try {
newResource.load(null);
} catch (IOException e) {
e.printStackTrace();
}
return newResource;
}
} |
package com.yox89.ld32.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.utils.Align;
import com.yox89.ld32.Gajm;
import com.yox89.ld32.Physics;
import com.yox89.ld32.actors.Torch;
import com.yox89.ld32.util.PhysicsUtil;
import com.yox89.ld32.util.PhysicsUtil.BodyParams;
public class StartScreen extends BaseScreen {
private Stage game;
private Gajm gajm;
public StartScreen(Gajm gajm) {
this.gajm = gajm;
}
@Override
protected void init(Stage game, Stage ui, Physics physics) {
this.game = game;
final Texture img = manage(new Texture("StartButtonEng.png"));
img.setFilter(TextureFilter.Linear, TextureFilter.Linear);
final StartGameButtonActor startBtn = new StartGameButtonActor(img,
physics.world,
Math.min(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT) / 5f);
game.addActor(startBtn);
startBtn.setPosition(GAME_WORLD_WIDTH / 2 - startBtn.getWidth() / 2,
GAME_WORLD_HEIGHT / 2);
PhysicsUtil.createBody(new BodyParams(physics.world) {
@Override
public void setShape(PolygonShape ps) {
ps.setAsBox(startBtn.getWidth() / 2, startBtn.getHeight() / 2f);
}
}).setTransform(startBtn.getX() + startBtn.getWidth() / 2,
startBtn.getY() + startBtn.getHeight() / 2, 0f);
Torch startBtnTorch = new Torch(physics, Color.MAGENTA);
startBtnTorch.setPosition(startBtn.getX() + startBtn.getWidth() / 2f,
startBtn.getY() + startBtn.getHeight() / 2);
game.addActor(startBtnTorch);
Torch torchUpCorner = new Torch(physics);
torchUpCorner.setPosition(GAME_WORLD_WIDTH - 1, GAME_WORLD_HEIGHT - 1);
game.addActor(new Torch(physics));
game.addActor(torchUpCorner);
final Label titleLbl = new Label("LD32 Work in progress",
new LabelStyle(manage(new BitmapFont()), Color.CYAN));
titleLbl.setPosition(
Gdx.graphics.getWidth() / 2 - titleLbl.getMinWidth(), Gdx.graphics.getHeight() * 0.8f);
titleLbl.setFontScale(2f);
final Label copyLbl = new Label(
"Made by: Kevlanche, Jonathan Hagberg, "
+ "\nAdam Nilsson & Marie Versland in ~24 hours so far",
new LabelStyle(manage(new BitmapFont()), Color.CYAN));
copyLbl.setAlignment(Align.center);
copyLbl.setFontScale(0.9f);
copyLbl.setPosition((Gdx.graphics.getWidth() - copyLbl.getMinWidth() / copyLbl.getFontScaleX()) / 2 , 50);
ui.addActor(titleLbl);
ui.addActor(copyLbl);
}
private class StartGameButtonActor extends Actor {
private final Texture mTexture;
public StartGameButtonActor(Texture tex, World world, final float size) {
mTexture = tex;
setSize(size * 2, size);
addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x, float y,
int pointer, int button) {
switchScreen(new Runnable() {
@Override
public void run() {
gajm.setScreen(new TiledLevelScreen(gajm, 1));
}
});
return true;
};
@Override
public void enter(InputEvent event, float x, float y,
int pointer, Actor fromActor) {
setColor(Color.WHITE);
super.enter(event, x, y, pointer, fromActor);
}
@Override
public void exit(InputEvent event, float x, float y,
int pointer, Actor toActor) {
setColor(Color.LIGHT_GRAY);
super.exit(event, x, y, pointer, toActor);
}
});
setColor(Color.LIGHT_GRAY);
}
@Override
public void act(float delta) {
super.act(delta);
if (Gdx.input.isKeyPressed(Keys.J)) {
gajm.setScreen(new TiledLevelScreen(gajm, 5));
}
if (Gdx.input.isKeyPressed(Keys.K)) {
gajm.setScreen(new TiledLevelScreen(gajm, 6));
}
if (Gdx.input.isKeyPressed(Keys.M)) {
gajm.setScreen(new TiledLevelScreen(gajm, 7));
}
if (Gdx.input.isKeyPressed(Keys.L)) {
gajm.setScreen(new TiledLevelScreen(gajm, 8));
}
if (Gdx.input.isKeyPressed(Keys.O)) {
gajm.setScreen(new TiledLevelScreen(gajm, 0));
}
if (Gdx.input.isKeyPressed(Keys.U)) {
gajm.setScreen(new TiledLevelScreen(gajm, 2));
}
if (Gdx.input.isKeyPressed(Keys.T)) {
gajm.setScreen(new TiledLevelScreen(gajm, 3));
}
if (Gdx.input.isKeyPressed(Keys.N)) {
gajm.setScreen(new TiledLevelScreen(gajm, 4));
}
if (Gdx.input.isKeyPressed(Keys.B)) {
gajm.setScreen(new TiledLevelScreen(gajm, 9));
}
}
@Override
public void draw(Batch batch, float parentAlpha) {
batch.setColor(getColor());
batch.draw(mTexture, getX(), getY(), getOriginX(), getOriginY(),
getWidth(), getHeight(), getScaleX(), getScaleY(),
getRotation(), 0, 0, mTexture.getWidth(),
mTexture.getHeight(), false, false);
}
}
} |
package ru.osetsky;
public class Count {
/**
* Wait before terminate.
*/
private static final long WATCH_DOG_TIMER = 1000;
/**
* Count.
*/
private final Thread count;
/**
* Time.
*/
private final Thread time;
/**
* Constructor initialize two threads.
*
* @param line - words.
*/
public Count(String line) {
this.count = new Thread(new Count.CountChar(line));
this.time = new Thread(new Count.Time());
}
/**
* Start threads.
*/
public void count() {
System.out.println("Start");
count.start();
time.start();
System.out.println("End");
}
/**
* Class interrupter.
*/
public class Time implements Runnable {
/**
* Run.
*/
@Override
public void run() {
if (count != null && count.isAlive()) {
System.out.printf("%s %s %n", "Terminate: ", count.getName());
count.interrupt();
}
}
}
/**
* Class counter.
*/
public class CountChar implements Runnable {
/**
* Counter.
*/
private final CountWords counter;
/**
* Constructor initialize counter.
*
* @param line - words.
*/
public CountChar(String line) {
this.counter = new CountWords(line);
}
/**
* Run.
*/
@Override
public void run() {
int words = this.counter.words();
if (!count.isInterrupted()) {
System.out.printf("%s %d %n", "Words", words);
}
}
}
/**
* @param args - default.
* @throws InterruptedException - Exception.
*/
public static void main(String[] args) throws InterruptedException {
new Count("job for java").count();
}
} |
package com.javadude.observer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class ButtonExample {
private static class ButtonReport implements ActionListener {
@Override public void actionPerformed(ActionEvent e) {
System.out.println("Button was pressed!");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton("Press Me");
frame.add(button);
ButtonReport buttonReport = new ButtonReport();
button.addActionListener(buttonReport);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
} |
package com.special.ResideMenu;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.*;
import android.view.animation.AnimationUtils;
import android.widget.*;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.view.ViewHelper;
import java.util.ArrayList;
import java.util.List;
public class ResideMenu extends FrameLayout {
public static final int DIRECTION_LEFT = 0;
public static final int DIRECTION_RIGHT = 1;
private static final int PRESSED_MOVE_HORIZONTAL = 2;
private static final int PRESSED_DOWN = 3;
private static final int PRESSED_DONE = 4;
private static final int PRESSED_MOVE_VERTICAL = 5;
private ImageView imageViewShadow;
private ImageView imageViewBackground;
private LinearLayout layoutLeftMenu;
private LinearLayout layoutRightMenu;
private View scrollViewLeftMenu;
private View scrollViewRightMenu;
private View scrollViewMenu;
/**
* Current attaching activity.
*/
private Activity activity;
/**
* The DecorView of current activity.
*/
private ViewGroup viewDecor;
private TouchDisableView viewActivity;
/**
* The flag of menu opening status.
*/
private boolean isOpened;
private float shadowAdjustScaleX;
private float shadowAdjustScaleY;
/**
* Views which need stop to intercept touch events.
*/
private List<View> ignoredViews;
private List<ResideMenuItem> leftMenuItems;
private List<ResideMenuItem> rightMenuItems;
private DisplayMetrics displayMetrics = new DisplayMetrics();
private OnMenuListener menuListener;
private float lastRawX;
private boolean isInIgnoredView = false;
private int scaleDirection = DIRECTION_LEFT;
private int pressedState = PRESSED_DOWN;
private List<Integer> disabledSwipeDirection = new ArrayList<Integer>();
// Valid scale factor is between 0.0f and 1.0f.
private float mScaleValue = 0.5f;
private boolean mUse3D;
private static final int ROTATE_Y_ANGLE = 10;
public ResideMenu(Context context) {
super(context);
initViews(context, -1, -1);
}
/**
* This constructor provides you to create menus with your own custom
* layouts, but if you use custom menu then do not call addMenuItem because
* it will not be able to find default views
*/
public ResideMenu(Context context, int customLeftMenuId,
int customRightMenuId) {
super(context);
initViews(context, customLeftMenuId, customRightMenuId);
}
private void initViews(Context context, int customLeftMenuId,
int customRightMenuId) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.residemenu_custom, this);
if (customLeftMenuId >= 0) {
scrollViewLeftMenu = inflater.inflate(customLeftMenuId, this, false);
} else {
scrollViewLeftMenu = inflater.inflate(
R.layout.residemenu_custom_left_scrollview, this, false);
layoutLeftMenu = (LinearLayout) scrollViewLeftMenu.findViewById(R.id.layout_left_menu);
}
if (customRightMenuId >= 0) {
scrollViewRightMenu = inflater.inflate(customRightMenuId, this, false);
} else {
scrollViewRightMenu = inflater.inflate(
R.layout.residemenu_custom_right_scrollview, this, false);
layoutRightMenu = (LinearLayout) scrollViewRightMenu.findViewById(R.id.layout_right_menu);
}
imageViewShadow = (ImageView) findViewById(R.id.iv_shadow);
imageViewBackground = (ImageView) findViewById(R.id.iv_background);
RelativeLayout menuHolder = (RelativeLayout) findViewById(R.id.sv_menu_holder);
menuHolder.addView(scrollViewLeftMenu);
menuHolder.addView(scrollViewRightMenu);
}
/**
* Returns left menu view so you can findViews and do whatever you want with
*/
public View getLeftMenuView() {
return scrollViewLeftMenu;
}
/**
* Returns right menu view so you can findViews and do whatever you want with
*/
public View getRightMenuView() {
return scrollViewRightMenu;
}
@Override
protected boolean fitSystemWindows(Rect insets) {
// Applies the content insets to the view's padding, consuming that
// content (modifying the insets to be 0),
// and returning true. This behavior is off by default and can be
// enabled through setFitsSystemWindows(boolean)
// in api14+ devices.
// This is added to fix soft navigationBar's overlapping to content above LOLLIPOP
int bottomPadding = viewActivity.getPaddingBottom() + insets.bottom;
if (Build.VERSION.SDK_INT >= 21) {
bottomPadding += getNavigationBarHeight();
}
this.setPadding(viewActivity.getPaddingLeft() + insets.left,
viewActivity.getPaddingTop() + insets.top,
viewActivity.getPaddingRight() + insets.right,
bottomPadding);
insets.left = insets.top = insets.right = insets.bottom = 0;
return true;
}
private int getNavigationBarHeight() {
Resources resources = getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
return resources.getDimensionPixelSize(resourceId);
}
return 0;
}
/**
* Set up the activity;
*
* @param activity
*/
public void attachToActivity(Activity activity) {
initValue(activity);
setShadowAdjustScaleXByOrientation();
viewDecor.addView(this, 0);
}
private void initValue(Activity activity) {
this.activity = activity;
leftMenuItems = new ArrayList<ResideMenuItem>();
rightMenuItems = new ArrayList<ResideMenuItem>();
ignoredViews = new ArrayList<View>();
viewDecor = (ViewGroup) activity.getWindow().getDecorView();
viewActivity = new TouchDisableView(this.activity);
View mContent = viewDecor.getChildAt(0);
viewDecor.removeViewAt(0);
viewActivity.setContent(mContent);
addView(viewActivity);
ViewGroup parent = (ViewGroup) scrollViewLeftMenu.getParent();
parent.removeView(scrollViewLeftMenu);
parent.removeView(scrollViewRightMenu);
}
private void setShadowAdjustScaleXByOrientation() {
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
shadowAdjustScaleX = 0.034f;
shadowAdjustScaleY = 0.12f;
} else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
shadowAdjustScaleX = 0.06f;
shadowAdjustScaleY = 0.07f;
}
}
/**
* Set the background image of menu;
*
* @param imageResource
*/
public void setBackground(int imageResource) {
imageViewBackground.setImageResource(imageResource);
}
/**
* The visibility of the shadow under the activity;
*
* @param isVisible
*/
public void setShadowVisible(boolean isVisible) {
if (isVisible)
imageViewShadow.setBackgroundResource(R.drawable.shadow);
else
imageViewShadow.setBackgroundResource(0);
}
/**
* Add a single item to the left menu;
* <p/>
* WARNING: It will be removed from v2.0.
*
* @param menuItem
*/
@Deprecated
public void addMenuItem(ResideMenuItem menuItem) {
this.leftMenuItems.add(menuItem);
layoutLeftMenu.addView(menuItem);
}
/**
* Add a single items;
*
* @param menuItem
* @param direction
*/
public void addMenuItem(ResideMenuItem menuItem, int direction) {
if (direction == DIRECTION_LEFT) {
this.leftMenuItems.add(menuItem);
layoutLeftMenu.addView(menuItem);
} else {
this.rightMenuItems.add(menuItem);
layoutRightMenu.addView(menuItem);
}
}
/**
* WARNING: It will be removed from v2.0.
*
* @param menuItems
*/
@Deprecated
public void setMenuItems(List<ResideMenuItem> menuItems) {
this.leftMenuItems = menuItems;
rebuildMenu();
}
/**
* Set menu items by a array;
*
* @param menuItems
* @param direction
*/
public void setMenuItems(List<ResideMenuItem> menuItems, int direction) {
if (direction == DIRECTION_LEFT)
this.leftMenuItems = menuItems;
else
this.rightMenuItems = menuItems;
rebuildMenu();
}
private void rebuildMenu() {
if (layoutLeftMenu != null) {
layoutLeftMenu.removeAllViews();
for (ResideMenuItem leftMenuItem : leftMenuItems)
layoutLeftMenu.addView(leftMenuItem);
}
if (layoutRightMenu != null) {
layoutRightMenu.removeAllViews();
for (ResideMenuItem rightMenuItem : rightMenuItems)
layoutRightMenu.addView(rightMenuItem);
}
}
/**
* WARNING: It will be removed from v2.0.
*
* @return
*/
@Deprecated
public List<ResideMenuItem> getMenuItems() {
return leftMenuItems;
}
/**
* Return instances of menu items;
*
* @return
*/
public List<ResideMenuItem> getMenuItems(int direction) {
if (direction == DIRECTION_LEFT)
return leftMenuItems;
else
return rightMenuItems;
}
/**
* If you need to do something on closing or opening menu,
* set a listener here.
*
* @return
*/
public void setMenuListener(OnMenuListener menuListener) {
this.menuListener = menuListener;
}
public OnMenuListener getMenuListener() {
return menuListener;
}
/**
* Show the menu;
*/
public void openMenu(int direction) {
setScaleDirection(direction);
isOpened = true;
AnimatorSet scaleDown_activity = buildScaleDownAnimation(viewActivity, mScaleValue, mScaleValue);
AnimatorSet scaleDown_shadow = buildScaleDownAnimation(imageViewShadow,
mScaleValue + shadowAdjustScaleX, mScaleValue + shadowAdjustScaleY);
AnimatorSet alpha_menu = buildMenuAnimation(scrollViewMenu, 1.0f);
scaleDown_shadow.addListener(animationListener);
scaleDown_activity.playTogether(scaleDown_shadow);
scaleDown_activity.playTogether(alpha_menu);
scaleDown_activity.start();
}
/**
* Close the menu;
*/
public void closeMenu() {
isOpened = false;
AnimatorSet scaleUp_activity = buildScaleUpAnimation(viewActivity, 1.0f, 1.0f);
AnimatorSet scaleUp_shadow = buildScaleUpAnimation(imageViewShadow, 1.0f, 1.0f);
AnimatorSet alpha_menu = buildMenuAnimation(scrollViewMenu, 0.0f);
scaleUp_activity.addListener(animationListener);
scaleUp_activity.playTogether(scaleUp_shadow);
scaleUp_activity.playTogether(alpha_menu);
scaleUp_activity.start();
}
@Deprecated
public void setDirectionDisable(int direction) {
disabledSwipeDirection.add(direction);
}
public void setSwipeDirectionDisable(int direction) {
disabledSwipeDirection.add(direction);
}
private boolean isInDisableDirection(int direction) {
return disabledSwipeDirection.contains(direction);
}
private void setScaleDirection(int direction) {
int screenWidth = getScreenWidth();
float pivotX;
float pivotY = getScreenHeight() * 0.5f;
if (direction == DIRECTION_LEFT) {
scrollViewMenu = scrollViewLeftMenu;
pivotX = screenWidth * 1.5f;
} else {
scrollViewMenu = scrollViewRightMenu;
pivotX = screenWidth * -0.5f;
}
ViewHelper.setPivotX(viewActivity, pivotX);
ViewHelper.setPivotY(viewActivity, pivotY);
ViewHelper.setPivotX(imageViewShadow, pivotX);
ViewHelper.setPivotY(imageViewShadow, pivotY);
scaleDirection = direction;
}
/**
* return the flag of menu status;
*
* @return
*/
public boolean isOpened() {
return isOpened;
}
private OnClickListener viewActivityOnClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
if (isOpened()) closeMenu();
}
};
private Animator.AnimatorListener animationListener = new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
if (isOpened()) {
showScrollViewMenu(scrollViewMenu);
if (menuListener != null)
menuListener.openMenu();
}
}
@Override
public void onAnimationEnd(Animator animation) {
// reset the view;
if (isOpened()) {
viewActivity.setTouchDisable(true);
viewActivity.setOnClickListener(viewActivityOnClickListener);
} else {
viewActivity.setTouchDisable(false);
viewActivity.setOnClickListener(null);
hideScrollViewMenu(scrollViewLeftMenu);
hideScrollViewMenu(scrollViewRightMenu);
if (menuListener != null)
menuListener.closeMenu();
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
};
/**
* A helper method to build scale down animation;
*
* @param target
* @param targetScaleX
* @param targetScaleY
* @return
*/
private AnimatorSet buildScaleDownAnimation(View target, float targetScaleX, float targetScaleY) {
AnimatorSet scaleDown = new AnimatorSet();
scaleDown.playTogether(
ObjectAnimator.ofFloat(target, "scaleX", targetScaleX),
ObjectAnimator.ofFloat(target, "scaleY", targetScaleY)
);
if (mUse3D) {
int angle = scaleDirection == DIRECTION_LEFT ? -ROTATE_Y_ANGLE : ROTATE_Y_ANGLE;
scaleDown.playTogether(ObjectAnimator.ofFloat(target, "rotationY", angle));
}
scaleDown.setInterpolator(AnimationUtils.loadInterpolator(activity,
android.R.anim.decelerate_interpolator));
scaleDown.setDuration(250);
return scaleDown;
}
/**
* A helper method to build scale up animation;
*
* @param target
* @param targetScaleX
* @param targetScaleY
* @return
*/
private AnimatorSet buildScaleUpAnimation(View target, float targetScaleX, float targetScaleY) {
AnimatorSet scaleUp = new AnimatorSet();
scaleUp.playTogether(
ObjectAnimator.ofFloat(target, "scaleX", targetScaleX),
ObjectAnimator.ofFloat(target, "scaleY", targetScaleY)
);
if (mUse3D) {
scaleUp.playTogether(ObjectAnimator.ofFloat(target, "rotationY", 0));
}
scaleUp.setDuration(250);
return scaleUp;
}
private AnimatorSet buildMenuAnimation(View target, float alpha) {
AnimatorSet alphaAnimation = new AnimatorSet();
alphaAnimation.playTogether(
ObjectAnimator.ofFloat(target, "alpha", alpha)
);
alphaAnimation.setDuration(250);
return alphaAnimation;
}
/**
* If there were some view you don't want reside menu
* to intercept their touch event, you could add it to
* ignored views.
*
* @param v
*/
public void addIgnoredView(View v) {
ignoredViews.add(v);
}
/**
* Remove a view from ignored views;
*
* @param v
*/
public void removeIgnoredView(View v) {
ignoredViews.remove(v);
}
/**
* Clear the ignored view list;
*/
public void clearIgnoredViewList() {
ignoredViews.clear();
}
/**
* If the motion event was relative to the view
* which in ignored view list,return true;
*
* @param ev
* @return
*/
private boolean isInIgnoredView(MotionEvent ev) {
Rect rect = new Rect();
for (View v : ignoredViews) {
v.getGlobalVisibleRect(rect);
if (rect.contains((int) ev.getX(), (int) ev.getY()))
return true;
}
return false;
}
private void setScaleDirectionByRawX(float currentRawX) {
if (currentRawX < lastRawX)
setScaleDirection(DIRECTION_RIGHT);
else
setScaleDirection(DIRECTION_LEFT);
}
private float getTargetScale(float currentRawX) {
float scaleFloatX = ((currentRawX - lastRawX) / getScreenWidth()) * 0.75f;
scaleFloatX = scaleDirection == DIRECTION_RIGHT ? -scaleFloatX : scaleFloatX;
float targetScale = ViewHelper.getScaleX(viewActivity) - scaleFloatX;
targetScale = targetScale > 1.0f ? 1.0f : targetScale;
targetScale = targetScale < 0.5f ? 0.5f : targetScale;
return targetScale;
}
private float lastActionDownX, lastActionDownY;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
float currentActivityScaleX = ViewHelper.getScaleX(viewActivity);
if (currentActivityScaleX == 1.0f)
setScaleDirectionByRawX(ev.getRawX());
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
lastActionDownX = ev.getX();
lastActionDownY = ev.getY();
isInIgnoredView = isInIgnoredView(ev) && !isOpened();
pressedState = PRESSED_DOWN;
break;
case MotionEvent.ACTION_MOVE:
if (isInIgnoredView || isInDisableDirection(scaleDirection))
break;
if (pressedState != PRESSED_DOWN &&
pressedState != PRESSED_MOVE_HORIZONTAL)
break;
int xOffset = (int) (ev.getX() - lastActionDownX);
int yOffset = (int) (ev.getY() - lastActionDownY);
if (pressedState == PRESSED_DOWN) {
if (yOffset > 25 || yOffset < -25) {
pressedState = PRESSED_MOVE_VERTICAL;
break;
}
if (xOffset < -50 || xOffset > 50) {
pressedState = PRESSED_MOVE_HORIZONTAL;
ev.setAction(MotionEvent.ACTION_CANCEL);
}
} else if (pressedState == PRESSED_MOVE_HORIZONTAL) {
if (currentActivityScaleX < 0.95)
showScrollViewMenu(scrollViewMenu);
float targetScale = getTargetScale(ev.getRawX());
ViewHelper.setScaleX(viewActivity, targetScale);
ViewHelper.setScaleY(viewActivity, targetScale);
ViewHelper.setScaleX(imageViewShadow, targetScale + shadowAdjustScaleX);
ViewHelper.setScaleY(imageViewShadow, targetScale + shadowAdjustScaleY);
ViewHelper.setAlpha(scrollViewMenu, (1 - targetScale) * 2.0f);
lastRawX = ev.getRawX();
return true;
}
break;
case MotionEvent.ACTION_UP:
if (isInIgnoredView) break;
if (pressedState != PRESSED_MOVE_HORIZONTAL) break;
pressedState = PRESSED_DONE;
if (isOpened()) {
if (currentActivityScaleX > 0.56f)
closeMenu();
else
openMenu(scaleDirection);
} else {
if (currentActivityScaleX < 0.94f) {
openMenu(scaleDirection);
} else {
closeMenu();
}
}
break;
}
lastRawX = ev.getRawX();
return super.dispatchTouchEvent(ev);
}
public int getScreenHeight() {
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.heightPixels;
}
public int getScreenWidth() {
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.widthPixels;
}
public void setScaleValue(float scaleValue) {
this.mScaleValue = scaleValue;
}
public void setUse3D(boolean use3D) {
mUse3D = use3D;
}
public interface OnMenuListener {
/**
* This method will be called at the finished time of opening menu animations.
*/
public void openMenu();
/**
* This method will be called at the finished time of closing menu animations.
*/
public void closeMenu();
}
private void showScrollViewMenu(View scrollViewMenu) {
if (scrollViewMenu != null && scrollViewMenu.getParent() == null) {
addView(scrollViewMenu);
}
}
private void hideScrollViewMenu(View scrollViewMenu) {
if (scrollViewMenu != null && scrollViewMenu.getParent() != null) {
removeView(scrollViewMenu);
}
}
} |
package org.xins.tests.server;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.OptionsMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.xins.common.collections.BasicPropertyReader;
import org.xins.common.http.HTTPCallRequest;
import org.xins.common.http.HTTPCallResult;
import org.xins.common.http.HTTPServiceCaller;
import org.xins.common.service.TargetDescriptor;
import org.xins.common.text.FastStringBuffer;
import org.xins.common.text.HexConverter;
import org.xins.common.text.ParseException;
import org.xins.common.xml.Element;
import org.xins.common.xml.ElementParser;
/**
* Tests for XINS call convention.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:anthony.goubard@nl.wanadoo.com">anthony.goubard@nl.wanadoo.com</a>)
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*/
public class CallingConventionTests extends TestCase {
// Class functions
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(CallingConventionTests.class);
}
// Class fields
/**
* The random number generator.
*/
private final static Random RANDOM = new Random();
// Constructor
/**
* Constructs a new <code>CallingConventionTests</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public CallingConventionTests(String name) {
super(name);
}
// Methods
/**
* Tests the standard calling convention which should be the default.
*/
public void testStandardCallingConvention1() throws Throwable {
callResultCodeStandard(null);
}
/**
* Tests the standard calling convention.
*/
public void testStandardCallingConvention2() throws Throwable {
callResultCodeStandard("_xins-std");
}
/**
* Tests with an unknown calling convention.
*/
public void testInvalidCallingConvention() throws Throwable {
TargetDescriptor descriptor = new TargetDescriptor("http://127.0.0.1:8080/", 2000);
BasicPropertyReader params = new BasicPropertyReader();
params.set("_function", "ResultCode");
params.set("inputText", "blablabla");
params.set("_convention", "_xins-bla");
HTTPCallRequest request = new HTTPCallRequest(params);
HTTPServiceCaller caller = new HTTPServiceCaller(descriptor);
HTTPCallResult result = caller.call(request);
assertEquals(400, result.getStatusCode());
}
/**
* Calls the ResultCode function and expect the standard calling convention back.
*
* @param convention
* the name of the calling convention parameter, or <code>null</code>
* if no calling convention parameter should be sent.
*
* @throw Throwable
* if anything goes wrong.
*/
public void callResultCodeStandard(String convention) throws Throwable {
FastStringBuffer buffer = new FastStringBuffer(16);
HexConverter.toHexString(buffer, RANDOM.nextLong());
String randomFive = buffer.toString().substring(0, 5);
Element result1 = callResultCode(convention, randomFive);
assertNull("The method returned an error code for the first call: " + result1.getAttribute("errorcode"), result1.getAttribute("errorcode"));
assertNull("The method returned a code attribute for the first call: " + result1.getAttribute("code"), result1.getAttribute("code"));
assertNull("The method returned a success attribute for the first call: " + result1.getAttribute("success"), result1.getAttribute("success"));
Element result2 = callResultCode(convention, randomFive);
assertNotNull("The method did not return an error code for the second call.", result2.getAttribute("errorcode"));
assertNull("The method returned a code attribute for the second call: " + result2.getAttribute("code"), result2.getAttribute("code"));
assertNull("The method returned a success attribute for the second call: " + result2.getAttribute("success"), result2.getAttribute("success"));
}
/**
* Tests the old style calling convention.
*/
public void testOldCallingConvention1() throws Throwable {
FastStringBuffer buffer = new FastStringBuffer(16);
HexConverter.toHexString(buffer, RANDOM.nextLong());
String randomFive = buffer.toString().substring(0, 5);
Element result1 = callResultCode("_xins-old", randomFive);
assertNull("The method returned an error code for the first call: " + result1.getAttribute("errorcode"), result1.getAttribute("errorcode"));
assertNull("The method returned a code attribute for the first call: " + result1.getAttribute("code"), result1.getAttribute("code"));
assertNotNull("The method did not return a success attribute for the first call.", result1.getAttribute("success"));
Element result2 = callResultCode("_xins-old", randomFive);
assertNotNull("The method did not return an error code for the second call.", result2.getAttribute("errorcode"));
assertNotNull("The method did not return a code attribute for the second call.", result2.getAttribute("code"));
assertNotNull("The method did not return a success attribute for the second call.", result2.getAttribute("success"));
assertEquals("The code and errorcode are different.", result2.getAttribute("code"), result2.getAttribute("errorcode"));
}
/**
* Call the ResultCode function with the specified calling convention.
*
* @param convention
* the name of the calling convention parameter, or <code>null</code>
* if no calling convention parameter should be sent.
*
* @param inputText
* the value of the parameter to send as input.
*
* @return
* the parsed result as an Element.
*
* @throw Throwable
* if anything goes wrong.
*/
private Element callResultCode(String convention, String inputText) throws Throwable {
TargetDescriptor descriptor = new TargetDescriptor("http://127.0.0.1:8080/allinone/", 2000);
BasicPropertyReader params = new BasicPropertyReader();
params.set("_function", "ResultCode");
params.set("useDefault", "false");
params.set("inputText", inputText);
if (convention != null) {
params.set("_convention", convention);
}
HTTPCallRequest request = new HTTPCallRequest(params);
HTTPServiceCaller caller = new HTTPServiceCaller(descriptor);
HTTPCallResult result = caller.call(request);
byte[] data = result.getData();
ElementParser parser = new ElementParser();
return parser.parse(new StringReader(new String(data)));
}
/**
* Test the XML calling convention.
*/
public void testXMLCallingConvention() throws Throwable {
FastStringBuffer buffer = new FastStringBuffer(16);
HexConverter.toHexString(buffer, RANDOM.nextLong());
String randomFive = buffer.toString().substring(0, 5);
// Successful call
postXMLRequest(randomFive, true);
// Unsuccessful call
postXMLRequest(randomFive, false);
}
/**
* Posts XML request.
*
* @param randomFive
* A randomly generated String.
* @param success
* <code>true</code> if the expected result should be successfal,
* <code>false</code> otherwise.
*
* @throws Exception
* If anything goes wrong.
*/
private void postXMLRequest(String randomFive, boolean success) throws Exception {
String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xml";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<request function=\"ResultCode\">" +
" <param name=\"useDefault\">false</param>" +
" <param name=\"inputText\">" + randomFive + "</param>" +
"</request>";
Element result = postXML(destination, data);
assertEquals("result", result.getLocalName());
if (success) {
assertNull("The method returned an error code: " + result.getAttribute("errorcode"), result.getAttribute("errorcode"));
} else {
assertNotNull("The method did not return an error code for the second call: " + result.getAttribute("errorcode"), result.getAttribute("errorcode"));
assertEquals("AlreadySet", result.getAttribute("errorcode"));
}
assertNull("The method returned a code attribute: " + result.getAttribute("code"), result.getAttribute("code"));
assertNull("The method returned a success attribute.", result.getAttribute("success"));
List child = result.getChildElements();
assertEquals(1, child.size());
Element param = (Element) child.get(0);
assertEquals("param", param.getLocalName());
if (success) {
assertEquals("outputText", param.getAttribute("name"));
assertEquals(randomFive + " added.", param.getText());
} else {
assertEquals("count", param.getAttribute("name"));
assertEquals("1", param.getText());
}
}
/**
* Tests the XSLT calling convention.
*/
public void testXSLTCallingConvention() throws Throwable {
String html = getHTMLVersion(false);
assertTrue("The returned data is not an HTML file: " + html, html.startsWith("<html>"));
assertTrue("Incorrect HTML data returned.", html.indexOf("XINS version") != -1);
String html2 = getHTMLVersion(true);
assertTrue("The returned data is not an HTML file: " + html2, html2.startsWith("<html>"));
assertTrue("Incorrect HTML data returned.", html2.indexOf("API version") != -1);
}
private String getHTMLVersion(boolean useTemplateParam) throws Exception {
TargetDescriptor descriptor = new TargetDescriptor("http://127.0.0.1:8080/", 2000);
BasicPropertyReader params = new BasicPropertyReader();
params.set("_function", "_GetVersion");
params.set("_convention", "_xins-xslt");
if (useTemplateParam) {
String userDir = new File(System.getProperty("user.dir")).toURL().toString();
params.set("_template", userDir + "src/tests/getVersion2.xslt");
}
HTTPCallRequest request = new HTTPCallRequest(params);
HTTPServiceCaller caller = new HTTPServiceCaller(descriptor);
HTTPCallResult result = caller.call(request);
return result.getString();
}
/**
* Tests the SOAP calling convention.
*/
public void testSOAPCallingConvention() throws Throwable {
FastStringBuffer buffer = new FastStringBuffer(16);
HexConverter.toHexString(buffer, RANDOM.nextLong());
String randomFive = buffer.toString().substring(0, 5);
// Successful call
postSOAPRequest(randomFive, true);
// Unsuccessful call
postSOAPRequest(randomFive, false);
}
/**
* Posts SOAP request.
*
* @param randomFive
* A randomly generated String.
* @param success
* <code>true</code> if the expected result should be successfal,
* <code>false</code> otherwise.
*
* @throws Exception
* If anything goes wrong.
*/
private void postSOAPRequest(String randomFive, boolean success) throws Exception {
String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-soap";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" +
" <soap:Body>" +
" <ns0:ResultCodeRequest>" +
" <useDefault>false</useDefault>" +
" <inputText>" + randomFive + "</inputText>" +
" </ns0:ResultCodeRequest>" +
" </soap:Body>" +
"</soap:Envelope>";
Element result = postXML(destination, data);
assertEquals("Envelope", result.getLocalName());
assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size());
assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size());
Element bodyElem = (Element) result.getChildElements("Body").get(0);
if (success) {
assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("ResultCodeResponse").size());
Element responseElem = (Element) bodyElem.getChildElements("ResultCodeResponse").get(0);
assertEquals("Incorrect number of \"outputText\" elements.", 1, responseElem.getChildElements("outputText").size());
Element outputTextElem = (Element) responseElem.getChildElements("outputText").get(0);
assertEquals("Incorrect returned text", randomFive + " added.", outputTextElem.getText());
} else {
assertEquals("Incorrect number of \"Fault\" elements.", 1, bodyElem.getChildElements("Fault").size());
Element faultElem = (Element) bodyElem.getChildElements("Fault").get(0);
assertEquals("Incorrect number of \"faultcode\" elements.", 1, faultElem.getChildElements("faultcode").size());
Element faultCodeElem = (Element) faultElem.getChildElements("faultcode").get(0);
assertEquals("Incorrect faultcode text", "soap:Server", faultCodeElem.getText());
assertEquals("Incorrect number of \"faultstring\" elements.", 1, faultElem.getChildElements("faultstring").size());
Element faultStringElem = (Element) faultElem.getChildElements("faultstring").get(0);
assertEquals("Incorrect faultstring text", "AlreadySet", faultStringElem.getText());
}
}
/**
* Tests the SOAP calling convention for the type convertion.
*/
public void testSOAPCallingConvention2() throws Throwable {
String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-soap";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" +
" <soap:Body>" +
" <ns0:SimpleTypesRequest>" +
" <inputBoolean>0</inputBoolean>" +
" <inputByte>0</inputByte>" +
" <inputInt>0</inputInt>" +
" <inputLong>0</inputLong>" +
" <inputFloat>1.0</inputFloat>" +
" <inputText>0</inputText>" +
" </ns0:SimpleTypesRequest>" +
" </soap:Body>" +
"</soap:Envelope>";
Element result = postXML(destination, data);
assertEquals("Envelope", result.getLocalName());
assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size());
assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size());
Element bodyElem = (Element) result.getChildElements("Body").get(0);
assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("SimpleTypesResponse").size());
}
/**
* Tests the SOAP calling convention with a data section.
*/
public void testSOAPCallingConvention3() throws Throwable {
String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-soap";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" +
" <soap:Body>" +
" <ns0:DataSection3Request>" +
" <data>" +
" <address company=\"McDo\" postcode=\"1234\" />" +
" <address company=\"Drill\" postcode=\"4567\" />" +
" </data>" +
" </ns0:DataSection3Request>" +
" </soap:Body>" +
"</soap:Envelope>";
Element result = postXML(destination, data);
assertEquals("Envelope", result.getLocalName());
assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size());
assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size());
Element bodyElem = (Element) result.getChildElements("Body").get(0);
assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("DataSection3Response").size());
}
/**
* Tests the XML-RPC calling convention with an incomplete request.
*/
public void testXMLRPCCallingConvention() throws Exception {
String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xmlrpc";
// Send an incorrect request
String data = "<?xml version=\"1.0\"?>" +
"<methodCall>" +
" <methodName>SimpleTypes</methodName>" +
" <params>" +
" <param><value><struct><member>" +
" <name>inputBoolean</name>" +
" <value><boolean>0</boolean></value>" +
" </member></struct></value></param>" +
" </params>" +
"</methodCall>";
Element result = postXML(destination, data);
assertEquals("methodResponse", result.getLocalName());
Element faultElem = getUniqueChild(result, "fault");
Element valueElem = getUniqueChild(faultElem, "value");
Element structElem = getUniqueChild(valueElem, "struct");
Element member1 = (Element) structElem.getChildElements("member").get(0);
Element member1Name = getUniqueChild(member1, "name");
assertEquals("faultCode", member1Name.getText());
Element member1Value = getUniqueChild(member1, "value");
Element member1IntValue = getUniqueChild(member1Value, "int");
assertEquals("3", member1IntValue.getText());
Element member2 = (Element) structElem.getChildElements("member").get(1);
Element member2Name = getUniqueChild(member2, "name");
assertEquals("faultString", member2Name.getText());
Element member2Value = getUniqueChild(member2, "value");
Element member2StringValue = getUniqueChild(member2Value, "string");
assertEquals("_InvalidRequest", member2StringValue.getText());
}
/**
* Tests the XML-RPC calling convention for a successful result.
*/
public void testXMLRPCCallingConvention2() throws Exception {
String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xmlrpc";
// Send a correct request
String data = "<?xml version=\"1.0\"?>" +
"<methodCall>" +
" <methodName>SimpleTypes</methodName>" +
" <params>" +
" <param><value><struct><member>" +
" <name>inputBoolean</name>" +
" <value><boolean>1</boolean></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputByte</name>" +
" <value><i4>0</i4></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputInt</name>" +
" <value><i4>50</i4></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputLong</name>" +
" <value><string>123456460</string></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputFloat</name>" +
" <value><double>3.14159265</double></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputText</name>" +
" <value><string>Hello World!</string></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputDate</name>" +
" <value><dateTime.iso8601>19980717T14:08:55</dateTime.iso8601></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputTimestamp</name>" +
" <value><dateTime.iso8601>19980817T15:08:55</dateTime.iso8601></value>" +
" </member></struct></value></param>" +
" </params>" +
"</methodCall>";
Element result = postXML(destination, data);
assertEquals("methodResponse", result.getLocalName());
Element paramsElem = getUniqueChild(result, "params");
Element paramElem = getUniqueChild(paramsElem, "param");
Element valueElem = getUniqueChild(paramElem, "value");
Element structElem = getUniqueChild(valueElem, "struct");
}
/**
* Tests the XML-RPC calling convention for a data section.
*/
public void testXMLRPCCallingConvention3() throws Exception {
String destination = "http://127.0.0.1:8080/allinone/?_convention=_xins-xmlrpc";
// Send a correct request
String data = "<?xml version=\"1.0\"?>" +
"<methodCall>" +
" <methodName>DataSection3</methodName>" +
" <params>" +
" <param><value><struct><member>" +
" <name>inputText</name>" +
" <value><string>hello</string></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>data</name>" +
" <value><array><data>" +
" <value><struct><member>" +
" <name>address</name>" +
" <value><string></string></value>" +
" </member>" +
" <member>" +
" <name>company</name>" +
" <value><string>MyCompany</string></value>" +
" </member>" +
" <member>" +
" <name>postcode</name>" +
" <value><string>72650</string></value>" +
" </member></struct></value>" +
" </data></array></value>" +
" </member></struct></value></param>" +
" </params>" +
"</methodCall>";
Element result = postXML(destination, data);
assertEquals("methodResponse", result.getLocalName());
Element paramsElem = getUniqueChild(result, "params");
Element paramElem = getUniqueChild(paramsElem, "param");
Element valueElem = getUniqueChild(paramElem, "value");
Element structElem = getUniqueChild(valueElem, "struct");
}
/**
* Test the custom calling convention.
*/
public void testCustomCallingConvention() throws Exception {
URL url = new URL("http://127.0.0.1:8080/?query=hello%20Custom&_convention=xins-tests");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
assertEquals(200, connection.getResponseCode());
URL url2 = new URL("http://127.0.0.1:8080/?query=hello%20Custom&_convention=xins-tests");
HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection();
connection2.connect();
try {
assertEquals(400, connection2.getResponseCode());
} catch (IOException ioe) {
assertTrue(ioe.getMessage(), ioe.getMessage().indexOf(" 400") != -1);
}
}
/**
* Tests the HTTP OPTIONS method.
* Removed as not working - see bug #1483127
*/
public void testOptionsMethod() throws Exception {
// Prepare a connection
OptionsMethod method = new OptionsMethod("http://127.0.0.1:8080/");
HttpClient client = new HttpClient();
client.setConnectionTimeout(20000);
client.setTimeout(20000);
// Perform the call and release the connection
int code;
byte[] returnedData;
try {
code = client.executeMethod(method);
returnedData = method.getResponseBody();
} finally {
method.releaseConnection();
}
// Expect "200 OK"
assertEquals("Expected HTTP status code 200 in response to an HTTP OPTIONS request.",
200, code);
// Expect empty body
assertTrue("Expected no body in response to an HTTP OPTIONS request.",
returnedData == null || returnedData.length == 0);
// Expect "Accept" field in the response
Header[] acceptHeaders = method.getResponseHeaders("accept");
assertTrue("Expected an \"Accept\" header in response to an HTTP OPTIONS request.", acceptHeaders != null && acceptHeaders.length > 0);
assertTrue("Expected only one \"Accept\" header in response to an HTTP OPTIONS request. Received " + acceptHeaders.length, acceptHeaders.length == 1);
String acceptHeader = acceptHeaders[0].getValue();
assertTrue("Expected \"Accept\" header in response to HTTP OPTIONS request to have a non-empty value.", acceptHeader.trim().length() > 0);
List acceptValues = Arrays.asList(acceptHeader.split("[ ]*,[ ]*"));
String[] shouldBeSupported = { "GET", "POST", "HEAD", };
for (int i = 0; i < shouldBeSupported.length; i++) {
assertTrue("Expected \"Accept\" header in response to HTTP OPTIONS request to indicate the \"" + shouldBeSupported[i] + "\" method is supported. Instead the response is \"" + acceptHeader + "\".", acceptValues.contains(shouldBeSupported[i]));
}
}
/**
* Posts the XML data the the given destination.
*
* @param destination
* the destination where the XML has to be posted.
* @param data
* the XML to post.
*
* @return
* the returned XML already parsed.
*
* @throw Exception
* if anything goes wrong.
*/
private Element postXML(String destination, String data) throws Exception {
PostMethod post = new PostMethod(destination);
post.setRequestHeader("Content-Type", "text/xml; charset=UTF-8");
post.setRequestBody(data);
HttpClient client = new HttpClient();
client.setConnectionTimeout(5000);
client.setTimeout(5000);
try {
int code = client.executeMethod(post);
byte[] returnedData = post.getResponseBody();
ElementParser parser = new ElementParser();
String content = new String(returnedData);
System.err.println("content: " + content);
Element result = parser.parse(new StringReader(content));
return result;
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
}
}
/**
* Gets the unique child of the element.
*
* @param parentElement
* the parent element, cannot be <code>null</code>.
*
* @param elementName
* the name of the child element to get, or <code>null</code> if the
* parent have a unique child.
*
* @throws InvalidRequestException
* if no child was found or more than one child was found.
*/
private Element getUniqueChild(Element parentElement, String elementName)
throws ParseException {
List childList = null;
if (elementName == null) {
childList = parentElement.getChildElements();
} else {
childList = parentElement.getChildElements(elementName);
}
if (childList.size() == 0) {
throw new ParseException("No \"" + elementName +
"\" children found in the \"" + parentElement.getLocalName() +
"\" element of the XML-RPC request.");
} else if (childList.size() > 1) {
throw new ParseException("More than one \"" + elementName +
"\" children found in the \"" + parentElement.getLocalName() +
"\" element of the XML-RPC request.");
}
return (Element) childList.get(0);
}
} |
package yuku.alkitab.base.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QueryTokenizer {
public static final String TAG = QueryTokenizer.class.getSimpleName();
static Pattern oneToken = Pattern.compile("(\\+?)((?:\".*?\"|\\S)+)"); //$NON-NLS-1$
/**
* Convert a query string into tokens. Takes care of quotes and plus signs.
* Put quotes between words to make it one token, and optionally put plus sign before a token, to make it "whole phrase"
*
* Examples:
* a b => 'a', 'b'
* "a b" c => 'a b', 'c'
* a"bc"d => 'abcd'
* +"a bc" => '+abc'
* +a bc => '+a', 'bc'
* +a+b => '+a+b'
*
* @return tokens with plus still intact but no quotes.
*/
public static String[] tokenize(String query) {
List<String> raw_tokens = new ArrayList<String>();
Matcher matcher = QueryTokenizer.oneToken.matcher(query.toLowerCase(Locale.getDefault()));
while (matcher.find()) {
raw_tokens.add(matcher.group(1) + matcher.group(2));
}
//# process raw tokens
List<String> processed = new ArrayList<String>(raw_tokens.size());
for (int i = 0, len = raw_tokens.size(); i < len; i++) {
String token = raw_tokens.get(i);
if (token.length() > 0 && QueryTokenizer.tokenWithoutPlus(token).length() > 0) {
processed.add(token.replace("\"", "")); // remove quotes //$NON-NLS-1$ //$NON-NLS-2$
}
}
return processed.toArray(new String[processed.size()]);
}
static boolean isPlussedToken(String token) {
return (token.startsWith("+")); //$NON-NLS-1$
}
static String tokenWithoutPlus(String token) {
int pos = 0;
int len = token.length();
while (true) {
if (pos >= len) break;
if (token.charAt(pos) == '+') {
pos++;
} else {
break;
}
}
if (pos == 0) return token;
return token.substring(pos);
}
static boolean isMultiwordToken(String token) {
int start = 0;
if (isPlussedToken(token)) {
start = 1;
}
for (int i = start, len = token.length(); i < len; i++) {
char c = token.charAt(i);
if (! (Character.isLetter(c) || ((c=='-' || c=='\'') && i > start && i < len-1))) {
return true;
}
}
return false;
}
static Pattern pattern_letters = Pattern.compile("[\\p{javaLetter}'-]+");
/**
* For tokens such as "abc.,- def", which will be re-tokenized to "abc" "def"
*/
static List<String> tokenizeMultiwordToken(String token) {
List<String> res = new ArrayList<String>();
Matcher m = pattern_letters.matcher(token);
while (m.find()) {
res.add(m.group());
}
return res;
}
} |
package com.angles.angles;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import com.angles.model.Angle;
import com.angles.model.AnglesEvent;
import com.angles.model.User;
import com.google.cloud.backend.android.CloudBackendAsync;
import com.google.cloud.backend.android.CloudCallbackHandler;
import com.google.cloud.backend.android.CloudEntity;
import com.google.cloud.backend.android.DBTableConstants;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class OngoingEventActivity extends Activity {
private static final String DEBUG_TAG = "OngoingEventActivity";
public static final int REQUEST_CODE = 011;
public ImageView imageView;
public Activity currentActivity;
public User user;
private Uri recentPhotoUri;
private Bitmap recentPhoto;
private LinearLayout recentPhotoGallery;
private int sizeOfGallery = 0;
private File tempFile;
private Display display;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
AnglesEvent event = (AnglesEvent)bundle.getSerializable("event");
AnglesController.getInstance().getDisplayManager().displayOngoingEventActivity(this, event);
AnglesController.getInstance().getTouchManager().setOngoingEventListeners(this);
display = getWindowManager().getDefaultDisplay();
recentPhotoGallery = (LinearLayout)findViewById(R.id.recentPhotoGallery);
findViewById(R.id.btnCapturePhoto).setOnClickListener (new OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
tempFile = new File(Environment.getExternalStorageDirectory(),
"angle" + String.valueOf(Calendar.getInstance().getTimeInMillis()) + ".jpg");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
recentPhotoUri = Uri.fromFile(tempFile);
startActivityForResult(cameraIntent, REQUEST_CODE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
Log.d(DEBUG_TAG, "Request code: " + requestCode);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
/* Retrieve data from returned Activity
*/
getContentResolver().notifyChange(recentPhotoUri, null);
ContentResolver cr = getContentResolver();
try {
recentPhoto = MediaStore.Images.Media.getBitmap(cr, recentPhotoUri);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
/* Display the recently taken picture in the gallery.
* The gallery size is kept to no more than 4 pictures. */
if (sizeOfGallery > 3) {
recentPhotoGallery.removeViewAt(3);
recentPhotoGallery.addView(insertPhoto(tempFile.getAbsolutePath()), 0);
}
else {
recentPhotoGallery.addView(insertPhoto(tempFile.getAbsolutePath()), 0);
sizeOfGallery++;
}
/* Sending Image to Cloud */
user = AnglesController.getInstance().getAnglesUser();
byte[] data = convertImageToByteArray(recentPhotoUri);
Log.d(DEBUG_TAG, "Byte data size: " + String.valueOf(data.length));
CloudBackendAsync backend = new CloudBackendAsync(getApplicationContext());
Angle newAngle = new Angle(data, user);
CloudEntity entity = new CloudEntity(DBTableConstants.DB_TABLE_ANGLE);
entity.put(DBTableConstants.DB_ANGLE_IMAGE, newAngle.getImage());
entity.put(DBTableConstants.DB_ANGLE_CREATED_BY, newAngle.getCreatedBy().getUserName());
CloudCallbackHandler<CloudEntity> handler = new CloudCallbackHandler<CloudEntity>() {
@Override
public void onComplete(final CloudEntity result) {
Toast.makeText(getApplicationContext(),"Angle Sent!", Toast.LENGTH_LONG).show();
}
@Override
public void onError(final IOException ioe) {
Log.e(DEBUG_TAG, ioe.toString());
}
};
/* Execute the insertion with the handler.
*/
backend.insert(entity, handler);
}
else {
Toast.makeText(this, "Photo not taken.", Toast.LENGTH_SHORT).show();
}
tempFile.delete();
super.onActivityResult(requestCode, resultCode, returnedIntent);
}
private byte[] convertImageToByteArray(Uri uri) {
byte[] data = null;
try {
ContentResolver cr = getBaseContext().getContentResolver();
InputStream inputStream = cr.openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
} catch (FileNotFoundException fne) {
Log.e(DEBUG_TAG, "Error converting image to byte array: File not found.");
}
return data;
}
@SuppressLint("NewApi")
public View insertPhoto(String path) {
/* The bitmap is currently decoded based on calculations
* from a relative screen size. It assumes the picture should
* have a height no more than half the screen height, and a
* width no more than half the screen width.
*/
int targetWidth = 0;
int targetHeight = 0;
/* The previous means for calculating screen height and width
* have been deprecated as of API level 13. This check uses
* the current recommended getSize() method for API levels 13
* and up, and the supported way for previous API levels otherwise.
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Point size = new Point();
display.getSize(size);
targetWidth = (size.x)/2;
targetHeight = (size.y)/2;
}
else {
targetWidth = (getWindowManager().getDefaultDisplay().getWidth()) / 2;
targetHeight = (getWindowManager().getDefaultDisplay().getHeight()) / 2;
}
Bitmap bm = decodeSampledBitmapFromUri(path, 400, 600);
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setLayoutParams(new LayoutParams(targetWidth, targetHeight));
layout.setGravity(Gravity.CENTER);
Toast.makeText(this, "Size.x: " + targetWidth
+ ", Size.y: " + targetHeight, Toast.LENGTH_LONG).show();
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new LayoutParams(targetWidth, targetHeight));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bm);
layout.addView(imageView);
return layout;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
}
else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
} |
package smile.feature;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Haifeng Li
*/
public class BagTest {
public BagTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
/**
* Test of the uniqueness of features in the class Bag
*/
public void testUniquenessOfFeatures() {
System.out.println("unique features");
String[] featuresForBirdStories = {"crane", "sparrow", "hawk", "owl", "kiwi"};
String[] featuresForBuildingStories = {"truck", "concrete", "foundation", "steel", "crane"};
String testMessage = "This story is about a crane and a sparrow";
ArrayList<String> mergedFeatureLists = new ArrayList<String>();
mergedFeatureLists.addAll(Arrays.asList(featuresForBirdStories));
mergedFeatureLists.addAll(Arrays.asList(featuresForBuildingStories));
Bag<String> bag = new Bag<String>(mergedFeatureLists.toArray(new String[featuresForBirdStories.length + featuresForBuildingStories.length]));
double[] result = bag.feature(testMessage.split(" "));
assertEquals(9, result.length);
}
/**
* Test of feature method, of class Bag.
*/
@Test
public void testFeature() {
System.out.println("feature");
String[][] text = new String[2000][];
BufferedReader input = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/smile/data/text/movie.txt")));
try {
for (int i = 0; i < text.length; i++) {
String[] words = input.readLine().trim().split("\\s+");
text[i] = words;
}
} catch (IOException ex) {
System.err.println(ex);
} finally {
try {
input.close();
} catch (IOException e) {
System.err.println(e);
}
}
String[] feature = {
"outstanding", "wonderfully", "wasted", "lame", "awful", "poorly",
"ridiculous", "waste", "worst", "bland", "unfunny", "stupid", "dull",
"fantastic", "laughable", "mess", "pointless", "terrific", "memorable",
"superb", "boring", "badly", "subtle", "terrible", "excellent",
"perfectly", "masterpiece", "realistic", "flaws"
};
Bag<String> bag = new Bag<String>(feature);
double[][] x = new double[text.length][];
for (int i = 0; i < text.length; i++) {
x[i] = bag.feature(text[i]);
assertEquals(feature.length, x[i].length);
}
assertEquals(1.0, x[0][15], 1E-7);
}
} |
package org.jpmml.evaluator;
import java.util.Map;
import org.dmg.pmml.FieldName;
import org.dmg.pmml.LocalTransformations;
import org.dmg.pmml.MathContext;
import org.dmg.pmml.MiningFunction;
import org.dmg.pmml.MiningSchema;
import org.dmg.pmml.Model;
import org.dmg.pmml.ModelExplanation;
import org.dmg.pmml.ModelStats;
import org.dmg.pmml.ModelVerification;
import org.dmg.pmml.Output;
import org.dmg.pmml.PMMLObject;
import org.dmg.pmml.Targets;
import org.dmg.pmml.Visitor;
import org.dmg.pmml.VisitorAction;
import org.jpmml.model.Property;
import org.jpmml.schema.Extension;
@Extension
abstract
public class JavaModel extends Model {
private String modelName = null;
private MiningFunction miningFunction = null;
private String algorithmName = null;
private Boolean scorable = null;
private MathContext mathContext = null;
private MiningSchema miningSchema = null;
private LocalTransformations localTransformations = null;
private Targets targets = null;
private Output output = null;
private ModelStats modelStats = null;
private ModelExplanation modelExplanation = null;
private ModelVerification modelVerification = null;
public JavaModel(){
}
public JavaModel(MiningFunction miningFunction, MiningSchema miningSchema){
setMiningFunction(miningFunction);
setMiningSchema(miningSchema);
}
public JavaModel(Model model){
setModelName(model.getModelName());
setMiningFunction(model.getMiningFunction());
setAlgorithmName(model.getAlgorithmName());
setScorable(model.isScorable());
setMathContext(model.getMathContext());
setMiningSchema(model.getMiningSchema());
setLocalTransformations(model.getLocalTransformations());
setTargets(model.getTargets());
setOutput(model.getOutput());
setModelStats(model.getModelStats());
setModelExplanation(model.getModelExplanation());
setModelVerification(model.getModelVerification());
}
abstract
public Map<FieldName, ?> evaluate(ModelEvaluationContext context);
@Override
public String getModelName(){
return this.modelName;
}
@Override
public JavaModel setModelName(@Property("modelName") String modelName){
this.modelName = modelName;
return this;
}
@Override
public MiningFunction getMiningFunction(){
return this.miningFunction;
}
@Override
public JavaModel setMiningFunction(@Property("miningFunction") MiningFunction miningFunction){
this.miningFunction = miningFunction;
return this;
}
@Override
public String getAlgorithmName(){
return this.algorithmName;
}
@Override
public JavaModel setAlgorithmName(@Property("algorithmName") String algorithmName){
this.algorithmName = algorithmName;
return this;
}
@Override
public boolean isScorable(){
if(this.scorable == null){
return true;
}
return this.scorable;
}
@Override
public JavaModel setScorable(@Property("scorable") Boolean scorable){
this.scorable = scorable;
return this;
}
@Override
public MathContext getMathContext(){
if(this.mathContext == null){
return MathContext.DOUBLE;
}
return this.mathContext;
}
@Override
public JavaModel setMathContext(MathContext mathContext){
this.mathContext = mathContext;
return this;
}
@Override
public MiningSchema getMiningSchema(){
return this.miningSchema;
}
@Override
public JavaModel setMiningSchema(@Property("miningSchema") MiningSchema miningSchema){
this.miningSchema = miningSchema;
return this;
}
@Override
public LocalTransformations getLocalTransformations(){
return this.localTransformations;
}
@Override
public JavaModel setLocalTransformations(@Property("localTransformations") LocalTransformations localTransformations){
this.localTransformations = localTransformations;
return this;
}
@Override
public Targets getTargets(){
return this.targets;
}
@Override
public JavaModel setTargets(@Property("targets") Targets targets){
this.targets = targets;
return this;
}
@Override
public Output getOutput(){
return this.output;
}
@Override
public JavaModel setOutput(@Property("output") Output output){
this.output = output;
return this;
}
@Override
public ModelStats getModelStats(){
return this.modelStats;
}
@Override
public JavaModel setModelStats(@Property("modelStats") ModelStats modelStats){
this.modelStats = modelStats;
return this;
}
@Override
public ModelExplanation getModelExplanation(){
return this.modelExplanation;
}
@Override
public JavaModel setModelExplanation(@Property("modelExplanation") ModelExplanation modelExplanation){
this.modelExplanation = modelExplanation;
return this;
}
@Override
public ModelVerification getModelVerification(){
return this.modelVerification;
}
@Override
public JavaModel setModelVerification(@Property("modelVerification") ModelVerification modelVerification){
this.modelVerification = modelVerification;
return this;
}
@Override
public VisitorAction accept(Visitor visitor){
visitor.pushParent(this);
VisitorAction status = PMMLObject.traverse(visitor, getMiningSchema(), getLocalTransformations(), getTargets(), getOutput(), getModelStats(), getModelExplanation(), getModelVerification());
visitor.popParent();
if(status == VisitorAction.TERMINATE){
return VisitorAction.TERMINATE;
}
return VisitorAction.CONTINUE;
}
} |
package edu.knoxcraft.turtle3d;
import static edu.knoxcraft.turtle3d.KCTCommand.*;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author ppypp emhastings hahaha
*
*/
public class Turtle3D
{
/* Sample JSON commands:
{
"scriptname" : "script-test",
"commands" : [
{"cmd" : "forward",
"args" : {"dist" : 10}},
{"cmd" : "turnRight",
"args" : {"degrees" : 90}}
]
}
*/
private String scriptName;
private KCTScript script;
// Map for the static factory pattern.
// TODO: How to handle race conditions for the turtleMap in multithreading?
static Map<String,Turtle3D> turtleMap=new LinkedHashMap<String,Turtle3D>();
/**
* Static factory instead of constructor
* This lets us get the Turtle instances after running main, and then get their KCTScripts and generate
* the JSON code.
*
* @param name
* @return The turtle with the given name. If you try to create multiple turtles with the same name
* in the same main method, you will actually keep getting back the same turtle!
*/
public static Turtle3D createTurtle(String name) {
Turtle3D turtle=new Turtle3D(name);
turtleMap.put(name, turtle);
return turtle;
}
/**
* Private constructor to enforce static factory pattern
* @param scriptName
*/
private Turtle3D(String scriptName) {
script=new KCTScript(scriptName);
}
/**
* No need for students to call this method.
* @return
*/
public String getScriptName() {
return this.scriptName;
}
/**
* No need for students to call this method.
* @return
*/
public KCTScript getScript() {
return this.script;
}
/**
* Move the turtle forward the given distance.
* @param distance
*/
public void forward(int distance) {
KCTCommand cmd=new KCTCommand(FORWARD, JSONUtil.makeArgMap(DIST, distance));
script.addCommand(cmd);
}
/**
* Move the turtle backward the given distance.
* @param distance
*/
public void backward(int distance) {
KCTCommand cmd=new KCTCommand(BACKWARD, JSONUtil.makeArgMap(DIST, distance));
script.addCommand(cmd);
}
/**
* Turn the turtle to the right the given number of degrees.
* (Rounds to multiples of 45 deg)
* @param degrees
*/
public void turnRight(int degrees){
KCTCommand cmd=new KCTCommand(TURNRIGHT, JSONUtil.makeArgMap(DEGREES, degrees));
script.addCommand(cmd);
}
/**
* Turn the turtle to the left the given number of degrees.
* (Rounds to multiples of 45 deg)
* @param degrees
*/public void turnLeft(int degrees){
KCTCommand cmd=new KCTCommand(TURNLEFT, JSONUtil.makeArgMap(DEGREES, degrees));
script.addCommand(cmd);
}
/**
* Move the turtle up the given distance.
* @param degrees
*/
public void up(int distance){
KCTCommand cmd=new KCTCommand(UP, JSONUtil.makeArgMap(DIST, distance));
script.addCommand(cmd);
}
/**
* Move the turtle down the given distance.
* @param degrees
*/
public void down(int distance){
KCTCommand cmd=new KCTCommand(DOWN, JSONUtil.makeArgMap(DIST, distance));
script.addCommand(cmd);
}
/**
* Toggle turtle block placement mode
*/
public void blockPlace(){
KCTCommand cmd=new KCTCommand(PLACEBLOCKS);
script.addCommand(cmd);
}
/**
* Set turtle block type (int-based)
* @param type
*/
public void setBlock(int type){
KCTCommand cmd=new KCTCommand(SETBLOCK, JSONUtil.makeArgMap(BLOCKTYPE, type));
script.addCommand(cmd);
}
/**
* Set the turtle's relative position
* @param position [x, y, z]
*/
public void setPosition(int[] position){
KCTCommand cmd=new KCTCommand(SETPOSITION, JSONUtil.makeArgMap(POS, position));
script.addCommand(cmd);
}
/**
* Set the turtle's direction (int-based)
* @param degrees
*/
public void setDirection(int direction){
KCTCommand cmd=new KCTCommand(SETDIRECTION, JSONUtil.makeArgMap(DIR, direction));
script.addCommand(cmd);
}
} |
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// File created: 2010-08-09 13:06:32
package fi.tkk.ics.hadoop.bam;
import java.io.DataOutput;
import java.io.DataInput;
import java.io.IOException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.InputSplit;
/** Like a {@link org.apache.hadoop.mapreduce.lib.input.FileSplit}, but uses
* BGZF virtual offsets to fit with {@link
* net.sf.samtools.util.BlockCompressedInputStream}.
*/
public class FileVirtualSplit extends InputSplit implements Writable {
private Path file;
private long vStart;
private long vEnd;
private final String[] locations;
private static final String[] NO_LOCATIONS = {};
public FileVirtualSplit() { locations = NO_LOCATIONS; }
public FileVirtualSplit(Path f, long vs, long ve, String[] locs) {
file = f;
vStart = vs;
vEnd = ve;
locations = locs;
}
@Override public String[] getLocations() { return locations; }
@Override public long getLength() {
final long vsHi = vStart & ~0xffff;
final long veHi = vEnd & ~0xffff;
final long hiDiff = veHi - vsHi;
return hiDiff == 0 ? ((vEnd & 0xffff) - (vStart & 0xffff)) : hiDiff;
}
public Path getPath() { return file; }
/** Inclusive. */
public long getStartVirtualOffset() { return vStart; }
/** Exclusive. */
public long getEndVirtualOffset() { return vEnd; }
public void setStartVirtualOffset(long vo) { vStart = vo; }
public void setEndVirtualOffset(long vo) { vEnd = vo; }
@Override public void write(DataOutput out) throws IOException {
Text.writeString(out, file.toString());
out.writeLong(vStart);
out.writeLong(vEnd);
}
@Override public void readFields(DataInput in) throws IOException {
file = new Path(Text.readString(in));
vStart = in.readLong();
vEnd = in.readLong();
}
} |
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// File created: 2011-06-23 13:22:53
package fi.tkk.ics.hadoop.bam.cli.plugins;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.partition.InputSampler;
import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner;
import net.sf.picard.sam.ReservedTagConstants;
import net.sf.picard.sam.SamFileHeaderMerger;
import net.sf.samtools.SAMFileHeader;
import net.sf.samtools.SAMFileReader;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.util.BlockCompressedStreamConstants;
import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser;
import static fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.*;
import fi.tkk.ics.hadoop.bam.AnySAMInputFormat;
import fi.tkk.ics.hadoop.bam.AnySAMOutputFormat;
import fi.tkk.ics.hadoop.bam.BAMRecordReader;
import fi.tkk.ics.hadoop.bam.KeyIgnoringAnySAMOutputFormat;
import fi.tkk.ics.hadoop.bam.SAMFormat;
import fi.tkk.ics.hadoop.bam.SAMRecordWritable;
import fi.tkk.ics.hadoop.bam.cli.CLIPlugin;
import fi.tkk.ics.hadoop.bam.cli.Utils;
import fi.tkk.ics.hadoop.bam.util.Pair;
import fi.tkk.ics.hadoop.bam.util.SAMOutputPreparer;
import fi.tkk.ics.hadoop.bam.util.Timer;
public final class Sort extends CLIPlugin {
private static final List<Pair<CmdLineParser.Option, String>> optionDescs
= new ArrayList<Pair<CmdLineParser.Option, String>>();
private static final CmdLineParser.Option
reducersOpt = new IntegerOption('r', "reducers=N"),
verboseOpt = new BooleanOption('v', "verbose"),
outputFileOpt = new StringOption('o', "output-file=PATH"),
formatOpt = new StringOption('F', "format=FMT"),
noTrustExtsOpt = new BooleanOption("no-trust-exts");
public Sort() {
super("sort", "BAM and SAM sorting and merging", "4.0",
"WORKDIR INPATH [INPATH...]",
optionDescs,
"Merges together the BAM and SAM files in the INPATHs, sorting the "+
"result, in a distributed fashion using Hadoop. Output parts are "+
"placed in WORKDIR in, by default, headerless BAM format.");
}
static {
optionDescs.add(new Pair<CmdLineParser.Option, String>(
reducersOpt, "use N reduce tasks (default: 1), i.e. produce N "+
"outputs in parallel"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
verboseOpt, "tell the Hadoop job to be more verbose"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
outputFileOpt, "output a complete SAM/BAM file to the file PATH, "+
"removing the parts from WORKDIR; SAM/BAM is chosen "+
"by file extension, if appropriate (but -F takes "+
"precedence)"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
noTrustExtsOpt, "detect SAM/BAM files only by contents, "+
"never by file extension"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
formatOpt, "select the output format based on FMT: SAM or BAM"));
}
@Override protected int run(CmdLineParser parser) {
final List<String> args = parser.getRemainingArgs();
if (args.isEmpty()) {
System.err.println("sort :: WORKDIR not given.");
return 3;
}
if (args.size() == 1) {
System.err.println("sort :: INPATH not given.");
return 3;
}
final String wrkDir = args.get(0),
out = (String)parser.getOptionValue(outputFileOpt);
final List<String> strInputs = args.subList(1, args.size());
final List<Path> inputs = new ArrayList<Path>(strInputs.size());
for (final String in : strInputs)
inputs.add(new Path(in));
final boolean verbose = parser.getBoolean(verboseOpt);
final String intermediateOutName =
(out == null ? inputs.get(0) : new Path(out)).getName();
final Configuration conf = getConf();
SAMFormat format = null;
final String fmt = (String)parser.getOptionValue(formatOpt);
if (fmt != null) {
try { format = SAMFormat.valueOf(fmt.toUpperCase(Locale.ENGLISH)); }
catch (IllegalArgumentException e) {
System.err.printf("sort :: invalid format '%s'\n", fmt);
return 3;
}
}
if (format == null) {
if (out != null)
format = SAMFormat.inferFromFilePath(out);
if (format == null)
format = SAMFormat.BAM;
}
conf.set(AnySAMOutputFormat.OUTPUT_SAM_FORMAT_PROPERTY,
format.toString());
conf.setBoolean(AnySAMInputFormat.TRUST_EXTS_PROPERTY,
!parser.getBoolean(noTrustExtsOpt));
// Used by getHeaderMerger. SortRecordReader needs it to correct the
// reference indices when the output has a different index and
// SortOutputFormat needs it to have the correct header for the output
// records.
conf.setStrings(INPUT_PATHS_PROP, strInputs.toArray(new String[0]));
// Used by SortOutputFormat to name the output files.
conf.set(SortOutputFormat.OUTPUT_NAME_PROP, intermediateOutName);
// Let the output format know if we're going to merge the output, so that
// it doesn't write headers into the intermediate files.
conf.setBoolean(SortOutputFormat.WRITE_HEADER_PROP, out == null);
Path wrkDirPath = new Path(wrkDir);
final int reduceTasks = parser.getInt(reducersOpt, 1);
final Timer t = new Timer();
try {
// Required for path ".", for example.
wrkDirPath = wrkDirPath.getFileSystem(conf).makeQualified(wrkDirPath);
Utils.configureSampling(wrkDirPath, intermediateOutName, conf);
conf.setInt("mapred.reduce.tasks", reduceTasks);
final Job job = new Job(conf);
job.setJarByClass (Sort.class);
job.setMapperClass (Mapper.class);
job.setReducerClass(SortReducer.class);
job.setMapOutputKeyClass(LongWritable.class);
job.setOutputKeyClass (NullWritable.class);
job.setOutputValueClass (SAMRecordWritable.class);
job.setInputFormatClass (SortInputFormat.class);
job.setOutputFormatClass(SortOutputFormat.class);
for (final Path in : inputs)
FileInputFormat.addInputPath(job, in);
FileOutputFormat.setOutputPath(job, wrkDirPath);
job.setPartitionerClass(TotalOrderPartitioner.class);
System.out.println("sort :: Sampling...");
t.start();
InputSampler.<LongWritable,SAMRecordWritable>writePartitionFile(
job,
new InputSampler.RandomSampler<LongWritable,SAMRecordWritable>(
0.01, 10000, Math.max(100, reduceTasks)));
System.out.printf("sort :: Sampling complete in %d.%03d s.\n",
t.stopS(), t.fms());
job.submit();
System.out.println("sort :: Waiting for job completion...");
t.start();
if (!job.waitForCompletion(verbose)) {
System.err.println("sort :: Job failed.");
return 4;
}
System.out.printf("sort :: Job complete in %d.%03d s.\n",
t.stopS(), t.fms());
} catch (IOException e) {
System.err.printf("sort :: Hadoop error: %s\n", e);
return 4;
} catch (ClassNotFoundException e) { throw new RuntimeException(e); }
catch (InterruptedException e) { throw new RuntimeException(e); }
if (out != null) try {
System.out.println("sort :: Merging output...");
t.start();
final Path outPath = new Path(out);
final FileSystem srcFS = wrkDirPath.getFileSystem(conf);
FileSystem dstFS = outPath.getFileSystem(conf);
// First, place the BAM header.
final SAMFileHeader header = getHeaderMerger(conf).getMergedHeader();
final OutputStream outs = dstFS.create(outPath);
// Don't use the returned stream, because we're concatenating directly
// and don't want to apply another layer of compression to BAM.
new SAMOutputPreparer().prepareForRecords(outs, format, header);
// Then, the actual SAM or BAM contents.
final FileStatus[] parts = srcFS.globStatus(new Path(
wrkDir, conf.get(SortOutputFormat.OUTPUT_NAME_PROP) +
"-[0-9][0-9][0-9][0-9][0-9][0-9]*"));
{int i = 0;
final Timer t2 = new Timer();
for (final FileStatus part : parts) {
System.out.printf("sort :: Merging part %d (size %d)...",
++i, part.getLen());
System.out.flush();
t2.start();
final InputStream ins = srcFS.open(part.getPath());
IOUtils.copyBytes(ins, outs, conf, false);
ins.close();
System.out.printf(" done in %d.%03d s.\n", t2.stopS(), t2.fms());
}}
for (final FileStatus part : parts)
srcFS.delete(part.getPath(), false);
// And if BAM, the BGZF terminator.
if (format == SAMFormat.BAM)
outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK);
outs.close();
System.out.printf("sort :: Merging complete in %d.%03d s.\n",
t.stopS(), t.fms());
} catch (IOException e) {
System.err.printf("sort :: Output merging failed: %s\n", e);
return 5;
}
return 0;
}
private static final String INPUT_PATHS_PROP = "hadoopbam.sort.input.paths";
private static SamFileHeaderMerger headerMerger = null;
public static SamFileHeaderMerger getHeaderMerger(Configuration conf)
throws IOException
{
// TODO: it would be preferable to cache this beforehand instead of
// having every task read the header block of every input file. But that
// would be trickier, given that SamFileHeaderMerger isn't trivially
// serializable.
// Save it in a static field, though, in case that helps anything.
if (headerMerger != null)
return headerMerger;
final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>();
for (final String in : conf.getStrings(INPUT_PATHS_PROP)) {
final Path p = new Path(in);
final SAMFileReader r =
new SAMFileReader(p.getFileSystem(conf).open(p));
headers.add(r.getFileHeader());
r.close();
}
return headerMerger = new SamFileHeaderMerger(
SAMFileHeader.SortOrder.coordinate, headers, true);
}
}
final class SortReducer
extends Reducer<LongWritable,SAMRecordWritable,
NullWritable,SAMRecordWritable>
{
@Override protected void reduce(
LongWritable ignored, Iterable<SAMRecordWritable> records,
Reducer<LongWritable,SAMRecordWritable,
NullWritable,SAMRecordWritable>.Context
ctx)
throws IOException, InterruptedException
{
for (SAMRecordWritable rec : records)
ctx.write(NullWritable.get(), rec);
}
}
// Because we want a total order and we may change the key when merging
// headers, we can't use a mapper here: the InputSampler reads directly from
// the InputFormat.
final class SortInputFormat
extends FileInputFormat<LongWritable,SAMRecordWritable>
{
private AnySAMInputFormat baseIF = null;
private void initBaseIF(final Configuration conf) {
if (baseIF == null)
baseIF = new AnySAMInputFormat(conf);
}
@Override public RecordReader<LongWritable,SAMRecordWritable>
createRecordReader(InputSplit split, TaskAttemptContext ctx)
throws InterruptedException, IOException
{
initBaseIF(ctx.getConfiguration());
final RecordReader<LongWritable,SAMRecordWritable> rr =
new SortRecordReader(baseIF.createRecordReader(split, ctx));
rr.initialize(split, ctx);
return rr;
}
@Override protected boolean isSplitable(JobContext job, Path path) {
initBaseIF(job.getConfiguration());
return baseIF.isSplitable(job, path);
}
@Override public List<InputSplit> getSplits(JobContext job)
throws IOException
{
initBaseIF(job.getConfiguration());
return baseIF.getSplits(job);
}
}
final class SortRecordReader
extends RecordReader<LongWritable,SAMRecordWritable>
{
private final RecordReader<LongWritable,SAMRecordWritable> baseRR;
private SamFileHeaderMerger headerMerger;
public SortRecordReader(RecordReader<LongWritable,SAMRecordWritable> rr) {
baseRR = rr;
}
@Override public void initialize(InputSplit spl, TaskAttemptContext ctx)
throws InterruptedException, IOException
{
headerMerger = Sort.getHeaderMerger(ctx.getConfiguration());
}
@Override public void close() throws IOException { baseRR.close(); }
@Override public float getProgress()
throws InterruptedException, IOException
{
return baseRR.getProgress();
}
@Override public LongWritable getCurrentKey()
throws InterruptedException, IOException
{
return baseRR.getCurrentKey();
}
@Override public SAMRecordWritable getCurrentValue()
throws InterruptedException, IOException
{
return baseRR.getCurrentValue();
}
@Override public boolean nextKeyValue()
throws InterruptedException, IOException
{
if (!baseRR.nextKeyValue())
return false;
final SAMRecord r = getCurrentValue().get();
final SAMFileHeader h = r.getHeader();
// Correct the reference indices, and thus the key, if necessary.
if (headerMerger.hasMergedSequenceDictionary()) {
int ri = headerMerger.getMergedSequenceIndex(
h, r.getReferenceIndex());
r.setReferenceIndex(ri);
if (r.getReadPairedFlag())
r.setMateReferenceIndex(headerMerger.getMergedSequenceIndex(
h, r.getMateReferenceIndex()));
getCurrentKey().set(BAMRecordReader.getKey(r));
}
// Correct the program group if necessary.
if (headerMerger.hasProgramGroupCollisions()) {
final String pg = (String)r.getAttribute(
ReservedTagConstants.PROGRAM_GROUP_ID);
if (pg != null)
r.setAttribute(
ReservedTagConstants.PROGRAM_GROUP_ID,
headerMerger.getProgramGroupId(h, pg));
}
// Correct the read group if necessary.
if (headerMerger.hasReadGroupCollisions()) {
final String rg = (String)r.getAttribute(
ReservedTagConstants.READ_GROUP_ID);
if (rg != null)
r.setAttribute(
ReservedTagConstants.READ_GROUP_ID,
headerMerger.getProgramGroupId(h, rg));
}
return true;
}
}
final class SortOutputFormat
extends FileOutputFormat<NullWritable,SAMRecordWritable>
{
public static final String
OUTPUT_NAME_PROP = "hadoopbam.sort.output.name",
WRITE_HEADER_PROP = "hadoopbam.sort.output.write-header";
private KeyIgnoringAnySAMOutputFormat<NullWritable> baseOF;
private void initBaseOF(Configuration conf) {
if (baseOF != null)
return;
baseOF = new KeyIgnoringAnySAMOutputFormat<NullWritable>(conf);
baseOF.setWriteHeader(
conf.getBoolean(WRITE_HEADER_PROP, baseOF.getWriteHeader()));
}
@Override public RecordWriter<NullWritable,SAMRecordWritable> getRecordWriter(
TaskAttemptContext context)
throws IOException
{
initBaseOF(context.getConfiguration());
if (baseOF.getSAMHeader() == null)
baseOF.setSAMHeader(Sort.getHeaderMerger(
context.getConfiguration()).getMergedHeader());
return baseOF.getRecordWriter(context, getDefaultWorkFile(context, ""));
}
@Override public Path getDefaultWorkFile(TaskAttemptContext ctx, String ext)
throws IOException
{
initBaseOF(ctx.getConfiguration());
String filename = ctx.getConfiguration().get(OUTPUT_NAME_PROP);
String extension = ext.isEmpty() ? ext : "." + ext;
int part = ctx.getTaskAttemptID().getTaskID().getId();
return new Path(baseOF.getDefaultWorkFile(ctx, ext).getParent(),
filename + "-" + String.format("%06d", part) + extension);
}
// Allow the output directory to exist.
@Override public void checkOutputSpecs(JobContext job) {}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.